diff --git a/ccm-cms/src/main/java/org/librecms/CMSConfig.java b/ccm-cms/src/main/java/org/librecms/CMSConfig.java index e9174b9ba..839d66ce8 100644 --- a/ccm-cms/src/main/java/org/librecms/CMSConfig.java +++ b/ccm-cms/src/main/java/org/librecms/CMSConfig.java @@ -18,13 +18,10 @@ */ package org.librecms; -import com.arsdigita.bebop.form.DHTMLEditor; - import org.libreccm.cdi.utils.CdiUtil; import org.libreccm.configuration.Configuration; import org.libreccm.configuration.ConfigurationManager; import org.libreccm.configuration.Setting; -import org.libreccm.core.UnexpectedErrorException; import java.util.ArrayList; import java.util.Arrays; @@ -602,42 +599,6 @@ public class CMSConfig { this.useStreamlinedCreation = useStreamlinedCreation; } - public DHTMLEditor.Config getDHTMLEditorConfig() { - if (dhtmlEditorConfig.size() < 2) { - return DHTMLEditor.Config.STANDARD; - } else { - return new DHTMLEditor.Config(dhtmlEditorConfig.get(0), - dhtmlEditorConfig.get(1)); - } - - } - - public List getDhtmlEditorConfig() { - return new ArrayList<>(dhtmlEditorConfig); - } - - public void setDhtmlEditorConfig(final List dhtmlEditorConfig) { - this.dhtmlEditorConfig = new ArrayList<>(dhtmlEditorConfig); - } - - public List getDhtmlEditorPlugins() { - return new ArrayList<>(dhtmlEditorPlugins); - } - - public void setDhtmlEditorPlugins(final List dhtmlEditorPlugins) { - this.dhtmlEditorPlugins = new ArrayList<>(dhtmlEditorPlugins); - } - - public List getDhtmlEditorHiddenButtons() { - return new ArrayList<>(dhtmlEditorHiddenButtons); - } - - public void setDhtmlEditorHiddenButtons( - final List dhtmlEditorHiddenButtons) { - this.dhtmlEditorHiddenButtons - = new ArrayList<>(dhtmlEditorHiddenButtons); - } - public boolean isHideAdminTabs() { return hideAdminTabs; } diff --git a/ccm-cms/src/main/java/org/librecms/contenttypes/AuthoringKit.java b/ccm-cms/src/main/java/org/librecms/contenttypes/AuthoringKit.java index 50c7bd6ad..a3bbe5b79 100644 --- a/ccm-cms/src/main/java/org/librecms/contenttypes/AuthoringKit.java +++ b/ccm-cms/src/main/java/org/librecms/contenttypes/AuthoringKit.java @@ -18,7 +18,6 @@ */ package org.librecms.contenttypes; -import com.arsdigita.bebop.FormSection; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -34,7 +33,7 @@ import java.lang.annotation.Target; @Deprecated public @interface AuthoringKit { - Class createComponent(); + Class createComponent(); AuthoringStep[] steps(); diff --git a/ccm-cms/src/main/java/org/librecms/contenttypes/AuthoringKitInfo.java b/ccm-cms/src/main/java/org/librecms/contenttypes/AuthoringKitInfo.java index 13391a269..7b9ca9f7a 100644 --- a/ccm-cms/src/main/java/org/librecms/contenttypes/AuthoringKitInfo.java +++ b/ccm-cms/src/main/java/org/librecms/contenttypes/AuthoringKitInfo.java @@ -18,7 +18,6 @@ */ package org.librecms.contenttypes; -import com.arsdigita.bebop.FormSection; import java.util.ArrayList; import java.util.Collections; @@ -36,7 +35,7 @@ public class AuthoringKitInfo { * The create component (the form used to collect the mandatory data for the * content type). */ - private Class createComponent; + private Class createComponent; /** * The authoring steps of the authoring kit. @@ -47,12 +46,12 @@ public class AuthoringKitInfo { authoringSteps = new ArrayList<>(); } - public Class getCreateComponent() { + public Class getCreateComponent() { return createComponent; } public void setCreateComponent( - final Class createComponent) { + final Class createComponent) { this.createComponent = createComponent; } diff --git a/ccm-cms/src/main/java/org/librecms/util/LanguageUtil.java b/ccm-cms/src/main/java/org/librecms/util/LanguageUtil.java index c2fa03c4b..19f05a49d 100644 --- a/ccm-cms/src/main/java/org/librecms/util/LanguageUtil.java +++ b/ccm-cms/src/main/java/org/librecms/util/LanguageUtil.java @@ -20,16 +20,17 @@ package org.librecms.util; import com.arsdigita.globalization.GlobalizedMessage; import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.util.Pair; -import java.util.ArrayList; + import java.util.List; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.stream.Collectors; + import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.libreccm.configuration.ConfigurationManager; @@ -43,7 +44,7 @@ import org.libreccm.l10n.GlobalizationHelper; public class LanguageUtil { private static final Logger LOGGER = LogManager. - getLogger(LanguageUtil.class); + getLogger(LanguageUtil.class); @Inject private GlobalizationHelper globalizationHelper; @@ -51,16 +52,20 @@ public class LanguageUtil { /** * Mapping from the ISO639-1 2-letter codes to the ISO639-2 3-letter codes */ - private static final String ISO639_2LA_3LA = "com.arsdigita.cms.util.iso639rev"; + private static final String ISO639_2LA_3LA + = "com.arsdigita.cms.util.iso639rev"; + private static final ResourceBundle LANG_3LA = ResourceBundle.getBundle( - ISO639_2LA_3LA); + ISO639_2LA_3LA); /** * Mapping from the ISO639-1 2-letter codes to the full descriptive name */ - private static final String ISO639_2LA_FULL = "com.arsdigita.cms.util.iso639full"; + private static final String ISO639_2LA_FULL + = "com.arsdigita.cms.util.iso639full"; + private static final ResourceBundle LANG_FULL = ResourceBundle.getBundle( - ISO639_2LA_FULL); + ISO639_2LA_FULL); @Inject private ConfigurationManager confManager; @@ -70,11 +75,11 @@ public class LanguageUtil { @PostConstruct private void init() { final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); + KernelConfig.class); supportedLanguages = kernelConfig.getSupportedLanguages() - .stream() - .map(language -> new Locale(language)) - .collect(Collectors.toList()); + .stream() + .map(language -> new Locale(language)) + .collect(Collectors.toList()); } public GlobalizedMessage globalizedLanguageName(final String key) { @@ -92,34 +97,8 @@ public class LanguageUtil { */ public List getSupportedLanguages2LA() { return getSupportedLanguages().stream() - .map(locale -> locale.getLanguage()) - .collect(Collectors.toList()); - } - - /** - * Returns the collection of all supported languages. Each entry is a pair - * of 2 letter code as key and three letter code as value. - * - * @return all supported languages - */ - public List getSupportedLanguages3LA() { - return getSupportedLanguages().stream() - .map(locale -> new Pair(locale.getLanguage(), - locale.getISO3Language())) - .collect(Collectors.toList()); - } - - /** - * Returns the collection of all supported languages. Each entry is a pair - * of 2 letter code as key and full language name as a value. - * - * @return all supported languages - */ - public List getSupportedLanguagesFull() { - return getSupportedLanguages().stream() - .map(locale -> new Pair(locale.getLanguage(), - getLangFull(locale))) - .collect(Collectors.toList()); + .map(locale -> locale.getLanguage()) + .collect(Collectors.toList()); } /** @@ -127,8 +106,9 @@ public class LanguageUtil { * code. * * @param lang + * * @return three letter code for the two letter code. If the resource is not - * found then the key itself is returned. + * found then the key itself is returned. */ public String getLang3LA(final String lang) { String threeLA; @@ -137,7 +117,7 @@ public class LanguageUtil { threeLA = (new Locale(lang)).getISO3Language(); } catch (MissingResourceException ex) { LOGGER.warn("No 3 letter code for \"{}\" available via " - + "Locale#getISO3Language.", + + "Locale#getISO3Language.", lang); LOGGER.warn(ex); @@ -164,12 +144,12 @@ public class LanguageUtil { * @param lang 2 letter language code * * @return full language name for the given two letter code If the resource - * is not found then the key itself is returned. + * is not found then the key itself is returned. */ public String getLangFull(final Locale lang) { // Lookup language name via java.util.Locale String fullName = (lang.getDisplayLanguage( - globalizationHelper.getNegotiatedLocale())); + globalizationHelper.getNegotiatedLocale())); if (lang.getLanguage().equals(fullName)) { // If that fails @@ -192,30 +172,4 @@ public class LanguageUtil { return getLangFull(new Locale(lang)); } - /** - * Takes in a list of 2 letter codes and converts into 3 letter codes. Each - * entry is pair of 2 letter code as key and 3 letter code as value. - * - * @param list - * @return - */ - public List convertTo3LA(final List list) { - return list.stream() - .map(lang2Code -> new Pair(lang2Code, getLang3LA(lang2Code))) - .collect(Collectors.toList()); - } - - public List convertToFull(final List list) { - return list.stream() - .map(lang2Code -> new Pair(lang2Code, getLangFull(lang2Code))) - .collect(Collectors.toList()); - } - - public List convertToG11N(final List list) { - return list.stream() - .map(lang2Code -> new Pair(lang2Code, - globalizedLanguageName(lang2Code))) - .collect(Collectors.toList()); - } - } diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/AbstractSingleSelectionModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/AbstractSingleSelectionModel.java deleted file mode 100755 index 5dd69ade0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/AbstractSingleSelectionModel.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import java.util.Iterator; - -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.event.EventListenerList; -import com.arsdigita.util.Assert; -import com.arsdigita.util.Lockable; - - -/** - * A standard implementation of SingleSelectionModel and - * Lockable. Those wishing to define a SingleSelectionModel will - * ordinarily want to extend this class. - * - * jensp: Added generics and Java 8 streams instead of using an iterator. - * - * @param The type managed by the parameter model. - * - * @author Unknown - * @author Jens Pelzetter (jensp) - */ -public abstract class AbstractSingleSelectionModel - implements SingleSelectionModel, Lockable { - - private final EventListenerList m_listeners; - private boolean m_locked; - - /** - * Creates a new AbstractSingleSelectionModel. - */ - public AbstractSingleSelectionModel() { - m_listeners = new EventListenerList(); - } - - /** - * Returns true if there is a selected element. - * - * @param state the state of the current request - * - * @return true if there is a selected component; - * false otherwise. - */ - @Override - public boolean isSelected(final PageState state) { - return getSelectedKey(state) != null; - } - - @Override - public abstract T getSelectedKey(final PageState state); - - @Override - public abstract void setSelectedKey(final PageState state, final T key); - - @Override - public void clearSelection(final PageState state) { - setSelectedKey(state, null); - } - - // Selection change events - @Override - public void addChangeListener(final ChangeListener changeListener) { - Assert.isUnlocked(this); - m_listeners.add(ChangeListener.class, changeListener); - } - - @Override - public void removeChangeListener(final ChangeListener changeListener) { - Assert.isUnlocked(this); - m_listeners.remove(ChangeListener.class, changeListener); - } - - protected void fireStateChanged(final PageState state) { - final ChangeEvent event = new ChangeEvent(this, state); - final Iterator iterator = m_listeners - .getListenerIterator(ChangeListener.class); - while(iterator.hasNext()) { - iterator.next().stateChanged(event); - } - } - - // implement Lockable - @Override - public void lock() { - m_locked = true; - } - - @Override - public final boolean isLocked() { - return m_locked; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ActionLink.java b/ccm-core/src/main/java/com/arsdigita/bebop/ActionLink.java deleted file mode 100644 index 4c4aab7b2..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ActionLink.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.globalization.GlobalizedMessage; - - - -/** - * A link that runs its action listeners when it is clicked. The target of the - * link is the {@link Page} in which the action link is contained. - * - *

Typically, an action link is used in the following way: - *

- *   ActionLink l = new ActionLink("Send email to everybody");
- *   l.addActionListener(new ActionListener() {
- *      public void actionPerformed(ActionEvent e) {
- *        System.out.println("Link was clicked.");
- *        ... figure out who everybody is and send them email ...
- *      }
- *   });
- * 
- * - *

See {@link BaseLink} for a description of all Bebop Link classes - * and suggestions for using them. - * - * @author David Lutterkort - * @version $Id$ */ -public class ActionLink extends ControlLink { - - /** - * The value for the XML type attribute for an {@link ActionLink}. - */ - protected static final String TYPE_ACTION = "action"; - - /** - * Constructs a new ActionLink. The link encapsulates - * the child component (usually either a label or an image). - * - * @param child the component to be turned into a link - */ - public ActionLink(Component child) { - super(child); - setTypeAttr(TYPE_ACTION); - } - - /** - * Constructs a new ActionLink with the given string label. - * - * @param label the string label for the link - */ - public ActionLink(GlobalizedMessage label) { - this(new Label(label)); - } - - /** - * Constructs a new ActionLink with the given string label. - * - * @param label the string label for the link - * @deprecated refactor to use @see ActionLink(GlobalizedMessage label) - */ - public ActionLink(String label) { - this(new Label(label)); - } - - /** - * Sets the page state's control event. Should be overridden by child - * classes. By default, the link does not receive any control events. - * - * @param s the current page state - */ - @Override - public void setControlEvent(PageState s) { - s.setControlEvent(this); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/BaseLink.java b/ccm-core/src/main/java/com/arsdigita/bebop/BaseLink.java deleted file mode 100755 index a09484ace..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/BaseLink.java +++ /dev/null @@ -1,578 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.Assert; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.xml.Element; -import java.util.TooManyListenersException; - -/** - * The parent of all Bebop Link classes, this class represents a URL on a page. - * It may contain a label, an image, or any other component. - * - *

- * The following table lists all Bebop Link classes and suggests when they might - * be used. - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Link ClassUsage
{@link BaseLink}Parent class of Bebop Link classes. Extend this class to build your own - * Link class.
{@link Link}Link class that manages its own URL variables. Session information is - * added to the target URL for this type.
{@link ExternalLink}Link that does not encode the URL with any session information. Used for - * a link to a page outside the site.
{@link ControlLink} Used for references within its own page (often as fields in a table - * header for sorting a column).
{@link ActionLink}Sets its own control event and runs its own - * {@link com.arsdigita.bebop.event.ActionListener}s. When the link is clicked, - * the code in the Listener's actionPerformed method runs.
{@link ToggleLink}A link that turns into label when it is selected and turns back into a - * link when it is unselected.
- * - * @version $Id: BaseLink.java 998 2005-11-15 22:27:13Z sskracic $ - */ -public abstract class BaseLink extends DescriptiveComponent - implements Cloneable { - - /** - * The name of the attribute used in XML to indicate which type of link this - * link represents. - */ - private final static String TYPE_ATTR = "type"; - private final static String HREF_NO_JAVASCRIPT = "href_no_javascript"; - private final static String HREF = "href"; - - /** - * Component used to display the link. Typically a Label, may be e.g. an - * image as well. - */ - protected Component m_child; - - /** - * Property to store the url the Link points to. - */ - protected String m_url; - -// Use the parent class' property! -// /** Property to store informational text for the user about the Link, e.g. -// * how to use it, or when to use it (or not to use it). */ -// private GlobalizedMessage m_hint; - protected String m_noJavascriptURL = null; - - private PrintListener m_printListener; - - private String m_sConfirmMsg = ""; - private GlobalizedMessage m_confirmMsg; - - /** - * Constructor creates a link taking url as the target and display it to the - * user at the same time. It is the only allowed way to present the user - * with a not globlized information. The implementation currently miss-uses - * the Label component to display just a not globalized String which is - * deprecated. - * - * @param url - * - * @deprecated use BaseLink(Component,url) instead with a Label using a - * GlobalizedMessage instead - */ - public BaseLink(final String url) { - this(new Label(url), url); - } - - /** - * Constructor - * - * @param child display component (Label, Image, etc.) - * @param url URL to point at - */ - public BaseLink(final Component child, final String url) { - super(); - m_url = url; - m_child = child; - } - - /** - * Constructor. - * - * @param child display component (Label, Image, etc.) - * @param listener PrintListener, may be used to change either the Display - * text or the url within a locked page. - */ - public BaseLink(final Component child, final PrintListener listener) { - this(child, ""); - try { - addPrintListener(listener); - } catch (TooManyListenersException e) { - // Can't happen - throw new UncheckedWrapperException("Too many listeners: " + e - .getMessage(), e); - } - } - - /** - * Constructor. - * - * @param listener - */ - public BaseLink(final PrintListener listener) { - this("", listener); - } - - // DEPRECATED constructors - /** - * Constructor. - * - * @param label as text - * @param url - * - * @deprecated use BaseLink(Component,url) instead with a Label using a - * GlobalizedMessage instead - */ - public BaseLink(final String label, final String url) { - this(new Label(label), url); - } - - /** - * Constructor. - * - * @param label as text - * @param listener PrintListener, may be used to change either the Display - * text or the url within a locked page. - * - * @deprecated use BaseLink(Component,listener) instead with a Label using a - * GlobalizedMessage instead - */ - public BaseLink(final String label, final PrintListener listener) { - this(new Label(label), listener); - } - - // Class Methods - /** - * Clone. - * - * @return The clone of the object. - * - * @throws CloneNotSupportedException If cloning is not supported. - */ - @Override - public Object clone() throws CloneNotSupportedException { - final BaseLink result = (BaseLink) super.clone(); - result.m_printListener = null; - return result; - } - - /** - * Adds a print listener. Since the PrintListener is expected - * to modify the target of the PrintEvent, only one print - * listener can be set for a link. - * - * @param listener The print listener. Must not null. - * - * @throws IllegalArgumentException if listener is null. - * @throws TooManyListenersException if a print listener has previously been - * added. - */ - public void addPrintListener(final PrintListener listener) - throws IllegalStateException, TooManyListenersException { - if (listener == null) { - throw new IllegalArgumentException( - "Argument listener can not be null"); - } - if (m_printListener != null) { - throw new TooManyListenersException( - "Too many listeners. Can only have one"); - } - m_printListener = listener; - } - - /** - * Removes a previously added print listener. If the passed in - * listener is not the listener that was added with - * {@link #addPrintListener addPrintListener}, an IllegalArgumentException - * will be thrown. - * - * @param listener The listener that was previously added with - * addPrintListener. Must not be - * null. - * - * @throws IllegalArgumentException if listener is not the - * currently registered print listener or - * is null. - */ - public void removePrintListener(final PrintListener listener) - throws IllegalArgumentException { - if (listener == null) { - throw new IllegalArgumentException("listener can not be null"); - } - if (listener != m_printListener) { - throw new IllegalArgumentException( - "listener is not registered with this widget"); - } - m_printListener = null; - } - - /** - * Execute the {@link PrintListener} assigned to the link. - * - * @param state The current page state - * - * @return The base link after all {@link PrintListener} have been executed. - */ - protected BaseLink firePrintEvent(final PageState state) { - BaseLink l = this; - if (m_printListener != null) { - try { - l = (BaseLink) this.clone(); - m_printListener.prepare(new PrintEvent(this, state, l)); - } catch (CloneNotSupportedException e) { - l = this; - throw new UncheckedWrapperException(e); - } - } - return l; - } - - /** - * Retrieves the label component used to display the Link. Typically a - * Label, but may be an other type, e.g. an Image, as well. - * - * @return Component used to display the Link. - */ - public final Component getChild() { - return m_child; - } - - public void setChild(final Component child) { - Assert.isUnlocked(this); - m_child = child; - } - - /** - * Use a GlobalizedMessage to be used to display the link. It's primary - * purpose is to hide the parent class method to prevent its usage because - * Labels and GlobalizedMessages are used here differently (a - * GlobalizedMessage is here not directly used as a Label by specifying it - * as an attribute, inside a Label component). - * - * @param message The text to show. - */ - @Override - public void setLabel(final GlobalizedMessage message) { - Assert.isUnlocked(this); - Label label = new Label(message); - setChild((Component) label); - - } - - /** - * Get the target of the link. - * - * @return The target URL of the link. - */ - public final String getTarget() { - return m_url; - } - - public final void setTarget(final String url) { - Assert.isUnlocked(this); - - m_url = url; - } - - /** - * Sets the type of link this link represents. - * - * @param type the type of link - */ - protected void setTypeAttr(final String type) { - Assert.isUnlocked(this); - setAttribute(TYPE_ATTR, type); - } - - /** - * Generate the URL for the link. - * - * @param state The current {@link PageState}. - * @param parent The parent element of the link. - */ - protected abstract void generateURL(final PageState state, - final Element parent); - - /** - * Generates a DOM fragment: - * - *

-     * <bebop:link href="..." type="..." %bebopAttr;/>
-     * 
- * - * The {@code href} attribute contains the target the link should point to. - * The {@code type} attribute is used to give more fine grained control over - * which kind of link this element represents. The types are {@code link} - * for a {@code Link}, {@code control} for a {@link ControlLink}. There may - * be additional attributes depending on what type of link this link - * represents. - * - * @see ControlLink#generateXML - * - * @param state The current {@link PageState}. - * @param parent The XML element to attach the XML to. - */ - @Override - public void generateXML(final PageState state, final Element parent) { - if (isVisible(state)) { - BaseLink target = firePrintEvent(state); - - Element link = parent.newChildElement("bebop:link", BEBOP_XML_NS); - - target.generateURL(state, link); - target.exportConfirmAttributes(state, link); - //setup the link without javascript - target.setupNoJavascriptURL(state, link); - target.exportAttributes(link); - target.generateExtraXMLAttributes(state, link); - target.generateDescriptionXML(state, link); - target.getChild().generateXML(state, link); - } - } - - /** - * - * @param state - * @param sUrl - * - * @return - */ - private String getAbsoluteUrl(final PageState state, final String sUrl) { - String sReturn = ""; - - if ((sUrl.indexOf(":") != -1) || sUrl.indexOf("/") == 0) { - //if sUrl contains a ":" or begins with a "/", then it is an absolute URL - sReturn = sUrl; - } else { - //otherwise, it is a relative URL, so we need to make it an absolute URL - - //get the current URL - String sThisURL = ""; - try { - sThisURL = state.stateAsURL(); - } catch (java.io.IOException ioe) { - //ignore - } - //trim the current URL back to the last "/" character - int iIndex = sThisURL.lastIndexOf("/"); - - //if there is no "/" character, then assume we are at server root - if (iIndex == -1) { - sReturn = "/" + sUrl; - } else { - sReturn = sThisURL.substring(0, iIndex) + "/" + sUrl; - } - } - - return sReturn; - } - - /** - * Sets up no-JavaScript fallback HTML - * - * @param state The current {@link PageState}. - * @param link The link element. - */ - protected void setupNoJavascriptURL(final PageState state, - final Element link) { - String sURL = null; - - if (m_sConfirmMsg.length() > 0 - || (m_confirmMsg != null && m_confirmMsg.localize().toString() - .length() > 0)) { - - //if we want the confirm link, create the link - String sOkUrl = getAbsoluteUrl(state, link.getAttribute(HREF)); - String sCancelUrl = null; - try { - sCancelUrl = state.stateAsURL(); - } catch (java.io.IOException e) { - Assert.fail("Could not get current page state as URL"); - } - - if (m_sConfirmMsg.length() > 0) { - sURL = ConfirmPage.getConfirmUrl(m_sConfirmMsg, sOkUrl, - sCancelUrl); - } else if (m_confirmMsg != null) { - sURL = ConfirmPage.getConfirmUrl(m_confirmMsg.localize() - .toString(), sOkUrl, sCancelUrl); - } - - } else { - //don't want confirm link--just no javascript link - if (m_noJavascriptURL == null) { - //get the generatedURL and make it the default noJavaScript link - sURL = link.getAttribute(HREF); - } else { - sURL = m_noJavascriptURL; - } - } - link.addAttribute(HREF_NO_JAVASCRIPT, sURL); - exportAttributes(link); - } - - /** - * Adds type-specific XML attributes to the XML element representing this - * link. Subclasses should override this method if they introduce more - * attributes than the ones {@link #generateXML generateXML} produces by - * default. - * - * @param state The current request - * @param link The XML element representing this link - */ - protected void generateExtraXMLAttributes(final PageState state, - final Element link) { - } - - /** - * Sets onClick event and disables the javascript-based double-click - * protection for this link. Not for confirmation messages; Should call - * setConfirmation for that. - * - * @param value The confirmation link. To not use the value - * {@code return confirm(} with this method. - * - * @see #setConfirmation - */ - public void setOnClick(final String value) { - //should not use this method to set confirmation messages--should - //use setConfirmation() instead, or else the javascript will break - if (value != null) { - Assert.isTrue(!value.toLowerCase().startsWith("return confirm("), - "Do not use setOnClick() to set confirmation messages. " - + "Use setCofirmation() instead."); - } - - setAttribute(ON_CLICK, value); - } - - /** - * Forces the user to click through a confirmation dialog before this link - * is followed. The user is prompted with the specified message. If the user - * does not does not confirm, the link is not followed. The current - * implementation uses the JavaScript confirm function and the onClick - * attribute. If JavaScript is not enabled in the client browser, this - * method will redirect the browser to a Bebop confirmation page rather than - * use a JavaScript confirmation. Subsequent calls to setOnClick will undo - * the effect of this method. - * - * @param message the confirmation message presented to the user. This - * message cannot have an apostrophe or back slash. - * - * @deprecated Use setConfirmation(final GlobalizedMessage msg) instead - */ - public void setConfirmation(final String message) { - //make sure that the message doesn't have any apostrophe's - //or back slashes - - if (Assert.isEnabled()) { - final boolean isGoodMessage = message.indexOf("'") == -1 && message - .indexOf("\\") == -1; - Assert.isTrue(isGoodMessage, - "confirmation message cannot contain apostrophe or back slash"); - } - - m_sConfirmMsg = message; - } - - /** - * Set a GlobalizedMessage as confirmation message - * - * @param msg The text to show for confirming. - */ - public void setConfirmation(final GlobalizedMessage msg) { - m_confirmMsg = msg; - } - - /** - * Generate XML output for confirmation links - * - * @param state PageState - * @param link Parent element - */ - private void exportConfirmAttributes(final PageState state, - final Element link) { - - // If a confirmation message is set - if (m_sConfirmMsg.length() > 0 || m_confirmMsg != null) { - - // then add the needed attributes to link - link.addAttribute("confirm", "confirm"); - - // If m_sConfirmMsg is not empty - if (m_sConfirmMsg.length() > 0) { - - // then set the onclick attribute for the link with the static message - link.addAttribute(ON_CLICK, "return confirm(\\'" + m_sConfirmMsg - + "\\');"); - - // else if m_configMsg is set - } else if (m_confirmMsg != null) { - - //then set the onclick attribute for the link with a globalized message - link.addAttribute(ON_CLICK, "return confirm(\\'" + m_confirmMsg - .localize() + "\\');"); - - } - } - } - - public final void setNoJavascriptTarget(final String sURL) { - Assert.isUnlocked(this); - m_noJavascriptURL = sURL; - } - - public final String getNoJavascriptTarget() { - return m_noJavascriptURL; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/BasePage.java b/ccm-core/src/main/java/com/arsdigita/bebop/BasePage.java deleted file mode 100755 index 152c044bb..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/BasePage.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.util.Assert; - -/** - * The base page class for use with the PageFactory - * class. It sets two attributes on the XML tag for - * the bebop:page, namely application - * and id. The values for these two - * tags correspond to the parameters passed to the - * PageFactory.buildPage method. - *

- * This class is intended to be subclassed to provide - * the page infrastructure required by a project, for - * example, adding some navigation components. - * The SimplePage class provides a easy implementation - * whereby the navigation components can be specified - * in the enterprise.init file. - */ -public class BasePage extends Page { - - public BasePage(String application, - Label title, - String id) { - super(title, new SimpleContainer()); - - Assert.exists(application, "application name"); - setAttribute("application", application); - - if (id != null) { - setAttribute("id", id); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/BebopConfig.java b/ccm-core/src/main/java/com/arsdigita/bebop/BebopConfig.java deleted file mode 100755 index 28c74afb4..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/BebopConfig.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.page.PageTransformer; -import com.arsdigita.bebop.util.BebopConstants; -import com.arsdigita.templating.PresentationManager; -import com.arsdigita.util.UncheckedWrapperException; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.Configuration; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.configuration.Setting; - -import java.util.stream.Collectors; - -/** - * - * @author Jens Pelzetter - */ -@Configuration( - descBundle = "com.arsdigita.bebop.BebopConfig", - descKey = "description", - titleKey = "title" -) -public final class BebopConfig { - - @Setting( - descKey = "presenterClassName.desc", - labelKey = "presenterClassName.label" - ) - private String presenterClassName = PageTransformer.class.getName(); - - @Setting( - descKey = "basePageClassName.desc", - labelKey = "basePageClassName.label" - ) - private String basePageClassName = ""; - - @Setting( - descKey = "tidyConfigFile.desc", - labelKey = "tidyConfigFile.label" - ) - private String tidyConfigFile - = "com/arsdigita/bebop/parameters/tidy.properties"; - - @Setting( - descKey = "fancyErrors.desc", - labelKey = "fancyErrors.label" - ) - private Boolean fancyErrors = false; - - @Setting( - descKey = "dcpOnButtons.desc", - labelKey = "dcpOnButtons.label" - ) - private Boolean dcpOnButtons = true; - - @Setting( - descKey = "dcpOnLinks.desc", - labelKey = "dcpOnLinks.label" - ) - private Boolean dcpOnLinks = false; - - @Setting( - descKey = "treeSelectEnabled.desc", - labelKey = "treeSelectEnabled.label" - ) - private Boolean treeSelectEnabled = false; - - @Setting( - descKey = "dhtmlEditors.desc", - labelKey = "dhtmlEditors.label" - ) - private Set dhtmlEditors = new HashSet<>( - Arrays.asList(new String[]{BebopConstants.BEBOP_XINHAEDITOR, - BebopConstants.BEBOP_FCKEDITOR, - BebopConstants.BEBOP_DHTMLEDITOR, - BebopConstants.BEBOP_CCMEDITOR, - BebopConstants.BEBOP_TINYMCE_EDITOR})); - - @Setting( - descKey = "defaultDhtmlEditor.desc", - labelKey = "defaultDhtmlEditor.label" - ) - private String defaultDhtmlEditor = BebopConstants.BEBOP_TINYMCE_EDITOR; - - @Setting( - descKey = "dhtmlEditorSrcFile.desc", - labelKey = "dhtmlEditorSrcFile.label" - ) -// private String dhtmlEditorSrcFile = "/ccm-editor/ccm-editor-loader.js"; - private String dhtmlEditorSrcFile = "/webjars/tinymce/4.8.2/tinymce.js"; - - @Setting( - descKey = "showClassName.desc", - labelKey = "showClassName.label" - ) - private Boolean showClassName = false; - - public static BebopConfig getConfig() { - final ConfigurationManager confManager = CdiUtil.createCdiUtil() - .findBean(ConfigurationManager.class); - return confManager.findConfiguration(BebopConfig.class); - } - - public String getPresenterClassName() { - return presenterClassName; - } - - @SuppressWarnings("unchecked") - public Class getPresenterClass() { - try { - return (Class) Class. - forName(presenterClassName); - } catch (ClassNotFoundException ex) { - throw new UncheckedWrapperException(ex); - } - } - - public void setPresenterClassName(final String presenterClassName) { - this.presenterClassName = presenterClassName; - } - - public void setPresenterClass( - final Class presenterClass) { - setPresenterClassName(presenterClass.getName()); - } - - public String getBasePageClassName() { - return basePageClassName; - } - - @SuppressWarnings("unchecked") - public Class getBasePageClass() { - try { - return (Class) Class.forName(basePageClassName); - } catch (ClassNotFoundException ex) { - throw new UncheckedWrapperException(ex); - } - } - - public void setBasePageClassName(final String basePageClassName) { - this.basePageClassName = basePageClassName; - } - - public void setBasePageClass(final Class basePageClass) { - setBasePageClassName(basePageClass.getName()); - } - - public String getTidyConfigFile() { - return tidyConfigFile; - } - - public void setTidyConfigFile(final String tidyConfigFile) { - this.tidyConfigFile = tidyConfigFile; - } - - public Boolean getFancyErrors() { - return fancyErrors; - } - - public void setFancyErrors(final Boolean fancyErrors) { - this.fancyErrors = fancyErrors; - } - - public Boolean getDcpOnButtons() { - return dcpOnButtons; - } - - public void setDcpOnButtons(final Boolean dcpOnButtons) { - this.dcpOnButtons = dcpOnButtons; - } - - public Boolean getDcpOnLinks() { - return dcpOnLinks; - } - - public void setDcpOnLinks(final Boolean dcpOnLinks) { - this.dcpOnLinks = dcpOnLinks; - } - - public Boolean isTreeSelectEnabled() { - return treeSelectEnabled; - } - - public void setTreeSelectEnabled(final Boolean treeSelectEnabled) { - this.treeSelectEnabled = treeSelectEnabled; - } - - public Set getDhtmlEditors() { - return new HashSet<>(dhtmlEditors); - } - - public void setDhtmlEditors(final Set dhtmlEditors) { - this.dhtmlEditors = dhtmlEditors; - } - - public String getDefaultDhtmlEditor() { - return defaultDhtmlEditor; - } - - public void setDefaultDhtmlEditor(final String defaultDhtmlEditor) { - this.defaultDhtmlEditor = defaultDhtmlEditor; - } - - public String getDhtmlEditorSrcFile() { - return dhtmlEditorSrcFile; - } - - public void setDhtmlEditorSrcFile(final String dhtmlEditorSrcFile) { - this.dhtmlEditorSrcFile = dhtmlEditorSrcFile; - } - - public Boolean getShowClassName() { - return showClassName; - } - - public void setShowClassName(final Boolean showClassName) { - this.showClassName = showClassName; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 89 * hash + Objects.hashCode(tidyConfigFile); - hash = 89 * hash + Objects.hashCode(fancyErrors); - hash = 89 * hash + Objects.hashCode(dcpOnButtons); - hash = 89 * hash + Objects.hashCode(dcpOnLinks); - hash = 89 * hash + Objects.hashCode(treeSelectEnabled); - hash = 89 * hash + Objects.hashCode(dhtmlEditors); - hash = 89 * hash + Objects.hashCode(defaultDhtmlEditor); - hash = 89 * hash + Objects.hashCode(dhtmlEditorSrcFile); - hash = 89 * hash + Objects.hashCode(showClassName); - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof BebopConfig)) { - return false; - } - final BebopConfig other = (BebopConfig) obj; - if (!Objects.equals(tidyConfigFile, other.getTidyConfigFile())) { - return false; - } - if (!Objects.equals(defaultDhtmlEditor, other.getDefaultDhtmlEditor())) { - return false; - } - if (!Objects.equals(dhtmlEditorSrcFile, other.getDhtmlEditorSrcFile())) { - return false; - } - if (!Objects.equals(fancyErrors, other.getFancyErrors())) { - return false; - } - if (!Objects.equals(dcpOnButtons, other.getDcpOnButtons())) { - return false; - } - if (!Objects.equals(dcpOnLinks, other.getDcpOnLinks())) { - return false; - } - if (!Objects.equals(treeSelectEnabled, other.isTreeSelectEnabled())) { - return false; - } - if (!Objects.equals(dhtmlEditors, other.getDhtmlEditors())) { - return false; - } - return Objects.equals(showClassName, other.getShowClassName()); - } - - @Override - public String toString() { - return String.format( - "%s{ " - + "tidyConfigFile = %s, " - + "fancyErrors = %b, " - + "dcpOnButtons = %b, " - + "dcpOnLinks = %b, " - + "treeSelectEnabled = %b, " - + "dhtmlEditors = { %s }, " - + "defaultDhtmlEditor = %s, " - + "dhtmlEditorSrcFile = %s, " - + "showClassName = %b" - + " }", - super.toString(), - tidyConfigFile, - fancyErrors, - dcpOnButtons, - dcpOnLinks, - treeSelectEnabled, - dhtmlEditors.stream().collect(Collectors.joining(", ")), - defaultDhtmlEditor, - dhtmlEditorSrcFile, - showClassName); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/BoxPanel.java b/ccm-core/src/main/java/com/arsdigita/bebop/BoxPanel.java deleted file mode 100755 index f58d6046c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/BoxPanel.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import java.util.Iterator; - - -import com.arsdigita.xml.Element; - -import com.arsdigita.bebop.form.Hidden; - -// This interface contains the XML element name of this class -// in a constant which is used when generating XML -import com.arsdigita.bebop.util.BebopConstants; -import com.arsdigita.bebop.util.PanelConstraints; - -/** - * A container that prints its components in one row, either horizontally or - * vertically. - * - * @author David Lutterkort - * @version $Id: BoxPanel.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class BoxPanel extends SimpleContainer - implements BebopConstants, PanelConstraints { - - /** Specifies that components should be laid out left to right. */ - public final static int HORIZONTAL = 1; - - /** Specifies that components should be laid out top to bottom. */ - public final static int VERTICAL = 2; - - /** XML attribute for width */ - private static final String WIDTH_ATTR = "width"; - - /** XML attribute wether to draw a border. */ - private static final String BORDER_ATTR = "border"; - - /** Property to whether to draw a HORIZONTAL or VERTICAL box panel. */ - private int m_axis; - - /** Property to store whether to to center alignment. */ - private boolean m_centering; - - - /** - * Constructor, creates a box panel that lays out its components from - * top to bottom. The components are not centered. - */ - public BoxPanel() { - this(VERTICAL); - } - - /** - * Constructor, creates a box panel that lays out its components in the given - * direction. The components are not centered. - * - * @param axis the axis to use to lay out the components - */ - public BoxPanel(int axis) { - this(axis, false); - } - - /** - * Creates a box panel that lays out its components in the given - * direction and centers them if that is specified. - * - * @param axis the axis to use to lay out the components - * @param centering true if the layout should be centered - */ - public BoxPanel(int axis, boolean centering) { - m_axis = axis; - m_centering = centering; - } - - // Instance methods - - /** - * Sets the width attribute of the box panel. The given width should be in - * a form that is legal as the width attribute of an HTML - * table element. - * - * @param w the width of the box panel - */ - public void setWidth(String w) { - setAttribute(WIDTH_ATTR, w); - } - -// /** -// * Sets whether a border should be drawn. -// * -// * @param isBorder true if a border should be drawn -// * @deprecated Use {@link #setBorder(int border)} instead. -// */ -// public void setBorder(boolean isBorder) { -// if (isBorder) { -// setAttribute(BORDER_ATTR, "1"); -// } else { -// setAttribute(BORDER_ATTR, "0"); -// } -// } - - /** - * - * Sets the width of the border to draw around the components. This value - * will be used for the border attribute in an HTML - * table element. - * - * @param border the width of the border - */ - public void setBorder(int border) { - setAttribute(BORDER_ATTR, String.valueOf(border)); - } - - /** - * Adds nodes for the panel and its child components to be rendered, - * usually in a table. Any hidden widgets directly contained in the box - * panel are added directly to parent and are not in any - * of the cells that the box panel generates. - * - *

Generates DOM fragment: - *

<bebop:boxPanel [width=...] border=... center... axis...> - * <bebop:cell> cell contents </bebop:cell> - * </bebop:boxPanel> - * - * @param parent - */ - @Override - public void generateXML(PageState state, Element parent) { - if (isVisible(state)) { - Element panel = parent.newChildElement(BEBOP_BOXPANEL, BEBOP_XML_NS); - // or: rowPanel/columPanel? - panel.addAttribute("center", String.valueOf(m_centering)); - panel.addAttribute("axis", String.valueOf(m_axis)); - exportAttributes(panel); - - for (Iterator i = children(); i.hasNext();) { - Component c = (Component) i.next(); - - if (c.isVisible(state)) { - if (c instanceof Hidden) { - c.generateXML(state, parent); - } else { - Element cell = panel.newChildElement(BEBOP_CELL, BEBOP_XML_NS); - c.generateXML(state, cell); - } - } - } - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ColumnPanel.java b/ccm-core/src/main/java/com/arsdigita/bebop/ColumnPanel.java deleted file mode 100755 index ee68b7769..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ColumnPanel.java +++ /dev/null @@ -1,574 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.form.Hidden; -import com.arsdigita.bebop.util.Attributes; -import com.arsdigita.bebop.util.PanelConstraints; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - * A container that prints its components in a table. Each child is printed - * in its own table cell. The number of columns can be specified in the - * constructor. The components are put into the table in the order in which - * they were added to the ColumnPanel by filling the table one row - * at a time (filling each row from left to right), from the top of the table - * to the bottom. - * - *

The position of the component within the cell can be influenced with the - * following constraints. - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Horizontal alignmentUse LEFT, CENTER, or - * RIGHT.
Vertical alignmentUse TOP, MIDDLE, or - * BOTTOM.
Full widthUse FULL_WIDTH to instruct the panel to - * put the component in a row by itself, spanning the full width of the - * table.
Inserting childrenUse INSERT to instruct the panel to - * insert the corresponding component, assuming that it will also be - * laid out by a ColumnPanel with the same number of - * columns.
- * - *

Constraints can be combined by OR-ing them together. For example, to print - * a component in a row of its own, left-aligned, at the bottom of its cell, - * use the constraint FULL_WIDTH | LEFT | BOTTOM. - * - *

Using the INSERT constraint fuses the current ColumnPanel - * with the panel of the child to which the constraint is applied. For example, - * consider a {@link Form} that is to have a 2-column format with labels in the - * left column and widgets in the right column. If a {@link FormSection} is - * added to the form, it should be included seamlessly into the parent form. - * To do this, set the INSERT constraint when the {@link - * FormSection} is added to the ColumnPanel of the {@link Form}. At - * the same time, tell the ColumnPanel used to lay out the {@link - * FormSection} that it is to be inserted into another panel. - * - *

The following pseudo-code illustrates the example. (It assumes that - * Form and FormSection are decorators of the ColumnPanel.) - * - *

- *
- *   Form form = new Form(new ColumnPanel(2));
- *   FormSection sec = new FormSection(new ColumnPanel(2, true));
- *
- *   sec.add(new Label("Basic Item Metadata"), ColumnPanel.FULL_WIDTH);
- *   sec.add(new Label("Title:"), ColumnPanel.RIGHT);
- *   sec.add(new Text("title"));
- *
- *   form.add(sec, ColumnPanel.INSERT);
- * 
- * - * @author David Lutterkort - * @version $Id: ColumnPanel.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class ColumnPanel extends SimpleContainer - implements PanelConstraints { - - /** An empty constraint corresponding to the default */ - private static final Constraint DEFAULT_CONSTRAINT = new Constraint(); - - /** The number of columns in the panel */ - private int m_nCols; - - /** Explicitly registered constraints for child components. Maps - * Componentss to Constraints */ - private Map m_constraints; - - /** Is this panel inserted in another one ? If so, do not produce - * <table> tags */ - private boolean m_inserted; - - /** Border attributes */ - private Attributes m_border; - private Attributes m_padFrame; - private Attributes m_pad; - private String[] m_columnWidth; - - -// Instance methods - - /** - * Creates a table panel with the specified number of columns. - * - * @param nCols number of columns in the panel - */ - public ColumnPanel(int nCols) { - this(nCols, false); - makeBorder(); - makePadFrame(); - makePad(); - } - - /** - * Creates a table panel with the specified number of columns that will - * be printed as a direct child of a ColumnPanel - * with the same number of columns. - * @see #setInserted - * - * @param nCols number of columns in the panel - * @param inserted true if this panel - * is to be printed as a direct child of a - * ColumnPanel with the same number of - * columns - */ - public ColumnPanel(int nCols, boolean inserted) { - m_nCols = nCols; - setInserted(inserted); - m_constraints = new HashMap(); - m_columnWidth=new String[nCols]; - } - - /** - * Adds a component, specifying its constraints. - * - * @param c the component to add - * @param constraints the constraints for this component - */ - @Override - public void add(Component c, int constraints) { - super.add(c); - setConstraint(c, constraints); - } - - /** - * Sets whether this panel will be printed inside a - * ColumnPanel with the same number of columns. If - * inserted is true, no <table> tags will be produced - * to enclose the child components. - * @param inserted true if this panel is to be printed - * inside a ColumnPanel with the same number of columns - */ - public void setInserted(boolean inserted) { - Assert.isUnlocked(this); - m_inserted = inserted; - } - - /** - * Determines whether this panel is to be inserted into another panel. - * @return true if this panel is to be inserted - * into another panel; false otherwise. - * - * @see #setInserted - */ - public final boolean isInserted() { - return m_inserted; - } - - /** - * Returns the number of columns for this ColumnPanel - * @return the number of columns - * - */ - public final int getNumCols() { - return m_nCols; - } - - /** - * Adds child components as a subtree under table-style nodes. If any of the - * direct children are hidden form widgets, they are added directly to - * parent rather than included in any of the - * cell elements of the panel. - * - *

Generates a DOM fragment: - *

-     * <bebop:pad>
-     *   [<bebop:padFrame>]
-     *    [<bebop:border>]
-     *      <bebop:panelRow>
-     *       <bebop:cell> ... cell contents </bebop:cell>
-     *       <bebop:cell> ... cell contents </bebop:cell>
-     *       ...
-     *      </bebop:panelRow>
-     *      <bebop:panelRow>
-     *       <bebop:cell> ... cell contents </bebop:cell>
-     *       <bebop:cell> ... cell contents </bebop:cell>
-     *       ...
-     *      </bebop:panelRow>
-     *    [</bebop:border>]
-     *   [</bebop:padFrame>]
-     * </bebop:boxPanel>
- * @param state the current page state - * @param parent the parent element for these child components - */ - @Override - public void generateXML(PageState state, Element parent) { - if ( isVisible(state) ) { - - Element panel = parent.newChildElement("bebop:columnPanel", BEBOP_XML_NS); - exportAttributes(panel); - // parent.addContent(panel); - - generateChildren(state, parent, generateTopNodes(panel)); - } - } - - // Border attributes - - private void makeBorder() { - if ( m_border == null ) { - m_border = new Attributes(); - m_border.setAttribute("cellspacing", "0"); - m_border.setAttribute("cellpadding", "4"); - m_border.setAttribute("border", "0"); - m_border.setAttribute("width", "100%"); - } - } - - /** - * - * - * @param c - */ - public void setBorderColor(String c) { - makeBorder(); - m_border.setAttribute("bgcolor", c); - } - - /** - * - * - * @param w - */ - public void setBorderWidth(String w) { - makeBorder(); - m_border.setAttribute("cellpadding", w); - } - - public void setColumnWidth(int col, String width) { - m_columnWidth[col-1]=width; - } - - /** - * - * - * @param b - */ - public void setBorder(boolean b) { - if (b) { - makeBorder(); - } else { - m_border = null; - } - } - - // Pad and Padframe attributes - private void makePadFrame() { - if (m_padFrame == null) { - m_padFrame = new Attributes(); - m_padFrame.setAttribute("cellspacing", "0"); - m_padFrame.setAttribute("cellpadding", "6"); - m_padFrame.setAttribute("border", "0"); - m_padFrame.setAttribute("width", "100%"); - } - } - - /** - * - * - */ - private void makePad() { - if ( m_pad == null ) { - m_pad = new Attributes(); - m_pad.setAttribute("cellspacing", "0"); - m_pad.setAttribute("cellpadding", "2"); - m_pad.setAttribute("border", "0"); - m_pad.setAttribute("width", "100%"); - } - } - - /** - * - * - * @param c - */ - public void setPadColor(String c) { - makePadFrame(); - makePad(); - m_padFrame.setAttribute("bgcolor", c); - m_pad.setAttribute("bgcolor", c); - } - - /** - * - * - * @param w - */ - public void setWidth(String w) { - makePadFrame(); - m_padFrame.setAttribute("width", w); - } - - /** - * - * - * @param w - */ - public void setPadFrameWidth(String w) { - makePadFrame(); - m_padFrame.setAttribute("cellpadding", w); - } - - /** - * - * - * @param border - */ - public void setPadBorder(boolean border) { - makePad(); - if(border) { - m_pad.setAttribute("border", "1"); - } else { - m_pad.setAttribute("border", "0"); - } - } - - /** - * - * - * @param padding - */ - public void setPadCellPadding(String padding) { - makePad(); - m_pad.setAttribute("cellpadding", padding); - } - - /** - * add top tags (will translate to opening/closing), - * including display styles - */ - private Element generateTopNodes(Element parent) { - // FIXME: set background color, border effects, cell spacing etc. - if (isInserted()) { - return parent; - } - String l_class = getClassAttr(); - if (m_border != null) { - Element border = parent.newChildElement("bebop:border",BEBOP_XML_NS); - if (l_class != null) { - m_border.setAttribute("class", l_class); - } - m_border.exportAttributes(border); - // parent.addContent(border); - parent=border; // nest the rest inside border - } - if ( m_padFrame != null ) { - Element padFrame = parent.newChildElement("bebop:padFrame", BEBOP_XML_NS); - if (l_class != null) { - m_padFrame.setAttribute("class", l_class); - } - m_padFrame.exportAttributes(padFrame); - // parent.addContent(padFrame); - parent=padFrame; // nest the rest in padFrame - } - Element pad = parent.newChildElement("bebop:pad", BEBOP_XML_NS); - if (l_class != null) { - m_pad.setAttribute("class", l_class); - } - m_pad.exportAttributes(pad); - // parent.addContent(pad); - return pad; - } - - /** - * Lay out the child components using constraints registered for them, - * generating a DOM tree and extending another. - * - * @param state represents the state of the current request - * @param hiddenParent the element to which hiddens are added - * @param parent the element to which ordinary rows and cells are added - */ - private void generateChildren(PageState state, Element hiddenParent, - Element parent) { - // Count the number of components printed in the current row - int rowLen = m_nCols + 1; // Force generation of first row - Element row = null; - Element cell = null; - - for (Iterator i = children(); i.hasNext(); ) { - Component c = (Component) i.next(); - - if ( c.isVisible(state) ) { - - if ( c instanceof Hidden ) { - c.generateXML(state, hiddenParent); - } else { - if ( isInsert(c) ) { - c.generateXML(state, parent); - rowLen = m_nCols + 1; // Force generation of new row - } else { - if ( rowLen >= m_nCols || isFullWidth(c)) { - rowLen = 0; - row = parent.newChildElement("bebop:panelRow", BEBOP_XML_NS); - // parent.addContent(row); - } - cell = row.newChildElement("bebop:cell", BEBOP_XML_NS); - // row.addContent(cell); - if ( m_columnWidth[rowLen] != null ) { - cell.addAttribute("width", m_columnWidth[rowLen]); - } - getConstraint(c).exportAttributes(cell, m_nCols); - c.generateXML(state, cell); - rowLen++; - if ( isFullWidth(c) ) { - // Force a new row if c was full width - rowLen = m_nCols + 1; - } - } - } - } - } - } - - /** - * Sets the constraint for one child component. - * @param c the child component - * @param constraints the constraints to add - */ - public void setConstraint(Component c, int constraints) { - Assert.isUnlocked(this); - m_constraints.put(c, new Constraint(constraints)); - } - - /** - * Get the constraint object for a component. If no constraints have been - * set explicitly, return a default constraint object. - * - * @post return != null - */ - private Constraint getConstraint(Component c) { - Constraint result = (Constraint) m_constraints.get(c); - if ( result == null ) { - return DEFAULT_CONSTRAINT; - } else { - return result; - } - } - - private boolean isInsert(Component c) { - return getConstraint(c).isInsert(); - } - - private boolean isFullWidth(Component c) { - return getConstraint(c).isFullWidth(); - } - - - // Inner class(es) - - /** - * Represent the constraints for one child component - */ - private static class Constraint { - private boolean m_fullWidth; - private boolean m_insert; - private String m_alignment; // for print - private String m_halign; // for generateXML - private String m_valign; // for generateXML - - public Constraint() { - this(0); - } - - public Constraint(int constraints) { - StringBuilder s = new StringBuilder(); - - if ( (constraints & (LEFT|CENTER|RIGHT)) != 0 ) { - s.append(" align=\""); - if ( (constraints & LEFT) != 0) { - s.append(m_halign = "left"); - } else if ( (constraints & CENTER) != 0) { - s.append(m_halign = "center"); - } else if ( (constraints & RIGHT) != 0) { - s.append(m_halign = "right"); - } - s.append("\" "); - } else { - m_halign = null; - } - - if ( (constraints & (TOP|MIDDLE|BOTTOM)) != 0 ) { - s.append(" valign=\""); - if ( (constraints & TOP) != 0) { - s.append(m_valign = "top"); - } else if ( (constraints & MIDDLE) != 0) { - s.append(m_valign = "middle"); - } else if ( (constraints & BOTTOM) != 0) { - s.append(m_valign = "bottom"); - } - s.append("\" "); - } else { - m_valign = null; - } - - m_alignment = s.toString(); - - m_fullWidth = (constraints & FULL_WIDTH) != 0; - m_insert = (constraints & INSERT) != 0; - } - - public final boolean isFullWidth() { - return m_fullWidth; - } - - public final boolean isInsert() { - return m_insert; - } - - public final String getAlignment() { - return m_alignment; - } - - public final String getHAlign() { - return m_halign; - } - - public final String getVAlign() { - return m_valign; - } - - public void exportAttributes(Element cell, int nCols) { - String halign = getHAlign(); - String valign = getVAlign(); - if (halign != null) { - cell.addAttribute("align" , halign); - } - if (valign != null) { - cell.addAttribute("valign", valign); - } - if ( isFullWidth() ) { - cell.addAttribute("colspan", Integer.toString(nCols)); - } - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Completable.java b/ccm-core/src/main/java/com/arsdigita/bebop/Completable.java deleted file mode 100755 index e4589b816..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Completable.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.util.Assert; - -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -// Stacktraces is a support tool to use in a specifically difficult development -// situation. It is abundant in production and for normal development work and -// it provved to have funny side effects in a production environment. So it is -// commented out here but kept for further references. -// import com.arsdigita.developersupport.StackTraces; - -import java.util.ArrayList; -import java.util.Iterator; - - -/** - * Completable. - * - * @author rhs@mit.edu - **/ - -public abstract class Completable implements Component { - - private ArrayList m_completionListeners = new ArrayList(); - - public Completable() { - // See note above! - // if ( s_log.isDebugEnabled() ) { - // StackTraces.captureStackTrace(this); - // } - } - - public void addCompletionListener(ActionListener listener) { - Assert.isUnlocked(this); - m_completionListeners.add(listener); - } - - protected void fireCompletionEvent(PageState ps) { - ActionEvent evt = new ActionEvent(this, ps); - for (Iterator it = m_completionListeners.iterator(); it.hasNext(); ) { - ActionListener listener = (ActionListener) it.next(); - listener.actionPerformed(evt); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Component.java b/ccm-core/src/main/java/com/arsdigita/bebop/Component.java deleted file mode 100644 index b0b83b748..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Component.java +++ /dev/null @@ -1,387 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import java.util.Iterator; - -import com.arsdigita.util.Lockable; -import com.arsdigita.xml.Element; - -/** - * The common interface implemented by all Bebop components. - * - * During its lifetime, a component receives the following calls - * from the containing page. - * - *
    - *
  • During initialization/creation of the containing page: - *
      - *
    • {@link #register(Page)} is called to register - * state parameters that need to be preserved between requests to - * the same page. - *
    • - *
    • {@link #register(Form, FormModel)} is called if - * the component is contained - * in a {@link Form} or {@link FormSection}. Typically, only form - * widgets like text controls have parameters that need to be - * registered with the FormSection. - *
    • - *
    • {@link Lockable#lock lock} is called to lock the component and - * inform it that no further structural modifications will be - * made. - *
    • - *
    - *
  • - *
  • For each request made to the containing page: - *
      - *
    • If the request originated from - * this component, {@link #respond(PageState) respond} is called. - *
    • - *
    • To produce output, {@link #generateXML(PageState, Element) generateXML} is - * called to produce XML output that will be transformed by the - * templating system. - *
    • - *
    - *
  • - *
- * - * - *

Visibility

- * - *

A component can be either visible or - * invisible. Invisible components do not produce any output and - * containers should be careful to completely hide their presence. The - * visibility of a component can be influenced in a number of ways: - *

    - *
  • When a - * component is first added to the hierarchy of a {@link Page}, it is - * visible.
  • - *
  • A component's default (request-independent) visibility can be changed - * with a call to {@link Page#setVisibleDefault - * Page.setVisibleDefault} during setup of the page.
  • - *
  • A component - * can be made visible or invisible during the serving of a request with a - * call to {@link #setVisible setVisible}.
  • - *
- *

The {@link Page} makes sure that the visibility of components is - * preserved across repeated requests to the same page. - * - *

Standard Attributes

- *

Each component supports a few standard attributes that are copied - * through to the output when producing either HTML or XML - * output. These attributes are not used internally in any way, and setting - * them is entirely optional. - * - *

The standard attributes appear in the output as attributes in - * the element generated from this component. They correspond directly to - * properties with setters and getters. The standard attributes are as folows. - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Attribute Java property Purpose
id - * {@link #getIdAttr getIdAttr}/{@link #setIdAttr setIdAttr} - * Use to uniquely identify a component within the page. Uniqueness is - * not enforced. The id attribute allows stylesheet designers to - * access individual components.
class{@link #getClassAttr()}/{@link - * #setClassAttr(String)}Use as the generic name for a - * component. For example, if you have a UserInfoDisplay - * component, the class attribute can be used to name the - * component "UserInfoDisplay" so that a generic template rule - * can style all UserInfoDisplay components.
style{@link #getStyleAttr getStyleAttr}/{@link - * #setStyleAttr setStyleAttr}Use to add CSS style to an individual element.
- * - *

Caveat: Race Conditions

- *

- * When extending any Component, honor the - * Lockable contract indicated by extends {@link - * com.arsdigita.util.Lockable}. Beware that member variables - * are not inherently threadsafe, because you may be circumventing - * the contract. For variables that might be different for each - * request, use {@link RequestLocal}. If you must add member - * variables in the derived class, as a minimum be sure to safeguard - * any write access to instance variables with {@link - * com.arsdigita.util.Assert#assertNotLocked}. - *

- * @author David Lutterkort - * @author Stanislav Freidin - * @author Rory Solomon - * - * @version $Id$ - */ -public interface Component extends Lockable { - - /** - * The XML namespace used by all the Bebop components. - */ - String BEBOP_XML_NS = - "http://www.arsdigita.com/bebop/1.0"; - - /** - * The name for the class attribute. - * @see #setClassAttr(String) - * @see Standard Attributes - */ - String CLASS = "class"; - - /** - * The name for the style attribute. - * @see #setStyleAttr(String) - * @see Standard Attributes - */ - String STYLE = "style"; - - /** - * The name for the ID attribute. - * @see #setIdAttr - * @see Standard Attributes - */ - String ID = "id"; - - // HTML 4 event names - - /** - * The onClick event. - */ - String ON_CLICK = "onclick"; - - /** - *

Adds a DOM subtree representing this component under the given - * parent node. Uses the request values stored in state.

- * - * @param state represents the current request - * @param parent the node under which the DOM subtree should be added - * - * @pre state != null - * @pre parent != null - */ - void generateXML(PageState state, Element parent); - - - /** - *

Responds to the request. This method is only called if the request - * was made from a link or form that the component put on the page in the - * {@link PageState#stateAsURL} previous request.

- * - *

No output should be generated on the HTTP response. The component - * can store intermediate results in the state by calling - * {@link PageState#setAttribute setAttribute}.

- * - *

This method is called before any output is printed to the HTTP - * response so that the component can forward to a different page and - * thereby commit the response.

- * - * @param state represents the current request - * - * @pre state != null - */ - void respond(PageState state) - throws javax.servlet.ServletException; - - /** - * Returns an iterator over the children of this component. If the - * component has no children, returns an empty (not - * null) iterator. - * - * @return an iterator over the children of this component. - * - * @post return != null - */ - Iterator children(); - - /** - * Registers state parameters for the page with its model. - * - * A simple component with a state parameter param would do - * the following in the body of this method: - *
-     *   p.addComponent(this);
-     *   p.addComponentStateParam(this, param);
-     * 
- * - * You should override this method to set the default visibility - * of your component: - * - *
-     * public void register(Page p) {
-     *     super.register(p);
-     *     p.setVisibleDefault(childNotInitiallyShown,false);
-     *     p.setVisibleDefault(anotherChild, false);
-     * }
-     * 
- * - * Always call super.register when you override - * register. Otherwise your component may - * malfunction and produce errors like "Widget ... isn't - * associated with any Form" - * - * @param p - * @pre p != null - */ - void register(Page p); - - /** - * Registers form parameters with the form model for this - * form. This method is only important for {@link FormSection form - * sections} and {@link com.arsdigita.bebop.form.Widget widgets} - * (components that have a connection to an HTML form). Other - * components can implement it as a no-op. - * - * @param f - * @param m - * @pre f != null - * @pre m != null - */ - void register(Form f, FormModel m); - - /* Properties that will get copied straight to the output, - both in HTML and in XML - */ - - /** - * Gets the class attribute. - * - * @return the class attribute. - * - * @see #setClassAttr(String) - * @see Standard Attributes - */ - String getClassAttr(); - - /** - * Sets the class attribute. - * @param theClass a valid XML name - * @see Standard Attributes - * @see #getClassAttr - */ - void setClassAttr(String theClass); - - /** - * Gets the style attribute. - * - * @return the style attribute. - * - * @see #setStyleAttr - * @see Standard Attributes - */ - String getStyleAttr(); - - /** - * Sets the style attribute. style should be a valid CSS - * style, because its value will be copied verbatim to the output and - * appear as a style attribute in the top level XML or HTML - * output element. - * - * @param style a valid CSS style description for use in the - * style attribute of an HTML tag - * @see Standard Attributes - */ - void setStyleAttr(String style); - - /** - * Gets the id attribute. - * - * @return the id attribute. - * - * @see Standard Attributes - * @see #setIdAttr(String id) - */ - String getIdAttr(); - - /** - * Sets the id attribute. id - * should be an XML name - * that is unique within the {@link Page Page} in which this component is - * contained. The value of id is copied literally to the - * output and not used for internal processing. - * - * @param id a valid XML identifier - * @see Standard Attributes - */ - void setIdAttr(String id); - - /** - * Supplies a key for making parameter names unique. To be used - * instead of the component's index (see Component Prefix). - * To avoid collision with indexOf, it - * should (1) be a legal fragment of a cgi parameter, (2) differ from "g", - * and (3) not start with a digit. - * - * @param key - * @return - */ - Component setKey(String key); - - /** - * Retrieves the programmer-supplied key. Normally, there is no - * such key and the method returns null. - * - * @return the programmer-supplied key. - */ - String getKey(); - - /** - * Determines whether the component is visible in the request - * represented by state. - * @see #setVisible setVisible - * @see Description of Visibility - * above - * - * - * @param state represents the current request - * @return true if the component is visible; false - * otherwise. - * @pre state != null - */ - boolean isVisible(PageState state); - - /** - * Changes the visibility of the component. The component will keep the - * visibility that is set with this method in subsequent requests to this page. - * - * @param state represents the current request - * @param v true if the component should be visible - * @pre state != null - * @see Description of Visibility - * above - */ - void setVisible(PageState state, boolean v); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ComponentSelectionModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/ComponentSelectionModel.java deleted file mode 100755 index 17fd1ece6..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ComponentSelectionModel.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - - - -/** - * Encapsulates the selection of a single object from many - * possibilities. Similar to {@link SingleSelectionModel SingleSelectionModel}, - * but ties a component to the selection. - * - *

A call to the {@link #getComponent getComponent} method returns a - * component that can be used to display the current selection. - * - * @author David Lutterkort - * @author Stanislav Freidin - * @param - */ -public interface ComponentSelectionModel extends SingleSelectionModel { - - - /** - * Returns the component that should be used to output the currently - * selected element. - * - * @param state the state of the current request - * @return the component used to output the selected element. - */ - Component getComponent(PageState state); - - /** - * Return the selected object. The concrete type of the returned object - * depends on the implementation of the model. - * - * @param state represents the state of the current request - * @return the selected object - */ - //Object getElement(PageState state); - - /** - * Return an iterator over all the components that can possibly be used - * in rendering selected objects. If one component may be used to render - * various objects, for example for displaying detail information about - * each of a number of objects of the same type, the component needs to - * occur only once in the iterator. - * - * @return an iterator of components listing all the components that can - * may be used in displaying selected objects - */ - //Iterator components(); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ConfirmPage.java b/ccm-core/src/main/java/com/arsdigita/bebop/ConfirmPage.java deleted file mode 100755 index 628ed4892..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ConfirmPage.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - - -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.web.ParameterMap; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.web.URL; - -/** - * A Bebop Confirmation Page which should be mounted at ConfirmPage.CONFIRM_URL by the BebopMapDispatcher. - * This page takes three URL parameters: - *

    - *
  • A confirmation message with variable name ConfirmPage.CONFIRM_MSG_VAR - *
  • An OK URL with variable name ConfirmPage.OK_URL_VAR - *
  • A Cancel URL with variable name ConfirmPage.CANCEL_URL_VAR - *
- * The page displays a form asking the confirmation message passed in. If the user hits OK, - * Then the page redirects to the OK URL. Otherwise, if the user hits Cancel, - * The page redirects to the Cancel URL. - * @author Bryan Che - */ - -public class ConfirmPage extends Page { - private StringParameter m_ConfirmMsgParam; - private StringParameter m_OkUrlParam; - private StringParameter m_CancelUrlParam; - - private RequestLocal m_ConfirmMsgRL; - private RequestLocal m_OkUrlRL; - private RequestLocal m_CancelUrlRL; - - //URL at which to mount this page - public static final String CONFIRM_URL = "BEBOP-confirmation-page"; - - //URL variable names - private static final String CONFIRM_MSG_VAR = "confirm-msg"; - private static final String OK_URL_VAR = "ok-url"; - private static final String CANCEL_URL_VAR = "cancel-url"; - - public ConfirmPage() { - super(); - - m_ConfirmMsgParam = new StringParameter(CONFIRM_MSG_VAR); - m_OkUrlParam = new StringParameter(OK_URL_VAR); - m_CancelUrlParam = new StringParameter(CANCEL_URL_VAR); - - //add global state params - addGlobalStateParam(m_ConfirmMsgParam); - addGlobalStateParam(m_OkUrlParam); - addGlobalStateParam(m_CancelUrlParam); - - //initialize RequestLocals for the URL params - m_ConfirmMsgRL = new RequestLocal() { - protected Object initialValue(PageState ps) { - return ps.getValue(m_ConfirmMsgParam); - } - }; - m_OkUrlRL = new RequestLocal() { - protected Object initialValue(PageState ps) { - return ps.getValue(m_OkUrlParam); - } - }; - m_CancelUrlRL = new RequestLocal() { - protected Object initialValue(PageState ps) { - return ps.getValue(m_CancelUrlParam); - } - }; - - //set the title - buildTitle(); - - //add the form - ConfirmForm cf = new ConfirmForm(m_ConfirmMsgRL, m_OkUrlRL, m_CancelUrlRL); - add(cf); - - lock(); - } - - /** - * Returns a URL (minus "http://" string and server name) at which to access the ConfirmPage - * with the given Confirmation Message, OK URL, and Cancel URL. - * @param sConfirmMsg the Confirmation message to display on the page - * @param sOkUrl the URL to which to redirect if the user hits OK - * @param sCancelUrl the URL to which to redirect if the user hits Cancel - * @return URL at which to access the ConfirmPage - */ - public static String getConfirmUrl(String sConfirmMsg, String sOkUrl, String sCancelUrl) { - final ParameterMap params = new ParameterMap(); - - params.setParameter(CONFIRM_MSG_VAR, sConfirmMsg); - params.setParameter(OK_URL_VAR, sOkUrl); - params.setParameter(CANCEL_URL_VAR, sCancelUrl); - - return URL.there("/" + CONFIRM_URL, params).toString(); - } - - protected void buildTitle() { - class ConfirmPagePrintListener implements PrintListener { - public void prepare(PrintEvent e) { - Label label = (Label) e.getTarget(); - PageState ps = e.getPageState(); - - label.setLabel((String)m_ConfirmMsgRL.get(ps)); - } - } - - setTitle(new Label(new ConfirmPagePrintListener())); - } - - private class ConfirmFormPrintListener implements PrintListener { - private RequestLocal m_RL; - - ConfirmFormPrintListener(RequestLocal ConfirmMsgRL) { - m_RL = ConfirmMsgRL; - } - - public void prepare(PrintEvent e) { - Label label = (Label) e.getTarget(); - PageState ps = e.getPageState(); - - label.setLabel((String)m_RL.get(ps) ); - } - } - - private class ConfirmForm extends Form implements FormInitListener, FormProcessListener { - private Label m_ConfirmMsgLabel; - private Submit m_OkButton; - private Submit m_CancelButton; - - private RequestLocal m_OkRL; - private RequestLocal m_CancelRL; - - private String m_sOkUrl = null; - private String m_sCancelUrl = null; - - public ConfirmForm(RequestLocal ConfirmMsgRL, RequestLocal OkUrlRL, RequestLocal CancelUrlRL) { - super("ConfirmForm"); - m_ConfirmMsgLabel = new Label(new ConfirmFormPrintListener(ConfirmMsgRL)); - - this.add(m_ConfirmMsgLabel); - - m_OkButton = new Submit("OK"); - m_OkButton.setButtonLabel("OK"); - this.add(m_OkButton); - m_OkRL = OkUrlRL; - - m_CancelButton = new Submit("Cancel"); - m_CancelButton.setButtonLabel("Cancel"); - this.add(m_CancelButton); - m_CancelRL = CancelUrlRL; - - this.addInitListener(this); - this.addProcessListener(this); - } - - public void init(FormSectionEvent e) { - PageState ps = e.getPageState(); - - //initialize the OK and Cancel URL's - m_sOkUrl = (String) m_OkRL.get(ps); - m_sCancelUrl = (String) m_CancelRL.get(ps); - } - - public void process(FormSectionEvent e) { - PageState ps = e.getPageState(); - - if (m_OkButton.isSelected(ps)) { - throw new RedirectSignal(m_sOkUrl, true); - } else { - throw new RedirectSignal(m_sCancelUrl, false); - } - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Container.java b/ccm-core/src/main/java/com/arsdigita/bebop/Container.java deleted file mode 100755 index 4b81b5cdb..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Container.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - - -/** - * The common interface that is implemented by all Bebop containers. - * - * The Container interface extends the Component interface. A container is - * simply a component that contains other components. - * - * @author David Lutterkort - * @author Uday Mathur - * @version $Id: Container.java 287 2005-02-22 00:29:02Z sskracic $ - * */ -public interface Container extends Component { - - /** - * Adds a component to this container. - * - * @param pc component to add to this container - * @pre pc != null - */ - void add(Component pc); - - /** - * Adds a component with the specified layout constraints to this - * container. Layout constraints are defined in each layout container as - * static ints. To specify multiple constraints, uses bitwise OR. - * - * @param pc component to add to this container - * - * @param constraints layout constraints (a - * bitwise OR of static ints in the particular layout) - * - * @pre c != null - */ - void add(Component c, int constraints); - - /** - * Returns true if this list contains the specified element. - * More formally, returns true if and only if this list - * contains at least - * one element e such that (o==null ? e==null : o.equals(e)). - *

- * This method returns true only if the object has been - * directly added to this container. If this container contains another - * container that contains this object, this method returns - * false. - * - * @param o element whose presence in this container is to be tested - * - * @return true if this container contains the specified - * object directly; false otherwise. - * @pre o != null - */ - boolean contains(Object o); - - /** - * Gets the component - * at the specified position. Each call to the add method increments - * the index. Since the user has no control over the index of added - * components (other than counting each call to the add method), - * this method should be used in conjunction with indexOf. - * - * @param index the index of the item to be retrieved from this - * container - * - * @return the component at the specified position in this container. - * - * @pre index >= 0 && index < size() - * @post return != null */ - Component get(int index); - - /** - * - * - * @param pc component to search for - * - * @return the index in this list of the first occurrence of - * the specified element, or -1 if this list does not contain this - * element. - * - * @pre pc != null - * @post contains(pc) implies (return >= 0 && return < size()) - * @post ! contains(pc) implies return == -1 - */ - int indexOf(Component pc); - - /** - * Returns true if the container contains no components. - * - * @return true if this container contains no components; - * false otherwise. - * @post return == ( size() == 0 ) - */ - boolean isEmpty(); - - /** - * Returns the number of elements in this container. This does not - * recursively count components that are indirectly contained in this container. - * - * @return the number of components directly in this container. - * @post size() >= 0 - */ - int size(); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ControlLink.java b/ccm-core/src/main/java/com/arsdigita/bebop/ControlLink.java deleted file mode 100755 index df578523a..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ControlLink.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import java.io.IOException; -import java.util.ArrayList; - -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -/** - * A link back to the page in which it is contained. The control link captures - * and preserves the current state of the page, and possibly any control events - * that have been set. It is most useful inside a {@link - * com.arsdigita.bebop.list.ListCellRenderer} or a {@link - * com.arsdigita.bebop.table.TableCellRenderer}, where the list or table has - * already set up the events 'tight' for the control link to do the right thing. - * - *

- * Warning: Even though a control link lets you add action listeners, - * they are not run unless you override {@link #setControlEvent - * setControlEvent}. If you need this behavior, you should use an {@link - * ActionLink}. A control link is hardly ever useful unless it is contained in - * an event-generating component like {@link List} or {@link Table}. - * - *

- * Example: A control link is mainly useful to send events to other - * components. For example, the following control link will cause a control - * event delete with associated value 42 to be sent to the - * component fooComponent when the user clicks on it: - * - *

- *    ControlLink l = new ControlLink("click here") {
- *      public void setControlEvent(PageState s) {
- *        s.setControlEvent(fooComponent, "delete", 42);
- *      }
- *    };
- * 
- * - *

- * This requires that fooComponent is part of the page hierarchy. The - * control link l does not have to be part of the page hierarchy, and - * may be generated on the fly. (See {@link PageState} for details on control - * events.) - * - *

- * See {@link BaseLink} for a description of all Bebop Link classes. - * - * @author Stanislav Freidin - * @author David Lutterkort - * @version $Id: ControlLink.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class ControlLink extends BaseLink { - - /** - * The XML type attribute for a {@link ControlLink}. - */ - protected final String TYPE_CONTROL = "control"; - - /** - * A list of all action listeners. The list is instantiated lazily, and will - * therefore be null in most applications. - */ - private ArrayList m_actionListeners; - - /** - * Constructs a new ControlLink. The link will encapsulates the child - * component (which should be a label or an image). - * - * @param child the component that will be turned into a link - */ - public ControlLink(Component child) { - super(child, ""); - setTypeAttr(TYPE_CONTROL); - } - - /** - * Constructs a new ControlLink with the given string label. - * - * @param label the string label for the link - */ - public ControlLink(String label) { - this(new Label(label)); - } - - /** - * Adds an ActionListener, which will be run when - * {@link#respond respond} is called. - * - * @param listener The listener to add. - * - * @see #respond respond - */ - public void addActionListener(ActionListener listener) { - Assert.isUnlocked(this); - if (m_actionListeners == null) { - m_actionListeners = new ArrayList(); - } - m_actionListeners.add(listener); - } - - /** - * Removes a previously added ActionListener. - * - * @param listener The listener to remove. - * - * @see #addActionListener addActionListener - */ - public void removeActionListener(ActionListener listener) { - Assert.isUnlocked(this); - if (m_actionListeners == null) { - return; - } - m_actionListeners.remove(listener); - } - - /** - * Fires an ActionEvent, which causes all registered - * ActionListeners to be run. The source of the event is the - * TabbedPane. - * - * @param state the current page state - * - * @see #respond respond - */ - protected void fireActionEvent(PageState state) { - ActionEvent e = null; - if (m_actionListeners == null) { - return; - } - for (int i = 0; i < m_actionListeners.size(); i++) { - if (e == null) { - e = new ActionEvent(this, state); - } - ((ActionListener) m_actionListeners.get(i)).actionPerformed(e); - } - } - - /** - * Responds to the incoming request. Fires the ActionEvent. - * - * @param state the current page state - */ - @Override - public void respond(PageState state) { - fireActionEvent(state); - } - - /** - * Generates the URL for a link and sets it as the "href" attribute of the - * parent. - * - * @param state the current page state - * @param parent the parent element - */ - @Override - protected void generateURL(PageState state, Element parent) { - setControlEvent(state); - try { - parent.addAttribute("href", state.stateAsURL()); - } catch (IOException e) { - parent.addAttribute("href", ""); - } - exportAttributes(parent); - state.clearControlEvent(); - } - - /** - * Sets the page state's control event. Should be overridden by child - * classes. By default, the link receives no control events whatsoever. - * - * @param ps the current page state - */ - // FIXME: Why is this not protected ? - public void setControlEvent(PageState ps) { - return; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/DefaultSingleSelectionModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/DefaultSingleSelectionModel.java deleted file mode 100755 index 1cb0529d1..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/DefaultSingleSelectionModel.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.parameters.ParameterModel; - -/** - * @see SingleSelectionModel - * - * @author Jens Pelzetter - * @author unknown - */ -public class DefaultSingleSelectionModel - extends AbstractSingleSelectionModel { - - private final RequestLocal m_key; - - public DefaultSingleSelectionModel() { - super(); - m_key = new RequestLocal(); - } - - @Override - @SuppressWarnings("unchecked") - public T getSelectedKey(final PageState state) { - return (T) m_key.get(state); - } - - @Override - public ParameterModel getStateParameter() { - return null; - } - - @Override - public void setSelectedKey(final PageState state, final T key) { - if (key == null) { - if (getSelectedKey(state) != null) { - m_key.set(state, null); - fireStateChanged(state); - } - } else if (!key.equals(getSelectedKey(state))) { - m_key.set(state, key); - fireStateChanged(state); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/DescriptiveComponent.java b/ccm-core/src/main/java/com/arsdigita/bebop/DescriptiveComponent.java deleted file mode 100755 index 6e9ff74eb..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/DescriptiveComponent.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.xml.Element; - - - -/** - * A (Simple) Component with various descriptive information, specifically 'hints' - * with explanations about it's proper usage. These hints provide a kind of - * online manual. - * - * @author Peter Boy (pb@zes.uni-bremen.de) - * @version $Id: TextStylable.java 287 2005-02-22 00:29:02Z sskracic $ - */ -abstract public class DescriptiveComponent extends SimpleComponent { - - /** Property to store informational text for the user about the Link, e.g. - * how to use it, or when to use it (or not to use it). */ - private GlobalizedMessage m_hint; //= GlobalizationUtil.globalize("bebop.hint.no_entry_yet"); - - /** Property to store a (localized) label (or title) of this widget. A - * label is the text (name) displayed for the user to identify and - * distinguish the various elements on the screem. */ - private GlobalizedMessage m_label; - - /** - * Sets a popup hint for the component. It usually contains some explanation - * for the user about the component, how to use, why it is there, etc. - * - * @param hint GlobalizedMessage object with the information text. - */ - public void setHint(GlobalizedMessage hint) { - m_hint = hint; - } - - /** - * Retrieve the popup hint for the component. It is specifically meant for - * client classes which have to generate the xml on their own and can not - * use the generateDescriptionXML method provided. - * - * @return popup hint message for the component - */ - public GlobalizedMessage getHint() { - return m_hint; - } - - /** - * Sets a popup hint for the Link. It usually contains some explanation for - * the user about the link, how to use, why it is there, etc. - * - * @param label GlobalizedMessage object with the text to identify and - * distinguish the component. - */ - public void setLabel(GlobalizedMessage label) { - m_label = label; - } - - /** - * Retrieve the label for the component. It is specifically meant for - * client classes which have to generate the XML on their own and can not - * use the generateDescriptionXML method provided. - * - * @return popup hint message for the component - */ - public GlobalizedMessage getLabel() { - return m_label; - } - - /** - * Generates a (J)DOM fragment for clients to include into their generated - * XML. - * - * @param state The current page state. - * @param parent the XML Element instance to add the attributes managed by - * by this class - */ - protected void generateDescriptionXML(final PageState state, - final Element parent) { - - if (m_label != null) { - parent.addAttribute("label", (String) m_label.localize()); - } - if (m_hint != null) { - parent.addAttribute("hint", (String) m_hint.localize()); - } - // Do we need this? - //exportAttributes(parent); - } - - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/DimensionalNavbar.java b/ccm-core/src/main/java/com/arsdigita/bebop/DimensionalNavbar.java deleted file mode 100644 index 2b601f41a..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/DimensionalNavbar.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.xml.Element; - -import java.util.Iterator; - - -/** - * Delimited dimensional navbar. - * - * @author Michael Pih - * @version $Revision$ $Date$ - * @version $Id$ - */ -public class DimensionalNavbar extends SimpleContainer { - - private final static String BEBOP_XML_NS = "http://www.arsdigita.com/bebop/1.0"; - - public final static String LEFT = "left"; - public final static String RIGHT = "right"; - public final static String CENTER = "center"; - - private String m_startTag; - private String m_endTag; - private String m_delimiter; - private String m_align; - - public DimensionalNavbar() { - super(); - setAlign(RIGHT); - } - - public void setStartTag(String s) { - m_startTag = s; - } - - public void setEndTag(String s) { - m_endTag = s; - } - - public void setDelimiter(String s) { - m_delimiter = s; - } - - public void setAlign(String s) { - if ( s.equals(LEFT) || s.equals(RIGHT) || s.equals(CENTER) ) { - m_align = s; - } else { - throw new IllegalArgumentException - ("Align must be DimensionalNavbar.RIGHT, " + - "DimensionalNavbar.LEFT, or DimensionalNavbar.CENTER"); - } - } - - - public void generateXML(PageState state, Element parent) { - - Element navbar = parent.newChildElement("bebop:dimensionalNavbar", - BEBOP_XML_NS); - navbar.addAttribute("startTag", m_startTag); - navbar.addAttribute("endTag", m_endTag); - navbar.addAttribute("delimiter", m_delimiter); - navbar.addAttribute("align", m_align); - exportAttributes(navbar); - - Iterator children = children(); - Component child; - while ( children.hasNext() ) { - child = (Component) children.next(); - - child.generateXML(state, navbar); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ElementComponent.java b/ccm-core/src/main/java/com/arsdigita/bebop/ElementComponent.java deleted file mode 100644 index ac438f6b4..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ElementComponent.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.xml.Element; - -/** - * A component that gets its text entirely from a single XSL element. - * - * @author Sameer Ajmani - * @version $Id$ - **/ -public class ElementComponent extends SimpleComponent { - - private String m_name; - private String m_uri; - - /** - * Constructs an ElementComponent that uses the element with the given - * name under the given XSL namespace URI. - * - * @param name the name of the element to use - * @param uri the URI of the XSL namespace - **/ - public ElementComponent(String name, String uri) { - m_name = name; - m_uri = uri; - } - - /** - * Constructs a new element with the name and namespace given in this - * component's constructor, and adds the element to the parent element. - * @param state the current page state - * @param parent the parent element for this new element - **/ - public void generateXML(PageState state, Element parent) { - parent.newChildElement(m_name, m_uri); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Embedded.java b/ccm-core/src/main/java/com/arsdigita/bebop/Embedded.java deleted file mode 100644 index 83b6eaee6..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Embedded.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (C) 2014 Peter Boy, University of Bremen. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ - -package com.arsdigita.bebop; - -import static com.arsdigita.bebop.Component.BEBOP_XML_NS; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.xml.Element; - -/** - * Injects arbitrary content as a String into the xml output. It is not for - * any semantic type of data und it is not localizable. Specifically it is - * meant for data as Javascript and alike. - * - * It generates some fixed string to be included in the XML output. - * - * It resembles the Label methods for String parameters and currently - * generates the same XML attributes in order to avoid any need to modify the - * themes. - * - * @author pb - */ -public class Embedded extends SimpleComponent { - - private final String m_content; - /** The setting for output escaping affects how markup in the - * content is handled. - *

  • If output escaping is in effect (true), <b>example</b> - * will appear literally.
  • - *
  • If output escaping is disabled, <b>example</b> appears as the - * String "example" in bold (i.e. retaining the markup.
- * Default is false. */ - private boolean m_escaping = false; // default for a primitive - private PrintListener m_printListener; - - /** - * Default constructor creates a new Embedded with the empty - * content. - * - * @param content - */ - public Embedded() { - m_content = ""; - } - - /** - * Constructor creates a new Embedded with the specified - * (fixed) content. - * - * @param content - */ - public Embedded(String content) { - m_content = content; - } - - /** - * Constructor creates a new Embedded with the specified - * content and output escaping turned on if escaping is - * true. - * - * The setting for output escaping affects how markup in the - * content is handled. For example:
  • If output escaping - * is in effect, <b>content</b> will appear literally.
  • If - * output escaping is disabled, <b>content</b> appears as the String - * "context" in bold.
- * - * @param content the content to inject into the output. - * @param escaping true if output escaping will be in effect; - * false if output escaping will be disabled - */ - public Embedded(String content, boolean escaping) { - m_content = content; - m_escaping = escaping; - } - - /** - * Generates the (J)DOM fragment for a embedded. - *

-     * <bebop:link href="..." type="..." %bebopAttr;/>
-     * 
- * - * @param state The current {@link PageState}. - * @param parent The XML element to attach the XML to. - */ - @Override - public void generateXML(PageState state, Element parent) { - - if (!isVisible(state)) { - return; - } - - Embedded target = firePrintEvent(state); - - Element content = parent.newChildElement("bebop:label", BEBOP_XML_NS); - target.exportAttributes(content); - - if (!target.m_escaping) { - content.addAttribute("escape", "yes"); - } else { - content.addAttribute("escape", "no"); - } - - content.setText(m_content); - } - - /** - * - * @param state - * @return - */ - protected Embedded firePrintEvent(PageState state) { - Embedded e = this; - - if (m_printListener != null) { - try { - e = (Embedded) this.clone(); - m_printListener.prepare(new PrintEvent(this, state, e)); - } catch (CloneNotSupportedException nse) { - throw new RuntimeException( - "Couldn't clone Embedded for PrintListener. " - + "This probably indicates a serious programming error: " - + nse.getMessage()); - } - } - - return e; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ExternalLink.java b/ccm-core/src/main/java/com/arsdigita/bebop/ExternalLink.java deleted file mode 100644 index 627dea1d1..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ExternalLink.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.PrintListener; - -/** - * A link to an external (non-ACS) site. Does not propagate ACS-specific - * URL parameters. - * - *

See {@link BaseLink} for a description - * of all Bebop Link classes. - * - * @version $Id: ExternalLink.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class ExternalLink extends Link { - - public ExternalLink(Component child, String url) { - super(child, url); - } - - public ExternalLink(Component child, PrintListener l) { - super(child, l); - } - - public ExternalLink(String label, String url) { - super(label, url); - } - - public ExternalLink(String label, PrintListener l) { - super(label, l); - } - - public ExternalLink(PrintListener l) { - super(l); - } - /** - * Processes the URL for this link after the print listener runs. - * - * @param state the current page state - * @param url the original URL - * - * @return the original, unchanged URL. - **/ - protected String prepareURL(PageState state, String url) { - return url; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Form.java b/ccm-core/src/main/java/com/arsdigita/bebop/Form.java deleted file mode 100755 index 17ad67632..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Form.java +++ /dev/null @@ -1,560 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.form.Hidden; - -import javax.servlet.ServletException; - -import com.arsdigita.bebop.util.Traversal; -import com.arsdigita.bebop.util.BebopConstants; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.web.URL; -import com.arsdigita.web.Web; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.util.Assert; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.xml.Element; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Iterator; - -/** - * Represents the visual structure of an HTML form. Forms can be constructed with a Container - * argument to specify the type of layout this form will adhere to. The default is a column panel. - * - *

- * As an example, a form that accepts a first and last name may be set up as follows: - * - *

- * public class MyForm extends Form implements FormProcessListener {
- *
- * private Text m_firstName; private Text m_lastName;
- *
- * public MyForm() { super("myform"); add(new Label("First Name:")); m_firstName = new
- * Text("firstName"); m_firstName.setDefaultValue("John"); add(m_firstName);
- *
- * add(new Label("Last Name:")); m_lastName = new Text("lastName");
- * m_lastName.setDefaultValue("Doe"); m_lastName.addValidationListener(new NotNullValidationListener
- * ("The last name")); add(m_lastName);
- *
- * add(new Submit("save", "Save")); addProcessListener(this); }
- *
- * public void process(FormSectionEvent e) { PageState s = e.getPageState();
- *
- * System.out.println("You are " + m_firstName.getValue(s) + " " + m_lastName.getValue(s)); } }
- * 
- * - *

- * This form automatically checks that the user supplied a last name. Only then does it call the - * process method, which prints the user-supplied values. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Stas Freidin - * @author Rory Solomon - * @author David Lutterkort - * - */ -public class Form extends FormSection implements BebopConstants { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by editing - * /WEB-INF/conf/log4j.properties int hte runtime environment and set - * com.arsdigita.bebop.Form=DEBUG by uncommenting or adding the line. - */ - private static final Logger LOGGER = LogManager.getLogger(Form.class); - - /** - * Constant for specifying a get submission method for this form. See the W3C HTML specification for - * a description of what this attribute does. - */ - public final static String GET = "get"; - - /** - * Constant for specifying a post submission method for this form. See the W3C HTML specification for - * a description of what this attribute does. - */ - public final static String POST = "post"; - - /** - * The name of the name attribute for the form. - */ - private final static String NAME = "name"; - - /** - * The name of the method attribute for the form. - */ - private final static String METHOD = "method"; - - private String m_action; - private boolean m_processInvisible; - - /** - * Hold the FormData for one request. - */ - private RequestLocal m_formData; - - /** - * Determines whether or not a form is 'redirecting', meaning that it will clear the control - * event and redirect to the resulting state after form processing, so that a page reload won't - * cause the form to be resubmitted. - */ - private boolean m_isRedirecting = false; - - /** - * Constructs a new form with the specified name. At the time of creation, instantiates a new - * form model for the form and instantiates a default ColumnPanel to contain the components. - * - * @param name the name of the form - */ - public Form(String name) { - this(name, new GridPanel(2)); - } - - /** - * Constructs a new form with the specified name and container. At the time of creation, - * instantiates a new form model for the form and replaces the default ColumnPanel with the - * specified container as the implicit container of the components. - * - * @param name the name attribute of the form - * @param panel the implicit container that will hold the components - */ - public Form(String name, Container panel) { - super(panel, new FormModel(name)); - initFormData(); - setName(name); - setProcessInvisible(false); - addMagicTag(); - } - - /** - * Writes the output to a DOM to be used with the XSLT template to produce the appropriate - * output. If the form is not visible, no output is generated. - * - *

- * Generates a DOM fragment: - *

- *

-     * <bebop:form action=%url; %bebopAttr;>
-     *   .. XML for panel ..
-     *   .. XML for page state ..
-     * </bebop:form>
-     * 
- * - * @param s the page state used to determine the values of form widgets and page state - * attributes - * @param parent the XML element to which the form adds its XML representation - * - * @see PageState#generateXML - */ - @Override - public void generateXML(PageState s, Element parent) { - if (isVisible(s)) { - Element form = generateXMLSansState(s, parent); - - s.setControlEvent(this); - s.generateXML(form, getModel().getParametersToExclude()); - s.clearControlEvent(); - } - } - - /** - * Generates the XML representing the form and its widgets, but not the state information from - * s. - * - * @param s represents the curent request - * @param parent - * - * @return the top-level element for the form - */ - protected Element generateXMLSansState(PageState s, Element parent) { - Element form = parent.newChildElement("bebop:form", BEBOP_XML_NS); - - // Encode the URL with the servlet session information; - // do not use DispatcherHelper.encodeURL because the - // ACS global parameters are provided via the FormData. - String url = null; - - if (m_action == null) { - final URL requestURL = Web.getWebContext().getRequestURL(); - - if (requestURL == null) { - url = s.getRequest().getRequestURI(); - } else { - url = requestURL.getRequestURI(); - } - } else { - url = m_action; - } - - form.addAttribute("action", s.getResponse().encodeURL(url)); - - exportAttributes(form); - - m_panel.generateXML(s, form); - - generateErrors(s, form); - - return form; - } - - /** - * - * @param ps - * @param parent - */ - protected void generateErrors(PageState ps, Element parent) { - - for (Iterator it = getFormData(ps).getErrors(); it.hasNext();) { - Element errors = parent.newChildElement(BEBOP_FORMERRORS, - BEBOP_XML_NS); - Object msg = it.next(); - - if (msg == null) { - errors.addAttribute("message", "Unknown error"); - } else { - errors.addAttribute("message", - (String) ((GlobalizedMessage) msg).localize(ps.getRequest())); - } - errors.addAttribute("id", getName()); - } - - } - - /** - *

- * Determine whether or not this Form will redirect after its process listeners are fired.

- * - * @return - */ - public boolean isRedirecting() { - return m_isRedirecting; - } - - /** - * Setting the redirecting flag will cause the Form to clear the control event and redirect back - * to the current URL, after firing all process listeners. Doing so means that a user reload - * will not cause the form to be resubmitted. The default value for this flag is false. - * - * @param isRedirecting - */ - public void setRedirecting(boolean isRedirecting) { - Assert.isUnlocked(this); - m_isRedirecting = isRedirecting; - } - - /** - * Responds to the request by processing this form with the HTTP request given in - * state. - * - * @see #process process(...) - * - * @param state represents the current request - * - * @throws javax.servlet.ServletException - */ - @Override - public void respond(PageState state) throws ServletException { - final FormData data = process(state); - - if (m_isRedirecting && data.isValid()) { - state.clearControlEvent(); - - throw new RedirectSignal(state.toURL(), true); - } - } - - // * * * * * * * * * * * * * * * * * * * * * * * * * * * * - // Methods to set the HTML attributes of the FORM element - // * * * * * * * * * * * * * * * * * * * * * * * * * * * * - /** - * Sets the name attribute for the form. - * - * @param name the name for the form - * - * @pre ! isLocked() - */ - public void setName(String name) { - Assert.isUnlocked(this); - setAttribute(NAME, name); - } - - /** - * Gets the name attribute for this form. - * - * @return the name for this form. - */ - public String getName() { - return (String) getAttribute(NAME); - } - - /** - * Sets the enctype attribute used in the form element. No encoding - * type is specified by default. - * - * @param encType the encoding type - * - * @pre ! isLocked() - */ - public void setEncType(String encType) { - Assert.isUnlocked(this); - setAttribute("enctype", encType); - } - - /** - * Sets the onSubmit attribute used in the form element. No onsubmit - * handler is specified by default. - * - * @param javascriptCode the javascript code associated with this attribute - * - * @pre ! isLocked() - */ - public void setOnSubmit(String javascriptCode) { - Assert.isUnlocked(this); - setAttribute("onSubmit", javascriptCode); - } - - /** - * Sets the ONRESET attribute used in the FORM element. No onreset - * handler is specified by default. - * - * @param javascriptCode the javascript code associated with this attribute - * - * @pre ! isLocked() - */ - public void setOnReset(String javascriptCode) { - Assert.isUnlocked(this); - setAttribute("onReset", javascriptCode); - } - - /** - * Sets the HTTP method used to submit the form. - * - * @param method either GET or POST - * - * @pre ! isLocked() - */ - public void setMethod(String method) { - Assert.isUnlocked(this); - setAttribute(METHOD, method); - } - - private String getMethod() { - return getAttribute(METHOD); - } - - /** - * Returns true if form processing is turned on when the form is invisible. - * - * @return true if the form listeners should be processed even when the form is not visible on - * the page, false otherwise - */ - protected boolean getProcessInvisible() { - return m_processInvisible; - } - - /** - * Turns form processing on/off when the form is invisible. - * - * @param processInvisible true if the form listeners should be processed even when the form is - * not visible on the page - */ - protected void setProcessInvisible(boolean processInvisible) { - m_processInvisible = processInvisible; - } - - /** - * Sets the URL for the form's action attribute. This is the URL to which - * submissions will be sent when the user clicks a submit button on the form. By default, the - * action is null, instructing the form to set the action to the URL of the page in - * which it is used. If the action is set to a different URL, none of the listeners registered - * with this form will be run. - * - * @param action the URL to submit this form to - * - * @pre ! isLocked() - */ - public void setAction(String action) { - Assert.isUnlocked(this); - m_action = action; - } - - /** - * Returns the URL for the form's action attribute. - * - * @return the URL to which to submit this form. - * - * @see #setAction setAction - */ - public final String getAction() { - return m_action; - } - - /** - * Processes this form, creating a FormData object. Runs the right set of init, - * validation, and process listeners, depending on whether this is an initial request to the - * form and whether the form submission was valid. Submission listeners are always run. - * - * @see #getFormData - * - * @param state represents the current request - * - * @return the values extracted from the HTTP request contained in state. - * - * @throws com.arsdigita.bebop.FormProcessException - * @pre state != null - * @post return != null - */ - @Override - public FormData process(PageState state) throws FormProcessException { - Assert.exists(state, "PageState"); - FormData result = new FormData(getModel(), state.getRequest()); - setFormData(state, result); - - // Unless invisible form processing is turned on, don't run any - // listeners if this form is not visible. -// if (getProcessInvisible() || state.isVisibleOnPage(this)) { - getModel().process(state, result); -// } - return result; - } - - /** - * Returns the form data constructed by the {@link #process - * process} method for the request described by state. Processes the form if it has - * not already been processed. - * - * @param state describes the current request - * - * @return the values extracted from the HTTP request contained in state, or - * null if the form has not been processed yet. - * - * @pre state != null - * @post return != null - */ - public FormData getFormData(PageState state) { - return (FormData) m_formData.get(state); - } - - /** - * Adds a Hidden Tag to this form so that our controller can determine if this is an initial - * request. - */ - protected void addMagicTag() { - Hidden h = new Hidden(getModel().getMagicTagName()); - h.setDefaultValue("visited"); - add(h); - } - - /** - * Traverses the components contained in this form, collecting parameterModels and Listeners - * into this form's FormModel. - */ - protected void traverse() { - Traversal formRegistrar = new Traversal() { - - @Override - protected void act(Component c) { - if (c == Form.this) { - return; - } - if (c instanceof Form) { - throw new IllegalStateException("Forms cannot contain other Forms"); - } - c.register(Form.this, getModel()); - } - - }; - formRegistrar.preorder(this); - } - - /** - * Adds this form to the page and traverses the components contained in this form, collecting - * parameterModels and Listeners into this form's FormModel. - * - * @param p page in which to register this form - */ - @Override - public void register(Page p) { - traverse(); - p.addComponent(this); - } - - /** - * TODO - * - * @param model - */ - public void excludeParameterFromExport(ParameterModel model) { - getModel().excludeFormParameterFromExport(model); - } - - /** - * Initialize m_formData so that accessing the per-request form data forces the - * form to be processed on the first access and caches the form data for subsequent requests. - */ - private void initFormData() { - m_formData = new RequestLocal() { - - @Override - protected Object initialValue(PageState s) { - // TODO: We need to come up with the right strategy for - // how we deal with FormProcessExceptions. Are they fatal - // ? Do we just add them to the form validation errors ? - try { - return process(s); - } catch (FormProcessException e) { - LOGGER.error("Form Process exception", e); - throw new UncheckedWrapperException("Form Process error: " - + e.getMessage(), e); - } - } - - }; - } - - /** - * Converts to a String. - * - * @return a human-readable representation of this. - */ - @Override - public String toString() { - return super.toString() + " " + "[" + getName() + "," + getAction() + "," + getMethod() - + "," + isRedirecting() + "]"; - } - - /** - * Protected access to set the formdata request local. This method is required if a subclass - * wishes to override the process method. - * - * @param state - * @param data - */ - protected void setFormData(PageState state, FormData data) { - m_formData.set(state, data); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/FormData.java b/ccm-core/src/main/java/com/arsdigita/bebop/FormData.java deleted file mode 100755 index 0a1ccc694..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/FormData.java +++ /dev/null @@ -1,832 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import javax.servlet.http.HttpServletRequest; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Locale; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.util.Assert; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.URLRewriter; - -/** - * Manages the data associated with forms and other remote sources. - - *

The basic task of a FormData object is to transform - * a set of key-value string pairs into a validated set of Java data - * objects for use in subsequent processing. In most cases the original - * data is an HTTP request. - - *

To perform the transformation, a separate instance of - * FormModel is used to specify the name and basic data - * type of each expected parameter in the set, as well as any - * additional validation steps required. The FormData - * stores both the transformed data objects and any validation - * error messages associated with an individual parameter or the - * form as a whole. Once the data has been validated, individual data - * objects may be queried from a FormData using the - * standard get method of the Map interface. - * - *

FormData objects may also be used to control the - * entire lifecycle of self-validating forms, which report errors to - * the user in the context of the form itself, rather than on a - * separate page. - * - *

See the Forms API Developer Guide for details on using the - * FormData class. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Stas Freidin - * @version $Id: FormData.java 287 2005-02-22 00:29:02Z sskracic $ */ - -public class FormData implements Map, Cloneable { - - - private HashMap m_parameterDataValues = new HashMap(); - private LinkedList m_formErrors; - private FormModel m_model; - - private Locale m_locale; - private boolean m_isTransformed; - private boolean m_isValid; - - private boolean m_isSubmission; - - /** - * Ensure that no one can create this object from outside the package - * without supplying meaningful parameters - */ - private FormData() {} - - /** - * Constructs a new FormData object containing the - * transformed and validated query parameters from an HTTP request. - * - * @param model a FormModel describing the parameters - * and validation constraints for this request - * - * @param request an HTTP request object passed from the servlet - * container - * - * @pre model != null - * @pre request != null - * - * @throws FormProcessException if an error occurs. - */ - - public FormData(FormModel model, HttpServletRequest request) - throws FormProcessException { - - this(model, request, Locale.getDefault()); - } - - /** - * Constructs a new FormData object containing the - * transformed and validated query parameters from an HTTP request. - * - * @param model a FormModel describing the parameters - * and validation constraints for this request - * - * @param request an HTTP request object passed from the servlet - * container - * - * @param isSubmission true if the request should be treated - * as a form submission by the user - * - * @pre model != null - * @pre request != null - * - * @throws FormProcessException if an error occurs. - */ - public FormData(FormModel model, HttpServletRequest request, - boolean isSubmission) - throws FormProcessException { - - this(model, request, Locale.getDefault(), isSubmission); - } - - /** - * Constructs a new FormData object containing the - * transformed and validated query parameters from an HTTP request. - * - * @param model a FormModel describing the parameters - * and validation constraints for this request - * - * @param request an HTTP request object passed from the servlet - * container - * - * @param isSubmission true if the request should be treated - * as a form submission by the user - * - * @param fallback a fallback FormData object. If a value for - * a parameter in the form model model is not in - * the current request parameters, the fallback object is - * searched. - * - * @pre model != null - * @pre request != null - * - * @throws FormProcessException if an error occurs - */ - public FormData(FormModel model, HttpServletRequest request, - boolean isSubmission, FormData fallback) - throws FormProcessException { - - this(model, request, Locale.getDefault(), isSubmission, fallback); - } - - /** - * Constructs a new FormData object containing the - * transformed and validated query parameters from an HTTP request. - * Error messages are provided in the specified locale. - * - * @param model A FormModel describing the parameters - * and validation constraints for this request. - * - * @param request An HTTP request object passed from the servlet - * container. - * - * @param locale The locale for which all error messages will be - * prepared. This may be used in a multilingual environment to - * tailor the output to the preferences or geographic location of - * individual users on a per-request basis. - * - * @pre model != null - * @pre request != null - * @pre locale != null - * - * @throws FormProcessException if an error occurs - */ - public FormData(FormModel model, HttpServletRequest request, Locale locale) - throws FormProcessException { - this(model, request, locale, - request.getParameter(model.getMagicTagName()) != null); - } - - /** - * Constructs a new FormData object containing the - * transformed and validated query parameters from an HTTP request. - * Error messages are provided in the specified locale. - * - * @param model A FormModel describing the parameters - * and validation constraints for this request. - * - * @param request An HTTP request object passed from the servlet - * container. - * - * @param locale The locale for which all error messages will be - * prepared. This may be used in a multilingual environment to - * tailor the output to the preferences or geographic location of - * individual users on a per-request basis. - * - * @param isSubmission true if the request should be treated - * as a form submission by the user. - * - * @throws FormProcessException if an error occurs - * @pre model != null - * @pre request != null - * @pre locale != null - */ - public FormData(FormModel model, HttpServletRequest request, - Locale locale, boolean isSubmission) - throws FormProcessException { - this(model, request, locale, isSubmission, null); - } - - - /** - * Constructs a new FormData object containing the - * transformed and validated query parameters from an HTTP request. - * Error messages are provided in the specified locale. - * - * @param model A FormModel describing the parameters - * and validation constraints for this request. - * - * @param request An HTTP request object passed from the servlet - * container. - * - * @param locale The locale for which all error messages will be - * prepared. This may be used in a multilingual environment to - * tailor the output to the preferences or geographic location of - * individual users on a per-request basis. - * - * @param isSubmission true if the request should be treated - * as a form submission by the user. - * - * @param fallback a fallback FormData object. If a value for - * a parameter in the form model model is not in - * the current request parameters, the fallback object is - * searched. - * - * @throws FormProcessException if an error occurs - * @pre model != null - * @pre request != null - * @pre locale != null - */ - public FormData(FormModel model, HttpServletRequest request, - Locale locale, boolean isSubmission, - FormData fallback) - throws FormProcessException { - - Assert.exists(model, "FormModel"); - Assert.exists(request, "HttpServletRequest"); - Assert.exists(locale, "Locale"); - - m_locale = locale; - m_model = model; - m_isTransformed = false; - - m_isSubmission = isSubmission; - m_isValid = m_isSubmission; - - createParameterData(request, fallback); - - Iterator params = URLRewriter.getGlobalParams(request).iterator(); - while (params.hasNext()) { - ParameterData param = (ParameterData)params.next(); - setParameter(param.getModel().getName(), param); - } - } - - /** - * Validates this FormData object according to its form model. - * If the FormData is already valid, does nothing. - * - * @param state describes the current page state - * @pre state != null - */ - public void validate(PageState state) { - - if (isValid()) { - return; - } - - m_isValid = true; - - if (m_formErrors != null) { - m_formErrors.clear(); - } - - m_model.validate(state, this); - } - - /** - * Validates this FormData object against its form model, - * regardless of whether the object is currently valid. - * - * @param state describes the current page state - * @pre state != null - */ - public void forceValidate(PageState state) { - invalidate(); - validate(state); - } - - /** - * Reports a validation error on the form as a whole. - * - * @param message a String of the error message - * @pre message != null - * @deprecated refactor and use addError(GlobalizedMessage) instead - */ - public void addError(String message) { - addError(new GlobalizedMessage(message)); - } - - /** - * Reports a validation error on the form as a whole. - * Uses a GlobalizedMessage for inklusion - * - * @param message the error message - * @pre message != null - */ - public void addError(GlobalizedMessage message) { - - if (m_formErrors == null) { - m_formErrors = new LinkedList(); - } - - m_formErrors.add(message); - m_isValid = false; - } - - /** - * Adds an error message to the ParameterData object associated with - * the parameter model identified by name. - * - * @param name the name of the parameter model to whose - * ParameterData the error message will be added - * - * @param message the text of the error message to add - * - * @pre name != null - * @pre message != null - * @deprecated use addError(String name, GlobalizedMessage message) instead - */ - public void addError(String name, String message) { - - ParameterData parameter; - - if (!m_parameterDataValues.containsKey(name)) { - throw new IllegalArgumentException - ("Attempt to set Error in Non-Existant ParameterData"); - } - - parameter = (ParameterData) m_parameterDataValues.get(name); - parameter.addError(message); - m_isValid = false; - } - - - /** - * Adds an error message to the ParameterData object associated with - * the parameter model identified by name. - * - * @param name the name of the parameter model to whose - * ParameterData the error message will be added - * - * @param message the text of the error message to add - * - * @pre name != null - * @pre message != null - */ - public void addError(String name, GlobalizedMessage message) { - - ParameterData parameter; - - if (!m_parameterDataValues.containsKey(name)) { - throw new IllegalArgumentException - ("Attempt to set Error in Non-Existant ParameterData"); - } - - parameter = (ParameterData) m_parameterDataValues.get(name); - parameter.addError(message); - m_isValid = false; - } - - /** - * Returns the errors associated with the specified parameter. - * - * @param name the name of the parameter whose errors we are interested in - * - * @return an iterator of errors. Each error is just a string for - * now. - * - * @pre name != null - * @post return != null - */ - public Iterator getErrors(String name) { - - ParameterData parameter - = (ParameterData)m_parameterDataValues.get(name); - - if (parameter == null) { - return Collections.EMPTY_LIST.iterator(); - } - - return parameter.getErrors(); - } - - /** - * Returns an iterator over all the errors on this form that are not - * associated with any particular parameter. Such errors may have - * been generated by a FormValidationListener. - * - * @return an iterator over error messages. - * @post return != null - */ - public Iterator getErrors() { - - if (m_formErrors == null) { - return Collections.EMPTY_LIST.iterator(); - } - - return m_formErrors.iterator(); - } - - /** - * Returns an iterator over all of the errors on this form. - * This includes both errors associated with particular parameters - * and errors associated with the form as a whole. - * - * @return an iterator over all error messages. - * @post return != null - */ - public Iterator getAllErrors() { - - return new Iterator() { - - private Iterator params, paramErrors, formErrors; - - { - params = m_parameterDataValues.values().iterator(); - paramErrors = Collections.EMPTY_LIST.iterator(); - formErrors = getErrors(); - } - - private void seekToNextError() { - while (! paramErrors.hasNext() && params.hasNext()) { - paramErrors - = ((ParameterData)params.next()).getErrors(); - } - } - - @Override - public boolean hasNext() { - seekToNextError(); - return paramErrors.hasNext() || formErrors.hasNext(); - } - - @Override - public Object next() throws NoSuchElementException { - - seekToNextError(); - if (paramErrors.hasNext()) { - return paramErrors.next(); - } - - // An error will be thrown if !formErrors.hasNext() - return formErrors.next(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - - /** - * Gets the specified ParameterData object. - * - * @param name the name of the parameterModel to retrieve - * @return the parameter data object specified. - * - */ - public ParameterData getParameter(String name) { - return (ParameterData)m_parameterDataValues.get(name); - } - - /** - * Sets the ParameterData object identified by the name in this FormData - * Object. - * - * @param name the name of the parameterModel - * @param value - */ - public void setParameter(String name, ParameterData value) { - m_parameterDataValues.put(name,value); - } - - /** - * Returns a collection of all the ParameterData objects. - * - * @return a collection of all the ParameterData objects. - */ - public final Collection getParameters() { - return m_parameterDataValues.values(); - } - - /** - * Determines whether this request represents a submission event. - * - * @return true if this request represents a submission event; - * false if it represents an initialization event. - */ - public final boolean isSubmission() { - return m_isSubmission; - } - - /** - * Determines whether the key-value string pairs in the - * request have been transformed into Java data objects. - * - * @return true if the key-value string pairs have been - * transformed into Java data objects; - * false otherwise. - * - */ - public final boolean isTransformed() { - return m_isTransformed; - } - - /** - * Determines whether any errors were found during validation of - * a form submission. - * @return true if no errors were found; false - * otherwise. - * - */ - public final boolean isValid() { - return m_isValid; - } - - /** - * Sets isValid to false. We do not allow programmers - * to manually toggle the isValid value to true. - * Hence this method takes no - * arguments and only sets isValid flag to false - * @deprecated Use invalidate() instead - */ - public void setInvalid() { - invalidate(); - } - - /** - * Set isValid to false. We do not allow programmers - * to manually toggle the isValid value to true. - */ - public final void invalidate() { - m_isValid = false; - } - - // --- private helper methods to initialize object --- - - /** - * Sets the value of a parameter within the associated ParameterData - * object - * - * @param name Name of the parameterModel whose ParameterData object - * we are setting - * - * @param value Value to assign the ParmeterData object - * - */ - private void setParameterValue(String name, Object value) { - ParameterData parameter = (ParameterData) m_parameterDataValues.get(name); - if (parameter != null) { - parameter.setValue(value); - } else { - throw new IllegalArgumentException("Parameter " + name + - " does not exist"); - } - } - - /** - * Iterate through parameterModels extracting values from the - * request, and transforming the value according to the parameter - * model This code incorporates - * ParameterModel.createParameterData(request) - * - * @param request the HttpServletRequest - * @param fallback a fallback FormData object. If any parameter - * in the form model does not have a value in the request, - * try to locate its value in the fallback object. - */ - private void createParameterData(HttpServletRequest request, - FormData fallback) - throws FormProcessException { - ParameterModel parameterModel; - ParameterData parameterData; - Iterator parameters = m_model.getParameters(); - - while (parameters.hasNext()) { - parameterModel = (ParameterModel) parameters.next(); - - // createParamterData automagically handles default values - // and errors in tranformation. - - Object defaultValue = null; - if (fallback != null) { - parameterData = - fallback.getParameter(parameterModel.getName()); - if (parameterData != null) { - defaultValue = parameterData.getValue(); - } - } - - // specify a default from the fallback - parameterData = - parameterModel.createParameterData(request, - defaultValue, - isSubmission()); - Assert.exists(parameterData); - setParameter(parameterModel.getName(), parameterData); - } - m_isTransformed=true; - } - - // --- Public methods to satisfy Map interface --- - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean containsKey(Object key) { - return m_parameterDataValues.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - // this is very expensive with ParameterData - throw new UnsupportedOperationException(); - } - - /* - * This is just plain wrong. Either you pretend to be a Map of - * things, or you are a Map of ParameterData-s. - */ - @Override - public Set entrySet() { - return m_parameterDataValues.entrySet(); - } - - /** - * Returns the value contained by the ParameterData object named - * by key. - * If no key is found, throws IllegalArgumentException. - * @param key the parameter data object to retrieve - * @return the value in the specified parameter data object. - * @throws java.lang.IllegalArgumentException thrown when the key - * is not a valid parameter. - */ - @Override - public Object get(Object key) throws IllegalArgumentException { - - ParameterData p = getParameter((String)key); - if (p != null) { - return p.getValue(); - } - throw new IllegalArgumentException("parameter " + key + - " not part of the form model"); - } - - /** - * @param m - * @return - * @deprecated Use get(m.getName()) instead, and then manually check - * for model identity - */ - public Object get(ParameterModel m) { - ParameterData p = getParameter(m.getName()); - - return ( p.getModel() == m ) ? p : null; - } - - - /** - * Retrieves a date object for the specified parameter name. - * @param key the object to retrieve - * @return a date object for the specified parameter name. - * - */ - public Date getDate(Object key) { - return (Date) get(key); - } - - /** - * Retrieves an integer object for the specified parameter name. - * @param key the object to retrieve - * @return an integer object for the specified parameter name. - **/ - - public Integer getInteger(Object key) { - return (Integer) get(key); - } - - /** - * Retrieves a String object for the specified parameter name. - * @param key the object to retrieve - * @return a string object for the specified parameter name. - **/ - - public String getString(Object key) { - return (String) get(key); - } - - - @Override - public boolean isEmpty() { - return m_parameterDataValues.isEmpty(); - } - - @Override - public Set keySet() { - return m_parameterDataValues.keySet(); - } - - @Override - public Object put(Object key, Object value) { - Object previousValue = get(key); - setParameterValue((String)key, value); - m_isValid = false; - return previousValue; - } - - @Override - public void putAll(Map t) { - for (Iterator i = t.keySet().iterator(); i.hasNext(); ) { - String key = (String) i.next(); - setParameterValue(key, t.get(key)); - } - m_isValid = false; - } - - /** - * - * @param key - * @return - */ - @Override - public Object remove(Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public int size() { - return m_parameterDataValues.size(); - } - - @Override - public Collection values() { - throw new UnsupportedOperationException(); - } - - /** - * - * @return - * @throws CloneNotSupportedException - */ - @Override - public Object clone() throws CloneNotSupportedException { - FormData result = (FormData) super.clone(); - result.m_parameterDataValues = new HashMap(); - for (Iterator i= m_parameterDataValues.keySet().iterator(); - i.hasNext(); ) { - Object key = i.next(); - ParameterData val = (ParameterData) m_parameterDataValues.get(key); - result.m_parameterDataValues.put(key, val.clone()); - } - if (m_formErrors != null) { - result.m_formErrors = (LinkedList) m_formErrors.clone(); - } - - return result; - } - - - @Override - public String toString() { - StringBuilder s = new StringBuilder(); - - for (Iterator i = getAllErrors(); i.hasNext();) { - s.append(i.next()).append(System.getProperty("line.separator")); - } - - return s.toString(); - } - - /** - * Converts to a String. - * The method {@link #toString()} returns all errors. - * - * @return a human-readable representation of this. - */ - public String asString() { - String newLine = System.getProperty("line.separator"); - StringBuilder to = new StringBuilder(); - to.append(super.toString() + " = {" + newLine); - //Map - to.append("m_parameterDataValues = ") - .append(m_parameterDataValues).append(",").append(newLine); - //LinkedList - to.append("m_formErrors = " + m_formErrors + "," + newLine); - //FormModel - to.append("m_model = " + m_model + "," + newLine); - to.append("m_locale = " + m_locale + "," + newLine); - to.append("m_isTransformed = " + m_isTransformed + "," + newLine); - to.append("m_isValid = " + m_isValid + "," + newLine); - to.append("m_isSubmission = " + m_isSubmission + newLine); - to.append("}"); - return to.toString(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/FormModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/FormModel.java deleted file mode 100755 index 0b63473e4..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/FormModel.java +++ /dev/null @@ -1,552 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.EventListenerList; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.util.Assert; -import com.arsdigita.util.Lockable; -import com.arsdigita.util.URLRewriter; -import com.arsdigita.web.RedirectSignal; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -/** - * A container for two classes of - * objects: ParameterModels and ValidationListeners.

- *
    - *
  • ParameterModels are associated - * with the data objects that the user submits with the form.
  • - *
  • ValidationListeners provide custom - * cross-checking of parameter values.
  • - *
- *

Instances of this class provide a specification for transforming a - * set of key-value string pairs into a set of validated Java data - * objects. - * A single instance of this - * class can handle all submissions to a particular form. - *

The most common usage for this class is - * is to use a private variable in a servlet to store the - * model, and to construct it in the servlet init method. - * That way, the model persists for the lifetime of the servlet, reducing - * the memory and processing overhead for each request. - *

See the - * Forms API Developer Guide for details on using the - * FormModel class. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Stas Freidin - * @author Rory Solomon - */ -public class FormModel implements Lockable { - - private static final Logger LOGGER = LogManager.getLogger(FormModel.class); - - private static final String MAGIC_TAG_PREFIX = "form."; - - private String m_name = null; - private List m_parameterModels = null; - private List m_parametersToExclude = null; - private boolean m_locked = false; - private boolean m_defaultOverridesNull; - - protected EventListenerList m_listenerList; - - /** - * Constructs a new form model. - * - * @param name a URL-encoded keyword used to identify this form model - * */ - public FormModel(String name) { - this(name, false); - } - - /** - * Construct a new form model. The defaultOverridesNull - * parameter is passed on to all parameter models that are added to the - * form model. If it is true, the parameter model will use - * the default value whenever it would normally set the parameter's value - * to null, for example if the parameter is missing from the request. If - * this value is false, the default parameter value will - * only be used if the request being processed is not a submission, but - * an initial request for the form model. - * - *

This method is only package-friendly since it is only useful to - * the Page class. Everybody else should be happy with the public - * constructor. - * - * @param name a URL-encoded keyword used to identify this form model - * - * @param defaultOverridesNull true if the default value for - * parameters should be used whenever the value would be - * null ordinarily. - */ - FormModel(String name, boolean defaultOverridesNull) { - Assert.exists(name, "Name"); - m_parameterModels = new LinkedList(); - m_parametersToExclude = new LinkedList(); - m_listenerList = new EventListenerList(); - m_name = name; - m_defaultOverridesNull = defaultOverridesNull; - m_parameterModels.addAll(URLRewriter.getGlobalModels()); - } - - /** - * Returns the name of this form model. - * - * @return a URL-encoded keyword used to identify requests - * conforming to this form model. - * */ - public final String getName() { - return m_name; - } - - public final void setName(String name) { - m_name = name; - } - - String getMagicTagName() { - return MAGIC_TAG_PREFIX + getName(); - } - - /** - * Adds a parameter model to the form model. The parameter model - * should be fully configured before adding it to the form model. - * - * @param parameter a parameter model object - * */ - public final void addFormParam(ParameterModel parameter) { - Assert.exists(parameter, "Parameter"); - Assert.isUnlocked(this); - parameter.setDefaultOverridesNull(m_defaultOverridesNull); - m_parameterModels.add(parameter); - - if( LOGGER.isDebugEnabled() ) { - LOGGER.debug( "Added parameter: " + parameter.getName() + "[" + - parameter.getClass().getName() + "]" ); - } - } - - - /** - * Adds a parameter model to the list of parameters that should - * not be exported when the form is rendered. Useful examples - * of this are for forms that loop back on themselves such as - * search forms or a control bar. The parameter model - * should be fully configured and have been added to the form model - * before adding it to the list of items to exclude - * - * @param parameter a parameter model object - * */ - public final void excludeFormParameterFromExport(ParameterModel parameter) { - Assert.exists(parameter, "Parameter"); - Assert.isUnlocked(this); - m_parametersToExclude.add(parameter); - } - - - /** - * Determines whether the form model contains the specified parameter - * model. - * @param p the parameter model to check for - * @return true if the form model contains the specified - * parameter model; false otherwise. - */ - public final boolean containsFormParam(ParameterModel p) { - Assert.exists(p, "Parameter"); - return m_parameterModels.contains(p); - } - - /** - * Returns an iterator over the parameter models contained within - * the form model. - * - * @return an iterator over the parameter models contained within - * the form model. - * */ - public final Iterator getParameters() { - return m_parameterModels.iterator(); - } - - - /** - * Returns an iterator over the parameter models that are - * contained within the form model but should not be exported - * as part of the form's state. This is important for situations - * where the form loops back on itself (e.g. a ControlBar or - * a Search form). - */ - public final Iterator getParametersToExclude() { - return m_parametersToExclude.iterator(); - } - - /** - * Adds a listener that is called as soon as the {@link FormData} has been - * initialized with the request parameters, but before any of the init, - * validation, or process listeners are run. The listener's - * submitted method may throw a - * FormProcessException to signal that any further - * processing of the form should be aborted. - * - * @param listener a FormSubmissionListener value - */ - public void addSubmissionListener(FormSubmissionListener listener) { - Assert.exists(listener, "Submission Listener"); - m_listenerList.add(FormSubmissionListener.class, listener); - } - - /** - * Adds a validation listener, implementing a custom validation - * check that applies to the form as a whole. Useful for checks - * that require examination of the values of more than one parameter. - * - * @param listener an instance of a class that implements the - * FormValidationListener interface - * */ - public void addValidationListener(FormValidationListener listener) { - Assert.exists(listener, "FormValidationListener"); - Assert.isUnlocked(this); - m_listenerList.add(FormValidationListener.class, listener); - } - - /** - * Adds a listener for form initialization events. - *

Initialization events occur when a form is initially - * requested by the user, but not when the form is subsequently - * submitted. They typically - * perform actions such as querying the database for existed values - * to set up an edit form or obtaining a sequence value to set up a - * create form. - * @param listener an instance of a class that implements the - * FormInitListener interface - * */ - public void addInitListener(FormInitListener listener) { - Assert.exists(listener, "FormInitListener"); - Assert.isUnlocked(this); - m_listenerList.add(FormInitListener.class, listener); - } - - /** - * Adds a listener for form processing events.

Process events - * only occur after a form submission has been successfully - * validated. They are typically used to perform a database - * transaction or other operation based on the submitted data. - *

Process listeners are executed in the order in which they are - * added. - * - * @param listener an instance of a class that implements the - * FormProcessListener interface - * */ - public void addProcessListener(FormProcessListener listener) { - Assert.exists(listener, "FormProcessListener"); - Assert.isUnlocked(this); - m_listenerList.add(FormProcessListener.class, listener); - } - - /** - * Creates a new FormData object that is populated with default values - * (for an initial request) or values from the request (for - * a submission). - *

If this is a submission, validates the data and (if the - * data is valid) calls the process listeners. Returns a FormData object. - * - * @param state the PageState object holding request-specific information - * @return a FormData object. - * */ - public FormData process(PageState state) throws FormProcessException { - Assert.isLocked(this); - boolean isSubmission = - state.getRequest().getParameter(getMagicTagName()) != null; - return process(state, isSubmission); - } - - /** - * Creates a new FormData object that is populated with default values - * (for an initial request) or values from the request (for a - * submission). - *

If this is a submission, validates the data and (if the - * data is valid) calls the process listeners. Returns a FormData object. - * - * @param state the PageState object holding request specific information - * @param isSubmission true if the request is a submission; - * false if this is the first request to the form data. - */ - public FormData process(PageState state, boolean isSubmission) - throws FormProcessException { - Assert.isLocked(this); - FormData data = new FormData(this, state.getRequest(), isSubmission); - try { - process(state, data); - } finally { - } - return data; - } - - - /** - * Do the work for the public process method. Uses the - * prepopulated FormData and runs listeners on it as - * needed. - * - * @throws FormProcessException if an error occurs - */ - void process(final PageState state, final FormData data) - throws FormProcessException { - LOGGER.debug("Processing the form model"); - - final FormSectionEvent e = new FormSectionEvent(this, state, data); - - if (data.isSubmission()) { - LOGGER.debug("The request is a form submission; running " + - "submission listeners"); - - try { - fireSubmitted(e); - } catch (FormProcessException fpe) { - LOGGER.debug("A FormProcessException was thrown while firing " + - "submit; aborting further processing"); - return; - } finally { - } - - - try { - LOGGER.debug("Validating parameters"); - fireParameterValidation(e); - - LOGGER.debug("Validating form"); - fireFormValidation(e); - } finally { - } - - if (data.isValid()) { - LOGGER.debug("The form data is valid; running process " + - "listeners"); - - try { - fireFormProcess(e); - } catch (FormProcessException fpe) { - LOGGER.debug("A FormProcessException was thrown while " + - "initializing the form; storing the error", fpe); - - data.addError("Initialization Aborted: " + fpe.getMessages()); - } finally { - } - } else { - LOGGER.debug("The form data was not valid; this form " + - "will not run its process listeners"); - } - } else { - LOGGER.debug("The request is not a form submission; " + - "running init listeners"); - - try { - fireFormInit(e); - } catch (FormProcessException fpe) { - LOGGER.debug("A FormProcessException was thrown while " + - "initializing the form; storing the error", fpe); - - data.addError("Initialization Aborted: " + fpe.getMessages()); - } finally { - } - } - } - - protected void fireSubmitted(FormSectionEvent e) - throws FormProcessException { - Assert.exists(e.getFormData(), "FormData"); - Assert.isLocked(this); - FormProcessException delayedException = null; - - Iterator i = m_listenerList.getListenerIterator(FormSubmissionListener.class); - while (i.hasNext()) { - try { - ((FormSubmissionListener) i.next()).submitted(e); - } catch (FormProcessException ex) { - delayedException = ex; - } - } - if ( delayedException != null ) { - throw delayedException; - } - } - - /** - * Calls a form initialization listener. - * - * @param e a FormSectionEvent originating from the form - */ - protected void fireFormInit(FormSectionEvent e) throws FormProcessException { - Assert.exists(e.getFormData(), "FormData"); - Assert.isLocked(this); - Iterator i = m_listenerList.getListenerIterator(FormInitListener.class); - while (i.hasNext()) { - ((FormInitListener) i.next()).init(e); - } - } - - /** - * Private helper method that validates the individual parameters by - * calling ParameterValidationListeners from the individual - * parameterModels. - * - * @param e a FormSectionEvent originating from the form - * */ - protected void fireParameterValidation(FormSectionEvent e) { - FormData data = e.getFormData(); - Assert.exists(data, "FormData"); - Iterator parameters = getParameters(); - ParameterModel parameterModel; - ParameterData parameterData; - while (parameters.hasNext()) { - parameterModel = (ParameterModel) parameters.next(); - parameterData = (ParameterData) data.getParameter(parameterModel.getName()); - try { - parameterData.validate(); - if (!parameterData.isValid()) { - data.invalidate(); - } - } catch (FormProcessException fpe) { - data.addError("Processing Listener Error: " + fpe.getMessage()); - } - } - } - - /** - * Private helper method. Validates the form by calling - * FormValidationListeners - * - * @param e a FormSectionEvent originating from the Form - * */ - private void fireFormValidation(FormSectionEvent e) { - FormData data = e.getFormData(); - Assert.exists(data, "FormData"); - Iterator i = m_listenerList.getListenerIterator(FormValidationListener.class); - while (i.hasNext()) { - try { - ((FormValidationListener) i.next()).validate(e); - } catch (FormProcessException fpe) { - data.addError(fpe.getMessage()); - } - } - } - - /** - * Call form process listeners.

Form processing is performed - * after the form has been validated.

- * - * @param e a FormSectionEvent originating from the form - * */ - private void fireFormProcess(FormSectionEvent e) - throws FormProcessException { - Assert.exists(e.getFormData(), "FormData"); - if (!e.getFormData().isValid()) { - throw new IllegalStateException("Request data must be valid " + "prior to running processing filters."); - } - Iterator i = m_listenerList.getListenerIterator(FormProcessListener.class); - - RedirectSignal redirect = null; - while (i.hasNext()) { - try { - ((FormProcessListener) i.next()).process(e); - } catch( RedirectSignal signal ) { - if( LOGGER.isDebugEnabled() ) { - LOGGER.debug( "Delaying redirect to " + - signal.getDestinationURL() ); - } - - if( null != redirect ) { - LOGGER.error( "Non-deterministic redirect. Ignoring earlier occurrence.", redirect ); - } - - redirect = signal; - } - } - - if( null != redirect ) throw redirect; - } - - /** - * Call form validation listeners. Listeners that encounter - * validation errors report them directly to the - * FormData object.

Form validation is performed - * after the initial transformation of key-value string - * pairs into Java data objects is complete. - * - * @param state the page state for this request - * - * @param data the FormData object to validate - * - * @pre data != null - * */ - void validate(PageState state, FormData data) { - Assert.exists(data, "FormData"); - if (!data.isTransformed()) { - throw new IllegalStateException("Request data must be transformed " + "prior to running validation filters."); - } - fireParameterValidation(new FormSectionEvent(this, state, data)); - fireFormValidation(new FormSectionEvent(this, state, data)); - } - - /** - * Merge the parameterModels and Listeners from the supplied - * FormModel into the current FormModel. This method is useful when - * registering FormSections in Forms. - * - * @param m The FormModel to be merged into this FormModel - * */ - void mergeModel(FormModel m) { - Assert.isUnlocked(this); - Assert.exists(m, "FormSection's FormModel"); - m_parameterModels.addAll(m.m_parameterModels); - m_listenerList.addAll(m.m_listenerList); - } - - /** - * Locks this FormModel and all of its ParameterModels. - * */ - public void lock() { - for (Iterator i = getParameters(); i.hasNext(); ) { - ((ParameterModel) i.next()).lock(); - } - m_locked = true; - } - - /** - * Checks whether this FormModel is locked. - * - * @return true if this FormModel is locked; - * false otherwise. - * */ - public final boolean isLocked() { - return m_locked; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/FormProcessException.java b/ccm-core/src/main/java/com/arsdigita/bebop/FormProcessException.java deleted file mode 100644 index c4f3d2d52..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/FormProcessException.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.globalization.GlobalizedMessage; -import javax.servlet.ServletException; - -/** - * This class represents exceptions that occur within the processing methods - * of any of the form event listeners. Typically the code will catch specific - * exceptions such as SQLException and rethrow them as instances - * of this class to pass the message to the controller in a standard fashion. - * - *

Since this class is a subclass of ServletException, servlets - * that do form processing within a doPost or doGet - * methods do not need to explicitly catch instances of this class. However, - * they may wish to do so for special error reporting to the user, or to notify - * the webmaster via e-mail of the problem. - * - * @version $Id$ - */ - -public class FormProcessException extends ServletException { - - /** Globalized version of the exception message, intended for output in the UI */ - private GlobalizedMessage m_globalizedMessage; - - /** - * Constructor using a String as message presented to the user. - * @param message - * @deprecated Use FormProcessException(GlobalizedMessage) instead. The - * error message for the user should always be globalized so it - * can be transformed to the current users requested language. - */ - public FormProcessException(String message) { - super(message); - } - - /** - * Constructor using both types of messages which may be presented to the - * user. It's a kind of fallback just in kind we really need a non- - * globalized message. Usage is strongly discouraged. - * @param message - * @param globalizedMessage - */ - public FormProcessException(String message, - GlobalizedMessage globalizedMessage) { - super(message); - m_globalizedMessage = globalizedMessage; - } - - /** - * Constructor using a GlobalizedMessage as the error text presented to the - * user. Using this constructor is the strongly recommended way! - * - * @param globalizedMessage - */ - public FormProcessException(GlobalizedMessage globalizedMessage) { - super(); - m_globalizedMessage = globalizedMessage; - } - - /** - * - * @param message - * @param rootCause - * @deprecated use FormProcessException(String,GlobalizedMessage,Throwable) - * instead - */ - public FormProcessException(String message, - Throwable rootCause) { - super(message, rootCause); - } - - public FormProcessException(String message, - GlobalizedMessage globalizedMessage, - Throwable rootCause) { - super(message, rootCause); - m_globalizedMessage = globalizedMessage; - } - - public FormProcessException(Throwable rootCause) { - super(rootCause); - } - - /** - * Add a globalized version of the exception message just in case a non- - * globalized message enabled constructor has been used. - * - * @param globalizedMessage the globalized message intended for output in UI - */ - public void setGlobalizedMessage(GlobalizedMessage globalizedMessage) { - m_globalizedMessage = globalizedMessage; - } - - /** - * Retrieve the globalized version of the exception message, intended for - * use in the UI widgets. - * The standard non-globalizatin enabled exception message is for use in - * log entries only! - * - * @return the globalized message intended for output in UI - */ - GlobalizedMessage getGlobalizedMessage() { - return m_globalizedMessage; - } - /** - * In addition to printing the stack trace for this exception, also prints - * the stack trace for the root cause, if any. This is a workaround for - * those implementations of {@link ServletException} that don't implement - * printStackTrace correctly. If you happen to use an - * implementation that does, the stack trace for the root cause may be - * printed twice, which is not that big of a deal in the grand scheme of - * things. - */ - @Override - public void printStackTrace() { - super.printStackTrace(); - if (getRootCause() != null) { - System.err.print("Root cause: "); - getRootCause().printStackTrace(); - } - } - - /** - * @param s - * @see #printStackTrace() - */ - @Override - public void printStackTrace(java.io.PrintStream s) { - super.printStackTrace(s); - if (getRootCause() != null) { - s.println("Root cause: "); - getRootCause().printStackTrace(s); - } - } - - /** - * @param s - * @see #printStackTrace() - */ - @Override - public void printStackTrace(java.io.PrintWriter s) { - super.printStackTrace(s); - if (getRootCause() != null) { - s.println("Root cause: "); - getRootCause().printStackTrace(s); - } - } - - /** - *

Returns the concatenation of {@link #getMessage()} and {@link - * #getRootCause()}.getMessage().

- * @return - **/ - public String getMessages() { - StringBuilder result = new StringBuilder(getMessage()); - if ( getRootCause() != null ) { - result.append(" (root cause: ") - .append(getRootCause().getMessage()) - .append(")"); - } - return result.toString(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/FormSection.java b/ccm-core/src/main/java/com/arsdigita/bebop/FormSection.java deleted file mode 100755 index 0ab2446b9..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/FormSection.java +++ /dev/null @@ -1,811 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.EventListenerList; -import com.arsdigita.bebop.event.FormCancelListener; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Iterator; - -/** - * A standalone section of a Form. A FormSection - * contains other Bebop components, most importantly Widgets and - * associated listeners. It serves two purposes: - *
    - *
  • Divides a form into visual sections
  • - *
  • Serves as a container for form fragments that can function by themselves - * and can be dropped into other forms
  • - *
- *

- * Since a FormSection has its own init, validation, and process - * listeners, it can do all of its processing without any intervention from the - * enclosing form. - * - * Although a FormSection contains all the same pieces that a - * Form does, it can only be used if it is added directly or - * indirectly to a Form. FormSections that are not - * contained in a Form do not exhibit any useful behavior. - * - * @see Form - * @see FormModel - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Stas Freidin - * @author Rory Solomon - * @author David Lutterkort - */ -public class FormSection extends DescriptiveComponent implements Container { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int the runtime environment and - * set com.arsdigita.subsite.FormSection=DEBUG by uncommenting or adding the - * line. - */ - private static final Logger LOGGER = LogManager.getLogger(FormSection.class); - - /** - * Underlying FormModel that stores the parameter models for - * all the widgets in this form section. - */ - protected FormModel m_formModel; - - /** - * The container to which all children are added. A ColumnPanel - * by default. - */ - protected Container m_panel; - - /** - * Contains all the listeners that were added with the various - * addXXXListener methods. We maintain our own list of listeners, so that we - * can re-send the events the FormModel generates, but with us as the - * source, not the FormModel. - */ - private EventListenerList m_listeners; - - /** - * Listeners we attach to the FormModel to forward form model events to our - * listeners with the right source - */ - private FormSubmissionListener m_forwardSubmission; - - private FormInitListener m_forwardInit; - private FormValidationListener m_forwardValidation; - private FormProcessListener m_forwardProcess; - - /** - * Constructs a new form section. Sets the implicit layout Container of this - * FormSection to two column ColumnPanel by - * calling the 1-argument constructor. - * - */ - public FormSection() { - this(new ColumnPanel(2, true)); - } - - /** - * Constructs a new form section. Sets the form model of this - * FormSection to a new, anonymous FormModel. - * - * @param panel - * - */ - public FormSection(Container panel) { - this(panel, new FormModel("anonymous")); - } - - /** - * Constructs a new form section. Sets the implicit layout Container of this - * FormSection to panel. Sets the form model of - * this FormSection to model. - * - * @param panel the container within this form section that holds the - * components that are added to the form section with calls to - * the add methods - * - * @param model the form model for this form section - * - */ - protected FormSection(Container panel, FormModel model) { - super(); - m_panel = panel; - m_formModel = model; - m_listeners = new EventListenerList(); - } - - /** - * Adds a listener that is called as soon as the {@link FormData} has been - * initialized with the request parameters but before any of the init, - * validation, or process listeners are run. The listener's - * submitted method may throw a - * FormProcessException to signal that any further processing - * of the form should be aborted. - * - * @param listener a submission listener to run every time the form is - * submitted - * - * @see FormModel#addSubmissionListener - * @pre listener != null - */ - public void addSubmissionListener(FormSubmissionListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Adding submission listener " + listener + " to " - + this); - } - - Assert.exists(listener, "Submission Listener"); - Assert.isUnlocked(this); - forwardSubmission(); - m_listeners.add(FormSubmissionListener.class, listener); - } - - /** - * Removes the specified submission listener from the list of submission - * listeners (if it had previously been added). - * - * @param listener the submission listener to remove - */ - public void removeSubmissionListener(FormSubmissionListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Removing submission listener " + listener + " from " - + this); - } - - Assert.exists(listener, "Submission Listener"); - Assert.isUnlocked(this); - m_listeners.remove(FormSubmissionListener.class, listener); - } - - /** - * Calls the submitted method on all registered submission - * listeners. - * - * @param e the event to pass to the listeners - * - * @throws FormProcessException if one of the listeners throws such an - * exception. - */ - protected void fireSubmitted(FormSectionEvent e) - throws FormProcessException { - Assert.exists(e.getFormData(), "FormData"); - FormProcessException delayedException = null; - - Iterator i = m_listeners.getListenerIterator( - FormSubmissionListener.class); - while (i.hasNext()) { - final FormSubmissionListener listener = (FormSubmissionListener) i. - next(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Firing submission listener " + listener); - } - - try { - listener.submitted(e); - } catch (FormProcessException ex) { - LOGGER.debug(ex); - delayedException = ex; - } - } - if (delayedException != null) { - throw delayedException; - } - } - - /** - * - */ - protected void forwardSubmission() { - if (m_forwardSubmission == null) { - m_forwardSubmission = createSubmissionListener(); - getModel().addSubmissionListener(m_forwardSubmission); - } - } - - /** - * Creates the submission listener that forwards submission events to this - * form section. - * - * @return a submission listener that forwards submission events to this - * form section. - */ - protected FormSubmissionListener createSubmissionListener() { - return new FormSubmissionListener() { - - @Override - public void submitted(FormSectionEvent e) - throws FormProcessException { - fireSubmitted(new FormSectionEvent(FormSection.this, - e.getPageState(), - e.getFormData())); - } - - }; - } - - /** - * Adds a listener for form initialization events. Initialization events - * occur when a form is initially requested by the user, but not when the - * form is subsequently submitted. They typically perform actions such as - * querying the database for existing values to set up an edit form, or - * obtaining a sequence value to set up a create form. - * - * @param listener an instance of a class that implements the - * FormInitListener interface - * - */ - public void addInitListener(FormInitListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Adding init listener " + listener + " to " + this); - } - - Assert.exists(listener, "FormInitListener"); - Assert.isUnlocked(this); - forwardInit(); - m_listeners.add(FormInitListener.class, listener); - } - - /** - * Removes the specified init listener from the list of init listeners (if - * it had previously been added). - * - * @param listener the init listener to remove - */ - public void removeInitListener(FormInitListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Removing init listener " + listener + " from " + this); - } - - Assert.exists(listener, "Init Listener"); - Assert.isUnlocked(this); - m_listeners.remove(FormInitListener.class, listener); - } - - /** - * Calls the init method on all registered init listeners. - * - * @param e the event to pass to the listeners - * - * @throws FormProcessException if one of the listeners throws such an - * exception. - */ - protected void fireInit(FormSectionEvent e) throws FormProcessException { - Assert.exists(e.getFormData(), "FormData"); - Assert.isLocked(this); - Iterator i = m_listeners.getListenerIterator(FormInitListener.class); - while (i.hasNext()) { - final FormInitListener listener = (FormInitListener) i.next(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Firing init listener " + listener); - } - - listener.init(e); - } - } - - /** - * - */ - protected void forwardInit() { - if (m_forwardInit == null) { - m_forwardInit = createInitListener(); - getModel().addInitListener(m_forwardInit); - } - } - - /** - * Creates the init listener that forwards init events to this form section. - * - * @return an init listener that forwards init events to this form section. - */ - protected FormInitListener createInitListener() { - return new FormInitListener() { - - @Override - public void init(FormSectionEvent e) - throws FormProcessException { - fireInit(new FormSectionEvent(FormSection.this, - e.getPageState(), - e.getFormData())); - } - - }; - } - - /** - * Creates the cancel listener that forwards cancel events to this form - * section - * - * @return an cancel listener - */ - protected FormCancelListener createCancelListener() { - return new FormCancelListener() { - - @Override - public void cancel(FormSectionEvent e) throws FormProcessException { - fireCancel(new FormSectionEvent(FormSection.this, - e.getPageState(), - e.getFormData())); - } - - }; - } - - /** - * Adds a validation listener, implementing a custom validation check that - * applies to the form as a whole. Useful for checks that require - * examination of the values of more than one parameter. - * - * @param listener an instance of a class that implements the - * FormValidationListener interface - * - */ - public void addValidationListener(FormValidationListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Adding validation listener " + listener + " to " - + this); - } - - Assert.exists(listener, "FormValidationListener"); - Assert.isUnlocked(this); - forwardValidation(); - m_listeners.add(FormValidationListener.class, listener); - } - - /** - * Removes the specified validation listener from the list of validation - * listeners (if it had previously been added). - * - * @param listener a validation listener - */ - public void removeValidationListener(FormValidationListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Removing validation listener " + listener + " from " - + this); - } - - Assert.exists(listener, "Validation Listener"); - Assert.isUnlocked(this); - m_listeners.remove(FormValidationListener.class, listener); - } - - /** - * Calls the validate method on all registered validation - * listeners. - * - * @param e the event to pass to the listeners - */ - protected void fireValidate(FormSectionEvent e) { - FormData data = e.getFormData(); - Assert.exists(data, "FormData"); - Iterator i = m_listeners.getListenerIterator( - FormValidationListener.class); - while (i.hasNext()) { - try { - final FormValidationListener listener - = (FormValidationListener) i.next(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Firing validation listener " + listener); - } - - listener.validate(e); - } catch (FormProcessException fpe) { - LOGGER.debug(fpe); - data.addError(fpe.getGlobalizedMessage()); - } - } - } - - protected void forwardValidation() { - if (m_forwardValidation == null) { - m_forwardValidation = createValidationListener(); - getModel().addValidationListener(m_forwardValidation); - } - } - - /** - * Create the validation listener that forwards validation events to this - * form section. - * - * @return a validation listener that forwards validation events to this - * form section. - */ - protected FormValidationListener createValidationListener() { - return new FormValidationListener() { - - @Override - public void validate(FormSectionEvent e) { - fireValidate(new FormSectionEvent(FormSection.this, - e.getPageState(), - e.getFormData())); - } - - }; - } - - /** - * Adds a listener for form processing events. - *

- * Process events only occur after a form submission has been successfully - * validated. They are typically used to perform a database transaction or - * other operation based on the submitted data. - *

- * Process listeners are executed in the order in which they are added. - * - * @param listener an instance of a class that implements the - * FormProcessListener interface - * - */ - public void addProcessListener(final FormProcessListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Adding process listener " + listener + " to " + this); - } - - Assert.exists(listener, "FormProcessListener"); - Assert.isUnlocked(this); - - forwardProcess(); - m_listeners.add(FormProcessListener.class, listener); - } - - /** - * Removes the specified process listener from the list of process listeners - * (if it had previously been added). - * - * @param listener the process listener to remove - */ - public void removeProcessListener(FormProcessListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Removing process listener " + listener + " from " - + this); - } - - Assert.exists(listener, "Process Listener"); - Assert.isUnlocked(this); - - m_listeners.remove(FormProcessListener.class, listener); - } - - protected void forwardProcess() { - if (m_forwardProcess == null) { - m_forwardProcess = createProcessListener(); - getModel().addProcessListener(m_forwardProcess); - } - } - - protected FormProcessListener createProcessListener() { - return new FormProcessListener() { - - @Override - public void process(FormSectionEvent e) - throws FormProcessException { - fireProcess(new FormSectionEvent(FormSection.this, - e.getPageState(), - e.getFormData())); - } - - }; - } - - /** - * Calls the process method on all registered process - * listeners. - * - * @param e the event to pass to the listeners - * - * @throws FormProcessException if one of the listeners throws such an - * exception. - */ - protected void fireProcess(FormSectionEvent e) - throws FormProcessException { - Assert.exists(e.getFormData(), "FormData"); - Iterator i = m_listeners.getListenerIterator(FormProcessListener.class); - while (i.hasNext()) { - final FormProcessListener listener = (FormProcessListener) i.next(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Firing process listener " + listener); - } - - listener.process(e); - } - } - - /** - * Since a form section cannot be processed, always throws an error. - * (Processing of form sections is done by the form in which the section is - * contained.) - * - * @param data - * - * @return - * - * @throws javax.servlet.ServletException because processing a form section - * is not meaningful. - */ - public FormData process(PageState data) - throws javax.servlet.ServletException { - throw new UnsupportedOperationException(); - } - - /** - * Adds a listener for form cancellation events. Cancellation listeners are - * typically used to clean-up page state and potentially intermediate - * changes to the database. - * - * @param listener an instance of a class that implements the - * FormCancelListener interface - * - */ - public void addCancelListener(FormCancelListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Adding cancel listener " + listener + " to " + this); - } - - Assert.exists(listener, "FormCancelListener"); - Assert.isUnlocked(this); - m_listeners.add(FormCancelListener.class, listener); - } - - /** - * Removes the specified cancellation listener from the list of cancellation - * listeners (if it had previously been added). - * - * @param listener the cancellation listener to remove - */ - public void removeCancelListener(FormCancelListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Removing cancel listener " + listener + " from " - + this); - } - - Assert.exists(listener, "Cancel Listener"); - Assert.isUnlocked(this); - m_listeners.remove(FormCancelListener.class, listener); - } - - /** - * Calls the cancel method on all registered cancellation - * listeners. - * - * @param e the event to pass to the listeners - * - * @throws FormProcessException if one of the listeners throws such an - * exception. - */ - protected void fireCancel(FormSectionEvent e) - throws FormProcessException { - Assert.exists(e.getFormData(), "FormData"); - Iterator i = m_listeners.getListenerIterator(FormCancelListener.class); - while (i.hasNext()) { - final FormCancelListener listener = (FormCancelListener) i.next(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Firing cancel listener " + listener); - } - - listener.cancel(e); - } - } - - /** - * Traverses the children this FormSection, collecting parameter models and - * listeners into the supplied FormModel. Sets implicit pointers of widgets - * in this FormSection to the supplied Form. - * - * @param f pointer to the form that is set inside Widgets within this - * FormSection - * @param m the FormModel in which to merge ParameterModels and Listeners - * - */ - @Override - public void register(Form f, FormModel m) { - m.mergeModel(getModel()); - } - - /** - * Accessor method for this form's FormModel. - * - * @return FormModel The model of this form. - * - */ - protected final FormModel getModel() { - return m_formModel; - } - - /** - * Locks this FormSection, its FormModel, and the implicit Container. - * - */ - @Override - public void lock() { - m_formModel.lock(); - m_panel.lock(); - super.lock(); - } - - @Override - public void respond(PageState state) throws javax.servlet.ServletException { - //call listeners here. - throw new UnsupportedOperationException(); - } - - /** - * Returns the implicit Container of this FormSection. - * - * This must not be final, because MetaFrom needs to override it. - * - * @return - */ - public Container getPanel() { - return m_panel; - } - - /** - * Returns an iterator over the children of this component. If the component - * has no children, returns an empty iterator (not null !). - * - * @post return != null - * - */ - @Override - public Iterator children() { - return m_panel.children(); - } - - /** - * Builds an XML subtree for this component under the specified - * parent. Uses the request values stored in - * state.

- * - *

- * This method generates DOM to be used with the XSLT template to produce - * the appropriate output.

- * - * @param pageState the state of the current page - * @param parent the node that will be used to write to - * - */ - @Override - public void generateXML(PageState pageState, Element parent) { - if (isVisible(pageState)) { - m_panel.generateXML(pageState, parent); - } - } - - // Container methods - /** - * Adds a component to this container. - * - * @param pc the component to add to this container - * - */ - @Override - public void add(Component pc) { - m_panel.add(pc); - } - - /** - * Adds a component with the specified layout constraints to this container. - * Layout constraints are defined in each layout container as static ints. - * Use a bitwise OR to specify multiple constraints. - * - * @param pc the component to add to this container - * @param constraints layout constraints (a bitwise OR of static ints in the - * particular layout) - */ - @Override - public void add(Component pc, int constraints) { - m_panel.add(pc, constraints); - } - - /** - * Returns true if this list contains the specified element. - * More formally, returns true if and only if this list contains at least - * one element e such that (o==null ? e==null : o.equals(e)). - * - * This method returns true only if the component has been - * directly added to this container. If this container contains another - * container that contains this component, this method returns - * false. - * - * @param o element whose presence in this container is to be tested - * - * @return true if this Container contains the specified - * component directly; false otherwise. - * - * - */ - @Override - public boolean contains(Object o) { - return m_panel.contains(o); - } - - /** - * Returns the Component at the specified position. Each call to add() - * increments the index. This method should be used in conjunction with - * indexOf - * - * @param index The index of the item to be retrieved from this Container. - * Since the user has no control over the index of added - * components (other than counting each call to add), this - * method should be used in conjunction with indexOf. - * - * @return the component at the specified position in this container - * - */ - @Override - public Component get(int index) { - return (Component) m_panel.get(index); - } - - /** - * - * - * - * @param pc component to search for - * - * @return the index in this list of the first occurrence of the specified - * element, or -1 if this list does not contain this element. - * - */ - @Override - public int indexOf(Component pc) { - return m_panel.indexOf(pc); - } - - /** - * Determines whether the container contains any components. - * - * @return true if this container contains no components - * false otherwise. - * - */ - @Override - public boolean isEmpty() { - return m_panel.isEmpty(); - } - - /** - * Returns the number of elements in this container. This does not - * recursively count the components indirectly contained in this container. - * - * @return the number of components directly in this container. - * - */ - @Override - public int size() { - return m_panel.size(); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/FormStep.java b/ccm-core/src/main/java/com/arsdigita/bebop/FormStep.java deleted file mode 100755 index 957a83d62..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/FormStep.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.parameters.BooleanParameter; -import com.arsdigita.bebop.util.Traversal; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * The FormStep class modifies the behavior of FormSection with respect to - * listener firing. Instead of firing init listeners the first time the - * enclosing form is displayed on the page, the FormStep class fires init - * listeners the first time the FormStep itself is displayed on the page. The - * process, validate, and submission listeners are then fired on every - * submission following the one in which the init listeners were fired. This - * behavior is useful when used in conjunction with {@link MultiStepForm} or its - * subclasses to provide initialization in later steps of a multi step form that - * depends on the values entered in earlier steps. - * - * updated chris.gilbert@westsussex.gov.uk - support for session based wizards - * (which enable use of actionlinks in wizard) - * - * @see Wizard - * @see MultiStepForm - * - * @author rhs@mit.edu - * - */ -public class FormStep extends FormSection { - - private final static Logger LOGGER = LogManager.getLogger(FormStep.class); - - private Form m_form = null; - - // cg - changed to using a parameter that is stored in pagestate so that if there are links - // within the form then the init status of the steps is not lost - // private Hidden m_initialized; - private BooleanParameter m_initialized; - - /** - * Constructs a new FormStep with the given name. The name must uniquely - * identify this FormStep within it's enclosing Form. - * - * @param name A name that uniquely identifies this FormStep within it's - * enclosing Form. - * - */ - public FormStep(String name) { - addInitialized(name); - } - - /** - * Constructs a new FormStep with the given name. The name must uniquely - * identify this FormStep within it's enclosing Form. - * - * @param name A name that uniquely identifies this FormStep within it's - * enclosing Form. - * @param panel The container used to back this FormStep. - * - */ - public FormStep(String name, Container panel) { - super(panel); - addInitialized(name); - } - - protected FormStep(String name, Container panel, FormModel model) { - super(panel, model); - addInitialized(name); - } - - public void register(Page p) { - super.register(p); - p.addComponentStateParam(this, m_initialized); - Traversal trav = new Traversal() { - - protected void act(Component c) { - if (c instanceof Widget) { - ((Widget) c).setValidateInvisible(false); - } - } - - }; - - trav.preorder(this); - } - - public void register(Form form, FormModel model) { - super.register(form, model); - m_form = form; - } - - private void addInitialized(String name) { - // m_initialized = new Hidden(new BooleanParameter(name)); - // add(m_initialized); - m_initialized = new BooleanParameter(name); - m_initialized.setDefaultValue(Boolean.FALSE); - } - - public boolean isInitialized(PageState ps) { - // Object init = m_initialized.getValue(ps); - Boolean init = (Boolean) ps.getValue(m_initialized); - if (init == null) { - LOGGER.debug("init for step " + m_initialized.getName() - + " is null. returning true"); - // happens if step state is stored in session - - // form containing this step clears session - // info when processed, but fireProcess invoked - // on this step AFTER form is processed. At that point, - // the step has been initialised because we are on the - // final process at the end of the steps - // - init = Boolean.TRUE; - } - return init.booleanValue(); - } - - private void setInitialized(PageState ps) { - //m_initialized.setValue(ps, Boolean.TRUE); - ps.setValue(m_initialized, Boolean.TRUE); - } - - // Turn off forwarding of init events. - protected FormInitListener createInitListener() { - return new FormInitListener() { - - public void init(FormSectionEvent evt) { - } - - }; - } - - protected void fireSubmitted(FormSectionEvent evt) - throws FormProcessException { - if (isInitialized(evt.getPageState())) { - super.fireSubmitted(evt); - } - } - - protected void fireValidate(FormSectionEvent evt) { - if (isInitialized(evt.getPageState())) { - super.fireValidate(evt); - } - } - - protected void fireProcess(FormSectionEvent evt) - throws FormProcessException { - LOGGER.debug("fireprocess invoked on Formstep " + m_initialized - .getName()); - if (isInitialized(evt.getPageState())) { - super.fireProcess(evt); - - } - } - - public void generateXML(PageState ps, Element parent) { - if (!isInitialized(ps)) { - FormData fd = m_form.getFormData(ps); - try { - fireInit(new FormSectionEvent(this, ps, fd)); - setInitialized(ps); - } catch (FormProcessException ex) { - LOGGER.debug("initialization aborted", ex); - fd.addError("Initialization Aborted: " + ex.getMessages()); - } - } - - super.generateXML(ps, parent); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/GridPanel.java b/ccm-core/src/main/java/com/arsdigita/bebop/GridPanel.java deleted file mode 100755 index 62e91d764..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/GridPanel.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.util.BebopConstants; -import com.arsdigita.bebop.util.PanelConstraints; -import com.arsdigita.bebop.form.Hidden; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - *

A container that prints its components in a table. Each child is - * printed in its own table cell. The number of columns can be - * specified in the constructor. The components are put into the table - * in the order in which they were added to the GridPanel - * by filling the table one row - * at a time (filling each row from left to right), from the top of the table - * to the bottom.

- * - *

The position of the component within the cell can be influenced - * with the following constraints.

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Horizontal alignmentUse LEFT, CENTER, or - * RIGHT.
Vertical alignmentUse TOP, MIDDLE, or - * BOTTOM.
Full widthUse FULL_WIDTH to instruct the panel to put - * the component in a row by itself, spanning the full width of the - * table.
Inserting childrenUse INSERT to instruct the panel to - * insert the corresponding component, assuming that it will also be - * laid out by a ColumnPanel with the same number of - * columns.
- * - * - * - *

Constraints can be combined by - * ORing them together. For example, to print a component in a row of its - * own, left-aligned, at the bottom of its cell, use the constraint - * FULL_WIDTH | LEFT | BOTTOM.

- * - *

Using the INSERT constraint fuses the current - * GridPanel with the panel of the child to which the - * constraint is applied. For example, consider a {@link Form}, that - * is to have a 2-column format with labels in the left column - * and widgets in the right column. If a {@link FormSection} is added to - * the form, it should be included seamlessly into the parent - * form. To do this, set the INSERT - * constraint when the {@link FormSection} is added to the {@link - * Form}'s GridPanel. At the same time, tell the - * GridPanel used to lay out the {@link FormSection} - * that it is is to be inserted into another panel. - * The following - * pseudo-code illustrates the example. (It assumes that Form and - * FormSection are decorators of the GridPanel.)

- * - *
- * Form form = new Form(new GridPanel(2));
- * FormSection sec = new FormSection(new GridPanel(2, true));
- * // "true" in the above constructor tells the GridPanel it is inserted.
- *
- * sec.add(new Label("Basic Item Metadata"), GridPanel.FULL_WIDTH);
- * sec.add(new Label("Title:"), GridPanel.RIGHT);
- * sec.add(new Text("title"));
- *
- * form.add(sec, GridPanel.INSERT);
- * 
- * - * @see BoxPanel - * @see SplitPanel - * @author David Lutterkort - * @author Stanislav Freidin - * @author Justin Ross - * @version $Id: GridPanel.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class GridPanel extends SimpleContainer - implements BebopConstants, PanelConstraints { - - private static final ChildConstraint DEFAULT_CONSTRAINT - = new ChildConstraint(); - - private int m_numColumns; - - /* - * Explicitly registered constraints for child components. Maps - * Componentss to Constraints - */ - private Map m_childConstraintMap; - - /* - * Is this panel inserted in another one? If so, do not produce - * <table> tags. - */ - private boolean m_isInserted; - - /** - * Creates a table panel with the specified number of columns. - * - * @param numColumns the number of columns in the panel - */ - public GridPanel(int numColumns) { - this(numColumns, false); - } - - /** - * Creates a table panel with the specified number of columns and - * indicates whether the panel is inserted. - * - * @param numColumns the number of columns in the panel - * @param isInserted true if this panel is to be - * printed as a direct child of a GridPanel - * with the same number of columns - * @see #setInserted - */ - public GridPanel(int numColumns, boolean isInserted) { - m_numColumns = numColumns; - setInserted(isInserted); - m_childConstraintMap = new HashMap(); - } - - /** - * Adds a component, specifying constraints. - * @param component the component to add - * @param constraints the constraints for the component - */ - public void add(Component component, int constraints) { - super.add(component); - - m_childConstraintMap.put(component, new ChildConstraint(constraints)); - } - - /** - * Sets whether this panel will be printed inside a - * GridPanel with the same number of columns. If - * inserted is true, no <table> tags will be - * produced to enclose the child components. - * @param true if this panel is to be printed - * inside a GridPanel with the same number of columns - * - */ - public void setInserted(boolean isInserted) { - Assert.isUnlocked(this); - m_isInserted = isInserted; - } - - /** - * Determines whether this panel is to be inserted into another panel. - * @return true if this panel is to be inserted into another panel; - * false otherwise. - * @see #setInserted - */ - public final boolean isInserted() { - return m_isInserted; - } - - /** - * Adds child components as a subtree under table-style nodes. If any of the - * direct children are hidden form widgets, they are added directly to - * parent rather than included in any of the - * cell elements of the panel. - * - *

Generates a DOM fragment: - *

-     * <bebop:gridPanel>
-     *   <bebop:panelRow>
-     *     <bebop:cell> ... cell contents </bebop:cell>
-     *     <bebop:cell> ... cell contents </bebop:cell>
-     *     ...
-     *   </bebop:panelRow>
-     *   <bebop:panelRow>
-     *    <bebop:cell> ... cell contents </bebop:cell>
-     *    <bebop:cell> ... cell contents </bebop:cell>
-     *    ...
-     *   </bebop:panelRow>
-     * </bebop:gridPanel>
- * - * @param pageState - * @param parent - */ - @Override - public void generateXML(PageState pageState, Element parent) { - if (isVisible(pageState)) { - if (isInserted()) { - generateChildren(pageState, parent); - } else { - Element panel = parent.newChildElement(BEBOP_GRIDPANEL, BEBOP_XML_NS); - exportAttributes(panel); - generateChildren(pageState, panel); - } - } - } - - /* - * Lay out the child components using constraints registered for them, - * generating a DOM tree and extending another. - */ - private void generateChildren(PageState pageState, Element parent) { - int positionInRow = 0; - boolean newRowRequested = true; // First time through we want a new row. - Element row = null; - Element cell = null; - ChildConstraint constraint = null; - - Iterator iter = children(); - while (iter.hasNext()) { - Component child = (Component)iter.next(); - - if (child.isVisible(pageState)) { - if (child instanceof Hidden) { - child.generateXML(pageState, parent); - } else { - constraint = getChildConstraint(child); - - if (constraint.m_isInsert) { - child.generateXML(pageState, parent); - - newRowRequested = true; - } else { - if (positionInRow >= m_numColumns - || constraint.m_isFullWidth - || newRowRequested) { - positionInRow = 0; - - row = parent.newChildElement(BEBOP_PANELROW, BEBOP_XML_NS); - - if (constraint.m_isFullWidth) { - // If the column was full width, we - // want a new row in the next iteration. - newRowRequested = true; - } else if (newRowRequested) { - // Reset to off. - newRowRequested = false; - } - } - - cell = row.newChildElement(BEBOP_CELL, BEBOP_XML_NS); - - child.generateXML(pageState, cell); - - constraint.exportCellAttributes(cell, m_numColumns); - - positionInRow++; - } - } - } - } - } - - /* - * Helper stuff - */ - - private ChildConstraint getChildConstraint(Component component) { - ChildConstraint constraint = - (ChildConstraint)m_childConstraintMap.get(component); - - if (constraint == null) { - constraint = DEFAULT_CONSTRAINT; - } - - return constraint; - } - - private static class ChildConstraint { - public boolean m_isFullWidth; - public boolean m_isInsert; - public String m_horizontalAlignment; - public String m_verticalAlignment; - - public ChildConstraint() { - this(0); - } - - public ChildConstraint(int constraints) { - if ((constraints & LEFT) != 0) { - m_horizontalAlignment = "left"; - } else if ((constraints & CENTER) != 0) { - m_horizontalAlignment = "center"; - } else if ((constraints & RIGHT) != 0) { - m_horizontalAlignment = "right"; - } else { - m_horizontalAlignment = null; - } - - if ((constraints & TOP) != 0) { - m_verticalAlignment = "top"; - } else if ((constraints & MIDDLE) != 0) { - m_verticalAlignment = "middle"; - } else if ((constraints & BOTTOM) != 0) { - m_verticalAlignment = "bottom"; - } else { - m_verticalAlignment = null; - } - - m_isFullWidth = (constraints & FULL_WIDTH) != 0; - - m_isInsert = (constraints & INSERT) != 0; - } - - public void exportCellAttributes(Element cell, int numColumns) { - if (m_horizontalAlignment != null) { - cell.addAttribute("align", m_horizontalAlignment); - } - - if (m_verticalAlignment != null) { - cell.addAttribute("valign", m_verticalAlignment); - } - - if (m_isFullWidth) { - cell.addAttribute("colspan", Integer.toString(numColumns)); - } - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Image.java b/ccm-core/src/main/java/com/arsdigita/bebop/Image.java deleted file mode 100755 index c37d758cd..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Image.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.xml.Element; - -import com.arsdigita.util.Assert; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.event.PrintEvent; - -/** - * A simple wrapper class for images. - * - * @author David Lutterkort - * @author Stanislav Freidin - * - * @version $Id$ - */ - -public class Image extends DescriptiveComponent { - - private final String IMAGE_URL = "src"; - private final String ALT = "alt"; - private final String HEIGHT = "height"; - private final String WIDTH = "width"; - private final String BORDER = "border"; - - private PrintListener m_printListener; - - public Image(String imageURL, String alt) { - super(); - setImageURL(imageURL); - setAlt(alt); - } - - public Image(String imageURL) { - this(imageURL, ""); - } - - /** - * Creates a new Image that uses the print listener - * to generate output. - * - * @param l the print listener used to produce output - */ - public Image(PrintListener l) { - this(""); - addPrintListener(l); - } - - public void setImageURL(String imageURL) { - Assert.isUnlocked(this); - setAttribute(IMAGE_URL, imageURL); - } - - public void setAlt(String alt) { - Assert.isUnlocked(this); - setAttribute(ALT, alt); - } - /** - * - * - * @param height - */ - public void setHeight(String height) { - Assert.isUnlocked(this); - setAttribute(HEIGHT, height); - } - - /** - * - * - * @param width - */ - public void setWidth(String width) { - Assert.isUnlocked(this); - setAttribute(WIDTH, width); - } - - /** - * - * - * @param border - */ - public void setBorder(String border) { - Assert.isUnlocked(this); - setAttribute(BORDER, border); - } - - /** - * Adds a print listener. Only one print listener can be set for an - * image, since the PrintListener is expected to modify the - * target of the PrintEvent. - * @param listener the print listener - * @throws IllegalArgumentException if listener is null. - * @throws IllegalStateException if a print listener has previously been - * added. - * @pre listener != null */ - public void addPrintListener(PrintListener listener) - throws IllegalStateException, IllegalArgumentException - { - if ( listener == null ) { - throw new IllegalArgumentException - ("Argument listener can not be null"); - } - if ( m_printListener != null ) { - throw new IllegalStateException - ("Too many listeners. Can only have one"); - } - m_printListener = listener; - } - - /** - * Removes a previously added print listener. If listener is - * not the listener that was added with {@link #addPrintListener - * addPrintListener}, an IllegalArgumentException will be thrown. - * @param listener the listener that was previously added with - * addPrintListener - * @throws IllegalArgumentException if listener is not the - * currently registered print listener or is null. - * @pre listener != null - */ - public void removePrintListener(PrintListener listener) - throws IllegalArgumentException - { - if ( listener == null ) { - throw new IllegalArgumentException("listener can not be null"); - } - if ( listener != m_printListener ) { - throw new IllegalArgumentException - ("listener is not registered with this widget"); - } - m_printListener = null; - } - - /** - * Writes the output to a DOM to be used with the XSLT template - * to produce the appropriate output. - * - *

Generates DOM fragment: - *

-     * <bebop:image [src=...] [alt=...] [height=...]
-     *       [width=...] [border=...]/>
-     * 
- * - * @param parent the XML element to which the form adds its XML representation - * */ - @Override - public void generateXML(PageState state, Element parent) { - - if ( ! isVisible(state) ) { - return; - } - - Image target = firePrintEvent(state); - Element image = parent.newChildElement ("bebop:image", BEBOP_XML_NS); - target.exportAttributes(image); - } - - protected Image firePrintEvent(PageState state) { - Image i = this; - if ( m_printListener != null ) { - try { - i = (Image) this.clone(); - m_printListener.prepare(new PrintEvent(this, state, i)); - } catch ( CloneNotSupportedException e ) { - // FIXME: Failing silently here isn't so great - // It probably indicates a serious programming error - i = this; - } - } - return i; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Label.java b/ccm-core/src/main/java/com/arsdigita/bebop/Label.java deleted file mode 100755 index 1895d5e68..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Label.java +++ /dev/null @@ -1,447 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.util.Assert; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.xml.Element; - -/** - * A text label displayed to the user for information about and identification - * of certain parts of the screen. Therefore the label has to use a - * GlobalizedMessage for the information presented. - * - * A Label is meant to provide semantically relevant information and may not be - * used for fixed arbitrary Text. Use Embedded instead. - * - * (Previous usage: can be used to generate either some static, fixed - * text or a new text string for every request.) - * - * To modify the information with an already locked label use the {@link - * #setLabel(String,PageState)} method which can adjust for each request. - * - * @author David Lutterkort - * @version $Id: Label.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class Label extends DescriptiveComponent implements Cloneable { - - public static final String BOLD = "b"; - public static final String ITALIC = "i"; - - // the default label - private GlobalizedMessage m_label; - // a requestlocal set of labels (to avoid printlisteners) - private final RequestLocal m_requestLabel = new RequestLocal(); - private String m_fontWeight; - - /** The setting for output escaping affects how markup in the - * content is handled. - *
  • If output escaping is in effect (true), <b>example</b> - * will appear literally.
  • - *
  • If output escaping is disabled, <b>example</b> appears as the - * String "example" in bold (i.e. retaining the markup.
- * Default is false. */ - private boolean m_escaping = false; // default for a primitive anyway - private PrintListener m_printListener; - - /** - * Constructor creates a new Label with empty text. - */ - public Label() { - // A kind of fallback (or a hack) here. Parameter label is taken as - // a key for some (unknown) Resource bundle. Because GlobalizedMessage - // will not find a corrresponding message it will display the key - // itself, 'faking' a globalized message. - m_label = new GlobalizedMessage(" "); - } - - /** - * Creates a new Label with the specified (fixed) text. - * - * @param label the text to display - * @deprecated refactor to use Label(GlobalizedMessage label) instead - */ - public Label(String label) { - this(label, true); - } - - /** - * Creates a new Label with the specified text and - * output escaping turned on if escaping is true. - * - * The setting for output escaping affects how markup in the - * label is handled. For example: - *
  • If output escaping is in effect, <b>text</b> will appear - * literally.
  • - *
  • If output escaping is disabled, <b>text</b> appears as the - * word "text" in bold.
- * - * @param label the text to display - * @param escaping true if output escaping will be in effect; - * false if output escaping will be disabled - * - * @deprecated refactor to Label(GlobalizedMessage label, boolean escaping) - * instead - */ - public Label(String label, boolean escaping) { - setLabel(label); - setOutputEscaping(escaping); - } - - /** - *

Creates a new label with the specified text.

- * - * @param label the text to display - */ - public Label(GlobalizedMessage label) { - this(label, true); - } - - /** - * Creates a new label with the specified text as GlobalizedMessage - * and fontweight. - * - * @param label The text to display as GlobalizedMessage - * @param fontWeight The fontWeight e.g., Label.BOLD. Whether it has any - * effect depends on the theme! Take it just as a hint. - */ - public Label(GlobalizedMessage label, String fontWeight) { - this(label, true); - m_fontWeight = fontWeight; - } - - /** - *

Creates a new label with the specified text as GlobalizedMessage - * and output escaping turned on if escaping is - * true.

- * - * @param label the text to display as GlobalizedMessage - * @param escaping Whether or not to perform output escaping - */ - public Label(GlobalizedMessage label, boolean escaping) { - setLabel(label); - setOutputEscaping(escaping); - } - - /** - * Creates a new Label that uses the print listener to - * generate output. - * - * @param l the print listener used to produce output - */ - public Label(PrintListener l) { - this(); - addPrintListener(l); - } - - /** - * Creates a new label with the specified text and fontweight. - * - * @param label The text to display - * @param fontWeight The fontWeight e.g., Label.BOLD - * - * @deprecated without direct replacement. Refactor to use - * Label(GlobalizedMEssage) instead and modify the theme to - * use proper text marking. (Or use setFontWeight separately. - */ - public Label(String label, String fontWeight) { - this(label, true); - m_fontWeight = fontWeight; - } - - /** - * Provides the Label as Text, localized for the current request. - * - * Although it is not recommended, this method may be overridden to - * dynamically generate the text of the label. Overriding code may need - * the page state. - *

- * If possible, derived classes should override {@link #getLabel()} instead, - * which is called from this method. As long as we don't have a static - * method to obtain ApplicationContext, this is a way to get the - * RequestContext (to determine the locale). When ApplicationContext gets - * available, that will become the suggested way for overriding code to get - * context. - * - * @param state the current page state - * @return the string produced for this label - */ - public String getLabel(PageState state) { - return (String) getGlobalizedMessage(state).localize(state.getRequest()); - } - - // /** - // * . - // * - // * This method may be overridden to dynamically generate the default text of - // * the label. - // * - // * @return the string produced for this label. - // * - // * @deprecated Use {@link #getGlobalizedMessage()} - // */ - // Conflicts with Super's getLabel message of type GlobalizedMessage. But isn't - // needed anyway. Should deleted as soon as the refactoring of Label is - // completed (i.e. any string Label ironed out). - // public String getLabel() { - // return getGlobalizedMessage().getKey(); - // } - - /** - *

This should really be getLabel(), but since it was marked STABLE I - * can't change its return type.

- * - * @return the default label to display. - */ - public GlobalizedMessage getGlobalizedMessage() { - return getGlobalizedMessage(null); - } - - /** - *

This should really be getLabel(), but since it was marked STABLE I - * can't change its return type.

- * - * @param state the current PageState - * @return the label to display for this request, or if state is null, the - * default label - */ - public GlobalizedMessage getGlobalizedMessage(PageState state) { - if (state != null) { - GlobalizedMessage dynlabel = - (GlobalizedMessage) m_requestLabel.get(state); - if (dynlabel != null) { - return dynlabel; - } - } - return m_label; - } - - /** - * Sets new default text for this Label. - * - * @param label The new label text; will be used as a key into the current - * ResourceBundle if possible, or displayed literally. - * @deprecated refactor to use - * @see setLabel(GlobalizedMessage) instead! - */ - public void setLabel(String label) { - setLabel(label, null); - } - - /** - * Sets new request-specific text for this Label to use on this request. If - * state is null, then sets the default text instead. - * - * @param label The new label text; will be used as a key into the current - * ResourceBundle if possible, or displayed literally. - * @param state the page state - * @pre state == null implies !isLocked() - * @deprecated refactor to use - * @see setLabel(GlobalizedMessage, PageState) instead! - */ - public void setLabel(String label, PageState state) { - if (label == null || label.length() == 0) { - label = " "; - } - // A kind of fallback (or a hack) here. Parameter label is taken as - // a key for some (unknown) Resource bundle. Because GlobalizedMessage - // will not find a corrresponding message it will display the key - // itself, 'faking' a globalized message. - setLabel(new GlobalizedMessage(label), state); - } - - /** - * Sets the text for this label using a GlobalizedMessage. - * - * @param label The GlobalizedMessage containing the label text or the - * lookup key to use in the ResourceBundle - * @param state the current page state; if null, sets the default text for - * all requests. - * @pre state == null implies !isLocked() - */ - public void setLabel(GlobalizedMessage label, PageState state) { - if (state == null) { - Assert.isUnlocked(this); - m_label = label; - } else { - m_requestLabel.set(state, label); - } - } - - /** - * Sets the default text for this Label. - * - * Overwrites parent's method an therefore prevents the usage of parent's - * label methods (which are attributes, but here it is the content). - * - * @param label The GlobalizedMessage containing the label text or the - * lookup key to use in the ResourceBundle - */ - @Override - public void setLabel(GlobalizedMessage label) { - setLabel(label, null); - } - - public final boolean getOutputEscaping() { - return m_escaping; - } - - /** - * Controls whether output is escaped during transformation, by default - * true. If true, it will be printed literally, and the user will see - * <b>. When false, the browser will interpret as a bold tag. - * - * @param escaping - */ - public final void setOutputEscaping(boolean escaping) { - m_escaping = escaping; - } - - public final String getFontWeight() { - return m_fontWeight; - } - - public void setFontWeight(String fontWeight) { - Assert.isUnlocked(this); - m_fontWeight = fontWeight; - } - - /** - * Adds a print listener. Only one print listener can be set for a label, - * since the PrintListener is expected to modify the target - * of the PrintEvent. - * - * @param listener the print listener - * @throws IllegalArgumentException if listener is null. - * @throws IllegalStateException if a print listener has previously been - * added. - * @pre listener != null - */ - public void addPrintListener(PrintListener listener) - throws IllegalStateException, IllegalArgumentException { - if (listener == null) { - throw new IllegalArgumentException("Argument listener can not be null"); - } - if (m_printListener != null) { - throw new IllegalStateException("Too many listeners. Can only have one"); - } - m_printListener = listener; - } - - /** - * Removes a previously added print listener. If listener is - * not the listener that was added with {@link #addPrintListener - * addPrintListener}, an IllegalArgumentException will be thrown. - * - * @param listener the listener that was added with - * addPrintListener - * @throws IllegalArgumentException if listener is not the - * currently registered print listener or is null. - * @pre listener != null - */ - public void removePrintListener(PrintListener listener) - throws IllegalArgumentException { - if (listener == null) { - throw new IllegalArgumentException("listener can not be null"); - } - if (listener != m_printListener) { - throw new IllegalArgumentException("listener is not registered with this widget"); - } - m_printListener = null; - } - - /** - * Generates the (J)DOM fragment for a label. - *

-     * <bebop:link href="..." type="..." %bebopAttr;/>
-     * 
- * - * @param state The current {@link PageState}. - * @param parent The XML element to attach the XML to. - */ - @Override - public void generateXML(PageState state, Element parent) { - - if (!isVisible(state)) { - return; - } - - Label target = firePrintEvent(state); - - Element label = parent.newChildElement("bebop:label", BEBOP_XML_NS); - - target.exportAttributes(label); - target.generateDescriptionXML(state, label); - - String weight = target.getFontWeight(); - if (weight != null && weight.length() > 0) { - label.addAttribute("weight", weight); - } - - if (!target.m_escaping) { - label.addAttribute("escape", "yes"); - } else { - label.addAttribute("escape", "no"); - } - - String key = getGlobalizedMessage() - .getKey() - .substring(getGlobalizedMessage() - .getKey().lastIndexOf(".") + 1); - - // This if clause is needed to prevent printing of keys if the - // GlobalizedMessage was created from a String by this class - if(!key.equals(target.getLabel(state))) { - label.addAttribute("key", key); - } - - /* - * This may break with normal JDOM. We may need to have a node for - * the case where there is no weight. The problem comes in that - * setText *may* kill the other content in the node. It will kill - * the other text, so it may be a good idea anyways. - */ - label.setText(target.getLabel(state)); - } - - /** - * - * @param state - * @return - */ - protected Label firePrintEvent(PageState state) { - Label l = this; - - if (m_printListener != null) { - try { - l = (Label) this.clone(); - m_printListener.prepare(new PrintEvent(this, state, l)); - } catch (CloneNotSupportedException e) { - throw new RuntimeException( - "Couldn't clone Label for PrintListener. " - + "This probably indicates a serious programming error: " - + e.getMessage()); - } - } - - return l; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Link.java b/ccm-core/src/main/java/com/arsdigita/bebop/Link.java deleted file mode 100644 index dfb29fe54..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Link.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.arsdigita.xml.Element; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.util.Assert; -import com.arsdigita.web.URL; -import com.arsdigita.web.ParameterMap; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * A URL on a page. May contain a label, an image, or any other component. A - * Link is a BaseLink that manages URL variables. - * - *

- * Example: The common usage for a Link component is illustrated in the - * code fragment below: - * - *

- *  Page p = new Page("Link Example");
- *  Link link = new Link(new Label(GlobalizedMessage),"path/to/target/");
- *  link.setVar("foo","1");
- *  p.add(link);
- * 
- * - *

- * The target of the link above will be rendered in HTML as: - * href="path/to/target/?foo=1" - * If either the link text or the URL needs to be changed for a link within a - * locked page, a {@link PrintListener} should be used. - */ -public class Link extends BaseLink { - - private static final Logger LOGGER = LogManager - .getLogger(ParameterMap.class); - - private static final String FRAME_TARGET_ATTR = "target"; - - private URL m_webURL = null; - private ParameterMap m_params = new ParameterMap(); - - /** - * The value for the XML type attribute for a plain link. - */ - protected final String TYPE_LINK = "link"; - - /** - *

- * Passing this value to {@link #setTargetFrame setTargetFrame} will create - * a link that opens a new browser window whenever it is clicked. - *

- * - * @see #setTargetFrame - */ - public static final String NEW_FRAME = "_blank"; - - /** - * initialization steps common to all constructors - */ - private void init() { - setTypeAttr(TYPE_LINK); - } - - /** - * Constructor creates a link taking url as the target and display it to the - * user at the same time. It is the only allowed way to present the user - * with a not globlized information. The implementation currently miss-uses - * the Label component to display just a not globalized String which is - * deprecated. - * - * @param url - * - * @deprecated use BaseLink(Component,url) instead with a Label using a - * GlobalizedMessage instead - */ - public Link(final String url) { - super(new Label(url), url); - } - - /** - * Constructor, creates a link with a globalized label or an image as label. - * - * @param child The Component parameter in this constructor is - * usually a {@link Label} or {@link Image}. - * @param url Starting with release 5.2, this method prefixes the - * passed-in url with the path to the CCM dispatcher. Code - * using this constructor should not prefix url - * with the webapp context path or the dispatcher servlet path. - * - * The vast majority of CCM UI code expects to link through the dispatcher. - * Code that does not should use the Link constructor taking a - * URL. - * - * @see #Link(String,URL) - */ - public Link(Component child, String url) { - super(child, url); - init(); - } - - /** - * Constructors with PrintListener parameters allow for a - * {@link PrintListener} to be set for the Link, without the need to make a - * separate call to the addPrintListener method. PrintListeners are - * a convenient way to alter underlying Link attributes such as Link text or - * target URL within a locked page on a per request basis. - * - * @param child - * @param l - */ - public Link(Component child, PrintListener l) { - super(child, l); - - init(); - } - - /** - * Constructors with PrintListener parameters allow for a - * {@link PrintListener} to be set for the Link, without the need to make a - * separate call to the addPrintListener method. PrintListeners are - * a convenient way to alter underlying Link attributes such as Link text or - * target URL within a locked page on a per request basis. - * - * @deprecated refactor to use Link(Component,PrintListener) to provide a - * globalized label for the link. - */ - public Link(String label, PrintListener l) { - super(label, l); - - init(); - } - - /** - * Constructors with PrintListener parameters allow for a - * {@link PrintListener} to be set for the Link, without the need to make a - * separate call to the addPrintListener method. PrintListeners are - * a convenient way to alter underlying Link attributes such as Link text or - * target URL within a locked page on a per request basis. - * - * @param listener PrintListener, may be used to change either the Display - * text or the url within a locked page. - */ - public Link(PrintListener listener) { - super(listener); - - init(); - } - - /** - *

- * This constructor is a common one for a Link component, as it allows for - * the Link text and the target URL to be set at the same time during - * construction.

- * - *

- * Starting with release 5.2, this method prefixes the passed-in - * url with the path to the CCM dispatcher. Code using this - * constructor should not prefix url with the webapp context - * path or the dispatcher servlet path.

- * - *

- * The vast majority of CCM UI code expects to link through the dispatcher. - * Code that does not should use the Link constructor taking a - * URL.

- * - * @see #Link(String,URL) - * @deprecated refactor to use Link(Component,PrintListener) to provide a - * globalized label for the link. - */ - public Link(String label, String url) { - super(label, url); - - init(); - } - - /** - *

- * Constructs a Link using a URL. When this constructor is - * used, the method {@link #setVar(String,String)} and its deprecated - * equivalent have no effect on the resulting hyperlink. Instead, use the - * ParameterMap argument to URL.

- * - * @see com.arsdigita.web.URL - * @see com.arsdigita.web.ParameterMap - * @param label a String of label text - * @param url a URL for the link's target - * - * @deprecated refactor to use Link(Component,URL) to provide a globalized - * label for the link. - */ - public Link(String label, URL url) { - super(label, url.toString()); - - init(); - - m_webURL = url; - } - - @Override - public Object clone() throws CloneNotSupportedException { - Link result = (Link) super.clone(); - - result.m_params = (ParameterMap) m_params.clone(); - - return result; - } - - /** - * Sets a query variable and its value. Overwrites any values that may have - * been set previously under the specified name. - *

- * All the variables set with this method are appended to the query string - * in the URL that is output for this Link. - * - * @param name the name of the query - * @param value the value for the query - * - * @pre name != null - */ - public void setVar(String name, String value) { - Assert.isUnlocked(this); - - m_params.setParameter(name, value); - } - -// No longer used anywhere in the code base -// /** -// * Set a query variable and its value -// * @deprecated use {@link #setVar setVar} -// */ -// public void addURLVars(String name, String value) { -// setVar(name, value); -// } - /** - * - * @return may be this method should be deprecated as well as addURLVars? - */ - public String getURLVarString() { - return m_params.toString(); - } - - /** - *

- * Get the "target" attribute of the link, which determines which browser - * frame will load the new page when this link is clicked.

- */ - public String getTargetFrame() { - return getAttribute(FRAME_TARGET_ATTR); - } - - /** - *

- * Set the "target" attribute of the link, which determines which browser - * frame will load the new page when this link is clicked.

- */ - public void setTargetFrame(String frameName) { - setAttribute(FRAME_TARGET_ATTR, frameName); - } - - /** - * - * @param state - * @param parent - */ - protected void generateURL(PageState state, Element parent) { - parent.addAttribute("href", prepareURL(state, getTarget())); - - exportAttributes(parent); - } - - /** - * Processes the URL for this link after the print listener runs. - * - * @param location the original URL - * - * @return the URL appended with ACS-specific URL parameters. - */ - protected String prepareURL(final PageState state, String location) { - - final HttpServletRequest req = state.getRequest(); - final HttpServletResponse resp = state.getResponse(); - - if (m_webURL == null) { - m_params.runListeners(req); - - if (location.startsWith("/")) { - location = URL.getDispatcherPath() + location; - } - - if (location.indexOf("?") == -1) { - // m_params adds the "?" as needed. - - return resp.encodeURL(location + m_params); - } else { - // The location already includes a query string, so - // append to it without including a "?". - - if (location.endsWith("&")) { - return resp.encodeURL(location + m_params.getQueryString()); - } else { - return resp.encodeURL(location + "&" + m_params - .getQueryString()); - } - } - } else { - return m_webURL.toString(); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/List.java b/ccm-core/src/main/java/com/arsdigita/bebop/List.java deleted file mode 100755 index 0047ec30f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/List.java +++ /dev/null @@ -1,877 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; - -import javax.servlet.ServletException; - -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.list.ListCellRenderer; -import com.arsdigita.bebop.list.DefaultListCellRenderer; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.event.EventListenerList; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.util.Assert; -import com.arsdigita.bebop.util.BebopConstants; - -import com.arsdigita.xml.Element; - -/** - * A List, similar to a javax.swing.JList, that keeps - * track of a sequence of items and selections of one or more of these items. A - * separate model, {@link ListModel}, is used to represent the items in the - * list. - * - * @see ListModel - * @see ListModelBuilder - * @see com.arsdigita.bebop.list.ListCellRenderer - * @author David Lutterkort - * @version $Id: List.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class List extends SimpleComponent implements BebopConstants { - - /** - * The name of the StringParameter that the list uses to keep track of which - * item is selected. - */ - public static final String SELECTED = "sel"; - - /** - * The name of the event the list sets when producing links that change - * which item is selected. - */ - public static final String SELECT_EVENT = "s"; - - /** - * The model builder for this list. Is used to produce a new model for each - * request served by this List. - * - * @see #setListModelBuilder - * @see ArrayListModelBuilder - * @see MapListModelBuilder - */ - private ListModelBuilder m_modelBuilder; - - private RequestLocal m_model; - - /** - * The renderer used to format list items. - * - * @see DefaultListCellRenderer - */ - private ListCellRenderer m_renderer; - - private EventListenerList m_listeners; - - private SingleSelectionModel m_selection; - - private ChangeListener m_changeListener; - - private Component m_emptyView; - - private boolean m_stateParamsAreRegistered; - - /** - *

- * Vertical List layout.

- * - */ - public static final int VERTICAL = 0; - - /** - *

- * Horizontal List layout.

- * - */ - public static final int HORIZONTAL = 1; - - private int m_layout = VERTICAL; - - /** - * Creates a new List that uses the specified list model - * builder to generate per-request {@link ListModel ListModels}. - * - * @param b the model builder used for this list - * - * @pre b != null - */ - public List(ListModelBuilder b) { - this(); - m_modelBuilder = b; - m_emptyView = null; - } - - /** - * Creates an empty List. - */ - public List() { - // Force the use of the 'right' constructor - this((SingleSelectionModel) null); - m_selection = new ParameterSingleSelectionModel(new StringParameter( - SELECTED)); - } - - /** - * Create an empty List. - */ - public List(SingleSelectionModel selection) { - // This is the real constructor. All other constructors must call it - // directly or indirectly - super(); - m_renderer = new DefaultListCellRenderer(); - m_listeners = new EventListenerList(); - m_selection = selection; - setListData(new Object[0]); - initListModel(); - m_emptyView = null; - m_stateParamsAreRegistered = true; - } - - /** - * Creates a new List from an array of objects. Uses an - * internal {@link ListModelBuilder}. Each {@link ListModel} that is built - * will iterate through the entries of the object, returning the objects - * from calls to {@link ListModel#getElement} and the corresponding index, - * which is converted to a String from calls to {@link - * ListModel#getKey}. - * - * @param values an array of items - * - * @pre values != null - * @see #setListData(Object[] v) - */ - public List(Object[] values) { - this(); - setListData(values); - } - - /** - * Creates a new List from a map. Uses an internal {@link - * ListModelBuilder}. Each {@link ListModel} that is built will iterate - * through the entries in map in the order in which they are - * returned by map.entrySet().iterator(). Calls to {@link - * ListModel#getElement} return one value in map. Calls to - * {@link ListModel#getElement} return the corresponding key, which is - * converted to a String by calling toString() on - * the key. - * - * @param map a key-value mapping for the list items - * - * @pre map != null - */ - public List(Map map) { - this(); - setListData(map); - } - - /** - * Registers this List and its state parameter(s) with the - * specified page. - * - * @param p the page this list is contained in - * - * @pre p != null - * @pre ! isLocked() - */ - public void register(Page p) { - Assert.isUnlocked(this); - if (m_selection.getStateParameter() != null) { - p.addComponentStateParam(this, m_selection.getStateParameter()); - } - } - - /** - * Responds to a request in which this List was the targetted - * component. Calls to this method should only be made through links - * generated by this list. - * - *

- * Determines the new selected element and fires a {@link - * ChangeEvent} if it has changed. After that, fires an {@link - * ActionEvent}. - * - * @param state the state of the current request - * - * @throws ServletException if the control event is unknown. - * @pre state != null - * @see #fireStateChanged fireStateChanged - * @see #fireActionEvent fireActionEvent - */ - public void respond(PageState state) throws ServletException { - String event = state.getControlEventName(); - - if (SELECT_EVENT.equals(event)) { - setSelectedKey(state, state.getControlEventValue()); - } else { - throw new ServletException("Unknown event '" + event + "'"); - } - fireActionEvent(state); - } - - /** - * Allow subclasses to override how the layout is determined. - * - * @param list - */ - protected void exportLayoutAttribute(final Element list) { - if (m_layout == VERTICAL) { - list.addAttribute("layout", "vertical"); - } else { - list.addAttribute("layout", "horizontal"); - } - } - - protected String getTagName() { - return BEBOP_LIST; - } - - protected String getTagXMLNS() { - return BEBOP_XML_NS; - } - - /** - * Generates XML representing the items in the list. The items are formatted - * using a {@link ListCellRenderer}. generateXML is called on - * each component returned by the renderer. - * - *

- * The XML that is generated has the following form: - *

-     *   <bebop:list mode="single" %bebopAttr;>
-     *     <bebop:cell [selected="selected"] key="itemKey">
-     *        ... XML generated for component returned by renderer ...
-     *     </bebop:cell>
-     *     ... more <bebop:cell> elements, one for each list item ...
-     *   </bebop:list>
- * - * @param state the state of the current request - * @param parent the element into which XML is generated - * - * @pre state != null - * @pre parent != null - * @see com.arsdigita.bebop.list.ListCellRenderer - */ - public void generateXML(PageState state, Element parent) { - - if (!isVisible(state)) { - return; - } - - ListModel m = getModel(state); - - // Check if there are items in the list - if (m.next()) { - - // The list has items - Element list = parent.newChildElement(getTagName(), getTagXMLNS()); - exportAttributes(list); - -// if (m_layout == VERTICAL) { -// list.addAttribute("layout", "vertical"); -// } else { -// list.addAttribute("layout", "horizontal"); -// } - exportLayoutAttribute(list); - - Component c; - - Object selKey; - if (getStateParamsAreRegistered()) { - selKey = getSelectedKey(state); - } else { - selKey = null; - } - - int i = 0; - do { - Element item = list.newChildElement(BEBOP_CELL, BEBOP_XML_NS); - - String key = m.getKey(); - Assert.exists(key); - - // Converting both keys to String for comparison - // since ListModel.getKey returns a String - boolean selected = (selKey != null) && key.equals(selKey - .toString()); - - item.addAttribute("key", key); - if (selected) { - item.addAttribute("selected", "selected"); - } - if (getStateParamsAreRegistered()) { - state.setControlEvent(this, SELECT_EVENT, key); - } - c = getCellRenderer().getComponent(this, state, m.getElement(), - key, i, selected); - c.generateXML(state, item); - i += 1; - } while (m.next()); - - } else { - // The list has no items - if (m_emptyView != null) { - // Display the empty view - m_emptyView.generateXML(state, parent); - } else { - // For compatibility reasons, generate an empty - // list element. In the future, this should go away - Element list = parent.newChildElement(BEBOP_LIST, BEBOP_XML_NS); - exportAttributes(list); - } - } - - state.clearControlEvent(); - } - - /** - *

- * Retrieve the current List layout.

- * - * @return List.VERTICAL or List.HORIZONTAL - * - */ - public int getLayout() { - return m_layout; - } - - /** - *

- * Set the current List layout.

- * - * @param layout New layout value, must be List.VERTICAL or List.HORIZONTAL - * - */ - public void setLayout(int layout) { - Assert.isUnlocked(this); - Assert.isTrue((layout == VERTICAL) || (layout == HORIZONTAL), - "Invalid layout code passed to setLayout"); - m_layout = layout; - } - - /** - * This method is part of a mechanism to freakishly allow List's to be used - * as parent classes for components that do not have their state params - * registered with the page. An example of a situation like this is Form - * ErrorDisplay being used in a Metaform - */ - public void setStateParamsAreRegistered(boolean val) { - m_stateParamsAreRegistered = val; - } - - public boolean getStateParamsAreRegistered() { - return m_stateParamsAreRegistered; - } - - /** - * Returns the renderer currently used for rendering list items. - * - * @return the current list cell renderer. - * - * @see #setCellRenderer setCellRenderer - * @see com.arsdigita.bebop.list.ListCellRenderer - */ - public final ListCellRenderer getCellRenderer() { - return m_renderer; - } - - /** - * Sets the cell renderer to be used when generating output with or - * {@link #generateXML generateXML}. - * - * @param r a ListCellRenderer value - * - * @pre r != null - * @pre ! isLocked() - * @see com.arsdigita.bebop.list.ListCellRenderer - */ - public final void setCellRenderer(ListCellRenderer r) { - Assert.isUnlocked(this); - m_renderer = r; - } - - /** - * Returns the model builder currently used to build each request-specific - * {@link ListModel}. - * - * @return a ListModelBuilder value. - * - * @see #setModelBuilder setModelBuilder - * @see ListModelBuilder - */ - public final ListModelBuilder getModelBuilder() { - return m_modelBuilder; - } - - /** - * Sets the model builder used to build each request-specific - * {@link ListModel}. - * - * @param b a ListModelBuilder value - * - * @pre ! isLocked() - * @see ListModelBuilder - */ - public final void setModelBuilder(ListModelBuilder b) { - Assert.isUnlocked(this); - m_modelBuilder = b; - } - - /** - * Sets the empty view component, which is shown if there are no items in - * the list. This component must be stateless. For example, it could be an - * Image or a Label. - * - * @param c the new empty view component - */ - public final void setEmptyView(Component c) { - Assert.isUnlocked(this); - m_emptyView = c; - } - - /** - * Gets the empty view component. The empty view component is shown if there - * are no items in the list. - * - * @return the empty view component. - */ - public final Component getEmptyView() { - return m_emptyView; - } - - /** - * Initialize the private m_model variable. The initial value - * is what the model builder returns for the state. - */ - private void initListModel() { - m_model = new RequestLocal() { - - protected Object initialValue(PageState s) { - return getModelBuilder().makeModel(List.this, s); - } - - }; - } - - /** - * Gets the list model used in processing the request represented by - * state. - * - * @param state the state of the current request - * - * @return the list model used in processing the request represented by - * state. - */ - public ListModel getModel(PageState state) { - return (ListModel) m_model.get(state); - } - - /** - * Sets the list to use for the values in values. Each {@link - * ListModel} that is built will iterate through the entries of the object, - * returning the objects from calls to {@link ListModel#getElement} and the - * corresponding index, which is converted to a String from - * calls to {@link ListModel#getKey}. - * - * @param values an array of items - * - * @pre values != null - * @pre ! isLocked() - */ - public void setListData(Object[] values) { - Assert.isUnlocked(this); - m_modelBuilder = new ArrayListModelBuilder(values); - } - - /** - * Sets the list to use the entries in map. Each {@link - * ListModel} that is built will iterate through the entries in - * map in the order in which they are returned by - * map.entrySet().iterator(). Calls to {@link - * ListModel#getElement} return one value in map. Calls to - * {@link ListModel#getElement} return the corresponding key, which is - * converted to a String by calling toString() on - * the key. - * - * @param map a key-value mapping for the list items - * - * @pre map != null - * @pre ! isLocked() - */ - public void setListData(Map map) { - Assert.isUnlocked(this); - m_modelBuilder = new MapListModelBuilder(map); - } - - /** - * Gets the selection model. The model keeps track of which list item is - * currently selected, and can be used to manipulate the selection - * programmatically. - * - * @return the model used by the list to keep track of the selected list - * item. - */ - public final SingleSelectionModel getSelectionModel() { - return m_selection; - } - - /** - * Sets the selection model that the list uses to keep track of the - * currently selected list item. - * - * @param m the new selection model - * - * @pre m != null - * @pre ! isLocked() - */ - public final void setSelectionModel(SingleSelectionModel m) { - Assert.isUnlocked(this); - if (m_changeListener != null) { - // Transfer the change listener - m_selection.removeChangeListener(m_changeListener); - m.addChangeListener(m_changeListener); - } - m_selection = m; - } - - /** - * Gets the key for the selected list item. This will only be a valid key if - * {@link #isSelected isSelected} is true. - * - * @param state the state of the current request - * - * @return the key for the selected list item. - * - * @pre isSelected(state) - */ - public Object getSelectedKey(PageState state) { - return m_selection.getSelectedKey(state); - } - - /** - * Sets the selection to the one with the specified key. If key - * was not already selected, fires the {@link - * ChangeEvent}. - * - * @param state the state of the current request - * @param key the key for the selected list item - * - * @see #fireStateChanged fireStateChanged - */ - public void setSelectedKey(PageState state, String key) { - m_selection.setSelectedKey(state, key); - } - - /** - * Returns true if one of the list items is currently selected. - * - * @param state the state of the current request - * - * @return true if one of the list items is selected - * false otherwise. - */ - public boolean isSelected(PageState state) { - return m_selection.isSelected(state); - } - - /** - * Clears the selection in the request represented by state. - * - * @param state the state of the current request - * - * @post ! isSelected(state) - */ - public void clearSelection(PageState state) { - m_selection.clearSelection(state); - } - - /** - * Creates the change listener that is used for forwarding change events - * fired by the selection model to change listeners registered with the - * list. The returned change listener refires the event with the list, - * rather than the selection model, as source. - * - * @return the change listener used internally by the list. - */ - protected ChangeListener createChangeListener() { - return new ChangeListener() { - - public void stateChanged(ChangeEvent e) { - fireStateChanged(e.getPageState()); - } - - }; - } - - /** - * Adds a change listener. A change event is fired whenever the selected - * list item changes during the processing of a request. The change event - * that listeners receive names the list as the source. - * - * @param l the change listener to run when the selected item changes in a - * request - * - * @pre ! isLocked() - */ - public void addChangeListener(ChangeListener l) { - Assert.isUnlocked(this); - if (m_changeListener == null) { - m_changeListener = createChangeListener(); - m_selection.addChangeListener(m_changeListener); - } - m_listeners.add(ChangeListener.class, l); - } - - /** - * Removes a change listener. The listener should have been previously added - * with {@link #addChangeListener addChangeListener}, although no error is - * signalled if the change listener is not found among the list's listeners. - * - * @param l the change listener to remove from the list - */ - public void removeChangeListener(ChangeListener l) { - Assert.isUnlocked(this); - m_listeners.remove(ChangeListener.class, l); - } - - /** - * Fires a change event to signal that the selected list item has changed in - * the request represented by state. The source of the event is - * the list. - * - * @param state the state of the current request - */ - protected void fireStateChanged(PageState state) { - Iterator i = m_listeners.getListenerIterator(ChangeListener.class); - ChangeEvent e = null; - - while (i.hasNext()) { - if (e == null) { - e = new ChangeEvent(this, state); - } - ((ChangeListener) i.next()).stateChanged(e); - } - } - - // Action events - /** - * Adds an action listener. This method is run whenever - * {@link #respond respond} is called on the list. This gives clients a way - * to track mouse clicks received by the list. - * - * @param 1 the action listener to add - * - * @pre l != null - * @pre ! isLocked() - * @see #respond respond - */ - public void addActionListener(ActionListener l) { - Assert.isUnlocked(this); - m_listeners.add(ActionListener.class, l); - } - - /** - * Removes a previously added action listener. - * - * @param 1 the action listener to remove - * - * @see #addActionListener addActionListener - */ - public void removeActionListener(ActionListener l) { - Assert.isUnlocked(this); - m_listeners.remove(ActionListener.class, l); - } - - /** - * Fires an action event signalling that the list received the request - * submission. All registered action listeners are run. The source of the - * event is the list. - * - * @param state the state of the current request - * - * @pre state != null - * @see #respond respond - */ - protected void fireActionEvent(PageState state) { - Iterator i = m_listeners.getListenerIterator(ActionListener.class); - ActionEvent e = null; - - while (i.hasNext()) { - if (e == null) { - e = new ActionEvent(this, state); - } - ((ActionListener) i.next()).actionPerformed(e); - } - } - - // ListModelBuilder for maps - /** - * Build list models from a map. The list models use the result of - * toString() called on the key of the map entries as their - * keys and return the associated value as the element for the list items - * the list model iterates over. - */ - private static class MapListModelBuilder implements ListModelBuilder { - - private Map m_map; - private boolean m_locked; - - public MapListModelBuilder() { - this(Collections.EMPTY_MAP); - } - - public MapListModelBuilder(Map m) { - m_map = m; - } - - public ListModel makeModel(List l, PageState state) { - return new ListModel() { - - private Iterator i = m_map.entrySet().iterator(); - private Map.Entry e = null; - - public boolean next() { - if (!i.hasNext()) { - e = null; - return false; - } - e = (Map.Entry) i.next(); - return true; - } - - public Object getElement() { - checkState(); - return e.getValue(); - } - - public String getKey() { - checkState(); - return e.getKey().toString(); - } - - private void checkState() { - if (e == null) { - throw new IllegalStateException( - "No valid current item. " - + "Model is either before first item or after last item"); - } - } - - }; - } - - public void lock() { - m_locked = true; - } - - public final boolean isLocked() { - return m_locked; - } - - } - - // ListModelBuilder for arrays - /** - * Build list models from an array of values. The list models use the index - * of the array entries, converted to a String, as the key for - * the list items and the array values as their elements. - */ - private static class ArrayListModelBuilder implements ListModelBuilder { - - private Object[] m_values; - private boolean m_locked; - - public ArrayListModelBuilder() { - this(new Object[0]); - } - - public ArrayListModelBuilder(Object[] values) { - m_values = values; - } - - public ListModel makeModel(List l, PageState state) { - return new ListModel() { - - private int i = -1; - - public boolean next() { - i += 1; - return (i < m_values.length); - } - - public Object getElement() { - checkState(); - return m_values[i]; - } - - public String getKey() { - checkState(); - return String.valueOf(i); - } - - private void checkState() { - if (i < 0) { - throw new IllegalStateException( - "Before first item. Call next() first."); - } - if (i >= m_values.length) { - throw new IllegalStateException( - "After last item. Model exhausted."); - } - } - - }; - } - - public void lock() { - m_locked = true; - } - - public final boolean isLocked() { - return m_locked; - } - - } - - /** - * A {@link ListModel} that has no rows. - */ - public static final ListModel EMPTY_MODEL = new ListModel() { - - public boolean next() { - return false; - } - - public String getKey() { - throw new IllegalStateException("ListModel is empty"); - } - - public Object getElement() { - throw new IllegalStateException("ListModel is empty"); - } - - }; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ListPanel.java b/ccm-core/src/main/java/com/arsdigita/bebop/ListPanel.java deleted file mode 100644 index d51f0d5ec..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ListPanel.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import static com.arsdigita.bebop.Component.*; - -import java.util.Iterator; - -import com.arsdigita.xml.Element; - -/** - * A container that outputs its components in a <list>. Each child is - * printed in its own list item. The components are put into the list in the - * order in which they were added to the ListPanel, progressing - * from top to bottom. - * - *

- * ListPanels can be ordered or unordered.

- * - * @author Christian Brechbühler (christian@arsdigita.com) - * - * @version $Id$ - * - */ -public class ListPanel extends SimpleContainer { - - public static final boolean ORDERED = true; - public static final boolean UNORDERED = false; - private boolean m_ordered; - - /** - * Creates a simple list. - * - * @param ordered true is an ordered (numbered) list; - * false is an unordered (bulleted) list - * - */ - public ListPanel(boolean ordered) { - m_ordered = ordered; - } - - /** - * Adds child components as a subtree under list-item nodes. - *

- * Generates a DOM fragment: - *

- *

-     * <bebop:listPanel>
-     *   <bebop:cell> ... cell contents </bebop:cell>
-     *   <bebop:cell> ... cell contents </bebop:cell>
-     *   ...
-     * </bebop:list>

- * - * @param state the state of the current request - * @param parent the node under which this subtree will be added - */ - public void generateXML(PageState state, Element parent) { - - if (isVisible(state)) { - - Element list = parent.newChildElement("bebop:listPanel", - BEBOP_XML_NS); - list.addAttribute("ordered", String.valueOf(m_ordered)); - exportAttributes(list); - - // generate XML for children - for (Iterator i = children(); i.hasNext();) { - Component c = (Component) i.next(); - - Element item = list.newChildElement("bebop:cell", BEBOP_XML_NS); - c.generateXML(state, item); - } - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/MapComponentSelectionModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/MapComponentSelectionModel.java deleted file mode 100755 index f75d5da77..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/MapComponentSelectionModel.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import java.util.Map; - -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.util.Assert; -import com.arsdigita.util.Lockable; - -/** - * A simple implementation of a {@link ComponentSelectionModel}. Uses a map to - * bind keys to components. - *

- * This class also encapsulates a {@link SingleSelectionModel}, which is useful - * if the {@link SingleSelectionModel} comes from a {@link List} or similar - * class. - * - * @author Jens Pelzetter - * @author David Lutterkort - * @author Stanislav Freidin - */ -public class MapComponentSelectionModel implements ComponentSelectionModel, - Lockable { - - private SingleSelectionModel m_selModel; - private Map m_components; - private boolean m_locked; - - /** - * Constructs a new MapSingleSelectionModel, using selModel as the inner - * selection model and encapsulating the components map. - * - * @param selModel the single selection model to use to determine the - * currently selected key/component - * @param components the map of components that can be selected. The map is - * stored by reference. Therefore, changes to the map will - * affect the MapComponentSelectionModel instance. - */ - public MapComponentSelectionModel(final SingleSelectionModel selModel, - final Map components - ) { - m_components = components; - m_selModel = selModel; - m_locked = false; - } - - /** - * Constructs a new MapSingleSelectionModel, using a - * DefaultSingleSelectionModel selection model and encapsulating the - * components map. - * - * @param components the map of components that can be selected. The map is - * stored by reference. Therefore, changes to the map will - * affect the MapComponentSelectionModel instance. - */ - public MapComponentSelectionModel(final Map components) { - this(new DefaultSingleSelectionModel<>(), components); - } - - /** - * Retrieves the internal SingleSelectionModel. - * - * @return the internal SingleSelectionModel. - */ - public final SingleSelectionModel getSingleSelectionModel() { - return m_selModel; - } - - /** - * Retrieves the internal Map of components. Deprecate ??? - * - * @return the internal map of components. - */ - public final Map getComponentsMap() { - return m_components; - } - - /** - * Returns the component that should be used to output the currently - * selected element. - * - * @param state the state of the current request - * - * @return the component used to output the selected element. - */ - @Override - public Component getComponent(final PageState state) { - if (!isSelected(state)) { - return null; - } - return m_components.get((m_selModel.getSelectedKey(state))); - } - - /** - * Adds another key-component mapping to the model. Passthrough to the - * underlying Map. - * - * @param key the key for the mapping - * @param component the component for the mapping - */ - public void add(final T key, final Component component) { - Assert.isUnlocked(this); - m_components.put(key, component); - } - - // Passthrough to SingleSelectionModel - /** - * Returns true if there is a selected element. - * - * @param state the state of the current request - * - * @return true if there is a selected component - * false otherwise. - */ - @Override - public boolean isSelected(final PageState state) { - return m_selModel.isSelected(state); - } - - /** - * Returns the key that identifies the selected element. - * - * @param state a PageState value - * - * @return a String value. - */ - @Override - public T getSelectedKey(final PageState state) { - return m_selModel.getSelectedKey(state); - } - - /** - * Sets the selected key. If key is not in the collection of - * objects underlying this model, an IllegalArgumentException - * is thrown. - * - * @param state the state of the current request - * - * @throws IllegalArgumentException if the supplied key cannot - * be selected in the context of the - * current request. - */ - @Override - public void setSelectedKey(final PageState state, final T key) { - m_selModel.setSelectedKey(state, key); - } - - /** - * Clears the selection. - * - * @param state the state of the current request - * - * @post ! isSelected(state) - */ - @Override - public void clearSelection(final PageState state) { - m_selModel.clearSelection(state); - } - - /** - * Adds a change listener to the model. The listener's - * stateChanged is called whenever the selected key changes. - * - * @param changeListener a listener to notify when the selected key changes - */ - @Override - public void addChangeListener(final ChangeListener changeListener) { - Assert.isUnlocked(this); - m_selModel.addChangeListener(changeListener); - } - - /** - * Removes a change listener from the model. - * - * @param changeListener the listener to remove - */ - @Override - public void removeChangeListener(final ChangeListener changeListener) { - Assert.isUnlocked(this); - m_selModel.removeChangeListener(changeListener); - } - - /** - * Returns the state parameter that will be used to keep track of the - * currently selected key. Typically, the implementing class will simply - * call:
- *

return new StringParameter("foo");
This method - * may return null if a state parameter is not appropriate in the context of - * the implementing class. - * - * @return the state parameter to use to keep track of the currently - * selected component. - */ - @Override - public ParameterModel getStateParameter() { - return m_selModel.getStateParameter(); - } - - // implement Lockable - @Override - public final void lock() { - m_locked = true; - } - - @Override - public final boolean isLocked() { - return m_locked; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/MetaForm.java b/ccm-core/src/main/java/com/arsdigita/bebop/MetaForm.java deleted file mode 100755 index 04c9c7c03..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/MetaForm.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.util.Traversal; -import com.arsdigita.xml.Element; - -/** - * A form that is instantiated on a per-request basis. This class - * functions as a placeholder and decorator of the request-specific form - * in a Bebop {@link Page}. - * - *

Subclasses only need to override {@link #buildForm buildForm} to - * return the request-specific form. The meta form takes care of - * interfacing that form with the normal control flow of serving a Bebop - * Page. The meta form will fool the request-specific forms - * into thinking that they are part of a static Bebop Page. - * The properties of the meta form should be used to initialize the - * correspoding properties of the request-specific form whenever - * possible. These properties include name, - * method, and encType. - * - *

Listeners can be added directly to the meta form and are run - * whenever the corresponding listeners would be run on an ordinary - * form. The source of the FormSectionEvent will be the meta - * form. - * - * @author Stas Freidin - * @author David Lutterkort - */ - -public abstract class MetaForm extends Form { - - private RequestLocal m_dynamicForm; - - /** - * Constructs a new meta form. - * - * @param name the name of the form - */ - public MetaForm(String name) { - super(name); - m_dynamicForm = new RequestLocal() { - protected Object initialValue(PageState s) { - Form result = buildForm(s); - result.getModel().mergeModel(getModel()); - // form isn't part of the page, so it is invisible - // on the page (vacuously). We should consider it - // visible iff the static container MetaForm is visible. - result.setProcessInvisible( - MetaForm.this.getProcessInvisible() || - s.isVisibleOnPage(MetaForm.this)); - result.traverse(); - Traversal t = new Traversal() { - public void act(Component c) { - c.lock(); - } - }; - t.preorder(result); - return result; - } - }; - } - - /** - * Retrieves the form for the request represented by - * state. If the form hasn't been built - * yet, calls {@link #buildForm buildForm} to build the - * form. - * - * @param state describes the current request - * @return a custom-built form for this request. - * @pre state != null - * @post return != null - */ - protected Form getDynamicForm(PageState state) { - return (Form) m_dynamicForm.get(state); - } - - /** - * Builds the dynamic form. Subclasses should override this method to - * build the form based on the request represented by state. - * - * @param state describes the current request - * @return the form to be used for this request. - * @pre state != null - * @post return != null - */ - public abstract Form buildForm(PageState state); - - /** - * Force a rebuilding and updating of the dynamic form. Calls - * buildForm again and sets the dynamic form to the form - * returned by it. - * - * @param s describes the current request - */ - public void rebuildForm(PageState s) { - m_dynamicForm.set(s, m_dynamicForm.initialValue(s)); - } - - /** - * Returns the form data constructed by {@link #process process} for the - * request described by state. If the form for this request - * hasn't been built yet, calls {@link #buildForm buildForm}. - * - * @param state describes the current request - * @return the values extracted from the HTTP request contained - * in state, or null if the form has not - * yet been processed. - * @pre state != null - */ - public FormData getFormData(PageState state) { - return getDynamicForm(state).getFormData(state); - } - - /** - * Generates the XML representing the form and its widgets, but not - * the state information, from s. The XML generation is - * delegated to the request-specific form by calling {@link - * #generateXMLSansState generateXMLSansState} on it. - * - * @param s represents the curent request - * @return the top-level element for the form. - */ - protected Element generateXMLSansState(PageState s, Element parent) { - return getDynamicForm(s).generateXMLSansState(s, parent); - } - - /** - * Processes the request-specific form for the request represented by - * state. - * - * @param state describes the current request - * @return the form data extracted from the current request. - * @pre state != null - * @post return != null - * @see Form#process Form.process(...) - * @see FormModel#process FormModel.process(...) - */ - public FormData process(PageState state) - throws FormProcessException { - - if (state.isVisibleOnPage(this)) - return getDynamicForm(state).process(state); - return null; // XXX is this ok ? - } - - /** - * Do nothing; the dynamic form will take care of the tag. - */ - protected void addMagicTag() { - return; - } - - /** - * Not implemented because meta forms currently don't support mixing static and - * dynamic widgets. - * @throws UnsupportedOperationException - */ - public void add(Component pc, int constraints) { - throw new UnsupportedOperationException("Not implemented"); - } - - /** - * Not implemented. - * @throws UnsupportedOperationException - */ - public Container getPanel() { - throw new UnsupportedOperationException("Not implemented"); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ModalContainer.java b/ccm-core/src/main/java/com/arsdigita/bebop/ModalContainer.java deleted file mode 100644 index 577ee3301..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ModalContainer.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.util.Assert; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.Iterator; - -/** - * ModalContainer is a container that manages visibility for a set of - * components. It allows only one of its children to be visible. One of its - * children can be selected as the default visible component. If none is - * selected the child with index equal to zero is used. The modal container sets - * the appropriate default and PageState-based visibility for its children. - * - * @author Archit Shah - * - */ -public class ModalContainer extends SimpleContainer implements Resettable { - - private static final Logger LOGGER = LogManager.getLogger( - ModalContainer.class); - - private int m_default = 0; - - private ArrayList m_changeListeners = new ArrayList(); - - public ModalContainer() { - super(); - } - - public ModalContainer(String tagName, - String xmlns) { - super(tagName, xmlns); - } - - /** - * Registers state parameters for the page with its model. - * - * Used here to set the visibility of the component. - * - * The super class' method is empty, so the rule "Always call - * super.register when you override register - * doessn't apply here. - * - * @pre p != null - * @param p - */ - @Override - public void register(Page p) { - Assert.isUnlocked(this); - - Iterator it = children(); - while (it.hasNext()) { - // guaranteed to have at least one child - Component child = (Component) it.next(); - if (m_default != indexOf(child)) { - p.setVisibleDefault(child, false); - } - } - } - - public void setDefaultComponent(Component c) { - Assert.isUnlocked(this); - - if (!contains(c)) { - add(c); - } - - m_default = indexOf(c); - } - - public Component getDefaultComponent() { - return get(m_default); - } - - public void setVisibleComponent(PageState state, Component c) { - LOGGER.debug("changing visibility"); - - Component old = getVisibleComponent(state); - try { - old.setVisible(state, false); - } catch (NullPointerException e) { - // rare(?) situation where something messes with the - // visibility of the components. don't have to do anything - } - c.setVisible(state, true); - if (old != c) { - Iterator listeners = m_changeListeners.iterator(); - while (listeners.hasNext()) { - ChangeListener l = (ChangeListener) listeners.next(); - l.stateChanged(new ChangeEvent(this, state)); - } - } - } - - public Component getVisibleComponent(PageState state) { - Iterator it = children(); - while (it.hasNext()) { - Component c = (Component) it.next(); - if (c.isVisible(state)) { - return c; - } - } - - return null; - } - - /** - * Makes the next component in a wizard sequence visible while hiding all - * other components. - * - */ - public void next(PageState state) { - setVisibleComponent(state, - get(indexOf(getVisibleComponent(state)) + 1)); - } - - /** - * Makes the previous component in a wizard sequence visible while hiding - * all other components. - * - */ - public void previous(PageState state) { - setVisibleComponent(state, - get(indexOf(getVisibleComponent(state)) - 1)); - } - - /** - * Makes the component specified by index visible - * - * @param state - * @param index 0 based index of component - */ - public void jumpTo(PageState state, int index) { - setVisibleComponent(state, get(index)); - } - - /** - * Makes the specified component visible - * - */ - public void jumpTo(PageState state, Component comp) { - setVisibleComponent(state, get(indexOf(comp))); - } - - /** - * Resets the container to display the default component. - * - */ - public void reset(PageState state) { - setVisibleComponent(state, getDefaultComponent()); - } - - /** - * Adds a listener that is called whenever this container's mode (i.e., - * visible component) is changed using setVisibleComponent(). - * - */ - public void addModeChangeListener(ChangeListener cl) { - Assert.isUnlocked(this); - - m_changeListeners.add(cl); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Page.java b/ccm-core/src/main/java/com/arsdigita/bebop/Page.java deleted file mode 100755 index 7a2f3aa48..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Page.java +++ /dev/null @@ -1,1361 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.RequestEvent; -import com.arsdigita.bebop.event.RequestListener; -import com.arsdigita.bebop.parameters.BitSetParameter; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.util.Traversal; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.util.Assert; -import com.arsdigita.util.SystemInformation; -import com.arsdigita.xml.Document; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.BitSet; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; - -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletRequestWrapper; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.ParserConfigurationException; - -/** - * The top-level container for all Bebop components and containers. - * - *

    - *
  • Holds references to the components of a page.
  • - *
  • Provides methods for servicing requests and for notifying other - * components that a request for this page has been received through - * {@link ActionListener ActionListeners}.
  • - *
  • Tracks request parameters for stateful components, such as tabbed panes - * and sortable tables.
  • - *
- * - * A typical Page may be created as follows: null

- * Page p = new Page("Hello World");
- * p.add(new Label("Hello World");
- * p.lock();
- * 

- * - * @author David Lutterkort - * @author Stanislav Freidin - * @author Uday Mathur - */ -public class Page extends SimpleComponent implements Container { - - /** - * Class specific logger instance. - */ - private static final Logger LOGGER = LogManager.getLogger(Page.class); - /** - * The delimiter character for components naming - */ - private static final String DELIMITER = "."; - /** - * The prefix that gets prepended to all state variables. Components must - * not use variables starting with this prefix. This guarantees that the - * page state and variables individual components wish to pass do not - * interfere with each other. - */ - private static final String COMPONENT_PREFIX = "bbp" + DELIMITER; - private static final String INTERNAL = COMPONENT_PREFIX; - /** - * The name of the special parameter that indicates which component has been - * selected. - */ - static final String SELECTED = INTERNAL + "s"; - static final String CONTROL_EVENT = INTERNAL + "e"; - static final String CONTROL_VALUE = INTERNAL + "v"; - static final Collection CONTROL_EVENT_KEYS; - - static { - LOGGER.debug("Static initalizer is starting..."); - CONTROL_EVENT_KEYS = new ArrayList(3); - CONTROL_EVENT_KEYS.add(SELECTED); - CONTROL_EVENT_KEYS.add(CONTROL_EVENT); - CONTROL_EVENT_KEYS.add(CONTROL_VALUE); - LOGGER.debug("Static initalizer finished."); - } - - /** - * The name of the request parameter used for the visibility state of - * components stored in m_invisible. - */ - static final String INVISIBLE = INTERNAL + "i"; - /** - * Map of stateful components (id --> Component) SortedMap used because - * component based hash for page is based on concatenation of component ids, - * and so need to guarantee that they are returned in the same order for the - * same page - cg. - */ - private SortedMap m_componentMap; - private List m_components; - /** - * Map of component -> owned parameter collection - */ - private Map m_componentParameterMap = new HashMap(); - private FormModel m_stateModel; - /** - * Container that renders this Page. - */ - protected Container m_panel; - private List m_actionListeners; - private List m_requestListeners; - /** - * The title of the page to be added in the head of HTML output. The title - * is wrapped in a Label to allow developers to add PrintListeners to - * dynamically change the value of the title. - */ - private Label m_title; - /** - * Stores the actual title for the current request. The title may be - * generated with a PrintListener of the m_title Label. - */ - private RequestLocal m_currentTitle; - /** - * A list of all the client-side stylesheets. The elements of the list are - * of type Page.Stylesheet, defined at the end of this file. - */ - private List m_clientStylesheets; - private StringParameter m_selected; - private StringParameter m_controlEvent; - private StringParameter m_controlValue; - /** - * The default (initial) visibility of components. The encoding is identical - * to that for PageState.m_invisible. - * - * This variable is package-friendly since it needs to be accessed by - * PageState. - */ - protected BitSet m_invisible; - /** - * The PageErrorDisplay component that will display page state validation - * errors on this page - */ - private Component m_errorDisplay; - /** - * Indicates whether finish() has been called on this Page. - */ - private boolean m_finished = false; - /** - * indicates whether pageState.stateAsURL() should export the entire state - * for this page, or whether it should only export the control event as a - * URL and use the HttpSession for the rest of the page state. - */ - private boolean m_useHttpSession = false; - - /** - * Returns true if this page should export state through the - * HttpSession instead of the URL query string. - *

- * If this returns true, then PageState.stateAsURL() will only - * export the control event as a URL query string. If this returns - * false, then stateAsURL() will export the entire page state. - * - * @see PageState#stateAsURL - * - * @return true if this page should export state through the - * HttpSession; false if it should export using the URL - * query string. - */ - public boolean isUsingHttpSession() { - return m_useHttpSession; - } - - /** - * Indicates to this page whether it should export its entire state to - * subsequent requests through the URL query string, or if it should use the - * HttpSession instead and only use the URL query string for the control - * event. - * - * @see PageState#stateAsURL - * - * @param b true if PageState.stateAsURL() will export only the - * control event as a URL query string. false if - * stateAsURL() will export the entire page state. - */ - public void setUsingHttpSession(boolean b) { - m_useHttpSession = b; - } - - // //////////////////////////////////////////////////////////////////////// - // Constructor Section - // //////////////////////////////////////////////////////////////////////// - /** - * Constructor, creates an empty page with the specified title and panel. - * - * @param title title for this page - * @param panel container for this page - * - * @deprecated use Page(Lab el, Container) instead. - */ - public Page(String title, Container panel) { - this(new Label(title), panel); - } - - /** - * Constructor, creates an empty page with the specified title and panel. - * - * @param title title for this page as (globalized) Label - * @param panel container for this page - */ - public Page(Label title, Container panel) { - super(); - m_actionListeners = new LinkedList(); - m_requestListeners = new LinkedList(); - m_panel = panel; - m_clientStylesheets = new ArrayList(); - m_components = new ArrayList(); - m_componentMap = new TreeMap(); - setErrorDisplay(new PageErrorDisplay()); - m_title = title; - - // Initialize the RequestLocal where the title for the current - // request will be kept - m_currentTitle = new RequestLocal() { - - @Override - protected Object initialValue(PageState state) { - return m_title.firePrintEvent(state); - } - - }; - - // Initialize the set of state parameters to hold - // the ones necessary for keeping track of the selected component and - // the name and value of a 'control event' - m_selected = new StringParameter(SELECTED); - m_controlEvent = new StringParameter(CONTROL_EVENT); - m_controlValue = new StringParameter(CONTROL_VALUE); - - m_stateModel = new FormModel("stateModel", true); - m_stateModel.addFormParam(m_selected); - m_stateModel.addFormParam(m_controlEvent); - m_stateModel.addFormParam(m_controlValue); - - // Set up the visibility tracking parameters - m_invisible = new BitSet(32); - BitSetParameter p = new BitSetParameter(INVISIBLE, - BitSetParameter.ENCODE_DGAP); - m_stateModel.addFormParam(p); - } - - /** - * Creates an empty page with default title and implicit BoxPanel container. - */ - public Page() { - this(""); - } - - /** - * Creates an empty page with the specified title and implicit BoxPanel - * container. - * - * @param title title for this page - */ - public Page(Label title) { - this(title, new BoxPanel()); - BoxPanel bp = (BoxPanel) m_panel; - bp.setWidth("100%"); - } - - /** - * Creates an empty page with the specified title and implicit BoxPanel - * container. - * - * @param title title for this page - */ - public Page(String title) { - this(new Label(title)); - } - - /** - * Adds a component to this container. - * - * @param c component to add to this container - */ - @Override - public void add(Component c) { - m_panel.add(c); - - } - - /** - * Adds a component with the specified layout constraints to this container. - * Layout constraints are defined in each layout container as static ints. - * To specify multiple constraints, use bitwise OR. - * - * @param c component to add to this container - * @param constraints layout constraints (a bitwise OR of static ints in the - * particular layout) - */ - @Override - public void add(Component c, int constraints) { - m_panel.add(c, constraints); - } - - /** - * Returns true if this list contains the specified element. - * More formally, returns true if and only if this list - * contains at least one element e such that (o==null ? e==null : - * o.equals(e)). - *

- * This method returns true only if the component has been - * directly added to this container. If this container contains another - * container that contains this component, this method returns - * false. - * - * @param o element whose presence in this container is to be tested - * - * @return true if this Container contains the specified - * component directly; false otherwise. - */ - @Override - public boolean contains(Object o) { - return m_panel.contains(o); - } - - /** - * Returns the component at the specified position. Each call to the add - * method increments the index. Since the user has no control over the index - * of added components (other than counting each call to add), this method - * should be used in conjunction with indexOf. - * - * @param index the index of the item to be retrieved from this Container - * - * @return the component at the specified position in this container. - */ - @Override - public Component get(int index) { - return m_panel.get(index); - } - - /** - * Gets the index of a component. - * - * @param c component to search for - * - * @return the index in this list of the first occurrence of the specified - * element, or -1 if this list does not contain this element. - * - * @pre c != null - * @post contains(c) implies (return >= 0) && (return < size()) @pos t - * !contains(c) implies return == -1 - */ - @Override - public int indexOf(Component c) { - return m_panel.indexOf(c); - } - - /** - * Returns true if the container contains no components. - * - * @return true if this container contains no components; - * false otherwise. - */ - @Override - public boolean isEmpty() { - return m_panel.isEmpty(); - } - - /** - * Returns the number of elements in this container. This does not - * recursively count the components that are indirectly contained in this - * container. - * - * @return the number of components directly in this container. - */ - @Override - public int size() { - return m_panel.size(); - } - - @Override - public Iterator children() { - return Collections.singletonList(m_panel).iterator(); - } - - /** - * Returns the panel that the Page uses for rendering its - * components. - * - * @return the panel. - */ - public final Container getPanel() { - return m_panel; - } - - /** - * Set the Container used for rendering components on this page. Caution - * should be used with this function, as the existing container is simply - * overwritten. - * - * @param c - * - * @author Matthew Booth (mbooth@redhat.com) - */ - public void setPanel(Container c) { - m_panel = c; - } - - /** - * Retrieves the title of this page. - * - * @return the static title of this page. - */ - public final Label getTitle() { - return m_title; - } - - /** - * Retrieves the title of this page as a Bebop label component. - * - * @param state the state of the current request - * - * @return the title of the page for the current request. - */ - public final Label getTitle(PageState state) { - return (Label) m_currentTitle.get(state); - } - - /** - * Sets the title for this page from the passed in string. - * - * @param title title for this page - */ - public void setTitle(String title) { - Assert.isUnlocked(this); - setTitle(new Label(title)); - } - - /** - * Set the title for this page from the passed in label. - * - * @param title title for this page - */ - public void setTitle(Label title) { - Assert.isUnlocked(this); - m_title = title; - } - - /** - * Sets the {@link Component} that will display the validation errors in the - * current {@link PageState}. Any validation error in the - * PageState will cause the Page to completely - * ignore all other components and render only the error display component. - *

- * By default, a {@link PageErrorDisplay} component is used to display the - * validation errors. - * - * @param c the component that will display the validation errors in the - * current PageState - */ - public final void setErrorDisplay(Component c) { - Assert.isUnlocked(this); - m_errorDisplay = c; - } - - /** - * Gets the {@link Component} that will display the validation errors in the - * current {@link PageState}. Any validation error in the - * PageState will cause the Page to completely - * ignore all other components and render only the error display component. - *

- * By default, a {@link PageErrorDisplay} component is used to display the - * validation errors. - * - * @return the component that will display the validation errors in the - * current PageState. - */ - public final Component getErrorDisplay() { - return m_errorDisplay; - } - - /** - * Adds a client-side stylesheet that should be used in HTML output. - * Arbitrarily many client-side stylesheets can be added with this method. - * To use a CSS stylesheet, call something like - * setStyleSheet("style.css", "text/css"). - * - *

- * These values will ultimately wind up in a <link> - * tag in the head of the HTML page. - * - *

- * Note that the stylesheet set with this call has nothing to do with the - * XSLT stylesheet (transformer) that is applied to the XML generated from - * this page! - * - * @param styleSheetURI the location of the stylesheet - * @param mimeType the MIME type of the stylesheet, usually - * text/css - * - * @pre ! isLocked() - */ - public void addClientStylesheet(String styleSheetURI, String mimeType) { - m_clientStylesheets.add(new Stylesheet(styleSheetURI, mimeType)); - } - - /** - * Adds a global state parameter to this page. Global parameters are values - * that need to be preserved between requests, but that have no special - * connection to any of the components on the page. For a page that displays - * details about an item, a global parameter would be used to identify the - * item. - * - * If the parameter was previously added as a component state parameter, its - * name is unmangled and stays unmangled. - * - * @see #addComponentStateParam - * - * @param p the global parameter to add - * - * @pre ! isLocked() - * @pre parameter != null - */ - public void addGlobalStateParam(ParameterModel p) { - Assert.isUnlocked(this); - p.setName(unmangle(p.getName())); - m_stateModel.addFormParam(p); - } - - /** - * Constructs the top nodes of the DOM or JDOM tree. Used by - * generateXML(PageState, Document) below. - *

- * Generates DOM fragment: - *

-     * <bebop:page>
-     *   <bebop:title> ... value set with setTitle ... </bebop:title>
-     *   <bebop:stylesheet href='styleSheetURI' type='mimeType'>
-     *   ... page content gnerated by children ...
-     * </bebop:page>
The content of the <title> - * element can be set by calling {@link #setTitle setTitle}. The - * <stylesheet> element will only be present if a stylesheet - * has been set with {@link - * #setStyleSheet setStyleSheet}. - * - * @param ps the page state for the current page - * @param parent the DOM node for the whole Document - * - * @return - * - * @pre isLocked() - */ - protected Element generateXMLHelper(PageState ps, Document parent) { - Assert.isLocked(this); - - Element page = parent.createRootElement("bebop:page", BEBOP_XML_NS); - exportAttributes(page); - - /* Generator information */ - exportSystemInformation(page); - - Element title = page.newChildElement("bebop:title", BEBOP_XML_NS); - title.setText(getTitle(ps).getLabel(ps)); - - for (Iterator i = m_clientStylesheets.iterator(); i.hasNext();) { - ((Stylesheet) i.next()).generateXML(page); - } - - return page; - } - - /** - * Constructs a DOM or JDOM tree with all components on the page. The tree - * represents the page that results from the - * {@link javax.servlet.http.HttpServletRequest} kept in the - * state. - * - * @param state the page state produced by {@link #process} - * @param parent the DOM node for the whole Document - * - * @see #process process - * @pre isLocked() - * @pre state != null - */ - public void generateXML(PageState state, Document parent) { - // always export page state as HTTP session - if (m_useHttpSession) { - state.stateAsHttpSession(); - } - - Element page = generateXMLHelper(state, parent); - - // If the page state has errors, ignore all the components and - // render only the error display component - if (state.getErrors().hasNext()) { - m_errorDisplay.generateXML(state, page); - } else { - m_panel.generateXML(state, page); - } - - if (KernelConfig.getConfig().isDebugEnabled() - && debugStructure(state.getRequest())) { - - Element structure = page.newChildElement("bebop:structure", - BEBOP_XML_NS); - - showStructure(state, structure); - } - } - - private static boolean debugStructure(HttpServletRequest req) { - return "transform".equals(req.getParameter("debug")); - } - - /** - * Do nothing. Top-level add nodes is meaningless. - * - * @param elt - */ - @Override - public void generateXML(PageState state, Element elt) { - } - - /** - * Creates a PageState object and processes it by calling the respond method - * on the selected component. Processes a request by notifying the component - * from which the process originated and {@link #fireActionEvent - * broadcasts} an {@link ActionEvent} to all the listeners that registered - * with {@link #addActionListener addActionListener}. - * - * @see #generateXML(PageState,Document) generateXML - * - * @param request - * @param response - * - * @return - * - * @throws javax.servlet.ServletException - * @pre isLocked() - * @pre request != null - * @pre response != null - */ - public PageState process(HttpServletRequest request, - HttpServletResponse response) - throws ServletException { - - PageState result = new PageState(this, request, response); - try { - process(result); - } finally { - } - return result; - } - - /** - * Processes the supplied PageState object according to this PageModel. - * Calls the respond method on the selected Bebop component. - */ - public void process(PageState state) throws ServletException { - Assert.isLocked(this); - try { - fireRequestEvent(state); - } finally { - } - - // Validate the state; any errors in the state will be displayed - // by generateXML - state.forceValidate(); - - if (state.isValid()) { - try { - state.respond(); - } finally { - } - try { - fireActionEvent(state); - } finally { - - } - } - } - - /** - * Builds a DOM Document from the current request state by doing a - * depth-first tree walk on the current set of components in this Page, - * calling generateXML on each. Does NOT do the rendering. If the HTTP - * response has already been committed, does not build the XML document. - * - * @param req - * @param res - * @return a DOM ready for rendering, or null if the response has already - * been committed. - * @throws javax.servlet.ServletException - * - */ - public Document buildDocument(final HttpServletRequest req, - final HttpServletResponse res) - throws ServletException { - try { - Document doc = new Document(); - - final ServletRequest request = unwrapRequest(req); - if (!(request instanceof HttpServletRequest)) { - throw new ServletException("Request is not a HttpServletRequest."); - } - final PageState state = process((HttpServletRequest) request, res); - - // only generate XML document if the response is not already - // committed - if (!res.isCommitted()) { - try { - generateXML(state, doc); - } finally { - } - return doc; - } else { - return null; - } - } catch (ParserConfigurationException e) { - throw new ServletException(e); - } - } - - private ServletRequest unwrapRequest(final HttpServletRequest request) { - - ServletRequest current = request; - while (current instanceof ServletRequestWrapper) { - current = ((ServletRequestWrapper) current).getRequest(); - } - - return current; - } - - /** - * Finishes building the page. The tree of components is traversed and each - * component is told to add its state parameters to the page's state model. - * - * @pre ! isLocked() - */ - private void finish() { - if (!m_finished) { - Assert.isUnlocked(this); - - Traversal componentRegistrar = new Traversal() { - - @Override - protected void act(Component c) { - addComponent(c); - c.register(Page.this); - } - - }; - if (m_panel == null) { - LOGGER.warn("m_panel is null"); - } - componentRegistrar.preorder(m_panel); - if (m_errorDisplay != null) { - addComponent(m_errorDisplay); - m_errorDisplay.register(Page.this); - } - - m_finished = true; - } - } - - /** - * Locks the page and all its components against further modifications. - * - *

- * Locking a page helps in finding mistakes that result from modifying a - * page's structure.

- */ - @Override - public void lock() { - if (!m_finished) { - finish(); - } - m_stateModel.lock(); - Traversal componentLocker = new Traversal() { - - @Override - protected void act(Component c) { - c.lock(); - } - - }; - - componentLocker.preorder(m_panel); - - super.lock(); - } - - @Override - public void respond(PageState state) throws javax.servlet.ServletException { - throw new UnsupportedOperationException(); - } - - /** - * Registers a listener that is notified whenever a request to this page is - * made, after the selected component has had a chance to respond. - * - * @pre l != null - * @pre ! isLocked() - */ - public void addActionListener(ActionListener l) { - Assert.isUnlocked(this); - m_actionListeners.add(l); - } - - /** - * Remove a previously registered action listener. - * - * @pre l != null - * @pre ! isLocked() - */ - public void removeActionListener(ActionListener l) { - Assert.isUnlocked(this); - m_actionListeners.remove(l); - } - - /** - * Registers a listener that is notified whenever a request to this page is - * made, before the selected component has had a chance to respond. - * - * @pre l != null - * @pre ! isLocked() - */ - public void addRequestListener(RequestListener l) { - Assert.isUnlocked(this); - m_requestListeners.add(l); - } - - /** - * Removes a previously registered request listener. - * - * @param 1 the listener to remove - * - * @pre l != null - * @pre ! isLocked() - */ - public void removeRequestListener(RequestListener l) { - Assert.isUnlocked(this); - m_requestListeners.remove(l); - } - - /** - * Broadcasts an {@link ActionEvent} to all registered listeners. The source - * of the event is this page, and the state recorded in the event is the one - * resulting from processing the current request. - * - * @param the state for this event - * - * @pre state != null - */ - protected void fireActionEvent(PageState state) { - ActionEvent e = null; - - for (Iterator i = m_actionListeners.iterator(); i.hasNext();) { - if (e == null) { - e = new ActionEvent(this, state); - } - - final ActionListener listener = (ActionListener) i.next(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Firing action listener " + listener); - } - - listener.actionPerformed(e); - } - } - - /** - * Broadcasts a {@link RequestEvent} to all registered listeners. The source - * of the event is this page, and the state recorded in the event is the one - * resulting from processing the current request. - * - * @param state the state for this event - * - * @pre state != null - */ - protected void fireRequestEvent(PageState state) { - RequestEvent e = null; - - for (Iterator i = m_requestListeners.iterator(); i.hasNext();) { - if (e == null) { - e = new RequestEvent(this, state); - } - - final RequestListener listener = (RequestListener) i.next(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Firing request listener " + listener); - } - - listener.pageRequested(e); - } - } - - /** - * Export page generator information if set. The m_pageGenerator is a - * HashMap containing the information as key value. In general this should - * include generator name and generator version. - * - * @param page parent element - should be bebeop:page - * - * @pre m_pageGenerator != null && !m_pageGenerator.isEmpty() - */ - final protected void exportSystemInformation(Element page) { - SystemInformation sysInfo = SystemInformation.getInstance(); - if (!sysInfo.isEmpty()) { - Element gen = page.newChildElement("bebop:systemInformation", - BEBOP_XML_NS); - - Iterator> keyValues = sysInfo.iterator(); - while (keyValues.hasNext()) { - Map.Entry entry = keyValues.next(); - gen.addAttribute(entry.getKey(), entry.getValue()); - } - } - } - - // Client-side stylesheet storage - private class Stylesheet { - - String m_URI; - String m_type; - - public Stylesheet(String stylesheetURI, String mimeType) { - m_URI = stylesheetURI; - m_type = mimeType; - } - - public void generateXML(Element parent) { - Element style = parent.newChildElement("bebop:stylesheet", - BEBOP_XML_NS); - style.addAttribute("href", m_URI); - if (m_type != null) { - style.addAttribute("type", m_type); - } - } - - } - - /** - * Adds a component to the page model. - */ - public void addComponent(Component c) { - Assert.isUnlocked(this); - - if (!stateContains(c)) { - if (c == null) { - LOGGER.error("c is null"); - } /*else { - s_log.error("c: " + c.toString()); - }*/ - - String key = c.getKey(); - if (key == null) { - key = Integer.toString(m_components.size()); - } - if (m_componentMap.get(key) != null) { - throw new IllegalArgumentException( - "Component key must not be duplicated. The key " + key - + " is shared by more than one component."); - } - m_componentMap.put(key, c); - m_components.add(c); - } - } - - /** - * Registers a state parameter for a component. It is permissible to - * register the same state parameter several times, from the same or - * different components. The name of the parameter will be changed to ensure - * that it won't clash with any other component's parameter. If the - * parameter is added more than once, the name is only changed the first - * time it is added. - * - * @param c the component to register the parameter for - * @param p the state parameter to register - * - * @see #addGlobalStateParam - * - * @pre stateContains(c) - * @pre ! isLocked() - * @pre p != null - */ - public void addComponentStateParam(Component c, ParameterModel p) { - Assert.isUnlocked(this); - - if (!stateContains(c)) { - throw new IllegalArgumentException( - "Component must be registered in Page"); - } - if (!m_stateModel.containsFormParam(p)) { - String name = parameterName(c, p.getName()); - LOGGER.debug(String - .format("Setting name of parameter to add to '%s'", - name)); - p.setName(name); - m_stateModel.addFormParam(p); - - Collection params = (Collection) m_componentParameterMap.get(c); - if (params == null) { - params = new ArrayList(); - m_componentParameterMap.put(c, params); - } - params.add(p); - } - } - - /** - *

- * Get the parameters registered for a given component.

- */ - public Collection getComponentParameters(Component c) { - return (Collection) m_componentParameterMap.get(c); - } - - /** - * Gets the state index of a component. This is the number assigned to the - * component in the register traveral - * - * @param c the component to search for - * - * @return the index in this list of the first occurrence of the specified - * element, or -1 if this list does not contain this element. - * - * @pre c != null - * @post contains(c) implies (return >= 0) && (return < size()) @pos t - * !contains(c) implies return == -1 - */ - public int stateIndex(Component c) { - return m_components.indexOf(c); - } - - /** - * The number of components in the page model. - * - * @post return >= 0 - */ - public int stateSize() { - return m_components.size(); - } - - /** - * Checks whether this component is already in the page model. - * - * @pre c != null - */ - public boolean stateContains(Component c) { - return m_components.contains(c); - } - - /** - * Gets a page component by index. - * - * @pre (i >= 0) && (i < size()) @pos t return != null - */ - public Component getComponent(int i) { - return (Component) m_components.get(i); - } - - /** - * Gets a page component by key. - * - * @pre s != null - */ - Component getComponent(String s) { - return (Component) m_componentMap.get(s); - } - - /** - * Gets the form model that contains the parameters for the page's state. - */ - public final FormModel getStateModel() { - return m_stateModel; - } - - /** - * Gets the ParameterModels held in this Page. - * - * @return an iterator of ParameterModels. - */ - public Iterator getParameters() { - return m_stateModel.getParameters(); - } - - /** - * Checks whether the specified component is visible by default on the page. - * - * @param c a component contained in the page - * - * @return true if the component is visible by default; - * false otherwise. - * - * @see #setVisibleDefault setVisibleDefault - * @see Component#setVisible Component.setVisible - */ - public boolean isVisibleDefault(Component c) { - Assert.isTrue(stateContains(c)); - - return !m_invisible.get(stateIndex(c)); - } - - /** - * Sets whether the specified component is visible by default. The default - * visibility is used when a page is displayed for the first time and on - * subsequent requests until the visibility of a component is changed - * explicitly with {@link Component#setVisible - * Component.setVisible}. - * - *

- * When a component is first added to a page, it is visible. - * - * @param c a component whose visibility is to be set - * @param v true if the component is visible; - * false otherwise. - * - * @see Component#setVisible Component.setVisible - * @see Component#register Component.register - */ - public void setVisibleDefault(Component c, boolean v) { - Assert.isUnlocked(this); - - addComponent(c); - int i = stateIndex(c); - if (v) { - m_invisible.clear(i); - } else { - m_invisible.set(i); - } - } - - /** - * The global name of the parameter name in the component - * c. - */ - public String parameterName(Component c, String name) { - if (c == null || !stateContains(c)) { - return name; - } - - return componentPrefix(c) + name; - } - - /** - * The global name of the parameter name. - */ - public String parameterName(String name) { - return parameterName(null, name); - } - - void reset(final PageState ps, Component cmpnt) { - Traversal resetter = new Traversal() { - - @Override - protected void act(Component c) { - Collection cp = getComponentParameters(c); - if (cp != null) { - Iterator iter = cp.iterator(); - while (iter.hasNext()) { - ParameterModel p = (ParameterModel) iter.next(); - ps.setValue(p, null); - } - } - c.setVisible(ps, isVisibleDefault(c)); - } - - }; - resetter.preorder(cmpnt); - } - - /** - * Return the prefix that is prepended to each component's state parameters - * to keep them unique. - */ - private final String componentPrefix(Component c) { - if (c == null) { - return COMPONENT_PREFIX + "g" + DELIMITER; - } else { - // WRS: preferentially use key if it exists - String key = c.getKey(); - if (key == null) { - if (stateContains(c)) { - key = String.valueOf(stateIndex(c)); - } else { - throw new IllegalArgumentException( - "Cannot generate prefix for component: key is null " - + "and component " + c.toString() + "/" + c.getKey() - + " did not register with page."); - } - } - return COMPONENT_PREFIX + key + DELIMITER; - } - } - - /** - * Undo the name change that {@link #parameterName} does. - * - * @param name a possibly mangled name - * - * @return the unmangled name. - */ - private static final String unmangle(String name) { - if (!name.startsWith(COMPONENT_PREFIX)) { - return name; - } - // Find the second occurence of delimiter - int prefix = name.indexOf(DELIMITER, name.indexOf(DELIMITER) + 1); - if (prefix >= 0 && prefix < name.length()) { - return name.substring(prefix + 1); - } - return name; - } - - // Procs for debugging output - private static String NAME = "name"; - - /** - * Produces an XML fragment that captures the layout of this page. - */ - private void showStructure(PageState s, Element root) { - final HttpServletRequest req = s.getRequest(); - Element state = root.newChildElement("bebop:state", BEBOP_XML_NS); - // Selected component - String sel = req.getParameter(m_selected.getName()); - Element selected = state.newChildElement("bebop:selected", BEBOP_XML_NS); - - selected.addAttribute(NAME, m_selected.getName()); - selected.setText(sel); - - // Control event - Element eventName = state.newChildElement("bebop:eventName", - BEBOP_XML_NS); - eventName.addAttribute(NAME, m_controlEvent.getName()); - eventName.setText(req.getParameter(m_controlEvent.getName())); - Element eventValue = state.newChildElement("bebop:eventValue", - BEBOP_XML_NS); - eventValue.addAttribute(NAME, m_controlValue.getName()); - eventValue.setText(req.getParameter(m_controlValue.getName())); - - // Global parameters - Element globalState = root.newChildElement("bebop:params", BEBOP_XML_NS); - for (Iterator ii = getStateModel().getParameters(); ii.hasNext();) { - ParameterModel p = (ParameterModel) ii.next(); - if (!p.getName().startsWith(COMPONENT_PREFIX)) { - Element param = globalState.newChildElement("bebop:param", - BEBOP_XML_NS); - param.addAttribute(NAME, p.getName()); - param.setText(String.valueOf(s.getValue(p))); - } - } - - showVisibility(s, this, root); - } - - /** - * @see showStructure(PageState, Element) - */ - private void showVisibility(PageState s, Component c, Element parent) { - HttpServletRequest req = s.getRequest(); - - Element cmp = parent.newChildElement("bebop:component", BEBOP_XML_NS); - cmp.addAttribute(NAME, getDebugLabel(c)); - cmp.addAttribute("idx", String.valueOf(stateIndex(c))); - cmp.addAttribute("isVisible", (s.isVisible(c) ? "yes" : "no")); - cmp.addAttribute("class", c.getClass().getName()); - - if (c.getKey() != null) { - String prefix = componentPrefix(c); - for (Iterator i = getStateModel().getParameters(); i.hasNext();) { - ParameterModel p = (ParameterModel) i.next(); - if (!p.getName().startsWith(prefix)) { - continue; - } - - Element param = parent.newChildElement("bebop:param", - BEBOP_XML_NS); - param.addAttribute(NAME, unmangle(p.getName())); - param.addAttribute("defaultValue", - String.valueOf(req.getParameter(p.getName()))); - param - .addAttribute("currentValue", String.valueOf(s.getValue(p))); - } - } - for (Iterator i = c.children(); i.hasNext();) { - showVisibility(s, ((Component) i.next()), cmp); - } - } - - private static String getDebugLabel(Component c) { - if (c.getKey() != null) { - return c.getKey(); - } - - String klass = c.getClass().getName(); - return klass.substring(klass.lastIndexOf(".") + 1, klass.length()); - } - - /** - * return a string that represents an ordered list of component ids used on - * the page. For situations where only the components present is of - * importance, this may be used by implementations of hashCode & equals - * - * @return - */ - public String getComponentString() { - Iterator it = m_componentMap.keySet().iterator(); - /*int hash = 0; - while (it.hasNext()) { - String componentId = (String)it.next(); - s_log.debug("component id = " + componentId); - hash = hash | componentId.hashCode(); - s_log.debug("hash so far = " + hash); - }*/ - Date start = new Date(); - - StringBuilder hashString = new StringBuilder(); - while (it.hasNext()) { - String componentId = (String) it.next(); - hashString.append(componentId); - } - LOGGER.debug("Time to create hashCode for page: " + (new Date().getTime() - - start. - getTime())); - return hashString.toString(); - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/PageErrorDisplay.java b/ccm-core/src/main/java/com/arsdigita/bebop/PageErrorDisplay.java deleted file mode 100755 index e424804e6..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/PageErrorDisplay.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.list.ListCellRenderer; -import com.arsdigita.util.LockableImpl; -import com.arsdigita.xml.Element; -import com.arsdigita.globalization.GlobalizedMessage; - -import java.util.Iterator; - -/** - * Displays validation errors for the page. These might have occured due to validation listeners on - * some state parameters within the page. - * - * @author Stanislav Freidin - * @version $Id: PageErrorDisplay.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class PageErrorDisplay extends List { - - private static final String COLOR = "color"; - - /** - * Constructs a new PageErrorDisplay. - */ - public PageErrorDisplay() { - this(new PageErrorModelBuilder()); - } - - /** - * Constructs a new PageErrorDisplay from the errors supplied by a list model - * builder. - * - * @param builder the {@link ListModelBuilder} that will supply the errors - * - */ - protected PageErrorDisplay(ListModelBuilder builder) { - super(builder); - setCellRenderer(new LabelCellRenderer()); - setTextColor("red"); - setClassAttr("pageErrorDisplay"); - } - - /** - * Sets the HTML color of the error messages. - * - * @param c An HTML color, such as "#99CCFF" or "red" - */ - public void setTextColor(String c) { - setAttribute(COLOR, c); - } - - /** - * Gets the HTML color of the error messages. - * - * @return the HTML color of the error messages. - */ - public String getTextColor() { - return getAttribute(COLOR); - } - - /** - * Determines if there are errors to display. - * - * @param state the current page state - * - * @return true if there are any errors to display; false otherwise. - */ - protected boolean hasErrors(PageState state) { - return (state.getErrors().hasNext()); - } - - /** - * Generates the XML for this component. If the state has no errors in it, does not generate any - * XML. - * - * @param state the current page state - * @param parent the parent XML element - */ - public void generateXML(PageState state, Element parent) { - if (hasErrors(state)) { - super.generateXML(state, parent); - } - } - - // A private class which builds a ListModel based on form errors - private static class PageErrorModelBuilder extends LockableImpl - implements ListModelBuilder { - - public PageErrorModelBuilder() { - super(); - } - - public ListModel makeModel(List l, PageState state) { - return new StringIteratorModel(state.getErrors()); - } - - } - - // A ListModel which generates items based on an Iterator - protected static class StringIteratorModel implements ListModel { - - private Iterator m_iter; - private GlobalizedMessage m_error; - private int m_i; - - public StringIteratorModel(Iterator iter) { - m_iter = iter; - m_error = null; - m_i = 0; - } - - public boolean next() { - if (!m_iter.hasNext()) { - m_i = 0; - return false; - } - - m_error = (GlobalizedMessage) m_iter.next(); - ++m_i; - - return true; - } - - private void checkState() { - if (m_i == 0) { - throw new IllegalStateException( - "next() has not been called succesfully" - ); - } - } - - public Object getElement() { - checkState(); - return m_error; - } - - public String getKey() { - checkState(); - return Integer.toString(m_i); - } - - } - - // A ListCellRenderer that renders labels - private static class LabelCellRenderer implements ListCellRenderer { - - public Component getComponent(List list, PageState state, Object value, - String key, int index, boolean isSelected) { - return new Label((GlobalizedMessage) value); - } - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/PageFactory.java b/ccm-core/src/main/java/com/arsdigita/bebop/PageFactory.java deleted file mode 100644 index 4c148f78d..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/PageFactory.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.util.UncheckedWrapperException; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -/** - *

The PageFactory provides a framework for - * instantiating instances of the Bebop Page class in a - * project- and application-independant manner.

- * - *

History

- * - *

The traditional approach to writing bebop applications is to - * subclass the com.arsdigita.bebop.Page, adding various components to - * provide navigation & layout and writing custom XSL for styling - * purposes.

- * - *

The problem of this approach is that when multiple applications - * are combined to form a complete site, is it difficult to produce an - * integrated navigation infrastructure & uniform styling across all - * pages. In addition, by placing application specific functionality - * in a subclass of Page, the ability to reuse & embed applications - * within each other is hampered since Page objects cannot be - * nested.

- * - *

Use Case

- * - *

The PageFactory addresses the following situations

- * - *
    - *
  1. It is common for all pages on a site to have a particular - * structure. ie, header, footer, left sidebar & main content area.
  2. - * - *
  3. It is desirable to customize page structure without making code changes - * to individual applications.
  4. - *
- * - *

Example Usage

- * - *

The point of interaction for PageFactory is typically in the - * application's Dispatcher class. Rather than invoking the Page - * constructor (ie new Page(title)), applications call - * PageFactory.buildPage(title, "appname") This method - * will return an instance of Page with the currently configured - * navigation components added.

- * - *

The two compulsory arguments to the buildPage - * method are the name of the application (ie, 'forum', 'cms'), and - * the page title (either as a String or Label object). The - * application name is used as key in both the enterprise.init file - * configuration & the XSL templates. There is optionally a third - * string id parameter which provides a unique identifier - * for the page within the application. If the page class is a - * subclass of ApplicationPage this will be used to set the XML - * id attribute.

- * - *

Consider the following example (based loosely on the Simple - * Survey application):

- * - *
- * package com.arsdigita.simplesurvey.dispatcher;
- *
- * import com.arsdigita.simplesurvey.ui.IndexPanel;
- * import com.arsdigita.simplesurvey.ui.AdminPanel;
- * import com.arsdigita.simplesurvey.ui.SurveySelectionModel;
- * import com.arsdigita.bebop.BigDecimalParameter;
- * import com.arsdigita.bebop.page.BebopMapDispatcher;
- *
- * public class Dispatcher extends BebopMapDispatcher {
- *
- *   public Dispatcher() {
- *     Page index = buildIndexPage();
- *     Page admin = buildAdminPage();
- *
- *
- *     addPage("index.jsp",index);
- *     addPage("", index);
- *     addPage("admin/index.jsp",index);
- *     addPage("admin", index);
- *   }
- *
- *   private Page buildIndexPage() {
- *     SurveySelectionModel survey =
- *        new SurveySelectionModel(new BigDecimalParameter("survey"));
- *
- *     Page page = PageFactory.buildPage("simplesurvey",
- *                                       "Simple Survey",
- *                                       "index");
- *     page.add(IndexPanel(survey));
- *     page.addGlobalStateParam(survey.getStateParameter());
- *     page.lock();
- *     return page;
- *   }
- *
- *   private Page buildAdminPage() {
- *     SurveySelectionModel survey =
- *        new SurveySelectionModel(new BigDecimalParameter("survey"));
- *
- *     Page page = PageFactory.buildPage("simplesurvey",
- *                                       "Simple Survey Administration",
- *                                       "admin");
- *     page.add(AdminPanel(survey));
- *     page.addGlobalStateParam(survey.getStateParameter());
- *     page.lock();
- *     return page;
- *   }
- *
- * }
- * 
- * - *

Updating existing applications

- * - *

The process of updating existing applications to make use of the - * PageFactory varies according to the complexity of the application - * in question.

- * - *

In the simplest case where an application has not subclassed the - * Page class, then it is just a case of replacing calls to new - * Page(title) with PageFactory.buildPage("appname", - * title).

- * - *

When an application has subclassed Page, then the initial - * approach is to change the subclass in question so that it derives - * from SimpleContainer instead of Page. Any calls to the - * addGlobalStateParam or addRequestListener - * methods can be moved from the constructor into the - * register method where there will be direct access to - * the Page object.

- * - *

Configuring the page factory

- * - *

The com.arsdigita.bebop.base_page system property - * may be used to specify the full name of a subclass of Page which - * provides the constructor signature detailed in the - * setPageClass method. If omitted it defaults to - * BasePage.

- * - *

The com.arsdigita.ui package provides an - * alternative subclass called SimplePage which supports - * specification.

- * - * @see com.arsdigita.bebop.BasePage - */ -public class PageFactory { - - private static Class s_page; - private static Constructor s_cons; - private static boolean initialized = false; - - static void init() { - if (initialized) { - return; - } - setPageClass(BebopConfig.getConfig().getBasePageClass()); - } - - /** - * Sets the page class to instantiate. The - * class should have a public constructor that - * takes three arguments. The first 'String' - * argument is the name of the application, the - * second 'Label' is the page title, and the - * third (optionally null) argument is a page - * id (unique string with this application). - * - * The common case is to inherit from ApplicationPage - * and pass these three arguments straight through - * to its constructor. - * - * @param page the page class - */ - public static void setPageClass(Class page) { - try { - s_cons = page.getConstructor(new Class[] { - String.class, Label.class, String.class - }); - s_page = page; - initialized = true; - } catch (NoSuchMethodException ex) { - throw new UncheckedWrapperException( - "cannot find constructor " + s_page.getName() + - "(String application, Label title, String id)", - ex - ); - } catch (SecurityException ex) { - throw new UncheckedWrapperException( - "cannot retrieve constructor for " + s_page.getName(), - ex - ); - } - } - - /** - * Instantiates a new instance of the Page class. - * - * @param application the application name - * @param title the page title - * @return a subclass of com.arsdigita.bebop.Page - */ - public static Page buildPage(String application, - String title) { - return buildPage(application, new Label(title)); - } - - /** - * Instantiates a new instance of the Page class, - * with the optional unique page id string. - * - * @param application the application name - * @param title the page title - * @param id the page id within the application - * @return a subclass of com.arsdigita.bebop.Page - */ - public static Page buildPage(String application, - String title, - String id) { - return buildPage(application, new Label(title), id); - } - - /** - * Instantiates a new instance of the Page class. - * - * @param application the application name - * @param title the label for the page title - * @return a subclass of com.arsdigita.bebop.Page - */ - public static Page buildPage(String application, - Label title) { - return buildPage(application, title, null); - } - - /** - * Instantiates a new instance of the Page class, - * with the optional unique page id string. - * - * @param application the application name - * @param title the label for the page title - * @param id the page id within the application - * @return a subclass of com.arsdigita.bebop.Page - */ - public static Page buildPage(String application, - Label title, - String id) { - init(); - Page page = null; - try { - page = (Page)s_cons.newInstance(new Object[] { - application, title, id - }); - } catch (InstantiationException ex) { - throw new UncheckedWrapperException( - "cannot instantiate page class " + s_page.getName(), ex - ); - } catch (IllegalArgumentException ex) { - throw new UncheckedWrapperException( - "cannot instantiate page class " + s_page.getName(), ex - ); - } catch (IllegalAccessException ex) { - throw new UncheckedWrapperException( - "constructor for page class " + s_page.getName() + - " is not public", ex - ); - } catch (InvocationTargetException ex) { - throw new UncheckedWrapperException( - "cannot instantiate page class " + s_page.getName(), ex - ); - } - - return page; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/PageState.java b/ccm-core/src/main/java/com/arsdigita/bebop/PageState.java deleted file mode 100644 index 5b45cd646..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/PageState.java +++ /dev/null @@ -1,1078 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.parameters.BitSetParameter; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.util.Traversal; -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.util.Assert; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.web.ParameterMap; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.web.URL; -import com.arsdigita.web.Web; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.BitSet; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -/** - *

The request-specific data (state) for a {@link Page}. All - * methods that need access to the state of the associated page during - * the processing of an HTTP request are passed a - * PageState object. Since PageState - * contains request-specific data, it should only be live during the - * servicing of one HTTP request. This class has several related - * responsibilites:

- * - *

State Management

- * - *

PageState objects store the values for global and - * component state parameters and are responsible for retrieving these - * values from the HTTP request. Components can access the values of - * their state parameters through the {@link #getValue getValue} and - * {@link #setValue setValue} methods.

- * - *

This class is also responsible for serializing the current state of - * the page in a variety of ways for inclusion in the output: {@link - * #generateXML generateXML} adds the state to an XML element and {@link - * #stateAsURL stateAsURL} encodes the page's URL.

- * - *

The serialized form of the current page state can be quite large - * so the page state can also be preserved in the HttpSession, on the - * server. The Page object specifies this by calling {@link - * Page#setUsingHttpSession setUsingHttpSession(true)}. When this - * flag is set, then the page state will be preserved in the - * HttpSession, and the {@link #stateAsURL stateAsURL} method will - * only serialize the current URL and the control event. It will also - * include a URL variable that the subsequent request uses to retrieve - * the correct page state from the HttpSession. If the page state for - * a particular request cannot be found, the constructor will throw a - * {@link SessionExpiredException SessionExpiredException}.

- * - *

Up to {@link #getMaxStatesInSession getMaxStatesInSession()} - * independent copies of the page state may be stored in the - * HttpSession, to preserve the behavior of the browser's "back" - * button.

- * - *

Note: As a convention, only the component to which a - * state parameter belongs should modify it by calling - * getValue and setValue. All other objects - * should manipulate the state of a component only through - * well-defined methods on the component.

- * - *

Control Events

- * - *

The control event consists of a pair of strings, the name - * of the event and its associated value. Components use the - * control event to send themselves a "delayed signal", i.e. a signal - * that is triggered when the same page is requested again through a - * link that has been generated with the result of {@link #stateAsURL} - * as the target. The component can then access the name and value of - * the event with calls to {@link #getControlEventName} and {@link - * #getControlEventValue}.

- * - *

Typically, a component will contain code corresponding to the following - * in its generateXML method: - *

- *  public void generateXML(PageState state, Element parent) {
- *  if ( isVisible(state) ) {
- *      MyComponent target = firePrintEvent(state);
- *      Element link = new Element ("bebop:link", BEBOP_XML_NS);
- *      parent.addContent(link);
- *      target.generateURL(state, link);
- *      target.exportAttributes(link);
- *      target.generateExtraXMLAttributes(state, link);
- *      target.getChild().generateXML(state, link);
- *  }
- *  }
- * 
- * (In reality, the component would not write a bebop:link element - * directly, but use a {@link ControlLink} to do that automatically.) - *

When the user clicks on the link that the above generateXML - * method produces, the component's respond method is called - * and can access the name and value of the event with code similar to the - * following: - *

- *   public void respond(PageState state) {
- *     String name = state.getControlEventName();
- *     String value = state.getControlEventValue();
- *     if ( "name".equals(name) ) {
- *       doSomeStateChange(value);
- *     } else {
- *       throw new IllegalArgumentException("Can't understand event " + name);
- *     }
- *   }
- * 
- * - * - *

Temporary Storage

- * - *

Request local variables make it possible to store arbitrary objects - * in the page state and allow components (and other objects) to cache - * results of previous computations. For example, the {@link Form} - * component uses a request local variable to store the {@link FormData} it - * generates from the request and make it acessible to the widgets it - * contains, and to other components through calling {@link - * Form#getFormData Form.getFormData(state)}. See the documentation for - * {@link RequestLocal} on how to use your own request local variables. - * - *

Convenience Access to Related Objects

- * - *

PageState objects store references to the HTTP request - * and response that is currently being served. Components are free to - * manipulate these objects as they see fit. - *

- * - * @author David Lutterkort - * @author Uday Mathur - */ -public class PageState { - - /** Class specific logger instance. */ - private static final Logger LOGGER = LogManager.getLogger(PageState.class); - - /** The underlying Page object. */ - private Page m_page; - - /** - * The request to which this object corresponds - */ - private HttpServletRequest m_request; - - /** - * The response to which results will be sent. - */ - private HttpServletResponse m_response; - - /** - * The values of global and component specific state parameters extracted - * from the request. - */ - private FormData m_pageState; - - /** - * Temporary storage of arbitrary objects. - */ - private Map m_attributes; - - /** - * The component that currently holds exclusive access to the control - * event. Usually null, unlesss a component calls {@link - * #grabControlEvent}. - */ - private Component m_grabbingComponent; - - /** - * The visibility state of components. For a component with n = - * Page.stateIndex, the n-th bit is set if the component is not - * visible. - * - *

Initially, this variable refers to Page.m_invisible. Only when a - * call to {@link #setVisible} is made, is that value - * copied. (Copy-on-write) - */ - private BitSet m_invisible; - private boolean m_visibilityDirty = true; - - private int m_nextSession; - - private final static String SESSION_ATTRIBUTE = - "com.arsdigita.bebop.FormData"; - private final static String SESSION_COUNTER_ATTRIBUTE = - "com.arsdigita.bebop.FormData.counter"; - private final static String CURRENT_SESSION_PARAMETER = - "bbp.session"; - private final static String PAGE_STATE_ATTRIBUTE = - "com.arsdigita.bebop.PageState"; - - private static int s_maxSessions = 10; - - private Traversal m_visibilityTraversal = new VisibilityTraversal(); - private List m_visibleComponents; - - /** - * Returns the maximum number of independent page states that may be stored - * in the HttpSession, for preserving the behavior of the "back" button. - * @return the maximum number of independent page states that may - * be stored in the HttpSession. - */ - public static int getMaxStatesInSession() { - return s_maxSessions; - } - - /** - * Sets the maximum number of independent page states that may be stored in - * the HttpSession, for preserving the behavior of the "back" button. - * @param x the maximum number of independent page states to store - * in the HttpSession. - */ - public static void setMaxStatesInSession(int x) { - s_maxSessions = x; - } - - /** - * Returns the page state object for the given request, or null if none - * exists yet. - * - * @param request The servlet request. - * - * @return The page state object for the given request, or null if none - * exists yet. - **/ - public static PageState getPageState(HttpServletRequest request) { - return (PageState) request.getAttribute(PAGE_STATE_ATTRIBUTE); - } - - /** - * Returns the page state object for the current request, or null if none - * exists yet. - * - * @return The page state object for the current request, or null if none - * exists yet. - **/ - - public static PageState getPageState() { - HttpServletRequest request = DispatcherHelper.getRequest(); - - if (request == null) { - return null; - } else { - return getPageState(request); - } - } - - /** - * Construct the PageState for an HTTP request. - * - * Calls {@link FormModel#process process} on the form model underlying - * the page model and calls {@link Component#respond respond} on the - * component from which the request originated. - * - * @param page The model of the page - * @param request The request being served - * @param response Where the response should be sent - * - * @pre request != null && request.get(page.PAGE_SELECTED) != null - * @pre response != null && ! response.isCommitted() - * @pre page != null - * - */ - public PageState(Page page, HttpServletRequest request, - HttpServletResponse response) - throws ServletException { - m_page = page; - - if ( m_page == null ) { - m_page = new Page(); - m_page.lock(); - } - - m_request = request; - m_response = response; - - FormData pageStateFromSession = null; - if (m_page.isUsingHttpSession()) { - pageStateFromSession = getStateFromSession(); - } - - // always treat the request as a submission - m_pageState = new FormData(m_page.getStateModel(), request, true, - pageStateFromSession); - m_page.getStateModel().process(this, m_pageState); - m_invisible = decodeVisibility(); - - // Add the PageState to the request - m_request.setAttribute(PAGE_STATE_ATTRIBUTE, this); - } - - - protected BitSet decodeVisibility() { - BitSet difference = (BitSet)m_pageState.get(Page.INVISIBLE); - BitSet current = (BitSet)m_page.m_invisible.clone(); - if (difference != null) { - current.xor(difference); - } - return current; - } - - protected BitSet encodeVisibility(BitSet current) { - BitSet difference = (BitSet)m_page.m_invisible.clone(); - difference.xor(current); - return difference; - } - - /** - * Helper function that returns the PageState object from the - * HttpSession. - */ - private FormData getStateFromSession() throws SessionExpiredException { - HttpSession session = m_request.getSession(true); - FormData state = null; - - // have to bootstrap this manually from the request - String key = - m_request.getParameter(CURRENT_SESSION_PARAMETER); - if (key != null) { - state = (FormData)session.getAttribute(SESSION_ATTRIBUTE + key); - // session is expired if we're looking for a particular - // page state and couldn't find it. - if (state == null) { - throw new SessionExpiredException(); - } - } - return state; - } - - /** - * Process the PageState and fire necessary events. Call respond on the - * selected bebop component. - */ - public void respond() throws ServletException { - String compKey = (String) m_pageState.get(Page.SELECTED); - - if ( compKey != null ) { - Component c = m_page.getComponent(compKey); - if ( c == null ) { - throw new ServletException("Selected component not on page."); - } - try { - c.respond(this); - } finally { - } - } - } - - /** - * Return the page for which this object holds the state. - * - * @return the page for which this object holds state. - * @post return != null - */ - public final Page getPage() { - return m_page; - } - - - /** - * Return the request object for the HTTP request. - * - * @return The HTTP request being currently served. - */ - public final HttpServletRequest getRequest() { - return m_request; - } - - /** - * Return the response object for the HTTP response. - * - * @return The response for the HTTP request being served - */ - public final HttpServletResponse getResponse() { - return m_response; - } - - /** - * The index of a component in the page model - * - * @pre c != null - */ - private int indexOf(Component c) { - return m_page.stateIndex(c); - } - - /** - * Return true is the comonent c is currently - * visible. This method should only be used by components - * internally. All other objects should call {@link Component#isVisible - * Component.isVisible} on the component. - * - * @param c the components whose visibility should be returned - * @return true if the component is visible - */ - public boolean isVisible(Component c) { - if ( ! getPage().stateContains(c)) { - return true; - } - if ( m_invisible == null ) { - return m_page.isVisibleDefault(c); - } else { - return ! m_invisible.get(indexOf(c)); - } - } - - /** - * Return true is the component c is currently - * visible on the page displayed to the end user. This is true - * if the component's visibility flag is set, and it is in a - * container visible to the end user. - * - *

This method is different than isVisible which - * only returns the visibility flag for the individual component. - * - * @param c the components whose visibility should be returned - * @return true if the component is visible - */ - public boolean isVisibleOnPage(Component c) { - if (m_visibleComponents == null) { - m_visibleComponents = new ArrayList(); - m_visibilityTraversal.preorder(getPage().getPanel()); - } - - return m_visibleComponents.contains(c); - } - - private class VisibilityTraversal extends Traversal { - protected void act(Component c) { - m_visibleComponents.add(c); - } - - protected int test(Component c) { - if (isVisible(c)) { - return PERFORM_ACTION; - } else { - // not visible, so neither are children - return SKIP_SUBTREE; - } - } - } - - - /** - * Set the visibility of a component. Calls to this method change the - * default visibility set with {@link Page#setVisibleDefault - * Page.setVisibleDefault}. This method should only be used by - * components internally. All other objects should call {@link - * Component#setVisible Component.setVisible} on the component. - * - *

Without explicit changes, a component is visible. - * - * @param c the component whose visibility is to be changed - * @param v true if the component should be visible - */ - public void setVisible(final Component c, final boolean v) { - if (Assert.isEnabled()) { - Assert.isTrue(getPage().stateContains(c), - "Component" + c + " is not registered on Page " + - getPage()); - } - - if (m_invisible == null || m_invisible == getPage().m_invisible) { - // copy on write - m_invisible = (BitSet) getPage().m_invisible.clone(); - } - - int i = indexOf(c); - - if (v) { - if (!m_invisible.get(i)) - return; - m_invisible.clear(i); - } else { - if (m_invisible.get(i)) - return; - m_invisible.set(i); - } - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Marking visibility parameter as dirty " + m_request + " because of component " + c); - } - // Do this only in toURL since the RLE is expensive - //m_pageState.put(Page.INVISIBLE, encodeVisibility(m_invisible)); - m_visibilityDirty = true; - m_visibleComponents = null; - } - - /** - * Resets the given component and its children to their default - * visibility. Also resets the state parameters of the given - * component and its children to null. This is not a speedy - * method. Do not call gratuitously. - * - * @param c the parent component whose state parameters and - * visibility you wish to reset. - * */ - public void reset(Component c) { - getPage().reset(this, c); - } - -// /** -// * Store an attribute keyed on the object key. The -// * PageState puts no restrictions on what can be stored as -// * an attribute or how they are managed. -// * -// * To remove an attribute, call setAttribute(key, null). -// * -// * The attributes are only accessible as long as the -// * PageState is alive, typically only for the duration of -// * the request. -// * -// * @deprecated Use either setAttribute on {@link -// * HttpServletRequest the HTTP request object}, or, preferrably, use a -// * {@link RequestLocal request local} variable. Will be removed on -// * 2001-06-13. -// * -// */ -// public void setAttribute(Object key, Object value) { -// if ( m_attributes == null ) { -// m_attributes = new HashMap(); -// } -// m_attributes.put(key, value); -// } - -// /** -// * Get the value of an attribute stored with the same key with {@link -// * #setAttribute setAttribute}. -// * -// * @deprecated Use either getAttribute on {@link -// * HttpServletRequest the HTTP request object}, or, preferrably, use a -// * {@link RequestLocal request local} variable. Will be removed on -// * 2001-06-13. -// * -// */ -// public Object getAttribute(Object key) { -// if ( m_attributes == null ) { -// return null; -// } -// return m_attributes.get(key); -// } - - /** - * Set the value of the state parameter p. The concrete - * type of value must be compatible with the type of the - * state parameter. - * - *

The parameter must have been previously added with a call to - * {@link Page#addComponentStateParam - * Page.getComponentStateParam}. This method should only be called by - * the component that added the state parameter to the page. Users of - * the component should manipulate the parameter through methods the - * component provides. - * - * @param p a state parameter - * @param value the new value for this state parameter. The concrete - * type depends on the type of the parameter being used. - */ - public void setValue(ParameterModel p, Object value) { - m_pageState.put(p.getName(), value); - } - - /** - * Get the value of state parameter p. The concrete type of - * the return value depends on the type of the parameter being - * used. - * - *

The parameter must have been previously added with a call to - * {@link Page#addComponentStateParam - * Page.addComponentStateParam}. This method should only be called by - * the component that added the state parameter to the page. Users of - * the component should manipulate the parameter through methods the - * component provides. - * - * @param p a state parameter - * @return the current value for this state parameter. The concrete - * type depends on the type of the parameter being used. - */ - public Object getValue(ParameterModel p) { - return m_pageState.get(p.getName()); - } - - /** - * Get the value of a global state parameter. - * @deprecated Use {@link #getValue(ParameterModel m)} instead. If you - * don't have a reference to the parameter model, you should not be - * calling this method. Instead, the component that registered the - * parameter should provide methods to manipulate it. Will be removed - * 2001-06-20. - */ - public Object getGlobalValue(String name) { - // WRS 9/7/01 - // work-around: m_pageState will throw an exception when we get - // a named parameter that's not in the form model. But for - // API stability, we need to trap this and return null; since - // there's no way to tell what set of globalValues are legal - // in any particular page--that's what ParameterModels are for. - try { - return m_pageState.get(m_page.parameterName(name)); - } catch (IllegalArgumentException iae) { - return null; - } - } - -// /** -// * Change the value of a global parameter -// * -// * @deprecated Use {@link #setValue(ParameterModel m, Object o)} -// * instead. If you don't have a reference to the parameter model, you -// * should not be calling this method. Instead, the component that -// * registered the parameter should provide methods to manipulate -// * it. Will be removed 2001-06-20. -// */ -// public void setGlobalValue(String name, Object value) { -// m_pageState.put(m_page.parameterName(name), value); -// } - - // Handling the control event - - /** - * Grab the control event. Until {@link #releaseControlEvent - * releaseControlEvent(c)} is called, only the component c - * can be used in calls to {@link #setControlEvent setControlEvent}. - * @pre c != null - */ - public void grabControlEvent(Component c) { - if ( m_grabbingComponent != null && m_grabbingComponent != c ) { - throw new IllegalStateException - ("Component " + m_grabbingComponent.toString() + - " already holds the control event"); - } - m_grabbingComponent = c; - } - - /** - * Set the control event. The control event is a delayed event - * that only gets acted on when another request to this Page - * is made. It is used to set which component should receive the - * submission and lets the component set one component-specific name-value - * pair to be used in the submission. - *

- * After calling this method links and hidden form controls generated - * with {@link #stateAsURL} have been amended so that if the user clicks such a - * link or submits a form containing those hidden controls, the exact - * same values can be retrieved with {@link #getControlEventName} and - * {@link #getControlEventValue}. - *

- * Stateful components can use the control event to change their - * state. For example, a tabbed pane t might call - * setControlEvent(t, "select", "2") just prior to - * generating the link for its second tab. - *

- * The values of name and value have no - * meaning to the page state, they are simply passed through without - * modifications. It is up to specific components what values of - * name and value are meaningful for it. - * - * @param c - * @param name The component specific name of the event, may be - * null - * @param value The component specific value of the event, may be - * null - * @pre c == null || getPage().stateContains(c) - */ - public void setControlEvent(Component c, String name, String value) { - Assert.isTrue(c == null || getPage().stateContains(c), - "c == null || getPage().stateContains(c)"); - if ( m_grabbingComponent != null && m_grabbingComponent != c ) { - throw new IllegalStateException - ("Component " + m_grabbingComponent.toString() + - " holds the control event"); - } - // FIXME: This needs to take named components into account - String key = null; - if (c != null) { - key = c.getKey(); - if (key == null) { - key = Integer.toString(m_page.stateIndex(c)); - } - } - m_pageState.put(Page.SELECTED, - (c == null) ? null : key); - m_pageState.put(Page.CONTROL_EVENT, name); - m_pageState.put(Page.CONTROL_VALUE, value); - } - - /** - * Set the control event. Both the event name and its value will be - * null. - */ - public void setControlEvent(Component c) { - setControlEvent(c, null, null); - } - - /** - * Clear the control event. Links and hidden form variables generated - * after this call will not cause any component's respond method to be - * called. - * - * @throws IllegalStateException if any component has grabbed the - * control event but not released it yet. - */ - public void clearControlEvent() { - setControlEvent(null); - } - - /** - * Get the name of the control event. - */ - public String getControlEventName() { - return (String) m_pageState.get(Page.CONTROL_EVENT); - } - - /** - * Get the value associated with the control event. - */ - public String getControlEventValue() { - return (String) m_pageState.get(Page.CONTROL_VALUE); - } - - /** - * Release the control event. - * @param c The component that was passed to the last call to - * grabControlEvent - * @pre getPage().stateContains(c) - */ - public void releaseControlEvent(Component c) { - if ( m_grabbingComponent == null ) { - throw new IllegalStateException - ("No component holds the control event, but " + c.toString() + - " tries to release it."); - } - if ( c != m_grabbingComponent ) { - throw new IllegalStateException - ("Component " + m_grabbingComponent.toString() + - " holds the control event, but " + c.toString() + - " tries to release it."); - } - m_grabbingComponent = null; - } - - /** - * Add elements to parent that represent the current page - * state. For each component or global state parameter on the page, a - * <bebop:pageState> element is added to - * parent. The name and value attributes - * of the element contain the name and value of the state parameters as - * they should appear in an HTTP request made back to this page. - * - *

Generates DOM fragment: - *

-     * <bebop:pageState name=... value=.../>
-     * 
- * - * @param form This is the form in which the hidden variables will exist - * - * @see #setControlEvent setControlEvent - */ - public void generateXML(Element parent) { - synchronizeVisibility(); - - for ( Iterator i = m_pageState.getParameters().iterator(); - i.hasNext(); ) { - ParameterData p = (ParameterData) i.next(); - - String key = (String) p.getName(); - String value = p.marshal(); - - if ( value != null ) { - Element hidden = parent.newChildElement("bebop:pageState", - Component.BEBOP_XML_NS); - hidden.addAttribute("name", key); - hidden.addAttribute("value", value); - } - } - } - - public void generateXML(Element parent, Iterator models) { - synchronizeVisibility(); - - List excludeParams = new ArrayList(); - if (models != null) { - while (models.hasNext()) { - excludeParams.add(((ParameterModel)models.next()).getName()); - } - } - - for ( Iterator i = m_pageState.getParameters().iterator(); - i.hasNext(); ) { - ParameterData p = (ParameterData) i.next(); - - String key = (String) p.getName(); - String value = p.marshal(); - - if (value == null || excludeParams.contains(key)) { - continue; - } - - Element hidden = parent.newChildElement("bebop:pageState", - Component.BEBOP_XML_NS); - hidden.addAttribute("name", key); - hidden.addAttribute("value", value); - } - } - - /** - * Export the current page state into the HttpSession by putting the entire - * m_pageState (type FormData) object into the HttpSession. - * - *

- * Package visibility is intentional. - * - * @see #setControlEvent setControlEvent */ - void stateAsHttpSession() { - // create session if we need to - HttpSession session = m_request.getSession(true); - // get + increment counter counter - Integer counterObj = - (Integer)session.getAttribute(SESSION_COUNTER_ATTRIBUTE); - if (counterObj == null) { - m_nextSession = 0; - } else { - m_nextSession = counterObj.intValue() + 1; - } - - session.setAttribute(SESSION_ATTRIBUTE + m_nextSession, m_pageState); - session.setAttribute(SESSION_COUNTER_ATTRIBUTE, - new Integer(m_nextSession)); - // remove an old session - int toRemove = m_nextSession - s_maxSessions; - if (toRemove >= 0) { - session.removeAttribute(SESSION_ATTRIBUTE + toRemove); - } - } - - /** - *

Write the current state of the page as a URL.

- * - *

The URL representing the state points to the same URL that - * the current request was made from and contains a query string - * that represents the page state.

- * - *

If the current page has the useHttpSession flag set, then - * the URL query string that we generate will only contain the - * current value of the control event, and the rest of the page - * state is preserved via the HttpSession. Otherwise, the query - * string contains the entire page state.

- * - * @return a string containing the current state of a page. - * @see #setControlEvent setControlEvent - * @see Page#isUsingHttpSession Page.isUsingHttpSession - * @see Page#setUsingHttpSession Page.setUsingHttpSession - */ - public String stateAsURL() throws IOException { - return m_response.encodeURL(toURL().toString()); - } - - public final URL toURL() { - synchronizeVisibility(); - - final ParameterMap params = new ParameterMap(); - - if (LOGGER.isDebugEnabled()) { - dumpVisibility(); - } - - final Iterator iter = m_pageState.getParameters().iterator(); - - while (iter.hasNext()) { - final ParameterData data = (ParameterData) iter.next(); - - final String key = (String) data.getName(); - - if (!m_page.isUsingHttpSession() - || Page.CONTROL_EVENT_KEYS.contains(key)) { - final String value = data.marshal(); - - if (value != null) { - params.setParameter(key, value); - } - } - - } - - if (m_page.isUsingHttpSession()) { - params.setParameter(CURRENT_SESSION_PARAMETER, - new Integer(m_nextSession)); - } - - return URL.request(m_request, params); - } - - - private void synchronizeVisibility() { - if (m_visibilityDirty) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Encoding visibility parameter " + m_request); - } - m_pageState.put(Page.INVISIBLE, encodeVisibility(m_invisible)); - m_visibilityDirty = false; - } - } - - private void dumpVisibility() { - BitSetParameter raw = new BitSetParameter("raw", BitSetParameter.ENCODE_RAW); - BitSetParameter dgap = new BitSetParameter("dgap", BitSetParameter.ENCODE_DGAP); - - BitSet current = (BitSet)m_invisible; - BitSet base = (BitSet)m_page.m_invisible; - - BitSet difference = (BitSet)current.clone(); - difference.xor(base); - - LOGGER.debug("Current: " + current.toString()); - LOGGER.debug("Default: " + base.toString()); - LOGGER.debug("Difference: " + difference.toString()); - - LOGGER.debug("Current RAW: " + raw.marshal(current)); - LOGGER.debug("Default RAW: " + raw.marshal(base)); - LOGGER.debug("Difference RAW: " + raw.marshal(difference)); - - LOGGER.debug("Current DGAP: " + dgap.marshal(current)); - LOGGER.debug("Default DGAP: " + dgap.marshal(base)); - LOGGER.debug("Difference DGAP: " + dgap.marshal(difference)); - - LOGGER.debug("Current Result: " + dgap.unmarshal(dgap.marshal(current))); - LOGGER.debug("Default Result: " + dgap.unmarshal(dgap.marshal(base))); - LOGGER.debug("Difference Result: " + dgap.unmarshal(dgap.marshal(difference))); - - if (!current.equals(dgap.unmarshal(dgap.marshal(current)))) { - LOGGER.debug("Broken marshal/unmarshal for current"); - } - if (!base.equals(dgap.unmarshal(dgap.marshal(base)))) { - LOGGER.debug("Broken marshal/unmarshal for default"); - } - if (!difference.equals(dgap.unmarshal(dgap.marshal(difference)))) { - LOGGER.debug("Broken marshal/unmarshal for difference"); - } - } - - /** - * Get the URI to which the current request was made. Copes with the - * black magic that is needed to get the URI if the request was handled - * through a dispatcher. If no dispatcher was involved in the request, - * returns the request URI from the HTTP request. - * - * @post return != null - * - * @return the URI to which the current request was made - */ - public String getRequestURI() { - final URL url = Web.getWebContext().getRequestURL(); - - if (url == null) { - return m_request.getRequestURI(); - } else { - return url.getRequestURI(); - } - } - - /** - * Return true if all the global and component state parameters - * extracted from the HTTP request were successfully validated against - * their parameter models in the {@link Page}. - * - * @return true if the values of all global and component state - * parameters are valid with respect to their parameter models. - */ - public boolean isValid() { - return m_pageState.isValid(); - } - - /** - * Return an iterator over the errors that occurred in trying to - * validate the state parameters against their parameter models in - * {@link Page}. - * - * @return an iterator over validation errors - * @see FormData#getErrors - */ - public Iterator getErrors() { - return m_pageState.getAllErrors(); - } - - /** - * Return a string with all the errors that occurred in trying to - * validate the state parameters against their parameter models in - * {@link Page}. The string consists simply of the concatenation of all - * error messages that the result of {@link #getErrors} iterates over. - * - * @return all validation errors concatenated into one string - */ - public String getErrorsString() { - StringBuffer s = new StringBuffer(); - for (Iterator i = m_pageState.getAllErrors(); i.hasNext(); ) { - s.append(i.next().toString()); - s.append(System.getProperty("line.separator")); - } - return s.toString(); - } - - /** - * Force the validation of all global and component state parameters - * against their parameter models. This method only needs to be called if - * the values of the parameters have been changed with {@link #setValue - * setValue} or {@link #setGlobalValue setGlobalValue} and may now - * contain invalid values. - */ - public void forceValidate() { - m_pageState.forceValidate(this); - } - - /** Convert to a String. - * @return a human-readable representation of this. - */ - public String toString() { - String newLine = System.getProperty("line.separator"); - String result = - super.toString() + " = {" + newLine - + "m_page = " + m_page + "," + newLine - + "m_request = " + m_request + "," + newLine - + "m_response = " + m_response + "," + newLine - // FormData - + "m_pageState = " + m_pageState.asString() + "," + newLine - + "m_attributes = " + m_attributes + "," + newLine - // Map to FormData - + "," + newLine - + "m_grabbingComponent = " + m_grabbingComponent + "," + newLine - + "m_invisible = " + m_invisible + newLine - + "}"; - return result; - } - - /** - * Clear the control event then redirect to the new page state. - * - * @param isCommitRequested indicates if a commit required before the redirect - * - * @throws RedirectSignal to the new page state - * - * @see RedirectSignal#RedirectSignal(String, boolean) - */ - public void redirectWithoutControlEvent(boolean isCommitRequested) { - clearControlEvent(); - try { - throw new RedirectSignal(stateAsURL(), true); - } catch (IOException ioe) { - throw new UncheckedWrapperException(ioe); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/PaginationModelBuilder.java b/ccm-core/src/main/java/com/arsdigita/bebop/PaginationModelBuilder.java deleted file mode 100755 index 892e971b3..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/PaginationModelBuilder.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -/** - * A model builder for - * the {@link Paginator} component. - * - *

The {@link #getTotalSize(Paginator, PageState)} method of this - * class is called during the generation of page links for a - * Paginator component. When using a - * Paginator component with a {@link List} or a {@link - * Table}, you can achieve greater flexibility in terms of caching and - * performance by having the model builder implement this interface. - * - *

Unlike other model builder classes in Bebop, there is no - * PaginationModel class, as this would only be an int. - * - * @see Paginator - * - * @author Phong Nguyen - * @version $Id$ - * @since 4.6.10 - **/ -public interface PaginationModelBuilder { - - // $Change: 44247 $ - // $Revision$ - // $DateTime: 2004/08/16 18:10:38 $ - // $Author$ - - /** - * Returns the total number of results to paginate. - * - * @param paginator the Paginator instance that invoked this method - * @param state the current page state - * @return the total number of results to paginate. - **/ - int getTotalSize(Paginator paginator, PageState state); - - /** - * Determines whether the paginator should be visible in the request - * represented by state. - * This should normally delegate to the isVisible method of the - * associated displayed component. - * - * @return true if the paginator is visible in the request; - * false otherwise. - * - * @param state represents the current request - * @return true if the component is visible; false - * otherwise. - * @pre state != null - */ - boolean isVisible(PageState state); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Paginator.java b/ccm-core/src/main/java/com/arsdigita/bebop/Paginator.java deleted file mode 100755 index 8bbac5f16..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Paginator.java +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.parameters.IntegerParameter; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.util.LockableImpl; -import com.arsdigita.xml.Element; - -/** - * A pagination component used to select different page views from a list of - * items. - * - *

In most cases, this component will be used with either a {@link - * List} or a {@link Table}. Here is an example on how to use this pagination - * component with a Table: - * - *


- * Table myTable = new Table(new myTableModelBuilder(),
- *                           new DefaultTableColumnModel());
- * Paginator pgntr = new Paginator((PaginationModelBuilder) myTable.getModelBuilder(), 10);
- *
- * Page p = new Page();
- * p.add(pgntr);
- * p.add(myTable);
- * 
- * - *

The model builder that is used in - * myTable was designed to also implement the {@link PaginationModelBuilder} - * interface. With both interfaces being implemented by the same class, it is - * much easier to cache the results of operations performed on the {@link com.arsdigita.persistence.DataQuery} - * used to generate the results. - * - *


- * public class myTableModelBuilder extends LockableImpl
- *     implements TableModelBuilder, PaginatedModelBuilder {
- *
- *     private RequestLocal m_query;
- *
- *     public myTableModelBuilder() {
- *         super();
- *         m_query = new RequestLocal();
- *     }
- *
- *     private getDataQuery(PageState state) {
- *         // returns the DataQuery used to generate rows for the table
- *     }
- *
- *     public int getTotalSize(Paginator pgntr, PageState state) {
- *         DataQuery query = getDataQuery(state);
- *         query.setRange(new Integer(pgntr.getFirst(state)),
- *                        new Integer(pgntr.getLast(state) + 1));
- *         m_query.set(state, query);
- *         return (int) query.size();
- *     }
- *
- *     public TableModel makeModel(Table table, PageState state) {
- *         return new myTableModel(table, state, (DataQuery) m_query.get(state));
- *     }
- * }
- * 
- * - *

Subclasses that wish to render the page links in a different format will - * override the {@link #buildPaginationDisplay()} method. The implementation of - * this method must set the selection model used to retrieve the page number by - * calling the {@link - * #setPageNumSelectionModel(SingleSelectionModel)} method. Aside from changing - * the display, this pagination component will hide itself if - * {@link PaginationModelBuilder#getTotalSize(Paginator, PageState)} is less - * than the page size (i.e., a single page can be used to display the entire - * results). This default behavior can be changed by calling {@link #setHiddenIfSinglePage(boolean)} - * with - * false. - * - * @see PaginationModelBuilder - * - * @author Phong Nguyen - * @version $Id$ - * @since 4.6.10 - * - */ -public class Paginator extends SimpleContainer implements Resettable { - - // $Change: 44247 $ - // $Revision$ - // $DateTime: 2004/08/16 18:10:38 $ - // $Author$ - // The builder which returns the total number of items to - // paginate. - private PaginationModelBuilder m_builder; - // The selection model that returns the selected page number. The - // contained ParameterModel should be a StringParameter, since - // this is the default for List and Table. - private SingleSelectionModel m_pageNumModel; - // The selection model that returns the number of items to display - // for one page. - private SingleSelectionModel m_pageSizeModel; - // This is used to determine if this component should be hidden - // when there is only a single page to display. Defaults to true. - private boolean m_hiddenIfSinglePage; - // A label that contains a space, " ". This is used to insert - // spaces between the page links from within the list's - // generateXML() method. - private BoxPanel m_spacePanel; - private Label m_space; - // defined in List.java - private static final String _SELECT_EVENT = "s"; - - /** - * Constructor. - * - * @param builder The builder used to retrieve the total number of results - * to paginate. - * @param defaultPageSize The default number of results to display on each - * page. - * - */ - public Paginator(PaginationModelBuilder builder, int defaultPageSize) { - super(); - - m_builder = builder; - m_hiddenIfSinglePage = true; - - // Create the selection model which returns the size of one - // page and set its default value. - IntegerParameter sizeParam = new IntegerParameter("ps"); - sizeParam.setDefaultValue(new Integer(defaultPageSize)); - sizeParam.setDefaultOverridesNull(true); - m_pageSizeModel = new ParameterSingleSelectionModel(sizeParam); - - // Builds the display for rendering page links, this also sets - // the page number selection model. - buildPaginationDisplay(); - } - - /** - * Builds the display for rendering the page links. Subclasses can override - * this method to provide a different rendering of the page links. If this - * is the case, make sure that the {@link - * #setPageNumSelectionModel(SingleSelectionModel)} method is called to set - * the selection model for retrieving the selected page number. - * - */ - protected void buildPaginationDisplay() { - PaginatorList list = new PaginatorList(new PageListModelBuilder(this, getPaginationModelBuilder())); - setPageNumSelectionModel(list.getSelectionModel()); - - // This is used within the list's generateXML() method to - // insert spaces between the page links. - m_space = new Label(" ", false); - m_spacePanel = new BoxPanel(BoxPanel.HORIZONTAL); - m_spacePanel.add(m_space); - - BoxPanel display = new BoxPanel(BoxPanel.HORIZONTAL); - display.add(new Label(GlobalizationUtil.globalize("bebop.page"))); - display.add(list); - display.add(m_space); - add(display); - } - - /** - * Sets the selection model that is used for returning the selected page - * number. Subclasses that override the {@link - * #buildPaginationDisplay()} method will need to call this method. - * - * @param pageNumModel The selection model used for returning the selected - * page number. - * - */ - protected void setPageNumSelectionModel(SingleSelectionModel pageNumModel) { - m_pageNumModel = pageNumModel; - } - - /** - * Returns the selected page number. - * - * @param state Represents the current state of the request. - * @return The selected page number. - * - */ - public int getSelectedPageNum(PageState state) { - String pageNum = (String) m_pageNumModel.getSelectedKey(state); - if (pageNum == null) { - m_pageNumModel.setSelectedKey(state, "1"); - return 1; - } - return Integer.parseInt(pageNum); - } - - /** - * Sets the selected page number. - * - * @param state Represents the current state of the request. - * @param pageNum The number of the page to set as selected. - * - */ - public void setSelectedPageNum(PageState state, int pageNum) { - m_pageNumModel.setSelectedKey(state, String.valueOf(pageNum)); - } - - /** - * Returns the number of items to display per page. - * - * @param state Represents the current state of the request. - * @return The number of items to display per page. - * - */ - public int getPageSize(PageState state) { - return ((Integer) m_pageSizeModel.getSelectedKey(state)).intValue(); - } - - /** - * Sets the number of items to display per page. - * - * @param state Represents the current state of the request. - * @param pageSize The number of items to display per page. - * - */ - public void setPageSize(PageState state, int pageSize) { - m_pageSizeModel.setSelectedKey(state, new Integer(pageSize)); - } - - /** - * This returns the total number of pages that will be displayed by this - * paginator. - * - * @param state The page state - */ - public int getTotalPages(PageState state) { - int totalSize = m_builder.getTotalSize(this, state); - int pageSize = getPageSize(state); - int minSize = totalSize / pageSize; - if (minSize * pageSize == totalSize) { - return minSize; - } else { - return minSize + 1; - } - } - - /** - * Returns the number of the first item to display. - * - * @param state Represents the current state of the request. - * @return The number of the first item to display. - * - */ - public int getFirst(PageState state) { - return ((getSelectedPageNum(state) - 1) * getPageSize(state)) + 1; - } - - /** - * Returns the number of the last item to display. - * - * @param state Represents the current state of the request. - * @return The number of teh last item to display. - * - */ - public int getLast(PageState state) { - // NOTE: If the returned integer is used for - // DataQuery.setRange(int, int), then it needs to be - // incremented by 1. - return (getSelectedPageNum(state) * getPageSize(state)); - } - - /** - * Returns the builder that is used to retrieve the total number of items to - * paginate. - * - * @return The builder used to compute the total number of items to - * paginate. - * - */ - public PaginationModelBuilder getPaginationModelBuilder() { - return m_builder; - } - - /** - * Specifies whether this component is hidden if there is only a single page - * of items to display. - * - * @return Returns - * true if this component is hidden when there is only a single - * page to view. - * - */ - public boolean isHiddenIfSinglePage() { - return m_hiddenIfSinglePage; - } - - /** - * Sets whether or not this component should be hidden if there is only a - * single page of items to display. - * - * @param isHidden By default, this component will be hidden when there is - * only a single page to display. Set this to - * false if this is not the desired effect. - * - */ - public void setHiddenIfSinglePage(boolean isHidden) { - m_hiddenIfSinglePage = isHidden; - } - - /** - * Returns - * true if this component is visible. This component will not - * be visible if the paginator model builder's isVisible method reports - * false. If this component is set to be hidden when there is only a single - * page to display, then the total page size returned from the {@link PaginationModelBuilder} - * object must be greater than the number of items per page. - * - * @param state Represents the current state of the request. - * @return Returns - * true if this component is visible. - * - * @see #getPageSize(PageState) - * @see PaginationModelBuilder#getTotalSize(Paginator, PageState) - * - */ - @Override - public boolean isVisible(PageState state) { - return (super.isVisible(state) - && m_builder.isVisible(state) - && ((!m_hiddenIfSinglePage) - || m_builder.getTotalSize(this, state) > getPageSize(state))); - } - - /** - * Register the page size selection model. - * - * @param p The page to register with. - * - */ - @Override - public void register(Page p) { - super.register(p); - p.setVisibleDefault(m_spacePanel, false); - p.addComponentStateParam(this, m_pageSizeModel.getStateParameter()); - } - - /** - * Resets this component by clearing the selected page. - * - * @param state Represents the current state of the request. - * - */ - public void reset(PageState state) { - m_pageNumModel.clearSelection(state); - } - - /** - * This class was added to provide greater flexibility in displaying the - * page links. Links can be displayed in a space separated list to support - * wrapping or in a table with a fixed number of page links per row. By - * default the page links will be rendered inside a one-cell table. If the - * number of page links to display per line is specified, then each page - * link will be rendered in it's own cell. - * - */ - private class PaginatorList extends List { - - public PaginatorList(ListModelBuilder builder) { - super(builder); - } - - /** - * If the number of page links to display per line is specified then the - * generated xml will be similar to that of a Table. Else, it will be - * similar to a simple container. - * - * @param state Represents the current state of the request. - * @param parent The element to which to attach the XML. - * - */ - @Override - public void generateXML(PageState state, Element parent) { - if (!this.isVisible(state)) { - return; - } - - // maybe display the Previous arrow - if (getSelectedPageNum(state) > 1) { - state.setControlEvent(this, _SELECT_EVENT, - Integer.toString(getSelectedPageNum(state) - 1)); - (new ControlLink(new Label("<"))).generateXML(state, parent); - (new Label(" ")).generateXML(state, parent); - state.setControlEvent(this, _SELECT_EVENT, - Integer.toString(getSelectedPageNum(state) - 1)); - (new ControlLink(new Label(GlobalizationUtil.globalize("bebop.previous")))).generateXML(state, parent); - (new Label(" ")).generateXML(state, parent); - } - - ListModel m = getModel(state); - Object selKey = getSelectedKey(state); - Component c; - int i = 0; - while (m.next()) { - String key = m.getKey(); - // Converting both keys to String for comparison - // since ListModel.getKey returns a String - boolean selected = (selKey != null) && (key != null) - && selKey.toString().equals(key.toString()); - - state.setControlEvent(this, _SELECT_EVENT, m.getKey()); - c = getCellRenderer().getComponent(this, state, m.getElement(), - m.getKey(), i, selected); - c.generateXML(state, parent); - m_space.generateXML(state, parent); - i += 1; - } - - // maybe display the next arrow - if (getSelectedPageNum(state) < getTotalPages(state)) { - state.setControlEvent(this, _SELECT_EVENT, - Integer.toString(getSelectedPageNum(state) + 1)); - (new Label(" ")).generateXML(state, parent); - (new ControlLink(new Label(GlobalizationUtil.globalize("bebop.next")))).generateXML(state, parent); - (new Label(" ")).generateXML(state, parent); - state.setControlEvent(this, _SELECT_EVENT, - Integer.toString(getSelectedPageNum(state) + 1)); - (new ControlLink(new Label(">"))).generateXML(state, parent); - } - - state.clearControlEvent(); - } - } - - /** - * A list model builder for the pagination list. - * - */ - private class PageListModelBuilder extends LockableImpl - implements ListModelBuilder { - - Paginator m_paginator; - PaginationModelBuilder m_builder; - - public PageListModelBuilder(Paginator paginator, - PaginationModelBuilder builder) { - super(); - m_paginator = paginator; - m_builder = builder; - } - - public ListModel makeModel(List list, PageState state) { - return new PageListModel(m_builder.getTotalSize(m_paginator, state), - getPageSize(state), - getSelectedPageNum(state)); - } - } - - /** - * A list model for the pagination list which is used to generate the text - * for the page links. - * - */ - private class PageListModel extends LockableImpl - implements ListModel { - - int m_totalSize; - int m_pageSize; - int m_pageCount; - int m_current; - - public PageListModel(int totalSize, int pageSize, int current) { - super(); - m_totalSize = totalSize; - m_pageSize = pageSize; - m_pageCount = 0; - m_current = current; - } - - public boolean next() { - if (m_pageCount * m_pageSize < m_totalSize) { - m_pageCount += 1; - return true; - } - return false; - } - - public Object getElement() { - /* - * TODO: Remove or relocate this int begin = ((m_pageCount-1) * - * m_pageSize) + 1; int end = (m_pageCount) * m_pageSize; if (end > - * m_totalSize) { end = m_totalSize; } return "" + begin + "-" + - * end; - */ - if (Math.abs(m_current - m_pageCount) <= 5 - || m_pageCount == 1 - || m_pageCount * m_pageSize >= m_totalSize) { - return Integer.toString(m_pageCount); - } else { - return "."; - } - } - - public String getKey() { - return Integer.toString(m_pageCount); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/ParameterSingleSelectionModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/ParameterSingleSelectionModel.java deleted file mode 100755 index 997e7827b..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/ParameterSingleSelectionModel.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.util.Assert; - -/** - * An implementation of {@link SingleSelectionModel} that uses a state parameter - * for managing the currently selected key. - *

- * - * A typical use case for this class is as follows. - *

- *
- * 
- * public TheConstructor() {
- *   m_parameter = new StringParameter("my_key");
- *   m_sel = new ParameterSingleSelectionModel(m_parameter);
- * }
- *
- * public void register(Page p) {
- *   p.addComponent(this);
- *   p.addComponentStateParam(this, m_param);
- * }
- * 
- * 
- *
- * - * jensp 2016-02-26: Added generics - * - * @param Generics parameter - * - * @author Stanislav Freidin - * @author Jens Pelzetter - * - */ -public class ParameterSingleSelectionModel - extends AbstractSingleSelectionModel { - - private final ParameterModel m_parameter; - - /** - * Constructs a new ParameterSingleSelectionModel. - * - * @param m the parameter model that will be used to keep track of the - * currently selected key - */ - public ParameterSingleSelectionModel(ParameterModel m) { - super(); - - m_parameter = m; - } - - /** - * Returns the key that identifies the selected element. - * - * @param state a PageState value - * - * @return a String value. - */ - @Override - @SuppressWarnings("unchecked") - public T getSelectedKey(final PageState state) { - final FormModel model = state.getPage().getStateModel(); - if (model.containsFormParam(m_parameter)) { - return (T) state.getValue(m_parameter); - } else { - return null; - } - } - - @Override - public final ParameterModel getStateParameter() { - return m_parameter; - } - - /** - * Set the selected key. - * - * @param state represents the state of the current request - * @param newKey the new selected key - */ - @Override - public void setSelectedKey(final PageState state, final Object newKey) { - final Object oldKey = getSelectedKey(state); - - if (Assert.isEnabled()) { - final FormModel model = state.getPage().getStateModel(); - Assert.isTrue(model.containsFormParam(m_parameter), - String.format( - "Parameter %s is not part of the FormModel.", - m_parameter.getName())); - } - - state.setValue(m_parameter, newKey); - - if (newKey == null && oldKey == null) { - return; - } - - if (newKey != null && newKey.equals(oldKey)) { - return; - } - - fireStateChanged(state); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/PropertyEditor.java b/ccm-core/src/main/java/com/arsdigita/bebop/PropertyEditor.java deleted file mode 100755 index ffe48d1ad..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/PropertyEditor.java +++ /dev/null @@ -1,815 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.list.DefaultListCellRenderer; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.util.Assert; -import com.arsdigita.util.LockableImpl; -import com.arsdigita.util.SequentialMap; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.globalization.GlobalizedMessage; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; - -/** - * Maintains a set of forms that are used when editing the - * properties of some object. The component maintains a single - * display pane and a list of forms that are selectable by links. - *

- * By default, the component looks something like this: - *


- * +----------------+
- * |                |
- * |  Display Pane  |
- * |                |
- * +----------------+
- * [link to form1]
- * [link to form2]
- * [link to form3]
- * 
- * - * When the user clicks on a link, the display pane is hidden and the - * corresponding form is shown. - * - *

- * Enter foo: [           ]
- * Enter bar: [           ]
- *
- *          [Save] [Cancel]
- * 
- * - * When the user clicks the Save or Cancel button on the form, the form - * is hidden and the display pane (with its list of links) - * is shown once again. - *

- * The simple usage pattern for this class is as follows: - * - *


- * PropertyEditor editor = new PropertyEditor();
- * editor.setDisplayComponent(new FooComponent());
- * NameEditForm n = new NameEditForm();
- * editor.add("name", "Edit Name", n, n.getCancelButton());
- * AddressEditForm a = new AddressEditForm();
- * editor.add("address", "Edit Address", a, a.getCancelButton());
- * 
- * - * The PropertyEditor will automatically add the right - * listeners to the forms. - *

- * This class is used extensively in the default authoring kit steps, - * especially PageEdit and TextPageBody in CMS. - *

- * Advanced Usage:
- * The PropertyEditor may be used to maintain - * visibility of any components, not just forms. The - * {@link #addComponent(String, String, Component)} method - * can be used to add an arbitrary component to the editor. The - * component will be shown in the list of links, along with other components - * and/or forms. The component will be shown as usual when the user clicks - * on a link. However, you must be sure to include a call to - * {@link #showDisplayPane(PageState)} when the component needs to be hidden. - *

- * In addition, it is possible to manually generate {@link ActionLink}s - * that will display the right components in the editor. The - * {@link #addComponent(String, Component)} method can be used to add - * a component to the PropertyEditor without automatically - * generating the link for it. The {@link #addVisibilityListener(ActionLink, String)} - * method can then be used to add an appropriate {@link ActionListener} to any - * {@link ActionLink}. For example: - * - *

// Add a form
- * Form fooForm = new FooForm();
- * editor.addComponent(FOO_FORM, fooForm);
- * editor.addListeners(fooForm, fooForm.getCancelButton());
- * // Create a link that shows the form
- * fooLink = new ActionLink("Edit the Foo property");
- * editor.addVisibilityListener(fooLink, FOO_FORM);
- * - * Note that the visibility of the form will be handled automatically. There - * is no need to show or hide it manually. This approach allows - * greater flexibility in placing links on a page. The links may be - * part of the editor's display pane, but they do not have to be. - *

- * More-advanced Usage:
- * The PropertyEditor is backed by a - * {@link PropertyEditorModel} through a {@link PropertyEditorModelBuilder}. - * Therefore, the PropertyEditor is a model-backed component, - * as described in the Bebop tutorials. This means that the list - * of properties for the editor could be generated dynamically during - * each request. The {@link #setModelBuilder(PropertyEditorModelBuilder)} method - * can be used to set a specialized {@link PropertyEditorModelBuilder} for the - * editor. In order to write the model builder, you may choose to extend the - * protected inner classes {@link PropertyEditor.DefaultModelBuilder} and - * {@link PropertyEditor.DefaultModel}. It is also possible to write the model - * builder and the corresponding model from scratch. However, most people won't - * need to do this. - *

- * For example, SecurityPropertyEditor uses a custom - * {@link PropertyEditorModelBuilder} in order to hide the links for properties - * which the web user is not allowed to edit. - *

- * - * @author Stanislav Freidin - * @version $Id: PropertyEditor.java 1638 2007-09-17 11:48:34Z chrisg23 $ - */ -public class PropertyEditor extends SimpleContainer { - - private SequentialMap m_forms; - private SequentialMap m_labels; - private Component m_display; - private Container m_displayPane; - private List m_list; - private PropertyEditorModelBuilder m_builder; - private RequestLocal m_model; - private java.util.List m_additionalDisplayComponents = new ArrayList(); - - /** - * Constructs a new, empty PropertyEditor. - * The {@link #setDisplayComponent(Component)} method must be called before - * this component is locked. - */ - public PropertyEditor() { - this(null); - } - - /** - * Constructs a new PropertyEditor with the given - * display component. The pane defaults to a {@link - * com.arsdigita.bebop.SimpleContainer}. - * - * @param display the display component - */ - public PropertyEditor(Component display) { - this(display, new SimpleContainer()); - } - - /** - * Constructs a new PropertyEditor with the given - * display component and display pane. - * - * @param display the display component - * @param pane the display pane. The caller should pass in a - * freshly allocated Container. - */ - public PropertyEditor(Component display, Container pane) { - super(); - setClassAttr("propertyEditor"); - m_forms = new SequentialMap(); - m_labels = new SequentialMap(); - m_display = null; - - m_displayPane = pane; - super.add(m_displayPane); - - m_list = new List(); - m_list.setCellRenderer(new IdentityCellRenderer()); - - // Change listener: reset visibility - // Should a ComponentSelectionModel be used here instead ? It's tempting, - // but there doesn't seem to be a real need for it - m_list.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - PageState state = e.getPageState(); - - // Get the visible component - Component c = null; - if ( !m_list.isSelected(state) ) { - // Select the display pane - c = m_displayPane; - } else { - c = getComponent(getSelectedComponentKey(state)); - } - - // Iterate over the forms - for(Iterator i = m_forms.values().iterator(); i.hasNext(); ) { - Component f = (Component)i.next(); - f.setVisible(state, (f == c)); - } - - m_displayPane.setVisible(state, (m_displayPane == c)); - } - }); - - // Don't add the list yet; add it when we add the display - // component - - if(display != null) - setDisplayComponent(display); - - // Prepare the model builder - setModelBuilder(new DefaultModelBuilder()); - - m_model = new RequestLocal() { - @Override - protected Object initialValue(PageState s) { - return getModelBuilder().makeModel(PropertyEditor.this, s); - } - }; - } - - /** Set the display component visible by default, and the - * form(s) invisible by default. - */ - @Override - public void register(Page p) { - Assert.exists(m_display, "display component"); - - p.setVisibleDefault(m_displayPane, true); - - for(Iterator i = m_forms.values().iterator(); i.hasNext(); ) { - p.setVisibleDefault((Component)i.next(), false); - } - } - - /** - * Hides the form(s) and shows the display pane. - * - * @param state the page state - */ - public void showDisplayPane(PageState state) { - m_list.clearSelection(state); - } - - /** - * Shows the component that is identified by the specified key. - * - * @param state the page state - * @param key - */ - public void showComponent(PageState state, String key) { - m_list.setSelectedKey(state, key); - } - - /** - * Returns the key of the currently visible component, or null if - * the display pane is currently visible. - * @param state the page state - * - * @return the key of the currently visible component, or null if the - * display pane is visible. - */ - public String getSelectedComponentKey(PageState state) { - return (String)m_list.getSelectedKey(state); - } - - /** - * add an additional component below the list of links - * @param c - */ - public void addDisplayComponent(Component c) { - m_additionalDisplayComponents.add(c); - } - /** - * Adds the display component if it has not been added already. - * - * @param c the display component to add - */ - public void setDisplayComponent(Component c) { - if(m_display != null) { - throw new IllegalStateException("Display component has already been set"); - } - - m_displayPane.add(c); - m_displayPane.add(m_list); - Iterator it = m_additionalDisplayComponents.iterator(); - while (it.hasNext()) { - m_displayPane.add((Component)it.next()); - } - - m_display = c; - } - - /** - * Adds a component to the property editor. The component will be - * completely invisible. It is up to the user to call - * {@link #showComponent(PageState, String)} to display the component and to - * call {@link #showDisplayPane(PageState)} when the component needs to be hidden. - * - * @param key the symbolic key for the component (must be unique - * for this PropertyEditor) - * @param c the component - */ - public void addComponent(String key, Component c) { - m_forms.put(key, c); - super.add(c); - } - - /** - * Adds a component to the list of links. It is up to the component to - * correctly call {@link #showDisplayPane(PageState)} when it is done. - * - * @param key the symbolic key for the component (must be unique - * for this PropertyEditor) - * @param label the label for the link - * @param c the component - * @deprecated use addComponent(String,GlobalizedMessage,Component) instead - */ - public void addComponent(String key, String label, Component c) { - addComponent(key, c); - m_labels.put(key, label); - } - - /** - * Adds a component to the list of links. It is up to the component to - * correctly call {@link #showDisplayPane(PageState)} when it is done. - * - * @param key the symbolic key for the component (must be unique - * for this PropertyEditor) - * @param label the label for the link - * @param c the component - */ - public void addComponent(String key, GlobalizedMessage label, Component c) { - addComponent(key, c); - m_labels.put(key, label); - } - - /** - * Adds a form to the set of forms that can be used to edit the - * properties. - * - * @param key the symbolic key for the form (must be unique - * for this PropertyEditor) - * @param label the label for the link - * @param form the form component - * @deprecated use add(String,GlobalizedMessage,Form) instead. - */ - public void add(String key, String label, Form form) { - addComponent(key, label, form); - addProcessListener(form); - } - - /** - * Adds a form to the set of forms that can be used to edit the - * properties. - * - * @param key the symbolic key for the form (must be unique - * for this PropertyEditor) - * @param label the label for the link - * @param form the form component - */ - public void add(String key, GlobalizedMessage label, Form form) { - addComponent(key, label, form); - addProcessListener(form); - } - - /** - * Adds a form to the set of forms that can be used to edit the - * properties. - * - * @param key the symbolic key for the form (must be unique - * for this PropertyEditor) - * @param label the label for the link - * @param form the form component - * @param cancelButton the Cancel button on the form - * @deprecated use add(String,GlobalizedMessage,Form,Submit) instead. - */ - public void add(String key, String label, Form form, Submit cancelButton) { - add(key, label, form); - addListeners(form, cancelButton); - } - - /** - * Adds a form to the set of forms that can be used to edit the - * properties. - * - * @param key the symbolic key for the form (must be unique - * for this PropertyEditor) - * @param label the label for the link - * @param form the form component - * @param cancelButton the Cancel button on the form - */ - public void add(String key, GlobalizedMessage label, Form form, Submit cancelButton) { - add(key, label, form); - addListeners(form, cancelButton); - } - - /** - * Adds a form to the set of forms that can be used to edit the - * properties. - * - * @param key the symbolic key for the form (must be unique - * for this PropertyEditor) - * @param label the label for the link - * @param formSection the form component - * - * @pre !(formSection instanceof Form) - * @deprecated use add(String,GlobalizedMessage,FormSection) instead. - */ - public void add(String key, String label, FormSection formSection) { - if (formSection instanceof Form) { - throw new IllegalArgumentException("formSection is an instance of Form"); - } - Form form = new Form("property" + key); - form.add(new FormErrorDisplay(form), ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - form.add(formSection); - form.setMethod(Form.POST); - form.setEncType("multipart/form-data"); - add(key, label , form); - } - - /** - * Adds a form to the set of forms that can be used to edit the - * properties. - * - * @param key the symbolic key for the form (must be unique - * for this PropertyEditor) - * @param label the label for the link - * @param formSection the form component - * - * @pre !(formSection instanceof Form) - */ - public void add(String key, GlobalizedMessage label, FormSection formSection) { - if (formSection instanceof Form) { - throw new IllegalArgumentException("formSection is an instance of Form"); - } - Form form = new Form("property" + key); - form.add(new FormErrorDisplay(form), ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - form.add(formSection); - form.setMethod(Form.POST); - form.setEncType("multipart/form-data"); - add(key, label , form); - } - - /** - * Adds a form to the set of forms that can be used to edit the properties. - * - * @param key the symbolic key for the form (must be unique - * for this PropertyEditor) - * @param label the label for the link - * @param formSection the form component - * @param cancelButton the Cancel button on the form - * @deprecated use add(String,GlobalizedMessage,FormSection,Submit) instead. - */ - public void add(String key, - String label, - FormSection formSection, - Submit cancelButton) { - Form form = new Form("property" + key); - form.add(new FormErrorDisplay(form), ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - form.add(formSection); - form.setMethod(Form.POST); - form.setEncType("multipart/form-data"); - add(key, label , form, cancelButton); - } - - /** - * Adds a form to the set of forms that can be used to edit the - * properties. - * - * @param key the symbolic key for the form (must be unique - * for this PropertyEditor) - * @param label the label for the link as a GlobalizedMessage - * @param formSection the form component - * @param cancelButton the Cancel button on the form - */ - public void add(String key, - GlobalizedMessage label, - FormSection formSection, - Submit cancelButton) { - Form form = new Form("property" + key); - form.add(new FormErrorDisplay(form), ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - form.add(formSection); - form.setMethod(Form.POST); - form.setEncType("multipart/form-data"); - add(key, label , form, cancelButton); - } - - /** - * Retrieves the component at the specified key. - * - * @param key the key of the component to retrieve - * @return a component that has been added to this - * PropertyEditor at the specified key, or null - * if no such component exists. - */ - public Component getComponent(String key) { - return (Component)m_forms.get(key); - } - - /** - * Adds a submission listener to the form that will hide all components - * and show the display pane. This method should be used to add - * submission listeners to forms that are buried deep inside some - * component and are not members of this PropertyEditor. - * - * @param form the form - * @param cancelButton the Cancel button on the form - */ - public void addCancelListener(FormSection form, Submit cancelButton) { - // Add a different submission listener for each form since the - // cancel button may be different - final Submit theButton = cancelButton; - - form.addSubmissionListener(new FormSubmissionListener() { - @Override - public void submitted(FormSectionEvent e) throws FormProcessException { - PageState state = e.getPageState(); - if(theButton.isSelected(state)) { - showDisplayPane(state); - throw new FormProcessException( - "Submission Cancelled", - GlobalizationUtil.globalize("bebop.cancel.msg")); - } - } - }); - } - - /** - * Adds a process listener to the form that will hide all components - * and show the display pane. This method should be used to add - * process listeners to forms that are buried deep inside some - * component and are not members of this PropertyEditor. - * - * @param form the form - */ - public void addProcessListener(FormSection form) { - form.addProcessListener(new FormProcessListener() { - @Override - public void process(FormSectionEvent e) throws FormProcessException { - PageState state = e.getPageState(); - showDisplayPane(state); - } - }); - } - - /** - * Adds all required listeners to the form to ensure that - * if the form is either submitted successfully or cancelled, - * the display pane will be shown. This method should be used - * to add listeners to forms that are buried deep inside some - * component, and are not members of this PropertyEditor. - * - * @param form the form - * @param cancelButton the Cancel button on the form - */ - public void addListeners(FormSection form, Submit cancelButton) { - addCancelListener(form, cancelButton); - addProcessListener(form); - } - - /** - * This method can be used to add an {@link ActionListener} to any - * {@link ActionLink}, causing the action link to show the specified - * component when it is clicked. For example, this method may be useful - * if the {@link ActionLink} that is supposed to show the component is - * buried somewhere deep within the UI. - * - * @param l the {@link ActionLink} - * @param key the key of the component that will be shown when the link - * is clicked, as specified in the - * {@link #addComponent(String, Component)} method - * @see #addComponent(String, Component) - */ - public void addVisibilityListener(ActionLink l, String key) { - final String t_key = key; - l.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - showComponent(e.getPageState(), t_key); - } - }); - } - - /** - * Returns the {@link List} that contains all the links. - * @return the {@link List} that contains all the links. - */ - public List getList() { - return m_list; - } - - /** - * Returns the {@link PropertyEditorModelBuilder} that supplies this - * property editor with its {@link PropertyEditorModel} during each - * request. - * - * @return the {@link PropertyEditorModelBuilder} for this component. - */ - protected final PropertyEditorModelBuilder getModelBuilder() { - return m_builder; - } - - /** - * Sets the {@link PropertyEditorModelBuilder} that will supply this - * property editor with its {@link PropertyEditorModel} during each - * request. - * @param b the property editor model builder - */ - protected final void setModelBuilder(PropertyEditorModelBuilder b) { - Assert.isUnlocked(this); - m_builder = b; - m_list.setModelBuilder(new BuilderAdapter(this)); - } - - /** - * Returns the {@link PropertyEditorModel} in use during the current - * request. - * - * @param s represents the current request - * @return the {@link PropertyEditorModel} that supplies the properties - * for the current request. - */ - protected final PropertyEditorModel getModel(PageState s) { - return (PropertyEditorModel)m_model.get(s); - } - - /** - * Returns the display component. - * @return the display component. - */ - public Component getDisplayComponent() { - return m_display; - } - - /** - * Returns the display pane (component + list). - * @return the display pane (component + list). - */ - public Container getDisplayPane() { - return m_displayPane; - } - - /** - * Returns the map of labels. - * @return the map of labels. - */ - protected SequentialMap getLabelsMap() { - return m_labels; - } - - /** - * Locks this component. - */ - @Override - public void lock() { - getModelBuilder().lock(); - super.lock(); - } - - /** - * Renders the components generated by the model directly - */ - protected static class IdentityCellRenderer extends DefaultListCellRenderer { - - @Override - public Component getComponent(List list, PageState state, Object value, - String key, int index, boolean isSelected) { - return (Component)value; - } - } - - /** - * Default implementation of the {@link PropertyEditorModelBuilder}. - * Takes in a SequentialMap of key->label, and constructs a ControlLink for each - * label. - */ - protected static class DefaultModelBuilder - extends LockableImpl implements PropertyEditorModelBuilder { - - public DefaultModelBuilder() { - super(); - } - - /** - * Return an iterator of all properties of the specified property - * editor. These properties should be passed into the constructor - * of the {@link PropertyEditor.DefaultModel} - * @param p - * @return - */ - protected Iterator getProperties(PropertyEditor p) { - return p.getLabelsMap().entrySet().iterator(); - } - - /** - * Construct a {@link PropertyEditorModel} for the current - * request. - */ - @Override - public PropertyEditorModel makeModel(PropertyEditor p, PageState s) { - return new DefaultModel(getProperties(p)); - } - } - - /** - * Internal class with default implementation of the {@link PropertyEditorModel}. - * Takes in an iterator of key->label pairs, and constructs a ControlLink - * for each label. - */ - protected static class DefaultModel implements PropertyEditorModel { - - protected Iterator m_iter; - protected Map.Entry m_entry; - - public DefaultModel(Iterator iter) { - m_iter = iter; - m_entry = null; - } - - @Override - public boolean next() { - if(!m_iter.hasNext()) { - m_entry = null; - return false; - } - m_entry = (Map.Entry)m_iter.next(); - return true; - } - - /** - * Actually retrieve action link and label. Will be executed at each - * request to ensure proper localization. - * @return - */ - @Override - public Component getComponent() { - Assert.exists(m_entry); - if ( m_entry.getValue() instanceof GlobalizedMessage ) { - ControlLink l = new ControlLink(new - Label((GlobalizedMessage)m_entry.getValue())); - l.setClassAttr("actionLink"); - return l; - } else { - ControlLink l = new ControlLink(new Label((String)m_entry.getValue())); - - l.setClassAttr("actionLink"); - return l; - } - } - - @Override - public Object getKey() { - Assert.exists(m_entry); - return m_entry.getKey(); - } - } - - /** - * Adapts a {@link PropertyEditorModelBuilder} to a {@link ListModelBuilder} - */ - private static final class BuilderAdapter extends LockableImpl - implements ListModelBuilder { - - private final PropertyEditor m_parent; - - public BuilderAdapter(PropertyEditor parent) { - super(); - m_parent = parent; - } - - @Override - public ListModel makeModel(List l, PageState state) { - return new ModelAdapter(m_parent.getModel(state)); - } - } - - /** - * Adapts a {@link PropertyEditorModel} to a {@link ListModel} - */ - private static final class ModelAdapter implements ListModel { - - private final PropertyEditorModel m_model; - - public ModelAdapter(PropertyEditorModel model) { - m_model = model; - } - - @Override - public boolean next() { return m_model.next(); } - @Override - public Object getElement() { return m_model.getComponent(); } - @Override - public String getKey() { return m_model.getKey().toString(); } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/PropertyEditorModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/PropertyEditorModel.java deleted file mode 100755 index cd3aff8bf..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/PropertyEditorModel.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -/** - * Provides properties for the {@link PropertyEditor} during - * each request. This class is intended for advanced users only. - * - * @author Stanislav Freidin - * @version $Id: PropertyEditorModel.java 287 2005-02-22 00:29:02Z sskracic $ - * @see PropertyEditorModelBuilder - */ -public interface PropertyEditorModel { - - - /** - * Advances to the next property, if possible. - * - * @return false if there are no more properties; - * true otherwise. - */ - boolean next(); - - /** - * Returns the component that should act as a "button" for editing the - * property. Typically, this method returns a {@link ControlLink} - * of some sort. When the link is clicked, the {@link PropertyEditor} - * will display the pane for editing the property. - * - * @return a component (usually a {@link ControlLink}) that will act - * as the "button" for editing the property. - */ - Component getComponent(); - - /** - * Returns the unique key of the current property, usually - * a simple String. - * - * @return the key of the current property. - */ - Object getKey(); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/PropertyEditorModelBuilder.java b/ccm-core/src/main/java/com/arsdigita/bebop/PropertyEditorModelBuilder.java deleted file mode 100755 index 9ccb0d2e0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/PropertyEditorModelBuilder.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.util.Lockable; - -/** - * Generates a {@link PropertyEditorModel} for the {@link PropertyEditor} - * during each request. This class is intended for advanced users only. - * - * @author Stanislav Freidin - * @version $Id: PropertyEditorModelBuilder.java 287 2005-02-22 00:29:02Z sskracic $ - * @see PropertyEditor - */ -public interface PropertyEditorModelBuilder extends Lockable { - - - /** - * Constructs a {@link PropertyEditorModel} for the current request. - * @param p the parent {@link PropertyEditor} - * @param s represents the current request - * @return the {@link PropertyEditorModel} for the current request. - */ - PropertyEditorModel makeModel(PropertyEditor p, PageState s); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/PropertySheetModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/PropertySheetModel.java deleted file mode 100644 index b875534ea..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/PropertySheetModel.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.globalization.GlobalizedMessage; - -/** - * An abstraction that the - * {@link PropertySheet} class uses to display a - * 2-column table of label-value pairs. - * - * @author Stanislav Freidin - * @version $Id: PropertySheetModel.java 287 2005-02-22 00:29:02Z sskracic $ - * @see PropertySheetModelBuilder - */ - -public interface PropertySheetModel { - - - /** - * Advances to the next property, if possible. - * - * @return false if there are no more properties; - * true otherwise. - */ - boolean nextRow(); - - /** - * Returns the label for the current property. - * - * @return the current label. - * @deprecated use getGlobalizedLabel() instead - */ - String getLabel(); - - /** - * Returns the GlobalizedMessage for the current property - * @return the current GlobalizedMessage - */ - GlobalizedMessage getGlobalizedLabel(); - - - /** - * Returns the string representation of the current property. - * - * @return the current value formatted as a string. - */ - String getValue(); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/RequestLocal.java b/ccm-core/src/main/java/com/arsdigita/bebop/RequestLocal.java deleted file mode 100644 index 9672340a3..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/RequestLocal.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import javax.servlet.http.HttpServletRequest; -import java.util.HashMap; -import java.util.Map; - -/** - * A variable whose value is local to each request. Objects that need to store - * values that change in every request should declare them to be - * RequestLocal. These variables hold their values only during a - * duration of a request. They get reinitialized by a call to {@link - * #initialValue(PageState)} for every new HTTP request. - * - *

For example, a class that wants to implement a request local property - * foo would do the following:

- * - *
- * public class SomeClass {
- *     private RequestLocal m_foo;
- *     
- *     public SomeClass() {
- *       m_foo = new RequestLocal() {
- *             protected Object initialValue(PageState s) {
- *                 // Foo could be a much more complicated value
- *                 return s.getRequestURI();
- *             }
- *         };
- *     }
- *     
- *     public String getFoo(PageState s) {
- *         return (String) m_foo.get(s);
- *     }
- *     
- *     public void setFoo(PageState s, String v) {
- *         m_foo.set(s, v);
- *     }
- * }
- * 
- * - * @author David Lutterkort - * @version $Id$ - */ -public class RequestLocal { - - private static final String ATTRIBUTE_KEY = - "com.arsdigita.bebop.RequestLocal"; - - // Fetch the map used to store RequestLocals, possibly creating it along the - // way - private Map getMap(HttpServletRequest request) { - // This lock is paranoid. We can remove it if we know that only one - // thread will be touching a request object at a time. (Seems likely, - // but, like I said, I'm paranoid.) - synchronized (request) { - Map result = (Map)request.getAttribute(ATTRIBUTE_KEY); - result = (Map)request.getAttribute(ATTRIBUTE_KEY); - if (result == null) { - result = new HashMap(); - request.setAttribute(ATTRIBUTE_KEY, result); - } - return result; - } - } - - /** - * Returns the value to be used during the request represented by - * state. This method is called at most once per request, - * the first time the value of this RequestLocal is - * requested with {@link #get get}. RequestLocal must be - * subclassed, and this method must be overridden. Typically, an - * anonymous inner class will be used. - * - * - * @param state represents the current state of the request - * @return the initial value for this request local variable. - */ - protected Object initialValue(PageState state) { - return null; - } - - /** - * Returns the request-specific value for this variable for the request - * associated with state. - * - * @param state represents the current state of the request - * @return the value for this request local variable. - */ - public Object get(PageState state) { - Map map = getMap(state.getRequest()); - Object result = map.get(this); - - if ( result == null && !map.containsKey(this) ) { - result = initialValue(state); - set(state, result); - } - return result; - } - - /** - * Sets a new value for the request local variable and associates it with - * the request represented by state. - * - * @param state represents the current state of the request - * @param value the new value for this request local variable - */ - public void set(PageState state, Object value) { - set(state.getRequest(), value); - } - - /** - *

Sets a new value for the request local variable and associates it with - * the request represented by request

- * - *

This method is intended for use when a Dispatcher needs to assign some - * value to a RequestLocal for Bebop Page processing before Page processing - * begins.

- * - * @param request represents the current request - * @param value the new value for this request local variable - */ - public void set(HttpServletRequest request, Object value) { - getMap(request).put(this, value); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Resettable.java b/ccm-core/src/main/java/com/arsdigita/bebop/Resettable.java deleted file mode 100644 index 685678ed5..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Resettable.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.PageState; - -/** - * - * Interface that should be implemented by components that have - * state parameters that need to be reset when the component is shown - * to the user. The details of when the reset method is called are left - * to the application programmer. - * - * @version $Id$ - */ -public interface Resettable { - - /** - * Resets the state of the component to its original - * appearance. - * - * @param state the page state - */ - void reset(PageState state); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/SaveCancelSection.java b/ccm-core/src/main/java/com/arsdigita/bebop/SaveCancelSection.java deleted file mode 100755 index b9e6d20c1..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/SaveCancelSection.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.util.GlobalizationUtil; - -/** - * A form section with two buttons (Save and Cancel) aligned to - * the right. - * - * @author Stanislav Freidin - * @author Sören Bernstein - * @version $Id: SaveCancelSection.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class SaveCancelSection extends FormSection { - - private Submit m_saveWidget, m_cancelWidget; - - /** - * Constructs a new SaveCancelSection. - */ - public SaveCancelSection() { - super(new BoxPanel(BoxPanel.HORIZONTAL, false)); - - BoxPanel panel = (BoxPanel)getPanel(); - panel.setWidth("2%"); - - createWidgets(); - - add(m_saveWidget, BoxPanel.RIGHT); - add(m_cancelWidget, BoxPanel.RIGHT); - } - - public SaveCancelSection(Container c) { - super(c); - - createWidgets(); - add(m_saveWidget); - add(m_cancelWidget); - } - - private void createWidgets() { - m_saveWidget = new Submit("save"); - m_saveWidget.setButtonLabel(GlobalizationUtil.globalize("bebop.save")); - - m_cancelWidget = new Submit("cancel"); - m_cancelWidget.setButtonLabel(GlobalizationUtil.globalize("bebop.cancel")); - } - - /** - * Gets the Save button. - * @return the Save button. - */ - public Submit getSaveButton() { - return m_saveWidget; - } - - /** - * Gets the Cancel button. - * @return the Cancel button. - */ - public Submit getCancelButton() { - return m_cancelWidget; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/SegmentedPanel.java b/ccm-core/src/main/java/com/arsdigita/bebop/SegmentedPanel.java deleted file mode 100644 index 53beaef2d..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/SegmentedPanel.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import static com.arsdigita.bebop.Component.*; -import static com.arsdigita.bebop.util.BebopConstants.*; - -import com.arsdigita.xml.Element; -import com.arsdigita.util.Assert; - -import com.arsdigita.bebop.util.BebopConstants; -import java.util.Iterator; - -/** - * Generates a list of segments. Each segment consists of a header (which could - * be any Bebop component) and a body (which, likewise, could be any component). - * The entire SegmentedPanel look roughly like this: - * - *

- * ----------------------
- * Header 1
- * ----------------------
- * Body 1
- * More Body 1
- * Even more Body 1
- * ----------------------
- * Header 2
- * ----------------------
- * Body 2
- * More Body 2
- * Even more Body 2
- * 
- * - * Typically, the body of each segment will be a {@link SimpleContainer} which - * contains many other components - *

- * The XML generated by this component looks something like this: - *


- * <bebop:segmentedPanel>
- *   <bebop:segment id="foo">
- *     <bebop:segmentHeader>
- *       <aRandomHeaderComponent/>
- *       <anotherRandomHeaderComponent/>
- *       ...
- *     </bebop:segmentHeader>
- *     <bebop:segmentBody>
- *       <aRandomBodyComponent>
- *       <anotherRandomBodyComponent>
- *       ...
- *     </bebop:segmentBody>
- *   </bebop:segment>
- *   ...
- * </bebop:segmentedPanel>
- * 
- * - * @see #generateXML(PageState, Element) - * - * @author Michael Pih - * @version $Id$ - */ -public class SegmentedPanel extends SimpleContainer - implements BebopConstants { - - public static final String HEADER_CLASS = "seg-header"; - - /** - * Construct a new SegmentedPanel - */ - public SegmentedPanel() { - super(); - } - - /** - * Construct a new SegmentedPanel - * - * @param idAttr the XSL ID attribute for this container - * @see SimpleComponent#setIdAttr(String) - */ - public SegmentedPanel(String idAttr) { - this(); - setIdAttr(idAttr); - } - - /** - * Add a segment to this container - * - * @param header the component that will act as the header - * @param body the component that will act as the body - * @return the new segment - */ - public Segment addSegment(Component header, Component body) { - Segment s = new Segment(header, body); - add(s); - return s; - } - - /** - * Add a segment to this container. - * - * @param segmentID the XSL ID attribute for the new segment. - * @param header the component that will act as the header. - * @param body the component that will act as the body - * @return the new segment - */ - public Segment addSegment(String segmentID, Component header, Component body) { - Segment s = addSegment(header, body); - s.setIdAttr(segmentID); - return s; - } - - /** - * Add a segment to this container. - * - * @param segmentID the XSL ID attribute for the new segment. The XSL - * template for this component will render the correct header based on the - * ID attribute - * @param body the component that will act as the body - * @return the new segment - */ - public Segment addSegment(String segmentID, Component body) { - return addSegment(segmentID, null, body); - } - - /** - * Add and return a new empty segment. - * - * @return a new empty segment that is part of the panel. - */ - public Segment addSegment() { - Segment result = new Segment(); - add(result); - return result; - } - - /** - * Generate the XML for this component, as described above - * - * @param state represents the page state for the current request - * @param parent the parent XML element - */ - @Override - public void generateXML(PageState state, Element parent) { - if (isVisible(state)) { - Element panel = parent. - newChildElement(BEBOP_SEG_PANEL, BEBOP_XML_NS); - exportAttributes(panel); - super.generateXML(state, panel); - } - } - - /** - * A single Segment within this container - */ - public static class Segment extends SimpleContainer { - - private SimpleContainer m_header; - private SimpleContainer m_body; - - /** - * Construct an empty Segment - */ - public Segment() { - this(null, null); - } - - /** - * Construct a new Segment - * - * @param header the component which will act as the header; the XSL - * class attribute for the component will be set to - * {@link #HEADER_CLASS}. Typically, this component will be a - * {@link Label} - * @param body the component which represents the body of the segment, - * Typically, this component will be a {@link SimpleContainer} or a - * panel of some sort - */ - public Segment(Component header, Component body) { - super(); - if (header != null) { - addHeader(header); - } - if (body != null) { - add(body); - } - } - - /** - * Construct a new Segment with no header - * - * @param body the component which represents the body of the segment, - * Typically, this component will be a {@link SimpleContainer} or a - * panel of some sort - */ - public Segment(Component body) { - this(null, body); - } - - /** - * Add a header component. - * - * @param c an additional header component - */ - public void addHeader(Component c) { - Assert.isUnlocked(this); - if (m_header == null) { - m_header = new SimpleContainer(BEBOP_SEG_HEADER, BEBOP_XML_NS); - super.add(m_header); - } - m_header.add(c); - } - - /** - * Add a component to the body of this segment - * - * @param c - */ - @Override - public void add(Component c) { - Assert.isUnlocked(this); - if (m_body == null) { - m_body = new SimpleContainer(BEBOP_SEG_BODY, BEBOP_XML_NS); - super.add(m_body); - } - m_body.add(c); - } - - /** - * Add a component to the body of this segment - * - * @param c - */ - @Override - public void add(Component c, int constraints) { - add(c); - } - -// @Override -// public boolean isVisible(final PageState state) { -// boolean result = super.isVisible(state); -// -// if (m_header != null) { -// result = result && m_header.isVisible(state); -// -// final Iterator children = m_header.children(); -// while (children.hasNext()) { -// final Component component = (Component) children.next(); -// result = result && component.isVisible(state); -// } -// } -// -// if (m_body != null) { -// result = result && m_body.isVisible(state); -// -// final Iterator children = m_body.children(); -// while (children.hasNext()) { -// final Component component = (Component) children.next(); -// result = result && component.isVisible(state); -// } -// } -// -// return result; -// } - - /** - * Generate the XML for this segment - * - * @param state the current page state - * @param parent the parent XML element - */ - @Override - public void generateXML(PageState state, Element parent) { - if (isVisible(state)) { - Element seg = parent. - newChildElement(BEBOP_SEGMENT, BEBOP_XML_NS); - exportAttributes(seg); - super.generateXML(state, seg); - } - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/SessionExpiredException.java b/ccm-core/src/main/java/com/arsdigita/bebop/SessionExpiredException.java deleted file mode 100755 index 9e0aad4ec..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/SessionExpiredException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import javax.servlet.ServletException; - -/** - * - * - * @version $Id: SessionExpiredException.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class SessionExpiredException extends ServletException { - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/SimpleComponent.java b/ccm-core/src/main/java/com/arsdigita/bebop/SimpleComponent.java deleted file mode 100755 index a1ef15c6f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/SimpleComponent.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import java.util.Collections; -import java.util.Iterator; - -import com.arsdigita.bebop.util.Attributes; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -/** - * A simple implementation of the Component interface. - * - * - * @author David Lutterkort - * @author Stanislav Freidin - * @author Rory Solomon - * @author Uday Mathur - * - * @version $Id: SimpleComponent.java 1498 2007-03-19 16:22:15Z apevec $ - */ -public class SimpleComponent extends Completable - implements Component, Cloneable { - - private boolean m_locked; - - /** - * The Attribute object is protected to make it easier for the Form Builder - * service to persist the SimpleComponent. Locking violation is not a - * problem since if the SimpleComponent is locked then the Attribute object - * will also be locked. - */ - protected Attributes m_attr; - - private String m_key = null; // name mangling key - - /** - * Clones a component. The clone is not locked and has its own set of - * attributes. - * - * @return the clone of a component. - * - * @throws java.lang.CloneNotSupportedException If cloning is not supported. - */ - @Override - public Object clone() throws CloneNotSupportedException { - SimpleComponent result = (SimpleComponent) super.clone(); - if (m_attr != null) { - result.m_attr = (Attributes) m_attr.clone(); - } - result.m_locked = false; - return result; - } - - /** - * Registers state parameters for the page with its model. Documentation - * from Interface Componment: - * - * A simple component with a state parameter param would do the - * following in the body of this method: - *
-     *   p.addComponent(this);
-     *   p.addComponentStateParam(this, param);
-     * 
- * - * You should override this method to set the default visibility of your - * component: - * - *
-     * public void register(Page p) {
-     *     super.register(p);
-     *     p.setVisibleDefault(childNotInitiallyShown,false);
-     *     p.setVisibleDefault(anotherChild, false);
-     * }
-     * 
- * - * Always call super.register when you override - * register. Otherwise your component may malfunction and - * produce errors like "Widget ... isn't associated with any Form" - * - * @param p - */ - @Override - public void register(Page p) { - return; - } - - /** - * Registers form parameters with the form model for this form. This method - * is only important for {@link FormSection form sections} and - * {@link com.arsdigita.bebop.form.Widget widgets} (components that have a - * connection to an HTML form). Other components can implement it as a - * no-op. - * - * @param f The form the register. - * @param m The form model to use with the form. - * - */ - @Override - public void register(Form f, FormModel m) { - return; - } - - /** - * Does processing that is special to the component receiving the click. - * - * @param state The current page state - * - * @throws javax.servlet.ServletException If an error occurs. - */ - @Override - public void respond(PageState state) - throws javax.servlet.ServletException { - } - - @Override - public Iterator children() { - return Collections.EMPTY_LIST.iterator(); - } - - /** - * Adds [J]DOM nodes for this component. Specifically for base class - * SimpleComponent, does nothing. - * - * @param state The current page state. - * @param p The parent element. All elements generated in the method will - * be child elements of {@code p}. - */ - @Override - public void generateXML(PageState state, Element p) { - return; - } - - @Override - public final boolean isLocked() { - return m_locked; - } - - @Override - public void lock() { - if (m_attr != null) { - m_attr.lock(); - } - m_locked = true; - } - - /** - * Unlocks this component. Package visibility is intentional; the only time - * a component should be unlocked is when it's pooled and gets locked - * because it's put into a page. It needs to be unlocked when the instance - * is recycled. - */ - void unlock() { - m_locked = false; - - } - - /* Working with standard component attributes */ - /** - * Gets the class attribute. - * - * @return the class attribute. - */ - @Override - public String getClassAttr() { - return getAttribute(CLASS); - } - - /** - * Sets the class attribute. - * - * @param theClass a valid XML name - */ - @Override - public void setClassAttr(String theClass) { - Assert.isUnlocked(this); - setAttribute(CLASS, theClass); - } - - /** - * Gets the style attribute. - * - * @return the style attribute. - */ - @Override - public String getStyleAttr() { - return getAttribute(STYLE); - } - - /** - * Sets the style attribute. style should be a valid CSS style, - * since its value will be copied verbatim to the output and appear as a - * style attribute in the top level XML or HTML output element. - * - * @param style a valid CSS style description for use in the - * style attribute of an HTML tag - * - * @see Standard Attributes - */ - @Override - public void setStyleAttr(String style) { - Assert.isUnlocked(this); - setAttribute(STYLE, style); - } - - /** - * Gets the id attribute. - * - * @return the id attribute. - * - * @see #setIdAttr(String id) - */ - @Override - public String getIdAttr() { - return getAttribute(ID); - } - - /** - * Sets the id attribute. id should be an XML name - * that is unique within the {@link Page Page} in which this component is - * contained. The value of id is copied literally to the output - * and not used for internal processing. - * - * @param id a valid XML identifier - * - * @see Standard Attributes - */ - @Override - public void setIdAttr(String id) { - Assert.isUnlocked(this); - setAttribute(ID, id); - } - - /* Methods for attribute management */ - /** - * Sets an attribute. Overwrites any old values. These values are used to - * generate attributes for the top level XML or HTML element that is output - * from this component with {@link #generateXML generateXML}. - * - * @param name attribute name, case insensitive - * @param value new attribute value - */ - final protected void setAttribute(String name, String value) { - Assert.isUnlocked(this); - if (m_attr == null) { - m_attr = new Attributes(); - } - m_attr.setAttribute(name, value); - } - - /** - * Gets the value of an attribute. - * - * - * @param name attribute name, case insensitive - * - * @return the string value previously set with {@link #setAttribute - * setAttribute}, or null if none was set. - * - * @see #setAttribute - */ - final protected String getAttribute(String name) { - return (m_attr == null) ? null : m_attr.getAttribute(name); - } - - /** - * Adds the attributes set with {@link #setAttribute setAttribute} to the - * element target. The attributes set with - * exportAttributes overwrite attributes with identical names - * that target might already have. - * - * @param target element to which attributes are added - * - * @see #setAttribute - */ - final protected void exportAttributes(com.arsdigita.xml.Element target) { - if (m_attr != null) { - m_attr.exportAttributes(target); - } - if (KernelConfig.getConfig().isDebugEnabled() || BebopConfig.getConfig() - .getShowClassName()) { - target.addAttribute("bebop:classname", getClass().getName(), - BEBOP_XML_NS); - } - } - - /** - * Returns true if any attributes have been set. - * - * @return true if any attributes have been set; - * false otherwise. - */ - final protected boolean hasAttributes() { - return m_attr != null; - } - - /* - * Set an arbitrary meta data attribute on the component. - * The name of the attribute in the XML will be prefixed - * with the string 'metadata.' - */ - final public void setMetaDataAttribute(String name, String value) { - setAttribute("metadata." + name, value); - } - - final public String getMetaDataAttribute(String name) { - return getAttribute("metadata." + name); - } - - /** - * Supplies a key for parameter name mangling. - * - * @param key the key to mangle - * - * @return This component. - */ - @Override - public Component setKey(String key) { - Assert.isUnlocked(this); - if (key.charAt(0) >= 0 && key.charAt(0) <= 9) { - throw new IllegalArgumentException("key \"" + key - + "\" must not start with a digit."); - } - m_key = key; - return this; - } - - /** - * Retrieves a key for parameter name mangling. - * - * @return a key for parameter name mangling. - */ - @Override - public final String getKey() { - return m_key; - } - - @Override - public boolean isVisible(PageState s) { - return s.isVisible(this); - } - - @Override - public void setVisible(PageState s, boolean v) { - s.setVisible(this, v); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/SimpleContainer.java b/ccm-core/src/main/java/com/arsdigita/bebop/SimpleContainer.java deleted file mode 100755 index 8aa3c1c50..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/SimpleContainer.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -/** - * A basic implementation of the {@link Container} interface which, by default, - * renders all of its children directly, without wrapping them in any kind of - * tag. - * - * However, the {@link #SimpleContainer(String, String)} constructor and/or the - * {@link #setTag(String)} method can be used to cause the container to wrap - * the XML for its children in an arbitrary tag. This functionality is useful - * for XSL templating. - * - * For example, a template rule might be written to arrange the children of this - * component in paragraphs: - * - *

- * // Java Code:
- * m_container = new SimpleContainer("cms:foo", CMS_XML_NS);
- *
- * // XSL code:
- * <xsl:template match="cms:foo">
- *   <xsl:for-each select="*">
- *     <p>
- *     <xsl:apply-templates select="."/>
- *     </p>
- *   </xsl:for-each>
- * </xsl:template>
- * 
- * - * @author David Lutterkort - * @author Stanislav Freidin - * @author Rory Solomon - * @author Uday Mathur - * - * @version $Id: SimpleContainer.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class SimpleContainer extends SimpleComponent implements Container { - - private List m_components; - private String m_tag, m_ns; - - /** - * Constructs a new, empty SimpleContainer. - */ - public SimpleContainer() { - this(null, null); - } - - /** - * Constructs a new, empty SimpleContainer that will - * wrap its children in the specified tag. - * - * @param tag the name of the XML element that will be used to wrap the - * children of this container - * @param ns the namespace for the tag - */ - public SimpleContainer(String tag, String ns) { - super(); - m_components = new ArrayList(); - m_tag = tag; - m_ns = ns; - } - - /** - * Adds a component to this container. - * - * @param pc the component to be added - */ - public void add(Component pc) { - Assert.isUnlocked(this); - m_components.add(pc); - } - - /** - * Adds a component to this container. - * - * @param pc the component to be added - * @param constraints this parameter is ignored. Child classes should - * override the add method if they wish to provide special handling - * of constraints. - */ - public void add(Component c, int constraints) { - add(c); - } - - /** - * Determines membership. - * @return true if the specified object is in this container; - * false otherwise. - * @param o the object type, typically a component. Type - * Object allows slicker code when o comes from any kind of collection. - */ - public boolean contains(Object o) { - return m_components.contains(o); - } - - /** - * Determines whether the container is empty. - * - * @return false if the container has any children; - * true otherwise. - */ - public boolean isEmpty() { - return m_components.isEmpty(); - } - - /** - * - * - * - */ - public int indexOf(Component pc) { - return m_components.indexOf(pc); - } - - /** - * Returns the number of children inside this container. - * @return the number of children inside this container. - */ - public int size() { - return m_components.size(); - } - - /** - * - * - * - */ - public Component get(int index) { - return (Component) m_components.get(index); - } - - /** - * Returns all the components of this container. - * @return all the components of this container. - */ - @Override - public Iterator children() { - return m_components.iterator(); - } - - /** - * Sets the XML tag that will be used to wrap the children of - * this container. - * - * @param tag the XML tag, or null if children will not be wrapped - * in any manner. - */ - protected final void setTag(String tag) { - Assert.isUnlocked(this); - m_tag = tag; - } - - /** - * Sets the XML namespace for the tag that will be used to wrap - * the children of this container. - * - * @param ns the XML namespace - */ - protected final void setNamespace(String ns) { - Assert.isUnlocked(this); - m_ns = ns; - } - - /** - * Retrieves the name of the XML tag that will be used to - * wrap the child components. - * - * @return the name of the XML tag that will be used to - * wrap the child components, or null if no tag was specified. - */ - public final String getTag() { - return m_tag; - } - - /** - * Retrieves the name of the XML namespace for the tag that will be used to - * wrap the child components. - * - * @return the name of the XML namespace for the tag that will be used to - * wrap the child components, or null if no namespace was specified. - */ - public final String getNamespace() { - return m_ns; - } - - /** - * Generates the containing element. It is added with this - * component's tag below the specified parent element. If the passed in - * element is null, the method - * passes through p. - - * @param p the parent XML element - * @return the element to which the children will be added. - */ - protected Element generateParent(Element p) { - String tag = getTag(); - if (tag == null) { - return p; - } - Element parent = p.newChildElement(tag, getNamespace()); - exportAttributes(parent); - return parent; - } - - /** - * Generates the XML for this container. If the tag property - * is nonempty, wraps the children in the specified XML tag. - * - * @param state represents the current request - * @param p the parent XML element - * @see #setTag(String) - * @see #setNamespace(String) - */ - public void generateChildrenXML(PageState state, Element p) { - for (Iterator i = children(); i.hasNext(); ) { - Component c = (Component) i.next(); - - // XXX this seems to be a redundant vis check - if ( c.isVisible(state) ) { - c.generateXML(state, p); - } - } - } - - /** - * Generates the XML for this container. If the tag property - * is nonempty, wraps the children in the specified XML tag. - * - * @param state represents the current request - * @param p the parent XML element - * @see #setTag(String) - * @see #setNamespace(String) - */ - @Override - public void generateXML(PageState state, Element p) { - if ( isVisible(state) ) { - Element parent = generateParent(p); - generateChildrenXML(state, parent); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/SingleSelectionModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/SingleSelectionModel.java deleted file mode 100755 index b6088f45f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/SingleSelectionModel.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - - -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.parameters.ParameterModel; - -/** - * Encapsulates the selection of a single object from many - * possibilities. The SingleSelectionModel allows components to - * communicate selections without tying the component that manages the - * selection in the user interface (for example a {@link List}) to the - * components that consume the selection (such as an edit form that needs - * to know which object should be edited). - * - *

Selections are identified by a key, which must identify the - * underlying object uniquely among all objects that could possibly be - * selected. For objects stored in a database, this is usually a suitable - * representation of the object's primary key. The model relies on the - * key's equals method to compare keys, and requires that the - * key's toString method produces a representation of the key - * that can be used in URL strings and hidden form controls. - * - * Edit for CCM NG: Added generics. - * - * @param Type for the key - * - * @author David Lutterkort - * @author Jens Pelzetter - */ -public interface SingleSelectionModel { - - /** - * Returns true if there is a selected element. - * - * @param state the state of the current request - * @return true if there is a selected component; - * false otherwise. - */ - boolean isSelected(PageState state); - - /** - * Returns the key that identifies the selected element. - * - * @param state a PageState value - * @return a String value. - */ - T getSelectedKey(PageState state); - - /** - * Sets the selected key. If key is not in the collection of - * objects underlying this model, an - * IllegalArgumentException is thrown. - * - * @param state the state of the current request - * @param key the selected key - * @throws IllegalArgumentException if the supplied key can not - * be selected in the context of the current request. - */ - void setSelectedKey(PageState state, T key); - - /** - * Clears the selection. - * - * @param state the state of the current request - */ - void clearSelection(PageState state); - - /** - * Adds a change listener to the model. The listener's - * stateChanged method is called whenever the selected key changes. - * - * @param changeListener a listener to notify when the selected key changes - */ - void addChangeListener(ChangeListener changeListener); - - /** - * Removes a change listener from the model. - * - * @param changeListener the listener to remove - */ - void removeChangeListener(ChangeListener changeListener); - - /** - * Returns the state parameter that will be used to keep track - * of the currently selected key. Typically, the implementing - * class will simply call: - * - * {@code return new StringParameter("foo");} - * - * This method may return null if a state parameter is not - * appropriate in the context of the implementing class. - * - * @return the state parameter to use to keep - * track of the currently selected component, or - * null if a state parameter is not appropriate. - */ - ParameterModel getStateParameter(); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/TabbedPane.java b/ccm-core/src/main/java/com/arsdigita/bebop/TabbedPane.java deleted file mode 100644 index 7e8f0656f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/TabbedPane.java +++ /dev/null @@ -1,523 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop; - -import static com.arsdigita.bebop.Component.*; - -import com.arsdigita.bebop.parameters.IntegerParameter; -import com.arsdigita.util.Assert; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Iterator; -import java.util.List; -import java.util.ArrayList; - -import javax.servlet.ServletException; - -/* FIXME: Add methods for using images in the tab strip */ -/** - * A tabbed pane that lets the user switch between components by clicking on a - * given title in the tab strip. - *

- * Tabs (components) are added using the {@link #addTab addTab} method. Each - * entry consists of a label (which is a string) and the {@link Component} that - * is displayed if the user clicks on the label. - *

- * There is always exactly one component that is currently visible, the - * component that is returned by {@link #getCurrentPane}. Without user - * interaction, this is the default pane -- that was set by - * {@link #setDefaultPane} -- or, if none has been set, the first component that - * was added to the TabbedPane. - *

- * - * @author David Lutterkort - * @author Stanislav Freidin - * @author Uday Mathur - * @version $Id$ - */ -public class TabbedPane extends SimpleContainer { - - private static final String CURRENT_PANE = "pane"; - /** - * The name for the event to change the selected pane. The value is the - * index of the pane - */ - private static final String SELECT_EVENT = "select"; - - private Pane m_defaultPane; - private IntegerParameter m_currentPaneParam; - private List m_actionListeners; - - private static final Logger LOGGER = LogManager.getLogger(TabbedPane.class - .getName()); - - /** - * Constructs an empty TabbedPane. - */ - public TabbedPane() { - m_currentPaneParam = new IntegerParameter(CURRENT_PANE); - } - - /** - * Registers with the specified root container. Adds a state parameter to - * keep track of the visible component to the page. - * - * @param p the root container to register with - * - * @pre p != null - */ - public void register(Page p) { - Assert.isUnlocked(this); - - p.addComponentStateParam(this, m_currentPaneParam); - // if there is no default pane, then set it to the first one - // in the list - Iterator i = children(); - if (!i.hasNext()) { - LOGGER.warn("TabbedPane registered with no panes"); - } else if (m_defaultPane == null) { - setDefaultPaneIndex(0); - } - while (i.hasNext()) { - Pane pane = (Pane) i.next(); - p.setVisibleDefault(pane.getComponent(), pane == m_defaultPane); - } - } - - /** - * Adds a new pane to the dialog. Assigns a rather unhelpful default label - * (the pane number) to the component. Use {@link #addTab addTab} instead. - * - * @pre pc != null - */ - public void add(Component pc) { - addTab(String.valueOf(size()), pc); - } - - /** - * Adds a new pane with layout constraints to the dialog. Ignores the - * constraints. Assigns a rather unhelpful default label (the pane number) - * to the component. Use {@link #addTab - * addTab} instead. - * - * @pre pc != null - */ - public void add(Component pc, int constraints) { - add(pc); - } - - /** - * Adds a tab and its associated component. - * - * @param label the text to display in the tab strip - * @param c the component to display when the user clicks on the - * label in the tab strip - * - * @pre label != null && c != null - */ - public void addTab(Component label, Component c) { - Assert.isUnlocked(this); - super.add(new Pane(label, c)); - } - - /** - * Adds a tab and its associated component. - * - * @param label the text to display in the tab strip - * @param c the component to display when the user clicks on the - * label in the tab strip - * - * @pre label != null && c != null - */ - public void addTab(String label, Component c) { - addTab(new Label(label), c); - } - - /** - * Adds an ActionListener, which is run whenever {@link - * #respond respond} is called. - * - * @param 1 the action listener - * - * @pre l != null - * @pre ! isLocked() - * @see #respond respond - */ - public void addActionListener(ActionListener l) { - Assert.isUnlocked(this); - if (m_actionListeners == null) { - m_actionListeners = new ArrayList(); - } - m_actionListeners.add(l); - } - - /** - * Removes a previously added ActionListener. - * - * @param 1 the action listener to remove - * - * @see #addActionListener addActionListener - */ - public void removeActionListener(ActionListener l) { - Assert.isUnlocked(this); - if (m_actionListeners == null) { - return; - } - m_actionListeners.remove(l); - } - - /** - * Fires an ActionEvent. All registered - * ActionListeners are run. The source of the event is the - * TabbedPane. - * - * @param state the current page state - * - * @pre state != null - * @see #respond respond - */ - protected void fireActionEvent(PageState state) { - ActionEvent e = null; - if (m_actionListeners == null) { - return; - } - for (Iterator i = m_actionListeners.iterator(); i.hasNext();) { - if (e == null) { - e = new ActionEvent(this, state); - } - ((ActionListener) i.next()).actionPerformed(e); - } - } - - /** - * Sets the index of the default pane, which is visible until the user - * clicks on another label in the tab strip. - * - * @param i the index of the default pane - */ - protected void setDefaultPaneIndex(int i) { - m_currentPaneParam.setDefaultValue(new Integer(i)); - m_defaultPane = (Pane) get(i); - } - - /** - * Sets the default pane, which is visible until the user clicks on another - * label in the tab strip. - * - * @param pane the component to display as the default pane - * - * @pre findPane(pane) != -1 - */ - public void setDefaultPane(Component pane) - throws IllegalArgumentException { - Assert.isUnlocked(this); - - setDefaultPaneIndex(findPaneSafe(pane)); - } - - /** - * Show or hide a particular tab - * - * @param s the page state - * @param i the index of the tab - * @param v if true, shows the tab. Otherwise, hides the tab - */ - public void setTabVisible(PageState s, int i, boolean v) { - get(i).setVisible(s, v); - } - - /** - * Show or hide a particular tab - * - * @param s the page state - * @param c the body of the tab - * @param v if true, shows the tab. Otherwise, hides the tab - */ - public void setTabVisible(PageState s, Component c, boolean v) { - int i = findPaneSafe(c); - setTabVisible(s, i, v); - } - - /** - * Determine if a particular tab is visible - * - * @param s the page state - * @param i the index of the tab - */ - public boolean isTabVisible(PageState s, int i) { - return get(i).isVisible(s); - } - - /** - * Determine if a particular tab is visible - * - * @param s the page state - * @param c the body of the tab - */ - public boolean isTabVisible(PageState s, Component c) { - int i = findPaneSafe(c); - return isTabVisible(s, i); - } - - /** - * Find the pane whose body is the specified component - * - * @param c the component - * - * @return the pane index on success, -1 if no such pane exists - */ - protected int findPane(Component c) { - int index = 0; - for (Iterator i = children(); i.hasNext(); index++) { - Pane p = (Pane) i.next(); - if (p.getComponent() == c) { - return index; - } - } - - return -1; - } - - private int findPaneSafe(Component c) { - int i = findPane(c); - if (i == -1) { - throw new IllegalArgumentException( - "Pane not part of this tabbed dialog"); - } - - return i; - } - - /** - * Gets the default pane. If no default pane has been set explicitly, the - * first pane is returned. - * - * @return the default pane, or null if there are no panes. - */ - public Component getDefaultPane() { - return m_defaultPane.getComponent(); - } - - /** - * Gets the pane with the specified label. - * - * @return the pane with the specified label, or null if a pane - * with that label does not exist. - */ - public Component getPane(Component label) { - for (Iterator i = children(); i.hasNext();) { - Pane p = (Pane) i.next(); - if (p.getLabel().equals(label)) { - return p.getComponent(); - } - } - return null; - } - - /** - * Gets the pane with the specified key in its label. Returns null if a pane - * with that label does not exist. This function exists for backward - * compatibility. - * - * @return the pane with the specified label, or null if a pane - * with that label does not exist. - */ - public Component getPane(String label) { - - for (Iterator i = children(); i.hasNext();) { - Pane p = (Pane) i.next(); - Component pLabel = p.getLabel(); - if (pLabel instanceof Label - && ((Label) pLabel).getLabel().equals(label)) { - return p.getComponent(); - } - } - return null; - } - - /** - * Gets the currently visible pane. - * - * @pre data != null - */ - public Component getCurrentPane(PageState data) { - return getCurrent(data).getComponent(); - } - - /** - * Get the currently visible Pane, the tab label together with - * its component. - */ - private Pane getCurrent(PageState data) { - Integer i = (Integer) data.getValue(m_currentPaneParam); - if (i == null) { - if (m_defaultPane != null) { - - return m_defaultPane; - } else { - return (Pane) get(0); - } - } - return (Pane) get(i.intValue()); - } - - public void setSelectedIndex(PageState state, int index) { - if (index != getSelectedIndex(state)) { - getCurrentPane(state).setVisible(state, false); - state.setValue(m_currentPaneParam, new Integer(index)); - getCurrentPane(state).setVisible(state, true); - } - } - - public int getSelectedIndex(PageState state) { - Integer current = (Integer) state.getValue(m_currentPaneParam); - if (current == null) { - return -1; - } - return current.intValue(); - } - - /** - * Builds a DOM representing the header for the tab strip. Marks the current - * pane. - */ - protected void generateTabs(PageState data, Element parent) { - Element strip = parent.newChildElement("bebop:tabStrip", BEBOP_XML_NS); - exportAttributes(strip); - - Pane current = getCurrent(data); - strip.addAttribute("selected", current.getComponent().getClass() - .getName()); - Iterator tabs; - int i; - for (tabs = children(), i = 0; tabs.hasNext(); i++) { - Pane pane = (Pane) tabs.next(); - // Skip hidden tabs - if (!pane.isVisible(data)) { - continue; - } - - data.setControlEvent(this, SELECT_EVENT, String.valueOf(i)); - - Element tab = strip.newChildElement("bebop:tab", BEBOP_XML_NS); - if (pane == current) { - tab.addAttribute("current", "t"); - } else { - try { - tab.addAttribute("href", data.stateAsURL()); - } catch (java.io.IOException ioe) { - // stateAsURL failed => this node gets neither href nor current - //TODO cat.error("cannot get stateAsURL from "+data); - } - } - String key = ((Label) pane.getLabel()).getGlobalizedMessage() - .getKey(); - tab.addAttribute("key", key.substring(key.lastIndexOf(".") + 1)); - pane.getLabel().generateXML(data, tab); - } - data.clearControlEvent(); - } - - /** - * Services the request by building a DOM tree with the tabs themselves and - * then the included page. - *

- * Generates a DOM fragment: - *

- *

-     * <bebop:tabbedPane>
-     *  <bebop:tabStrip>
-     *   <bebop:tab [href="..."] [current="t|f"]> .. label .. </bebop:tab>
-     *   <bebop:tab [href="..."] [current="t|f"]> .. label .. </bebop:tab>
-     *   <bebop:tab [href="..."] [current="t|f"]> .. label .. </bebop:tab>
-     *  </bebop:tabStrip>
-     *  <bebop:currentPane>
-     *    ... contentes ..
-     *  </bebop:currentPane>
-     * </bebop:tabbedPane>
-     * 
- */ - public void generateXML(PageState state, Element parent) { - if (isVisible(state) && !isEmpty()) { - Element tabbed = parent.newChildElement("bebop:tabbedPane", - BEBOP_XML_NS); - generateTabs(state, tabbed); - exportAttributes(tabbed); - - Element pane = tabbed.newChildElement("bebop:currentPane", - BEBOP_XML_NS); - exportAttributes(pane); - getCurrentPane(state).generateXML(state, pane); - } - } - - /** - * Notifies the TabbedPane that one of the tabs has been - * selected. Changes the currently visible pane and runs all the {@link - * ActionListener ActionListeners}. - *

- * The respond method on the now-visible component is - * not called. - * - * @pre state != null - */ - public void respond(PageState state) - throws ServletException { - String event = state.getControlEventName(); - - if (SELECT_EVENT.equals(event)) { - String value = state.getControlEventValue(); - setSelectedIndex(state, Integer.parseInt(value)); - } else { - throw new ServletException("Received unknown control event " + event); - } - fireActionEvent(state); - } - - /** - * Associates a label with the component - */ - private class Pane extends SimpleContainer { - - private Component m_label; - private Component m_component; - - public Pane(Component label, Component c) { - m_label = label; - super.add(label); - m_component = c; - super.add(c); - } - - public final Component getLabel() { - return m_label; - } - - public final Component getComponent() { - return m_component; - } - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/Text.java b/ccm-core/src/main/java/com/arsdigita/bebop/Text.java deleted file mode 100644 index 3261f8648..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/Text.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.bebop; - -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.xml.Element; - -/** - * - * @author Jens Pelzetter - */ -public class Text extends SimpleComponent { - - private String text; - private boolean outputEscaped; - private PrintListener printListener; - - public Text() { - this(""); - } - - public Text(final String text) { - this.text = text; - outputEscaped = true; - } - - public Text(final PrintListener printListener) { - this(); - this.printListener = printListener; - } - - public String getText() { - return text; - } - - public void setText(final String text) { - this.text = text; - } - - public boolean isOutputEscaped() { - return outputEscaped; - } - - public void setOutputEscaped(final boolean outputEscaped) { - this.outputEscaped = outputEscaped; - } - - public void setPrintListener(final PrintListener printListener) { - if (printListener == null) { - throw new IllegalArgumentException("PrintListener can't be null"); - } - - this.printListener = printListener; - } - - @Override - public void generateXML(final PageState state, final Element parent) { - - if (!isVisible(state)) { - return; - } - - final Text target = firePrintEvent(state); - - final Element textElem = parent.newChildElement("bebop:text", - BEBOP_XML_NS); - - target.exportAttributes(textElem); - - if (outputEscaped) { - textElem.addAttribute("escape", "no"); - } else { - textElem.addAttribute("escape", "yes"); - } - - textElem.setText(target.getText()); - } - - protected Text firePrintEvent(final PageState state) { - final Text component; - if (printListener == null) { - component = this; - } else { - try { - component = (Text) this.clone(); - printListener.prepare(new PrintEvent(this, state, component)); - } catch (CloneNotSupportedException ex) { - throw new UncheckedWrapperException( - "Could not clone Text component for PrintListener. " - + "This propaby indicates a serious programming error."); - } - } - - return component; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/ActionEvent.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/ActionEvent.java deleted file mode 100755 index fba6ef94c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/ActionEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; - -/** - * A component-defined event. Components usually fire an - * ActionEvent to indicate that they were the ones receiving - * the click in a user's submission, for example, a form might use an - * ActionEvent to signal that it has been submitted. - * - * @see ActionListener - * @see java.awt.event.ActionEvent - * - * @author David Lutterkort - * - * @version $Id$ - */ - -public class ActionEvent extends PageEvent { - - /** - * Construct an ActionEvent. - * - * @param source the component that originated the event - * @param state the state of the containing page under the current - * request - */ - public ActionEvent(Component source, PageState state) { - super(source, state); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/ActionListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/ActionListener.java deleted file mode 100755 index a1d7674da..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/ActionListener.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import java.util.EventListener; - -/** - * The listener interface for receiving action events. The class that is - * interested in processing an action event implements this interface, and - * the object created with that class is registered with a component, using - * the component's addActionListener method. When the action event occurs, - * that object's actionPerformed method is invoked. - * - * @see ActionEvent - * @see java.awt.event.ActionListener - * - * @author David Lutterkort - * - * @version $Id$ - */ -public interface ActionListener extends EventListener { - - /** - * Invoked when an action has been performed. - * - * @pre e != null - */ - void actionPerformed(ActionEvent e); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/ChangeEvent.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/ChangeEvent.java deleted file mode 100755 index 8876f1915..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/ChangeEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.PageState; - -/** - * This class will be - * renamed to SelectionEvent. - */ -public class ChangeEvent extends PageEvent { - - public ChangeEvent(Object source, PageState state) { - super(source, state); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/ChangeListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/ChangeListener.java deleted file mode 100755 index f69dfc1dd..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/ChangeListener.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import java.util.EventListener; - -/** - * This class will be - * renamed to SelectionListener. - */ -public interface ChangeListener extends EventListener { - - void stateChanged(ChangeEvent e); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/EventListenerList.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/EventListenerList.java deleted file mode 100755 index 5806849d5..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/EventListenerList.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * Convenience extensions to {@link javax.swing.event.EventListenerList - * Swing's EventListenerList}. - * - */ -public class EventListenerList extends javax.swing.event.EventListenerList { - - private static final long serialVersionUID = -1930203818146602205L; - - /** - * Append all the event listeners from l. - * - * @param list The list of listeners to copy from - * - * @pre l != null - */ - public void addAll(final EventListenerList list) { - - if ( list.listenerList.length == 0 ) { - return; - } - - Object[] tmp = new Object[listenerList.length + list.listenerList.length]; - System.arraycopy(listenerList, 0, tmp, 0, listenerList.length); - System.arraycopy(list.listenerList, 0, - tmp, listenerList.length, list.listenerList.length); - listenerList = tmp; - } - - /** - * Return an iterator over all event listeners of class t. - * This iterator replaces the for loop mentioned in the documentation for - * {@link javax.swing.event.EventListenerList Swing's - * EventListenerList}. - * - * @param - * @param type The class of the event listeners that should be returned - * @return - * - * @pre t != null - * */ - public Iterator getListenerIterator(final Class type) { - return new EventListenerIterator<>(type); - } - - private class EventListenerIterator implements Iterator { - - /** - * The listener we will return with the next call to next(). - * listener[_next] is always a class object of type t, unless all - * matching listeners have been returned, in which case _next - * is -1 - * */ - private final int count; - private int next; - private final Class type; - - EventListenerIterator(Class type) { - - count = getListenerList().length; - next = -2; - this.type = type; - findNext(); - } - - @Override - public boolean hasNext() { - return (next < count); - } - - @Override - @SuppressWarnings("unchecked") - public T next() throws NoSuchElementException { - if ( ! hasNext() ) { - throw new NoSuchElementException("Iterator exhausted"); - } - int result = next; - findNext(); - return (T) getListenerList()[result+1]; - } - - @Override - public void remove() throws UnsupportedOperationException { - throw new UnsupportedOperationException("Removal not supported"); - } - - /** - * Advance _next so that either _next == -1 - * if all listeners of class _t have been returned in the - * enclosing EventListenerList, or that - * getListenersList()[_next] == _t and - * getListenersList()[_next+1] (the corresponding listener - * object) has not been returned yet by next(). - * */ - private void findNext() { - - for (int i = next+2; iImplementations of this method are responsible for catching - * specific exceptions that may occur during processing, and either - * handling them internally or rethrowing them as instances of - * FormProcessException to be handled by the calling - * procedure. - */ - - void cancel(FormSectionEvent e) throws FormProcessException; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormInitListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/FormInitListener.java deleted file mode 100755 index 08e964c19..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormInitListener.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.FormProcessException; -import java.util.EventListener; - -/** - * Defines the interface for initializing a form with default values. - * Typical implementations of this interface query the database to - * set up an "edit" form, or obtain an id from a sequence to initialize - * a "create" form. - * - * @author Karl Goldstein - * @author Uday Mathur - * @version $Id$ - */ -public interface FormInitListener extends EventListener { - - /** - * Initializes a FormData object already populated with values from - * the request. - * - * @param date The form data containing data included with this - * request. The initializer may require knowledge of form or - * parameter properties. - * - * @param request The HTTP request associated with the - * initialization event. This supplied so that the initializer may - * rely on contextual information, such information extracted from - * headers or cookies or an associated HttpSession - * object. - * */ - void init(FormSectionEvent e) throws FormProcessException; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormProcessListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/FormProcessListener.java deleted file mode 100755 index a3abaf87a..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormProcessListener.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.FormProcessException; -import java.util.EventListener; - -/** - * Defines the interface for a class that performs a processing step - * on valid data. - * - * @author Karl Goldstein - * @author Uday Mathur - * @version $Id$ - */ - -public interface FormProcessListener extends EventListener { - - /** - * Performs a processing step on the data in the - * FormData object. - * - *

Implementations of this method are responsible for catching - * specific exceptions that may occur during processing, and either - * handling them internally or rethrowing them as instances of - * FormProcessException to be handled by the calling - * procedure. - * - *

Implementations of this method cannot assume success or - * failure of other FormProcessListeners associated with a - * particular FormModeel. Each implementation must act independently - * - * @param model The form model describing the structure and properties - * of the form data included with this request. - * - * @param data The container for all data objects associated with - * the request. String values for all parameters specified in the - * form model are converted to Java data objects and validated - * before processing occurs. - * - * @param request The HTTP request information from which the form - * data was extracted. Note that the request object is supplied - * only in case the processing step requires contextual information - * (information extracted from cookies or the peer address, for - * example) or needs to modify session properties. - * - * @param response The HTTP response that will be returned to the - * user. The processing step may require access to this object to - * set cookies or handle errors. */ - - void process(FormSectionEvent e) throws FormProcessException; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormSectionEvent.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/FormSectionEvent.java deleted file mode 100755 index 5b3167c6d..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormSectionEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.PageState; - -/** - * An event originating from a form. FormSectionEvents are - * used to notify listeners that values in a form should be initilialized, - * validated or processed. - * - * @author David Lutterkort - * - * @version $Id$ - * - * @see FormInitListener - * @see FormValidationListener - * @see FormProcessListener - */ -public class FormSectionEvent extends PageEvent { - - private final FormData _formData; - - /** - * Get the form data for to the form that fired the event in the current - * request. - * - * @return form data - */ - public final FormData getFormData() { - return _formData; - } - - /** - * Construct a FormSectionEvent. - * - * @param source the form model that fired the event - * @param state the state of the enclosing page - * @param formData the form data constructed so far - */ - public FormSectionEvent(Object source, - PageState state, - FormData formData) { - super(source, state); - _formData = formData; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormSubmissionListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/FormSubmissionListener.java deleted file mode 100755 index 127c25c33..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormSubmissionListener.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import java.util.EventListener; - -import com.arsdigita.bebop.FormProcessException; - -/** - * The listener called just before a form starts examining a - * submission. This listener can throw a {@link FormProcessException} to - * indicate that any further processing of the submission should be - * aborted. This usually leaves the corresponding {@link - * com.arsdigita.bebop.FormData FormData} object in an undefined - * state. - * - * @author David Lutterkort - * @version $Id$ - */ -public interface FormSubmissionListener extends EventListener { - - /** - * This method gets called as soon as the FormData for a - * form has been filled with the request parameters. The values in the - * FormData are transformed but not validated. - * - * @param e the event encapsulating form data, page state and event source - * @throws FormProcessException to signal that further processing of the - * form should be aborted. - */ - void submitted(FormSectionEvent e) throws FormProcessException; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormValidationListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/FormValidationListener.java deleted file mode 100755 index 29ff676c4..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/FormValidationListener.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.FormProcessException; -import java.util.EventListener; - -/** - * Defines the interface for a class that implements a validation check - * on a set of form data. - * - * @author Karl Goldstein - * @author Uday Mathur - * @version $Id$ - */ -public interface FormValidationListener extends EventListener { - - /** - * Performs a validation check on the specified FormData - * object, involving any number of parameters. - * - *

The check is always performed after all HTTP request - * parameters have been converted to data objects and stored in the - * FormData object. - * - *

If a validation error is encountered, the setError - * method of the FormData object may be used to set an - * error message for reporting back to the user. - * - *

This method is responsible for catching any exceptions that - * may occur during the validation. These exceptions may either - * be handled internally, or if they are unrecoverable may be - * rethrown as instances of FormProcessException. - * - * @param e FormSectionEvent containing the FormData as well as the - * PageState. - * Clients may access the PageState by executing something like - * PageState state = fse.getPageState(); - * Method getFormData() allows access to the Form's data. - * - * @exception FormProcessException ff the data does not pass the check. - */ - - void validate(FormSectionEvent e) throws FormProcessException; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/PageEvent.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/PageEvent.java deleted file mode 100755 index 2f3b5ae0c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/PageEvent.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.PageState; - -import java.util.EventObject; - -/** - * The base class for all page related events. All page related events - * should be derived from this class, since it defines a standard way to - * get at the source of the event and at the state of the page under the - * request that is currently being processed. - * - * @author David Lutterkort - * - * @version $Id$ - */ -public class PageEvent extends EventObject { - - private PageState _state; - - /** - * Construct a new PageEvent. - * @param source the object firing the event, usually a {@link - * com.arsdigita.bebop.Component Component}. - * @param state the state of the page under the current request - */ - public PageEvent(Object source, PageState state) { - super(source); - _state = state; - } - - /** - * Get the state of the page under the request in which the event was fired - */ - public final PageState getPageState() { - return _state; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/ParameterEvent.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/ParameterEvent.java deleted file mode 100755 index e76e5998f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/ParameterEvent.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.ParameterData; - -import java.util.EventObject; - -/** - * An event connected to a request parameter. - * - * @author David Lutterkort - * - * @version $Id$ - * - * @see ParameterListener - * @see com.arsdigita.bebop.parameters.ParameterModel - * @see com.arsdigita.bebop.parameters.ParameterData - */ - -public class ParameterEvent extends EventObject { - - /* The request specific data about the event */ - private ParameterData m_data; - private PageState m_state; - - /** - * Construct a ParameterEvent - * - * @param source the object that originated the event - * @param data the data for the parameter from the current request - **/ - - public ParameterEvent(Object source, ParameterData data) { - super(source); - m_data = data; - m_state = PageState.getPageState(); - } - - - /** - * Get the request specific data about the parameter. - **/ - - public final ParameterData getParameterData() { - return m_data; - } - - - /** - * - **/ - - public PageState getPageState() { - return m_state; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/ParameterListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/ParameterListener.java deleted file mode 100755 index dd1a2499e..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/ParameterListener.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.FormProcessException; -import java.util.EventListener; - -/** - * Defines the interface for a class that validates the values of a - * single parameter. - * - * @author Karl Goldstein - * @author Uday Mathur - * @version $Id$ */ - -public interface ParameterListener extends EventListener { - - /** - * Performs a validation check on the data objects associated with a - * specific parameter. Validate should call - * ParameterData.addError() with a message regarding the nature - * of the error. - * @param e - * @throws com.arsdigita.bebop.FormProcessException - */ - void validate(ParameterEvent e) throws FormProcessException; -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/PrintEvent.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/PrintEvent.java deleted file mode 100755 index 7b22af400..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/PrintEvent.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.PageState; - -/** - * An event originating from a component. PrintEvents are - * fired just before the source component is output either as - * part of an XML document or as part of an HTML page. - * - * @see PrintListener - * - * @author Uday Mathur - * @author David Lutterkort - * - * @version $Id$ - * - */ -public class PrintEvent extends PageEvent { - - private Object m_target; - - /** - * Construct a PrintEvent - * - * @param source the object that originated the event - * @param data the data for the parameter from the current request - * @pre source != null - * @pre target != null - */ - public PrintEvent(Object source, PageState state, Object target) { - super(source, state); - m_target = target; - } - - /** - * Get the target object, the one that can be freely modified by print - * listeners. Initially, the target is an unlocked clone of the source of - * the event. - * @post return != null - */ - public final Object getTarget() { - return m_target; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/PrintListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/PrintListener.java deleted file mode 100755 index 0613f31ba..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/PrintListener.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import java.util.EventListener; - -/** - * Listeners of this class are called just before a {@link com.arsdigita.bebop.Component} is - * about to be output, either in the form of an XML element, or by printing - * its HTML representation. The {@link #prepare prepare method} of the - * listener can make modifications to the {@link PrintEvent#getTarget - * target} of the event. The target will then be used to produce output - * instead of the source. - *

- * {@link PrintEvent PrintEvents} are unicast events, which means - * that components should only permit the registration of one - * PrintListener. Since the PrintListener is - * expected to modify the target, allowing multiple listeners to modify the - * target of one event would make it impossible to predict the resulting - * target component, since an individual listener can not know which - * listeners have run before it and which ones will run after it. - *

- * As an example consider the following code: - *

- *   Label l = new Label("Default text");
- *   l.addPrintListener( new PrintListener {
- *     private static final BigDecimal ONE = new BigDecimal(1);
- *     private BigDecimal count = new BigDecimal(0);
- *     public void prepare(PrintEvent e) {
- *       Label t = e.getTarget();
- *       synchronized (count) {
- *         count.add(ONE);
- *       }
- *       t.setLabel("Call no." + count + " since last server restart");
- *     }
- *   });
- * Adding the label l to a page will lead to a label that - * changes in every request and print how many times the containing label - * has been called. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author David Lutterkort - * @version $Id$ - */ - -public interface PrintListener extends EventListener { - - /** - * Prepare the target component returned by {@link PrintEvent#getTarget - * e.getTarget()} for output. The target component is an unlocked clone - * of the source of the event and can be freely modified within this - * method. - * - * @param e Event containing the page state, the source and the target of - * the event - * - * @see PrintEvent - */ - - void prepare(PrintEvent e); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/RequestEvent.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/RequestEvent.java deleted file mode 100755 index f2017c112..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/RequestEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; - -/** - * An event indicating that a Bebop page is being loaded, and control - * is about to be passed to the currently selected component - * - * @author David Lutterkort - * - * @version $Id$ - * - * @see ActionListener - * @see java.awt.event.ActionEvent - */ - -public class RequestEvent extends PageEvent { - - /** - * Construct an ActionEvent. - * - * @param source the component that originated the event - * @param state the state of the containing page under the current - * request - */ - public RequestEvent(Component source, PageState state) { - super(source, state); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/RequestListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/RequestListener.java deleted file mode 100755 index 3219cf2e8..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/RequestListener.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import java.util.EventListener; - -/** - * The listener interface for receiving request events. The class that is - * interested in processing a request event implements this interface, and - * the object created with that class is registered with a Bebop page, using - * the Page.addRequestListener method. When the page has finished processing - * the page state, and is about to pass control to the currently selected - * component, the pageRequested method will be called. - * - * @author David Lutterkort - * - * @version $Id$ - * - * @see ActionEvent - * @see java.awt.event.ActionListener - */ -public interface RequestListener extends EventListener { - - /** - * Invoked when an action has been performed. - * - * @pre e != null - */ - void pageRequested(RequestEvent e); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/SearchAndSelectListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/SearchAndSelectListener.java deleted file mode 100755 index 1f626414a..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/SearchAndSelectListener.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import java.util.EventListener; - -/** - * Analogous to Widget - * PrintListeners, this is called when the widget is displayed (or - * validated) to get the dataset. The dataset should be created - * dynamically so it can vary according to form variables. - * Eventually, this may also support setting the initial value for a - * SearchAndSelect widget, so that it may act as an edit widget as - * well. - * - * @author Patrick McNeill - * @version $Id$ - * @since 4.5 */ -public interface SearchAndSelectListener extends EventListener { - - SearchAndSelectModel getModel( PageEvent e ); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/SearchAndSelectModel.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/SearchAndSelectModel.java deleted file mode 100755 index a8585fa10..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/SearchAndSelectModel.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -/** - * Listener interface for - * the SeachAndSelect Bebop widget. SearchAndSelect requires - * knowledge about the data it is searching over (to determine the - * display method and to actually execute the query). - * - * @author Patrick McNeill - * @version $Id$ - * @since 4.5 */ -public interface SearchAndSelectModel { - - /** - * Specify the user's search and restrict the result set to those queries - * that match. An empty string should return all results. - * - * @param query the user's search string, space or comma delimited words - */ - void setQuery ( String query ); - - /** - * Retrieve the query that was last used. - * - * @return the query string - */ - String getQuery (); - - /** - * Return the number of items that are currently selected by the query - * string. If the query string is empty, this should return the number - * of items in the dataset. - * - * @return the number of currently selected items - */ - int resultsCount (); - - /** - * Get the "i"th label (0 based indexing) - * - * @param i the label number to retrieve - * @return the ith label - */ - String getLabel (int i); - - /** - * Get the "i"th ID (0 based indexing) - * - * @param i the ID number to retrieve - * @return the ith ID - */ - String getID (int i); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/TableActionAdapter.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/TableActionAdapter.java deleted file mode 100755 index 4f0a708de..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/TableActionAdapter.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.FormProcessException; - -/** - * An implentation of the TableActionListener interface meant to save the - * developer from having to override both the {@link - * #cellSelected(TableActionEvent)} and {@link #headSelected(TableActionEvent)} - * methods when they only need to change the behavior of one. - * - * @see TableActionEvent - * @author David Lutterkort - * @version $Id$ - */ -public class TableActionAdapter implements TableActionListener { - - /** - * A no-op implementation of {@link - * TableActionListener#cellSelected(TableActionEvent)}. - * - * @param e the event fired for the table. - */ - public void cellSelected(TableActionEvent e) throws FormProcessException {} - - /** - * A no-op implementation of {@link - * TableActionListener#headSelected(TableActionEvent)}. - * - * @param e the event fired for the table. - */ - public void headSelected(TableActionEvent e) { - return; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/TableActionEvent.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/TableActionEvent.java deleted file mode 100755 index f141f31a0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/TableActionEvent.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; - -/** - * An event for the {@link com.arsdigita.bebop.Table} component. - * Table will fire this event when one of its active cells receives a - * click. - * - * @see TableActionListener - * @see TableActionAdapter - * @author David Lutterkort - * @version $Id$ - */ -public class TableActionEvent extends ActionEvent { - - private Object m_rowKey; - private Integer m_column; - - /** - * Construct a TableActionEvent for a click on a particular row - * and a particular column. - * - * @param source the Component generating the event. - * @param s the state for the current request. - * @param rowKey the key for the row where the click was registered. - * @param column the index of the column where the click was registered. - */ - public TableActionEvent(Component source, PageState s, - Object rowKey, Integer column) { - super(source, s); - m_rowKey = rowKey; - m_column = column; - } - - /** - * Construct a TableActionEvent for a click on a particular row. - * - * @param source the Component generating the event. - * @param s the state for the current request. - * @param rowKey the key for the row where the click was registered. - */ - public TableActionEvent(Component source, PageState s, Object rowKey) { - this(source, s, rowKey, new Integer(-1)); - } - - /** - * Get the key for the row that received the click. - * - * @return the key for the row that received the click. - */ - public final Object getRowKey() { - return m_rowKey; - } - - /** - * Get the index of the column that received the click. - * - * @return the index of the column that received the click. - */ - public final Integer getColumn() { - return m_column; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/TableActionListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/TableActionListener.java deleted file mode 100755 index 36ca19ebc..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/TableActionListener.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.FormProcessException; - -import java.util.EventListener; - -/** - * Specifies the interface for handling events on {@link - * com.arsdigita.bebop.Table}. Programmers wishing to override just - * one of these methods, not both, may prefer to use {@link - * TableActionAdapter}. - * - * @see TableActionEvent - * @see TableActionAdapter - * @author David Lutterkort - * @version $Id$ - */ -public interface TableActionListener extends EventListener { - - /** - * An event handler for actions on a particular cell or a set of - * cells. - * - * @param e the event fired for the table. - */ - void cellSelected(TableActionEvent e) throws FormProcessException; - - /** - * An event handler for actions on a particular column heading or - * set of column headings. - * - * @param e the event fired for the table. - */ - void headSelected(TableActionEvent e); -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/TreeExpansionEvent.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/TreeExpansionEvent.java deleted file mode 100755 index db4f05586..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/TreeExpansionEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; - -/** - * An event for the {@link com.arsdigita.bebop.Tree} component. - * Tree will fire this event when one of its nodes is expanded or - * collapsed. - * - * @author David Lutterkort - * @version $Id$ - */ -public class TreeExpansionEvent extends ActionEvent { - - private Object m_nodeKey; - - public TreeExpansionEvent(Component source, PageState s, Object nodeKey) { - super(source, s); - m_nodeKey = nodeKey; - } - - /** - * Get the key for the node that was expanded or collapsed. - * - * @return the key for the node that was expanded or collapsed. - */ - public final Object getNodeKey() { - return m_nodeKey; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/event/TreeExpansionListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/event/TreeExpansionListener.java deleted file mode 100755 index a5c8e12cd..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/event/TreeExpansionListener.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.event; - -import java.util.EventListener; - -/** - * The listener that is notified when a tree node is expanded or - * collapsed. - * - * @author David Lutterkort - * @version $Id$ - */ -public interface TreeExpansionListener extends EventListener { - - /** - * Called whenever an item in the tree has been collapsed. - */ - void treeCollapsed(TreeExpansionEvent event); - - /** - * Called whenever an item in the tree has been expanded. - */ - void treeExpanded(TreeExpansionEvent event); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/CheckboxGroup.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/CheckboxGroup.java deleted file mode 100755 index 38c3adb69..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/CheckboxGroup.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - - - - -import com.arsdigita.bebop.parameters.ArrayParameter; -// This interface contains the XML element name of this class -// in a constant which is used when generating XML -import com.arsdigita.bebop.util.BebopConstants; - -/** - * A class representing a group of associated checkboxes. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Rory Solomon - * @author Michael Pih - * @version $Id$ - */ -public class CheckboxGroup extends OptionGroup implements BebopConstants { - - public CheckboxGroup(String name) { - this(new ArrayParameter(name)); - } - - public CheckboxGroup(ArrayParameter param) { - super(param); - //m_xmlElement = BEBOP_CHECKBOX; - } - - /** - * Returns a string naming the type of this widget. - */ - public String getType() { - return "checkbox"; - } - - /** The XML tag. - * @return The tag to be used for the top level DOM element - * generated for this type of Widget. */ - @Override - protected String getElementTag() { - return BEBOP_CHECKBOXGROUP; - } - - @Override - public String getOptionXMLElement() { - return BEBOP_CHECKBOX; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/DHTMLEditor.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/DHTMLEditor.java deleted file mode 100755 index 2748266a7..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/DHTMLEditor.java +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright (C) 2001-2006 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import com.arsdigita.bebop.BebopConfig; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.web.Web; -import com.arsdigita.xml.Element; - -/** - * Displays and manages a WYSIWYG HTML editor that takes advantage of DHTML - * scripting features. This class can use: - *
    - *
  • CCM Editor, a new editor using HTML5 features.
  • - *
  • Xinha
  • - *
  • FCKeditor
  • - *
  • HTMLarea for backwards compatibility, development discontinued
  • - *
- * Editor is chosen based on the configuration parameter - * {@code waf.bebop.dhtml_editor} default is {@code ccm-editor}. - * - * @author Jim Parsons - * @author Richard Li - * @author Chris Burnett - * @author Alan Pevec - * @author Jens Pelzetter - * - */ -public class DHTMLEditor extends TextArea { - - /** - * Constant for specifying OFF value for the WRAP - * attribute of this image input. - * - * See here - * for a description of what this attribute does. - */ - public static final int OFF = 0; - - /** - * Constant for specifying HARD value for the WRAP - * attribute of this image input. - * - * See here - * for a description of what this attribute does. - */ - public static final int HARD = 1; - - /** - * Constant for specifying SOFT value for the WRAP - * attribute of this image input. See here - * for a description of what this attribute does. - */ - public static final int SOFT = 2; - - /** - * Configuration objects for supported DHTML editors - */ - public static class Config { - - // WARNING: Processing of these default values by CMSConfig does NOT - // work correctly because of deviciencies in unmarshal method there. - public static final Config XINHA_STANDARD = new Config("Xinha.Config", - "/assets/xinha/CCMcoreXinhaConfig.js"); - - /** - * Example FCKEditor configuration. - */ - public static final Config FCK_STANDARD = new Config( - "FCKEditor.Config.StyleDefault", - "/assets/fckeditor/config/fckconfigstyledefault.js"); - - public static final Config FCK_CMSADMIN = new Config( - "FCKEditor.Config.StyleCMSAdmin", - "/assets/fckeditor/config/fckconfigstylecmsadmin.js"); - - /** - * Example old HTMLarea configuration. - */ - public static final Config HTMLAREA - = new Config("HTMLArea.Config", null); - - /** - * Example of configuration for ccm-editor - */ - public static final Config CCM_EDITOR = new Config("ccm-editor.loader", - "/ccm-editor/ccm-editor-loader.js"); - - public static final Config STANDARD = new Config("tinymce.config", - "/tinymce/tinymce-config.js"); - - private String m_name; - private String m_path; - - public Config(String name) { - this(name, null); - } - - public Config(String name, - String path) { - m_name = name; - m_path = path; - } - - public String getName() { - return m_name; - } - - public String getPath() { - return m_path; - } - - public static Config valueOf(String cfg) { - int offset = cfg.indexOf(","); - if (offset != -1) { - return new Config(cfg.substring(0, offset), - cfg.substring(offset + 1)); - } else { - return new Config(cfg); - } - } - - public String toString() { - if (m_path == null) { - return m_name; - } else { - return m_name + "," + m_path; - } - } - - } //end config object(s) - - private Config m_config; - private Set m_plugins; - private Set m_hiddenButtons; - - /** - * Constructor - * - * @param name - */ - public DHTMLEditor(String name) { - this(new StringParameter(name)); - } - - /** - * Constructor - * - * @param model - */ - public DHTMLEditor(ParameterModel model) { - this(model, Config.STANDARD); - } - - /** - * Constructor - * - * @param model - * @param config - */ - public DHTMLEditor(ParameterModel model, - Config config) { - super(model); - m_config = config; - m_plugins = new HashSet(); - m_hiddenButtons = new HashSet(); - } - - /** - * Returns a string naming the type of this widget. - */ - public String getType() { - return "DHTMLEditor"; - } - - public String getEditorURL() { - return BebopConfig.getConfig().getDhtmlEditorSrcFile().substring( - 0, - BebopConfig.getConfig().getDhtmlEditorSrcFile().lastIndexOf("/") + 1); - } - - public String getEditorSrc() { - return BebopConfig.getConfig().getDhtmlEditorSrcFile(); - } - - /** - * deprecated - use {@link setConfig(Config)} - * - * @param config - */ - public void setConfig(String config) { - setAttribute("config", config); - } - - public void setConfig(Config config) { - m_config = config; - } - - public void addPlugin(String name) { - m_plugins.add(name); - } - - /** - * Prevent the specified button from being displayed in the editor toolbar. - * - * @param name name of the button, as specified in the btnList of the - * htmlarea.js file - * - */ - public void hideButton(String name) { - m_hiddenButtons.add(name); - } - - /** - * Sets the ROWS attribute for the TEXTAREA tag. - */ - @Override - public void setRows(int rows) { - setAttribute("rows", String.valueOf(rows)); - } - - /** - * Sets the COLS attribute for the TEXTAREA tag. - */ - @Override - public void setCols(int cols) { - setAttribute("cols", String.valueOf(cols)); - } - - /** - * Sets the COLS attribute for the TEXTAREA tag. - */ - @Override - public void setWrap(int wrap) { - String wrapString = null; - - switch (wrap) { - case OFF: - wrapString = "off"; - break; - case HARD: - wrapString = "hard"; - break; - case SOFT: - wrapString = "soft"; - break; - } - - if (wrapString != null) { - setAttribute("wrap", wrapString); - } - } - - /** - * The XML tag. - * - * @return The tag to be used for the top level DOM element generated for - * this type of Widget. - */ - @Override - protected String getElementTag() { - return BebopConfig.getConfig().getDefaultDhtmlEditor(); - } - - /** - * Generates the DOM for the DHTML editor widget - *

- * Generates DOM fragment: - *

- * <bebop:dhtmleditor name=... value=... [onXXX=...]/> - * - */ - @Override - public void generateWidget(PageState state, Element parent) { - String value = getParameterData(state).marshal(); - Element editor = parent.newChildElement(getElementTag(), BEBOP_XML_NS); - - editor.addAttribute("name", getName()); - generateDescriptionXML(state, editor); - - // Set the needed config params so they don't have to be hardcoded in - //the theme - editor.addAttribute("editor_url", - Web.getWebappContextPath().concat(getEditorURL())); - editor.addAttribute("editor_src", - Web.getWebappContextPath().concat(getEditorSrc())); - - if (value != null) { - editor.setText(value); - } - - exportAttributes(editor); - - Element config = editor.newChildElement("bebop:config", BEBOP_XML_NS); - config.addAttribute("name", m_config.getName()); - if (m_config.getPath() != null) { - config.addAttribute( - "path", String.format("%s/%s", - Web.getWebappContextPath(), - m_config.getPath())); - } - if (m_hiddenButtons.size() > 0) { - - StringBuffer hiddenButtons = new StringBuffer(); - // list must start and end with a space - hiddenButtons.append(" "); - Iterator hidden = m_hiddenButtons.iterator(); - while (hidden.hasNext()) { - hiddenButtons.append(hidden.next()); - hiddenButtons.append(" "); - } - config.addAttribute("hidden-buttons", hiddenButtons.toString()); - } - Iterator plugins = m_plugins.iterator(); - while (plugins.hasNext()) { - String name = (String) plugins.next(); - Element plugin = editor - .newChildElement("bebop:plugin", BEBOP_XML_NS); - plugin.addAttribute("name", name); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/Date.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/Date.java deleted file mode 100755 index f54a89ebf..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/Date.java +++ /dev/null @@ -1,502 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import java.text.DateFormatSymbols; - -import java.util.Calendar; -import java.util.GregorianCalendar; - -import com.arsdigita.util.Assert; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.DateParameter; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.parameters.DateTimeParameter; -import com.arsdigita.bebop.parameters.IncompleteDateParameter; -import com.arsdigita.bebop.parameters.NotNullValidationListener; - -// This interface contains the XML element name of this class -// in a constant which is used when generating XML -import com.arsdigita.bebop.util.BebopConstants; - -import com.arsdigita.bebop.util.GlobalizationUtil; - -import com.arsdigita.xml.Element; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; - -import java.text.SimpleDateFormat; -import java.util.Locale; - -/** - * A class representing a date field in an HTML form. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Michael Pih - * @author Sören Bernstein - * @version $Id$ - */ -public class Date extends Widget implements BebopConstants { - - protected OptionGroup m_year; - protected OptionGroup m_month; - protected TextField m_day; - private int m_year_begin; - private int m_year_end; - private Locale m_locale; - private boolean yearAsc = true; - - /** - * Inner class for the year fragment - */ - protected class YearFragment extends SingleSelect { - - protected Date parent; - private boolean autoCurrentYear; //Decide wether to set the current year if year is null - - /** - * Constructor. - * - * @param name - * @param parent - */ - public YearFragment(String name, Date parent) { - super(name); - this.parent = parent; - setHint(GlobalizationUtil.globalize("bebop.date.year.hint")); - } - - /** - * - * @param ps - * - * @return - */ - @Override - protected ParameterData getParameterData(PageState ps) { - Object value = getValue(ps); - if (value == null) { - return null; - } - return new ParameterData(getParameterModel(), value); - } - - /** - * - * @param autoCurrentYear - */ - public void setAutoCurrentYear(final boolean autoCurrentYear) { - this.autoCurrentYear = autoCurrentYear; - } - - /** - * - * @param ps - * - * @return - */ - @Override - public Object getValue(PageState ps) { - ParameterModel model = parent.getParameterModel(); - if (model instanceof IncompleteDateParameter) { - if (((IncompleteDateParameter) model).isYearSkipped()) { - return null; - } - } - Object value = parent.getFragmentValue(ps, Calendar.YEAR); - if ((value == null) && autoCurrentYear) { - Calendar currentTime = GregorianCalendar.getInstance(); - int currentYear = currentTime.get(Calendar.YEAR); - value = new Integer(currentYear); - } - return value; - } - - } - - /** - * - */ - protected class MonthFragment extends SingleSelect { - - protected Date parent; - - public MonthFragment(String name, Date parent) { - super(name); - this.parent = parent; - } - - @Override - protected ParameterData getParameterData(PageState ps) { - Object value = getValue(ps); - if (value == null) { - return null; - } - return new ParameterData(getParameterModel(), value); - } - - @Override - public Object getValue(PageState ps) { - ParameterModel model = parent.getParameterModel(); - if (model instanceof IncompleteDateParameter) { - if (((IncompleteDateParameter) model).isMonthSkipped()) { - return null; - } - } - return parent.getFragmentValue(ps, Calendar.MONTH); - } - - } - - /** - * - */ - protected class DayFragment extends TextField { - - protected Date parent; - - public DayFragment(String name, Date parent) { - super(name); - this.parent = parent; - } - - @Override - protected ParameterData getParameterData(PageState ps) { - Object value = getValue(ps); - if (value == null) { - return null; - } - return new ParameterData(getParameterModel(), value); - } - - @Override - public Object getValue(PageState ps) { - ParameterModel model = parent.getParameterModel(); - if (model instanceof IncompleteDateParameter) { - if (((IncompleteDateParameter) model).isDaySkipped()) { - return null; - } - } - return parent.getFragmentValue(ps, Calendar.DATE); - } - - } - - /** - * Construct a new Date. The model must be a DateParameter - */ - public Date(ParameterModel model) { - super(model); - - if (!(model instanceof DateParameter - || model instanceof DateTimeParameter)) { - throw new IllegalArgumentException( - "The Date widget " + model.getName() - + " must be backed by a DateParameter parmeter model"); - } - - String name = model.getName(); - String nameYear = name + ".year"; - String nameMonth = name + ".month"; - String nameDay = name + ".day"; - - Calendar currentTime = GregorianCalendar.getInstance(); - - m_year = new YearFragment(nameYear, this); - m_month = new MonthFragment(nameMonth, this); - m_day = new DayFragment(nameDay, this); - - m_day.setMaxLength(2); - m_day.setSize(2); - - populateMonthOptions(); - - int currentYear = currentTime.get(Calendar.YEAR); - setYearRange(currentYear - 1, currentYear + 3); - - } - - /** - * Constructor. - * - * @param name - */ - public Date(String name) { - this(new DateParameter(name)); - } - - public void setAutoCurrentYear(final boolean autoCurrentYear) { - ((YearFragment) m_year).setAutoCurrentYear(autoCurrentYear); - } - - public void setYearRange(int yearBegin, int yearEnd) { - Assert.isUnlocked(this); - if (yearBegin != m_year_begin || yearEnd != m_year_end) { - m_year_begin = yearBegin; - m_year_end = yearEnd; - - m_year.clearOptions(); - if (this.getParameterModel() instanceof IncompleteDateParameter) { - // Create an empty year entry to unset a date, if either - // a) skipYearAllowed is true - // b) skipDayAllowed is true and skipMonthAllowed is true, to unset a date - if (((IncompleteDateParameter) this.getParameterModel()) - .isSkipYearAllowed() - || (((IncompleteDateParameter) this.getParameterModel()) - .isSkipDayAllowed() - && ((IncompleteDateParameter) this - .getParameterModel()) - .isSkipMonthAllowed())) { - m_year.addOption(new Option("", "")); - } - } - if (yearAsc) { - for (int year = m_year_begin; year <= m_year_end; year++) { - m_year.addOption(new Option(String.valueOf(year))); - } - } else { - for (int year = m_year_end; year >= m_year_begin; year--) { - m_year.addOption(new Option(String.valueOf(year))); - } - } - } - } - - public boolean getYearAsc() { - return yearAsc; - } - - public void setYearAsc(final boolean yearAsc) { - this.yearAsc = yearAsc; - } - - public void addYear(java.util.Date date) { - Calendar cal = new GregorianCalendar(); - cal.setTime(date); - int year = (cal.get(Calendar.YEAR)); - if (year < m_year_begin) { - m_year.prependOption(new Option(String.valueOf(year))); - } - - if (year > m_year_end) { - m_year.addOption(new Option(String.valueOf(year))); - } - } - - /** - * Returns a string naming the type of this widget. - * - * @return - */ - @Override - public String getType() { - return "date"; - } - - /** - * Sets the MAXLENGTH attribute for the INPUT tag used to - * render this form element. - * - * @param length - */ - public void setMaxLength(int length) { - setAttribute("MAXLENGTH", String.valueOf(length)); - } - - @Override - public boolean isCompound() { - return true; - } - - /** - * The XML tag for this derived class of Widget. - * - * @return - */ - @Override - protected String getElementTag() { - return BEBOP_DATE; - } - - /** - * - * @param ps - * @param parent - */ - @Override - public void generateWidget(PageState ps, Element parent) { - - if (!isVisible(ps)) { - return; - } - - Element date = parent.newChildElement(getElementTag(), BEBOP_XML_NS); - date.addAttribute("name", getParameterModel().getName()); - if (getLabel() != null) { - date.addAttribute("label", (String) getLabel().localize(ps - .getRequest())); - } - exportAttributes(date); - generateDescriptionXML(ps, date); - generateLocalizedWidget(ps, date); - - // If Element could be null insert an extra widget to clear entry - if (!hasValidationListener(new NotNullValidationListener())) { - date.newChildElement("NoDate"); - } - } - - // Resepct the localized - public void generateLocalizedWidget(PageState ps, Element date) { - - Locale defaultLocale = Locale.getDefault(); - Locale locale = CdiUtil.createCdiUtil().findBean( - GlobalizationHelper.class).getNegotiatedLocale(); - - // Get the current Pattern - // XXX This is really, really, really, really, really, really bad - // but there is no way to get a SimpleDateFormat object for a - // different locale the the system default (the one you get with - // Locale.getDefault();). Also there is now way getting the pattern - // in another way (up until JDK 1.1 there was), so I have to temporarly - // switch the default locale to my desired locale, get a SimpleDateFormat - // and switch back. - Locale.setDefault(locale); - String format = new SimpleDateFormat().toPattern(); - Locale.setDefault(defaultLocale); - - // Repopulate the options for the month select box to get them localized - populateMonthOptions(); - - char[] chars = format.toCharArray(); - for (int i = 0; i < chars.length; i++) { - - // Test for doublettes - if (i >= 1 && chars[i - 1] == chars[i]) { - continue; - } - - switch (chars[i]) { - case 'd': - m_day.generateXML(ps, date); - break; - case 'M': - m_month.generateXML(ps, date); - break; - case 'y': - m_year.generateXML(ps, date); - break; - default: - break; - } - - } - - } - - @Override - public void setDisabled() { - m_month.setDisabled(); - m_day.setDisabled(); - m_year.setDisabled(); - } - - @Override - public void setReadOnly() { - m_month.setReadOnly(); - m_day.setReadOnly(); - m_year.setReadOnly(); - } - - /** - * Sets the Form Object for this Widget. This method will throw an exception - * if the _form pointer is already set. To explicity change the _form - * pointer the developer must first call setForm(null) - * - * @param f the Form Object for this Widget. - * - * @exception IllegalStateException if form already set. - */ - @Override - public void setForm(Form f) { - super.setForm(f); - m_year.setForm(f); - m_month.setForm(f); - m_day.setForm(f); - } - - public Object getFragmentValue(PageState ps, int field) { - Assert.exists(ps, "PageState"); - FormData f = getForm().getFormData(ps); - if (f != null) { - java.util.Date value = (java.util.Date) f.get(getName()); - if (value != null) { - Calendar c = Calendar.getInstance(); - c.setTime(value); - return new Integer(c.get(field)); - } - } - return null; - } - - @Override - public void setClassAttr(String at) { - m_month.setClassAttr(at); - m_year.setClassAttr(at); - m_day.setClassAttr(at); - super.setClassAttr(at); - } - - private void populateMonthOptions() { - - Locale locale = CdiUtil.createCdiUtil().findBean( - GlobalizationHelper.class).getNegotiatedLocale(); - - if (m_locale == null || (locale != null && !m_locale.equals(locale))) { - - DateFormatSymbols dfs = new DateFormatSymbols(locale); - String[] months = dfs.getMonths(); - - m_month.clearOptions(); - - if (this.getParameterModel() instanceof IncompleteDateParameter) { - if (((IncompleteDateParameter) this.getParameterModel()) - .isSkipMonthAllowed()) { - m_month.addOption(new Option("", "")); - } - } - for (int i = 0; i < months.length; i += 1) { - // This check is necessary because - // java.text.DateFormatSymbols.getMonths() returns an array - // of 13 Strings: 12 month names and an empty string. - if (months[i].length() > 0) { - m_month.addOption(new Option(String.valueOf(i), months[i])); - } - } - m_locale = CdiUtil.createCdiUtil().findBean( - GlobalizationHelper.class).getNegotiatedLocale(); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/DateTime.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/DateTime.java deleted file mode 100755 index dc780534f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/DateTime.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.DateTimeParameter; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.util.BebopConstants; -import com.arsdigita.xml.Element; - -/** - * A class representing a date and time field in an HTML form. - * (based on the code in Date.java) - * - * @author Sören Bernstein - * @version $Id$ - */ -public class DateTime extends Widget implements BebopConstants { - - private Date m_date; - private Time m_time; - - /** - * Construct a new DateTime. The model must be a DateTimeParameter - * @param model - */ - public DateTime(ParameterModel model) { - this(model, false); - } - - /** - * Construct a new DateTime. The model must be a DateTimeParameter - * @param model - * @param showSeconds - */ - public DateTime(ParameterModel model, boolean showSeconds) { - super(model); - - if (!(model instanceof DateTimeParameter)) { - throw new IllegalArgumentException( - "The DateTime widget " + model.getName() + - " must be backed by a DateTimeParameter parmeter model"); - } - - m_date = new Date(model); - m_time = new Time(model, showSeconds); - } - - public DateTime(String name) { - this(new DateTimeParameter(name)); - } - - public void setYearRange(int startYear, int endYear) { - m_date.setYearRange(startYear, endYear); - } - - /** - * Returns a string naming the type of this widget. - * @return - */ - @Override - public String getType() { - return "dateTime"; - } - - /** - * Sets the MAXLENGTH attribute for the INPUT tag - * used to render this form element. - */ - public void setMaxLength(int length) { - setAttribute("MAXLENGTH", String.valueOf(length)); - } - - public boolean isCompound() { - return true; - } - - /** The XML tag for this derived class of Widget. - */ - @Override - protected String getElementTag() { - return BEBOP_DATETIME; - } - - @Override - public void generateWidget(PageState ps, Element parent) { - - if (!isVisible(ps)) { - return; - } - - Element datetime = parent.newChildElement(getElementTag(), BEBOP_XML_NS); - datetime.addAttribute("name", getParameterModel().getName()); - m_date.generateLocalizedWidget(ps, datetime); - m_time.generateLocalizedWidget(ps, datetime); - - generateDescriptionXML(ps, datetime); - - // If Element could be null insert a extra widget to clear entry - if (!hasValidationListener(new NotNullValidationListener())) { - datetime.newChildElement("NoDateTime"); - } - } - - @Override - public void setDisabled() { - m_date.setDisabled(); - m_time.setDisabled(); - } - - @Override - public void setReadOnly() { - m_date.setReadOnly(); - m_time.setReadOnly(); - } - - /** - * Sets the Form Object for this Widget. This method will throw an - * exception if the _form pointer is already set. To explicity - * change the _form pointer the developer must first call - * setForm(null) - * - * @param the Form Object for this Widget. - * @exception IllegalStateException if form already set. - */ - @Override - public void setForm(Form f) { - super.setForm(f); - m_date.setForm(f); - m_time.setForm(f); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/Deditor.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/Deditor.java deleted file mode 100755 index 23342b5c5..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/Deditor.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - - -import com.arsdigita.xml.Element; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.parameters.ParameterModel; -// This interface contains the XML element name of this class -// in a constant which is used when generating XML -import com.arsdigita.bebop.util.BebopConstants; - - - -/** - * A class representing a textarea field in an HTML form. - * - * @deprecated See {@link DHTMLEditor} - * @author Jim Parsons - */ -public class Deditor extends Widget implements BebopConstants { - - - /** - * Constant for specifying OFF value for the - * WRAP attribute of this image input. See here - * for a description of what this attribute does. */ - - public static final int OFF = 0; - - /** - * Constant for specifying HARD value for the - * WRAP attribute of this image input. * See here - * for a description of what this attribute does. - */ - public static final int HARD = 1; - - /** - * Constant for specifying SOFT value for the - * WRAP attribute of this image input. See here - * for a description of what this attribute does. - */ - public static final int SOFT = 2; - - public Deditor(String name) { - super(name); - } - - public Deditor(ParameterModel model) { - super(model); - } - - - /** - * Returns a string naming the type of this widget. - */ - public String getType() { - return "deditor"; - } - - - /** - * Set the default value (text) - * @deprecated [since 17Aug2001] use {@link Widget#setDefaultValue(Object)} - */ - public void setValue( String text ) { - this.setDefaultValue(text); - } - - /** - * Sets the ROWS attribute for the TEXTAREA tag. - */ - public void setRows(int rows) { - setAttribute("rows", String.valueOf(rows)); - } - - /** - * Sets the COLS attribute for the TEXTAREA tag. - */ - public void setCols(int cols) { - setAttribute("cols", String.valueOf(cols)); - } - - /** - * Sets the COLS attribute for the TEXTAREA tag. - */ - public void setWrap(int wrap) { - String wrapString = null; - - switch (wrap) { - case OFF: - wrapString = "off"; - break; - case HARD: - wrapString = "hard"; - break; - case SOFT: - wrapString = "soft"; - break; - } - - if (wrapString != null) { - setAttribute("wrap", wrapString); - } - } - - /** - * Is this a compound widget? - * @return false - */ - public boolean isCompound() { - return false; - } - - /** The XML tag. - * @return The tag to be used for the top level DOM element - * generated for this type of Widget. */ - protected String getElementTag() { - return "bebop:deditor"; - } - - /** - * Generates the DOM for the textarea widget - *

Generates DOM fragment: - *

<bebop:textarea name=... value=... [onXXX=...]/> - * - */ - public void generateWidget( PageState state, Element parent ) { - - Element deditor = parent.newChildElement(getElementTag(), BEBOP_XML_NS); - - deditor.addAttribute("name", getName()); - - String userAgent = - state.getRequest().getHeader("user-agent").toLowerCase(); - boolean isIE55 = - (userAgent != null && - ((userAgent.indexOf("msie 5.5") != -1) || - (userAgent.indexOf("msie 6") != -1))); - - deditor.addAttribute("isIE55", (new Boolean(isIE55)).toString()); - - - String value = getParameterData(state).marshal(); - if ( value == null ) { - value = ""; - } - Element texter = deditor.newChildElement("bebop:textcontent",BEBOP_XML_NS); - texter.setCDATASection(value); - exportAttributes(deditor); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/Fieldset.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/Fieldset.java deleted file mode 100644 index 40922d78a..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/Fieldset.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.xml.Element; - -/** - * A fieldset for form. - * - * @author Sören Bernstein - */ -public class Fieldset extends SimpleContainer { - - GlobalizedMessage m_title; - - public Fieldset(GlobalizedMessage title) { - super("bebop:fieldset", BEBOP_XML_NS); - m_title = title; - } - - @Override - public void generateXML(PageState state, Element p) { - if (isVisible(state)) { - Element parent = generateParent(p); - parent.addAttribute("legend", (String) m_title.localize()); - generateChildrenXML(state, parent); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/FileUpload.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/FileUpload.java deleted file mode 100755 index 41b6da0ec..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/FileUpload.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.parameters.GlobalizedParameterListener; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.dispatcher.MultipartHttpServletRequest; -import com.arsdigita.globalization.GlobalizedMessage; - -import javax.servlet.http.HttpServletRequest; - - -/** - * A class representing a file upload widget. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Stas Freidin - * @author Rory Solomon - * @author Michael Pih - * @version $Id$ */ - -public class FileUpload extends Widget { - - public FileUpload(String name) { - this(name, true); - } - - public FileUpload(String name, boolean validateInputFile) { - super(name); - addValidationListener(new FileExistsValidationListener()); - } - - public FileUpload(ParameterModel model) { - this(model, true); - } - - public FileUpload(ParameterModel model, boolean validateInputFile) { - super(model); - addValidationListener(new FileExistsValidationListener()); - } - - /** - * Returns a string naming the type of this widget. - * @return - */ - @Override - public String getType() { - return "file"; - } - - /** - * - * @return - */ - @Override - public boolean isCompound() { - return false; - } - - - /** - * - */ - private class FileExistsValidationListener extends GlobalizedParameterListener { - - public FileExistsValidationListener() { - setError(new GlobalizedMessage("file_empty_or_not_found", getBundleBaseName())); - } - - @Override - public void validate (ParameterEvent e) { - ParameterData data = e.getParameterData(); - HttpServletRequest request = e.getPageState().getRequest(); - String filename = (String) data.getValue(); - - if (!(request instanceof MultipartHttpServletRequest) || - filename == null || - filename.length() == 0) { - return; - } - - if (((MultipartHttpServletRequest) request).getFile(data.getModel() - .getName()) - .length()==0) { - data.addError(filename + " " + getError().localize()); - } - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/FormErrorDisplay.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/FormErrorDisplay.java deleted file mode 100755 index 22ec69276..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/FormErrorDisplay.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.PageErrorDisplay; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.PageState; -import com.arsdigita.util.LockableImpl; - -import java.util.Collections; - -/** - * Displays validation errors on the form which were added by the form's - * validation listener. Does not handle errors in the individual parameters; - * these errors are handled by the form's template. This class is not - * a form widget, since it does not produce a value. - * - * @author Stanislav Freidin - * @version $Id$ - * - */ -public class FormErrorDisplay extends PageErrorDisplay { - - private Form m_form; - - /** - * Construct a new FormErrorDisplay - * - * @param form The parent form whose errors will be displayed by - * this widget - */ - public FormErrorDisplay(Form form) { - super(new FormErrorModelBuilder(form)); - m_form = form; - } - - /** - * Return the form whose errors are to be displayed - * @return the form whose errors are to be displayed - */ - public final Form getForm() { - return m_form; - } - - /** - * Determine if there are errors to display - * - * @param state the current page state - * @return true if there are any errors to display; false otherwise - */ - protected boolean hasErrors(PageState state) { - FormData data = m_form.getFormData(state); - return (data != null && data.getErrors().hasNext()); - } - - // A private class which builds a ListModel based on form errors - private static class FormErrorModelBuilder extends LockableImpl - implements ListModelBuilder { - - private Form m_form; - - public FormErrorModelBuilder(Form form) { - super(); - m_form = form; - } - - public ListModel makeModel(List l, PageState state) { - FormData data = m_form.getFormData(state); - if(data == null) { - return new StringIteratorModel(Collections.EMPTY_LIST.iterator()); - } else { - return new StringIteratorModel(data.getErrors()); - } - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/Hidden.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/Hidden.java deleted file mode 100755 index 968df902b..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/Hidden.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.parameters.ParameterModel; - -/** - * A class representing a hidden HTML form element. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Stas Freidin - * @author Rory Solomon - * @author Michael Pih - * @version $Id$ - */ -public class Hidden extends Widget { - - public Hidden(String name) { - super(name); - } - - public Hidden(ParameterModel model) { - super(model); - } - - /** - * Returns a string naming the type of this widget. - */ - public String getType() { - return "hidden"; - } - - public boolean isCompound() { - return false; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/ImageSubmit.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/ImageSubmit.java deleted file mode 100755 index 94728e23e..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/ImageSubmit.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.util.PanelConstraints; - -/** - * A class representing an image HTML form element. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Rory Solomon - * @author Michael Pih - * @version $Id$ - */ -public class ImageSubmit extends Widget implements PanelConstraints { - - - /** - * Constructor. - * - * @param name - */ - public ImageSubmit(String name) { - super(name); - } - - public ImageSubmit(ParameterModel model) { - super(model); - } - - /** - * Returns a string naming the type of this widget. - * - * @return - */ - @Override - public String getType() { - return "image"; - } - - /** - * Sets the SRC attribute for the INPUT tag - * used to render this form element. - * - * @param location - */ - public void setSrc(String location) { - setAttribute("src",location); - } - - /* - * Sets the ALRT attribute for the INPUT tag - * used to render this form element. - */ - public void setAlt(String alt) { - setAttribute("alt",alt); - } - - /** - * Sets the ALIGN attribute for the INPUT tag - * used to render this form element. Uses the positional constants defined - * in Interface PanelConstraints. - * Note: These may be refactored in future versions. - * - * @param align Symbolic constant denoting the alignment. - */ - public void setAlign(int align) { - String alignString = null; - - switch (align) { - case LEFT: - alignString = "left"; - break; - case RIGHT: - alignString = "right"; - break; - case TOP: - alignString = "top"; - break; - case ABSMIDDLE: - alignString = "absmiddle"; - break; - case ABSBOTTOM: - alignString = "absbottom"; - break; - case TEXTTOP: - alignString = "texttop"; - break; - case MIDDLE: - alignString = "middle"; - break; - case BASELINE: - alignString = "baseline"; - break; - case BOTTOM: - alignString = "botton"; - break; - } - - if (alignString != null) - setAttribute("align",alignString); - } - - @Override - public boolean isCompound() { - return false; - } - - /** - * Callback method for rendering this Image widget in a visitor. - */ - /* public void accept(FormVisitor visitor) throws IOException { - visitor.visitImage(this); - } - */ - - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/MultipleSelect.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/MultipleSelect.java deleted file mode 100755 index cbcdcc65c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/MultipleSelect.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.parameters.ArrayParameter; -// This interface contains the XML element name of this class -// in a constant which is used when generating XML -import com.arsdigita.bebop.util.BebopConstants; - -/** - * A class - * representing an HTML SELECT element. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Rory Solomon - * @author Michael Pih - * @version $Id$ */ -public class MultipleSelect extends Select implements BebopConstants { - - public MultipleSelect(String name) { - super(new ArrayParameter(name)); - } - - /** State that this is a multiple select - * @return true - */ - public boolean isMultiple() - { return true; } - - /** The XML tag for this derived class of Widget. */ - - protected String getElementTag() { - return BEBOP_MULTISELECT; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/MultipleSelectPairWidget.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/MultipleSelectPairWidget.java deleted file mode 100755 index 638d99194..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/MultipleSelectPairWidget.java +++ /dev/null @@ -1,557 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.FormStep; -import com.arsdigita.bebop.GridPanel; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.parameters.ArrayParameter; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Iterator; -import java.util.HashMap; -import java.util.Map; - -/** - *

Multiple select widget pair for knowledge types. This FormStep - * displays two multiple select widgets, one which contains possible - * the user may want to add, and the right displays the options that - * are currently applicable.

- * - *

To use the widget, you should call {@link - * #setLeftMultipleSelect(RequestLocal)} and {@link - * #setRightMultipleSelect(RequestLocal)} and pass in the appropriate - * collections to initialize the MutlipleSelect options. Then, in the - * process listener of the form in which the MultipleSelectPairWidget - * is embedded, call {@link #getSelectedOptions(PageState)} and {@link - * #getUnselectedOptions(PageState)} to get the chosen values. The process - * listener for the parent form must use the Submit.isSelected(ps) so - * that the process listener can distinguish between different types - * of form submits.

- * - *

Note that the right multiple select can be empty and does not need - * to be set. This class also uses a relatively inefficient - * implementation of removeOption in {@link OptionGroup OptionGroup} - * so that operations run in O(N^2). This can be reduced to O(N) with - * a more optimal implementation of OptionGroup.

- * - * @see Option - * @see OptionGroup - * @version $Id$ - */ -public class MultipleSelectPairWidget extends FormStep { - - private Hidden m_addSelectOptions; - private Hidden m_removeSelectOptions; - private MultipleSelect m_addSelect; - private MultipleSelect m_removeSelect; - private Submit m_addSubmit; - private Submit m_removeSubmit; - private RequestLocal m_addSelectDataSource; - private RequestLocal m_removeSelectDataSource; - private RequestLocal m_selectsPopulated; - private RequestLocal m_leftSelectMap = null; - private RequestLocal m_rightSelectMap = null; - private boolean m_leftSideChanges; - - private String m_qualifier; - - private final static int RIGHT = 1; - private final static int LEFT = 2; - - // Empty array for internal use. Should be part of a generic utility class. - private static final String[] EMPTY_STRING_ARRAY = new String[0]; - - // Configuration options. - private int m_multipleSelectSize = 20; - - /** - * This create a standard MultipleSelectPairWidget with the - * default names used for internal widgets. - */ - public MultipleSelectPairWidget() { - this(null); - } - - public MultipleSelectPairWidget(String nameQualifier) { - super(nameQualifier + "MultipleSelectPairWidget", new GridPanel(3)); - m_qualifier = nameQualifier; - - m_addSelectOptions = - new Hidden(new ArrayParameter(qualify("addSelectOptions"))); - m_removeSelectOptions = new Hidden - (new ArrayParameter(qualify("removeSelectOptions"))); - - m_addSelect = new MultipleSelect(qualify("leftSelect")); - m_addSelect.setSize(m_multipleSelectSize); - m_removeSelect = new MultipleSelect(qualify("rightSelect")); - m_removeSelect.setSize(m_multipleSelectSize); - setLeftSideChanges(true); - - m_addSubmit = new Submit(qualify("->"), " -> "); - m_removeSubmit = new Submit(qualify("<-"), " <- "); - - GridPanel centerPanel = new GridPanel(1); - centerPanel.add(m_addSubmit); - centerPanel.add(m_removeSubmit); - - add(m_addSelect, GridPanel.LEFT); - add(centerPanel, GridPanel.CENTER); - add(m_removeSelect, GridPanel.RIGHT); - add(m_addSelectOptions); - add(m_removeSelectOptions); - - m_selectsPopulated = new RequestLocal(); - addInitListener(new MultipleSelectPairFormInitListener - (m_selectsPopulated)); - addProcessListener(new MultipleSelectPairFormProcessListener - (m_selectsPopulated)); - } - - public boolean isSelected(PageState ps) { - return m_addSubmit.isSelected(ps) || m_removeSubmit.isSelected(ps); - } - - /** - * @param collection A collection of Option objects - */ - public void setLeftMultipleSelect(RequestLocal collection) { - m_addSelectDataSource = collection; - } - - /** - * This lets the user pass in a RequestLocal that returns - * a java.util.Map that contains the option value as the - * key and the actual option as the map value. - * When populating the left select, the system will use - * this map before falling back to the default map. - */ - public void setLeftMultipleSelectMap(RequestLocal map) { - m_leftSelectMap = map; - } - - /** - * This lets the user pass in a RequestLocal that returns - * a java.util.Map that contains the option value as the - * key and the actual option as the map value. - * When populating the left select, the system will use - * this map before falling back to the default map. - */ - public void setRightMultipleSelectMap(RequestLocal map) { - m_rightSelectMap = map; - } - - /** - * This returns the left select widget so that callers - * can have access to the underlying parameters and - * other features (e.g. in case they need to add a - * ParameterListener) - */ - public Widget getLeftSelect() { - return m_addSelect; - } - - /** - * This returns the left select widget so that callers - * can have access to the underlying parameters and - * other features (e.g. in case they need to add a - * ParameterListener) - */ - public Widget getRightSelect() { - return m_removeSelect; - } - - - /** - * @param doesChange This indicates whether the items in the - * "to add" select box are removed as they are added to - * the "to remove" select box. That is, as choices are - * selected, should they be removed from the list of - * choices? This defaults to true. - */ - public void setLeftSideChanges(boolean doesChange) { - m_leftSideChanges = doesChange; - } - - /** - * This returns an indication of whether or not the left - * multiple select changes as items are moved from the left - * to the right. - */ - public boolean leftSideChanges() { - return m_leftSideChanges; - } - - - /** - * @param collection A collection of Option objects - */ - public void setRightMultipleSelect(RequestLocal collection) { - m_removeSelectDataSource = collection; - } - - /** - * Returns the selected options, those selected from the left hand widget - * - * @return array of options - * @post return != null - */ - public String[] getSelectedOptions(PageState ps) { - String[] options = (String[]) m_removeSelectOptions.getValue(ps); - // Probably unneccessary, as widget should be populated with EMPTY_STRING_ARRAY in init listener - // if there is no data. - if (null == options) { - options = EMPTY_STRING_ARRAY; - } - return options; - } - - /** - * Returns the unselected options, those removed from the right hand widget - * - * @return array of options - * @post return != null - */ - public String[] getUnselectedOptions(PageState ps) { - String[] options = (String[]) m_addSelectOptions.getValue(ps); - // Probably unneccessary, as widget should be populated with EMPTY_STRING_ARRAY in init listener - // if there is no data. - if (null == options) { - options = EMPTY_STRING_ARRAY; - } - return options; - } - - public void generateXML(PageState state, Element element) { - // if the page has not been populated then it need to - // be populated from the hidden variables. Otherwise, - // nothing will be displayed in the multi-select boxes. - if (!Boolean.TRUE.equals(m_selectsPopulated.get(state)) && - isInitialized(state)) { - List addOptions = new ArrayList(); - List removeOptions = new ArrayList(); - - String[] unselected = getUnselectedOptions(state); - for (int i = 0; i < unselected.length; i++) { - String option = unselected[i]; - addOptions.add(option); - } - - String[] selected = getSelectedOptions(state); - for (int i = 0; i < selected.length; i++) { - String option = selected[i]; - removeOptions.add(option); - } - - - m_selectsPopulated.set(state, Boolean.TRUE); - generateOptionValues(state, addOptions, removeOptions, - setupOptionMap(state)); - m_addSelect.addOption(getEmptyOption(), state); - m_removeSelect.addOption(getEmptyOption(), state); - } - super.generateXML(state, element); - } - - /** - * This changes the name of the parameter so that it is possible - * to include several of these on the same page. - */ - private String qualify(String property) { - if (m_qualifier != null) { - return m_qualifier + "_" + property; - } else { - return property; - } - } - - - /** - * @size The number of rows to display in the multiple selects. - */ - public void setMultipleSelectSize(int size) { - m_multipleSelectSize = size; - m_removeSelect.setSize(m_multipleSelectSize); - m_addSelect.setSize(m_multipleSelectSize); - } - - private HashMap setupOptionMap(PageState ps) { - // We put all of our options into a HashMap so that we can add the - // Option object to the destination MultipleSelect. - HashMap optionsMap = new HashMap(); - Collection addOptions = (Collection) m_addSelectDataSource.get(ps); - - Iterator i; - Option option; - - i = addOptions.iterator(); - while ( i.hasNext() ) { - option = (Option) i.next(); - optionsMap.put(option.getValue(), option); - } - - if ( m_removeSelectDataSource != null ) { - Collection removeOptions = (Collection) m_removeSelectDataSource.get(ps); - if ( removeOptions != null ) { - i = removeOptions.iterator(); - while ( i.hasNext() ) { - option = (Option) i.next(); - if (optionsMap.get(option.getValue()) == null) { - optionsMap.put(option.getValue(), option); - } - } - } - } - - return optionsMap; - } - - private void generateOptionValues(PageState ps, List addOptions, - List removeOptions, - HashMap m_optionsMap) { - Iterator iter; - - iter = addOptions.iterator(); - while ( iter.hasNext() ) { - String s = (String) iter.next(); - Option o = getOption(ps, m_optionsMap, s, LEFT); - // it is possible to be null if for some reason the key, s, is - // not found any of the maps - if (o != null) { - m_addSelect.addOption(o, ps); - } - } - - iter = removeOptions.iterator(); - while ( iter.hasNext() ) { - String s = (String) iter.next(); - Option o = getOption(ps, m_optionsMap, s, RIGHT); - // it is possible to be null if for some reason the key, s, is - // not found any of the maps - if (o != null) { - m_removeSelect.addOption(o, ps); - } - } - } - - - /** - * This looks at the request locals set in setRightMultipleSelectMap - * and setLeftMultipleSelectMap before falling back on the default - * mapping that was auto-generated. If the value is found - * in the passed in map then that value is used. Otherwise, the - * value is located in the default mapping - */ - private Option getOption(PageState state, Map optionMapping, String key, - int side) { - if (side == RIGHT) { - if (m_rightSelectMap != null) { - Map map = (Map)m_rightSelectMap.get(state); - if (map.get(key) != null) { - return (Option)map.get(key); - } - } - } else { - if (m_leftSelectMap != null) { - Map map = (Map)m_leftSelectMap.get(state); - if (map.get(key) != null) { - return (Option)map.get(key); - } - } - } - return (Option)optionMapping.get(key); - } - - private class MultipleSelectPairFormProcessListener - implements FormProcessListener { - - // This is to allow a call back to set an item as being - // initialized - private RequestLocal m_processed; - MultipleSelectPairFormProcessListener(RequestLocal processed) { - m_processed = processed; - } - - public void process(FormSectionEvent evt) { - PageState ps = evt.getPageState(); - - if (!m_addSubmit.isSelected(ps) - && !m_removeSubmit.isSelected(ps)) { - return; - } - - m_processed.set(ps, Boolean.TRUE); - - HashMap m_optionsMap; - List addOptions = new ArrayList(); - List removeOptions = new ArrayList(); - - m_optionsMap = setupOptionMap(ps); - - // We first update the array lists that contain the list - // of unselected options based on the contents of the - // hidden form variables. - updateUnselectedOptions(ps, addOptions, removeOptions); - - // Then we update those array lists based on what the user - // moves. - if ( m_addSubmit.isSelected(ps) ) { - String[] selectedArray = (String[]) m_addSelect.getValue(ps); - if ( selectedArray != null ) { - List selectedAddOptions = Arrays.asList(selectedArray); - Iterator iter = selectedAddOptions.iterator(); - while ( iter.hasNext() ) { - String s = (String) iter.next(); - // we only want to add the item if it has not - // already been added - if (!removeOptions.contains(s)) { - removeOptions.add(s); - } - if (leftSideChanges()) { - addOptions.remove(s); - } - } - } - } - - if ( m_removeSubmit.isSelected(ps) ) { - String[] selectedArray = (String[]) m_removeSelect.getValue(ps); - if ( selectedArray != null ) { - List selectedRemoveOptions = Arrays.asList(selectedArray); - Iterator iter = selectedRemoveOptions.iterator(); - while ( iter.hasNext() ) { - String s = (String) iter.next(); - removeOptions.remove(s); - // if the left side does not change then the - // item was never removed from the addOptions so - // it does not need to be added back. - if (leftSideChanges()) { - addOptions.add(s); - } - } - } - } - - // Next, we put the full list of options back into the hidden. - // we have to convert this to a String[]...otherwise we - // can get a ClassCastException when used within a Wizard - String[] newValues = (String[]) addOptions.toArray(EMPTY_STRING_ARRAY); - m_addSelectOptions.setValue(ps, newValues); - - // We do the same conversion for the new values - newValues = (String[]) removeOptions.toArray(EMPTY_STRING_ARRAY); - m_removeSelectOptions.setValue(ps, newValues); - - // We finally generate the option values. - generateOptionValues(ps, addOptions, removeOptions, m_optionsMap); - m_addSelect.addOption(getEmptyOption(), ps); - m_removeSelect.addOption(getEmptyOption(), ps); - } - - private void updateUnselectedOptions(PageState ps, List addOptions, - List removeOptions) { - // We add the unselected options back to the MultipleSelects. - String[] unselected = getUnselectedOptions(ps); - for (int i = 0; i < unselected.length; i++) { - String s = unselected[i]; - addOptions.add(s); - } - - String[] selected = getSelectedOptions(ps); - for (int i = 0; i < selected.length; i++) { - String s = selected[i]; - removeOptions.add(s); - } - - - } - } - - private class MultipleSelectPairFormInitListener implements FormInitListener { - private RequestLocal m_initialized; - MultipleSelectPairFormInitListener(RequestLocal initialized ) { - m_initialized = initialized; - } - - public void init(FormSectionEvent evt) { - PageState ps = evt.getPageState(); - m_initialized.set(ps, Boolean.TRUE); - - String[] addOptionsForHidden = EMPTY_STRING_ARRAY; - String[] removeOptionsForHidden = EMPTY_STRING_ARRAY; - - Assert.exists(m_addSelectDataSource, - "You must provide some options for the " + - "user to choose!"); - - Collection addOptions = (Collection) m_addSelectDataSource.get(ps); - if (addOptions.size() > 0) { - Iterator iter = addOptions.iterator(); - addOptionsForHidden = new String[addOptions.size()]; - int idx = 0; - while ( iter.hasNext() ) { - Option option = (Option) iter.next(); - m_addSelect.addOption(option, ps); - addOptionsForHidden[idx++] = option.getValue(); - } - - } - - if ( m_removeSelectDataSource != null ) { - Collection c = (Collection) m_removeSelectDataSource.get(ps); - if ( c != null && c.size() > 0 ) { - removeOptionsForHidden = new String[c.size()]; - Iterator iter = c.iterator(); - int idx = 0; - while ( iter.hasNext() ) { - Option option = (Option) iter.next(); - m_removeSelect.addOption(option, ps); - removeOptionsForHidden[idx++] = option.getValue(); - } - } - } - - m_addSelectOptions.setValue(ps, addOptionsForHidden); - m_removeSelectOptions.setValue(ps, removeOptionsForHidden); - m_addSelect.addOption(getEmptyOption(), ps); - m_removeSelect.addOption(getEmptyOption(), ps); - } - } - - private Option getEmptyOption() { - return new Option("", - new Label("        " + - "        " + - "        " + - "        " + - "        " + - "        ", - false)); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/Option.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/Option.java deleted file mode 100755 index 65960c7cc..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/Option.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.DescriptiveComponent; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.util.Assert; -import com.arsdigita.bebop.util.BebopConstants; -import com.arsdigita.xml.Element; - -/** - * A class representing an option of a widget. - * - * The Option consist of two parts: - * - a value, used by the background task to process the option - * - a display component, used to display the option to the user in the GUI, - * usually a Label (title), but may be e.g. an image as well. - - * @author Rory Solomon - * @author Michael Pih - * - * $Id$ - */ -public class Option extends DescriptiveComponent { - - /** The value of the option, used by the background task to process the - * option. - * NOTE: The display component, the label, is provided by parent class! */ - private String m_value; - /** The display component for the user in the GUI. It's usually a Label, - * but may be e.g. an image as well. */ - private Component m_component; - private OptionGroup m_group; - private boolean m_isSelectOption; - - // /////////////////////////////////////////////////////////////////////// - // Constructor Section - // - - /** - * A (too) simple Constructor which uses a String as value as well as - * display component. - * - * @param value A String used as value as well as display component. - * @deprecated use Option(value,component) instead - */ - public Option(String value) { - this(value, value); - } - - /** - * Constructor creates an Option whose label part consisting of a string. - * This results in a badly globalized label part. The localization depends - * on the language selected at the time the Option is created. - * - * @param value - * @param label - * @deprecated use Option(value,component) instead - */ - public Option(String value, String label) { - setValue(value); - setLabel(label); - } - - /** - * Constructor creates an Option whose label part consisting of a Component, - * usually a Label(GlobalizedMessage). - * This constructor should be used to create a fully globalized and - * localized user interface. - * - * @param value - * @param label - */ - public Option(String value, Component label) { - setValue(value); - setComponent(label); - } - - // /////////////////////////////////////////////////////////////////////// - // Getter/Setter Section - // - - /** - * Retrieves the value part of an option. - * @return the value part of this option. - */ - public final String getValue() { - return m_value; - } - - /** - * Sets of modifies the value of on option. - * @param value new value part of the option - */ - public final void setValue(String value) { - m_value = value; - } - - - /** - * Retrieves the display part of the option. - * @return the display component for this option - */ - public final Component getComponent() { - return m_component; - } - - /** - * Sets of modifies the display component of an option. - * - * @param component the display component for this option - */ - public final void setComponent(Component component) { - Assert.isUnlocked(this); - m_component = component; - } - - /** - * Sets of modifies the display component of an option providing a Label. - * The label is internally stored as a component. - * - * @param label - */ - public final void setLabel(Label label) { - setComponent(label); - } - - /** - * This sets the display component using a String. It results in a badly - * globalized UI - * - * @param label String to use as the display component - * @deprecated Use {@link #setComponent(Component component)} instead - */ - public final void setLabel(String label) { - setComponent(new Label(label)); - } - - - /** - * - * @param group - */ - public final void setGroup(OptionGroup group) { - Assert.isUnlocked(this); - Assert.exists(group); - m_group = group; - m_isSelectOption = BebopConstants.BEBOP_OPTION.equals(m_group.getOptionXMLElement()); - } - - /** - * - * @return - */ - public final OptionGroup getGroup() { - return m_group; - } - - /** - * Retrieves the name (identifier) of the option group containing this - * option. Don't know the purpose of this. - * - * @return The name (identifier) of the option group this option belongs - * to - */ - public String getName() { - return m_group.getName(); - } - - - /** - * Sets the ONFOCUS attribute for the HTML tags that compose - * this element. - * @param javascriptCode - */ - public void setOnFocus(String javascriptCode) { - setAttribute(Widget.ON_FOCUS,javascriptCode); - } - - /** - * Sets the ONBLUR attribute for the HTML tags that compose - * this element. - * @param javascriptCode - */ - public void setOnBlur(String javascriptCode) { - setAttribute(Widget.ON_BLUR,javascriptCode); - } - - /** - * Sets the ONSELECT attribute for the HTML tags that compose - * this element. - * @param javascriptCode - */ - public void setOnSelect(String javascriptCode) { - setAttribute(Widget.ON_SELECT,javascriptCode); - } - - /** - * Sets the ONCHANGE attribute for the HTML tags that compose - * this element. - * @param javascriptCode - */ - public void setOnChange(String javascriptCode) { - setAttribute(Widget.ON_CHANGE,javascriptCode); - } - - - /** - * Sets the ON_KEY_UP attribute for the HTML tags that compose - * this element. - * @param javascriptCode - **/ - - public void setOnKeyUp(String javascriptCode) { - setAttribute(Widget.ON_KEY_UP, javascriptCode); - } - - /** - * Sets the ONCLICK attribute for the HTML tags that compose - * this element. - * @param javascriptCode - */ - public void setOnClick(String javascriptCode) { - setAttribute(Widget.ON_CLICK,javascriptCode); - } - - private ParameterData getParameterData(PageState s) { - return m_group.getParameterData(s); - } - - public boolean isSelected(ParameterData data) { - if (data == null || data.getValue() == null) { - return false; - } - Object value = data.getValue(); - - Object[] selectedValues; - if (value instanceof Object[]) { - selectedValues = (Object[])value; - } else { - selectedValues = new Object[] {value}; - } - String optionValue = getValue(); - - if (optionValue == null || selectedValues == null) { - return false; - } - for (Object selectedValue : selectedValues) { - if (selectedValue != null - && optionValue.equalsIgnoreCase(selectedValue.toString())) { - return true; - } - } - return false; - } - - /** - * Generate XML depending on what OptionGr. - * - * @param s - * @param e - */ - @Override - public void generateXML(PageState s, Element e) { - Element option = e.newChildElement(m_group.getOptionXMLElement(), BEBOP_XML_NS); - if ( ! m_isSelectOption ) { - option.addAttribute("name", getName()); - } - option.addAttribute("value", getValue()); - - if (m_component != null) { - m_component.generateXML(s, option); - } else { - (new Label()).generateXML(s, option); - } - - exportAttributes(option); - if ( isSelected(getParameterData(s)) ) { - if ( m_isSelectOption ) { - option.addAttribute("selected", "selected"); - } else { - option.addAttribute("checked", "checked"); - } - } - } - - /** - * Kludge to live with the fact that options don't do their own - * printing. Don't use this method, it will go away ! - * - * @deprecated Will be removed without replacement once option handling - * has been refactored. - */ - final void generateAttributes(Element target) { - exportAttributes(target); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/form/OptionGroup.java b/ccm-core/src/main/java/com/arsdigita/bebop/form/OptionGroup.java deleted file mode 100755 index 3c1385139..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/form/OptionGroup.java +++ /dev/null @@ -1,596 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.form; - -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.ParameterModelWrapper; -import com.arsdigita.bebop.util.BebopConstants; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.text.Collator; - -import java.util.Iterator; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; - -/** - * A class representing any widget that contains a list of options. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Rory Solomon - * @author Michael Pih - */ -public abstract class OptionGroup extends Widget implements BebopConstants { - - private static final Logger LOGGER = LogManager.getLogger(OptionGroup.class); - - /** - * The XML element to be used by individual options belonging to this group. - * This variable has to be initialized by every subclass of OptionGroup. - * LEGACY: An abstract method would be the better design, but changing it - * would break the API. - */ - //protected String m_xmlElement; - // this only needs to be an ArrayList for multiple selection option groups - private List m_selected; - private List
- * line 4 column 22 - Warning: replacing unexpected
by - * line 5 column 1 - Warning: discarding unexpected - * line 6 column 2 - Error: is not recognized! - * line 6 column 2 - Warning: discarding unexpected - * line 6 column 9 - Warning: discarding unexpected - * This document has errors that must be fixed before - * using HTML Tidy to generate a tidied up version. - * - * If there are no errors (meaning, there are only warning or - * no warnings), then the last chunk does not appear. - */ - - String summary = null; - while (st.hasMoreTokens()) { - String token = st.nextToken(); - if ( token.startsWith(LINE_WARNING_START) ) { - if ( !canBeIgnored(token) ) { - warningsAndErrors.add(StringUtils.quoteHtml(token)); - m_hasWarnings = true; - } - } else { - summary = token; - if ( st.hasMoreTokens() ) { - summary += st.nextToken(""); - } - break; - } - } - - StringBuffer sb = new StringBuffer(); - - if ( warningsAndErrors.size() > 0 ) { - if ( warningsAndErrors.size() == 1 ) { - sb.append("

").append((String) warningsAndErrors.get(0)); - sb.append("

").append(LINE_SEPARATOR); - } else { - sb.append("
    ").append(LINE_SEPARATOR); - for (Iterator i=warningsAndErrors.iterator(); i.hasNext(); ) { - sb.append("
  1. ").append((String) i.next()); - sb.append("
  2. ").append(LINE_SEPARATOR); - } - sb.append("
").append(LINE_SEPARATOR); - } - } - if ( summary != null ) { - sb.append("

").append(StringUtils.quoteHtml(summary)).append("

"); - m_hasErrors = !isWarning(summary); - } - m_formattedMessage = sb.toString(); - } - } - - private static class LockableProperties extends Properties { - private boolean m_isLocked = false; - - public LockableProperties() { - super(); - } - - public LockableProperties(Properties defaults) { - super(defaults); - } - - public void lock() { - m_isLocked = true; - } - - private void checkIfLocked() { - if (m_isLocked) { - throw new RuntimeException - ("The object cannot be modified once initialized."); - } - } - - public Object setProperty(String key, String value) { - checkIfLocked(); - return super.setProperty(key, value); - } - - public void load(InputStream is) throws IOException { - checkIfLocked(); - super.load(is); - } - - public Object put(Object key, Object value) { - checkIfLocked(); - return super.put(key, value); - } - - public void putAll(java.util.Map t) { - checkIfLocked(); - super.putAll(t); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/TimeParameter.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/TimeParameter.java deleted file mode 100755 index cde3c5c13..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/TimeParameter.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -import com.arsdigita.globalization.Globalization; - -import com.arsdigita.util.StringUtils; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; - -import java.text.DateFormat; -import java.text.ParseException; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; - -import javax.servlet.http.HttpServletRequest; - -/** - * A class that represents the model for a time form parameter. - * - * @see com.arsdigita.bebop.parameters.DateTimeParameter - * @author Dave Turner - * @version $Id$ - */ -public class TimeParameter extends ParameterModel { - - public TimeParameter(String name) { - super(name); - } - - /** - * This method returns a new Calendar object that is manipulated within - * transformValue to create a Date Object. This method should be overridden - * if you wish to use a Calendar other than the lenient GregorianCalendar. - * - * @param request the servlet request from which Locale can be extracted if - * needed - * - * @return a new Calendar object - * - */ - protected Calendar getCalendar(HttpServletRequest request) { - return new GregorianCalendar(); - } - - /** - * Computes a dateTime object from multiple parameters in the request. This - * method searches for parameters named getName() + ".hour", - * getName() + ".minute", - * getName() + ".second", and - * getName() + ".amOrPm". - * - */ - public Object transformValue(HttpServletRequest request) - throws IllegalArgumentException { - - Calendar c = getCalendar(request); - c.clear(); - - String hour = Globalization - .decodeParameter(request, getName() + ".hour"); - String minute = Globalization.decodeParameter(request, getName() - + ".minute"); - String second = Globalization.decodeParameter(request, getName() - + ".second"); - String amOrPm = Globalization.decodeParameter(request, getName() - + ".amOrPm"); - - if (StringUtils.emptyString(hour) && StringUtils.emptyString(minute) - && StringUtils.emptyString(second)) { - return transformSingleValue(request); - } - - if (!StringUtils.emptyString(hour)) { - int hourInt = Integer.parseInt(hour); - /* Das ist alles Blödsinn. Beim 24-Stundenformat brauchen wir das sowieso nicht. -Beim 12-Stunden-Formato müßte es, wenn überhaupt, anderherum sein: Aus einer -eingetragenen 0 in den Stunden muß eine 12 werden. ABER: Die Informationen -werden in einem Calendar-Object gespeichert, das intern immer 24-Stunden-Format -verwendet. Das 12-Stunden-Format ist eine Frage der Formatierung und somit -hier irrelevant. Es bleibt zu testet, ob ein 12:00 AM im Caendar-Object tatsächlich -zu 0:00 Uhr wird. - if ((hourInt == 12) && has12HourClock()) { - hourInt = 0; - } - */ - c.set(Calendar.HOUR, hourInt); - } - - if (!StringUtils.emptyString(minute)) { - c.set(Calendar.MINUTE, Integer.parseInt(minute)); - } - - if (!StringUtils.emptyString(second)) { - c.set(Calendar.SECOND, Integer.parseInt(second)); - } - - if (amOrPm != null) { - c.set(Calendar.AM_PM, Integer.parseInt(amOrPm)); - } - - return c.getTime(); - } - - public Object unmarshal(String encoded) { - try { - return new Date(Long.parseLong(encoded)); - } catch (NumberFormatException ex) { - throw new IllegalArgumentException("Cannot unmarshal time '" - + encoded + "': " + ex - .getMessage()); - } - } - - public String marshal(Object value) { - return Long.toString(((Date) value).getTime()); - } - - public Class getValueClass() { - return Date.class; - } - - private boolean has12HourClock() { - Locale locale = CdiUtil.createCdiUtil().findBean( - GlobalizationHelper.class).getNegotiatedLocale(); - DateFormat format_12Hour = DateFormat.getTimeInstance(DateFormat.SHORT, - Locale.US); - DateFormat format_locale = DateFormat.getTimeInstance(DateFormat.SHORT, - locale); - - String midnight = ""; - try { - midnight = format_locale.format(format_12Hour.parse("12:00 AM")); - } catch (ParseException ignore) { - } - - return midnight.contains("12"); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/TrimmedStringParameter.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/TrimmedStringParameter.java deleted file mode 100755 index ee56545a0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/TrimmedStringParameter.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -import javax.servlet.http.HttpServletRequest; - -/** - * A class that represents the model for String form parameters. - * This class extends StringParameter and differs by calling trim() - * on non-null values. This class is useful for fields you want to - * put in the DB without leading and trailng spaces - * - * @author Karl Goldstein - * @author Uday Mathur - * @version $Id$ - */ -public class TrimmedStringParameter extends StringParameter { - - public TrimmedStringParameter(String name) { - super(name); - } - - public Object transformValue(HttpServletRequest request) - throws IllegalArgumentException { - - String requestValue = (String)super.transformValue(request); - if (requestValue!=null) { - requestValue = requestValue.trim(); - } - return (requestValue==null) ? null : unmarshal(requestValue); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/TypeCheckValidationListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/TypeCheckValidationListener.java deleted file mode 100755 index 3f07f7e47..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/TypeCheckValidationListener.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.globalization.GlobalizedMessage; - -/** - * Verifies that the - * parameter's type is the expected type - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Stas Freidin - * @author Rory Solomon - * @version $Id$ - */ -public class TypeCheckValidationListener extends GlobalizedParameterListener { - - private Class m_type; - - public TypeCheckValidationListener(Class type) { - this.m_type = type; - } - - public TypeCheckValidationListener(Class type, GlobalizedMessage error) { - this.m_type = type; - setError(error); - } - - public void validate (ParameterEvent e) { - - ParameterData data = e.getParameterData(); - Object obj = data.getValue(); - - if (obj == null && data.isTransformed()) { - return; - } - - if (getError() == null) { - setError(new GlobalizedMessage( - "type_check", - getBundleBaseName(), - new Object[] { - data.getName(), - m_type.getName(), - obj.toString(), - obj.getClass().getName() - } - )); - } - - if (!m_type.isInstance(obj)) { - data.addError(getError()); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URIParameter.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URIParameter.java deleted file mode 100644 index 142bd4398..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URIParameter.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2009 Permeance Technologies Pty Ltd. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -/** - * A parameter that contains a URI formatted according to RFC2396: - * - * @see URIValidationListener - * - * @author terry_permeance - */ -public class URIParameter extends StringParameter { - - public URIParameter(String name) { - super(name); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URIValidationListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URIValidationListener.java deleted file mode 100644 index df8e2f2d4..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URIValidationListener.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) Permeance Technologies Pty Ltd. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -import java.net.URI; -import java.net.URISyntaxException; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.event.ParameterListener; -import com.arsdigita.globalization.GlobalizedMessage; - -/** - * A parameter listener that ensures a parameter is a URI formatted - * according to RFC2396: - * - *
- *
- * The following examples illustrate URI that are in common use.
- * 
- * ftp://ftp.is.co.za/rfc/rfc1808.txt
- *    -- ftp scheme for File Transfer Protocol services
- * 
- * gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles
- *    -- gopher scheme for Gopher and Gopher+ Protocol services
- * 
- * http://www.math.uio.no/faq/compression-faq/part1.html
- *    -- http scheme for Hypertext Transfer Protocol services
- * 
- * mailto:mduerst@ifi.unizh.ch
- *    -- mailto scheme for electronic mail addresses
- * 
- * news:comp.infosystems.www.servers.unix
- *    -- news scheme for USENET news groups and articles
- * 
- * telnet://melvyl.ucop.edu/
- *    -- telnet scheme for interactive services via the TELNET Protocol
- * 
- *
- * - * @author terry_permeance - */ -public class URIValidationListener extends GlobalizedParameterListener { - - public URIValidationListener() { - setError(new GlobalizedMessage("uri_parameter_is_invalid", getBundleBaseName())); - } - - /** - * @see ParameterListener#validate(ParameterEvent) - */ - public void validate(ParameterEvent e) throws FormProcessException { - - ParameterData d = e.getParameterData(); - String value = (String)d.getValue(); - - if (value != null && value.length() > 0) { - try { - URI uri = new URI(value); - if (!uri.isAbsolute()) { - d.addError(this.getError()); - } - } catch (URISyntaxException ex) { - d.addError(this.getError()); - } - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URLParameter.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URLParameter.java deleted file mode 100755 index 74f74b601..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URLParameter.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -import com.arsdigita.globalization.Globalization; -import java.net.MalformedURLException; -import java.net.URL; -import javax.servlet.http.HttpServletRequest; - -/** - * A class that represents the model for URL form parameters. - * - * @author Karl Goldstein - * @author Uday Mathur - * @author Rory Solomon - * @version $Id$ - */ -public class URLParameter extends StringParameter { - - public URLParameter(String name) { - super(name); - } - - @Override - public Object transformValue(HttpServletRequest request) - throws IllegalArgumentException { - - String requestValue = Globalization.decodeParameter(request, getName()); - if (requestValue==null) { - return null; - } - URL URLValue; - try { - URLValue = new URL(requestValue); - } catch (MalformedURLException e) { - try { - URLValue = new URL("HTTP://" + requestValue); - } catch (MalformedURLException e2) { - throw new IllegalArgumentException - (getName() + " is not a valid URL: '" + requestValue + - "'; " + e2.getMessage()); - } - } - return unmarshal(requestValue); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URLTokenValidationListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URLTokenValidationListener.java deleted file mode 100755 index 3c2c9df4e..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URLTokenValidationListener.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.globalization.GlobalizedMessage; -//import com.arsdigita.bebop.parameters.ParameterData; - -import org.apache.oro.text.perl.Perl5Util; - -/** - * Verifies that the parameter's value is composed only of character which are - * valid as part on an URL name (the token). - * That is only alpha-numeric, underscore, or hyphen characters. - * [a-zA-Z_0-9\-] - * - * Note: An empty string will pass the validation tests. - * - * @author Michael Pih - * @version $Id$ - */ -public class URLTokenValidationListener extends GlobalizedParameterListener { - - /** match 1 or more instances of a non-alpha-numeric character */ - private static final String NON_KEYWORD_PATTERN = "/[^a-zA-Z_0-9\\-]+/"; - - /** - * Default Constructor setting a predefined label as error message. - */ - public URLTokenValidationListener() { - setError(new GlobalizedMessage("bebop.parameters.must_be_valid_part_of_url", - getBundleBaseName() ) - ); - } - - /** - * Constructor taking a label specified as key into a resource bundle to - * customize the error message. - * - * @param label key into the resource bundle - * @deprecated use URLTokenValidationListener(GlobalizedMessage error) - */ - public URLTokenValidationListener(String label) { - setError(new GlobalizedMessage(label, getBundleBaseName())); - } - - /** - * Constructor taking a GlobalizedMessage as error message to display. - * - * @param error GloblizedMessage taken as customized error message. - */ - public URLTokenValidationListener(GlobalizedMessage error) { - setError(error); - } - - - /** - * Validates the parameter by checking if the value is a valid keyword. - * A keyword is defined as any combination of alph-numeric characters, - * hyphens, and/or underscores. [a-zA-Z_0-9\-] - * - * Note: An empty string will pass the validation tests. - * - * @param event The parameter event - */ - @Override - public void validate(ParameterEvent event) { - ParameterData data = event.getParameterData(); - Object value = data.getValue(); - - Perl5Util util = new Perl5Util(); - if ( !util.match(NON_KEYWORD_PATTERN, value.toString()) ) { - return; - } - data.addError(getError()); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URLValidationListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URLValidationListener.java deleted file mode 100755 index 5cfcbf2b5..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/URLValidationListener.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.event.ParameterListener; -import com.arsdigita.bebop.FormProcessException; -//import com.arsdigita.bebop.parameters.ParameterData; -import java.net.MalformedURLException; -import java.net.URL; - -/** - * - * - */ -public class URLValidationListener implements ParameterListener { - - @Override - public void validate(ParameterEvent e) - throws FormProcessException { - - ParameterData d = e.getParameterData(); - String value = (String)d.getValue(); - - if (!value.equals("")) { - try { - new URL(value); - } catch (MalformedURLException ex) { - d.invalidate(); - d.addError("Please enter a URL"); - } - } -} -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/UniqueStringValidationListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/UniqueStringValidationListener.java deleted file mode 100644 index 21a4bf3fc..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/UniqueStringValidationListener.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) Permeance Technologies Pty Ltd. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.Assert; - -/** - * Validates that a {@link String} property of a {@link DomainObject} is unique. - * - * @author - * terry_permeance - */ -public class UniqueStringValidationListener extends GlobalizedParameterListener { - - public UniqueStringValidationListener(String baseDataObjectType, - String propertyKey, - ParameterModel domainParameter) { - - this.setError(new GlobalizedMessage("parameter_not_unique", this - .getBundleBaseName())); - Assert.exists(baseDataObjectType); - Assert.exists(propertyKey); - Assert.exists(domainParameter); - m_baseDataObjectType = baseDataObjectType; - m_propertyKey = propertyKey; - m_domainParameter = domainParameter; - } - - public void validate(ParameterEvent e) throws FormProcessException { - -// ParameterData data = e.getParameterData(); -// String propertyValue = (data.getValue() == null ? null : String.valueOf( -// data.getValue())); -// -// if (propertyValue != null && propertyValue.length() > 0) { -// // Get the current domain object -// DomainObject domainObject = (DomainObject) e.getPageState() -// .getValue(m_domainParameter); -// -// // Check if there are any existing matches -// DataCollection collection = SessionManager.getSession().retrieve( -// m_baseDataObjectType); -// collection.addEqualsFilter(m_propertyKey, propertyValue); -// while (collection.next()) { -// if (domainObject == null || !collection.getDataObject().getOID() -// .equals(domainObject.getOID())) { -// data.addError(this.getError()); -// break; -// } -// } -// } - } - - private final String m_baseDataObjectType; - - private final String m_propertyKey; - - private final ParameterModel m_domainParameter; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/WordValidationListener.java b/ccm-core/src/main/java/com/arsdigita/bebop/parameters/WordValidationListener.java deleted file mode 100755 index 11a9a9298..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/parameters/WordValidationListener.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.parameters; - -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.event.ParameterListener; -import com.arsdigita.bebop.FormProcessException; - -import org.apache.logging.log4j.LogManager; -import org.apache.oro.text.perl.Perl5Util; - -import org.apache.logging.log4j.Logger; - -public class WordValidationListener implements ParameterListener { - - private static final Logger LOGGER = LogManager.getLogger( WordValidationListener.class ); - - public void validate(ParameterEvent e) - throws FormProcessException { - - ParameterData d = e.getParameterData(); - String value = (String)d.getValue(); - - if( null == value ) return; - - if( LOGGER.isDebugEnabled() ) { - LOGGER.debug( "Name: " + d.getName() + ", Value: " + value ); - } - - Perl5Util re = new Perl5Util(); - if (!re.match("/^\\s*\\w*\\s*$/", value)) { - d.invalidate(); - d.addError("Please enter a single word"); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/util/Attributes.java b/ccm-core/src/main/java/com/arsdigita/bebop/util/Attributes.java deleted file mode 100755 index 192a0caa2..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/util/Attributes.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.util; - -import com.arsdigita.util.Assert; -import com.arsdigita.util.Lockable; - -import java.util.Map; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Collection; - -/** - * This class represents a set of key-value pairs, for use in - * extending the XML attributes of Bebop components. - * - * @version $Id: Attributes.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class Attributes implements Lockable, Cloneable { - - /** - * Map of attributes. - */ - private HashMap m_attributes; - - private boolean m_locked; - - /** - * Creates an Attributes object. - */ - public Attributes() { - m_attributes = new HashMap(); - m_locked = false; - } - - /** - * Clone the attributes. The clone is not locked and has its own set of - * attributes and values. - * @post ! ((Attributes) return).isLocked() - */ - public Object clone() throws CloneNotSupportedException { - Attributes result = (Attributes) super.clone(); - result.m_attributes = (HashMap) m_attributes.clone(); - result.m_locked = false; - return result; - } - - /** - *

Sets an arbitrary attribute for inclusion in the HTML tags that - * compose element. For standard attributes in the HTML 4.0 - * specification, use of this method has the same effect as the - * specific mutator method provided for each attribute.

- * - *

Setting an attribute name to null - * removes it.

- * - * @param name The name of the attribute - * @param value The value to assign the named attribute - */ - public void setAttribute(String name, String value) { - Assert.isUnlocked(this); - name = name.toLowerCase(); - m_attributes.put(name, value); - } - - /** - * Return the value of an attribute. - * - * @pre name != null - * - * @param name the name of the attribute - * @return the value set previously with - * {@link #setAttribute setAttribute} - */ - public String getAttribute(String name) { - return (String) m_attributes.get(name.toLowerCase()); - } - - /** - * Return a collection of all of the attribute keys represented. - * This, along with {@link #getAttribute(String name)} allows - * you to iterate through all of the attributes. All elements - * of the Collection are Strings - */ - public Collection getAttributeKeys() { - return m_attributes.keySet(); - } - - - /** - * Copy all attributes into the given DOM Element. This will - * override any preexisting Element attributes of the same names. - */ - public void exportAttributes(com.arsdigita.xml.Element target) { - Iterator attributesIterator = m_attributes.entrySet().iterator(); - - while (attributesIterator.hasNext()) { - Map.Entry entry = (Map.Entry) attributesIterator.next(); - - if (entry.getValue() != null) { - target.addAttribute((String) entry.getKey(), - (String) entry.getValue()); - } - } - } - - public void lock() { - m_locked = true; - } - - public final boolean isLocked() { - return m_locked; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/util/BebopConstants.java b/ccm-core/src/main/java/com/arsdigita/bebop/util/BebopConstants.java deleted file mode 100755 index b75834720..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/util/BebopConstants.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.util; - -/** - * An interface that contains all the Bebop constants that are used by Bebop - * components in generating the output XML. - * - * @author Jim Parsons - * @version $Id: BebopConstants.java 1224 2006-06-18 22:28:30Z apevec $ - */ -public interface BebopConstants { - - String BEBOP_CHECKBOXGROUP = "bebop:checkboxGroup"; - String BEBOP_CHECKBOX = "bebop:checkbox"; - String BEBOP_DATE = "bebop:date"; - String BEBOP_DATETIME = "bebop:datetime"; - String BEBOP_TIME = "bebop:time"; - String BEBOP_MULTISELECT = "bebop:multiSelect"; - String BEBOP_OPTION = "bebop:option"; - String BEBOP_RADIOGROUP = "bebop:radioGroup"; - String BEBOP_RADIO = "bebop:radio"; - String BEBOP_SELECT = "bebop:select"; - String BEBOP_TEXTAREA = "bebop:textarea"; - String BEBOP_DHTMLEDITOR = "bebop:dhtmleditor"; - String BEBOP_FCKEDITOR = "bebop:fckeditor"; - String BEBOP_XINHAEDITOR = "bebop:xinha"; - String BEBOP_CCMEDITOR = "bebop:ccmeditor"; - String BEBOP_TINYMCE_EDITOR = "bebop:tinymce"; - String BEBOP_FORMWIDGET = "bebop:formWidget"; - String BEBOP_FORMERRORS = "bebop:formErrors"; - String BEBOP_PORTAL = "bebop:portal"; - String BEBOP_PORTLET = "bebop:portlet"; - String BEBOP_BOXPANEL = "bebop:boxPanel"; - String BEBOP_CELL = "bebop:cell"; - String BEBOP_COLUMNPANEL = "bebop:columnPanel"; - String BEBOP_GRIDPANEL = "bebop:gridPanel"; - String BEBOP_BORDER = "bebop:cell"; - String BEBOP_PAD = "bebop:pad"; - String BEBOP_PADFRAME = "bebop:padFrame"; - String BEBOP_PANELROW = "bebop:panelRow"; - String BEBOP_LIST = "bebop:list"; - String BEBOP_TABLE = "bebop:table"; - String BEBOP_TABLEBODY = "bebop:tbody"; - String BEBOP_TABLEROW = "bebop:trow"; - String BEBOP_SEG_PANEL = "bebop:segmentedPanel"; - String BEBOP_SEGMENT = "bebop:segment"; - String BEBOP_SEG_BODY = "bebop:segmentBody"; - String BEBOP_SEG_HEADER = "bebop:segmentHeader"; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/util/Color.java b/ccm-core/src/main/java/com/arsdigita/bebop/util/Color.java deleted file mode 100755 index 10a649323..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/util/Color.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.util; - -/** - *

A class for Bebop color parameters.

- * - *
- * private Page buildSomePage() {
- *     Page page = new Page("Some Page");
- *
- *     Label label = new Label("Some Text");
- *
- *     // Make the label text green.
- *     label.setColor(new Color(0,255,0));
- *
- *     // Here's another way of doing the same thing.
- *     label.setColor(Color.green);
- *
- *     page.add(label);
- *
- *     page.lock();
- *
- *     return page;
- * }
- * 
- * - * @author Jim Parsons - * @version $Id: Color.java 287 2005-02-22 00:29:02Z sskracic $ - * @deprecated without replacement. Bebop must never directly specify design - * properties but semantic properties. tjhe theme engine - * decides about the design and the display! - */ -public class Color { - - private int m_red = 255; - private int m_green = 255; - private int m_blue = 255; - - /** An instance of the color black. */ - public static final Color black = new Color(0,0,0); - - /** An instance of the color blue. */ - public static final Color blue = new Color(0,0,255); - - /** An instance of the color cyan. */ - public static final Color cyan = new Color(0,255,255); - - /** An instance of the color darkGray. */ - public static final Color darkGray = new Color(169,169,169); - - /** An instance of the color gray. */ - public static final Color gray = new Color(128,128,128); - - /** An instance of the color green. */ - public static final Color green = new Color(0,128,0); - - /** An instance of the color lightGray. */ - public static final Color lightGray = new Color(211,211,211); - - /** An instance of the color magenta. */ - public static final Color magenta = new Color(255,0,255); - - /** An instance of the color orange. */ - public static final Color orange = new Color(255,165,0); - - /** An instance of the color pink. */ - public static final Color pink = new Color(255,192,203); - - /** An instance of the color red. */ - public static final Color red = new Color(255,0,0); - - /** An instance of the color white. */ - public static final Color white = new Color(255,255,255); - - /** An instance of the color yellow. */ - public static final Color yellow = new Color(255,255,0); - - /** An instance of the color nobukoBlue, an exotic medium torquoise. */ - public static final Color nobukoBlue = new Color(72,209,204); - - /** - * Make a color from the constituents red, green, and blue. Each - * color argument is an integer in the range of 0 to 255. - * - * @param red the amount of red. Must be an int in the range of 0 to 255. - * @param green the amount of green. Must be an int in the range of 0 to - * 255. - * @param blue the amount of blue. Must be an int in the range of 0 to 255. - * @deprecated without replacement. Bebop must never directly specify design - * properties but semantic properties. tjhe theme engine - * decides about the design and the display! - */ - public Color(int redValue, int greenValue, int blueValue) { - if (redValue >= 0 && redValue < 256) { - m_red = redValue; - } - - if (greenValue >= 0 && greenValue < 256) { - m_green = greenValue; - } - - if (blueValue >= 0 && blueValue < 256) { - m_blue = blueValue; - } - } - - /** - * Make a color from the constituents red, green, and blue. Each - * color argument is a float in the range of 0 to 1. - * - * @param red the amount of red. Must be a float in the range of 0 to 1. - * @param green the amount of green. Must be a float in the range of 0 to - * 1. - * @param blue the amount of blue. Must be a float in the range of 0 to 1. - */ - public Color(float redValue, float greenValue, float blueValue) { - if (redValue >= 0.0f && redValue <= 1.0f) { - m_red = (int)(255 * redValue); - } - - if (greenValue >= 0.0f && greenValue <= 1.0f) { - m_green = (int)(255 * greenValue); - } - - if(blueValue >= 0.0f && blueValue <= 1.0f) { - m_blue = (int)(255 * blueValue); - } - } - - /** - * Return a string with hex values padded out two places with a - * leading 0. - * - * @return a string representing this color. - */ - public String toString() { - String result, redString, greenString, blueString; - - if (m_red < 16) { - redString = "0" + Integer.toHexString(m_red); - } else { - redString = Integer.toHexString(m_red); - } - - if (m_green < 16) { - greenString = "0" + Integer.toHexString(m_green); - } else { - greenString = Integer.toHexString(m_green); - } - - if (m_blue < 16) { - blueString = "0" + Integer.toHexString(m_blue); - } else { - blueString = Integer.toHexString(m_blue); - } - - result = redString + greenString + blueString; - - return result; - } - - /** - * Produce an HTML hex-based representation of this color. - * - * @return an HTML hex color. - */ - public String toHTMLString() { - String result = "#" + this.toString(); - - return result; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/util/GlobalizationUtil.java b/ccm-core/src/main/java/com/arsdigita/bebop/util/GlobalizationUtil.java deleted file mode 100755 index e0458a410..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/util/GlobalizationUtil.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.util; - -import com.arsdigita.globalization.Globalized; -import com.arsdigita.globalization.GlobalizedMessage; - -/** - * Compilation of methods to simplify the handling of globalizing keys. - * Basically it adds the name of package's resource bundle files to the - * globalize methods and forwards to GlobalizedMessage, shortening the - * method invocation in the various application classes. - * - * @version $Revision: #6 $ $Date: 2004/08/16 $ - */ -public class GlobalizationUtil implements Globalized { - - /** Name of Java resource files to handle CMS's globalisation. */ - private static final String BUNDLE_NAME = "com.arsdigita.bebop.BebopResources"; - - /** - * Returns a globalized message using the package specific bundle, - * provided by BUNDLE_NAME. - * @param key - * @return - */ - public static GlobalizedMessage globalize(String key) { - return new GlobalizedMessage(key, BUNDLE_NAME); - } - - /** - * Returns a globalized message object, using the package specific bundle, - * as specified by BUNDLE_NAME. Also takes in an Object[] of arguments to - * interpolate into the retrieved message using the MessageFormat class - * (i.e. {0}, {1},... for adding variable strings). - * @param key - * @param args - * @return new instance of a globalized message - */ - public static GlobalizedMessage globalize(String key, Object[] args) { - return new GlobalizedMessage(key, BUNDLE_NAME, args); - - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/util/PanelConstraints.java b/ccm-core/src/main/java/com/arsdigita/bebop/util/PanelConstraints.java deleted file mode 100644 index 5657d652c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/util/PanelConstraints.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2014 Peter Boy, University of Bremen. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ - -package com.arsdigita.bebop.util; - -/** - * An interface that contains positional constraints used by the panel classes - * (BoxPanel, ColumnPanel and GridPanel) in generating the output XML. - * - * Used by some other classes as well which have to position box elements (e.g. - * c.ad.bebop.form.ImageSubmit) - * - * @author Peter Boy (pb@zes.uni-bremen.de) - * @version $Id: PanelConstraints.java 1224 2014-06-18 22:28:30Z $ - */ -public interface PanelConstraints { - - /** - * Left-align a component. - */ - public static final int LEFT = 1 ; // << 0; - - /** - * Center a component. - */ - public static final int CENTER = 1 << 1; - - /** - * Right-align a component. - */ - public static final int RIGHT = 1 << 2; - - /** - * Align the top of a component. - */ - public static final int TOP = 1 << 3; - - /** - * Align the middle of a component. - */ - public static final int MIDDLE = 1 << 4; - - /** - * Align the bottom of a component. - */ - public static final int BOTTOM = 1 << 5; - - /** - * Lay out a component across the full width of the panel. - */ - public static final int FULL_WIDTH = 1 << 6; - - /** - * Insert the child component assuming it is printed in a table with the - * same number of columns. - */ - public static final int INSERT = 1 << 7; - - /** - * Constant for specifying ABSMIDDLE alignment of this image input. See the - * - * W3C HTML 4.01 Specification for a description of this attribute. - */ - public static final int ABSMIDDLE = 1 << 8; - - /** - * Constant for specifying ABSBOTTOM alignment of this image input. See the - * - * W3C HTML 4.01 Specification for a description of this attribute. - */ - public static final int ABSBOTTOM = 1 << 9; - - /** - * Constant for specifying ABSBOTTOM alignment of this image input. See the - * - * W3C HTML 4.01 Specification for a description of this attribute. - */ - public static final int TEXTTOP = 1 << 10; - - /** - * Constant for specifying ABSBOTTOM alignment of this image input. See the - * - * W3C HTML 4.01 Specification for a description of this attribute. - */ - public static final int BASELINE = 1 << 11; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/util/SequentialMap.java b/ccm-core/src/main/java/com/arsdigita/bebop/util/SequentialMap.java deleted file mode 100755 index 489b94f7d..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/util/SequentialMap.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.util; - -/** - * A map that keeps its entries in a fixed sequence. All iterators returned - * by this class, for example by entrySet().iterator(), are - * guaranteed to return the entries in the order in which they were put in - * the map. This implementation allows null for both the key - * or the associated value for a map entry. - * - *

- * Almost all of the map operations, for example {@link #get get} or {@link - * #containsKey containsKey} require time linear in the size of the map, - * making this map only suitable for small map sizes. - * - * @author David Lutterkort - * @version $Id: SequentialMap.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class SequentialMap extends com.arsdigita.util.SequentialMap { - - - /** - * Creates an empty SequentialMap. - */ - public SequentialMap() { - super(); - } - - /** - * Find an entry with the given key. key may be null. - * - *

- * Requires time linear in the size of the map - * - * @param key the key to find - * @return the index with key key or -1 if no such entry - * exists. - */ - public int findKey(Object key) { - return indexOf(key); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/util/Size.java b/ccm-core/src/main/java/com/arsdigita/bebop/util/Size.java deleted file mode 100755 index 176d90c4f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/util/Size.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.util; - -/** - *

A class for Bebop size parameters.

- * - *
- * private Page buildSomePage() {
- *     Page page = new Page("Some Page");
- *
- *     // Put a 10-pixel margin around the contents of this page.
- *     page.setMargin(new Size(10));
- *
- *     // Or, instead, put a 10% margin around it.
- *     page.setMargin(new Size(10, UNIT_PERCENT));
- *
- *     page.lock();
- *
- *     return page;
- * }
- * 
- * - * @author Justin Ross - * @author Jim Parsons - * @author Christian - * Brechbühler - * @version $Id: Size.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class Size { - - private float m_scalar; - private String m_unitAbbreviation = ""; - - /** - * Constant for describing sizes in pixels. - */ - public static final int UNIT_PIXEL = 1; - - /** - * Constant for describing a component in terms of percent size - * relative to its container. - */ - public static final int UNIT_PERCENT = 2; - - /** - * Construct a new Size. Classes extending Size should call super - * with the abbreviation of their unit. - * - * @param scalar a simple magnitude. Note that this value may - * be negative. - * @param unitAbbreviation an unit abbreviation for use when the - * size is printed. - * @pre unitAbbreviation != null - */ - protected Size(float scalar, String unitAbbreviation) { - m_scalar = scalar; - m_unitAbbreviation = unitAbbreviation; - } - - /** - * Construct a new Size in pixels. - * - * @param numPixels a simple magnitude. Note that this value may - * be negative. - */ - public Size(int numPixels) { - this((float)(numPixels), ""); - } - - /** - * Construct a new Size using the type indicated in unitEnum. - * unitEnum is any of the UNIT_* constants defined in this class. - * - * @param scalar a simple magnitude. Note that this value may be - * negative. - * @param unitEnum a unit type. - */ - public Size(float scalar, int unitEnum) { - m_scalar = scalar; - - if (unitEnum == UNIT_PIXEL) { - m_unitAbbreviation = ""; - } else if (unitEnum == UNIT_PERCENT) { - m_unitAbbreviation = "%"; - } else { - throw new IllegalArgumentException - ("Bad argument for unitEnum in Size constructor."); - } - } - - /** - * Return the size as a string. This string will be used in - * writing the style attributes of Bebop XML. - * - * @return this Size as a string for inclusion in XML. - * @post return != null */ - public String toString() { - String sizeAsString = Float.toString(m_scalar) + m_unitAbbreviation; - - return sizeAsString; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/util/Traversal.java b/ccm-core/src/main/java/com/arsdigita/bebop/util/Traversal.java deleted file mode 100755 index 915e98d8a..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/util/Traversal.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.bebop.util; - -import java.util.Iterator; -import java.util.Set; -import java.util.HashSet; - -import com.arsdigita.bebop.Component; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - *

- * - *

A utility class for walking down a tree of Bebop components and - * performing some work on each one.

- * - *

Uses a filter to perform the action only on certain components. - * This filter may be used to skip only individual components or entire - * subtrees. The default filter matches all components.

- * - */ -public abstract class Traversal { - - private static final Logger LOGGER = LogManager.getLogger(Traversal.class); - - /** - * If test returns PERFORM_ACTION, - * then the action is performed on the component and its children. - * (This is the default.) - */ - public final static int PERFORM_ACTION = 0; - - /** - * If test returns SKIP_COMPONENT, - * then the current component is skipped but its descendants are still - * traversed. - */ - public final static int SKIP_COMPONENT = 1; - - /** - * If test returns SKIP_SUBTREE, - * then the current component and all of its descendants are skipped. - */ - public final static int SKIP_SUBTREE = 2; - - - private Set m_visiting = null; - - { - if (LOGGER.isDebugEnabled()) { - m_visiting = new HashSet(); - } - } - - /** - * Defines the action to be performed on each node. Users of this - * class should override this method with behavior for their - * particular domain. - * - * @param c the component on which to perform this action. - */ - protected abstract void act(Component c); - - /** - * Invoke {@link #act} on this component, and then do the same for - * each of its children for which the supplied - * test condition is true. - * - * @param c the component on which to call {@link #act}. */ - public void preorder(Component c) { - if (LOGGER.isDebugEnabled() && m_visiting.contains(c)) { - LOGGER.debug("Cycle detected at component " + c + - "; visiting nodes: " + m_visiting); - throw new IllegalStateException - ("Component " + c + " is part of a cycle"); - } - - LOGGER.debug("---"); - LOGGER.debug("Current component: '{}'", c); - LOGGER.debug("Visiting: {}", m_visiting); - - //s_log.debug("preorder called for component " + c.toString()); - - int flag = test(c); - - if (flag == PERFORM_ACTION) { - act(c); - } - - if (flag != SKIP_SUBTREE) { - if (LOGGER.isDebugEnabled()) { - m_visiting.add(c); - } - - for (Iterator i = c.children(); i.hasNext(); ) { - final Component component = (Component) i.next(); - LOGGER.debug("Calling preorder for component '{}'...", - component); - LOGGER.debug("---"); - preorder (component); - } - } - - if (LOGGER.isDebugEnabled()) { - m_visiting.remove(c); - } - } - - /** - * The default component test returns PERFORM_ACTION - * to act on all components in the tree. Override this method - * to supply your own component test. - * @param c the component to test - * @return by default returns PERFORM_ACTION on all - * components. - */ - protected int test(Component c) { - return PERFORM_ACTION; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/bebop/util/package.html b/ccm-core/src/main/java/com/arsdigita/bebop/util/package.html deleted file mode 100755 index bbd73a730..000000000 --- a/ccm-core/src/main/java/com/arsdigita/bebop/util/package.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - Bebop Utilities - - - -

- -Utility classes that are used throughout Bebop. - -

- - - diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/AbortRequestSignal.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/AbortRequestSignal.java deleted file mode 100644 index 4c45bce01..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/AbortRequestSignal.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -/** - * When thrown, this throwable will percolate up the call stack to - * the top level to abort all processing of this request. The top - * level (BaseDispatcherServlet) will treat it as a normal request - * and try to commit the transaction - */ - -public class AbortRequestSignal extends Error { - - // extending error is a bit of a misnomer but it's what - // we want: an unchecked exception that won't get caught - // by catch (Exception). -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/AccessDeniedException.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/AccessDeniedException.java deleted file mode 100644 index 5a12afb87..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/AccessDeniedException.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import javax.servlet.http.HttpServletRequest; - - -/** - * AccessDeniedException is the runtime exception that is thrown - * whenever the current user does not have access to the requested resources. - * - * @author Michael Pih - * @version $Id$ - */ -public class AccessDeniedException extends RuntimeException { - - - public final static String ACCESS_DENIED = - "com.arsdigita.cms.dispatcher.AccessDeniedException"; - - - // The default error detail message. - private final static String ERROR_MSG = "Access Denied"; - - // The URL where the AccessDeniedException is thrown. - private String m_url; - - - /** - * Constructs an AccessDeniedException with the default detail message. - */ - public AccessDeniedException() { - this(ERROR_MSG); - } - - /** - * Constructs an AccessDeniedException with the specified detail message. - * - * @param msg The error detail message - */ - public AccessDeniedException(String msg) { - super(msg); - - // Try and fetch the current request URL. - HttpServletRequest request = DispatcherHelper.getRequest(); - if ( request != null ) { - m_url = DispatcherHelper.getRequest().getRequestURI(); - request.setAttribute(ACCESS_DENIED, m_url); - } else { - m_url = null; - } - } - - /** - * Fetches the URL where the AccessDeniedException originated. - * - * @return The original URL - */ - public String getOriginalURL() { - return m_url; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/BaseDispatcherServlet.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/BaseDispatcherServlet.java deleted file mode 100755 index 4d84008b0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/BaseDispatcherServlet.java +++ /dev/null @@ -1,643 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import com.arsdigita.util.StringUtils; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.web.RedirectSignal; -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; -import java.util.Vector; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * Contains functions common to all entry-point dispatcher servlets in the core. - * - * Any dispatcher that is the first in its chain to handle an HTTP request must - * also be a servlet and should extend this class. - * - *

- * You do not need to extend this class unless your dispatcher is also - * a servlet and is mounted in web.xml. In any given ACS installation, you - * generally only have one servlet that is mounted through web.xml, and that is - * usually the com.arsdigita.sitenode.SiteNodeDispatcher, mapped to - * URL "/". - * - *

- * When a request comes in: - * - *

  • first we try to serve a concrete file that matches the URL (for - * example, if the URL is /dir/image.gif, try to serve $docroot/dir/image.gif) - * - *
  • if the URL has no extension we assume it is a virtual directory. if there - * is no trailing slash, redirect to URL + "/". - * - *
  • if the URL has no extension and a trailing slash, it is treated as a - * directory. If the directory exists as a concrete directory on disk, and has a - * welcome file (index.*) then serve as a directory by forwarding to the - * "default" servlet. - * - *
  • if there is no concrete match for the URL on disk, we set up a - * RequestContext object that acts as a request wrapper storing metadata about - * the request; and call the dispatch method. - * - *
- * - * @author Bill Schneider - * @author Jens Pelzetter - * $ - */ -public abstract class BaseDispatcherServlet extends HttpServlet - implements Dispatcher, DispatcherConstants { - - private static final Logger LOGGER = LogManager.getLogger( - BaseDispatcherServlet.class); - private final static int NOT_FOUND = 0; - private final static int STATIC_FILE = 1; - private final static int JSP_FILE = 2; - private final static String WEB_XML_22_PUBLIC_ID - = "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"; - private final static String WEB_XML_23_PUBLIC_ID - = "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"; - /** - * We use a Vector here instead of another collection because Vector is - * synchronised. - */ - private static Vector s_listenerList = new Vector(); - /** - * list of active requests - */ - private static Vector s_activeList = new Vector(); - private static final long serialVersionUID = 7349556332411247334L; - - static { - LOGGER.debug("Static initalizer starting..."); - // Add the basic request listeners. - - BaseDispatcherServlet.addRequestListener(new RequestListener() { - - public void requestStarted(RequestEvent re) { - DispatcherHelper.setRequest(re.getRequest()); - } - - public void requestFinished(RequestEvent re) { - // We could do this: - // DispatcherHelper.setRequest(null); - // but some later RequestListener might want to access - // the request or session. So we'll just let the - // DispatcherHelper hang on to one stale - // HttpServletRequest (per thread). The reference will - // be overwritten on the next request, so we keep only - // a small amount of garbage. - } - - }); - - BaseDispatcherServlet.addRequestListener(new RequestListener() { - - public void requestStarted(RequestEvent re) { - - } - - public void requestFinished(RequestEvent re) { - - } - - }); - - - LOGGER.debug("Static initalizer finished."); - } - - private List m_welcomeFiles = new ArrayList(); - - /** - * Reads web.xml to get the configured list of welcome files. We have to - * read web.xml ourselves because there is no public API to get this - * information from the ServletContext. - */ - public synchronized void init() throws ServletException { - super.init(); - try { - File file = new File(getServletContext().getRealPath( - "/WEB-INF/web.xml")); - // all we care about is the welcome-file-list element - SAXParserFactory spf = SAXParserFactory - .newInstance(); - spf.setValidating(false); - SAXParser parser = spf.newSAXParser(); - parser.parse(file, new WebXMLReader()); - } catch (SAXException se) { - LOGGER.error("error in init", se); - } catch (ParserConfigurationException pce) { - LOGGER.error("error in init", pce); - } catch (IOException ioe) { - LOGGER.error("error in init", ioe); - } - // default to index.jsp, index.html - if (m_welcomeFiles.isEmpty()) { - m_welcomeFiles.add("index.jsp"); - m_welcomeFiles.add("index.html"); - } - getServletContext().setAttribute(WELCOME_FILES, m_welcomeFiles); - } - - /** - * Adds a request listener to this. - * - * @param rl the RequestListener to add to the listener list - */ - public static void addRequestListener(RequestListener rl) { - s_listenerList.add(rl); - } - - /** - * A placeholder method for performing user authentication during request - * processing. Subclasses should override this method. - * - * @param req the current servlet request object - * @param req the current servlet response object - * @param req the current request context - * - * @return the updated request context (which may be the same as the context - * context parameter). - * - * @throws com.arsdigita.dispatcher.RedirectException if the dispatcher - * should redirect the - * client to the page - * contained in the - * exception - * - */ - protected abstract RequestContext authenticateUser(HttpServletRequest req, - HttpServletResponse resp, - RequestContext ctx) - throws RedirectException; - - /** - * Called directly by the servlet container when this servlet is invoked - * from a URL request. First tries to dispatch the URL to a concrete file on - * disk, if there is a matching file. Otherwise, sets up an initial - * RequestContext, tries to identify the user/session, parses form - * variables, and wraps the request object to handle multipart forms if - * necessary. Calls the dispatch method as declared in - * implementing subclasses. - * - * @param req the servlet request - * @param resp the servlet response - * - * @throws javax.servlet.ServletException re-thrown when - * dispatch throws an - * exception - * @throws java.io.IOException re-thrown when - * dispatch throws an - * IOException - */ - public void service(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("\n*** *** *** *** *** ***\n" - + "Servicing request for URL '" + req - .getRequestURI() - + "'\n" + "*** *** *** *** *** ***"); - } - - boolean reentrant = true; - RequestContext reqCtx = DispatcherHelper.getRequestContext(req); - boolean finishedNormal = false; - - // there are two types of re-entrancy we need to consider: - // * forwarded requests specified by the application, - // where the forwarded request is picked up by a subclass - // of BDS. (e.g., SND forwards /foo/bar to - // /packages/foo/www/bar.jsp) - // * a secondary request, forwarded by the CONTAINER in response - // to an exception thrown from service(), after the first request - // completes - // - // in the FIRST case, we need to guard against running - // the start/end listeners again. in the SECOND case, - // we need to treat this like a new request so that - // we open a transaction, etc. for serving the error page. - // wrap entire rest of method in try-catch block. that way if - // some method call throws ServletException or IOException, - // implicitly exiting the service method, we'll still be able - // to free up the database connection in a finally. - // STEP #1: if no extension, treat as directory; - // make sure we have a trailing slash. and redirect - //otherwise. - DispatcherHelper.setRequest(req); - - if (trailingSlashRedirect(req, resp)) { - // note, this is OUTSIDE of try/catch/finally. No - // listeners of any kind are run! - return; - } - - // STEP #2: try to serve concrete static file, if one exists. - // (defer serving concrete JSPs until after listeners run) - int concreteFileType = concreteFileType(req); - if (concreteFileType == STATIC_FILE) { - LOGGER.debug("Setting world cache headers on static file"); - DispatcherHelper.cacheForWorld(resp); - DispatcherHelper.forwardRequestByName("default", req, resp, - getServletContext()); - return; - } - - try { - if (req.getAttribute(REENTRANCE_ATTRIBUTE) == null) { - reentrant = false; - - waitForPreviousRequestToFinish(req); - - // need an identifier for this particular request - String requestId = Thread.currentThread().getName() + "|" - + System. - currentTimeMillis(); - req.setAttribute(REENTRANCE_ATTRIBUTE, requestId); - s_activeList.add(requestId); - - try { - // first time through: - // do all actions that must be done initially on hit - StartRequestRecord srr = startRequest(req, resp); - reqCtx = srr.m_reqCtx; - req = srr.m_req; - LOGGER.debug("After startRequest the request is now " + req); - } catch (RedirectException re) { - final String url = re.getRedirectURL(); - - resp.sendRedirect(resp.encodeRedirectURL(url)); - - return; - } - } else { - req = DispatcherHelper.maybeWrapRequest(req); - - // if we're handling a secondary request for an - // error, but we haven't run the finally ... block - // on the primary request yet (this happens when - // sendError is called explicitly, as opposed to when - // the container calls sendError(500...) in response - // to an exception rethrown here) we DON'T run the - // request listeners. BUT we need to clear - // the request context. - if (req.getAttribute(ERROR_REQUEST_ATTRIBUTE) != null - || req.getAttribute(JSP_EXCEPTION_ATTRIBUTE) != null) { - // reset URL boookeeping but don't wipe out - // whole object since it might actually be a - // KernelRequestContext with user / session info - if (reqCtx instanceof InitialRequestContext) { - ((InitialRequestContext) reqCtx). - initializeURLFromRequest(req, true); - } - } - } - // finally, call dispatch - finishedNormal = false; - - if (concreteFileType == JSP_FILE) { - // STEP #3: dispatch to a concrete JSP if we have a matching - // one - DispatcherHelper.forwardRequestByName("jsp", req, resp); - } else { - // STEP #4: if no concrete file exists, dispatch to - // implementing class - dispatch(req, resp, reqCtx); - } - - // if JSP already dispatched to error page, no exception - // will be thrown. have to check for attribute manually. - if (req.getAttribute(JSP_EXCEPTION_ATTRIBUTE) == null) { - finishedNormal = true; - } - } catch (AbortRequestSignal ars) { - // treat this as a normal end of request and - // try to commit - finishedNormal = true; - } catch (IOException ioe) { - LOGGER.error("error in BaseDispatcherServlet", ioe); - throw ioe; - } catch (ServletException se) { - // SDM #140226, improved handling of - // ServletException.getRootCause() - Throwable t = se; - Throwable rootError; - do { - rootError = t; - t = ((ServletException) t).getRootCause(); - } while (t instanceof ServletException); - if (t != null) { - rootError = t; - } - // handle this in case AbortRequestSignal got wrapped - // accidentally--e.g., inside a JSP. - if (rootError != null - && (rootError instanceof AbortRequestSignal)) { - finishedNormal = true; - } else if (rootError != null - && (rootError instanceof RedirectSignal)) { - LOGGER.debug("rethrowing RedirectSignal", rootError); - throw (RedirectSignal) rootError; - } else { - LOGGER.error("error in BaseDispatcherServlet", rootError); - throw new ServletException(rootError); - } - } catch (RuntimeException re) { - LOGGER.error("error in BaseDispatcherServlet", re); - throw re; - } catch (Error error) { - LOGGER.error("error in BaseDispatcherServlet", error); - throw error; - } finally { - if (!reentrant) { - // run the request listener events - fireFinishedListener( - new RequestEvent(req, resp, reqCtx, false, - finishedNormal)); - // at this point, clear the attribute so - // a secondary request will work - // and remove the request from the list of currently-active - // requests - Object requestId = req.getAttribute(REENTRANCE_ATTRIBUTE); - synchronized (s_activeList) { - s_activeList.remove(requestId); - s_activeList.notifyAll(); - } - req.removeAttribute(REENTRANCE_ATTRIBUTE); - } - } - } - - /** - * Processes a request when it is first handled by the servlet. This method - * runs exactly once for each request, even if the request is reentrant. - * - * @return a tuple containing the updated request context and the request - * - * @throws com.arsdigita.dispatcher.RedirectException if the dispatcher - * should redirect the - * client to the page - * contained in the - * exception - * - */ - private StartRequestRecord startRequest(HttpServletRequest req, - HttpServletResponse resp) - throws RedirectException, IOException, ServletException { - - // turn multipart request into wrapped request - // to make up for servlet 2.2 brokenness - req = DispatcherHelper.maybeWrapRequest(req); - - RequestContext reqCtx = new InitialRequestContext(req, - getServletContext()); - - // run the request listener events - fireStartListener(new RequestEvent(req, resp, reqCtx, true)); - - // Authenticate user AFTER request listeners because authentication - // may need to use the database connection (opened by a listener). - // Allow subclass to update request context with user info. - reqCtx = authenticateUser(req, resp, reqCtx); - - // save the request context in the request - DispatcherHelper.setRequestContext(req, reqCtx); - - return new StartRequestRecord(reqCtx, req); - } - - /** - * Fires all finished listeners. Collects and logs errors to ensure that all - * finished listeners run. - * - * @param evt the current RequestEvent to broadcast to all event listeners - */ - protected void fireFinishedListener(RequestEvent evt) { - for (int i = 0; i < s_listenerList.size(); i++) { - try { - ((RequestListener) s_listenerList.get(i)).requestFinished(evt); - } catch (Exception e) { - LOGGER.error("Error running request finished listener " - + s_listenerList. - get(i) + " (#" + i + ")", e); - } - } - } - - /** - * Fires all start listeners. Does not collect and log errors. - * Instead, a runtime failure in a start listener will inhibit further - * servicing of the request. - * - * @param evt the current RequestEvent to broadcast to all event listeners - */ - protected void fireStartListener(RequestEvent evt) { - for (int i = 0; i < s_listenerList.size(); i++) { - ((RequestListener) s_listenerList.get(i)).requestStarted(evt); - } - } - - /** - * Kludge for returning a typed 2-tuple. - */ - private class StartRequestRecord { - - RequestContext m_reqCtx; - HttpServletRequest m_req; - - public StartRequestRecord(RequestContext rc, HttpServletRequest req) { - m_reqCtx = rc; - m_req = req; - } - - } - - private void waitForPreviousRequestToFinish(HttpServletRequest req) { - // handle concurrence -- serialize requests from the same - // user agent, so that you can't follow a link/redirect from - // a request until the request's transaction has committed - - // get identifier from previous request, if there is any - HttpSession sess = req.getSession(false); - if (sess != null) { - Object sema = sess.getAttribute(REDIRECT_SEMAPHORE); - if (sema != null) { - while (s_activeList.indexOf(sema) != -1) { - try { - synchronized (s_activeList) { - s_activeList.wait(); - } - } catch (InterruptedException ie) { - } - } - sess.removeAttribute(REDIRECT_SEMAPHORE); - } - } - } - - /** - * helper method: if the current request URL points to a concrete file under - * the webapp root, returns STATIC_FILE or JSP_FILE indicating the type of - * file. returns NOT_FOUND if no corresponding concrete file exists. - * - *

- * If the concrete file is a directory, then we require that the directory - * have a welcome file like index.*; this prevents us from serving directory - * listings. For directories we return STATIC_FILE if there is a welcome - * file, otherwise return NOT_FOUND. - * - * @return STATIC_FILE if the current request points to a concrete static - * file (non-JSP) or a directory that has a welcome file. returns - * JSP_FILE if it corresponds to a dynamic JSP file. returns - * NOT_FOUND otherwise. - */ - private int concreteFileType(HttpServletRequest req) - throws ServletException, IOException { - - String path = DispatcherHelper.getCurrentResourcePath(req); - - ServletContext sctx = this.getServletContext(); - File realFile = new File(sctx.getRealPath(path)); - if (realFile.exists() && (!realFile.isDirectory() || hasWelcomeFile( - realFile))) { - // yup. Go there, bypass the site map. - // we have a concrete file so no forwarding to - // rewrite the request URL is necessary. - if (realFile.getName().endsWith(".jsp")) { - return JSP_FILE; - } else { - return STATIC_FILE; - } - } else { - return NOT_FOUND; - } - } - - /** - * returns true if dir is a directory and has a welcome file like index.*. - * - * @pre dir.isDirectory() - */ - private boolean hasWelcomeFile(File dir) { - if (!dir.isDirectory()) { - throw new IllegalArgumentException("dir must be a directory"); - } - String[] files = dir.list(); - for (int i = 0; i < files.length; i++) { - if (m_welcomeFiles.indexOf(files[i]) >= 0) { - return true; - } - } - return false; - } - - private boolean trailingSlashRedirect(HttpServletRequest req, - HttpServletResponse resp) - throws IOException { - String path = DispatcherHelper.getCurrentResourcePath(req); - // first, see if we have an extension - if (path.lastIndexOf(".") <= path.lastIndexOf("/")) { - // maybe no extension. check if there's a trailing - // slash already. - if (!path.endsWith("/")) { - // no trailing slash - String targetURL = req.getContextPath() + path + "/"; - String query = req.getQueryString(); - if (query != null && query.length() > 0) { - targetURL += "?" + query; - } - resp.sendRedirect(resp.encodeRedirectURL(targetURL)); - return true; - } - } - return false; - } - - /** - * SAX content handler class to pick welcome-file-list out of web.xml - */ - private class WebXMLReader extends DefaultHandler { - - StringBuffer m_buffer = new StringBuffer(); - - @Override - public InputSource resolveEntity(String publicId, String systemId) - throws SAXException { - // we don't want to read the web.xml dtd - if (WEB_XML_22_PUBLIC_ID.equals(publicId) - || WEB_XML_23_PUBLIC_ID.equals(publicId)) { - StringReader reader = new StringReader(" "); - return new InputSource(reader); - } else { - try { - return super.resolveEntity(publicId, systemId); - } catch (Exception e) { - if (e instanceof SAXException) { - throw (SAXException) e; - } else { - throw new UncheckedWrapperException("Resolve Error", e); - } - } - } - } - - @Override - public void characters(char[] ch, int start, int len) { - for (int i = 0; i < len; i++) { - m_buffer.append(ch[start + i]); - } - } - - @Override - public void endElement(String uri, - String localName, - String qname) { - if (qname.equals("welcome-file-list")) { - String[] welcomeFiles = StringUtils.split(m_buffer.toString(), - ','); - for (int i = 0; i < welcomeFiles.length; i++) { - m_welcomeFiles.add(welcomeFiles[i].trim()); - } - } - m_buffer = new StringBuffer(); - } - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/ChainedDispatcher.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/ChainedDispatcher.java deleted file mode 100755 index 60d1aec5d..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/ChainedDispatcher.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * This interface defines - * a dispatcher that is intended to be chained together with other dispatchers. - * The functional difference between ChainedDispatcher and Dispatcher is - * that a ChainedDispatcher's chainedDispatch() method can return a status - * code to indicate that it was successful or unsuccessful in finding - * a resource to dispatch to. - * - *

This interface is mainly used in conjunction with - * DispatcherChain, a general-purpose dispatcher that joins many - * different ChainedDispatchers together in a chain of different - * URL-to-resource mappings; if one cannot find a resource, the next - * one is tried. This is useful when an application has several - * different methods to find a resource for a URL and each method can - * be separated into a re-usable module. - * - *

For example, suppose an application resolves a URL to a resource - * like this: - * - *

    - *
  • try to serve a file /templates/$site-node/$page.jsp - *
  • if not found, try to serve a Bebop Page mapped to $page - *
  • if not found, try to serve a file /packages/$key/www/$page.jsp - *
  • if not found, serve "not found" page - *
- * - * If we implement each stage as a separate ChainedDispatcher, then we - * can mix and match these dispatch stages in any number of - * applications. - * - * @author Bill Schneider - * @version $Id$ - */ - -public interface ChainedDispatcher { - - public final static int DISPATCH_BREAK = 0; - public final static int DISPATCH_CONTINUE = 1; - - /** - * Dispatch this request and return a status code if - * successful. - * - * @param request The servlet request object - * @param response the servlet response object - * @param actx The request context - * @return DISPATCH_BREAK if dispatch successful, DISPATCH_CONTINUE - * if no resource found (try next dispatcher in chain) - */ - public int chainedDispatch(HttpServletRequest request, - HttpServletResponse response, - RequestContext actx) - throws IOException, ServletException; -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/DirectoryListingException.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/DirectoryListingException.java deleted file mode 100644 index a30d47629..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/DirectoryListingException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -/** - * Trown when a directory exists without an index file. Intended to signal that - * code that lists the contents of a directory may want to be triggered. - * - * @author Bill Schneider - * @version $Id$ - */ - -public class DirectoryListingException extends Exception { - - public DirectoryListingException() { - super(); - } - - public DirectoryListingException(String s) { - super(s); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/Dispatcher.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/Dispatcher.java deleted file mode 100755 index d8758bb89..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/Dispatcher.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Defines a single dispatch - * method that allows programmers to pass extra context information - * around in a RequestContext object. Thus, when dispatcher A chains - * to dispatcher B, dispatcher B can determine what portion of the - * original request URL it needs to work with and what portion just - * made dispatcher A chain to dispatcher B. This context information - * allows a dispatcher to dynamically hand off a request to another - * dispatcher. - * - * A dispatcher is an entry point for a package. Each package - * defines a dispatcher, which brokers out requests within the package. - * The dispatcher for a package can dispatch requests to other packages. - * Multiple packages can share the same dispatcher type but - * not instance.

- * - * If a dispatcher object for a package also implements HttpServlet, - * then it is also an entry point for the entire web application. - * - * @author Bill Schneider - * @version $Id$ - */ - -public interface Dispatcher { - - - /** - * Dispatches this request. - * @param request the servlet request object - * @param response the servlet response object - * @param actx the request context - * @exception java.io.IOException may be thrown by the dispatcher - * to indicate an I/O error - * @exception javax.servlet.ServletException may be thrown by the - * dispatcher to propagate a generic error to its caller - */ - public void dispatch(HttpServletRequest request, - HttpServletResponse response, - RequestContext actx) - throws IOException, ServletException; -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherChain.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherChain.java deleted file mode 100755 index c1c6caff0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherChain.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import java.io.IOException; -import java.util.Iterator; -import java.util.LinkedList; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Generic implementation - * of "try this URL-resource mapping; if nothing found try ..." - * pattern. This is useful for packages whose URL-to-resource mapping - * is a composition of many separate, reusable mappings. The goal is to - * reduce multi-branched, hard-coded if-else blocks. - * - *

This class makes it easier to break up dispatchers into a series - * of smaller, re-usable, but not totally self-contained classes whose - * dispatch method tries to find a resource according to its mapping, - * and serves it if it finds one. If it can't find a resource, it - * returns a failure - * status code (DISPATCHER_CONTINUE) and the DispatcherChain tries the - * next dispatcher in the sequence. - * - *

The dispatcher chain tries each dispatcher in the dispatcher - * chain successively in the order in which they were added to the chain. - * - * @version $Id$ - */ -public class DispatcherChain implements Dispatcher { - - private LinkedList m_dispatcherChain = new LinkedList(); - - /** - * Dispatches to the dispatcher chain. Tries each dispatcher - * in the sequence, in which they were added, and breaks out of - * the loop when either one dispatcher returns DISPATCH_BREAK or - * a dispatcher throws an exception. - * - * @param req the current servlet request - * @param resp the current servlet response object - * @param ctx the current RequestContext object - * @throws java.io.IOException re-thrown when a dispatcher in the - * chain throws an IOException. - * @throws javax.servlet.ServletException re-thrown when a dispatcher - * in the chain throws a ServletException. - */ - public void dispatch(HttpServletRequest req, - HttpServletResponse resp, - RequestContext ctx) - throws ServletException, IOException { - - Iterator iter = null; - synchronized(this) { - iter = m_dispatcherChain.iterator(); - } - // already have a new iterator instance, so don't need - // to synchronize rest of proc. - while (iter.hasNext()) { - ChainedDispatcher disp = (ChainedDispatcher)iter.next(); - int status = disp.chainedDispatch(req, resp, ctx); - if (status == ChainedDispatcher.DISPATCH_BREAK) { - break; - } - } - } - - /** - * Adds a dispatcher to the dispatcher chain. Dispatchers are - * executed in the order they are added to the chain, so this - * dispatcher will be executed after all the dispatchers that - * were previously added to the chain and before all the - * dispatchers that haven't yet been added to the chain. - * @param cd the dispatcher to add - */ - public synchronized void addChainedDispatcher(ChainedDispatcher cd) { - m_dispatcherChain.addLast(cd); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherConfig.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherConfig.java deleted file mode 100755 index 2a4e44466..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherConfig.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.dispatcher; - -import java.util.Objects; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.Configuration; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.configuration.Setting; - -/** - * - * @author Jens Pelzetter - */ -@Configuration( - descBundle = "com.arsdigita.dispatcher.DispatcherConfig", - descKey = "description", - titleKey = "title" -) -public final class DispatcherConfig { - - @Setting( - descKey = "cachingActive.desc", - labelKey = "cachingActive.label" - ) - private Boolean cachingActive = true; - - @Setting( - descKey = "defaultExpiry.desc", - labelKey = "defaultExpiry.label" - ) - private Integer defaultExpiry = 259200; - - @Setting( - descKey = "staticUrlPrefix.desc", - labelKey = "statusUrlPrefix.label" - ) - private String staticUrlPrefix = "/STATICII/"; - - @Setting( - descKey = "defaultPageClass.desc", - labelKey = "defaultPageClass.label" - ) - private String defaultPageClass = "com.arsdigita.bebop.Page"; - - public static DispatcherConfig getConfig() { - final ConfigurationManager confManager = CdiUtil.createCdiUtil() - .findBean(ConfigurationManager.class); - return confManager.findConfiguration(DispatcherConfig.class); - } - - public Boolean isCachingActive() { - return cachingActive; - } - - public void setCachingActive(final Boolean cachingActive) { - this.cachingActive = cachingActive; - } - - public Integer getDefaultExpiry() { - return defaultExpiry; - } - - public void setDefaultExpiry(final Integer defaultExpiry) { - this.defaultExpiry = defaultExpiry; - } - - public String getStaticUrlPrefix() { - return staticUrlPrefix; - } - - public void setStaticUrlPrefix(final String staticUrlPrefix) { - this.staticUrlPrefix = staticUrlPrefix; - } - - public String getDefaultPageClass() { - return defaultPageClass; - } - - public void setDefaultPageClass(final String defaultPageClass) { - this.defaultPageClass = defaultPageClass; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 97 * hash + Objects.hashCode(cachingActive); - hash = 97 * hash + Objects.hashCode(defaultExpiry); - hash = 97 * hash + Objects.hashCode(staticUrlPrefix); - hash = 97 * hash + Objects.hashCode(defaultPageClass); - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof DispatcherConfig)) { - return false; - } - final DispatcherConfig other = (DispatcherConfig) obj; - if (!Objects.equals(staticUrlPrefix, other.getStaticUrlPrefix())) { - return false; - } - if (!Objects.equals(defaultPageClass, other.getDefaultPageClass())) { - return false; - } - if (!Objects.equals(cachingActive, other.isCachingActive())) { - return false; - } - return Objects.equals(defaultExpiry, other.getDefaultExpiry()); - } - - @Override - public String toString() { - return String.format("%s{ " - + "cachingActive = %b, " - + "defaultExpiry = %d, " - + "staticUrlPrefix = \"%s\", " - + "defaultPageClass = \"%s\"" - + " }", - super.toString(), - cachingActive, - defaultExpiry, - staticUrlPrefix, - defaultPageClass); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherConstants.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherConstants.java deleted file mode 100644 index f693d9488..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherConstants.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -interface DispatcherConstants { - - /** - * Attribute name for the Throwable object saved when a JSP - * handles an error with the errorPage directive. - */ - final static String JSP_EXCEPTION_ATTRIBUTE = - "javax.servlet.jsp.jspException"; - - /** - * Attribute name for the URI that caused an error - * when the servlet container forwards to an error page. - */ - final static String ERROR_REQUEST_ATTRIBUTE = - "javax.servlet.error.request_uri"; - - /** - * Attribute name to indicate that the dispatcher is within - * a request--that is, request start listeners have run but - * request end listeners haven't yet. - */ - final static String REENTRANCE_ATTRIBUTE = - "com.arsdigita.dispatcher.inside_request"; - - /** - * The attribute name for an included resource URI after - * a servlet include (nesting). - */ - final static String INCLUDE_URI = - "javax.servlet.include.request_uri"; - - /** - * The attribute where we store the current RequestContext - * object. - */ - final static String REQUEST_CONTEXT_ATTR = - "com.arsdigita.dispatcher.RequestContext"; - - /** - * The attribute where we store the original HttpServletRequest - * object when we need to wrap the servlet request. - */ - final static String ORIGINAL_REQUEST_ATTR = - "com.arsdigita.dispatcher.OriginalRequest"; - - /** - * The attribute where we store the wrapped servlet request - * object when we need to restore the original request object - * for a forward/include. - */ - final static String WRAPPED_REQUEST_ATTR = - "com.arsdigita.dispatcher.WrappedRequest"; - - /** - * The session attribute where we store an identifier for the - * previous request that made a redirect. This prohibits us from - * following a redirect until after the request that generated the - * redirect commits its transaction. - */ - final static String REDIRECT_SEMAPHORE = - "com.arsdigita.dispatcher.redirect_semaphore"; - - /** - * The application attribute (in ServletContext) where we store the - * list of welcome files from web.xml. - */ - final static String WELCOME_FILES = - "com.arsdigita.dispatcher.welcomefiles"; - - - final static String DISPATCHER_PREFIX_ATTR = - "com.arsdigita.dispatcher.DispatcherPrefix"; -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherHelper.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherHelper.java deleted file mode 100644 index 327b47d90..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/DispatcherHelper.java +++ /dev/null @@ -1,1277 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -//import com.arsdigita.kernel.Kernel; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.util.Assert; -import com.arsdigita.util.ParameterProvider; -import com.arsdigita.util.StringUtils; -import com.arsdigita.util.URLRewriter; -import com.arsdigita.web.ParameterMap; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.web.URL; -import com.arsdigita.web.Web; - -import org.apache.logging.log4j.LogManager; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Enumeration; -import java.util.Locale; -import java.util.Set; -import java.util.TimeZone; - -import javax.mail.MessagingException; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.jsp.PageContext; - -import org.apache.logging.log4j.Logger; -import org.apache.shiro.web.servlet.ShiroHttpServletRequest; - -import java.net.URLEncoder; - -import javax.servlet.ServletRequestWrapper; - -/** - * Class static helper methods for request dispatching. Contains various - * generally useful procedural abstractions. - * - * @author Bill Schneider - * @since 4.5 - */ -public final class DispatcherHelper implements DispatcherConstants { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int hte runtime environment and - * set com.arsdigita.dispatcher.DispatcherHelper=DEBUG by uncommenting or - * adding the line. - */ - private static final Logger LOGGER = LogManager.getLogger( - DispatcherHelper.class); - private static String s_webappCtx; - private static String s_staticURL; - private static boolean s_cachingActive; - private static int s_defaultExpiry; - public static SimpleDateFormat rfc1123_formatter; - private static boolean initialized = false; - - static void init() { - if (initialized) { - return; - } - - rfc1123_formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", - Locale.ROOT); - rfc1123_formatter.setTimeZone(TimeZone.getTimeZone("GMT")); - - s_staticURL = DispatcherConfig.getConfig().getStaticUrlPrefix(); - s_defaultExpiry = DispatcherConfig.getConfig().getDefaultExpiry(); - s_cachingActive = DispatcherConfig.getConfig().isCachingActive(); - - initialized = true; - } - - /** - * The current HttpServletRequest. - */ - private static final ThreadLocal s_request = new ThreadLocal(); - - /** - * null constructor, private so no one can instantiate! - */ - private DispatcherHelper() { - } - - /** - * Return default cache expiry. Default is specified in the configuration - * file (registry) if not otherweise set. - * - * @return default cache expiry - */ - public static int getDefaultCacheExpiry() { - init(); - return s_defaultExpiry; - } - - static void setDefaultCacheExpiry(int expiry) { - init(); - s_defaultExpiry = expiry; - } - - public static boolean isCachingActive() { - init(); - return s_cachingActive; - } - - static void setCachingActive(boolean status) { - init(); - s_cachingActive = status; - } - - /** - * Returns the URL path (relative to the webapp root) for the current - * (calling) resource. This works around the quirk that, if servlet A - * includes servlet B, calling getRequestURI() in B returns "A" and not "B". - * - * @param req - * - * @return the URL path (relative to the webapp root) for the currently - * executing resource. - */ - public static String getCurrentResourcePath(HttpServletRequest req) { - String attr = (String) req.getAttribute(INCLUDE_URI); - String str; - if (attr == null) { - str = req.getRequestURI(); - if (str.indexOf("?") > -1) { - str = str.substring(0, str.indexOf("?")); - } - } else { - str = attr; - } - int startIndex = req.getContextPath().length(); - str = str.substring(startIndex); - // fix-up URL -- sometimes broken (Tomcat serving error pages) - if (str.startsWith("//")) { - str = str.substring(1); - } - return str; - } - - /** - * Gets the application context from the request attributes. - * - * @param req - * - * @return the application context from the request attributes. - */ - public static RequestContext getRequestContext(HttpServletRequest req) { - return (RequestContext) req.getAttribute(REQUEST_CONTEXT_ATTR); - } - - public static RequestContext getRequestContext() { - return (RequestContext) getRequest().getAttribute(REQUEST_CONTEXT_ATTR); - } - - public static String getDispatcherPrefix(HttpServletRequest req) { - final HttpServletRequest request; - if (req instanceof ShiroHttpServletRequest) { - request = (HttpServletRequest) ((ServletRequestWrapper) req) - .getRequest(); - } else { - request = req; - } - return (String) request.getAttribute(DISPATCHER_PREFIX_ATTR); - } - - public static void setDispatcherPrefix(HttpServletRequest req, - String val) { - req.setAttribute(DISPATCHER_PREFIX_ATTR, val); - } - - /** - * Sets the current request context as a request attribute for later - * retrieval. - * - * @param req the current request object - * @param ac the current request context - * - * @post DispatcherHelper.getRequestContext(req) == ac - */ - public static void setRequestContext(HttpServletRequest req, - RequestContext ac) { - req.setAttribute(REQUEST_CONTEXT_ATTR, ac); - } - - private static void forwardHelper(javax.servlet.RequestDispatcher rd, - HttpServletRequest req, - HttpServletResponse resp) - throws ServletException, IOException { - - Object attr = req.getAttribute(INCLUDE_URI); - - // Yes this does mean we're throwing away any POSTed - // data from a MultipartHttpServletRequest, but we've - // got to do what Servlet API specs say. Specifically - // tomcat assumes it gets back the original request :( - // So we need to go through hoops to 'unrestore' the - // original request when it comes back to us in just - // a second... - // Of course if the request disappears off to a 3rd - // party servlet we're screwed - req = restoreOriginalRequest(req); - LOGGER.debug("Forwarding the request object " + req); - if (attr != null) { - rd.include(req, resp); - req.setAttribute(INCLUDE_URI, attr); - } else { - try { - rd.forward(req, resp); - } catch (IllegalStateException e) { - rd.include(req, resp); - } - } - } - - /** - * Forwards the request from this resource to another resource at the - * servlet-container level. This is a wrapper for - * javax.servlet.RequestDispatcher and is intended to hide the fact that you - * can't "forward" a request once you've done an "include" in it. - * - * @param path the URL of the resource, relative to the webapp root. For - * example, if you request a JSP page with /context/foo/bar, you - * would call this method with path == /foo/bar. - * @param req the current request - * @param resp the current response - * @param sctx the current servlet context - * - * @exception java.io.IOException may be propagated from target - * resource - * @exception javax.servlet.ServletException may be propagated from target - * resource - */ - public static void forwardRequestByPath(String path, - HttpServletRequest req, - HttpServletResponse resp, - ServletContext sctx) - throws IOException, ServletException { - RequestDispatcher rd = sctx.getRequestDispatcher(path); - forwardHelper(rd, req, resp); - } - - /** - * Equivalent to forwardRequestByPath(path, req, resp, - * DispatcherHelper.getRequestContext(req).getServletContext()). - * - * @param path - * @param req - * @param resp - * - * @throws java.io.IOException - * @throws javax.servlet.ServletException - */ - public static void forwardRequestByPath(String path, - HttpServletRequest req, - HttpServletResponse resp) - throws IOException, ServletException { - ServletContext sctx = DispatcherHelper.getRequestContext(req) - .getServletContext(); - forwardRequestByPath(path, req, resp, sctx); - } - - /** - * Forwards the request from this resource to another resource at the JSP - * container level. This is a wrapper for PageContext.forward - * and PageContext.include and is intended to transparently - * switch between "forward" and "include" depending on whether or not an - * include has already been done on the request. - * - * @param path the URL of the resource, relative to the webapp root. - * For example, if you request a JSP page with - * /context/foo/bar, you would call this method with path - * == /foo/bar. - * - * @param pageContext the JSP page context - * - * @exception java.io.IOException may be propagated from target - * resource - * @exception javax.servlet.ServletException may be propagated from target - * resource - */ - public static void forwardRequestByPath(String path, - PageContext pageContext) - throws IOException, ServletException { - - ServletRequest req = pageContext.getRequest(); - Object attr = req.getAttribute(INCLUDE_URI); - // restore original request if we're using the wrapped - // multipart request here - if (attr != null) { - pageContext.include(path); - req.setAttribute(INCLUDE_URI, attr); - } else { - try { - pageContext.forward(path); - } catch (IllegalStateException e) { - pageContext.include(path); - } - } - } - - /** - * Forwards the request from this resource to a servlet resource (named in - * server.xml) at the servlet-container level. This is a wrapper for - * javax.servlet.RequestDispatcher and is intended to hide the fact that you - * can't "forward" a request once you've done an "include" in it. - * - * @param name the named servlet to forward to - * @param req the current request - * @param resp the current response - * @param sctx the current servlet context - * - * @exception java.io.IOException may be propagated from target - * resource - * @exception javax.servlet.ServletException may be propagated from target - * resource - */ - public static void forwardRequestByName(String name, - HttpServletRequest req, - HttpServletResponse resp, - ServletContext sctx) - throws IOException, ServletException { - RequestDispatcher rd = sctx.getNamedDispatcher(name); - forwardHelper(rd, req, resp); - } - - /** - * Equivalent to forwardRequestByName(name, req, resp, - * DispatcherHelper.getRequestContext(req).getServletContext()). - * - * @param name - * @param req - * @param resp - * - * @throws java.io.IOException - * @throws javax.servlet.ServletException - */ - public static void forwardRequestByName(String name, - HttpServletRequest req, - HttpServletResponse resp) - throws IOException, ServletException { - ServletContext sc = getRequestContext(req).getServletContext(); - forwardRequestByName(name, req, resp, sc); - } - - /** - * Given the name of a resource in the file system that is missing an - * extension, picks an extension that matches. Serves a file with a - * .jsp extension first, if available. Otherwise picks any file - * that matches. For directories, it tacks on the "index" filename plus the - * extension. - * - * Unsupported - * - * @param abstractFile the extensionless file - * @param actx the current application context - * - * @return a filename suffix (".jsp", "index.html", etc.) such that - * (abstractFile.getAbsolutePath() + suffix) is a valid file in the - * filesystem - * - * @exception com.arsdigita.dispatcher.RedirectException if the - * requested - * file is a - * directory - * and the - * original - * request URL - * does not - * end with a - * trailing - * slash. - * @exception java.io.FileNotFoundException if no - * matching - * file - * exists. - * @throws com.arsdigita.dispatcher.DirectoryListingException - * @deprecated abstract URLs are no longer supported. Use extensions when - * your file on disk has an extension. - */ - public static String resolveAbstractFile(File abstractFile, - RequestContext actx) - throws RedirectException, DirectoryListingException, - java.io.FileNotFoundException { - LOGGER.debug("Resolving abstract file"); - - File dirToSearch = null; - String fStr = abstractFile.getAbsolutePath(); - int lastSlash = fStr.lastIndexOf(File.separatorChar); - String filenameStub = fStr.substring(lastSlash + 1); - - boolean indexPage = false; - if (abstractFile.isDirectory()) { - if (!actx.getOriginalURL().endsWith("/")) { - // redirect to prevent confused browser - throw new RedirectException(actx.getOriginalURL() + "/"); - } - dirToSearch = abstractFile; - filenameStub = "index"; - indexPage = true; - } else if (abstractFile.exists()) { - // file exists and is not a directory; don't resolve any - // further - return ""; - } else { - dirToSearch = new File(abstractFile.getParent()); - } - - File filesInDir[] = dirToSearch.listFiles(); - - final String extensionSearchList[] = {".jsp"}; - - if (filesInDir != null) { - for (String searchExtension : extensionSearchList) { //1.5 enhanced loop - File possibleFile = new File(dirToSearch, - filenameStub + searchExtension); - for (int i = 0; i < filesInDir.length; i++) { - if (filesInDir[i].equals(possibleFile)) { - return (indexPage ? File.separator + "index" : "") - + searchExtension; - } - } - } - - // no preferential matches, so just match whatever - // we can - // note that if we have an index page, we really don't - // want to match the abstractFile itself because it's - // a directory; we want to match the "index.*" file - // IN this directory. - File abstractFileIndex = new File(abstractFile, "index"); - for (int i = 0; i < filesInDir.length; i++) { - String fidStr = filesInDir[i].getPath(); - int lastDot = fidStr.lastIndexOf("."); - if (lastDot == -1) { - // Match must have extension - // perfect match already tested - continue; - } - File possibleStub = new File(fidStr.substring(0, lastDot)); - if (indexPage && abstractFileIndex.equals(possibleStub)) { - return "index" + fidStr.substring(lastDot); - } else if (abstractFile.equals(possibleStub)) { - return fidStr.substring(lastDot); - } - } - } - if (!abstractFile.isDirectory()) { - // couldn't find anything and not a directory, so throw - // An exception - throw new FileNotFoundException(abstractFile.getAbsolutePath()); - } else { - // we have a directory, no index file, maybe serve - // as a directory listing? - throw new DirectoryListingException(abstractFile.getAbsolutePath()); - } - } - - /** - * If the given servlet request is wrapped in one of our own classes, - * returns the original (unwrapped) request object and stores a reference to - * the request wrapper in the request attributes of the returned request. - * Otherwise just returns the request object. - * - * @param req the servlet request - * - * @return the original servlet request object, as created by the servlet - * container. This can be used as a parameter for forward(). - */ - public static HttpServletRequest restoreOriginalRequest( - HttpServletRequest req) { - if (req instanceof MultipartHttpServletRequest) { - HttpServletRequest oldReq = (HttpServletRequest) req.getAttribute( - ORIGINAL_REQUEST_ATTR); - oldReq.setAttribute(WRAPPED_REQUEST_ATTR, req); - req = oldReq; - } - return req; - } - - /** - * If we've stored a reference to a request wrapper as a request attribute - * to the current servlet request, returns the wrapper object. Otherwise, - * returns the request object. - * - * @param req the current servlet request - * - * @return the previously created wrapper around the current servlet - * request, if any; otherwise returns the request object. - */ - public static HttpServletRequest restoreRequestWrapper( - HttpServletRequest req) { - // switch back wrapped request if we're forwarded - // from somewhere else. - Object maybeWrappedReq = req.getAttribute(WRAPPED_REQUEST_ATTR); - if (maybeWrappedReq != null - && !(req instanceof MultipartHttpServletRequest)) { - req = (HttpServletRequest) maybeWrappedReq; - } - return req; - } - - /** - * This method will optionally wrap the request if it is a multipart POST, - * or restore the original wrapper if it was already wrapped. - * - * @param sreq - * - * @return - * - * @throws java.io.IOException - * @throws javax.servlet.ServletException - */ - public static HttpServletRequest maybeWrapRequest(HttpServletRequest sreq) - throws IOException, ServletException { - final String type = sreq.getContentType(); - - if (sreq.getMethod().toUpperCase().equals("POST") - && type != null - && type.toLowerCase().startsWith("multipart")) { - final HttpServletRequest orig = sreq; - - final HttpServletRequest previous = DispatcherHelper - .restoreRequestWrapper(orig); - - if (previous instanceof MultipartHttpServletRequest) { - LOGGER.debug("Build new multipart request from previous " - + previous + " and current " + orig); - - MultipartHttpServletRequest previousmp - = (MultipartHttpServletRequest) previous; - - sreq = new MultipartHttpServletRequest(previousmp, - orig); - - DispatcherHelper.saveOriginalRequest(sreq, - orig); - - LOGGER.debug("The main request is now " + sreq); - } else { - LOGGER.debug( - "The request is a new multipart; wrapping the request " - + "object"); - try { - sreq = new MultipartHttpServletRequest(sreq); - } catch (MessagingException me) { - throw new ServletException(me); - } - - DispatcherHelper.saveOriginalRequest(sreq, orig); - } - } else { - LOGGER.debug("The request is not multipart; proceeding " - + "without wrapping the request"); - } - return sreq; - } - - /** - * Stores req as request attribute of oldReq. - * - * @param req the current servlet request (wrapper) - * @param oldReq the original servlet request - */ - public static void saveOriginalRequest(HttpServletRequest req, - HttpServletRequest oldReq) { - req.setAttribute(ORIGINAL_REQUEST_ATTR, oldReq); - } - - /** - * Redirects the client to the given URL without rewriting it. Delegates to - * the sendExternalRedirect method. - * - * @throws java.io.IOException - * @deprecated This method does not rewrite URLs. Use - * sendRedirect(HttpServletRequest, HttpServletResponse, String) for - * redirects within this ACS or sendExternalRedirect(HttpServletResponse, - * String) for redirects to sites outside this ACS. - * - * @param resp the current response - * @param url the destination URL for redirect - * - */ - public static void sendRedirect(HttpServletResponse resp, - String url) - throws IOException { - sendExternalRedirect(resp, url); - } - - /** - * Rewrites the given URL and redirects the client to the rewritten URL. - * This method should be used for redirects within this ACS. - * - * @param req the current request; used as a source for parameters for URL - * rewriting - * @param resp the current response - * @param url the destination URL for redirect - * - * @throws java.io.IOException - * - */ - public static void sendRedirect(HttpServletRequest req, - HttpServletResponse resp, - String url) - throws IOException { - sendExternalRedirect(resp, url); - } - - /** - * Redirects the client to the given URL without rewriting it. This method - * should be used for redirects to sites outside this ACS. - * - * @param resp the current response - * @param url the destination URL for redirect - * - * @throws java.io.IOException - * - */ - public static void sendExternalRedirect(HttpServletResponse resp, - String url) - throws IOException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Redirecting to URL '" + url + "'", new Throwable()); - } - - if (StringUtils.emptyString(url)) { - // This is a fix so that redirecting to empty string - // (i.e. index file in current directory) - // works properly when running in Apache. - // DEE 3/13/01 the original apache redirect-fix string of "?" - // has been replaced with ".", because - // IE will reload the current page if redirected to "?". - url = "."; - } - - HttpServletRequest req = getRequest(); - Object attr; - if (req != null - && (attr = req.getAttribute(REENTRANCE_ATTRIBUTE)) != null) { - req.getSession(true).setAttribute(REDIRECT_SEMAPHORE, attr); - } - - if (url.startsWith("http")) { - final int start = url.indexOf("/", url.indexOf("//") + 2); - final String path = start >= 0 ? url.substring(start) : "/"; - - if (!path.startsWith(URL.getDispatcherPath())) { - url = path; - } - } - - if (url.startsWith("/")) { - final int sep = url.indexOf('?'); - URL destination = null; - - if (sep == -1) { - destination = URL.there(req, url); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Setting destination to " + destination); - } - } else { - final ParameterMap params = ParameterMap.fromString(url - .substring(sep + 1)); - - destination = URL.there(req, url.substring(0, sep), params); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Setting destination with map to " - + destination); - } - } - throw new RedirectSignal(destination, true); - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Redirecting to URL without using URL.there. " - + "URL is " + url); - } - throw new RedirectSignal(url, true); - } - } - - /** - * Adds a ParameterProvider to the URLRewriter engine. - * ParameterProviders are used when - * encodeRedirectURL and encodeURL are called. - * They add global state parameters like the session ID (for cookieless - * login) to URLs for links and redirects. - * - * @param provider the parameter provider to add - * - * @see com.arsdigita.util.URLRewriter#addParameterProvider - * @deprecated use URLRewriter.addParameterProvider - */ - public static void addParameterProvider(ParameterProvider provider) { - URLRewriter.addParameterProvider(provider); - } - - /** - * Clears all parameter providers. - * - * @deprecated use URLRewriter#clearParameterProviders() instead - * @see com.arsdigita.util.URLRewriter#clearParameterProviders() - * - */ - public static void clearParameterProviders() { - URLRewriter.clearParameterProviders(); - } - - /** - * Returns the set of global parameter models, or the empty set if no - * provider is set. - * - * @return a set of Bebop parameter models. - * - * @deprecated use URLRewriter.getGlobalModels instead - * @see com.arsdigita.util.URLRewriter#getGlobalModels() - * - */ - public static Set getGlobalModels() { - return URLRewriter.getGlobalModels(); - } - - /** - * Returns the set of global URL parameters for the given request, or the - * empty set if no provider is set. - * - * @param req the current request - * - * @return a Set of Bebop parameter data. - * - * @deprecated use URLRewriter.getGlobalParams instead - * - */ - public static Set getGlobalParams(HttpServletRequest req) { - return URLRewriter.getGlobalParams(req); - } - - /** - * Prepares the given URL for a client link. If no providers are set, has no - * effect. - * - * @param url the target URL to prepare - * - * @return the prepared URL with global parameters added from providers - * - * @deprecated This method does not encode the servlet session ID. Use - * encodeURL(req, res, url) instead. - * - */ - public static String prepareURL(String url, HttpServletRequest req) { - return URLRewriter.prepareURL(url, req); - } - - /** - * Encodes the given URL for the client. Adds ACS global parameters and - * servlet session parameters to the URL. If the URL will be used for - * redirection, use sendRedirect(req, resp, url) instead. - * - * @param req the current request - * @param resp the current response - * @param url the target URL (for a link) to encode - * - * @return the new URL, with extra URL variables added from parameter - * providers - * - * @deprecated use URLRewriter.encodeURL instead - * @see com.arsdigita.util.URLRewriter - * - */ - public static String encodeURL(HttpServletRequest req, - HttpServletResponse resp, - String url) { - return URLRewriter.encodeURL(req, resp, url); - } - - /** - * Returns a global URL prefix for referencing static assets (images, CSS, - * etc.) on disk in href attributes. This can be on the same server - * ("/STATIC/") or a different server/port ("http://server:port/dir/"). The - * return value is guaranteed to end with a trailing slash. - * - * Usage example: - *

-     * String pathToImage = DispatcherHelper.getStaticURL() + "images/pic.gif";
-     * Image img = new Image(pathToImage);
-     * 
- * - * @return a URL prefix ending with a trailing slash. - */ - public static String getStaticURL() { - init(); - return s_staticURL; - } - - /** - * sets the global URL prefix for referencing static assets (images, CSS, - * etc.) from user-agents in href attributes. Package visibility is - * intentional. - * - * @param s the static asset URL - * - * @pre s != null - */ - static void setStaticURL(String s) { - init(); - if (s == null) { - return; - } - if (!s.endsWith("/")) { - s += "/"; - } - s_staticURL = s; - } - - /** - * sets the webapp Context using the webappContext parameter in - * enterprise.init. This is an optional parameter. If it is not specified, - * null will be used and the value of s_webappContext will be set when there - * is a request. Package visibility is intentional. - * - * @param webappCtx the webappContext specified in enterprise.init. Normally - * this wouldbe "/". - */ - static void setWebappContext(String webappCtx) { - init(); - if (webappCtx == null) { - return; - } - if (!webappCtx.startsWith("/")) { - webappCtx = "/" + webappCtx; - } - s_webappCtx = webappCtx; - LOGGER.warn("webappContext set to '" + webappCtx + "'"); - } - - /** - * Gets the webapp Context using the following procedure: - * - * 1. If there is a request, get the value from the request. 2. If there is - * no request, get the value saved from a previous request. 3. If there is - * no request or previous request, use the value specified by the - * enterprise.init webappContext parameter. 4. Lastly, return null. - * - * @return - */ - public static String getWebappContext() { - init(); - String webappCtx = null; - HttpServletRequest request = DispatcherHelper.getRequest(); - if (request != null) { - webappCtx = request.getContextPath(); - - // Safety check to make sure the webappCtx from the request - // matches the webappCtx from enterprise.init. - if (s_webappCtx != null) { - if (s_webappCtx.equals("/")) { - s_webappCtx = ""; - } - if (!s_webappCtx.equals(webappCtx)) { - LOGGER.warn( - "webappContext changed. Expected='" + s_webappCtx - + "' found='" + webappCtx - + "'.\nPerhaps the enterprise.init " - + "com.arsdigita.dispatcher.Initializer webappContext " - + "parameter is wrong."); - // Save the webappCtx from the request for future use. - s_webappCtx = webappCtx; - } - } - } else { - if (s_webappCtx != null && s_webappCtx.equals("/")) { - s_webappCtx = ""; - } - webappCtx = s_webappCtx; - } - return webappCtx; - } - - /** - * Aborts all processing of the current request and treat it as successfully - * completed. We abort the request by percolating an unchecked Error up - * through the call stack. Then the BaseDispatcherServlet.service method - * traps this and commits whatever DML has already happened on the - * transaction. - * - * @exception com.arsdigita.dispatcher.AbortRequestSignal Error thrown to - * abort current - * request - */ - public static void abortRequest() { - throw new AbortRequestSignal(); - } - - /** - * Stores the HttpServletRequest in a ThreadLocal so that it can be accessed - * globally. - * - * @param r - */ - public static void setRequest(HttpServletRequest r) { - init(); - s_request.set(r); - } - - /** - * Gets the current HttpServletRequest for this thread. - * - * @return the current HttpServletRequest for this thread. - */ - public static HttpServletRequest getRequest() { - init(); - return (HttpServletRequest) s_request.get(); - } - - /** - * ************************************************ - */ - /* !!! Danger Will Robinson!!!! */ - /* */ - /* Don't go making changes to the cache headers */ - /* without reading *and* fully understanding the */ - /* sections on caching in RFC 2616 (HTTP 1.1) */ - /* */ - /* -- Daniel Berrange */ - /** - * ************************************************ - */ - /** - * If no existing cache policy is set, then call cacheDisable to disable all - * caching of the response. - * - * @param response - */ - public static void maybeCacheDisable(HttpServletResponse response) { - if (!response.containsHeader("Cache-Control")) { - cacheDisable(response); - } - } - - /** - * Aggressively disable all caching of the response. - * - * @param response - */ - public static void cacheDisable(HttpServletResponse response) { - init(); - if (!s_cachingActive) { - return; - } - - // Assert.isTrue(!response.containsHeader("Cache-Control"), - // "Caching headers have already been set"); - // XXX Probably need to assert here if isCommitted() returns true. - // But first need to figure out what is setting Cache-Control. - if (response.containsHeader("Cache-Control")) { - LOGGER.warn("Cache-Control has already been set. Overwriting."); - } - - forceCacheDisable(response); - } - - /** - * - * @param response - */ - public static void forceCacheDisable(HttpServletResponse response) { - init(); - if (!s_cachingActive) { - return; - } - - LOGGER.info("Setting cache control to disable"); - // Aggressively defeat caching - works even for HTTP 0.9 proxies/clients! - response.setHeader("Pragma", "no-cache"); - response.setHeader("Cache-Control", "must-revalidate, no-cache"); - response.setHeader("Expires", rfc1123_formatter.format(new Date(0))); - } - - /** - * If no existing cache policy is set, then call cacheForUser to enable - * caching for a user. - * - * @param response - */ - public static void maybeCacheForUser(HttpServletResponse response) { - if (!response.containsHeader("Cache-Control")) { - cacheForUser(response); - } - } - - /** - * Allow caching of the response for this user only, as identified by the - * Cookie header. The response will expire according to the default age - * setting. - * - * @param response - */ - public static void cacheForUser(HttpServletResponse response) { - cacheForUser(response, s_defaultExpiry); - } - - /** - * If no existing cache policy is set, then call cacheForUser to enable - * caching for a user - * - * @param response - * @param maxage the max time in second until this expires - */ - public static void maybeCacheForUser(HttpServletResponse response, - int maxage) { - if (!response.containsHeader("Cache-Control")) { - cacheForUser(response, maxage); - } - } - - /** - * If no existing cache policy is set, then call cacheForUser to enable - * caching for a user - * - * @param response - * @param expiry the time at which to expire - */ - public static void maybeCacheForUser(HttpServletResponse response, - Date expiry) { - if (!response.containsHeader("Cache-Control")) { - cacheForUser(response, expiry); - } - } - - /** - * Allow caching of the response for this user only, as identified by the - * Cookie header. The response will expire in 'age' seconds time. - * - * @param response - * @param maxage the max life of the response in seconds - */ - public static void cacheForUser(HttpServletResponse response, - int maxage) { - init(); - if (!s_cachingActive) { - return; - } - - Assert.isTrue(!response.containsHeader("Cache-Control"), - "Caching headers have already been set"); - - LOGGER.info("Setting cache control to user"); - - // For HTTP/1.1 user agents, we tell them only cache - // for the original person making the request - response - .setHeader("Last-Modified", rfc1123_formatter.format(new Date())); - response.setHeader("Cache-Control", "private, max-age=" + maxage); - - // NB. THis line is delibrately *NOT* using the actual expiry date - // supplied. HTTP/1.0 caches don't understand Cache-Control - // so we use a expiry time in the past to prevent accidental - // caching. HTTP/1.1 compliant caches still work, since they will - // look at the above max-age header in preference to Expires... - response.setHeader("Expires", rfc1123_formatter.format(new Date(0))); - } - - /** - * Allowing caching of the response for this user only. The response will - * expire at time given in the expiry parameter - * - * @param response - * @param expiry time at which to expire - */ - public static void cacheForUser(HttpServletResponse response, - Date expiry) { - cacheForUser(response, - (int) ((expiry.getTime() - (new Date()).getTime()) / 1000l)); - } - - /** - * If no existing cache policy is set, then call cacheForUser to enable - * caching for the world. The response expiry will take the default age - * setting. - * - * @param response - */ - public static void maybeCacheForWorld(HttpServletResponse response) { - if (!response.containsHeader("Cache-Control")) { - cacheForWorld(response); - } - } - - /** - * Allow caching of this response for anyone in the world. The response take - * the default expiry time. - * - * @param response - */ - public static void cacheForWorld(HttpServletResponse response) { - cacheForWorld(response, s_defaultExpiry); - } - - /** - * If no existing cache policy is set, then call cacheForUser to enable - * caching for the world. - * - * @param response - * @param maxage the time in seconds until expiry - */ - public static void maybeCacheForWorld(HttpServletResponse response, - int maxage) { - if (!response.containsHeader("Cache-Control")) { - cacheForWorld(response, maxage); - } - } - - /** - * If no existing cache policy is set, then call cacheForUser to enable - * caching for the world. - * - * @param response - * @param expiry the time at which it will expire - */ - public static void maybeCacheForWorld(HttpServletResponse response, - Date expiry) { - if (!response.containsHeader("Cache-Control")) { - cacheForWorld(response, expiry); - } - } - - /** - * Allow caching of this response for anyone in the world. The response will - * expire at the current time plus maxage seconds. - * - * @param response - * @param maxage time in seconds until this expires - */ - public static void cacheForWorld(HttpServletResponse response, - int maxage) { - init(); - if (!s_cachingActive) { - return; - } - - Assert.isTrue(!response.containsHeader("Cache-Control"), - "Caching headers have already been set"); - - Calendar expires = Calendar.getInstance(); - expires.add(Calendar.SECOND, maxage); - - LOGGER.info("Setting cache control to world"); - response.setHeader("Cache-Control", "public, max-age=" + maxage); - response.setHeader("Expires", - rfc1123_formatter.format(expires.getTime())); - response.setHeader("Last-Modified", - rfc1123_formatter.format(new Date())); - } - - /** - * Allow caching of this response for anyone in the world. THe response will - * expire at the time given. - * - * @param response - * @param expiry - */ - public static void cacheForWorld(HttpServletResponse response, - Date expiry) { - cacheForWorld(response, (int) ((expiry.getTime() - (new Date()) - .getTime()) / 1000l)); - } - - /** - * This method returns the best matching locale for the request. In contrast - * to the other methods available this one will also respect the - * supported_languages config entry. - * - * @return The negotiated locale - */ - public static Locale getNegotiatedLocale() { - final KernelConfig kernelConfig = KernelConfig.getConfig(); - - // Set the preferedLocale to the default locale (first entry in the - // config parameter list) - Locale preferedLocale - = new Locale(kernelConfig.getDefaultLanguage(), "", ""); - - // The ACCEPTED_LANGUAGES from the client - Enumeration locales = null; - - // Try to get the RequestContext - try { - locales = ((ServletRequest) DispatcherHelper.getRequest()) - .getLocales(); - - // For everey element in the enumerator - while (locales.hasMoreElements()) { - - // Test if the current locale is listed in the supported locales list - Locale curLocale = (Locale) locales.nextElement(); - if (kernelConfig.hasLanguage(curLocale.getLanguage())) { - preferedLocale = curLocale; - break; - } - - } - - } catch (NullPointerException ex) { - // Don't have to do anything because I want to fall back to default - // language anyway. This case should only appear during setup - } finally { - - return preferedLocale; - - } - } - - /** - * Encodes the given request into a return URL parameter. Returns - * URLencode(returnURL) where returnURL is - * returnURI?key=URLencode(val)&.... The original parameter - * values are doubly-encoded so that they are decoded appropriately. - * - * - * @param req the request to encode - * - * @return the URL-encoded parameter - * - */ - public static String encodeReturnURL(HttpServletRequest req) { - StringBuilder returnURL = new StringBuilder(100); - returnURL.append(Web.getWebContext().getRequestURL().getRequestURI()); - returnURL.append('?'); - - // convert posted parameters to URL parameters - Enumeration params = req.getParameterNames(); - boolean first = true; - while (params.hasMoreElements()) { - String key = (String) params.nextElement(); - String[] vals = req.getParameterValues(key); - for (int i = 0; i < vals.length; i++) { - if (first) { - first = false; - } else { - returnURL.append('&'); - } - returnURL.append(key); - returnURL.append('='); - returnURL.append(URLEncoder.encode(vals[i])); - } - } - - return URLEncoder.encode(returnURL.toString()); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/InitialRequestContext.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/InitialRequestContext.java deleted file mode 100644 index 4f90b1c7d..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/InitialRequestContext.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import java.util.Locale; -import java.util.ResourceBundle; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * Implements a request context for the site map application - * or for any application dispatcher that creates the first application context - * for an incoming request. - * - * @author Bill Schneider - * @since 4.5 - */ -public class InitialRequestContext implements RequestContext { - - private static final Logger LOGGER = LogManager.getLogger - (InitialRequestContext.class); - - private String m_urlSoFar; - private String m_urlRemainder; - private String m_originalUrl; - private ServletContext m_sctx; - private String m_outputType; - private Locale m_locale; - private boolean m_debugging; //These three vars are for /debug, /xml, /xsl - private boolean m_debuggingXML; - private boolean m_debuggingXSL; - - /** - * Copy constructor. Creates a new - * InitialRequestContext with identical properties - * as the parameter that. This is useful for deferred - * construction of subclass objects with the same properties. - * - * @param that a request context to copy basic properties from. - * @post this.getProcessedURLPart() == that.getProcessedURLPart() - * @post this.getRemainingURLPart() == that.getRemainingURLPart() - * @post this.getOriginalURL() == that.getOriginalURL() - * @post this.getServletContext() == that.getServletContext() - * @post this.getLocale() == that.getLocale() - **/ - protected InitialRequestContext(RequestContext that) { - this.m_urlSoFar = that.getProcessedURLPart(); - this.m_urlRemainder = that.getRemainingURLPart(); - this.m_originalUrl = that.getOriginalURL(); - this.m_sctx = that.getServletContext(); - this.m_outputType = that.getOutputType(); - this.m_locale = that.getLocale(); - this.m_debugging = that.getDebugging(); - this.m_debuggingXML = that.getDebuggingXML(); - this.m_debuggingXSL = that.getDebuggingXSL(); - } - - /** - * Constructs a new request context from the given servlet - * request. Some initial URL portion has already been handled by - * the servlet container in dispatching to our web application. - * @param request the servlet request - * @param sctx the servlet context - */ - public InitialRequestContext(HttpServletRequest request, - ServletContext sctx) { - m_sctx = sctx; - initializeURLFromRequest(request, false); - - Object obj = request.getParameter("outputType"); - if (obj != null) { - m_outputType = (String)obj; - } else { - m_outputType = "text/html"; - } - - m_locale = request.getLocale(); - } - - /** - * Initializes the URL in this request context and decomposes - * it into a part already processed (what part of the URL got - * us here already?) and the part not yet processed (what - * part will the next dispatcher in the chain use?). - * In the initial step, the only part of the URL used so far - * is the part that selects the servlet context (webapp). - */ - void initializeURLFromRequest(HttpServletRequest request, - boolean preserveOriginalURL) { - LOGGER.debug("Initializing processed and remaining URL parts."); - - String requestUrl = DispatcherHelper.getCurrentResourcePath(request); - m_urlSoFar = request.getContextPath(); - m_urlRemainder = requestUrl; - - if (LOGGER.isDebugEnabled()) { - String contextPath = request.getContextPath(); - LOGGER.debug("contextPath: " + contextPath); - } - - if (LOGGER.isDebugEnabled()) { - String servletPath = request.getServletPath(); - LOGGER.debug("servletPath: " + servletPath); - } - - if (LOGGER.isDebugEnabled()) { - String pathInfo = request.getPathInfo(); - LOGGER.debug("pathInfo: " + pathInfo); - } - - final String debugURL = "/debug"; - m_debugging = m_urlRemainder.startsWith(debugURL); // humor JTest - if (m_debugging) { - m_urlSoFar += debugURL; - m_urlRemainder = m_urlRemainder.substring(debugURL.length()); - } - - final String debugURLXML = "/xml"; - m_debuggingXML = m_urlRemainder.startsWith(debugURLXML); // humor JTest - if (m_debuggingXML) { - m_urlSoFar += debugURLXML; - m_urlRemainder = m_urlRemainder.substring(debugURLXML.length()); - } - - final String debugURLXSL = "/xsl"; - m_debuggingXSL = m_urlRemainder.startsWith(debugURLXSL); // humor JTest - if (m_debuggingXSL) { - m_urlSoFar += debugURLXSL; - m_urlRemainder = m_urlRemainder.substring(debugURLXSL.length()); - } - if (!preserveOriginalURL) { - LOGGER.debug("Overwriting original URL, since the caller did not " + - "ask to preserve it"); - m_originalUrl = m_urlSoFar + m_urlRemainder; - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Set processed URL to '" + m_urlSoFar + "'"); - LOGGER.debug("Set remaining URL to '" + m_urlRemainder + "'"); - } - } - - /** - * Returns the portion of the requested URL that was used so by far - * by all previous dispatchers in the chain. - * - * @return the portion of the requested URL that was used so by far - * by all previous dispatchers in the chain. - */ - public String getProcessedURLPart() { - return m_urlSoFar; - } - - /** - * Returns the portion of the requested URL that has not already been - * used by all previous dispatchers in the chain. - * - * @return the portion of the requested URL that has not already - * been used by all previous dispatchers in the chain. - */ - public String getRemainingURLPart() { - return m_urlRemainder; - } - - /** - * Sets the portion of the requested URL that has not already - * been processed by any previous dispatcher in the chain - * @param s the remaining unprocessed URL portion - */ - protected void setRemainingURLPart(String s) { - m_urlRemainder = s; - } - - /** - * Sets the portion of the requested URL that has already - * been processed by all the previous dispatchers in the chain. - * This allows decorating subclasses like SiteNodeRequestContext - * to mark an additional portion of the URL as processed. - * - * @param s the remaining unprocessed URL portion - */ - protected void setProcessedURLPart(String s) { - m_urlSoFar = s; - } - - public String getOriginalURL() { - return m_originalUrl; - } - - public ServletContext getServletContext() { - return m_sctx; - } - - /** - * At this point, we're not in any specific package, so just returns - * '/'. - */ - public String getPageBase() { - return "/"; - } - - /** - * @return the locale preferred by the user, as specified in the - * Accept-Language header. - */ - public Locale getLocale() { - return m_locale; - } - - public String getOutputType() { - return m_outputType; - } - - /** - * XXX Only added so that the class compiles. - */ - public ResourceBundle getResourceBundle() { - return null; - } - - public boolean getDebugging() { - return m_debugging; - } - - public boolean getDebuggingXML() { - return m_debuggingXML; - } - - public boolean getDebuggingXSL() { - return m_debuggingXSL; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/JSPApplicationDispatcher.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/JSPApplicationDispatcher.java deleted file mode 100755 index 870f61778..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/JSPApplicationDispatcher.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import java.io.File; -import java.io.IOException; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * Basic dispatcher class for dispatching URLs to JSP or - * other file-based assets (images, CSS, HTML, etc.) in the file - * system in the context of a single package's URL space. - *

- * Given an application context that contains a SiteNode, and a - * remaining URL, tries to resolve the remaining URL into a concrete file:
- * $root/packages/$key/$remaining-url
- * - * where
- * $root is the ACS webapp root
- * $key is siteNode.getPackageKey()
- * $remaining-url is given by appContext.getRemainingURLPart() - * - *

To make the URL mapping in JSPApplicationDispatcher work, you - * must map the "jsp" servlet in web.xml to whatever your entry-point - * dispatcher is (whatever servlet is mapped to the URL pattern "/"). - * Otherwise, requests for *.jsp will get picked up by the JSP - * container before any ACS dispatchers have a shot at URL mapping. - * - *

- * Example: if the application sample-app is mounted on the site nodes - * /sample1 and /sample2 then URLs will be dispatched as follows: - * - * - * - * - * - * - * - * - *
Request URL File served
/sample1/page.jsp /packages/sample-app/www/page.jsp
/sample2/image.gif /packages/sample-app/www/image.gif
/sample2/script.jsp /packages/sample-app/www/script.jsp
- * @author Bill Schneider - * @author Jens Pelzetter - */ -public class JSPApplicationDispatcher extends BaseDispatcherServlet - implements Dispatcher { - - private static final Logger LOGGER = LogManager.getLogger - (JSPApplicationDispatcher.class); - - private static JSPApplicationDispatcher s_instance = newInstance(); - private static final long serialVersionUID = 1662461509796743896L; - - /** - * Returns a new instance of a JSPApplicationDispatcher. - * @return a new JSPApplicationDispatcher. - */ - public static JSPApplicationDispatcher newInstance() { - return new JSPApplicationDispatcher(); - } - - /** - * Returns a new instance of JSPApplicationDispatcher. - * @return a JSPApplicationDispatcher object. - * @deprecated No longer returns a singleton instance. Remains - * in place for API stability. - */ - public static JSPApplicationDispatcher getInstance() { - return s_instance; - } - - // No Authentication is performed here. - protected RequestContext authenticateUser(HttpServletRequest req, - HttpServletResponse resp, - RequestContext ctx) - throws RedirectException { - return ctx; - } - - public void dispatch(HttpServletRequest req, - HttpServletResponse resp, - RequestContext actx) - throws IOException, ServletException { - - // Set the request context as a request attribute because a - // JSP page might need it, which doesn't get passed the - // request context as a parameter. - DispatcherHelper.setRequestContext(req, actx); - - ServletContext sctx = actx.getServletContext(); - String remainingURL = actx.getRemainingURLPart(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("I think the remaining URL is '" + remainingURL + "'"); - } - - // This is where we forward a request from /foo1/bar.ext or - // /foo2/bar.ext to /packages/foo/www/bar.ext the concrete - // file should then get picked up by BaseDispatcherServlet. - - String concreteURL = - actx.getPageBase() + - actx.getRemainingURLPart(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Looking for a concrete resource under the web app " + - "context at '" + concreteURL + "'"); - } - - File concreteFile = new File(sctx.getRealPath(concreteURL)); - - if (concreteFile.exists()) { - LOGGER.debug("Resource was found; forwarding"); - DispatcherHelper.setRequestContext(req, actx); - DispatcherHelper.forwardRequestByPath(concreteURL, req, resp); - } else { - LOGGER.debug("Resource not found"); - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/MultipartHttpServletRequest.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/MultipartHttpServletRequest.java deleted file mode 100644 index 9d75f5628..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/MultipartHttpServletRequest.java +++ /dev/null @@ -1,603 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.mail.MessagingException; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletInputStream; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; - -import com.arsdigita.globalization.Globalization; -import com.arsdigita.util.UncheckedWrapperException; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Collection; - -import javax.servlet.AsyncContext; -import javax.servlet.DispatcherType; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpUpgradeHandler; -import javax.servlet.http.Part; - -/** - * MultipartHttpServletRequest provides multipart/form-data handling - * capabilities to facilitate file uploads for servlets. This request object - * parses the HTTP request with MIME type "multipart" and places the encoded - * object in a stream. - * - * @author Karl Goldstein - * @author Michael Pih - * @author Uday Mathur - * @since 4.5 - */ -public class MultipartHttpServletRequest implements HttpServletRequest { - - private static final Logger LOGGER = LogManager.getLogger( - MultipartHttpServletRequest.class); - - private HttpServletRequest m_request; - private Map m_parameters = null; - - /** - * Create a multipart servlet request object and parse the request. - * - * @param request The request - * - * @throws javax.mail.MessagingException - * @throws java.io.IOException - */ - public MultipartHttpServletRequest(HttpServletRequest request) - throws MessagingException, IOException { - m_request = request; - m_parameters = Collections.synchronizedMap(new HashMap()); - parseMultipartRequest(m_request); - } - - /** - * Create a multipart servlet request object and parse the request. - * - * @param original - * @param current - */ - public MultipartHttpServletRequest(MultipartHttpServletRequest original, - HttpServletRequest current) { - m_request = current; - m_parameters = original.m_parameters; - } - - /** - * - * @param name - * - * @return - */ - @Override - public Object getAttribute(String name) { - return m_request.getAttribute(name); - } - - /** - * - * @return - */ - @Override - public Enumeration getAttributeNames() { - return m_request.getAttributeNames(); - } - - /** - * - * @param name - * - * @return - */ - @Override - public String getParameter(String name) { - String[] values = (String[]) m_parameters.get(name); - - if (values == null || values.length == 0) { - return null; - } else { - return values[0]; - } - } - - /** - * - * @return - */ - @Override - public Map getParameterMap() { - return m_parameters; - } - - /** - * - * @return - */ - @Override - public Enumeration getParameterNames() { - return Collections.enumeration(m_parameters.keySet()); - } - - /** - * - * @param name - * - * @return - */ - public String getFileName(String name) { - return getParameter(name); - } - - /** - * - * @param name - * - * @return - */ - public File getFile(String name) { - String path = getParameter(name + ".tmpfile"); - - if (path == null) { - return null; - } else { - return new File(path); - } - } - - /** - * - * @param name - * - * @return - */ - @Override - public String[] getParameterValues(String name) { - return (String[]) m_parameters.get(name); - } - - // Additional methods for HttpServletRequest - /** - * - * @return - */ - @Override - public String getAuthType() { - return m_request.getAuthType(); - } - - /** - * - * @return - */ - @Override - public Cookie[] getCookies() { - return m_request.getCookies(); - } - - public long getDateHeader(String name) { - return m_request.getDateHeader(name); - } - - public String getHeader(String name) { - return m_request.getHeader(name); - } - - public Enumeration getHeaders(String name) { - return m_request.getHeaders(name); - } - - public Enumeration getHeaderNames() { - return m_request.getHeaderNames(); - } - - public int getIntHeader(String name) { - return m_request.getIntHeader(name); - } - - public String getMethod() { - return m_request.getMethod(); - } - - public String getPathInfo() { - return m_request.getPathInfo(); - } - - public String getPathTranslated() { - return m_request.getPathTranslated(); - } - - public String getContextPath() { - return m_request.getContextPath(); - } - - public String getQueryString() { - return m_request.getQueryString(); - } - - public String getRemoteUser() { - return m_request.getRemoteUser(); - } - - public boolean isUserInRole(String role) { - return m_request.isUserInRole(role); - } - - public java.security.Principal getUserPrincipal() { - return m_request.getUserPrincipal(); - } - - public String getRequestedSessionId() { - return m_request.getRequestedSessionId(); - } - - public String getRequestURI() { - return m_request.getRequestURI(); - } - -// public StringBuffer getRequestURL() { -// throw new UnsupportedOperationException -// ("This is a Servlet 2.3 feature that we do not currently support"); -// } - - /* Obviously there was a problem with this method in early implementations - * of Servlet specification 2.3 which was resolved later. So it should be - * save to use it now. (2012-02-06) - */ - /** - * - * @return - */ - @Override - public StringBuffer getRequestURL() { - return m_request.getRequestURL(); - } - - /** - * - * @return - */ - @Override - public String getServletPath() { - return m_request.getServletPath(); - } - - public HttpSession getSession(boolean create) { - return m_request.getSession(create); - } - - public HttpSession getSession() { - return m_request.getSession(); - } - - public boolean isRequestedSessionIdValid() { - return m_request.isRequestedSessionIdValid(); - } - - public boolean isRequestedSessionIdFromCookie() { - return m_request.isRequestedSessionIdFromCookie(); - } - - public boolean isRequestedSessionIdFromURL() { - return m_request.isRequestedSessionIdFromURL(); - } - - public boolean isRequestedSessionIdFromUrl() { - return m_request.isRequestedSessionIdFromUrl(); - } - - //methods for ServletRequest Interface - public String getCharacterEncoding() { - return m_request.getCharacterEncoding(); - } - - /** - * - * @param encoding - * - * @throws java.io.UnsupportedEncodingException - */ - @Override - public void setCharacterEncoding(String encoding) - throws java.io.UnsupportedEncodingException { - throw new UnsupportedOperationException( - "This is a Servlet 2.3 feature that we do not currently support"); - } - - public int getContentLength() { - return m_request.getContentLength(); - } - - public String getContentType() { - return m_request.getContentType(); - } - - public ServletInputStream getInputStream() - throws IOException { - //maybe just throw an exception here -- UM - return m_request.getInputStream(); - } - - public String getProtocol() { - return m_request.getProtocol(); - } - - public String getScheme() { - return m_request.getScheme(); - } - - public String getServerName() { - return m_request.getServerName(); - } - - public int getServerPort() { - return m_request.getServerPort(); - } - - public BufferedReader getReader() throws IOException { - //maybe just throw an exception here -- Uday - return m_request.getReader(); - } - - public String getRemoteAddr() { - return m_request.getRemoteAddr(); - } - - public String getRemoteHost() { - return m_request.getRemoteHost(); - } - - public void setAttribute(String name, - Object o) { - m_request.setAttribute(name, o); - } - - public void removeAttribute(String name) { - m_request.removeAttribute(name); - } - - public Locale getLocale() { - return m_request.getLocale(); - } - - public Enumeration getLocales() { - return m_request.getLocales(); - } - - public boolean isSecure() { - return m_request.isSecure(); - } - - public RequestDispatcher getRequestDispatcher(String path) { - return m_request.getRequestDispatcher(path); - } - - public String getRealPath(String path) { - return m_request.getRealPath(path); - } - - /* - * Parse the body of multipart MIME-encoded request. - */ - private void parseMultipartRequest(HttpServletRequest request) - throws MessagingException, IOException { - // replace JAF+JavaMail combo (broken with CoyoteInputStream) - // with simple commons-fileupload - try { - ServletFileUpload upload = new ServletFileUpload( - new DiskFileItemFactory()); - List items = upload.parseRequest(request); - for (Iterator i = items.iterator(); i.hasNext();) { - FileItem item = (FileItem) i.next(); - String paramName = item.getFieldName(); - if (item.isFormField()) { - addParameterValue(paramName, item.getString()); - } else { - addParameterValue(paramName, item.getName()); - // save file - File tmpFile = File.createTempFile("acs", null, null); - tmpFile.deleteOnExit(); - addParameterValue(paramName + ".tmpfile", tmpFile.getPath()); - item.write(tmpFile); - } - } - } catch (Exception e) { - throw new RuntimeException(e); // XXX - } - } - - private void addParameterValue(String name, Object value) - throws IOException { - String[] newValues; - String[] values = (String[]) m_parameters.get(name); - - if (values == null) { - newValues = new String[1]; - } else { - newValues = new String[values.length + 1]; - System.arraycopy(values, 0, newValues, 0, values.length); - } - - newValues[newValues.length - 1] = convertToString(value); - - m_parameters.put(name, newValues); - } - - private String convertToString(Object value) throws IOException { - if (value instanceof String) { - return (String) value; - } - - if (value instanceof ByteArrayInputStream) { - StringBuilder output = new StringBuilder(); - - InputStreamReader reader; - try { - reader = new InputStreamReader( - (ByteArrayInputStream) value, - Globalization.DEFAULT_ENCODING); - } catch (UnsupportedEncodingException ex) { - throw new UncheckedWrapperException(ex); - } - - final int bufSize = 1024; - char[] buffer = new char[bufSize]; - - int read = bufSize; - while (bufSize == read) { - read = reader.read(buffer, 0, bufSize); - if (read > 0) { - output.append(buffer, 0, read); - } - } - - return output.toString(); - } - - // Fallback to default - return value.toString(); - } - - public String getLocalAddr() { - return m_request.getLocalAddr(); - } - - public String getLocalName() { - // TODO Auto-generated method stub - return m_request.getLocalName(); - } - - public int getLocalPort() { - // TODO Auto-generated method stub - return m_request.getLocalPort(); - } - - public int getRemotePort() { - // TODO Auto-generated method stub - return m_request.getRemotePort(); - } - - @Override - public String changeSessionId() { - return m_request.changeSessionId(); - } - - @Override - public boolean authenticate(final HttpServletResponse response) - throws IOException, ServletException { - return m_request.authenticate(response); - } - - @Override - public void login(final String username, - final String password) throws ServletException { - m_request.login(username, password); - } - - @Override - public void logout() throws ServletException { - m_request.logout(); - } - - @Override - public Collection getParts() throws IOException, ServletException { - return m_request.getParts(); - } - - @Override - public Part getPart(final String name) throws IOException, ServletException { - return m_request.getPart(name); - } - - @Override - public T upgrade(final Class handlerClass) - throws IOException, ServletException { - return m_request.upgrade(handlerClass); - } - - @Override - public long getContentLengthLong() { - return m_request.getContentLengthLong(); - } - - @Override - public ServletContext getServletContext() { - return m_request.getServletContext(); - } - - @Override - public AsyncContext startAsync() throws IllegalStateException { - return m_request.startAsync(); - } - - @Override - public AsyncContext startAsync(final ServletRequest servletRequest, - final ServletResponse servletResponse) - throws IllegalStateException { - return m_request.startAsync(servletRequest, servletResponse); - } - - @Override - public boolean isAsyncStarted() { - return m_request.isAsyncStarted(); - } - - @Override - public boolean isAsyncSupported() { - return m_request.isAsyncSupported(); - } - - @Override - public AsyncContext getAsyncContext() { - return m_request.getAsyncContext(); - } - - @Override - public DispatcherType getDispatcherType() { - return m_request.getDispatcherType(); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/RedirectException.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/RedirectException.java deleted file mode 100644 index 3650fbdbd..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/RedirectException.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -/** - * Thrown if the requested file is a - * directory and the original request URL does not end with a trailing - * slash. - * - * @author Bill Schneider - * @version $Id$ - * @since 4.5 */ -public class RedirectException extends Exception { - - public RedirectException(String s) { - super(s); - } - - public RedirectException() { - super(); - } - - public String getRedirectURL() { - return getMessage(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/RequestContext.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/RequestContext.java deleted file mode 100644 index 2493e0dc2..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/RequestContext.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import java.util.Locale; -import java.util.ResourceBundle; -import javax.servlet.ServletContext; - -/** - * Interface used when dispatchers are - * chained or piped together. Part of the requested URL will be used - * at each stage of the dispatch, and this interface is used by the - * dispatcher to tell what part of the URL has already been used to - * dispatch the request so far. The remainder is what the current - * dispatcher must work with. Because form/URL variables are not - * order-dependent, We only keep track of the path portion - * of the URL. - * - * @author Bill Schneider - * @version $Id$ - * @since 4.5 */ - -public interface RequestContext { - - - /** - * Gets the portion of the URL that has not been used by - * previous dispatchers in the chain. - * @return the portion of the URL that must be used by - * the current dispatcher. - */ - public String getRemainingURLPart(); - - /** - * Gets the portion of the URL that has already been used by - * previous dispatchers in the chain. - * @return the portion of the URL that has already been used. - */ - public String getProcessedURLPart(); - - /** - * Gets the original URL requested by the end user's browser. - * This URL does not change when a request is forwarded - * by the application; "/foo/bar" is still the original request - * URI in the browser even if we've dispatched the request to - * "/packages/foo/www/bar.jsp". - * - * @return the original URL requested by the end user's browser. - * All generated HREF, IMG SRC, and FORM ACTION attributes, and - * any redirects, will be relative to this URL. - */ - public String getOriginalURL(); - - /** - * Gets the current servlet context. - * @return the current servlet context, which must be set by implementation. - */ - public ServletContext getServletContext(); - - /** - * more methods will be implemented as needed, for locale, - * form variables, etc. - */ - - /** - * Gets the locale for the current request context. - * @return the locale for the current request context. - */ - public Locale getLocale(); - - /** - * Returns a java.util.ResourceBundle for the - * current request, based on the requested application and the - * user's locale preference. - * - * @return the current java.util.ResourceBundle to use - * in this request. - */ - public ResourceBundle getResourceBundle(); - - /** - * Gets the requested output type. - * @return the requested output type (normally "text/html" by default - * for a web browser request). - */ - public String getOutputType(); - - /** - * Gets the debugging flag. - * @return the debugging flag. - * Currently, debugging applies to XSL transformation. - */ - public boolean getDebugging(); - - /** - * Gets the show-XML-only flag. - * @return if true, indicates that the active - * PresentationManager should output raw, untransformed - * XML instead of processing it with XSLT. - */ - public boolean getDebuggingXML(); - - /** - * Gets the show-XSL-only flag. - * @return if true, indicates that the active - * PresentationManager should output the XSLT stylesheet - * in effect for this request. - */ - public boolean getDebuggingXSL(); - - - /** - * Gets the base path, relative to the webapp root, where JSP-based - * resources (and static pages) will be found. - * @return the base path, relative to the webapp root, where - * JSP-based resources will be found. - * Returns with a trailing slash (for example, - * /packages/package-key/www/). - */ - public String getPageBase(); -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/RequestEvent.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/RequestEvent.java deleted file mode 100755 index 7c7e8fc7a..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/RequestEvent.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Request event class. Passed as a - * parameter to the methods of RequestListener. - * - * @see RequestListener - * @author Bill Schneider - * @version $Id$ - * @since 4.5 */ -public class RequestEvent { - - - private HttpServletRequest m_req; - private HttpServletResponse m_resp; - private RequestContext m_ctx; - private boolean m_start; - private boolean m_finished_normal; - - /** - * Creates a new RequestEvent with a success/failure status - * code. - * @param req the current request - * @param resp the current response - * @param ctx the current request context - * @param start if true, indicates that this is a start-request event; - * if false, this is an end-request event. - * @param finishedNormal if true, indicates the request finished - * without error. - */ - public RequestEvent(HttpServletRequest req, - HttpServletResponse resp, - RequestContext ctx, - boolean start, - boolean finishedNormal) { - m_req = req; - m_resp = resp; - m_ctx = ctx; - m_start = start; - m_finished_normal = finishedNormal; - } - - - /** - * Creates a new RequestEvent with no status code. - * @param req the current request - * @param resp the current response - * @param ctx the current request context - * @param start if true, indicates that this is a start-request event; - * if false, this is an end-request event. - */ - public RequestEvent(HttpServletRequest req, - HttpServletResponse resp, - RequestContext ctx, - boolean start) { - this(req, resp, ctx, start, false); - } - - - /** - * Returns the current request for the request event. - * @return the current request - */ - public HttpServletRequest getRequest() { - return m_req; - } - - /** - * Returns the current response for the request event. - * @return the current response - */ - public HttpServletResponse getResponse() { - return m_resp; - } - - /** - * Returns the current request context for the request event. - * @return the current request context - */ - public RequestContext getRequestContext() { - return m_ctx; - } - - /** - * Returns true if the event is a start-request event; - * false for an end-request event. - * - * @return true if we're starting a request, false at end. - */ - public boolean isStart() { - return m_start; - } - - /** - * Returns a status code to indicate whether the request - * finished without error. - * - * @return true if the request finished without exception. - * false if the request finished with an error, or if the request - * event is a start-request. - */ - public boolean finishedNormal() { - return m_finished_normal; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/dispatcher/RequestListener.java b/ccm-core/src/main/java/com/arsdigita/dispatcher/RequestListener.java deleted file mode 100755 index 4a46ed758..000000000 --- a/ccm-core/src/main/java/com/arsdigita/dispatcher/RequestListener.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.dispatcher; - -import java.util.EventListener; - -/** - * Used to register callbacks for the code to run - * when a request starts or ends. - * - * @author Bill Schneider - * @version $Id$ - * @since 4.5 */ -public interface RequestListener extends EventListener { - - /** - * Called when ACSServlet starts processing an incoming request. - * @param e the event - */ - public void requestStarted(RequestEvent e); - - /** - * Called when ACSServlet finishes processing an incoming request. - * @param e the event - */ - public void requestFinished(RequestEvent e); -} diff --git a/ccm-core/src/main/java/com/arsdigita/domain/DomainService.java b/ccm-core/src/main/java/com/arsdigita/domain/DomainService.java deleted file mode 100755 index 5e0a47dbf..000000000 --- a/ccm-core/src/main/java/com/arsdigita/domain/DomainService.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.domain; - -import org.libreccm.core.CcmObject; -import org.libreccm.core.UnexpectedErrorException; - -import java.beans.BeanInfo; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Optional; - -/** - * - * This class should be extended by domain object services that need privileged - * access to the DataObject encapsulated by a DomainObject or the DataCollection - * encapsulated by a DomainCollection. - * - * Note: This class was tightly coupled with the old PDL based persistence - * system. The class has been adapted to use standard Bean/Reflection methods - * instead, but some the results may differ. - * - * @author Oumi Mehrotra - * @author Jens Pelzetter - */ -public abstract class DomainService { - - /** - * - * Get a property of the specified domain object. - * - * @param domainObject - * @param attr - * - * @return - * - */ - protected static Object get(final Object domainObject, - final String attr) { - - final BeanInfo beanInfo; - try { - beanInfo = Introspector.getBeanInfo(domainObject.getClass()); - } catch (IntrospectionException ex) { - throw new UnexpectedErrorException(ex); - } - - final Optional property = Arrays - .stream(beanInfo.getPropertyDescriptors()) - .filter(current -> attr.equals(current.getName())) - .findAny(); - - if (property.isPresent()) { - - final Method readMethod = property.get().getReadMethod(); - - final Object result; - try { - result = readMethod.invoke(domainObject); - } catch (IllegalAccessException | InvocationTargetException ex) { - throw new UnexpectedErrorException(ex); - } - return result; - } else { - return null; - } - } - - // These methods modify domain objects and should be used cautiously. - /** - * - * Set a property of the DomainObjects DataObject. - * - * - * @param domainObject - * @param attr - * @param value - */ - protected static void set(final Object domainObject, - final String attr, - final Object value) { - - final BeanInfo beanInfo; - try { - beanInfo = Introspector.getBeanInfo(domainObject.getClass()); - } catch (IntrospectionException ex) { - throw new UnexpectedErrorException(ex); - } - - final Optional property = Arrays - .stream(beanInfo.getPropertyDescriptors()) - .filter(current -> attr.equals(current.getName())) - .findAny(); - - if (property.isPresent()) { - - final Method writeMethod = property.get().getWriteMethod(); - - try { - writeMethod.invoke(domainObject, value); - } catch (IllegalAccessException | InvocationTargetException ex) { - throw new UnexpectedErrorException(ex); - } - - } - } - - /** - * - * Set an association DomainObjects DataObject. - * - * @see DomainObject#set(String, Object) - * - */ -// protected static void setAssociation(DomainObject domainObject, -// String attr, DomainObject dobj) { -// domainObject.set(attr, dobj); -// } - - /** - * Adds data object specified by value to the specified role (with - * multiplicity>1) of the specified domain object. - * - * @see DomainObject#add(String, DataObject) - */ -// protected static DataObject add(DomainObject domainObject, -// String roleName, DataObject value) { -// return domainObject.add(roleName, value); -// } - - /** - * Adds domain object specified by value to the specified role (with - * multiplicity>1) of the specified domain object. - * - * @see DomainObject#add(String, DomainObject) - */ -// protected static DataObject add(DomainObject domainObject, -// String roleName, DomainObject value) { -// return domainObject.add(roleName, value); -// } - - /** - * - * Removes data object specified by value from the specified role - * (with multiplicity>1) of the specified domain object. - * - * @see DomainObject#remove(String, DataObject) - */ -// protected static void remove(DomainObject domainObject, -// String roleName, DataObject value) { -// domainObject.remove(roleName, value); -// } - - /** - * - * Removes domain object specified by value from the specified role - * (with multiplicity>1) of the specified domain object. - * - * @see DomainObject#remove(String, DomainObject) - */ -// protected static void remove(DomainObject domainObject, -// String roleName, DomainObject value) { -// domainObject.remove(roleName, value); -// } - - /** - * - * Clears specified role (with multiplicity > 1) of specified domain object. - * - * @see DomainObject#clear(String) - */ -// protected static void clear(DomainObject domainObject, String roleName) { -// domainObject.clear(roleName); -// } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/formbuilder/FormBuilderConfig.java b/ccm-core/src/main/java/com/arsdigita/formbuilder/FormBuilderConfig.java deleted file mode 100755 index 096f4b6c0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/formbuilder/FormBuilderConfig.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.formbuilder; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.Configuration; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.configuration.Setting; - -import java.util.Objects; - -/** - * - * @author Jens Pelzetter - */ -@Configuration -public final class FormBuilderConfig { - - @Setting - private String actionsHelpUrl; - - @Setting - private String controlsHelpUrl; - - @Setting - @SuppressWarnings("PMD.LongVariable") - private Boolean interpolateEmailActions; - - public static FormBuilderConfig getConfig() { - final ConfigurationManager confManager = CdiUtil.createCdiUtil() - .findBean(ConfigurationManager.class); - return confManager.findConfiguration(FormBuilderConfig.class); - } - - public String getActionsHelpUrl() { - return actionsHelpUrl; - } - - public void setActionsHelpUrl(final String actionsHelpUrl) { - this.actionsHelpUrl = actionsHelpUrl; - } - - public String getControlsHelpUrl() { - return controlsHelpUrl; - } - - public void setControlsHelpUrl(final String controlsHelpUrl) { - this.controlsHelpUrl = controlsHelpUrl; - } - - public Boolean getInterpolateEmailActions() { - return interpolateEmailActions; - } - - @SuppressWarnings("PMD.LongVariable") - public void setInterpolateEmailActions(final Boolean interpolateEmailActions) { - this.interpolateEmailActions = interpolateEmailActions; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 71 * hash + Objects.hashCode(actionsHelpUrl); - hash = 71 * hash + Objects.hashCode(controlsHelpUrl); - hash = 71 * hash + Objects.hashCode(interpolateEmailActions); - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof FormBuilderConfig)) { - return false; - } - final FormBuilderConfig other = (FormBuilderConfig) obj; - if (!Objects.equals(actionsHelpUrl, other.getActionsHelpUrl())) { - return false; - } - if (!Objects.equals(controlsHelpUrl, other.getControlsHelpUrl())) { - return false; - } - return Objects.equals(interpolateEmailActions, - other.getInterpolateEmailActions()); - } - - @Override - public String toString() { - return String.format("%s{ " - + "actionsHelpUrl = \"%s\", " - + "controlsHelpUrl = \"%s\", " - + "interpolateEmailActions = %b" - + " }", - super.toString(), - actionsHelpUrl, - controlsHelpUrl, - interpolateEmailActions); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/globalization/Globalization.java b/ccm-core/src/main/java/com/arsdigita/globalization/Globalization.java deleted file mode 100644 index 5612ae720..000000000 --- a/ccm-core/src/main/java/com/arsdigita/globalization/Globalization.java +++ /dev/null @@ -1,535 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.globalization; - -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.dispatcher.RequestContext; -//import com.arsdigita.kernel.Kernel; -//import com.arsdigita.persistence.DataCollection; -//import com.arsdigita.persistence.Session; -//import com.arsdigita.persistence.SessionManager; -//import com.arsdigita.persistence.TransactionContext; - -import java.io.UnsupportedEncodingException; -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - *

- * Utilities for the globalization process. The methods in this class make use - * of the assumption that the ACS handles all locale and resource negotiation so - * that the application developer doesn't have to worry about it. - *

- * - * @version $Id$ - */ -public class Globalization { - - private static final Logger LOGGER = LogManager.getLogger( - Globalization.class); - - public static final String ENCODING_PARAM_NAME = "g11n.enc"; - - /** - * The default encoding for parameterts, as specified by the servlet spec - */ - public static final String DEFAULT_PARAM_ENCODING = "ISO-8859-1"; - - /** - * The default encoding for request/response body data, as specified by the - * servlet spec - */ - public static final String DEFAULT_ENCODING = "ISO-8859-1"; - -// private static Map s_localeToCharsetMap; - private static String s_defaultCharset = DEFAULT_ENCODING; - - private static boolean initialized = false; - - static void init() { - if (initialized) { - return; - } -// loadLocaleToCharsetMap(); - initialized = true; - } - -// // Load the Locale to Charset Map from persistent storage. -// public static void loadLocaleToCharsetMap() { -// // retrieve all Locale objects that have a defaultCharset associated -// // with them. -// Session s = SessionManager.getSession(); -// -// final TransactionContext tcontext = s.getTransactionContext(); -// boolean startedTransaction = false; -// -// try { -// if (!tcontext.inTxn()) { -// tcontext.beginTxn(); -// startedTransaction = true; -// } -// -// DataCollection locales = s.retrieve(Locale.BASE_DATA_OBJECT_TYPE); -// locales.addNotEqualsFilter("defaultCharset.id", null); -// -// Map map = new HashMap(); -// -// while (locales.next()) { -// Locale localeObject = new Locale(locales.getDataObject()); -// java.util.Locale locale = localeObject.toJavaLocale(); -// Charset defaultCharset = localeObject.getDefaultCharset(); -// Assert.exists(defaultCharset, -// "DefaultCharset for locale \"" -// + locale + "\" (" + localeObject + ")"); -// String charset = defaultCharset.getCharset(); -// -// if (s_log.isInfoEnabled()) { -// s_log.info("Mapping locale " + locale.toString() + -// " to charset " + charset); -// } -// -// // insert locale and charset into map -// map.put(locale.toString(), charset); -// } -// -// s_localeToCharsetMap = map; -// } finally { -// if (startedTransaction && tcontext.inTxn()) { -// tcontext.commitTxn(); -// } -// } -// } - static void setDefaultCharset(String encoding) { - s_defaultCharset = encoding; - } - - /** - * Get the default character set for encoding data - * - * @return String the character set - */ - public static String getDefaultCharset() { - return s_defaultCharset; - } - - /** - *

- * Get the default character set for a given locale. - *

- * - * @param locale - * - * @return String the character set - * - * @see java.util.Locale - */ - public static String getDefaultCharset(java.util.Locale locale) { - init(); - return "UTF-8"; -// String charset; -// -// if (locale == null || locale.toString().length() == 0) { -// throw new IllegalArgumentException("locale cannot be empty."); -// } -// -// if (s_log.isDebugEnabled()) { -// s_log.debug("Looking for charset for locale " + locale.toString()); -// } -// // Try a full name match (may include country) -// charset = "UTF-8"; -// -// if (charset != null) { -// // Found a match -// return charset; -// } -// -// if (s_log.isDebugEnabled()) { -// s_log.debug("Looking for charset for language " + locale.getLanguage()); -// } -// // If we didn't find a full name match, try just the language -// charset = "UTF-8"; -// -// if ( charset != null ) { -// return charset; -// } -// -// if (s_log.isDebugEnabled()) { -// s_log.debug("Falling back on default encoding " + getDefaultCharset()); -// } -// return getDefaultCharset(); - } - - /** - * Get the default character set for the request. First tries the - * getCharacterENcoding() method, then falls back on the - * DEFAULT_PARAM_ENCODING - * - * @return String the character set - */ - public static String getDefaultCharset(HttpServletRequest req) { - String charset = req.getCharacterEncoding(); - if (charset == null) { - charset = DEFAULT_PARAM_ENCODING; - } - return charset; - } - - /** - * Get the best locale for this request. - */ - private static java.util.Locale getLocale(HttpServletRequest req) { - java.util.Locale l = DispatcherHelper.getNegotiatedLocale(); - if (l == null) { - l = req.getLocale(); - } - if (l == null) { - l = java.util.Locale.getDefault(); - } - return l; - } - - /** - *

- * Decode the value of an HttpServletRequest parameter. The value is decoded - * appropriately (lets hope so anyway). - *

- * - * @param r The HttpServletRequest for which to get the value. - * @param name The name of the parameter to retrieve. - * - * @return String The decoded value of the parameter. - */ - public static final String decodeParameter( - HttpServletRequest r, String name - ) { - String re = r.getParameter(Globalization.ENCODING_PARAM_NAME); - String original = r.getParameter(name); - String real = null; - - if (re == null || re.length() == 0) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(ENCODING_PARAM_NAME + " is not set, using locale " - + "default encoding for parameter " + name); - } - re = getDefaultCharset(getLocale(r)); - } - - if (original == null || original.length() == 0) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Parameter " + name + " has no value"); - } - real = original; - } else if (getDefaultCharset(r).equals(re)) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Parameter " + name - + " is already in correct encoding"); - } - real = original; - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Parameter " + name + " is being converted from " - + getDefaultCharset(r) + " into " + re); - } - try { - real = new String(original.getBytes(getDefaultCharset(r)), - re); - } catch (UnsupportedEncodingException uee) { - LOGGER.warn("encoding " + re - + " is not supported, falling back on system default"); - real = original; - } - } - - return real; - } - - /** - *

- * Decode all of the values of an HttpServletRequest array parameter. - *

- * - * @param r The HttpServletRequest for which to decode the parameters. - * - * @return String[] The decoded parameters. - */ - public static final String[] decodeParameters(HttpServletRequest r, - String name) { - String re = r.getParameter(Globalization.ENCODING_PARAM_NAME); - String[] originals = r.getParameterValues(name); - String[] real = null; - - if (re == null || re.length() == 0) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(ENCODING_PARAM_NAME + " is not set, using locale " - + "default encoding for parameter " + name); - } - re = getDefaultCharset(getLocale(r)); - } - - if (originals == null || originals.length == 0) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Parameter " + name + " has no value"); - } - real = originals; - } else if (getDefaultCharset(r).equals(re)) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Parameter " + name - + " is already in correct encoding"); - } - real = originals; - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Parameter " + name + " is being converted from " - + getDefaultCharset(r) + " into " + re); - } - try { - real = new String[originals.length]; - for (int i = 0; i < originals.length; i++) { - real[i] = new String(originals[i].getBytes( - getDefaultCharset(r)), - re); - } - } catch (UnsupportedEncodingException uee) { - LOGGER.warn("encoding " + re - + " is not supported, falling back on system default"); - real = originals; - } - } - - return real; - } - - /** - *

- * Get the appropriate ResourceBundle based ont he request and locale. - *

- * - * @return ResourceBundle - * - * @see java.util.ResourceBundle - */ - public static ResourceBundle getResourceBundle() { - return getResourceBundle(DispatcherHelper.getRequest()); - } - - /** - *

- * Get the appropriate ResourceBundle based on the request and Locale - *

- * - * @param r The current HttpServletRequest - * - * @return ResourceBundle - * - * @see java.util.ResourceBundle - */ - public static ResourceBundle getResourceBundle(HttpServletRequest r) { - RequestContext rc = DispatcherHelper.getRequestContext(r); - ResourceBundle rb = null; - - rb = rc.getResourceBundle(); - - if (rb != null) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info(rb.getClass().getName() - + " is the chosen ResourceBundle."); - } - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("No matching ResourceBundle found"); - } - } - - return rb; - } - - /** - *

- * Get an Object from the appropriate ResourceBundle based on the - * appropriate Locale and key. - *

- * - * @param r The current HttpServletRequest. - * @param key The key used to select the appropriate Object - * - * @return The localized Object - * - * @see java.util.ResourceBundle - */ - public static Object getLocalizedObject(HttpServletRequest r, - String key) { - ResourceBundle rb = null; - Object l7dObject = key; - - // If the key does not contain a '#' character, then use the - // HttpServletRequest alone to determine the appropriate - // ResourceBundle. - int separator = key.indexOf('#'); - if (separator < 0) { - rb = getResourceBundle(r); - } else { - java.util.Locale locale = DispatcherHelper.getNegotiatedLocale(); - String targetBundle = key.substring(0, separator); - - try { - if (locale != null) { - rb = ResourceBundle.getBundle(targetBundle, locale); - } else { - rb = ResourceBundle.getBundle(targetBundle); - } - } catch (MissingResourceException mre) { - return key; - } - - key = key.substring(separator + 1); - } - - try { - if (rb != null) { - l7dObject = rb.getObject(key); - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("No ResourceBundle available"); - } - } - } catch (MissingResourceException e) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Key " + key + " was not found in the " - + "ResourceBundle"); - } - } - - return l7dObject; - } - - /** - *

- * Get a String from the appropriate ResourceBundle based on the appropriate - * Locale and key. - *

- * - * @param r The current HttpServletRequest. - * @param key The key used to select the appropriate String - * - * @return The localized String - * - * @see java.util.ResourceBundle - */ - public static String getLocalizedString(HttpServletRequest r, - String key) { - return (String) getLocalizedObject(r, key); - } - - /** - *

- * Get a parameterized String (for doing MessageFormatting) from the - * appropraite ResourceBundle based on the appropriate Locale and key. Then - * interpolate the values for the other keys passed. - *

- * - * @param r The current HttpServletRequest. - * @param key The key used to select the appropriate String - * @param arguments A Object[] containing the other keys to localize and - * interpolate into the parameterized string. It may also - * contain other Objects beside Strings, such as Date - * objects and Integers, etc. - * - * @return The localized and interpolated String - * - * @see java.text.MessageFormat - * @see java.util.ResourceBundle - */ - public static String getLocalizedString(HttpServletRequest r, - String key, - Object[] arguments) { - String l7dString = getLocalizedString(r, key); - - for (int i = 0; i < arguments.length; i++) { - // if we encounter a String object then treat it as a key and try - // to look it up in the appropriate ResourceBundle. - if (arguments[i] instanceof String) { - arguments[i] = getLocalizedString(r, (String) arguments[i]); - } - } - - // interpolate the values into the final string. - l7dString = MessageFormat.format(l7dString, arguments); - - return l7dString; - } - - /** - *

- * Find the ResourceBundle for this language without falling back to a - * default ResourceBundle in another language - *

- * - * @param targetBundle The ResourceBundle we are looking for. - * @param locale The Locale object representing the language we want. - * @param defaultLocale The Locale object representing the default language. - */ - public static ResourceBundle getBundleNoFallback(String targetBundle, - java.util.Locale locale, - java.util.Locale defaultLocale) { - ResourceBundle bundle = null; - - if (locale == null) { - locale = (defaultLocale != null) ? defaultLocale : java.util.Locale - .getDefault(); - } - - try { - bundle = ResourceBundle.getBundle(targetBundle, locale); - } catch (MissingResourceException e) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Didn't find ResourceBundle for " + targetBundle); - } - } - - String targetLanguage = locale.getLanguage(); - - // Make sure that if we found a ResourceBundle it is either in the - // language we were looking for or, by coincidence, the target - // language happens to match the default language for the system. - if (bundle != null) { - if (targetLanguage.equals(bundle.getLocale().getLanguage()) - || targetLanguage.equals(defaultLocale.getLanguage())) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Found matching ResourceBundle for " - + targetBundle); - } - } else { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Found non-matching ResourceBundle for " - + targetBundle); - } - bundle = null; - } - } - - return bundle; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/globalization/Globalized.java b/ccm-core/src/main/java/com/arsdigita/globalization/Globalized.java deleted file mode 100644 index 3eb15cb60..000000000 --- a/ccm-core/src/main/java/com/arsdigita/globalization/Globalized.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.globalization; -// import java.text.DateFormat; - -/** - * Standard, final constants used by the globalization APIs. This - * interface is designed to be extended on a package-by-package basis - * to include package-specific constants. A typical package specific - * constant would be the resource bundle name for a given package. By - * extending the Globalized interface and defining a final static - * BUNDLE_NAME constant, classes implementing the Globalized interface - * could call {@link GlobalizedMessage} and pass in the BUNDLE_NAME - * constant i.e., - * - *

- *

- *  new GlobalizedMessage("forums.newpost.proofread",
- *                        BUNDLE_NAME)
- * 
- *

- * - * @version $Revision$ $Date$ - * @version $Id$ - */ -public interface Globalized { - - /** The default format for displaying dates. */ - public final static int DATE_DISPLAY_FORMAT = java.text.DateFormat.MEDIUM; - - /** The default format for displaying time. */ - public final static int TIME_DISPLAY_FORMAT = java.text.DateFormat.SHORT; - - /** Override the value of this string for your particular package. */ - public final static String BUNDLE_NAME = "com.arsdigita.globalization"; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/globalization/LegacyGlobalizationHelper.java b/ccm-core/src/main/java/com/arsdigita/globalization/LegacyGlobalizationHelper.java deleted file mode 100644 index 414094a1d..000000000 --- a/ccm-core/src/main/java/com/arsdigita/globalization/LegacyGlobalizationHelper.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.arsdigita.globalization; - -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.kernel.KernelConfig; - -import java.util.Enumeration; - -import javax.servlet.ServletRequest; - -import java.util.Locale; -import java.util.StringTokenizer; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -/** - * - * @deprecated Replaced by {@link org.libreccm.l10n.GlobalizationHelper} - * - * @author Sören Bernstein - */ -@Deprecated -public class LegacyGlobalizationHelper { - - private static final String LANG_PARAM = "lang"; - - // Don't instantiate - private LegacyGlobalizationHelper() { - } - - /** - * This method returns the best matching locate for the request. In contrast - * to the other methods available this one will also respect the - * supported_languages config entry. - * - * @return The negotiated locale - */ - public static Locale getNegotiatedLocale() { - final KernelConfig kernelConfig = KernelConfig.getConfig(); - - // Set the preferedLocale to the default locale (first entry in the config parameter list) - Locale preferedLocale = getPrefferedLocale(); - - // The ACCEPTED_LANGUAGES from the client - Enumeration locales = null; - - // Try to get the RequestContext - try { - - // Get the SerrvletRequest - ServletRequest request = ((ServletRequest) DispatcherHelper - .getRequest()); - - // Get the selected locale from the request, if any - Locale selectedLocale = getSelectedLocale(request); - if (selectedLocale != null && kernelConfig.hasLanguage( - selectedLocale.getLanguage())) { - preferedLocale = selectedLocale; - } else { - - locales = request.getLocales(); - - // For everey element in the enumerator - while (locales.hasMoreElements()) { - - // Test if the current locale is listed in the supported locales list - Locale curLocale = (Locale) locales.nextElement(); - if (kernelConfig.hasLanguage(curLocale.getLanguage())) { - preferedLocale = curLocale; - break; - } - } - } - } catch (NullPointerException ex) { - // Don't have to do anything because I want to fall back to default language anyway - // This case should only appear during setup - } finally { - - return preferedLocale; - - } - } - -// public static Locale getSystemLocale() { -// -// } - private static Locale getPrefferedLocale() { - final KernelConfig kernelConfig = KernelConfig.getConfig(); - - Locale preferedLocale = new Locale(kernelConfig - .getDefaultLanguage(), "", ""); - return preferedLocale; - } - - /** - * Get the selected (as in fixed) locale from the ServletRequest - * - * @return the selected locale as Locale or null if not defined - */ - public static Locale getSelectedLocale(ServletRequest request) { - - // Return value - Locale selectedLocale = null; - - // Access current HttpSession or create a new one, if none exist - HttpSession session = ((HttpServletRequest) request).getSession(true); - // Get the session stored language string - String selectedSessionLang = (String) session.getAttribute(LANG_PARAM); - // Get the request langauge string - String selectedRequestLang = request.getParameter(LANG_PARAM); - - // If there is a request language string, then this will have priority - // because this will only be the case, if someone selected another - // language with the language selector - if (selectedRequestLang != null) { - // Get the Locale object for the param - if ((selectedLocale = scanLocale(selectedRequestLang)) != null) { - // Save the request parameter as session value - session.setAttribute(LANG_PARAM, selectedRequestLang); - } - } else // If there is a session stored language, use it - if (selectedSessionLang != null) { - selectedLocale = scanLocale(selectedSessionLang); - } - - return selectedLocale; - } - - /** - * Create a Locale from a browser provides language string - * - * @param lang A string encoded locale, as provided by browsers - * - * @return A Locale representation of the language string - */ - private static Locale scanLocale(String lang) { - - // Protect against empty lang string - if ((lang != null) && !(lang.isEmpty())) { - // Split the string and create the Locale object - StringTokenizer paramValues = new StringTokenizer(lang, "_"); - if (paramValues.countTokens() > 1) { - return new Locale(paramValues.nextToken(), paramValues - .nextToken()); - } else { - return new Locale(paramValues.nextToken()); - } - } - - return null; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/kernel/security/DefaultSecurityHelper.java b/ccm-core/src/main/java/com/arsdigita/kernel/security/DefaultSecurityHelper.java deleted file mode 100644 index e27c83cae..000000000 --- a/ccm-core/src/main/java/com/arsdigita/kernel/security/DefaultSecurityHelper.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.kernel.security; - -import javax.servlet.http.HttpServletRequest; - -/** - * Default implementation of SecurityHelper interface. - * - * @author Sameer Ajmani - * @see SecurityHelper - */ -public class DefaultSecurityHelper implements SecurityHelper { - - /** - * Determines whether the request is secure by calling - * req.isSecure(). - * - * @param request The current {@link HttpServletRequest} - * - * @return req.isSecure(). - * - */ - @Override - public boolean isSecure(final HttpServletRequest request) { - return request.isSecure(); - } - - /** - * Determines whether the current request requires that the user be logged - * in. - * - * @param request The current {@link HttpServletRequest} - * - * @return true if the request is secure and the page is not on - * a list of allowed pages (such as the login page and the - * bad-password page), false otherwise. - * - */ - @Override - public boolean requiresLogin(final HttpServletRequest request) { - // XXX workaround, old is broken anyway, - // it doesn't take into account dispatcher prefix ( /ccm ) - return false; - } - - /** - * Returns the full URL of the login page stored in the page map. - * - * @param request The current {@link HttpServletRequest} - * - * @return the full URL of the login page. - * - */ - @Override - public String getLoginURL(final HttpServletRequest request) { - //ToDo: Add correct method call here. - - //return UI.getLoginPageURL(); - return ""; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/kernel/security/SecurityHelper.java b/ccm-core/src/main/java/com/arsdigita/kernel/security/SecurityHelper.java deleted file mode 100755 index d4b63b271..000000000 --- a/ccm-core/src/main/java/com/arsdigita/kernel/security/SecurityHelper.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.kernel.security; - -import javax.servlet.http.HttpServletRequest; - -/** - * Provides methods for determining security properties for a request. - * - * @author Sameer Ajmani - * @version $Id: SecurityHelper.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public interface SecurityHelper { - - /** - * Determines whether the given request is secure. Implementation may - * simply return req.isSecure(), but certain deployments - * may use other information (such as the requested port number) - * instead. - * - * @param req the request to check - * - * @return true if the given request uses a secure - * protocol, false otherwise. - **/ - public boolean isSecure(HttpServletRequest req); - - /** - * Determines whether the given request requires the user to be logged - * in. If this method returns true, the system will call - * getLoginURL to determine where to redirect the client to - * log in. - * - * @param req the request to check - * - * @return true if the given request requires the user to - * be logged in, false otherwise. - **/ - public boolean requiresLogin(HttpServletRequest req); - - /** - * Determines where to redirect the client to log in. The system calls - * this method if the user fails to log in and - * {@code requiresLogin(req)} is true. - * - * @param req The request for which the login URL is determined. - * - * @return the URL to which the client should be redirected to log in, - * never null. - **/ - public String getLoginURL(HttpServletRequest req); -} diff --git a/ccm-core/src/main/java/com/arsdigita/kernel/security/Util.java b/ccm-core/src/main/java/com/arsdigita/kernel/security/Util.java deleted file mode 100644 index ad22e4993..000000000 --- a/ccm-core/src/main/java/com/arsdigita/kernel/security/Util.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2015 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.kernel.security; - -import com.arsdigita.util.Classes; - -import java.util.Iterator; -import java.util.List; - - -/** - * - * @author Jens Pelzetter - */ -public class Util { - - private static final SecurityConfig s_conf = SecurityConfig.getConfig(); - - private static SecurityHelper s_helper = null; - - /** - * list of excluded extensions - */ - private static List s_exclExts = null; - // private static List s_exclExts = s_conf.getExcludedExtensions(); - - /** - * This class needs not to be instantiated. - */ - private Util() { - } - - /** - * Returns the security helper instance. - * - * @return the security helper instance. - * - * - */ - public static SecurityHelper getSecurityHelper() { - if (s_helper == null) { - s_helper = (SecurityHelper) Classes.newInstance( - DefaultSecurityHelper.class); - } - return s_helper; - } - - /** - * Set the security helper instance. package local - */ - static void setSecurityHelper(Object helper) { - s_helper = (SecurityHelper) helper; - } - - /** - * Get a using a callback. - * - * @return an HttpServletRequest - * - * @throws LoginException if an error occurs. - */ -// static HttpServletRequest getRequest(CallbackHandler handler) -// throws LoginException { -// -// try { -// HTTPRequestCallback cb = new HTTPRequestCallback(); -// handler.handle(new Callback[]{cb}); -// return cb.getRequest(); -// } catch (IOException e) { -// throw new KernelLoginException("IO error getting HTTP request", e); -// } catch (UnsupportedCallbackException e) { -// throw new KernelLoginException("Error getting HTTP request", e); -// } -// } - /** - * Returns an iterator over the list of excluded extensions. - * - * @return an iterator over the list of excluded extensions. - */ - // TODO: Currently method is used by CredentialLoginModule only. If no other - // class will use it, it is trivial and should directly be moved over there. - public static Iterator getExcludedExtensions() { - - // Alternativly we may introduce a setExkludedExtensions method as with - // setSecurityHelper and avoid a reference to config object here at all. - // Nevertheless, we shoul use it consistantly! - if (s_exclExts == null) { - s_exclExts = s_conf.getExcludedExtensions(); - // return java.util.Collections.EMPTY_LIST.iterator(); - } - return s_exclExts.iterator(); - - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/kernel/ui/ACSObjectSelectionModel.java b/ccm-core/src/main/java/com/arsdigita/kernel/ui/ACSObjectSelectionModel.java deleted file mode 100755 index cfaafa068..000000000 --- a/ccm-core/src/main/java/com/arsdigita/kernel/ui/ACSObjectSelectionModel.java +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.kernel.ui; - -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.BigDecimalParameter; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.parameters.LongParameter; - -import com.arsdigita.util.Assert; -import com.arsdigita.util.UncheckedWrapperException; - -import java.lang.reflect.InvocationTargetException; -import java.math.BigDecimal; - -import javax.servlet.ServletException; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.libreccm.core.CcmObjectRepository; - -/** - * Loads a subclass of an ACSObject from the database. By default, uses a - * {@code Long} state parameter in order to store and - * retrieve the item id. - * - * - * This class has been edited to work with {@link CcmObject} instead of - * {@code ACSObject}. Most methods etc. are the the same. This should work as - * before. Also variable names etc. have been changed to match the common Java - * styles. - * - * - *

- * The getSelectedKey(PageState state) method will return the - * BigDecimal id of the currently selected object. This method will return the - * id even if the object with this id does not actually exist. - * - *

- * The getSelectedObject(PageState state) method will return the - * object whose id is getSelectedKey(PageState state). If the - * object does not actually exist, the method will return null - * - *

- * Thus, it is possible to implement the following pattern: - *

class MyComponent extends SimpleComponent {
- *  ACSObjectSelectionModel m_model;
- *
- *  public MyComponent() {
- *    super();
- *    m_model = new ACSObjectSelectionModel("item_id");
- *  }
- *
- *  public void register(Page p) {
- *    super.register(p);
- *    p.addComponentStateParam(this, p.getStateParameter());
- *  }
- *
- *  public void doSomethingUseful(PageState s) {
- *    if (m_model.isSelected(s)) {
- *      CusomACSObject obj = (CustomACSObject)m_model.getSelectedObject(state);
- *      // Do something with obj..
- *    }
- *  }
- *}
- * - * Naturally, the ACSObjectSelectionModel could also be passed in - * as a parameter in the MyComponent constructor. In this case, it - * should be up to the parent of MyComponent to register the - * model's state parameter. - *

- * Advanced Usage: The ACSObjectSelectionModel is actually - * just a wrapper for a {@link SingleSelectionModel} which maintains the - * currently selected object's ID as a {@link BigDecimal}. By default, a new - * {@link ParameterSingleSelectionModel} is wrapped in this way; however, any - * {@link SingleSelectionModel} may be wrapped. Thus, it becomes possible to use - * the ACSObjectSelectionModel even if the currently selected ID is - * not stored in a state parameter. - * - * @see com.arsdigita.bebop.SingleSelectionModel - * @see com.arsdigita.bebop.ParameterSingleSelectionModel - * - * @author Stanislav Freidin - * @author Jens Pelzetter - */ -public class ACSObjectSelectionModel implements SingleSelectionModel { - - private RequestLocal loaded; - private Class javaClassName; -// private Constructor constructor; - private String objectType; - private SingleSelectionModel selectionModel; - - /** - * Construct a new ACSObjectSelectionModel. - * - * @param parameter The state parameter which should be used to store the - * object ID - */ - public ACSObjectSelectionModel(final LongParameter parameter) { - this(null, null, parameter); - } - - /** - * Construct a new ACSObjectSelectionModel. - * - * @param parameterName The name of the state parameter which will be used - * to store the object ID. - */ - public ACSObjectSelectionModel(final String parameterName) { - this(null, null, new LongParameter(parameterName)); - } - - /** - * Construct a new ACSObjectSelectionModel. - * - * @param model The {@link SingleSelectionModel} which will supply a - * {@link Long} ID of the currently selected object - */ - public ACSObjectSelectionModel(final SingleSelectionModel model) { - this(null, null, model); - } - - /** - * Construct a new ACSObjectSelectionModel - * - * @param javaClass The name of the Java class which represents the object. - * Must be a subclass of {@link CcmObject}. In addition, the class must have - * a constructor with a single {@code id} parameter. - * @param objectType The name of the persistence metadata object type which - * represents the ACS object. In practice, will often be the same as the - * javaClass. - * @param parameterName The name of the state parameter which will be used - * to store the object ID. - */ - public ACSObjectSelectionModel(final String javaClass, - final String objectType, - final String parameterName) { - this(javaClass, objectType, new LongParameter(parameterName)); - } - - /** - * Construct a new ACSObjectSelectionModel - * - * @param javaClass The name of the Java class which represents the object. - * Must be a subclass of {@link CcmObject}. In addition, the class must have - * a constructor with a single {@code id} parameter. - * @param objectType The name of the persistence metadata object type which - * represents the ACS object. In practice, will often be the same as the - * javaClass. - * @param parameter The state parameter which should be used to store the - * object ID - */ - public ACSObjectSelectionModel(final String javaClass, - final String objectType, - final LongParameter parameter) { - this(javaClass, - objectType, - new ParameterSingleSelectionModel(parameter)); - } - - /** - * Construct a new ACSObjectSelectionModel - * - * @param javaClass The name of the Java class which represents the object. - * Must be a subclass of {@link CcmObject}. In addition, the class must have - * a constructor with a single {@code id} parameter. - * @param objectType The name of the persistence metadata object type which - * represents the ACS object. In practice, will often be the same as the - * javaClass. - * @param model The {@link SingleSelectionModel} which will supply a - * {@link BigDecimal} ID of the currently selected object - */ - public ACSObjectSelectionModel(final String javaClass, - final String objectType, - final SingleSelectionModel model) { - loaded = new RequestLocal() { - @Override - protected Object initialValue(final PageState state) { - return Boolean.FALSE; - } - }; - - if (javaClass != null) { - // Cache the Class object and the constructor for further use - try { - this.javaClassName = Class.forName(javaClass); -// this.constructor = javaClassName.getConstructor(); - } catch (ClassNotFoundException | SecurityException ex) { - throw new UncheckedWrapperException(String.format( - "Problem loading class %s", javaClass), - ex); - } - } - - this.objectType = objectType; - this.selectionModel = model; - } - - /** - * Set the ID of the current object. The next time - * {@link #getSelectedObject(PageState)} is called, the object with the - * specified ID will be loaded from the database. - * - * @param state The page state - * @param key A {@link BigDecimal} primary key for the object, or a String - * representation of a BigDecimal, such as "42". - */ - @Override - public void setSelectedKey(final PageState state, final Object key) { - //BigDecimal newKey = convertToBigDecimal(key); - - loaded.set(state, Boolean.FALSE); - selectionModel.setSelectedKey(state, key); - } - - /** - * Return the object which was selected and loaded from the database, using - * the values supplied in the page state. May return null if - * isSelected(state) == false, or if the object was not found. - * - * @param state The page state - * @return The currently selected domain object, or null if no object is - * selected. - */ - public CcmObject getSelectedObject(final PageState state) { - - Long id = convertToLong(getSelectedKey(state)); - if (id == null) { - return null; - } - - return loadACSObject(state, id); - } - - /** - * Load the selected object for the first time. Child classes may choose to - * override this method in order to load the object in nonstandard ways. The - * default implementation merely instantiates an {@link CcmObject} whose ID - * is the passed-in key. - * - * @param state the current page state - * @param key the currently selected key; guaranteed to be non-null - * @return the object identified by the specified key - */ - protected CcmObject loadACSObject(final PageState state, final Object key) { - // Cheesy back-and-forth conversion to ensure that - // the result will be a BigDecimal, not a String or - // something else. Should go away when ListModel.getKey is - // changed to return an Object. - final Long objectId = convertToLong(key); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CcmObjectRepository repository = cdiUtil.findBean( - CcmObjectRepository.class); - - return repository.findById(objectId).get(); - - } - - /** - * Select the specified object. - * - * @param state The page state - * @param object The content item to set - */ - public void setSelectedObject(final PageState state, - final CcmObject object) { - CcmObject item = object; - - if (item == null) { - loaded.set(state, Boolean.FALSE); - selectionModel.setSelectedKey(state, null); - } else { - loaded.set(state, Boolean.TRUE); - selectionModel.setSelectedKey(state, item.getObjectId()); - } - } - - /** - * Determine if the attempt to load the selected object has been made yet. - * Child classes may use this method to perform request-local - * initialisation. - * - * @param state the page state - * @return true if the attempt to load the selected object has already been - * made, false otherwise - */ - public boolean isInitialized(final PageState state) { - return ((Boolean) loaded.get(state)); - } - - /** - * A utility function which creates a new object with the given ID. Uses - * reflection to create the instance of the class supplied in the - * constructor to this ACSObjectSelectionModel. If no class - * name was supplied in the constructor, an assertion failure will occur. - * - * @param id The id of the new item - this is ignored and the object will - * have a different id - * @return The newly created item - * @throws javax.servlet.ServletException If an error occurs. - * @deprecated This ignores the ID since ACSObject.setID is a no-op - */ - public CcmObject createACSObject(final Long id) throws ServletException { - return createACSObject(); - } - - /** - * A utility function which creates a new object with the given ID. Uses - * reflection to create the instance of the class supplied in the - * constructor to this ACSObjectSelectionModel. If no class - * name was supplied in the constructor, an assertion failure will occur. - * - * @return The newly created item - * @throws javax.servlet.ServletException If an error occurs. - */ - public CcmObject createACSObject() throws ServletException { - Assert.exists(javaClassName, Class.class); - - try { - final CcmObject object = (CcmObject) javaClassName.getDeclaredConstructor().newInstance(); - return object; - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { - throw new ServletException(ex); - } - } - - /** - * @return the Class of the content items which are produced by this model - */ - public Class getJavaClass() { - return javaClassName; - } - - /** - * @return The name of the object type of the content items which are - * produced by this model - */ - public String getObjectType() { - return objectType; - } - - /** - * @return the underlying {@link SingleSelectionModel} which maintains the - * ID of the selected object - */ - public SingleSelectionModel getSingleSelectionModel() { - return selectionModel; - } - - //////////////////////// - // - // Passthrough methods - /** - * Return true if there is a selected object. - * - * @param state represents the state of the current request - * @return true if there is a selected component. - */ - @Override - public boolean isSelected(final PageState state) { - return selectionModel.isSelected(state); - } - - /** - * Return the key that identifies the selected object. - * - * @param state the current page state - * @return the {@link Long} ID of the - * currently selected object, or null if no object is selected. - * - */ - @Override - public Object getSelectedKey(final PageState state) { - Object key = selectionModel.getSelectedKey(state); - return key; - } - - /** - * Clear the selection. - * - * @param state the current page state. - */ - @Override - public void clearSelection(final PageState state) { - selectionModel.clearSelection(state); - loaded.set(state, Boolean.FALSE); - } - - /** - * Add a change listener to the model. The listener's - * stateChanged is called whenever the selected key changes. - * - * @param listener a listener to notify when the selected key changes - */ - @Override - public void addChangeListener(final ChangeListener listener) { - selectionModel.addChangeListener(listener); - } - - /** - * Remove a change listener from the model. - * - * @param listener the listener to remove. - */ - @Override - public void removeChangeListener(final ChangeListener listener) { - selectionModel.removeChangeListener(listener); - } - - /** - * Return the state parameter which will be used to keep track of the - * currently selected key. Most likely, the parameter will be a - * {@link BigDecimalParameter}. - * - * @return The state parameter which should be used to keep track of the ID - * of the currently selected object, or null if the ID is computed in some - * other way - * @see SingleSelectionModel#getStateParameter() - */ - @Override - public ParameterModel getStateParameter() { - return selectionModel.getStateParameter(); - } - - private static Long convertToLong(final Object value) { - Long newValue = null; - - if (value instanceof Long) { - newValue = (Long) value; - } else if (value != null) { - newValue = Long.parseLong(value.toString()); - } - - return newValue; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/mail/Mail.java b/ccm-core/src/main/java/com/arsdigita/mail/Mail.java index b5e85307b..5e3a814e3 100644 --- a/ccm-core/src/main/java/com/arsdigita/mail/Mail.java +++ b/ccm-core/src/main/java/com/arsdigita/mail/Mail.java @@ -18,7 +18,6 @@ */ package com.arsdigita.mail; -import com.arsdigita.util.MessageType; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -37,6 +36,7 @@ import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.stream.IntStream; + import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.activation.URLDataSource; @@ -49,6 +49,7 @@ import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/ccm-core/src/main/java/com/arsdigita/mail/MailConfig.java b/ccm-core/src/main/java/com/arsdigita/mail/MailConfig.java index 17e89a617..eb37a0c90 100755 --- a/ccm-core/src/main/java/com/arsdigita/mail/MailConfig.java +++ b/ccm-core/src/main/java/com/arsdigita/mail/MailConfig.java @@ -18,12 +18,12 @@ */ package com.arsdigita.mail; -import com.arsdigita.util.UncheckedWrapperException; import org.libreccm.cdi.utils.CdiUtil; import org.libreccm.configuration.Configuration; import org.libreccm.configuration.ConfigurationManager; import org.libreccm.configuration.Setting; +import org.libreccm.core.UnexpectedErrorException; import java.io.IOException; import java.net.URL; @@ -80,18 +80,26 @@ public final class MailConfig { properties.load(new URL(System .getProperty("ccm.mail.config")).openStream()); } catch (IOException ex) { - throw new UncheckedWrapperException(String.format( - "Unable to retrieve properties for JavaMail from \"%s\".", - System.getProperty("ccm.mail.config")), ex); + throw new UnexpectedErrorException( + String.format( + "Unable to retrieve properties for JavaMail " + + "from \"%s\".", + System.getProperty("ccm.mail.config")), + ex + ); } } } else { try { properties.load(new URL(javaMailPropertiesFile).openStream()); } catch (IOException ex) { - throw new UncheckedWrapperException(String.format( - "Unable to retrieve properties for JavaMail from \"%s\".", - javaMailPropertiesFile), ex); + throw new UnexpectedErrorException( + String.format( + "Unable to retrieve properties for JavaMail " + + "from \"%s\".", + javaMailPropertiesFile), + ex + ); } } diff --git a/ccm-core/src/main/java/com/arsdigita/util/MessageType.java b/ccm-core/src/main/java/com/arsdigita/mail/MessageType.java similarity index 94% rename from ccm-core/src/main/java/com/arsdigita/util/MessageType.java rename to ccm-core/src/main/java/com/arsdigita/mail/MessageType.java index 82db306cf..3fa7cd57a 100755 --- a/ccm-core/src/main/java/com/arsdigita/util/MessageType.java +++ b/ccm-core/src/main/java/com/arsdigita/mail/MessageType.java @@ -16,13 +16,12 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ -package com.arsdigita.util; +package com.arsdigita.mail; /** * Special MIME types useful for typing Message objects. * * @author Ron Henderson - * @version $Id: MessageType.java 287 2005-02-22 00:29:02Z sskracic $ */ public interface MessageType { diff --git a/ccm-core/src/main/java/com/arsdigita/runtime/CCMResourceManager.java b/ccm-core/src/main/java/com/arsdigita/runtime/CCMResourceManager.java deleted file mode 100644 index ed9cebdcd..000000000 --- a/ccm-core/src/main/java/com/arsdigita/runtime/CCMResourceManager.java +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * Copyright (C) 2009 Peter Boy (pb@zes.uni-bremen.de) All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.runtime; - -import com.arsdigita.util.UncheckedWrapperException; - -import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - *

CCMResourceManager Runtime environment repository object, stores essential - * properties of the runtime environment and provides them on request.

- * - *

Currently, is is limited to the

- *
    - *
  • base directory of the running webapp
  • - *
- *

It provides public methods to make the properties available.

- * - *

The singleton is initialised

- *
    - *
  • either during startup of the container (called by - * @see com.arsdigita.web.CCMApplicationContextListener (must be configured in - * web.xml)
  • - *
  • or by the command line system at the beginning of the processing (esp. - * package @see com.arsdigita.packaging.Mastertool).
  • - *
- *

Currently as a fall back mechanism the environmant Variable CCM_HOME is - * evaluated and used a last resort, if no initialisation has been done when - * a getter is first called.

- * - *

It is essential for the proper working of CCM that CCMResourceManager is - * initialised before any operation starts, as it is the case with the Startup - * class of the runtime package, which is responsible for organising database - * access.

- * - * - *

Subject to change!

- * - * A similiar task is performed by com.arsdigita.util.ResourceManager - * - * @author Justin Ross <jross@redhat.com> - * rewritten by - * @author pboy <pboy@barkhof.uni-bremen.de> - */ -public final class CCMResourceManager { - - private static final Logger LOGGER = LogManager.getLogger(CCMResourceManager.class); - - private static CCMResourceManager s_ccm; - - /** - * Full Pathname of the application base directory - * (document root in apache terminology) - */ - private static File m_baseDir; - - - /** - * Location of the registry in the applications directory tree - * as offset from the base directory - */ - // currently not used, should be refactored as File object for the sake of - // operating system independency! - // public static final String registryPath = "/WEB-INF/conf/registry"; - // public static final File registryPath = null; // currently not used, work in progress - - /* ************ Section singleton handlers ***************** */ - - /** - * Sets the singleton configuration property for the runtime - * environment. - * - */ - public static final synchronized void setBaseDirectory(String baseDirName) { - if (s_ccm == null) { - s_ccm = new CCMResourceManager(); - s_ccm.storeBaseDir(baseDirName); - } - else { - // baseDir already set, silently discard - LOGGER.info("baseDir already set as " + m_baseDir + ". Discarded."); - } - } - - /** - * Returns the singleton configuration property for the runtime - * environment. - * - * @return The RuntimeConfig record; it cannot be null - */ - public static final synchronized File getBaseDirectory() { - if (s_ccm == null) { - // should never happen, setBaseDirectory has to be executed first - // we try to resolve the problem in fetchBaseDir by search for - // a runtime environment variable (the old way). - s_ccm = new CCMResourceManager(); - } - - return s_ccm.fetchBaseDir(); - } - - /* ************ Section singleton handlers END ************** */ - - - /* ************ Constructors Section ************** */ - - /** - * Following the singleton pattern: Private constructor to prevent other - * clients from instantiating the class (and the compiler from generating - * a default public constructor). - */ - private CCMResourceManager() { } - - /* ************ Constructors Section END ************** */ - - - /* ************ Public getter/setter Section *************** */ - - /** - * Retrieve the homeDir as URL. - * - * Note! API changed. @see getHomeDirectory() - * May be removed in the future! - * - * @return Directory location in the servers file system as URL object. - */ - public static final URL getHomeURL() { - try { - return CCMResourceManager.getHomeDirectory().toURL(); - } catch (MalformedURLException e) { - throw new UncheckedWrapperException(e); - } - } - - /** - * Retrieve the homeDir, which is the location of the servlet server's - * servlet container directory in the file system of the server machine, - * as File object. - * - * Note! API changed! - * - * Originally it is used to determine all file object locations of a - * CCM installation, during the installation step as well as - * while running the application inside a servlet container. The CCM installation - * of a servlet container used to use a non-standard layout. It is based upon a - * system wide environment variable CCM_HOME to determine the home directory. - * - * The dependency from a system wide environment variable prevents a servlet - * container to run multiple instances of CCM. In addition to it CCM will - * be migrated to be installable in a standard way to a standard container. - * Therefore all file locations will be given relative to the applications - * directory (the baseDirectory @see m_baseDir). - * - * - * Method getHomeDirectory() is preserved during the transition phase. - * It may be removed in the future! Or it may be moved to - * c.ad.packaging for assistence of the installation step only. - * - * MODIFIED: - * CCM_HOME is now interpreted as the path to the applications base - * directory (web application context). - * - * @return Directory location in the servers file system as File object. - */ - static final File getHomeDirectory() { - - String home = System.getProperty("ccm.home"); - - if (home == null) { - throw new IllegalStateException - ("The ccm.home system property is null or not defined"); - } - - // make a guess, wether it is old style (i.e. referring to the containers - // base directory and therefor does not contain the webapps part) or - // new style referring to the apps base directory (and therefor containing - // the webapps part) - if (home.indexOf("webapps") > 0 ){ - // should be new style - } - else { - // presumably old style, add path to standard context name - home += "/webapps/ROOT"; - } - - File file = new File(home); - -// No need to require that home exists (indeed, during install it will not). -// Should be created by invoking method if not. -// if (!file.exists()) { -// throw new IllegalStateException -// ("The file given in the ccm.home system property " + -// "does not exist"); -// } - - if (!file.isDirectory()) { - throw new IllegalStateException - ("The file: " + home + " given in the ccm.home system property" - + " is not a directory"); - } - - return file; - } - - /** - * Provide the configDirectory as URL. - * - * @see getConfigDirectory() for details. - * - * Note! API changed! - * - * @return Directory location in the servers file system as URL object. - */ - public static final URL getConfigURL() { - try { - return CCMResourceManager.getConfigDirectory().toURL(); - } catch (MalformedURLException e) { - throw new UncheckedWrapperException(e); - } - } - - /** - * Retrieve the configDir, which is the location of the configuration - * database root (registry) in the file system tree of the server machine, - * as File object. - - * - * @return Directory location in the servers file system as File object. - */ - public static final File getConfigDirectory() { - - // Keep this in sync with informational attribut @see registryPath ! - File confdir = new File(new File(new File(CCMResourceManager.getBaseDirectory(), - "WEB-INF"),"conf"), "registry"); - - if (!confdir.exists()) { - if (!confdir.mkdirs()) { - throw new IllegalStateException - ("Could not create configuration directory: " + confdir); - } - } - if (!confdir.isDirectory()) { - throw new IllegalStateException - ("Configuration directory value is not a directory: " + confdir); - } - - return confdir; - } - - /** - * getWorkDirectory retrieves and eventually creates an internal directory - * in the servlet container for temporary files (work files), where subsystems - * may create subdirectories for internal use (e.g. Lucene search enginge or - * the PublishToFile machinery). - * - * The containers work file directory could be used as well, but may be - * inappropriate in case of confidential data. - * - * @return Directory location in the servers file system as File object. - */ - public static final File getWorkDirectory() { - File file = new File(new File(CCMResourceManager.getBaseDirectory(), - "WEB-INF"),"work"); - if (!file.exists()) { - if (!file.mkdirs()) { - throw new IllegalStateException - ("Could not create work directory: " + file); - } - } - if (!file.isDirectory()) { - throw new IllegalStateException - ("Work directory value is not a directory: " + file); - } - return file; - } - - /* ************ Public getter/setter Section END *************** */ - - - /* ************ Private Worker Section *************** */ - - /** - * Stores the passed in String as File object. - * - * @param baseDirName String containing the path, must not be null - */ - private final void storeBaseDir(String baseDirName) { - - LOGGER.debug("storeBaseDir: BaseDir name is given as " + baseDirName ); - m_baseDir = new File(baseDirName); - - // eventually: check if dir exists, create it if not. - if (!m_baseDir.exists()) { - if (!m_baseDir.mkdirs()) { - throw new IllegalStateException - ("Could not create base directory: " + m_baseDir); - } - } - if (!m_baseDir.isDirectory()) { - throw new IllegalStateException - ("Base directory value is not a directory: " + m_baseDir); - } - - } - - /** - * Retrieves the stored BaseDir File object. - * - * @return Base directory location in the servers file system as File object. - */ - private final File fetchBaseDir() { - - if (m_baseDir == null) { - // should never happen, but we try to cope with it anyway by - // falling back to getHomeDirectory() and the system wide - // environment variable. - // During transition phase only! Must be removed when the new - // standard compliant installation method is fully in place - // MODIFIED - // HomeDirectory now specifies the applications context dir. - m_baseDir = CCMResourceManager.getHomeDirectory(); - - // eventually: check if dir exists, create it if not. - if (!m_baseDir.exists()) { - if (!m_baseDir.mkdirs()) { - throw new IllegalStateException - ("Could not create base directory: " + m_baseDir); - } - } - if (!m_baseDir.isDirectory()) { - throw new IllegalStateException - ("Base directory value is not a directory: " + m_baseDir); - } - } - - return m_baseDir; - - } - - /* ************ Private Worker Section END *************** */ - - -} diff --git a/ccm-core/src/main/java/com/arsdigita/search/SearchConstants.java b/ccm-core/src/main/java/com/arsdigita/search/SearchConstants.java deleted file mode 100644 index 34d2fe283..000000000 --- a/ccm-core/src/main/java/com/arsdigita/search/SearchConstants.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.search; - -/** - * - * @author Jens Pelzetter - */ -public final class SearchConstants { - - private SearchConstants() { - //Nothing - } - - /** - * Constant for search XML namespace prefix - */ - public static final String XML_PREFIX = "search:"; - /** - * Constant for search XML namespace URL - */ - public static final String XML_NS = "http://rhea.redhat.com/search/1.0"; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/search/ui/BaseQueryComponent.java b/ccm-core/src/main/java/com/arsdigita/search/ui/BaseQueryComponent.java deleted file mode 100755 index 87909dd38..000000000 --- a/ccm-core/src/main/java/com/arsdigita/search/ui/BaseQueryComponent.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.search.ui; - -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormModel; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.globalization.Globalization; -import com.arsdigita.xml.Element; - -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.search.SearchConstants; - -import java.util.Set; -import java.util.HashSet; -import java.util.Iterator; -import org.apache.logging.log4j.LogManager; - -import org.apache.logging.log4j.Logger; - -/** - * This is a simple extension of the QueryComponent that provides management of - * the 'terms' parameter and uses FilterGenerators to populate a query - * specification - *

- * Typical use would be as follows: - *

- * Form f = new Form("search");
- * BaseQueryComponent q = new BaseQueryComponent();
- * q.add(new ObjectTypeFilterComponent("com.arsdigita.kernel.User");
- * q.add(new PermissionGenerator(PrivilegeDescriptor.READ));
- * q.add(new Submit("Go"));
- * f.add(q);
- * 
- */ -public class BaseQueryComponent extends QueryComponent { - - private static final Logger LOGGER = LogManager.getLogger( - BaseQueryComponent.class); - - private Set filters; - private Form form; - private final StringParameter termsParameter = new StringParameter("terms"); - - /** - * Creates a new query component - */ - public BaseQueryComponent() { - - super("query"); - filters = new HashSet(); - } - - @Override - public void register(final Page page) { - super.register(page); - } - - @Override - public void register(final Form form, final FormModel formModel) { - LOGGER.debug("Adding {} to form model...", termsParameter.getName()); - - termsParameter.setPassIn(true); - formModel.addFormParam(termsParameter); - this.form = form; - } - - /** - * Gets the current search terms - * - * @return - */ - @Override - protected String getTerms(final PageState state) { - - final FormData formData = form.getFormData(state); - - - if (formData == null) { - return null; - } else { - final ParameterData data = formData.getParameter(termsParameter. - getName()); - LOGGER.debug("Search terms were: {}", data.getValue()); - - return (String) data.getValue(); - } - } - - /** - * - * @param state - * @param parent - */ - @Override - public void generateXML(final PageState state, final Element parent) { - final Element content = generateParent(parent); - - final Element terms = new Element(SearchConstants.XML_PREFIX + "terms", - SearchConstants.XML_NS); - terms.addAttribute("param", termsParameter.getName()); - terms.addAttribute("value", - Globalization.decodeParameter( - state.getRequest(), - termsParameter.getName())); - generateErrorXML(state, terms); - content.addContent(terms); - - generateChildrenXML(state, content); - } - - protected void generateErrorXML(final PageState state, - final Element parent) { - final FormData formData = form.getFormData(state); - if (formData == null) { - return; - } - - final Iterator iterator = formData.getErrors(termsParameter.getName()); - while (iterator.hasNext()) { - final Element error = new Element( - SearchConstants.XML_PREFIX + "error", - SearchConstants.XML_NS); - error.setText((String) ((GlobalizedMessage) iterator.next()). - localize(state.getRequest()) - ); - parent.addContent(error); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/search/ui/QueryComponent.java b/ccm-core/src/main/java/com/arsdigita/search/ui/QueryComponent.java deleted file mode 100755 index 567355f97..000000000 --- a/ccm-core/src/main/java/com/arsdigita/search/ui/QueryComponent.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.search.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.search.SearchConstants; - -import org.apache.lucene.search.Query; -import org.hibernate.search.query.dsl.QueryBuilder; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.libreccm.search.SearchManager; - -/** - * A base class for generating a query specification from the state. Subclasses - * must implement two methods, one for getting the query terms, the other for - * getting a set of filter specs. - */ -public abstract class QueryComponent extends SimpleContainer - implements QueryGenerator { - - public QueryComponent(final String name) { - setTag(SearchConstants.XML_PREFIX + name); - setNamespace(SearchConstants.XML_NS); - } - - /** - * Determine if a query specification is available - * - * @return true if the user has entered some search terms - */ - @Override - public boolean hasQuery(final PageState state) { - String terms = getTerms(state); - - return (terms != null && !"".equals(terms)); - } - - /** - * Returns the current query specification - */ - @Override - public Query getQuerySpecification(final PageState state) { - - final String terms = getTerms(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final SearchManager searchManager = cdiUtil. - findBean(SearchManager.class); - - final QueryBuilder queryBuilder = searchManager - .createQueryBuilder(CcmObject.class); - - return queryBuilder - .keyword().onFields("displayName", - "summary", - "description", - "title") - .matching(terms) - .createQuery(); - - } - - /** - * Returns the current query terms - * - * @param state - * @return the query terms, or null - */ - protected abstract String getTerms(PageState state); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/search/ui/QueryGenerator.java b/ccm-core/src/main/java/com/arsdigita/search/ui/QueryGenerator.java deleted file mode 100755 index cf4be3acd..000000000 --- a/ccm-core/src/main/java/com/arsdigita/search/ui/QueryGenerator.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.search.ui; - -import com.arsdigita.bebop.PageState; -import org.apache.lucene.search.Query; - -/** - * This interface provides the API for retrieving a query specification based on - * the current state. The ResultsPane component uses an instance of this class - * to retrieve the query spec and display a list of results - * - * @see com.arsdigita.search.ui.QueryComponent - * @see com.arsdigita.search.ui.ResultsPane - */ -public interface QueryGenerator { - - /** - * Determines whether a query spec currently exists. - * - * @param state The current page state. - * @return true if a query spec is available. - */ - boolean hasQuery(PageState state); - - /** - * Retrieves the current query spec. This method can only be called if - * hasQuery(state) returns true. - * - * @param state The current page. - * @return The query - */ - Query getQuerySpecification(PageState state); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/search/ui/ResultsPane.java b/ccm-core/src/main/java/com/arsdigita/search/ui/ResultsPane.java deleted file mode 100755 index 41eff76f9..000000000 --- a/ccm-core/src/main/java/com/arsdigita/search/ui/ResultsPane.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.search.ui; - -import com.arsdigita.bebop.SimpleComponent; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.IntegerParameter; -import com.arsdigita.globalization.Globalization; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.search.SearchConstants; -import com.arsdigita.util.UncheckedWrapperException; - -import com.arsdigita.xml.Element; -import com.arsdigita.xml.XML; - -import com.arsdigita.web.URL; -import com.arsdigita.web.ParameterMap; -import com.arsdigita.web.Web; - -import java.beans.BeanInfo; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Arrays; - -import java.util.Iterator; -import java.util.List; -import java.util.Optional; - -import org.apache.logging.log4j.LogManager; - -import org.apache.logging.log4j.Logger; -import org.apache.lucene.search.Query; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.libreccm.search.SearchManager; - -public class ResultsPane extends SimpleComponent { - - private static final Logger LOGGER = LogManager.getLogger(ResultsPane.class); - public static final int PAGE_SIZE = 10; - - private final int pageSize = PAGE_SIZE; - - private final QueryGenerator queryGenerator; - private IntegerParameter pageNumber; - private boolean relative; - //jensp 2014-03-04 Allow using classes to set a suitable info messages. - private GlobalizedMessage searchHelpMsg; - private GlobalizedMessage noResultsMsg; - - public ResultsPane(final QueryGenerator query) { - pageNumber = new IntegerParameter("page"); - relative = false; - this.queryGenerator = query; - } - - /** - * Determines whether the links to the search results will be relative or - * absolute. The default is absolute. - * - * @param relative - */ - public void setRelativeURLs(final boolean relative) { - this.relative = relative; - } - - public void setSearchHelpMsg(final GlobalizedMessage msg) { - searchHelpMsg = msg; - } - - public void setNoResultsMsg(final GlobalizedMessage msg) { - noResultsMsg = msg; - } - - @Override - public void generateXML(final PageState state, final Element parent) { - if (!queryGenerator.hasQuery(state)) { - - LOGGER.debug("No query available, skipping XML generation"); - - final Element content = new Element( - SearchConstants.XML_PREFIX + "results", - SearchConstants.XML_NS); - final Element info = content.newChildElement("info"); - if (searchHelpMsg == null) { - info.setText( - "To search for content items, please enter at least 3 letters into the search field. You can narrow the result by using additional parameters."); - } else { - //info.setText(GlobalizationUtil.globalize("cms.ui.search_help").localize().toString()); - info.setText(searchHelpMsg.localize().toString()); - } - - parent.addContent(content); - return; - } - - final Query spec = queryGenerator.getQuerySpecification(state); - final SearchManager searchManager = CdiUtil.createCdiUtil().findBean( - SearchManager.class); - final List results = (List) searchManager. - executeQuery(spec); - LOGGER.debug("Got result list with {} items.", results.size()); - if (results.isEmpty()) { - final long objectCount = results.size(); - final int pageCount = (int) Math.ceil((double) objectCount - / (double) pageSize); - - final Integer page = (Integer) pageNumber.transformValue(state. - getRequest()); - int pageNum; - if (page == null) { - pageNum = 1; - } else if (page < 1) { - pageNum = 1; - } else if (page > pageCount) { - if (pageCount == 0) { - pageNum = 1; - } else { - pageNum = page; - } - } else { - pageNum = page; - } - - final long begin = ((pageNum - 1) * pageSize); - final long count = Math.min(pageSize, (objectCount - begin)); - final long end = begin + count; - - final Iterator iterator = results - .subList((int) begin, (int) begin + (int) count) - .iterator(); - - final Element content = new Element( - SearchConstants.XML_PREFIX + "results", - SearchConstants.XML_NS); - exportAttributes(content); - - LOGGER.debug("Paginator stats\n" - + " page number: {}\n" - + " page count.: {}\n" - + " page size..: {}\n" - + " begin......: {}\n" - + " end........: {}\n" - + " count : {}", - pageNum, - pageCount, - pageSize, - begin, - end, - objectCount); - - content.addContent(generatePaginatorXML(state, - pageNumber.getName(), - pageNum, - pageCount, - pageSize, - begin, - end, - objectCount)); - content.addContent(generateDocumentsXML(state, iterator)); - - parent.addContent(content); - } else { - // No search result, so we don't need a paginator, but we want - // to inform the user, that there are no results for this search - final Element content = new Element( - SearchConstants.XML_PREFIX + "results", - SearchConstants.XML_NS); - final Element info = content.newChildElement("info"); -// info.setText(GlobalizationUtil.globalize("cms.ui.search_no_results").localize().toString()); - if (noResultsMsg == null) { - info.setText("Sorry. Your search returned 0 results."); - } else { - info.setText(noResultsMsg.localize().toString()); - } - parent.addContent(content); - } - } - - protected Element generatePaginatorXML(final PageState state, - final String pageParam, - final int pageNumber, - final int pageCount, - final int pageSize, - final long begin, - final long end, - final long objectCount) { - final Element paginator = new Element( - SearchConstants.XML_PREFIX + "paginator", - SearchConstants.XML_NS); - final URL url = Web.getWebContext().getRequestURL(); - - final ParameterMap parameterMap = new ParameterMap(); - final Iterator current = url.getParameterMap().keySet().iterator(); - while (current.hasNext()) { - final String key = (String) current.next(); - if (key.equals(pageParam)) { - continue; - } - parameterMap.setParameterValues( - key, decodeParameters(url.getParameterValues(key), state)); - } - - paginator.addAttribute("pageParam", this.pageNumber.getName()); - paginator.addAttribute("baseURL", URL.there(url.getPathInfo(), - parameterMap).toString()); - paginator.addAttribute("pageNumber", XML.format(pageNumber)); - paginator.addAttribute("pageCount", XML.format(pageCount)); - paginator.addAttribute("pageSize", XML.format(pageSize)); - paginator.addAttribute("objectBegin", XML.format(begin + 1)); - paginator.addAttribute("objectEnd", XML.format(end)); - paginator.addAttribute("objectCount", XML.format(objectCount)); - - return paginator; - } - - private String[] decodeParameters(final String[] parameters, - final PageState state) { - - final String[] decoded = new String[parameters.length]; - - for (int i = 0; i < parameters.length; i++) { - decoded[i] = decodeParameter(parameters[i], state); - } - - return decoded; - } - - private String decodeParameter(final String parameter, - final PageState state) { - String re = state.getRequest().getParameter( - Globalization.ENCODING_PARAM_NAME); - - if ((re == null) || (re.isEmpty())) { - re = Globalization.getDefaultCharset(); - } - - if ((parameter == null) || (parameter.isEmpty())) { - return parameter; - } else if (Globalization.getDefaultCharset(state.getRequest()). - equals(re)) { - return parameter; - } else { - try { - return new String(parameter.getBytes(Globalization. - getDefaultCharset( - state.getRequest())), re); - } catch (UnsupportedEncodingException ex) { - LOGGER.warn("Unsupported encoding.", ex); - return parameter; - } - } - } - - protected Element generateDocumentsXML(final PageState state, - final Iterator results) { - - final Element documents = new Element( - SearchConstants.XML_PREFIX + "documents", - SearchConstants.XML_NS); - - LOGGER.debug("Outputting documents"); - - while (results.hasNext()) { - final CcmObject doc = results.next(); - LOGGER.debug("Current document {} {}", - doc.getObjectId(), - doc.getDisplayName()); - - documents.addContent(generateDocumentXML(state, doc)); - } - - return documents; - } - - private Optional getSummary(final CcmObject doc) { - final BeanInfo beanInfo; - try { - beanInfo = Introspector.getBeanInfo(doc.getClass()); - } catch (IntrospectionException ex) { - throw new UncheckedWrapperException(ex); - } - - final Optional propertyDesc - = Arrays.stream(beanInfo. - getPropertyDescriptors()) - .filter(descriptor -> { - return "description".equals(descriptor.getName()) - || "summary".equals(descriptor. - getName()); - }) - .findFirst(); - - if (propertyDesc.isPresent()) { - final Method readMethod = propertyDesc.get().getReadMethod(); - final String summary; - try { - summary = (String) readMethod.invoke(doc); - } catch (IllegalAccessException - | IllegalArgumentException - | InvocationTargetException ex) { - throw new UncheckedWrapperException(ex); - } - return Optional.of(summary); - } else { - return Optional.empty(); - } - } - - protected Element generateDocumentXML(final PageState state, - final CcmObject doc) { - final Element entry = new Element(SearchConstants.XML_PREFIX + "object", - SearchConstants.XML_NS); - - final Optional summary = getSummary(doc); - - entry.addAttribute("id", XML.format(doc.getObjectId())); - entry.addAttribute("uuid", XML.format(doc.getUuid())); -// entry.addAttribute("url", XML.format(relative ? url.getPath() + "?" -// + url.getQuery() -// : url.toString())); - entry.addAttribute("title", XML.format(doc.getDisplayName())); - if (summary.isPresent()) { - entry.addAttribute("summary", XML.format(summary)); - } - -// entry.addAttribute("locale", XML.format(doc.getLocale())); - -// Date creationDate = doc.getCreationDate(); -// if (creationDate != null) { -// entry.addAttribute("creationDate", XML.format( -// creationDate.toString())); -// } -// Party creationParty = doc.getCreationParty(); -// if (creationParty != null) { -// entry.addAttribute("creationParty", -// XML.format(creationParty.getDisplayName())); -// } -// -// Date lastModifiedDate = doc.getLastModifiedDate(); -// if (lastModifiedDate != null) { -// entry.addAttribute("lastModifiedDate", -// XML.format(lastModifiedDate)); -// } -// Party lastModifiedParty = doc.getLastModifiedParty(); -// if (lastModifiedParty != null) { -// entry.addAttribute("lastModifiedParty", -// XML.format(lastModifiedParty.getDisplayName())); -// } - -// LOGGER.debug( -// "about to add the contentSectionName from search index Doc to search result xml"); -// entry.addAttribute("contentSectionName", XML.format(doc. -// getContentSection())); - - return entry; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/ApplicationOIDPatternGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/ApplicationOIDPatternGenerator.java deleted file mode 100755 index 833526d19..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/ApplicationOIDPatternGenerator.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - - -import com.arsdigita.web.Web; - -import org.libreccm.web.CcmApplication; - -import javax.servlet.http.HttpServletRequest; - -import java.net.URLEncoder; - -/** - * This looks for the current application and will return its OID if - * it is available - */ -public class ApplicationOIDPatternGenerator implements PatternGenerator { - - /** - * Looks up the current application and returns its OID as String. - * The Return type is (unneccessarily) String[] due to the current API, but - * currently never returns more than just one value (one OID). - * - * @param key placeholder from the pattern string, without surrounding - * colons, constantly "oid" here. - * @param req current HttpServletRequest - * @return OID as String in an Array of Strings. This array is never longer - * as one element. - */ - @Override - public String[] generateValues(String key, - HttpServletRequest req) { - - final CcmApplication application = Web.getWebContext().getApplication(); - - if (application != null) { - String[] oid = new String[1]; - // FR: better URLEncode this - oid[0] = URLEncoder.encode(Long.toString(application.getObjectId())); - return oid; - } else { - return new String[] {}; - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/ApplicationPatternGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/ApplicationPatternGenerator.java deleted file mode 100755 index dd9f2ccb5..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/ApplicationPatternGenerator.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -// import com.arsdigita.dispatcher.DispatcherHelper; -// import com.arsdigita.sitenode.SiteNodeRequestContext; -// import com.arsdigita.kernel.SiteNode; -import com.arsdigita.web.Web; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.libreccm.web.CcmApplication; - -/** - * Generates a set of pattern values based on the application key, eg - * content-center, content-section. - */ -public class ApplicationPatternGenerator implements PatternGenerator { - - /** - * Private logger instance for debugging purpose - */ - private static final Logger LOGGER = LogManager.getLogger( - PatternGenerator.class); - - /** - * Implementation of the Interface class. - * - * @param key - * @param req - * - * @return - */ - @Override - public String[] generateValues(String key, - HttpServletRequest req) { - - LOGGER.debug("Processing Application with key: " + key); - - final CcmApplication app = Web.getWebContext().getApplication(); - if (app != null) { - String[] returnValue = {app.getApplicationType()}; - LOGGER.debug("Found application >>" + returnValue - + "<< in Application."); - return returnValue; - } - - LOGGER.debug("ApplicationType for >>" + key - + "<< not found. Trying SiteNodes instead."); - - throw new IllegalArgumentException( - "No ApplicationType found for type name " + key); - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/HostPatternGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/HostPatternGenerator.java deleted file mode 100755 index 3b51c499c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/HostPatternGenerator.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import com.arsdigita.util.servlet.HttpHost; -import com.arsdigita.web.WebConfig; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * Generates a set of patterns corresponding to the current host name. (actually - * just retrieves the current hostname from configuration file, StringArray - * returned is for sake of methods consistency) - */ -public class HostPatternGenerator implements PatternGenerator { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int the runtime environment and - * set com.arsdigita.templating.HostPatternGenerator=DEBUG by uncommenting - * or adding the line. - */ - private static final Logger LOGGER = LogManager.getLogger( - HostPatternGenerator.class); - - /** - * Looks up the hostname from configuration and returns it as String. The - * Return type is (unneccessarily) String[] due to the current API, but - * currently never returns more than just one value (one hostname:port). - * - * @param key placeholder from the pattern string, without surrounding - * colons, constantly "host" here. - * @param req current HttpServletRequest - * - * @return Hostname (including port if any), retrieved from CCM - * configuration - */ - @Override - public String[] generateValues(String key, - HttpServletRequest req) { - final HttpHost host = new HttpHost(WebConfig.getConfig().getHostName(), - WebConfig.getConfig().getHostPort()); - final String hostName = host.toString(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Generating Values for key: " + key + " [" - + "Hostname retrieved: >>" + hostName + "<<]"); - } - - return new String[]{host.toString()}; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/LocalePatternGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/LocalePatternGenerator.java deleted file mode 100755 index e1a9cb879..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/LocalePatternGenerator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import com.arsdigita.dispatcher.DispatcherHelper; - -import javax.servlet.http.HttpServletRequest; - -/** - * Generates a pattern based on the request negotiated locale - * in com.arsdigita.kernel.KernelContext - */ -public class LocalePatternGenerator implements PatternGenerator { - public String[] generateValues(String key, - HttpServletRequest req) { - return new String[] { - DispatcherHelper.getNegotiatedLocale().toString() - }; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/OutputTypePatternGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/OutputTypePatternGenerator.java deleted file mode 100755 index 68797bf33..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/OutputTypePatternGenerator.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import javax.servlet.http.HttpServletRequest; - -/** - * Generates a pattern for based on the outputType request - * parameter - */ -public class OutputTypePatternGenerator implements PatternGenerator { - public String[] generateValues(String key, - HttpServletRequest req) { - String query = req.getQueryString(); - if (query != null) { - int typeIndex = query.indexOf("outputType"); - if (typeIndex > -1) { - int secondaryIndex = query.indexOf("&", typeIndex); - String type = null; - if (secondaryIndex > -1) { - type = query.substring(typeIndex, secondaryIndex); - } else { - type = query.substring(typeIndex); - } - type = type.toLowerCase(); - if (type.indexOf("text/javascript") > -1) { - return new String[] { "text-javascript" }; - } else if (type.indexOf("text/html") > -1) { - return new String[] { "text-html" }; - } else if (type.indexOf("text/plain") > -1) { - return new String[] { "text-plain" }; - } - } - } - - return new String[] { }; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/PatternGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/PatternGenerator.java deleted file mode 100755 index 4b45dac28..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/PatternGenerator.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import javax.servlet.http.HttpServletRequest; - - -public interface PatternGenerator { - - public String[] generateValues(String name, - HttpServletRequest request); -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/PatternStylesheetResolver.java b/ccm-core/src/main/java/com/arsdigita/templating/PatternStylesheetResolver.java deleted file mode 100755 index 1dd0ad694..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/PatternStylesheetResolver.java +++ /dev/null @@ -1,440 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import com.arsdigita.util.StringUtils; -import com.arsdigita.util.UncheckedWrapperException; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.LineNumberReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.FileNotFoundException; -import java.io.IOException; - -import java.net.URL; -import java.net.MalformedURLException; - -import java.util.HashMap; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.LinkedList; - -import javax.servlet.http.HttpServletRequest; - - - -/** - *

- * This stylesheet resolver is used by the *PresentationManager - * class to work out which XSLT stylesheet to apply to the current Bebop XML - * output. - *

- * - *

- * This particular stylesheet resolver uses a flat file containing a list of - * stylesheet patterns, one per line. The file is called - * WEB-INF/resources/stylesheet-paths.txt. Such a file could look - * like this: - *

- * - *
- * # Comments and empty lines are ignored.
- *
- * /packages/aplaws/xsl/::vhost::/cms_::locale::.xsl
- * /packages/aplaws/xsl/::vhost::/cms.xsl
- * /packages/aplaws/xsl/default/cms_::locale::.xsl
- * /packages/aplaws/xsl/default/cms.xsl
- * /packages/content-section/xsl/cms_::locale::.xsl
- * /packages/content-section/xsl/cms.xsl
- * 
- * - *

- * You may use the com.arsdigita.templating.stylesheet_paths system - * property to change the file from which the stylesheet patterns are drawn. - *

- * - *

- * The patterns, such as ::vhost::, are substituted for string - * values: - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * clear - * - * - * - * - * - *
Pattern Meaning Examples
::host:: Host name www.aplaws.org
::vhost:: Virtual hostname. business.camden.gov.uk
::webapp:: Current web application name (ie. context or document root) ccm
::application:: Current CCM Application name navigation
::url:: URL stub of the current applications name tree admin
::prefix:: ?? ??
::outputtype:: Output format. text_html
::locale:: Current locale fr_FR
::outputtype:: Output format. text_html
- * - *

- * Each substituted string is cleaned up using the following rules: - *

- * - *
    - *
  • Whitespace is trimmed. - *
  • Converted to lowercase - *
  • If the string is null, it is converted to "default". - *
  • Any "/" characters are converted to "_" (underscore). - *
- * - *

- * The resolver looks at each stylesheet in turn, and the first one which - * actually exists on disk is returned. - *

- * - * Developer may customize the process by writing a custom pattern generator and - * add it in a custom integration package Initializer (e.g. ccm-ldn-aplaws) by - * following code: // Register additional PatternStyleSheetResolver for Web app. - * PatternStylesheetResolver.registerPatternGenerator( "[myKey]", new - * [My]PatternGenerator() ); - * - * - * @author Richard W.M. Jones - */ -public class PatternStylesheetResolver implements StylesheetResolver { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int the runtime environment and - * set com.arsdigita.templating.PatternStylesheetResolver=DEBUG by - * uncommenting or adding the line. - */ - private static final Logger s_log = LogManager.getLogger( - PatternStylesheetResolver.class); - - /** - * List of registered pattern generators which are queried in turn. - */ - private static final HashMap s_generators = new HashMap(); - - /** - * Registers a new pattern generator for the given key. - * - * @param key the key as it appears in the pattern string - * @param gen a pattern generator for producing values to be substituted for - * key - */ - public static void registerPatternGenerator(String key, - PatternGenerator gen) { - s_generators.put(key, gen); - } - - /* Statiic initializer block to initialize the standard pattern generators - * at load time. */ - static { - s_log.debug("Static initalizer starting..."); - registerPatternGenerator("locale", new LocalePatternGenerator()); - registerPatternGenerator("url", new URLPatternGenerator()); - registerPatternGenerator("application", - new ApplicationPatternGenerator()); - registerPatternGenerator("outputtype", new OutputTypePatternGenerator()); - registerPatternGenerator("prefix", new PrefixPatternGenerator()); - registerPatternGenerator("webapp", new WebAppPatternGenerator()); - registerPatternGenerator("host", new HostPatternGenerator()); - s_log.debug("Static initalizer finished."); - } - - /** - * Complete path to the file specifying stylesheet patterns. Configurable by - * configuration option in TemplatingConfig - */ - private String m_path = null; - /** - * A List of Lists each of its lists containing one pattern to resolve a - * probably appropriate stylesheet to apply. (i.e. one row of the file - * m_path above) - */ - private List m_paths = null; - - /** - * - * @param request - * - * @return - */ - @Override - public URL resolve(HttpServletRequest request) { - synchronized (this) { - if (m_paths == null) { - loadPaths(Templating.getConfig().getStylesheetPaths()); - } - } - s_log.debug("m_paths is " + m_paths); - - HashMap values = new HashMap(); - ArrayList paths = new ArrayList(); - Iterator it = m_paths.iterator(); - while (it.hasNext()) { - List pathList = (List) it.next(); - String[] bits = (String[]) pathList.toArray( - new String[pathList.size()] - ); - expandPlaceholders(bits, paths, values, request); - } - - Iterator files = paths.iterator(); - while (files.hasNext()) { - String[] bits = (String[]) files.next(); - - String resource = StringUtils.join(bits, ""); - // UGLY HACK - // If a placeholder returns an empty string (as in the example of - // the root webapp) the provided string contains a "//" as there is - // a slash before as well as after the placeholder in the pattern - // string. It's ugly so we'll replace it. - resource = resource.replace("//", "/"); - // The hack destroys the http protocol as well so we need another hack - resource = resource.replace("http:/", "http://"); - - if (s_log.isInfoEnabled()) { - s_log.info("Looking to see if resource " + resource + " exists"); - } - - URL origURL = null; - try { - origURL = new URL(resource); - } catch (MalformedURLException ex) { - throw new UncheckedWrapperException( - "malformed URL " + resource, ex); - } - - if (s_log.isInfoEnabled()) { - s_log.info("origURL is " + origURL); - } - - final URL xfrmedURL = (origURL == null) ? null : Templating - .transformURL(origURL); - - if (s_log.isInfoEnabled()) { - s_log.info("Transformed resource is " + xfrmedURL); - } - - try { - InputStream is = null; - if (xfrmedURL != null) { - is = xfrmedURL.openStream(); - } - if (is != null) { - is.close(); - // xfrmedURL may test for existence either as http request - // or as a file lookup. Anyway we return the original URL - // which used to be a http request. - // Note: we are returning the URL, not the resource! - return origURL; - } - } catch (FileNotFoundException ex) { - if (s_log.isDebugEnabled()) { - s_log.debug("File not found " + resource, ex); - } - // fall through & try next pattern - } catch (IOException ex) { - throw new UncheckedWrapperException("cannot open stream " - + resource, ex); - } - } - - throw new RuntimeException("no path to XSL stylesheet found; " - + "try modifying " + m_path); - } - - /** - * - * @param inBits - * @param paths - * @param values - * @param request - */ - private void expandPlaceholders(String[] inBits, - ArrayList paths, - HashMap values, - HttpServletRequest request) { - LinkedList queue = new LinkedList(); - if (s_log.isDebugEnabled()) { - s_log.debug("Queue initial entry " + StringUtils.join(inBits, "")); - } - queue.add(inBits); - while (!queue.isEmpty()) { - String[] bits = (String[]) queue.removeFirst(); - if (s_log.isDebugEnabled()) { - s_log.debug("Process queue entry " + StringUtils.join(bits, "")); - } - boolean clean = true; - for (int i = 0; i < bits.length && clean; i++) { - if (bits[i].startsWith("::") && bits[i].endsWith("::")) { - clean = false; - String[] vals = getValues(bits[i] - .substring(2, bits[i].length() - 2), - values, - request); - if (vals != null) { - for (int k = 0; k < vals.length; k++) { - String[] newBits = new String[bits.length]; - // In case the pattern for an element is an empty - // string (e.g. for the ROOT webapp) the slash before - // as well as after the placeholder are added - // resulting in a "//" which does no harm but is - // ugly. - for (int j = 0; j < bits.length; j++) { - if (j == i) { - newBits[j] = vals[k]; - } else { - newBits[j] = bits[j]; - } - } - if (s_log.isDebugEnabled()) { - s_log.debug("Requeue " + StringUtils.join( - newBits, "")); - } - queue.add(newBits); - } - } - } - } - - if (clean) { - if (s_log.isDebugEnabled()) { - s_log.debug("Finished expanding placeholders in " - + StringUtils.join(bits, "")); - } - paths.add(bits); - } - } - } - - /** - * - * @param key - * @param values - * @param request - * - * @return - */ - private String[] getValues(String key, - HashMap values, - HttpServletRequest request) { - if (s_log.isDebugEnabled()) { - s_log.debug("Lookup placeholder keys for " + key); - } - String[] vals = (String[]) values.get(key); - if (vals == null) { - PatternGenerator gen = (PatternGenerator) s_generators.get(key); - if (gen == null) { - return new String[]{}; - } - vals = gen.generateValues(key, request); - values.put(key, vals); - } - return vals; - } - - /** - * - * @param path - */ - private void loadPaths(String path) { - if (s_log.isInfoEnabled()) { - s_log.info("Loading paths from " + path); - } - - m_path = path; - try { - // Read the source file. - ClassLoader cload = Thread.currentThread().getContextClassLoader(); - InputStream stream = cload.getResourceAsStream(path.substring(0)); - s_log.debug("got stream using path " + path.substring(0)); - s_log.debug("stream.available is " + stream.available()); - m_paths = new ArrayList(); - - LineNumberReader file = new LineNumberReader(new InputStreamReader( - stream)); - String line; - int lineNum; - while ((line = file.readLine()) != null) { - lineNum = file.getLineNumber(); - // Ignore blank lines and comments. - line = line.trim(); - s_log.debug("line is " + line); - if ("".equals(line) - || line.startsWith("#") - || line.startsWith("!") - || line.startsWith("//")) { - continue; - } - - // Split up the line. - List list = StringUtils.splitUp(line, "::\\w+::"); - // Save the split line. - m_paths.add(list); - } - } catch (IOException ex) { - throw new UncheckedWrapperException( - "cannot read XSLT paths from " + path, ex); - - } catch (Exception e) { - s_log.debug("loadPaths threw exception " + e); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/PrefixPatternGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/PrefixPatternGenerator.java deleted file mode 100755 index d4ef430d8..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/PrefixPatternGenerator.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import com.arsdigita.dispatcher.DispatcherHelper; -import javax.servlet.http.HttpServletRequest; - -/** - * Generates a pattern for based on the request dispatcher prefix, - * eg /print/content/myitem.jsp -> { 'print' } - * /text-only/content/myitem.jsp -> { 'text-only' } - */ -public class PrefixPatternGenerator implements PatternGenerator { - - /** - * - * @param key - * @param req - * @return - */ - @Override - public String[] generateValues(String key, - HttpServletRequest req) { - String value = DispatcherHelper.getDispatcherPrefix(req); - if (value != null) { - return new String[] { value.substring(1) }; - } - else { - return new String[] { }; - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/PresentationManager.java b/ccm-core/src/main/java/com/arsdigita/templating/PresentationManager.java deleted file mode 100755 index 8ab8bd3cc..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/PresentationManager.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import com.arsdigita.xml.Document; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Interface for styling and serving XML documents to the response output - * stream. - * - * The PresentationManager contains the code that determines which - * XSLT transformer(s) are to be applied to a given document. - * - * The (default) SimplePresentationManager just links to the bebop - * implementation. It should suffice for most cases. - * - * A custom presentation manager is needed if an application needs to - * dynamically apply a set of templates to an XML document in a custom - * way. Typically, this occurs if the template selection - * depends on the outcome of some application-specific logic. - * - * @see com.arsdigita.templating.SimplePresentationManager - * - * @author Bill Schneider - * @version ACS 4.6 - * @version $Id$ - */ -public interface PresentationManager { - - /** - * Serves a page whose content is defined by the input XML - * document. Gets an appropriate XSLT Transformer object and - * uses the transformer to convert the DOM input to the final - * output. - * - * @param doc the XML document whose content is to be displayed - * to the output - * @param req the servlet request - * @param resp the servlet response - */ - public void servePage(Document doc, - HttpServletRequest req, - HttpServletResponse resp); - - // WRS: I really would like to be able to define - // "public static getInstance()" here to make the singleton pattern - // enforced at compile time, but Java doesn't allow that declaration - // in an interface or abstract class. -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/SimplePresentationManager.java b/ccm-core/src/main/java/com/arsdigita/templating/SimplePresentationManager.java deleted file mode 100755 index 5bd65ef20..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/SimplePresentationManager.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -/** - * An Implementation of a Presentation Manager as specified by the - * {@link PresentationManager} interface which may be used as a default. - * - * As bebop is currently the only one providing a presenation layer it simply - * links to the bebop implementation. At the same time it makes shure an - * implementation exists which can be used as default in the templating - * configuration registry. - */ -/* NON Javadoc comment: - * Used to be deprecated in version 6.6.0. Reverted to non-deprecated in version - * 6.6.0 release 3. Package templating provides the basic mechanism for CCM - * templating system an should provide an implementation of the Presentation - * Manager interface to be complete. - * @ deprecated Use {@link com.arsdigita.bebop.page.PageTransformer} - * instead - */ -public class SimplePresentationManager - extends com.arsdigita.bebop.page.PageTransformer - implements PresentationManager{ - // Empty -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/SimpleURIResolver.java b/ccm-core/src/main/java/com/arsdigita/templating/SimpleURIResolver.java deleted file mode 100755 index 230bb6735..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/SimpleURIResolver.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import org.apache.logging.log4j.LogManager; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.xml.transform.Source; -import javax.xml.transform.TransformerException; -import javax.xml.transform.URIResolver; -import javax.xml.transform.stream.StreamSource; - -import org.apache.logging.log4j.Logger; - -/** - * An implementation of the URIResolver interface that keeps track of all the - * URLs that have been loaded. - * If you set this as the URI resolver for a Transformer then this will track - * all the xsl:import and xsl:include statements. - * - * @version $Id$ - */ -final class SimpleURIResolver implements URIResolver { - - private static final Logger s_log = LogManager.getLogger - (SimpleURIResolver.class); - - private final Set m_uniqueStylesheetURIs; - private final List m_stylesheetURIs; - - /** - * Constructor, just initializes internal properties. - */ - public SimpleURIResolver() { - m_uniqueStylesheetURIs = new HashSet(); - m_stylesheetURIs = new ArrayList(); - } - - /** - * Returns all the stylesheet URIs encountered so far. - * - * @return a Set whose elements are isntances of java.net.URL - */ - public List getStylesheetURIs() { - return m_stylesheetURIs; - } - - /** - * Resolves a URL and returns a stream source. - * - * @param href the url to resolve - * @param base the base url to resolve relative to - */ - @Override - public Source resolve(final String href, final String base) - throws TransformerException { - if (s_log.isDebugEnabled()) { - s_log.debug("Resolve " + href + " (found in " + base + ")"); - } - - URL baseURL = null; - - if (base != null) { - try { - baseURL = new URL(base); - } catch (MalformedURLException ex) { - throw new TransformerException("cannot parse href " + base, ex); - } - } - - URL thisURL = null; - - try { - if (baseURL == null) { - thisURL = new URL(href); - } else { - thisURL = new URL(baseURL, href); - } - - if (!m_uniqueStylesheetURIs.contains(thisURL)) { - m_uniqueStylesheetURIs.add(thisURL); - m_stylesheetURIs.add(thisURL); - } - } catch (MalformedURLException ex) { - throw new TransformerException("cannot parse href " + href, ex); - } - - try { - if (s_log.isDebugEnabled()) { - s_log.debug("Got url " + thisURL); - } - - // Optimize calls to resource servlet into file:/// - // where possible - URL xfrmedURL = Templating.transformURL(thisURL); - - if ( xfrmedURL == null ) { - throw new TransformerException - ("URL does not exist: " + thisURL); - } - - if (s_log.isInfoEnabled()) { - s_log.info("Loading URL " + xfrmedURL); - } - - InputStream is = xfrmedURL.openStream(); - - // NB, don't pass through 'xfrmedURL' since imports - // are relative to 'thisURL' - return new StreamSource(is, thisURL.toString()); - } catch (IOException ex) { - throw new TransformerException( - String.format("cannot read stream for %s", - thisURL.toString()), - ex); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/StylesheetResolver.java b/ccm-core/src/main/java/com/arsdigita/templating/StylesheetResolver.java deleted file mode 100755 index 999ec51d6..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/StylesheetResolver.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import java.net.URL; -import javax.servlet.http.HttpServletRequest; - -/** - * The various PresentationManager classes resolve requests - * into stylesheets using classes derived from this interface. - * - * @version $Id$ - */ -public interface StylesheetResolver { - - /** - * Resolves a template for the request. - * - * @param sreq the HttpServletRequest for which to - * resolve a template - * @return URL where to try to find a stylesheet - */ - public URL resolve(HttpServletRequest sreq); -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/Templating.java b/ccm-core/src/main/java/com/arsdigita/templating/Templating.java deleted file mode 100755 index ec585ccbd..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/Templating.java +++ /dev/null @@ -1,485 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.arsdigita.templating; - -import com.arsdigita.bebop.BebopConfig; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.util.Assert; -import com.arsdigita.util.ExceptionUnwrapper; -import com.arsdigita.util.Exceptions; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.util.servlet.HttpHost; -import com.arsdigita.web.Web; -import com.arsdigita.web.WebConfig; -import com.arsdigita.xml.Document; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.Level; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -import javax.servlet.http.HttpServletRequest; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.ErrorListener; -import javax.xml.transform.TransformerException; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * An entry-point class for the functions of the templating package. The class - * manages access to all theme files (XSL as well as css, pirctures, etc). - * - * This class maintains a cache of XSLTemplate objects, managed via - * the getTemplate and purgeTemplate methods. - * - * @author Dan Berrange - * @author Justin Ross <jross@redhat.com> - */ -public class Templating { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int hte runtime environment and - * set com.arsdigita.templating.Templating=DEBUG by uncommenting it or - * adding the line. - */ - private static final Logger LOGGER = LogManager.getLogger(Templating.class); - - /** - * This is the name of the attribute that is set in the request whose value, - * if present, is a collection of TransformerExceptions that can be used to - * produce a "pretty" error. - */ - public static final String FANCY_ERROR_COLLECTION = "fancyErrorCollection"; - - /** - * Config object containing various parameter - */ - private static final TemplatingConfig s_config = TemplatingConfig - .getConfig(); - - static { - LOGGER.debug("Static initalizer starting..."); - - Exceptions.registerUnwrapper( - TransformerException.class, - new ExceptionUnwrapper() { - - @Override - public Throwable unwrap(Throwable t) { - TransformerException ex = (TransformerException) t; - return ex.getCause(); - } - - }); - - // now we initiate the CacheTable here - // default cache size used to be 50, which is too high I reckon, - // each template can eat up to 4 megs - Integer setting = s_config.getStylesheetCacheSize(); - int cacheSize = (setting == null ? 10 : setting.intValue()); - - setting = s_config.getStylesheetCacheAge(); - int cacheAge = (setting == null ? 60 * 60 * 24 * 3 : setting.intValue()); - - LOGGER.debug("Static initalizer finished..."); - } - - /** - * Gets the LegacyTemplatingConfig record. - * - * @return The LegacyTemplatingConfig of this runtime - */ - public static TemplatingConfig getConfig() { - return s_config; - } - - /** - * Returns a new instance of the current presentation manager class. This is - * an object which has the - * {@link com.arsdigita.templating.PresentationManager PresentationManager} - * interface which can be used to transform an XML document into an output - * stream. - * - * As of version 6.6.0 the bebop framework is the only instance to provide - * an implementation. To avoid class hierachie kludge we directly return the - * bebop config here. - * - * @return an instance of the PresentationManager interface - */ - /* NON Javadoc - * Used to be deprecated up to version 6.6.0. Reverted to non-deprecated. - * Package templating provides the basic mechanism for CCM templating - * machinerie and provides the Presentation Manager interface. It should be - * able to be queried for an implementation as well. - * @ deprecated Use {@link - * com.arsdigita.bebop.BebopConfig#getPresentationManager()} - * instead. - */ - public static PresentationManager getPresentationManager() { - try { - return (PresentationManager) BebopConfig.getConfig(). - getPresenterClass().newInstance(); - } catch (IllegalAccessException | InstantiationException ex) { - throw new UncheckedWrapperException(ex); - } - } - - /** - * Retrieves an XSL template. If the template is already loaded in the - * cache, it will be returned. If the template has been modified since it - * was first generated, it will be regenerated first. - * - * @param source the URL to the top-level template resource - * - * @return an XSLTemplate instance representing - * source - */ - public static synchronized XSLTemplate getTemplate(final URL source) { - return getTemplate(source, false, true); - } - - /** - * Retrieves an XSL template. If the template is already loaded in the - * cache, it will be returned. If the template has been modified since it - * was first generated, it will be regenerated first. - * - * @param source the URL to the top-level template - * resource - * @param fancyErrors Should this place any xsl errors in the request for - * use by another class. If this is true, the the errors - * are stored for later use. - * @param useCache Should the templates be pulled from cache, if - * available? True means they are pulled from cache. - * False means they are pulled from the disk. If this is - * false the pages are also not placed in the cache. - * - * @return an XSLTemplate instance representing - * source - */ - public static synchronized XSLTemplate getTemplate(final URL source, - boolean fancyErrors, - boolean useCache) { - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Getting template for URL " + source); - } - - Assert.exists(source, URL.class); - - XSLTemplate template = null; - - if (template == null) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("The template for URL " + source + " is not " - + "cached; creating and caching it now"); - } - - if (fancyErrors) { - LoggingErrorListener listener = new LoggingErrorListener(); - Web.getRequest().setAttribute(FANCY_ERROR_COLLECTION, - listener.getErrors()); - template = new XSLTemplate(source, listener); - } else { - template = new XSLTemplate(source); - } - - } else if (KernelConfig.getConfig().isDebugEnabled() - && template.isModified()) { - // XXX referencing Kernel above is a broken dependency. - // Debug mode should be captured at a lower level, - // probably on UtilConfig. - - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Template " + template + " has been modified; " - + "recreating it from scratch"); - } - - if (fancyErrors) { - LoggingErrorListener listener = new LoggingErrorListener(); - Web.getRequest().setAttribute(FANCY_ERROR_COLLECTION, - listener.getErrors()); - template = new XSLTemplate(source, listener); - } else { - template = new XSLTemplate(source); - } - } - - return template; - } - - /** - * Resolves and retrieves the template for the given request. - * - * @param sreq The current request object - * - * @return The resolved XSLTemplate instance - */ - public static XSLTemplate getTemplate(final HttpServletRequest sreq) { - return getTemplate(sreq, false, true); - } - - /** - * Resolves the template for the given request to an URL. - * - * @param sreq The current request object - * @param fancyErrors Should this place any xsl errors in the request for - * use by another class. If this is true, the the errors - * are stored for later use. - * @param useCache Should the templates be pulled from cache, if - * available? True means they are pulled from cache. - * False means they are pulled from the disk. If this is - * false the pages are also not placed in the cache. - * - * @return The resolved XSLTemplate instance - */ - public static XSLTemplate getTemplate(final HttpServletRequest sreq, - boolean fancyErrors, - boolean useCache) { - - Assert.exists(sreq, HttpServletRequest.class); - - final URL sheet = getConfig().getStylesheetResolver().resolve(sreq); - Assert.exists(sheet, URL.class); - - return Templating.getTemplate(sheet, fancyErrors, useCache); - } - - /** - * Removes an XSL template from the internal cache. The template for - * source will be regenerated on the next request for it. - * - * @param source the URL to the top-level template resource - */ - public static synchronized void purgeTemplate(final URL source) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Purging cached template for URL " + source); - } - - Assert.exists(source, URL.class); - } - - /** - * Removes all cached template objects. All template objects will be - * regenerated on-demand as each gets requested. - */ - public static synchronized void purgeTemplates() { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Purging all cached templates"); - } - } - - /** - * Generates a stream containing imports for a number of URLs. - * - * @param paths An iterator of java.net.URL objects - * - * @return a virtual XSL file - */ - public static InputStream multiplexXSLFiles(Iterator paths) { - // StringBuilder buf = new StringBuilder(); - Element root = new Element("xsl:stylesheet", - "http://www.w3.org/1999/XSL/Transform"); - root.addAttribute("version", "1.0"); - - while (paths.hasNext()) { - URL path = (URL) paths.next(); - - Element imp = root.newChildElement( - "xsl:import", - "http://www.w3.org/1999/XSL/Transform"); - imp.addAttribute("href", path.toString()); - - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Adding import for " + path.toString()); - } - } - - Document doc = null; - try { - doc = new Document(root); - } catch (ParserConfigurationException ex) { - throw new UncheckedWrapperException("cannot build document", ex); - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("XSL is " + doc.toString(true)); - } - - return new ByteArrayInputStream(doc.toString(true).getBytes()); - } - - /** - * Transforms an URL, that refers to a local resource inside the running CCM - * web application. NON-local URLs remain unmodified. - * - * In case of a virtual path "/resource" it is short-circuiting access to - * the resource servlet. All other http:// URLs are transformed into file:// - * for XSLT validation to work for these resources. It has the added benefit - * of speeding up loading of XSL... - * - * Currently the direct file access method is perferred! As soon as we - * refactor to directly access the published XSL files in the database and - * to avoid the unnecessary intermediate step via the file system, we have - * to use URL's instead to be able to redirect access to a specific address - * to a servlet which manages database retrieval. - */ - static URL transformURL(URL url) { - final WebConfig webConfig = WebConfig.getConfig(); - final HttpHost self = new HttpHost(webConfig.getHostName(), - webConfig.getHostPort()); - - /** - * Indicates whether url refers to a local resource inside the running - * CCM web application (inside it's webapp context) - */ - Boolean isLocal = false; - /** - * Contains the transformed "localized" path to url, i.e. without host - * part. - */ - String localPath = ""; - - // Check if the url refers to our own host - if (self.getName().equals(url.getHost()) - && ((self.getPort() == url.getPort()) - || (url.getPort() == -1 && self.getPort() == 80))) { - // host part denotes to a local resource, cut off host part. - localPath = url.getPath(); - isLocal = true; - } - // java.net.URL is unaware of JavaEE webapplication. If CCM is not - // installed into the ROOT context, the path includes the webapp part - // which must be removed as well. - // It's a kind of HACK, unfortunately. If CCM is installed into the - // root context we don't detect whether the first part of the path - // refers to another web application inside the host and assume local - // and unrestricted access. The complete code should get refactored to - // use ServletContext#getResource(path) - String installContext = Web.getWebappContextPath(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Installation context is >" + installContext + "<."); - } - if (!installContext.equals("")) { - // CCM is installed into a non-ROOT context - if (localPath.startsWith(installContext)) { - // remove webapp context part - localPath = localPath.substring(installContext.length()); - if (LOGGER.isDebugEnabled()) { - LOGGER - .debug("WebApp context removed: >>" + localPath + "<<"); - } - } - } - - if (isLocal) { - // url specifies the running CCM host and port (or port isn't - // specified in url and default for running CCM host - - if (localPath.startsWith("/resource")) { - // A virtual path to the ResourceServlet - localPath = localPath.substring("/resource".length()); //remove virtual part - URL newURL = Web.findResource(localPath); //without host part here! - if (LOGGER.isDebugEnabled()) { - LOGGER. - debug("Transforming resource " + url + " to " - + newURL); - } - return newURL; - } else { - // A real path to disk - final String filename = Web.getServletContext() - .getRealPath(localPath); - File file = new File(filename); - if (file.exists()) { - try { - URL newURL = file.toURL(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Transforming resource " + url + " to " - + newURL); - } - return newURL; - } catch (MalformedURLException ex) { - throw new UncheckedWrapperException(ex); - } - } else if (LOGGER.isDebugEnabled()) { - LOGGER.debug("File " + filename - + " doesn't exist on disk"); - } - } - } else // url is not the (local) running CCM host, no transformation - // is done - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("URL " + url + " is not local"); - } - - return url; // returns the original, unmodified url here - } - -} - -/** - * - * @author pb - */ -class LoggingErrorListener implements ErrorListener { - - private static final Logger LOGGER = LogManager.getLogger( - LoggingErrorListener.class); - private final ArrayList m_errors; - - LoggingErrorListener() { - m_errors = new ArrayList(); - } - - public Collection getErrors() { - return m_errors; - } - - @Override - public void warning(TransformerException e) throws TransformerException { - log(Level.WARN, e); - } - - @Override - public void error(TransformerException e) throws TransformerException { - log(Level.ERROR, e); - } - - @Override - public void fatalError(TransformerException e) throws TransformerException { - log(Level.FATAL, e); - } - - private void log(Level level, TransformerException ex) { - LOGGER.log(level, "Transformer " + level + ": " - + ex.getLocationAsString() + ": " + ex. - getMessage(), - ex); - m_errors.add(ex); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/TemplatingConfig.java b/ccm-core/src/main/java/com/arsdigita/templating/TemplatingConfig.java deleted file mode 100755 index 37643d2df..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/TemplatingConfig.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.templating; - -import com.arsdigita.util.UncheckedWrapperException; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.Configuration; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.configuration.Setting; - -import java.util.Objects; - -/** - * - * @author Jens Pelzetter - */ -@Configuration -public final class TemplatingConfig { - - @Setting - private String stylesheetPaths = "stylesheet-paths.txt"; - - @Setting - private String stylesheetResolverClass = PatternStylesheetResolver.class - .getName(); - - @Setting - private Integer stylesheetCacheSize = 10; - - @Setting - private Integer stylesheetCacheAge = 3600; - - public static TemplatingConfig getConfig() { - final ConfigurationManager confManager = CdiUtil.createCdiUtil() - .findBean(ConfigurationManager.class); - return confManager.findConfiguration(TemplatingConfig.class); - } - - public String getStylesheetPaths() { - return stylesheetPaths; - } - - public void setStylesheetPaths(final String stylesheetPaths) { - this.stylesheetPaths = stylesheetPaths; - } - - public String getStylesheetResolverClass() { - return stylesheetResolverClass; - } - - public StylesheetResolver getStylesheetResolver() { - - try { - @SuppressWarnings("unchecked") - final Class clazz - = (Class) Class - .forName(stylesheetResolverClass); - return clazz.newInstance(); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { - throw new UncheckedWrapperException( - "Unable to create configured StylesheetResolver.", - ex); - } - } - - public void setStylesheetResolverClass( - final String stylesheetResolverClass) { - try { - final Class clazz = Class.forName(stylesheetResolverClass); - if (!StylesheetResolver.class.isAssignableFrom(clazz)) { - throw new IllegalArgumentException(String.format( - "Provided class \"%s\" is not an " - + "implementation of the interface \"%s\".", - stylesheetResolverClass, - StylesheetResolver.class.getName())); - } - } catch (ClassNotFoundException ex) { - throw new IllegalArgumentException( - String.format("Unable to retrieve class \"%s\".", - stylesheetResolverClass), - ex); - } - - this.stylesheetResolverClass = stylesheetResolverClass; - } - - public Integer getStylesheetCacheSize() { - return stylesheetCacheSize; - } - - public void setStylesheetCacheSize(final Integer stylesheetCacheSize) { - this.stylesheetCacheSize = stylesheetCacheSize; - } - - public Integer getStylesheetCacheAge() { - return stylesheetCacheAge; - } - - public void setStylesheetCacheAge(final Integer stylesheetCacheAge) { - this.stylesheetCacheAge = stylesheetCacheAge; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 23 * hash + Objects.hashCode(stylesheetPaths); - hash = 23 * hash + Objects.hashCode(stylesheetResolverClass); - hash = 23 * hash + Objects.hashCode(stylesheetCacheSize); - hash = 23 * hash + Objects.hashCode(stylesheetCacheAge); - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (obj instanceof TemplatingConfig) { - return false; - } - final TemplatingConfig other = (TemplatingConfig) obj; - if (!Objects.equals(stylesheetPaths, other.getStylesheetPaths())) { - return false; - } - if (!Objects.equals(stylesheetResolverClass, - other.getStylesheetResolverClass())) { - return false; - } - if (!Objects.equals(stylesheetCacheSize, - other.getStylesheetCacheSize())) { - return false; - } - if (!Objects.equals(stylesheetCacheAge, - other.getStylesheetCacheAge())) { - return false; - } - return true; - } - - @Override - public String toString() { - return String.format("%s{ " - + "stylesheetPaths = \"%s\", " - + "stylesheetResolverClass = \"%s\", " - + "stylesheetCacheSize = %d, " - + "stylesheetCacheAge = %d" - + " }", - super.toString(), - stylesheetPaths, - stylesheetResolverClass, - stylesheetCacheSize, - stylesheetCacheAge); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/URLPatternGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/URLPatternGenerator.java deleted file mode 100755 index 2b8816d77..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/URLPatternGenerator.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import com.arsdigita.util.Assert; -import com.arsdigita.util.StringUtils; - -import com.arsdigita.web.Web; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.libreccm.web.CcmApplication; - -/** - * Generates a set of pattern values based on the URL path info for the current - * request. Slashes in the request are translated into hyphens; the file - * extension is stripped; any 'index' is removed, except for the top level. - * - * So some examples: - * - * /content/admin/item.jsp -> { "admin-item", "admin", "index" } - * /content/admin/index.jsp -> { "admin", "index" } /content/admin/ -> { - * "admin", "index" } /content/index.jsp -> { "index" } /content/ -> { "index" } - */ -public class URLPatternGenerator implements PatternGenerator { - - private static final Logger LOGGER = LogManager.getLogger( - URLPatternGenerator.class); - - private static final String DEFAULT_URL_MATCH = "index"; - - /** - * - * @param key - * @param req - * - * @return - */ - public String[] generateValues(String key, - HttpServletRequest req) { - String path = getPath(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Substituting values for url " + path); - } - - // Check for a file extension & strip it. - int dotIndex = path.lastIndexOf("."); - int slashIndex = path.lastIndexOf("/"); - if (dotIndex > -1 - && dotIndex > slashIndex) { - path = path.substring(0, dotIndex); - } - - // Strip '/index' if any - if (path != null && path.endsWith("/" + DEFAULT_URL_MATCH)) { - path = path.substring(0, path.length() - DEFAULT_URL_MATCH.length()); - } - - // Now strip trailing & leading slash - if (path != null && path.startsWith("/")) { - path = path.substring(1); - } - if (path != null && path.endsWith("/")) { - path = path.substring(0, path.length() - 1); - } - - if (path == null) { - path = ""; - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Normalized path is '" + path + "'"); - } - String[] bits = StringUtils.split(path, '/'); - if (LOGGER.isDebugEnabled()) { - for (int i = 0; i < bits.length; i++) { - LOGGER.debug(" -> '" + bits[i] + "'"); - } - } - - // Now we've cut off the file extension, it's time to do the - // funky concatenation trick. - for (int i = 1; i < bits.length; i++) { - bits[i] = bits[i - 1] + "-" + bits[i]; - } - - // Now we have to reverse it, so matching goes from most specific - // to most general & add in the default 'index' match - String[] reverseBits = new String[bits.length + 1]; - - for (int i = bits.length - 1, j = 0; i > -1; i--, j++) { - reverseBits[j] = bits[i]; - } - reverseBits[reverseBits.length - 1] = DEFAULT_URL_MATCH; - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("After concatenation & reversing"); - for (int i = 0; i < reverseBits.length; i++) { - LOGGER.debug(" -> '" + reverseBits[i] + "'"); - } - } - - return reverseBits; - } - - private String getPath() { - String base = getBasePath(); - String url = Web.getWebContext().getRequestURL().getPathInfo(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Base is " + base + " url is " + url); - } - - Assert.isTrue(url.startsWith(base), "URL " + url + " starts with " - + base); - - return url.substring(base.length() - 1); - } - - /** - * Provides the base URL of the application in the current Web request (i.e. - * application's PrimaryURL). If no application can be found or no - * PrimaryURL can be determined ROOT ("/") is returned. * - * XXX fix me, why can't we get this from Web.getWebContext().getRequestURL - * - * @return primary url of an application or ROOT - */ - private String getBasePath() { - - // retrieve the application of the request - CcmApplication app = Web.getWebContext().getApplication(); - if (app == null) { - return "/"; - } else { - return app.getPrimaryUrl().toString(); - } - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/WebAppPatternGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/WebAppPatternGenerator.java deleted file mode 100755 index 468b64714..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/WebAppPatternGenerator.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import com.arsdigita.web.Web; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.libreccm.web.CcmApplication; - -/** - * Generates a set of patterns corresponding to the current web application - * prefix. - */ -public class WebAppPatternGenerator implements PatternGenerator { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int hte runtime environment and - * set com.arsdigita.templating.WebAppPatternGenerator=DEBUG by uncommenting - * or adding the line. - */ - private static final Logger LOGGER = LogManager.getLogger( - WebAppPatternGenerator.class); - - /** - * - * @param key placeholder from the pattern string, without surrounding - * colons, constantly "webapp" here. - * @param req current HttpServletRequest - * - * @return List of webapps contextPath names in an Array of Strings. - */ - @Override - public String[] generateValues(String key, - HttpServletRequest req) { - - CcmApplication app = Web.getWebContext().getApplication(); - String ctx = (app == null) ? null : ""; - - if (app == null || ctx == null || "".equals(ctx)) { - ctx = Web.getWebappContextPath(); - } - - // JavaEE requires a leading "/" for web context part, but the pattern - // string already contains a "/", so we have to remove it here to - // too avoid a "//" - if (ctx.startsWith("/")) { - ctx = ctx.substring(1); - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Generating Values key: " + key + " [" - + "Web.getWebContext(): " + Web.getWebContext() + " ," - + "Application: " + Web.getWebContext().getApplication() - + "," + "ContextPath: >" + ctx + "<]"); - } - - /* "Older version: prior 6.6. Some modules used to be installed into - * its own web application context, but needed access to the main - * applications package files (e.g. bebop). Therefore the webapp context - * (ServletContext in API speech) of the main CCM application had to be - * added (which was ROOT by default) - * - * As of version 6.6 all packages are installed in one web application - * context, therefore no additional entry is required. - * This variation had first be introduced with the APLAWS integration - * package, which used to register an additional WebAppPatternGenerator, - * which simply cuts ","+ Web.ROOT_WEBAPP, under a different key - * "Webapp" (singular) */ - // return new String[] { ctx + "," + Web.getRootWebappContextPath() }; - return new String[]{ctx}; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/WrappedTransformerException.java b/ccm-core/src/main/java/com/arsdigita/templating/WrappedTransformerException.java deleted file mode 100755 index 33711e5c4..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/WrappedTransformerException.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import com.arsdigita.util.UncheckedWrapperException; - -import javax.xml.transform.TransformerException; - -/** - * A simple wrapper around TransformerException that provides a - * more useful {@link #getMessage()} method. - * - * @author Vadim Nasardinov - * @since 2003-11-21 - * @version $Id$ - */ -public final class WrappedTransformerException extends UncheckedWrapperException { - private TransformerException m_trex; - - /** - * The passed in TransformerException is retrievable later via - * {@link #getRootCause()}. - * - * @pre ex != null - **/ - public WrappedTransformerException(TransformerException ex) { - super(ex); - if ( ex == null ) { throw new NullPointerException("ex"); } - m_trex = ex; - } - - /** - * @see #WrappedTransformerException(TransformerException) - * @pre ex != null - **/ - public WrappedTransformerException(String msg, TransformerException ex) { - super(msg, ex); - if ( ex == null ) { throw new NullPointerException("ex"); } - m_trex = ex; - } - - /** - * The returned message includes the location information. - **/ - public String getMessage() { - StringBuffer sb = new StringBuffer(); - possiblyAppend(sb, super.getMessage()); - appendMessage(m_trex, sb); - return sb.toString(); - } - - private static void appendMessage(TransformerException ex, - StringBuffer sb) { - - if ( !possiblyAppend(sb, ex.getMessageAndLocation()) ) { - possiblyAppend(sb, ex.getMessage()); - possiblyAppend(sb, ex.getLocationAsString()); - } - if ( ex.getCause() instanceof TransformerException ) { - appendMessage((TransformerException) ex.getCause(), sb); - } else { - if ( ex.getCause() != null ) { - possiblyAppend(sb, ex.getCause().getMessage()); - } - } - } - - private static boolean possiblyAppend(StringBuffer sb, String str) { - if ( str == null ) { return false; } - sb.append(str).append("; "); - return true; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/XSLParameterGenerator.java b/ccm-core/src/main/java/com/arsdigita/templating/XSLParameterGenerator.java deleted file mode 100755 index 6d6a45600..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/XSLParameterGenerator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import javax.servlet.http.HttpServletRequest; - -/** - * This is an interface that allows developers to set variables - * that will be available inside of the XSL for use by all XSL stylesheets. - * Implementations of this class can be registered with the - * {@link com.arsdigita.templating.Templating} - * class for use by any {@link com.arsdigita.templating.PresentationManager} - * class - */ -public interface XSLParameterGenerator { - - /** - * This returns the correct value for the parameter. This is the - * value that is added to the transformer and is available to all - * stylesheets - * @param request - * @return - */ - public String generateValue(HttpServletRequest request); -} diff --git a/ccm-core/src/main/java/com/arsdigita/templating/XSLTemplate.java b/ccm-core/src/main/java/com/arsdigita/templating/XSLTemplate.java deleted file mode 100755 index c2655d79f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/templating/XSLTemplate.java +++ /dev/null @@ -1,387 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.templating; - -import com.arsdigita.util.Assert; -import com.arsdigita.util.IO; - -import java.io.File; -import java.io.PrintWriter; -import java.io.OutputStream; -import java.io.IOException; - -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import javax.xml.transform.ErrorListener; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Templates; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import org.w3c.dom.Document; - -/** - * A class for loading, caching and generally managing XSL templates and - * transformers. - * - * @author Dan Berrange - */ -public final class XSLTemplate { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int hte runtime environment and - * set com.arsdigita.templating.XSLTemplate=DEBUG by uncommenting or adding - * the line. - */ - private static final Logger LOGGER = LogManager.getLogger(XSLTemplate.class); - - /** - * Property containing the URL to the XSL source file or create this - * instance - */ - private final URL m_source; - private final Templates m_templates; - private final List m_dependents; - private final Date m_created; - - /** - * Creates and loads a new template from source, using - * listener to handle any errors. - * - * @param source A URL pointing to the template source text - * @param listener A ErrorListener to customize behavior on - * error - */ - public XSLTemplate(final URL source, - final ErrorListener listener) { - if (Assert.isEnabled()) { - Assert.exists(source, URL.class); - Assert.exists(listener, ErrorListener.class); - } - - m_source = source; - - final SimpleURIResolver resolver = new SimpleURIResolver(); - - try { - LOGGER.debug("Getting new templates object"); - - final TransformerFactory factory = TransformerFactory - .newInstance(); - factory.setURIResolver(resolver); - factory.setErrorListener(listener); - - m_templates = factory.newTemplates(resolver.resolve(m_source. - toString(), null)); - - LOGGER.debug("Done getting new templates"); - } catch (TransformerConfigurationException ex) { - throw new WrappedTransformerException(ex); - } catch (TransformerException ex) { - throw new WrappedTransformerException(ex); - } - - // List contains each include/import URL found in the style sheet - // recursively(!) (i.e. scanning each style sheet whose URL has been - // found in a style sheet, etc. - // In case of Mandalay (single entry stylesheet) about 250 URL's, all - // resolved when found Mandalay's start.xml in one go. - m_dependents = resolver.getStylesheetURIs(); - m_created = new Date(); - } - - /** - * Creates and loads a new template from source using the - * default ErrorListener. - * - * @param source A URL pointing to the template source text - */ - public XSLTemplate(final URL source) { - this(source, new Log4JErrorListener()); - } - - /** - * Gets the URL of the template source. - * - * @return The URL location of the template source; it cannot - * be null - */ - public final URL getSource() { - return m_source; - } - - /** - * Gets a list of all dependent stylesheet files. - * - * @return A List of URLs to dependent stylesheet - * files; it cannot be null - */ - public final List getDependents() { - return m_dependents; - } - - /** - * Generates a new Transformer from the internal - * Templates object. - * - * @return The new Transformer; it cannot be null - */ - public final synchronized Transformer newTransformer() { - LOGGER.debug("Generating new transformer"); - - try { - return m_templates.newTransformer(); - } catch (TransformerConfigurationException tce) { - throw new WrappedTransformerException(tce); - } - } - - /** - * Transforms the source document and sends it to - * result. If there are errors, listener handles - * them. This method internally creates and uses a new - * Transformer. - * - * @param source The Source to be transformed; it cannot be - * null - * @param result The Result to capture the transformed - * product; it cannot be null - * @param listener A ErrorListener to handle transformation - * errors; it cannot be null - */ - public final void transform(final Source source, - final Result result, - final ErrorListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Transforming " + source + " and sending it to " - + result + " using error listener " + listener); - } - - if (Assert.isEnabled()) { - Assert.exists(source, Source.class); - Assert.exists(result, Result.class); - Assert.exists(listener, ErrorListener.class); - } - - try { - final Transformer transformer = newTransformer(); - transformer.setErrorListener(listener); - - LOGGER.debug("Transforming the XML source document"); - - transformer.transform(source, result); - - LOGGER.debug("Finished transforming"); - } catch (TransformerConfigurationException tce) { - throw new WrappedTransformerException(tce); - } catch (TransformerException te) { - throw new WrappedTransformerException(te); - } - } - - /** - * Transforms the source document and sends it to - * result. This method internally creates and uses a new - * Transformer. - * - * @param source The Source to be transformed; it cannot be - * null - * @param result The Result to capture the transformed product; - * it cannot be null - */ - public final void transform(final Source source, - final Result result) { - transform(source, result, new Log4JErrorListener()); - } - - /** - * Transforms doc and streams the result to - * writer. If there are errors, listener handles - * them. - * - * @param doc The Document to transform; it cannot be null - * @param writer The PrintWriter to receive the transformed - * result; it cannot be null - * @param listener A ErrorListener to handle any errors; it - * cannot be null - */ - public final void transform(final Document doc, - final PrintWriter writer, - final ErrorListener listener) { - if (Assert.isEnabled()) { - Assert.exists(doc, Document.class); - Assert.exists(writer, PrintWriter.class); - Assert.exists(listener, ErrorListener.class); - } - - final DOMSource source = new DOMSource(doc); - final StreamResult result = new StreamResult(writer); - - transform(source, result, listener); - } - - /** - * Transforms doc and streams the result to - * writer. - * - * @param doc The Document to transform; it cannot be null - * @param writer The PrintWriter to receive the transformed - * result; it cannot be null - */ - public final void transform(final Document doc, - final PrintWriter writer) { - transform(doc, writer, new Log4JErrorListener()); - } - - /** - * Checks whether the XSL files associated with the template have been - * modified. - * - * @return true if any dependent files have been modified, - * otherwise false - */ - public final boolean isModified() { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Checking if the XSL files for " + this.getSource() - .toString() + " " - + "have been modified and need to be re-read"); - } - - final Iterator iter = m_dependents.iterator(); - - while (iter.hasNext()) { - final URL url = Templating.transformURL((URL) iter.next()); - Assert.exists(url, URL.class); - - if (url.getProtocol().equals("file")) { - final File file = new File(url.getPath()); - - if (file.lastModified() > m_created.getTime()) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("File " + file + " was modified " + file. - lastModified()); - } - - return true; - } - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("The URL is not to a file; assuming " + url - + " is not modified"); - } - } - } - - LOGGER.debug("No files were modified"); - - return false; - } - - /** - * Creates a ZIP file containing this stylesheet and all dependant's. NB, - * this method assumes that all stylesheets live in the same URL protocol. - * If the protocol a file is different from the protocol of the top level, - * then this file will be excluded from the ZIP. In practice this limitation - * is not critical, because XSL files should always use relative imports, - * which implies all imported files will be in the same URL space. - * - * @param os the output stream to write the ZIP to - * @param base the base directory in which the files will extract - * - * @throws java.io.IOException - */ - public void toZIP(OutputStream os, - String base) - throws IOException { - - final ZipOutputStream zos = new ZipOutputStream(os); - - URL src = getSource(); - String srcProto = src.getProtocol(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Outputting files for " + src); - } - - final Iterator sheets = getDependents().iterator(); - while (sheets.hasNext()) { - URL xsl = (URL) sheets.next(); - if (xsl.getProtocol().equals(srcProto)) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Outputting file " + xsl); - } - String path = xsl.getPath(); - if (path.startsWith("/")) { - path = path.substring(1); - } - - zos.putNextEntry(new ZipEntry(base + "/" + path)); - - IO.copy(xsl.openStream(), zos); - } else { - LOGGER.warn("Not outputting file " + xsl - + " because its not under protocol " + srcProto); - } - } - zos.finish(); - } - - private static class Log4JErrorListener implements ErrorListener { - - @Override - public void warning(TransformerException e) throws TransformerException { - log(Level.WARN, e); - } - - @Override - public void error(TransformerException e) throws TransformerException { - log(Level.ERROR, e); - } - - @Override - public void fatalError(TransformerException e) throws - TransformerException { - log(Level.FATAL, e); - } - - private static void log(Level level, TransformerException ex) { - LOGGER.log(level, "Transformer " + level + ": " + ex. - getLocationAsString() + ": " + ex.getMessage(), - ex); - } - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/toolbox/ToolboxConstants.java b/ccm-core/src/main/java/com/arsdigita/toolbox/ToolboxConstants.java deleted file mode 100644 index 204407118..000000000 --- a/ccm-core/src/main/java/com/arsdigita/toolbox/ToolboxConstants.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.toolbox; - -/** - * Constants for the classes in the Toolbox package - * - * @author Jens Pelzetter - */ -public class ToolboxConstants { - - /** - * Private constructor to avoid instantiation of this class. - */ - private ToolboxConstants() { - - } - - public static final String TOOLBOX_BUNDLE - = "com.arsdigita.toolbox.ToolboxResources"; - -} diff --git a/ccm-core/src/main/java/com/arsdigita/ui/SimplePageLayout.java b/ccm-core/src/main/java/com/arsdigita/ui/SimplePageLayout.java deleted file mode 100755 index 6627c58d8..000000000 --- a/ccm-core/src/main/java/com/arsdigita/ui/SimplePageLayout.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.ui; - - -import java.util.ArrayList; -import java.util.List; -import java.util.Iterator; -import java.util.HashMap; - -import com.arsdigita.util.Assert; -import com.arsdigita.bebop.SimpleComponent; - - -/** - * The SimplePageLayout class stores the list of - * components on a page. Each component has an - * associated layout tag which is interpreted by - * the XSL when formatting the page. If the XSLT - * template in question were implementing a four - * area border layout (header, footer, left & right - * margins), this tag might be one of the strings - * 'top', 'bottom', 'left', 'right'. The Java code - * places no constraints or intpretation of these - * layout tags. - */ -class SimplePageLayout { - - private HashMap m_tags = new HashMap(); - - /** - * Adds a component to the layout with a particular - * position tag. - * - * @param component A subclass of Component with a no-arg constructor - * @param tag the layout position tag - */ - public void addComponent(Class component, - String tag) { - Assert.exists(component, Class.class); - Assert.exists(tag, String.class); - - Assert.isTrue(SimpleComponent.class.isAssignableFrom(component), - "component is a subclass of SimpleComponent"); - - List list = (List)m_tags.get(tag); - if (list == null) { - list = new ArrayList(); - m_tags.put(tag, list); - } - - list.add(component); - } - - /** - * Retrieves an iterator for all the known position tags - * in this layout. - * - * @return an iterator of position tags - */ - public Iterator getPositionTags() { - return m_tags.keySet().iterator(); - } - - /** - * Retrieves an iterator for all components with - * a specified tag. - */ - public Iterator getComponents(String tag) { - List list = (List)m_tags.get(tag); - Assert.exists(list, List.class); - return list.iterator(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/ui/UI.java b/ccm-core/src/main/java/com/arsdigita/ui/UI.java deleted file mode 100644 index 9065cce26..000000000 --- a/ccm-core/src/main/java/com/arsdigita/ui/UI.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.ui; - - -import javax.servlet.http.HttpServletRequest; - -/** - *

- * A central location for commonly used UI services and their accessories.

- * - * - * @author pb - */ -public abstract class UI { - - /** - * The UI XML namespace. - */ - public static final String UI_XML_NS = "http://www.arsdigita.com/ui/1.0"; - - public static final String UI_BUNDLE_NAME = "com.arsdigita.ui.UIResources"; - - private static final UIConfig s_config = UIConfig.getConfig(); - - /** - * URL for systems public top level page (entry or start page). - */ - private static final String s_rootPageURL = s_config.getRootPageUrl(); - - /** - * URL to page a user should be redirected to after login. - */ - private static final String s_userRedirectURL = s_config - .getUserRedirectUrl(); - - /** - * (Absolute) URL for workspace page. - */ - private static final String s_workspaceURL = s_config.getWorkspaceUrl(); - - /** - * Provides a handle to the UI config record. - * - * @return Instance of LegacyUIConfig - */ - public static UIConfig getConfig() { - return s_config; - } - - /** - * Provides an absolute URL (leading slash) into the system top-level page - * (entry page / start page). It is relative to document root without any - * constant prefix if there is one configured. - * - * Method is typically called by servlets and especially by JSP's. - * - * Currently just a wrapper script to getRootPageURL() because req is - * currently ignored. - * - * @param req HttpServletRequest, may be used to determin the context of the - * current thread (application), currently not used and - * introduced here for backwards compatibility - * - * @return URL for top-level page as String - */ - public static String getRootPageURL(HttpServletRequest req) { - return getRootPageURL(); - } - - /** - * Provides an absolute URL (leading slash) into the system top-level page - * (entry page / start page). It is relative to document root without any - * constant prefix if there is one configured. - * - * Method is typically called by servlets and especially by JSP's. - * - * @return URL for top-level page as String - */ - public static String getRootPageURL() { - return s_rootPageURL; - } - - /** - * Provides the absolute URL of a page, which redirects an incomming request - * based on some clients property, usually whether the user is logged in, - * either to a general public page or to a user (client) specific page. - * - * It is relative to document root including leading slash but without any - * constant prefix if there is one configured. - * - * It is typically used after login to redirect to an appropriate page, by - * default to /peremissions/. A site should configure an application to - * their specific purposes. e.g ccm-cms provides a page - * content-center/redirect.jsp which redirects a user to the content-center - * if logged in. - * - * @return full URL of a user redirect page, may be null - */ - public static String getUserRedirectURL() { - return s_userRedirectURL; - } - - /** - * Wrapper method for { - * - * @see getUserRedirectURL()} which redirects a user to the content-center - * if logged in. - * - * Method is specifically used by various redirect JSP's. - * - * @param req HttpServletRequest, may be used to determin the context of the - * current thread (application), currently not used and - * introduced here for backwards compatibility - * - * @return full URL of a user redirect page, may be null - */ - public static String getUserRedirectURL(HttpServletRequest req) { - return getUserRedirectURL(); - } - - /** - * Provides the absolute URL for the system workspace page. It is relative - * to document root including leading slash but without any constant prefix - * if there is one configured. - * - * It is used by the user redirection page (see above) as redirection target - * if no logged in user exists or no user specific page is configured. By - * default it is configured as "pvt/" as well. An installation usually - * defines a different page according to their specific purposes, e.g. - * portal or navigation. - * - * @return URL for workspace page as String - */ - public static String getWorkspaceURL() { - return s_workspaceURL; - } - - /** - * Provides the absolute URL for the system workspace page. It is relative - * to document root including leading slash but without any constant prefix - * if there is one configured. - * - * Method is typically called by servlets and especially by JSP's. - * - * Currently just a wrapper script to getWorkspaceURL() because req is - * currently ignored. - * - * @param req HttpServletRequest, may be used to determin the context of the - * current thread (application), currently not used and - * introduced here for backwards compatibility - * - * @return URL for workspace page as String - */ - // In old LegacyInitializer - // WORKSPACE_PAGE_KEY = page.kernel.workspace=pvt/ (mod- t0 portal/nav) - public static String getWorkspaceURL(HttpServletRequest req) { - return getWorkspaceURL(); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/ui/UIConfig.java b/ccm-core/src/main/java/com/arsdigita/ui/UIConfig.java deleted file mode 100644 index 195be29ec..000000000 --- a/ccm-core/src/main/java/com/arsdigita/ui/UIConfig.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.ui; - - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.Configuration; -import org.libreccm.configuration.ConfigurationException; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.configuration.Setting; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.StringJoiner; - - -/** - * - * @author Jens Pelzetter - */ -@Configuration -public final class UIConfig { - - @Setting - private List defaultLayout = Arrays.asList(new String[]{ - "top:com.arsdigita.ui.UserBanner", - "bottom:com.arsdigita.ui.SiteBanner", - "bottom:com.arsdigita.ui.DebugPanel" - }); - - @Setting - private String rootPageUrl = "/register/"; - - @Setting - private String userRedirectUrl = "/permissions/"; - - @Setting - private String workspaceUrl = "/pvt/"; - - public static UIConfig getConfig() { - final ConfigurationManager confManager = CdiUtil.createCdiUtil() - .findBean(ConfigurationManager.class); - - return confManager.findConfiguration(UIConfig.class); - } - - public UIConfig() { - super(); - } - - public List getDefaultLayout() { - return new ArrayList<>(defaultLayout); - } - - public void setDefaultLayout(final List defaultLayout) { - this.defaultLayout = defaultLayout; - } - - public SimplePageLayout buildDefaultLayout() { - throw new UnsupportedOperationException(); - } - - public String getRootPageUrl() { - return rootPageUrl; - } - - public void setRootPageUrl(final String rootPageUrl) { - this.rootPageUrl = rootPageUrl; - } - - public String getUserRedirectUrl() { - return userRedirectUrl; - } - - public void setUserRedirectUrl(final String userRedirectUrl) { - this.userRedirectUrl = userRedirectUrl; - } - - public String getWorkspaceUrl() { - return workspaceUrl; - } - - public void setWorkspaceUrl(final String workspaceUrl) { - this.workspaceUrl = workspaceUrl; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 31 * hash + Objects.hashCode(defaultLayout); - hash = 31 * hash + Objects.hashCode(rootPageUrl); - hash = 31 * hash + Objects.hashCode(userRedirectUrl); - hash = 31 * hash + Objects.hashCode(workspaceUrl); - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof UIConfig)) { - return false; - } - final UIConfig other = (UIConfig) obj; - if (!Objects.equals(rootPageUrl, other.getRootPageUrl())) { - return false; - } - if (!Objects.equals(userRedirectUrl, other.getUserRedirectUrl())) { - return false; - } - if (!Objects.equals(workspaceUrl, other.getWorkspaceUrl())) { - return false; - } - return Objects.equals(defaultLayout, other.getDefaultLayout()); - } - - @Override - public String toString() { -// final StringJoiner joiner = new StringJoiner(", "); -// if (defaultLayout != null) { -// defaultLayout.forEach(s -> joiner.add(s)); -// } - - return String.format("%s{ " - + "defaultLayout = \"%s\", " - + "rootPageUrl = \"%s\", " - + "userRedirectUrl = \"%s\", " - + "workspaceUrl = \"%s\"" - + " }", - super.toString(), - defaultLayout, - rootPageUrl, - userRedirectUrl, - workspaceUrl); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/Assert.java b/ccm-core/src/main/java/com/arsdigita/util/Assert.java deleted file mode 100644 index 528b4cccc..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/Assert.java +++ /dev/null @@ -1,717 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * Utility functions for assertions. - * - *

The static methods in this class provide a standard way of - * asserting certain conditions.

- * - *

Though it is not right now, this class should be final. - * Do not subclass it. In a future revision of this software, this - * class will be made final.

- * - * @author David Lutterkort <dlutter@redhat.com> - * @author Uday Mathur - * @author Justin Ross <jross@redhat.com> - */ -public class Assert { - - /** Class specific logger instance. */ - private static final Logger LOGGER = LogManager.getLogger(Assert.class); - - private static final String DEFAULT_MESSAGE = "Assertion failure"; - - /** - * Configuration by a system wide / servlet container wide environment - * variable is evil and no longer supported API. - * Currently Assertion is set alway on. The non-deprecated methods of this - * class don't check for isEnabled anyway. So there is no effect. - * If configurability is really needed, configuration by config registry - * during system setup (eg. @link com.arsdigita.runtime.CCMResourceManager) - * has to be implemented - */ - private static boolean s_enabled = true; -// private static boolean s_enabled; -// -// static { -// final String enabled = System.getProperty -// (Assert.class.getName() + ".enabled"); -// -// if (enabled == null) { -// //s_enabled = false; -// //default value is true -// s_enabled = true; -// } else { -// // s_enabled = enabled.equals("true"); -// // Test: set to true anyway. -// // TODO: read from config registry, any dependency from a -// // environment variable is deprecated! -// s_enabled = true; -// } -// } - - /** - * Tells whether asserts are turned on. Use this to wrap code - * that should be optimized away if assertions are disabled. - * - * By default, assertions are disabled - */ - public static final boolean isEnabled() { - return s_enabled; - } - - static final void setEnabled(final boolean enabled) { - s_enabled = enabled; - } - - /** - * Throws an error. - * - * @param message A String describing the failure - * condition - * @throws AssertionError - */ - public static final void fail(final String message) { - error(message); - - throw new AssertionError(message); - } - - /** - * Throws an error. - * - * @throws AssertionError - */ - public static final void fail() { - error(DEFAULT_MESSAGE); - - throw new AssertionError(DEFAULT_MESSAGE); - } - - /** - * Asserts that an arbitrary condition is true and throws an - * error with message message if the condition is - * false. - * - * @param condition The condition asserted - * @param message An error message - * @throws AssertionError if the condition is false - */ - public static final void isTrue(final boolean condition, - final String message) { - if (!condition) { - error(message); - - throw new AssertionError(message); - } - } - - /** - * Asserts that an arbitrary condition is true and throws an - * error with message message if the condition is - * false. - * - * @param condition The condition asserted - * @param message An error message - * @throws AssertionError if the condition is false - * @deprecated use Assert.isTrue(condition, message) instead - * (we will follow the standard naming scheme) - */ - public static final void truth(final boolean condition, - final String message) { - Assert.isTrue(condition, message); - - - // if (!condition) { - // error(message); - // - // throw new AssertionError(message); - // } - } - - /** - * Asserts that an arbitrary condition is true and throws an - * error with message message if the condition is - * false. - * - * @param condition The condition asserted - * @throws AssertionError if the condition is false - */ - public static final void isTrue(final boolean condition) { - if (!condition) { - error(DEFAULT_MESSAGE); - - throw new AssertionError(DEFAULT_MESSAGE); - } - } - - /** - * Asserts that an arbitrary condition is true and throws an - * error with message message if the condition is - * false. - * - * @param condition The condition asserted - * @throws AssertionError if the condition is false - * @deprecated use Assert.isTrue(final boolean condition) instead - * (we will follow the standard naming scheme) - */ - public static final void truth(final boolean condition) { - Assert.isTrue(condition); - - // if (!condition) { - // error(DEFAULT_MESSAGE); - // - // throw new AssertionError(DEFAULT_MESSAGE); - // } - } - - /** - * Asserts that an arbitrary condition is false and throws an - * error if the condition is true. - * - * @param condition The condition asserted - * @param message An error message - * @throws AssertionError if the condition is false - */ - public static final void isFalse(final boolean condition, - final String message) { - if (condition) { - error(message); - - throw new AssertionError(message); - } - } - - /** - * Asserts that an arbitrary condition is false and throws an - * error if the condition is true. - * - * @param condition The condition asserted - * @throws AssertionError if the condition is false - */ - public static final void isFalse(final boolean condition) { - if (condition) { - error(DEFAULT_MESSAGE); - - throw new AssertionError(DEFAULT_MESSAGE); - } - } - - /** - * Asserts that an object is not null. - * - * @param object The object that must not be null - * @param clacc The Class of parameter - * object - * @throws AssertionError if the object is null - */ - public static void exists(final Object object, - final Class clacc) { - if (object == null) { - final String message = clacc.getName() + " is null"; - - error(message); - - throw new AssertionError(message); - } - } - - /** - * Asserts that an object is not null. - * - * @param object The Object that must not be null - * @param label A text to describe Object - * - * @throws AssertionError if the object is null - */ - public static void exists(final Object object, - final String label) { - if (object == null) { - final String message = - label != null && !label.isEmpty() - ? "Value of " + label + " is null." - : DEFAULT_MESSAGE ; - - error(message); - - throw new AssertionError(message); - } - } - - /** - * Asserts that an object is not null. - * - * @param object The object that must not be null - * @throws AssertionError if the object is null - */ - public static final void exists(final Object object) { - if (object == null) { - error(DEFAULT_MESSAGE); - - throw new AssertionError(DEFAULT_MESSAGE); - } - } - - /** - * Verifies that Lockable is locked and throws an - * error if it is not. - * - * @param lockable The object that must be locked - * @see com.arsdigita.util.Lockable - */ - public static final void isLocked(final Lockable lockable) { - if (lockable != null && !lockable.isLocked()) { - final String message = "Illegal access: " + lockable + - " is not locked"; - - error(message); - - throw new AssertionError(message); - } - } - - /** - * Verifies that lockable is not locked and - * throws an error if it is. - * - * @param lockable The object that must not be locked - * @see com.arsdigita.util.Lockable - */ - public static final void isUnlocked(final Lockable lockable) { - if (lockable != null && lockable.isLocked()) { - final String message = "Illegal access: " + lockable + " is locked."; - - error(message); - - throw new AssertionError(message); - } - } - - /** - * Verifies that two values are equal (according to their equals - * method, unless value1 is null, then according to - * ==). - * - * @param value1 The first value to be compared - * @param value2 The second - * @throws AssertionError if the arguments are unequal - */ - public static final void isEqual(final Object value1, - final Object value2) { - if (value1 == null) { - if (value2 != null) { - final String message = "null does not equal " + value2; - - error(message); - - throw new AssertionError(message); - } - } else { - if (!value1.equals(value2)) { - final String message = value1 + " does not equal " + value2; - - error(message); - - throw new AssertionError(message); - } - } - } - - /** - * Verifies that two values are equal (according to their equals - * method, unless value1 is null, then according to - * ==). - * - * @param value1 The first value to be compared - * @param value2 The second - * @throws AssertionError if the arguments are unequal - */ - public static final void isEqual(final Object value1, - final Object value2, - final String message) { - if (value1 == null) { - if (value2 != null) { - error(message); - - throw new AssertionError(message); - } - } else { - if (!value1.equals(value2)) { - error(message); - - throw new AssertionError(message); - } - } - } - - /** - * Verifies that two values are not equal (according to their - * equals method, unless value1 is null, then - * according to ==). - * - * @param value1 The first value to be compared - * @param value2 The second - * @throws AssertionError if the arguments are isNotEqual - */ - public static final void isNotEqual(final Object value1, - final Object value2) { - if (value1 == null) { - if (value2 == null) { - final String message = "null equals null"; - - error(message); - - throw new AssertionError(message); - } - } else { - if (value1.equals(value2)) { - final String message = value1 + " equals " + value2; - - error(message); - - throw new AssertionError(message); - } - } - } - - // Utility methods - - private static void error(final String message) { - // Log the stack trace too, since we still have code that - // manages to hide exceptions. - LOGGER.error(message, new AssertionError(message)); - } - - /////////////////////////////////////////////////////////////////////////// - // // - // The methods below are all deprecated. // - // // - /////////////////////////////////////////////////////////////////////////// - - /** - * @deprecated in favor of {@link #isEnabled()} - * - * pboy Jan.09: not used by any package in trunk - */ - // public static final boolean ASSERT_ON = true; - - /** - * Indicates state of the ASSERT_ON flag. - * - * pboy Jan.09: not used by any package in trunk - * - * @deprecated Use {@link #isEnabled()} instead - */ - // public static final boolean isAssertOn() { - // return isEnabled(); - // } - -// /** -// * Tells whether asserts are turned on. Use this to wrap code -// * that should be optimized away if asserts are disabled. -// * -// * @deprecated Use {@link #isEnabled()} instead -// */ -// public static final boolean isAssertEnabled() { -// return isEnabled(); -// } - - /** - * Assert that an arbitrary condition is true, and throw an - * exception if the condition is false. - * - * @param cond condition to assert - * @throws java.lang.IllegalStateException condition was false - * @deprecated Use {@link #truth(boolean, String)} instead - */ -/* public static final void isTrue(boolean cond) { - isTrue(cond, ""); - } -*/ - /** - * Assert that an arbitrary condition is true, and throw an - * exception with message msg if the condition is - * false. - * - * @param cond condition to assert - * @param msg failure message - * @throws java.lang.IllegalStateException condition was false - * @deprecated Use {@link #truth(boolean,String)} instead - */ -/* public static final void assertTrue(boolean cond, String msg) { - if (!cond) { - error(msg); - - throw new IllegalStateException(msg); - } - } -*/ - /** - * Asserts that an arbitrary condition is true and throws an - * error with message message if the condition is - * false. - * - * @param condition The condition asserted - * @param message An error message - * @throws AssertionError if the condition is false - * @deprecated use Assert.isTrue(condition, message) instead - * (we will follow the standard naming scheme) - */ -/* public static final void truth(final boolean condition, - final String message) { - Assert.isTrue(condition, message); - - // if (!condition) { - // error(message); - // - // throw new AssertionError(message); - // } - } -*/ - - /** - * Asserts that an arbitrary condition is true and throws an - * error with message message if the condition is - * false. - * - * @param condition The condition asserted - * @throws AssertionError if the condition is false - * @deprecated use Assert.isTrue(final boolean condition) instead - * (we will follow the standard naming scheme) - */ -/* public static final void truth(final boolean condition) { - Assert.isTrue(condition); - - // if (!condition) { - // error(DEFAULT_MESSAGE); - // - // throw new AssertionError(DEFAULT_MESSAGE); - // } - } -*/ - - /** - * Asserts that an arbitrary condition is false and throws an - * error if the condition is true. - * - * @param condition The condition asserted - * @param message An error message - * @throws AssertionError if the condition is false - */ -/* public static final void falsity(final boolean condition, - final String message) { - if (condition) { - error(message); - - throw new AssertionError(message); - } - } -*/ - - /** - * Asserts that an arbitrary condition is false and throws an - * error if the condition is true. - * - * @param condition The condition asserted - * @throws AssertionError if the condition is false - */ -/* public static final void falsity(final boolean condition) { - if (condition) { - error(DEFAULT_MESSAGE); - - throw new AssertionError(DEFAULT_MESSAGE); - } - } -*/ - /** - * Verify that a parameter is not null and throw a runtime - * exception if so. - * - * @deprecated Use {@link #exists(Object)} instead - */ -/* public static final void assertNotNull(Object o) { - assertNotNull(o, ""); - } -*/ - /** - * Verify that a parameter is not null and throw a runtime - * exception if so. - * - * @deprecated Use {@link #exists(Object,String)} instead - */ -/* public static final void assertNotNull(Object o, String label) { - if (isEnabled()) { - isTrue(o != null, "Value of " + label + " is null."); - } - } -*/ -// /** -// * Verify that a string is not empty and throw a runtime exception -// * if so. A parameter is considered empty if it is null, or if it -// * does not contain any characters that are non-whitespace. -// * -// * @deprecated with no replacement -// */ -// public static final void assertNotEmpty(String s) { -// assertNotEmpty(s, ""); -// } - - /** - * Verify that a string is not empty and throw a runtime exception - * if so. A parameter is considered empty if it is null, or if it - * does not contain any characters that are non-whitespace. - * - * @deprecated with no replacement - */ - public static final void assertNotEmpty(String s, String label) { - if (isEnabled()) { - isTrue(s != null && s.trim().length() > 0, - "Value of " + label + " is empty."); - } - } - - /** - * Verify that two values are equal (according to their equals method, - * unless expected is null, then according to ==). - * - * @param expected Expected value. - * @param actual Actual value. - * @throws java.lang.IllegalStateException condition was false - * @deprecated Use {@link #isEqual(Object,Object)} instead - */ - public static final void assertEquals(Object expected, Object actual) { - assertEquals(expected, actual, "expected", "actual"); - } - - /** - * Verify that two values are equal (according to their equals method, - * unless expected is null, then according to ==). - * - * @param expected Expected value. - * @param actual Actual value. - * @param expectedLabel Label for first (generally expected) value. - * @param actualLabel Label for second (generally actual) value. - * @throws java.lang.IllegalStateException condition was false - */ - public static final void assertEquals(Object expected, - Object actual, - String expectedLabel, - String actualLabel) { - if (isEnabled()) { - if (expected == null) { - isTrue(actual == null, - "Values not equal, " + - expectedLabel + " '" + "null" + "', " + - actualLabel + " '" + actual + "'"); - } else { - isTrue(expected.equals(actual), - "Values not equal, " + - expectedLabel + " '" + expected + "', " + - actualLabel + " '" + actual + "'"); - } - } - } - - /** - * Verify that two values are equal. - * - * @param expected Expected value. - * @param actual Actual value. - * @throws java.lang.IllegalStateException condition was false - * @deprecated Use {@link #truth(boolean, String)} instead - */ - public static final void assertEquals(int expected, int actual) { - assertEquals(expected, actual, "expected", "actual"); - } - - /** - * Verify that two values are equal. - * - * @param expected Expected value. - * @param actual Actual value. - * @param expectedLabel Label for first (generally expected) value. - * @param actualLabel Label for second (generally actual) value. - * @throws java.lang.IllegalStateException condition was false - * @deprecated Use {@link #truth(boolean, String)} instead - */ - public static final void assertEquals(int expected, int actual, - String expectedLabel, - String actualLabel) { - if (isEnabled()) { - isTrue(expected == actual, - "Values not equal, " + - expectedLabel + " '" + expected + "', " + - actualLabel + " '" + actual + "'"); - } - } - - /** - * Verify that the model is locked and throw a runtime exception - * if it is not locked. - * - * @deprecated Use {@link #isLocked(Lockable)} instead - */ -/* public static void assertLocked(Lockable l) { - if (isEnabled()) { - isTrue(l.isLocked(), - "Illegal access to an unlocked " + - l.getClass().getName()); - } - } -*/ - /** - * Verify that the model is locked and throw a runtime exception - * if it is locked. - * -// * @deprecated Use {@link #isUnlocked(Lockable)} instead - */ -/* public static void assertUnlocked(Lockable l) { - if (isEnabled()) { - isTrue(!l.isLocked(), - "Illegal access to a isLocked " + - l.getClass().getName()); - } - } -*/ - /** - * Verifies that lockable is not isLocked and - * throws an error if it is. - * - * @param lockable The object that must not be isLocked - * @see com.arsdigita.util.Lockable -// * @deprecated use isUnlocked(Lockable) instead - */ -/* public static final void unlocked(final Lockable lockable) { - if (lockable != null && lockable.isLocked()) { - final String message = "Illegal access: " + lockable + " is isLocked."; - - error(message); - - throw new AssertionError(message); - } - } -*/ - - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/Classes.java b/ccm-core/src/main/java/com/arsdigita/util/Classes.java deleted file mode 100644 index d206c0dbb..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/Classes.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Constructor; - -import java.util.Arrays; - -/** - * A collection of static utility methods for dealing with Java classes. - * - * @author Justin Ross - */ -public final class Classes { - - /** - * Loads a class from its fully qualified string name. - * - * @param clacc A fully qualified String naming the class to be - * loaded - */ - public static final Class loadClass(final String clacc) { - Assert.exists(clacc, String.class); - - try { - return Class.forName(clacc); - } catch (ClassNotFoundException ex) { - throw new UncheckedWrapperException(ex); - } - } - - /** - * Constructs a new instance of a class using the given parameters. - * - * @param clacc The Class of which to make a new instance - * @param params A Class[] representing the arguments of the - * desired constructor - * @param values An Object[] of values to fill the parameters - */ - public static final Object newInstance(final Class clacc, - final Class[] params, - final Object[] values) { - if (Assert.isEnabled()) { - Assert.exists(clacc, Class.class); - Assert.exists(params, Class.class); - Assert.exists(values, Object.class); - Assert.isTrue(params.length == values.length); - } - - try { - final Constructor constructor = clacc.getConstructor(params); - - return constructor.newInstance(values); - } catch (NoSuchMethodException ex) { - throw new UncheckedWrapperException(message(clacc, params, values), - ex); - } catch (IllegalAccessException ex) { - throw new UncheckedWrapperException(message(clacc, params, values), - ex); - } catch (InvocationTargetException ex) { - throw new UncheckedWrapperException(message(clacc, params, values), - ex); - } catch (InstantiationException ex) { - throw new UncheckedWrapperException(message(clacc, params, values), - ex); - } - } - - private static String message(Class klass, Class[] params, - Object[] values) { - return "class = " + klass + ", params = " + message(params) - + ", values = " + message(values); - } - - private static String message(Object[] array) { - if (array == null) { - return "" + null; - } else { - return Arrays.asList(array).toString(); - } - } - - /** - * Constructs a new instance of the class referred to by clacc. - * - * @param clacc The fully qualified String clacc of the object - * you wish to instantiate - * @param params A Class[] representing the arguments of the - * desired constructor - * @param values An Object[] of values to fill the parameters - */ - public static final Object newInstance(final String clacc, - final Class[] params, - final Object[] values) { - return newInstance(loadClass(clacc), params, values); - } - - /** - * Creates a new instance of clacc using its no-args - * constructor. If the class has no such constructor, it throws a runtime - * exception. - * - * @param clacc The class of which to create a new instance - */ - public static final Object newInstance(final Class clacc) { - return newInstance(clacc, new Class[0], new Object[0]); - } - - /** - * Creates a new instance of the class represented by clacc - * using its no-args constructor. If the class has no such constructor, it - * throws a runtime exception. - * - * @param clacc The fully-qualified String name of the class - */ - public static final Object newInstance(final String clacc) { - return newInstance(loadClass(clacc)); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/ExceptionUnwrapper.java b/ccm-core/src/main/java/com/arsdigita/util/ExceptionUnwrapper.java deleted file mode 100644 index 8171bed18..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/ExceptionUnwrapper.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - - -public interface ExceptionUnwrapper { - Throwable unwrap(Throwable t); -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/Exceptions.java b/ccm-core/src/main/java/com/arsdigita/util/Exceptions.java deleted file mode 100644 index 3f1506a35..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/Exceptions.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import org.apache.logging.log4j.LogManager; - -import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; - -import org.apache.logging.log4j.Logger; - -public class Exceptions { - - private static Logger LOGGER = LogManager.getLogger(Exceptions.class); - - private static Map s_unwrappers = new HashMap(); - - public static Throwable[] unwrap(Throwable t) { - Assert.exists(t, Throwable.class); - - List exceptions = new ArrayList(); - - exceptions.add(t); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Trying to unwrap " + t.getClass()); - } - - Throwable current = t; - - for (;;) { - Throwable inner = null; - ExceptionUnwrapper unwrapper = findUnwrapper(current.getClass()); - - if (unwrapper != null) { - inner = unwrapper.unwrap(current); - } - - if (inner == null) { - Assert.exists(current, Throwable.class); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Returning exception " + current.getClass()); - } - return (Throwable[])exceptions.toArray( - new Throwable[exceptions.size()]); - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Inner exception is " + inner.getClass()); - } - - exceptions.add(inner); - - current = inner; - } - - // Unreachable - //throw new RuntimeException("this cannot happen"); - } - - - public static void registerUnwrapper(Class exception, - ExceptionUnwrapper unwrapper) { - s_unwrappers.put(exception, unwrapper); - } - - public static void unregisterUnwrapper(Class exception) { - s_unwrappers.remove(exception); - } - - public static ExceptionUnwrapper getUnwrapper(Class exception) { - return (ExceptionUnwrapper)s_unwrappers.get(exception); - } - - public static ExceptionUnwrapper findUnwrapper(Class exception) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Finding unwrapper for " + exception.getName()); - } - - Class current = exception; - ExceptionUnwrapper unwrapper = null; - while (unwrapper == null && - current != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Trying class " + current.getName()); - } - unwrapper = (ExceptionUnwrapper)s_unwrappers.get(current); - current = current.getSuperclass(); - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Got unwrapper " + - (unwrapper != null ? unwrapper.getClass() : null)); - } - return unwrapper; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/Graph.java b/ccm-core/src/main/java/com/arsdigita/util/Graph.java deleted file mode 100755 index 24e0492de..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/Graph.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.util.List; - -/** - * The graph class allows you to build graphs of objects. - * - * @author Archit Shah (ashah@mit.edu) - * @author Vadim Nasardinov (vadimn@redhat.com) - * @version $Date$ - * @since 2003-01-22 - **/ -public interface Graph { - /** - * Creates a copy of this graph. - **/ - Graph copy(); - - /** - * Sets the graph's label. - **/ - void setLabel(String label); - - /** - * Returns the graph's label. - **/ - String getLabel(); - - /** - * Adds a node to the graph. - **/ - void addNode(Object node); - - /** - * Returns true if the graph has this node. - **/ - boolean hasNode(Object node); - - - /** - * Returns true if the graph has this edge. - * - * @pre hasNode(edge.getTail()) && hasNode(edge.getHead()) - **/ - boolean hasEdge(Graph.Edge edge); - - /** - * Returns the count of nodes in this graph. - **/ - int nodeCount(); - - /** - * Adds an edge to the graph. - **/ - void addEdge(Graph.Edge edge); - - /** - * A convenient shortcut for addEdge(new Graph.Edge(tail, head, - * label)). - * - * @see #addEdge(Graph.Edge) - **/ - void addEdge(Object tail, Object head, Object label); - - /** - * Returns a list of nodes that this graph has. (Todo: this should probably - * return a Set.) - **/ - List getNodes(); - - /** - * Removes specified node and all edges incident to it. - * - * @returns true if this Graph contains the specified node - **/ - boolean removeNode(Object node); - - /** - * A convenient shortcut for removeEdge(new Graph.Edge(tail, head, - * label)). - * - * @see #removeEdge(Graph.Edge) - **/ - boolean removeEdge(Object tail, Object head, Object label); - - /** - * Removes specified edge. - * - * @returns true if this Graph has the specified edge - **/ - boolean removeEdge(Graph.Edge edge); - - /** - * Removes all nodes and edges. - **/ - void removeAll(); - - /** - * Returns a list of outgoing edges leaving this node. - **/ - List getOutgoingEdges(Object node); - - /** - * Returns the number of outgoing edges this node has. A convenient shortcut - * for getOutgoingEdges(node).size(). - * - * @see #getOutgoingEdges(Object) - **/ - int outgoingEdgeCount(Object node); - - /** - * @see #outgoingEdgeCount(Object) - **/ - int incomingEdgeCount(Object node); - - /** - * @see #getOutgoingEdges(Object) - **/ - List getIncomingEdges(Object node); - - /** - * An edge is an ordered pair of nodes with a label attached to it. The - * first node of the pair is called the tail and the second the - * head. - * - *

Implementing classes are expected to supply a constructor of the form - * Graph.Edge(Object tail, Object head, Object label).

- **/ - interface Edge { - - /** - * Returns the tail node of the edge. - * - * @see #getHead() - **/ - Object getTail(); - - /** - * Returns the head node of the edge. - * - * @see #getTail() - **/ - Object getHead(); - - /** - * Returns the label associated with this edge. The label can be - * anything, depending on your particular graph. For example, if your - * nodes represent cities and edges represent freeways, then the label - * can be an Float representing the the distance (the - * length of the route). - **/ - Object getLabel(); - - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/GraphEdge.java b/ccm-core/src/main/java/com/arsdigita/util/GraphEdge.java deleted file mode 100755 index f969436f4..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/GraphEdge.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -/** - * Graph edge. - * - * @author Archit Shah (ashah@mit.edut) - * @author Vadim Nasardinov (vadimn@redhat.com) - * @since 2003-01-22 - * @version $Revision$ $Date$ - **/ -public final class GraphEdge implements Graph.Edge { - private Object m_tail; - private Object m_head; - private Object m_label; - - /** - * @pre tail != null - * @pre head != null - **/ - public GraphEdge(Object tail, Object head, Object label) { - Assert.exists(tail, Object.class); - Assert.exists(head, Object.class); - m_tail = tail; - m_head = head; - m_label = label; - } - - /** - * @set return != null - **/ - public Object getTail() { - return m_tail; - } - - /** - * @set return != null - **/ - public Object getHead() { - return m_head; - } - - public Object getLabel() { - return m_label; - } - - public String toString() { - StringBuffer buf = new StringBuffer(); - buf.append(m_tail).append(" -> ").append(m_head); - buf.append("[").append(m_label).append("]"); - return buf.toString(); - } - - public boolean equals(Object obj) { - if ( obj == null ) return false; - - if (obj instanceof Graph.Edge) { - Graph.Edge that = (Graph.Edge) obj; - Object thatLabel = that.getLabel(); - - boolean equalLabels = - (m_label == null && thatLabel == null ) || - (m_label != null && m_label.equals(thatLabel)) || - (thatLabel != null && thatLabel.equals(m_label)); - - return - m_tail.equals(that.getTail()) && - m_head.equals(that.getHead()) && - equalLabels; - } else { - return false; - } - } - - public int hashCode() { - return m_tail.hashCode() + m_head.hashCode() + - (m_label == null ? 0 : m_label.hashCode()); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/GraphFormatter.java b/ccm-core/src/main/java/com/arsdigita/util/GraphFormatter.java deleted file mode 100755 index e499fa193..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/GraphFormatter.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -/** - * Implementations of this interface can be used for pretty-printing graphs. - * - * @author Vadim Nasardinov (vadimn@redhat.com) - * @version $Date$ - * @since 2003-01-23 - **/ -public interface GraphFormatter { - - /** - * Returns graph attributes. - * - *

For example, if you choose to pretty-print your graph in the DOT - * language, then the graph attributes section may look like so:

- * - *
-     *  digraph mygraph {
-     *     // the following two lines are graph attributes
-     *     node[shape=box,fontsize=8,fontname=verdana,height=0.2,width=0.2,style=filled];
-     *     ranksep=0.05;
-     *
-     *     // the following lines are nodes and edges
-     *     A -> B -> C -> D;
-     *     B -> E -> F;
-     *     C -> G;
-     *     D -> I;
-     *     D -> J -> H;
-     *  }
-
-     **/
-    String graphAttributes(Graph graph);
-
-    /**
-     * Returns a textual representation of the node, preferably a short one that
-     * can be used in the following plain-text representation of the tree.
-     *
-     * 
-     * digraph tree {
-     *     A -> B -> C -> D;
-     *     B -> E -> F;
-     *     C -> G;
-     *     D -> I;
-     *     D -> J -> H;
-     * }
-     * 
- * - *

Example implementation:

- * - *
-     *  public String formatNode(Object node) {
-     *      return node == null ? null : ((ObjectType) node).getName();
-     *  }
-     * 
- **/ - String nodeName(Object node); - - /** - * Returns [bracketed] node attributes. - * - *
-     *  digraph g {
-     *      C[label="The C Language"];
-     *      J;
-     *      C -> J;
-     *  }
-     * 
- **/ - String nodeAttributes(Object node); - - /** - * Returns a short textual label describing the edge. - **/ - String edge(Object edge); -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/GraphSet.java b/ccm-core/src/main/java/com/arsdigita/util/GraphSet.java deleted file mode 100755 index 3d4b514a8..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/GraphSet.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.arsdigita.util.Assert; - -/** - * A Set-based implementation of the {@link com.arsdigita.util.Graph} interface. - * Once you've added a node to this graph, you must not mutate the node in a way - * that affects its equals(Object) and hashCode() - * methods. - * - *

This class permits the null node.

- * - *

This implementation is not synchronized..

- * - * @author Archit Shah (ashah@mit.edut) - * @author Vadim Nasardinov (vadimn@redhat.com) - * @since 2003-01-22 - * @version $Date$ - **/ -public class GraphSet implements Graph { - private final static String LINE_SEP = System.getProperty("line.separator"); - - private Set m_nodes = new HashSet(); - private Map m_outgoingEdges = new HashMap(); - private Map m_incomingEdges = new HashMap(); - private String m_label = "directed_graph"; - - public Graph copy() { - Graph newGraph = new GraphSet(); - for (Iterator nodes = getNodes().iterator(); nodes.hasNext(); ) { - Object node = nodes.next(); - newGraph.addNode(node); - for (Iterator edges=getOutgoingEdges(node).iterator(); edges.hasNext(); ) { - Graph.Edge edge = (Graph.Edge) edges.next(); - newGraph.addEdge(edge.getTail(), edge.getHead(), edge.getLabel()); - } - } - newGraph.setLabel(getLabel()); - return newGraph; - } - - public void setLabel(String label) { - Assert.isTrue(label !=null, "label is not null"); - m_label = label; - } - - public String getLabel() { - return m_label; - } - - public void addNode(Object name) { - m_nodes.add(name); - } - - public boolean hasNode(Object nodeName) { - return m_nodes.contains(nodeName); - } - - /** - * @pre hasNode(edge.getTail()) && hasNode(edge.getHead()) - **/ - public boolean hasEdge(Graph.Edge edge) { - return outgoingEdges(edge.getTail()).contains(edge); - } - - public int nodeCount() { - return m_nodes.size(); - } - - public void addEdge(Graph.Edge edge) { - m_nodes.add(edge.getTail()); - m_nodes.add(edge.getHead()); - outgoingEdges(edge.getTail()).add(edge); - incomingEdges(edge.getHead()).add(edge); - } - - public void addEdge(Object tail, Object head, Object label) { - addEdge(new GraphEdge(tail, head, label)); - } - - public List getNodes() { - return new ArrayList(m_nodes); - } - - public boolean removeNode(Object nodeName) { - boolean hasNode = m_nodes.remove(nodeName); - if (hasNode) { - Set out = (Set) m_outgoingEdges.remove(nodeName); - if (out != null) { - for (Iterator it = out.iterator(); it.hasNext(); ) { - Graph.Edge e = (Graph.Edge) it.next(); - incomingEdges(e.getHead()).remove(e); - } - } - Set in = (Set) m_incomingEdges.remove(nodeName); - if (in != null) { - for (Iterator it = in.iterator(); it.hasNext(); ) { - Graph.Edge e = (Graph.Edge) it.next(); - outgoingEdges(e.getTail()).remove(e); - } - } - } - return hasNode; - } - - public boolean removeEdge(Object tail, Object head, Object label) { - return removeEdge(new GraphEdge(tail, head, label)); - } - - public boolean removeEdge(Graph.Edge edge) { - boolean hasEdge = outgoingEdges(edge.getTail()).remove(edge); - if (hasEdge) { incomingEdges(edge.getHead()).remove(edge); } - return hasEdge; - } - - public void removeAll() { - m_nodes.clear(); - m_outgoingEdges.clear(); - m_incomingEdges.clear(); - } - - private Set outgoingEdges(Object nodeName) { - Set edges = (Set) m_outgoingEdges.get(nodeName); - if (edges == null) { - edges = new HashSet(4); - m_outgoingEdges.put(nodeName, edges); - } - - return edges; - } - - private static String objToString(Object obj) { - return obj == null ? "null" : obj.toString(); - } - - public List getOutgoingEdges(Object node) { - Assert.isTrue(hasNode(node), objToString(node)); - return new ArrayList(outgoingEdges(node)); - } - - public int outgoingEdgeCount(Object node) { - Assert.isTrue(hasNode(node), objToString(node)); - return outgoingEdges(node).size(); - } - - public int incomingEdgeCount(Object node) { - Assert.isTrue(hasNode(node), objToString(node)); - return incomingEdges(node).size(); - } - - private Set incomingEdges(Object nodeName) { - Set edges = (Set) m_incomingEdges.get(nodeName); - if ( edges == null ) { - edges = new HashSet(); - m_incomingEdges.put(nodeName, edges); - } - return edges; - } - - public List getIncomingEdges(Object node) { - Assert.isTrue(hasNode(node), objToString(node)); - return new ArrayList(incomingEdges(node)); - } - - /** - * Returns a printable representation of the graph that has the following - * form. - * - *
-     * digraph foo {
-     *     Boston -> New_York [label="214 miles"];
-     *     Boston -> Chicago [label="983 miles"];
-     *     New_York -> Chicago [label="787 miles"];
-     *     Boston -> Westford [label="35 miles"];
-     *     Raleigh -> Westford [label="722 miles"];
-     * }
-     * 
- * - *

Note that to get a neat printable representation, each node and edge - * label must have a short printable representation.

- **/ - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("graph ").append(getLabel()).append(" {"); - sb.append(LINE_SEP); - List sortedNodes = new ArrayList(m_nodes); - Collections.sort(sortedNodes); - for (Iterator nodes=sortedNodes.iterator(); nodes.hasNext(); ) { - Object node = nodes.next(); - for (Iterator edges = getOutgoingEdges(node).iterator(); edges.hasNext(); ) { - Graph.Edge edge = (Graph.Edge) edges.next(); - sb.append(" "); - sb.append(objToString(node)).append(" -> "); - sb.append(objToString(edge.getHead())); - sb.append("[label=\"").append(edge.getLabel()); - sb.append("\"];"); - sb.append(LINE_SEP); - } - } - sb.append("}"); - return sb.toString(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/Graphs.java b/ccm-core/src/main/java/com/arsdigita/util/Graphs.java deleted file mode 100755 index e92130e66..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/Graphs.java +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.Stack; - -/** - * A collection of methods that operate on {@link com.arsdigita.util.Graph - * graphs}. - * - * @author Archit Shah (ashah@mit.edu) - * @author Vadim Nasardinov (vadimn@redhat.com) - * @version $Date$ - * @since 2003-01-22 - **/ -public class Graphs { - - /** - * A simple implementation of the {@link Graphs.EdgeSelector} interface that - * selects outgoing edges. - **/ - public final static EdgeSelector FORWARD_SELECTOR = new EdgeSelector() { - public boolean test(Graph.Edge edge, boolean forward) { - return forward; - } - }; - - private static final String INDENT = " "; - - private Graphs() {} - - /** - * Finds a path in graph from begin to end - * - * @see #findPath(Graph, Object, Graphs.EdgeSelector, Graphs.NodeSelector) - * @returns list of edges representing the found path - * @throws NullPointerException if any of the three arguments is null. - **/ - public static final List findPath(Graph graph, Object begin, Object end) { - NodeSelector terminator = new EqualityTerminator(end); - return findPath(graph, begin, FORWARD_SELECTOR, terminator); - } - - /** - * Performs a traversal of graph looking for path that starts - * with startNode and terminates with a node that satisfies the - * test specified by terminator and consists only of those - * edges that satisfy the test specified by selector. - * - * @return a path from start node to a node that satisfies the condition - * specified by terminator, such that all edges in the path - * satisfy the condition specified by selector. An empty list - * is returned, if no such path can be found. - **/ - public static List findPath(Graph graph, Object startNode, - EdgeSelector selector, - NodeSelector terminator) { - - Stack path = new Stack(); - findPathRecur - (graph, startNode, selector, terminator, new HashSet(), path); - return path; - } - - - private static final boolean findPathRecur - (Graph graph, Object start, - EdgeSelector selector, NodeSelector terminator, - Set searched, Stack path) { - - Iterator it = graph.getOutgoingEdges(start).iterator(); - searched.add(start); - - while (it.hasNext()) { - Graph.Edge edge = (Graph.Edge) it.next(); - if ( !selector.test(edge, true) ) { continue; } - - path.push(edge); - final Object node = edge.getHead(); - - if (terminator.test(node)) { - return true; - } - - if (!searched.contains(node)) { - boolean found = findPathRecur - (graph, node, selector, terminator, searched, path); - - if ( found ) { return true; } - } - path.pop(); - } - return false; - } - - /** - * @param edgePath a list of edges such as the one returned by - * {@link #findPath(Graph, Object, Object)}. - * @return the same path represented as a list of nodes rather than edges. - * - * @throws IllegalStateException if edgePath is not a valid - * path. For example, (a->b, c->d, d->e) is invalid, because - * the edge between b and c is missing. - * @throws NullPointerException if edgePath is null - **/ - public static final List edgePathToNodePath(List edgePath) { - List path = new ArrayList(); - Graph.Edge lastEdge = null; - for (Iterator edges = edgePath.iterator(); edges.hasNext(); ) { - Graph.Edge edge = (Graph.Edge) edges.next(); - if ( lastEdge != null ) { - if ( !lastEdge.getHead().equals(edge.getTail()) ) { - throw new IllegalArgumentException - ("non-contiguous path segment:\n" + lastEdge + "\n" + - edge); - } - } - path.add(edge.getTail()); - lastEdge = edge; - } - if ( lastEdge != null ) { - path.add(lastEdge.getHead()); - } - return path; - } - - private static String objToString(Object obj) { - return obj == null ? "null" : obj.toString(); - } - - /** - * @return nodes reachable from start, including the - * start node itself. - * - * @pre graph.hasNode(start) - **/ - public static Graph nodesReachableFrom(Graph graph, Object start) { - Assert.isTrue(graph.hasNode(start)); - Graph result = new GraphSet(); - result.addNode(start); - Set processedTails = new HashSet(); - nodesReachableRecurse(graph, start, processedTails, result); - return result; - } - - private static void nodesReachableRecurse(Graph gg, Object currentNode, - Set processedTails, - Graph accumulator) { - - processedTails.add(currentNode); - - for (Iterator edges=gg.getOutgoingEdges(currentNode).iterator(); edges.hasNext(); ) { - Graph.Edge edge = (Graph.Edge) edges.next(); - if ( processedTails.contains(edge.getHead()) ) { - continue; - } - accumulator.addEdge(edge); - nodesReachableRecurse - (gg, edge.getHead(), processedTails, accumulator); - } - } - - /** - * Returns a list of nodes in gg that have no outgoing edges. - **/ - public static List getSinkNodes(Graph gg) { - List result = new ArrayList(); - for (Iterator nodes = gg.getNodes().iterator(); nodes.hasNext(); ) { - Object node = nodes.next(); - if ( gg.getOutgoingEdges(node).size() == 0 ) { - result.add(node); - } - } - return result; - } - - /** - * Pretty-prints the tree in a format patterned off of the DOT - * language. - * - * @pre tree != null - * @pre fmtr != null - * @pre writer != null - **/ - public static void printTree(Tree tree, GraphFormatter fmtr, - PrintWriter writer) { - - Assert.exists(tree, "tree"); - Assert.exists(fmtr, "formatter"); - Assert.exists(writer, "writer"); - - writer.println("digraph " + tree.getLabel() + " {"); - printTreeRecurse(tree, fmtr, writer); - writer.println("}"); - } - - private static void printTreeRecurse(Tree tree, GraphFormatter fmtr, - PrintWriter writer) { - - String root = fmtr.nodeName(tree.getRoot()); - for (Iterator ii=tree.getSubtrees().iterator(); ii.hasNext(); ) { - Tree.EdgeTreePair pair = (Tree.EdgeTreePair) ii.next(); - String edge = fmtr.edge(pair.getEdge()); - String child = fmtr.nodeName(pair.getTree().getRoot()); - writer.print(INDENT + root + " -> " + child); - if ( edge != null ) { - writer.print("[label=\"" + edge + "\"]"); - } - writer.println(";"); - printTreeRecurse(pair.getTree(), fmtr, writer); - } - } - - /** - * Pretty-prints the graph. - * - * @see #printTree(Tree, GraphFormatter, PrintWriter) - * @pre graph != null - * @pre fmtr != null - * @pre writer != null - **/ - public static void printGraph(Graph graph, GraphFormatter fmtr, - PrintWriter writer) { - - Assert.exists(graph, "tree"); - Assert.exists(fmtr, "formatter"); - Assert.exists(writer, "writer"); - - writer.println("digraph " + graph.getLabel() + " {"); - String graphAttrs = fmtr.graphAttributes(graph); - if ( graphAttrs != null ) { - writer.println(graphAttrs); - } - for (Iterator nodes=graph.getNodes().iterator(); nodes.hasNext(); ) { - Object node = nodes.next(); - int nodeCount = graph.outgoingEdgeCount(node) + - graph.incomingEdgeCount(node); - - String nodeName = fmtr.nodeName(node); - String nodeAttrs = fmtr.nodeAttributes(node); - - if ( nodeCount==0 || nodeAttrs != null ) { - writer.print(INDENT + nodeName); - - if ( nodeAttrs == null ) { - writer.println(";"); - } else { - writer.println(nodeAttrs + ";"); - } - } - - if (graph.outgoingEdgeCount(node) == 0) { - // we'll print this node when we print the outgoing edges of - // some other node - continue; - } - Iterator edges = graph.getOutgoingEdges(node).iterator(); - while (edges.hasNext()) { - Graph.Edge edge = (Graph.Edge) edges.next(); - StringBuffer sb = new StringBuffer(); - sb.append(INDENT).append(fmtr.nodeName(edge.getTail())); - sb.append(" -> ").append(fmtr.nodeName(edge.getHead())); - if ( edge.getLabel() != null ) { - sb.append("[label=\""); - sb.append(fmtr.edge(edge.getLabel())); - sb.append("\"]"); - } - sb.append(";"); - writer.println(sb.toString()); - } - } - writer.println("}"); - } - - /** - * @see #findPath(Graph, Object, Graphs.EdgeSelector, Graphs.NodeSelector) - **/ - public interface EdgeSelector { - /** - * @param edge the edge to test - * @param forward the value of false indicates that an edge - * is to be traversed backwards. Useful, when you want to find a path - * starting with the destination and working your way back to the - * source. The value true indicates that edge is being - * considered for traversal in the natural, forward direction. - **/ - boolean test(Graph.Edge edge, boolean forward); - } - - /** - * @see #findPath(Graph, Object, Graphs.EdgeSelector, Graphs.NodeSelector) - **/ - public interface NodeSelector { - boolean test(Object node); - } - - public final static class EqualityTerminator implements NodeSelector { - private Object m_node; - - /** - * @throws NullPointerException if node is null - **/ - public EqualityTerminator(Object node) { - if (node==null) { throw new NullPointerException("node"); } - - m_node = node; - } - - public boolean test(Object node) { - return m_node.equals(node); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/IO.java b/ccm-core/src/main/java/com/arsdigita/util/IO.java deleted file mode 100755 index 910c0197d..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/IO.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.IOException; - -/** - * A library of methods for dealing with I/O streams. - */ -public class IO { - - /** - * Copies the contents of an input stream to another - * output stream. - * - * @param src the source file to be sent - * @param dst the destination to send the file to - */ - public static void copy(InputStream src, - OutputStream dst) - throws IOException { - - byte buf[] = new byte[4096]; - int ret; - - while ((ret = src.read(buf)) != -1) { - dst.write(buf, 0, ret); - } - - dst.flush(); - } - - - // XXX add a method that, given a InputStream - // figures out what character set the containing - // document is, ie reads the XML prolog. - // Also have similar char set discovery APIs - // for HttpServletRequest objects. -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/JavaPropertyReader.java b/ccm-core/src/main/java/com/arsdigita/util/JavaPropertyReader.java deleted file mode 100644 index 3c3e6c9af..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/JavaPropertyReader.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import com.arsdigita.util.parameter.ErrorList; -import com.arsdigita.util.parameter.Parameter; -import com.arsdigita.util.parameter.ParameterReader; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * An implementation of ParameterReader that uses - * standard Java properties to retrieve values. - * - * Subject to change. - * - * @see com.arsdigita.util.parameter.ParameterReader - * @see JavaPropertyWriter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class JavaPropertyReader implements ParameterReader { - - private static final Logger LOGGER = LogManager.getLogger - (JavaPropertyReader.class); - - private final Properties m_props; - - /** - * Constructs a parameter reader that uses props. - * - * @param props The Properties object that stores - * property values; it cannot be null - */ - public JavaPropertyReader(final Properties props) { - Assert.exists(props, Properties.class); - - m_props = props; - } - - /** - * Loads the internal Properties object using - * in. - * - * @param in The InputStream that has the source - * properties; it cannot be null - */ - public final void load(final InputStream in) { - Assert.exists(in, InputStream.class); - - try { - m_props.load(in); - } catch (IOException ioe) { - throw new UncheckedWrapperException(ioe); - } - } - - /** - * Reads a String value back for a - * param. - * - * @param param The Parameter whose value is - * requested; it cannot be null - * @param errors An ErrorList to trap any errors - * encountered when reading; it cannot be null - * @return The String value for param; - * it can be null - */ - @Override - public final String read(final Parameter param, final ErrorList errors) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Reading " + param + " from " + m_props); - } - - if (Assert.isEnabled()) { - Assert.exists(param, Parameter.class); - Assert.exists(errors, ErrorList.class); - } - - return m_props.getProperty(param.getName()); - } - - /** - * Returns a String representation of this object. - * - * @return super.toString() + "," + properties.size() - */ - @Override - public String toString() { - return super.toString() + "," + m_props.size(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/JavaPropertyWriter.java b/ccm-core/src/main/java/com/arsdigita/util/JavaPropertyWriter.java deleted file mode 100644 index d8c77f5de..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/JavaPropertyWriter.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import com.arsdigita.util.parameter.Parameter; -import com.arsdigita.util.parameter.ParameterWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Properties; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * Subject to change. - * - * An implementation of ParameterWriter that uses - * standard Java properties to store values. - * - * @see com.arsdigita.util.parameter.ParameterWriter - * @see JavaPropertyReader - * @author Justin Ross <jross@redhat.com> - */ -public class JavaPropertyWriter implements ParameterWriter { - - private static final Logger LOGGER = LogManager.getLogger - (JavaPropertyWriter.class); - - private static final String s_header = - " Generated by " + JavaPropertyWriter.class.getName(); - - private final Properties m_props; - - /** - * Constructs a parameter writer that uses props. - * - * @param props The Properties object that stores - * property values; it cannot be null - */ - public JavaPropertyWriter(final Properties props) { - Assert.exists(props, Properties.class); - - m_props = props; - } - - /** - * Tells the internal property object to store its values to - * out. - * - * @param out The OutputStream to send the saved - * parameters to; it cannot be null - */ - public final void store(final OutputStream out) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Storing " + this); - } - - Assert.exists(out, OutputStream.class); - - try { - m_props.store(out, s_header); - } catch (IOException ioe) { - throw new UncheckedWrapperException(ioe); - } - } - - /** - * Writes a String value back for a - * param. - * - * @param param The Parameter whose value is - * to be written; it cannot be null - * @param value The String value to write out; it can - * be null - */ - public final void write(final Parameter param, final String value) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Writing " + param + " with value " + value); - } - - if (Assert.isEnabled()) { - Assert.exists(param, Parameter.class); - } - - // XXX: Properties objects blow up when you try to put null - // values in them. This null check fixes it for now, but it - // doesn't let us explicitly write out a null value if that's - // what we actually want to store. I.e. our property store - // doesn't know the difference between a parameter being - // unspecified and a parameter being explicitly set to null. - if (value != null) { - m_props.setProperty(param.getName(), value); - } - } - - /** - * Returns a String representation of this object. - * - * @return super.toString() + "," + properties.size() - */ - public String toString() { - return super.toString() + "," + m_props.size(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/Lockable.java b/ccm-core/src/main/java/com/arsdigita/util/Lockable.java deleted file mode 100644 index 5a03ba944..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/Lockable.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -/** - * A common interface for all lockable parts of ACS. The locking mechanism makes - * it possible to safely split all data structures that are used inside a web - * server into ones that are constant across all requests and those that may - * change during a request. - * - *

- * The distinction betwen static and request-specific data helps in optimizing - * the amount of memory that needs to be allocated for each request. Data - * structures that are static can be allocated and initialized ahead of time, - * e.g., in the init method of a servlet. The initialized data - * structures are then locked to make them immutable. This mechanism - * ensures that static structures that are supposed to be shared by many - * requests, often even concurrently, do not change and are not "polluted" by - * request-specific data. - * - *

- * There is no automatic mechanism that makes an object immutable by itself. The - * right checks and operations need to be implemented by each class implementing - * Lockable. - * - *

- * Bebop parameters are a good example of how one logical structure is split - * into two classes: the class {@link - * com.arsdigita.bebop.parameters.ParameterModel} is Lockable and - * only contains the description of the parameter in an HTTP request that is - * static and does not change on a per-request basis, such as the name of the - * parameter and the (Java) type that the parameter value should be converted - * to. The class {@link - * com.arsdigita.bebop.parameters.ParameterData} contains all the - * request-specific information for a parameter, such as the value of the - * parameter. - * - *

- * Any class that implements Lockable is expected to be fully - * modifiable until its {@link #lock} method is called. From that point on, it - * is read-only and should throw exceptions whenever an attempt is made to - * modify it. - * - * @author David Lutterkort - * @version $Id$ - */ -public interface Lockable { - - /** - * Lock an object. Locked objects are to be considered immutable. Any - * attempt to modify them, e.g., through a setXXX method should - * lead to an exception. - * - *

- * Most lockable Bebop classes throw an {@link - * java.lang.IllegalStateException} if an attempt is made to modify a locked - * instance. - */ - void lock(); - - /** - * Return whether an object is locked and thus immutable, or can still be - * modified. - * - * @return {@code true} if the object is immutable, {@code false} otherwise. - */ - boolean isLocked(); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/LockableImpl.java b/ccm-core/src/main/java/com/arsdigita/util/LockableImpl.java deleted file mode 100644 index 0e9d5faf2..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/LockableImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -/** - * A generic implementation of the Lockable interface. - * - * @see Lockable - * - * @author Michael Bryzek - * @version $Id$ - * - */ -public class LockableImpl implements Lockable { - - private boolean m_locked = false; - - /** - * Lock an object. Locked objetcs are to be considered immutable. Any - * attempt to modify them, e.g., through a setXXX method should - * lead to an exception. - * - * @see Lockable#lock() - * - */ - // must not be final so cms.ui.Grid.GridModelBuilder can override it. - @Override - public void lock() { - m_locked = true; - } - - /** - * Return whether an object is locked and thus immutable, or can still be - * modified. - * - * @return - * - * @see Lockable#isLocked() - * - */ - // must not be final so cms.ui.PropertySheet.PSTMBAdapter can override it. - @Override - public boolean isLocked() { - return m_locked; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/OrderedMap.java b/ccm-core/src/main/java/com/arsdigita/util/OrderedMap.java deleted file mode 100644 index e585537d0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/OrderedMap.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import org.apache.logging.log4j.LogManager; - -import java.util.TreeMap; -import java.util.HashMap; -import java.util.Comparator; - -import org.apache.logging.log4j.Logger; - -/** - * An implementation of Map which preserves the order in which you put - * entries into it. - * - * @deprecated use {@link com.arsdigita.util.SequentialMap} instead - * @author Justin Ross <jross@redhat.com> - */ -public class OrderedMap extends TreeMap { - - private static final Logger LOGGER = LogManager.getLogger(OrderedMap.class); - - private OrderingComparator m_comparator; - - public OrderedMap() { - super(new OrderingComparator()); - - m_comparator = (OrderingComparator) comparator(); - } - - /** - * Calls to put define the order in which the OrderedMap returns - * its contents in calls to entrySet().iterator(); - */ - public Object put(final Object key, final Object value) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Adding a new map entry: " + key + " => " + value); - } - - m_comparator.keep(key); - - return super.put(key, value); - } - - public Object clone() { - final OrderedMap result = (OrderedMap) super.clone(); - - result.m_comparator = (OrderingComparator) m_comparator.clone(); - - return result; - } - - public void clear() { - super.clear(); - - m_comparator.clear(); - } -} - -final class OrderingComparator implements Comparator, Cloneable { - private static final Logger LOGGER = LogManager.getLogger - (OrderingComparator.class); - - private HashMap m_sortKeyMap = new HashMap(); - private long m_currSortKey = 0; - - public final int compare(final Object o1, final Object o2) { - Long sk1 = (Long) m_sortKeyMap.get(o1); - Long sk2 = (Long) m_sortKeyMap.get(o2); - - if (sk1 == null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("The sort key of " + o1 + " is null; " + - "returning 1"); - } - - return 1; - } else if (sk2 == null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("The sort key of " + o2 + " is null; " + - "returning -1"); - } - - return -1; - } else { - final int result = (int) (sk1.longValue() - sk2.longValue()); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("The sort key of " + o1 + " is " + - sk1.longValue()); - LOGGER.debug("The sort key of " + o2 + " is " + - sk2.longValue()); - LOGGER.debug("The result is " + result); - } - - if (Assert.isEnabled() && result == 0) { - Assert.isTrue(o1.equals(o2)); - } - - return result; - } - } - - final void keep(final Object key) { - m_sortKeyMap.put(key, new Long(m_currSortKey++)); - } - - protected Object clone() { - try { - final OrderingComparator result = - (OrderingComparator) super.clone(); - - result.m_sortKeyMap = (HashMap) m_sortKeyMap.clone(); - - return result; - } catch (CloneNotSupportedException cnse) { - // I don't think we can get here. - - return null; - } - } - - final void clear() { - m_sortKeyMap.clear(); - m_currSortKey = 0; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/Pair.java b/ccm-core/src/main/java/com/arsdigita/util/Pair.java deleted file mode 100755 index f96c94395..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/Pair.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.util.Map; - -/** - *

- * The simplest possible implementation of Map.Entry. Instances - * of this class contains references to the key and - * value set in the constructor. - *

- * - * @author David Lutterkort - * @version $Id: Pair.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class Pair implements Map.Entry, Cloneable { - - private Object m_key; - private Object m_value; - - /** - *

- * Creates a new Pair instance. - *

- * - * @param key the key for this pair. - * @param value the value for this pair. - */ - public Pair(Object key, Object value) { - m_key = key; - m_value = value; - } - - /** - *

- * Return a shallow copy of this pair. The key and value of the new pair - * refer to the same objects as the key and value in the pair being - * cloned. - *

- * - * @return Object A new pair, referring to the same key and value - */ - protected Object clone() { - return new Pair(m_key, m_value); - } - - /** - *

- * Returns the key corresponding to this pair. - *

- * - * @return Object The key for this pair. - */ - public final Object getKey() { - return m_key; - } - - /** - *

- * Returns the value corresponding to this pair. - *

- * - * @return Object The value for this pair. - */ - public final Object getValue() { - return m_value; - } - - /** - *

- * Replaces the value corresponding to this pair with the specified - * value. - *

- * - * @param new value to be stored in this entry. - * - * @return Object Old value corresponding to the entry. - */ - public Object setValue(Object value) { - Object oldValue = m_value; - - m_value = value; - - return oldValue; - } - - /** - *

- * Compare the specified object with this pair. Returns true if the given - * object is also a Map.Entry and its key and value are - * equal to those of this pair. More formally, two entries e1 and e2 - * represent the same mapping if - *

-     * (e1.getKey()==null ?
-     *     e2.getKey()==null : e1.getKey().equals(e2.getKey()))  &&
-     * (e1.getValue()==null ?
-     *     e2.getValue()==null : e1.getValue().equals(e2.getValue()))
-     * 
- *

- * - * @param o object to be compared for equality with this pair. - * - * @return boolean true if the specified object is equal to this pair as a - * map entry. - */ - public boolean equals(Object o) { - boolean rv = false; - - if (!(o instanceof Map.Entry)) { - rv = false; - } else { - Map.Entry e = (Map.Entry) o; - rv = ( - (m_key == null ? e.getKey() == null : m_key.equals(e.getKey())) && - (m_value == null ? e.getValue() == null : m_value.equals(e.getValue())) - ); - } - - return rv; - } - - /** - *

- * The hash code for this pair. The hash code is the bitwise exclusive or - * of the hash codes of the key and the value. If either of these entries - * is null, its hash code is taken to be 0 in - * the exclusive or. - *

- * - * @return int The hash code of this pair. - */ - public int hashCode() { - return (m_key == null ? 0 : m_key.hashCode()) ^ - (m_value == null ? 0 : m_value.hashCode()); - } - - /** - *

- * Convert this pair to a String. The returned string is of - * the form key=value where key and - * value are the entries in this pair, converted to - * String. - *

- * - * @return String of the form key=value - */ - public String toString() { - return m_key + "=" + m_value; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/ParameterProvider.java b/ccm-core/src/main/java/com/arsdigita/util/ParameterProvider.java deleted file mode 100644 index 90a7cb205..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/ParameterProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.util.Set; -import javax.servlet.http.HttpServletRequest; - -/** - * - * @version$Id$ - */ -public interface ParameterProvider { - - /** - * Return the set of bebop ParameterModels that this provides. - **/ - public Set getModels(); - /** - * Return the URL parameters for this request as a set of bebop - * ParameterData. - **/ - public Set getParams(HttpServletRequest req); -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/Record.java b/ccm-core/src/main/java/com/arsdigita/util/Record.java deleted file mode 100644 index 1078e934e..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/Record.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public abstract class Record { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int the runtime environment and - * set com.arsdigita.util.Record=DEBUG by uncommenting or adding the line. - */ - private static final Logger LOGGER = LogManager.getLogger(Record.class); - - private Class m_class; - private Logger m_log; - private String[] m_fields; - private boolean m_undergoingAccess = false; - - protected Record(Class clacc, Logger log, String[] fields) { - m_class = clacc; - m_fields = fields; - m_log = log; - } - - protected final void accessed(String field) { - if (m_log.isDebugEnabled()) { - synchronized (this) { - if (m_undergoingAccess == false) { - final Method accessor = accessor(field); - - m_undergoingAccess = true; - final String value = prettyLiteral(value(accessor)); - m_undergoingAccess = false; - - m_log.debug("Returning " + value + " for " + field); - } - } - } - } - - protected final void mutated(String field) { - if (m_log.isInfoEnabled()) { - final Method accessor = accessor(field); - - m_undergoingAccess = true; - final String value = prettyLiteral(value(accessor)); - m_undergoingAccess = false; - - m_log.info(field + " set to " + value); - } - } - - private String prettyLiteral(final Object o) { - if (o == null) { - return null; - } else if (o instanceof String) { - return "\"" + o + "\""; - } else { - return o.toString(); - } - } - - private Method accessor(final String field) { - try { - Method method = m_class.getDeclaredMethod("get" + field, - new Class[]{}); - - return method; - } catch (NoSuchMethodException nsme) { - try { - Method method = m_class.getDeclaredMethod("is" + field, - new Class[]{}); - - return method; - } catch (NoSuchMethodException me) { - throw new UncheckedWrapperException(nsme); - } - } - } - - private Object value(final Method m) { - try { - return m.invoke(this, new Object[]{}); - } catch (IllegalAccessException iae) { - throw new UncheckedWrapperException(iae); - } catch (InvocationTargetException ite) { - throw new UncheckedWrapperException(ite); - } - } - - public final String getCurrentState() { - final StringBuffer info = new StringBuffer(); - - for (int i = 0; i < m_fields.length; i++) { - final Method method = accessor(m_fields[i]); - final String name = method.getName(); - final String value = prettyLiteral(value(method)); - final int len = name.length(); - - if (len < 30) { - for (int j = 0; j < 30 - len; j++) { - info.append(' '); - } - } - - info.append(name); - info.append("() -> "); - info.append(value); - info.append("\n"); - } - - return info.toString(); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/SequentialMap.java b/ccm-core/src/main/java/com/arsdigita/util/SequentialMap.java deleted file mode 100755 index c23b3b388..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/SequentialMap.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - *

- * A map that keeps its entries in a fixed sequence. All iterators returned - * by this class, for example by entrySet().iterator(), are - * guaranteed to return the entries in the order in which they were put in - * the map. This implementation allows null for both the key - * or the associated value for a map entry. - *

- * - *

- * Almost all of the map operations, for example {@link #get get} or {@link - * #containsKey containsKey} require time linear in the size of the map, - * making this map only suitable for small map sizes. - *

- * - * @author David Lutterkort - * @version $Id: SequentialMap.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class SequentialMap extends AbstractMap implements Map { - - private ArrayList m_entries = null; - private Set m_entrySet = null; - - /** - *

- * Creates an empty SequentialMap. - *

- */ - public SequentialMap() { - m_entries = new ArrayList(); - } - - /** - *

- * Return the number of entries in the map. - *

- * - * @return int the number of entries. - */ - public int size() { - return m_entries.size(); - } - - /** - *

- * Index of the entry with the given key. key may be null. - *

- * - *

- * Requires time linear in the size of the map. - *

- * - * @param key the key to find. - * - * @return int the index with key key or -1 if no such entry - * exists. - */ - public int indexOf(Object key) { - int index = -1; - - for (int i = 0; i < size(); i++) { - Map.Entry p = (Map.Entry) m_entries.get(i); - - if (key == null) { - if (p.getKey() == null) { - index = i; - } - } else { - if (key.equals(p.getKey())) { - index = i; - } - } - } - - return index; - } - - /** - *

- * Return true if the map maps one or more keys to the specified - * value. More formally, returns true if and only if this map contains at - * least one mapping to a value v such that - * (value==null ? v==null : value.equals(v)). - *

- * - *

- * Requires time linear in the size of the map - *

- * - * @param value value whose presence in this map is to be tested. - * - * @return true if this map maps one or more keys to the - * specified value. - */ - public boolean containsValue(Object value) { - boolean contains = false; - - for (int i = 0; i < size(); i++) { - Map.Entry p = (Map.Entry) m_entries.get(i); - - if (value == null) { - if (p.getValue() == null) { - contains = true; - } - } else { - if (value.equals(p.getValue())) { - contains = true; - } - } - } - - return contains; - } - - /** - *

- * Returns true if this map contains a mapping for the - * specified key. - *

- * - *

- * Requires time linear in the size of the map. - *

- * - * @param key key whose presence in this map is to be tested. - * - * @return boolean true if this map contains a mapping for the - * specified key. - */ - public boolean containsKey(Object key) { - return (indexOf(key) != -1); - } - - /** - *

- * Returns the value to which this map maps the specified key. Returns - * null if the map contains no mapping for this key. A - * return value of null does not necessarily indicate that - * the map contains no mapping for the key; it's also possible that the - * map explicitly maps the key to null. The - * containsKey operation may be used to distinguish these - * two cases. - *

- * - *

- * Requires time linear in the size of the map. - *

- * - * @param key key whose associated value is to be returned. - * - * @return Object the value to which this map maps the specified key, or - * null if the map contains no mapping for this key. - */ - public Object get(Object key) { - int i = indexOf(key); - - return (i == -1) ? null : ((Map.Entry) m_entries.get(i)).getValue(); - } - - /** - *

- * Returns the value which is stored at the specified sequential - * position in the map. May throw an IndexOutOfBoundsException - * if (index < 0 || index >= size()). - *

- * - *

- * Requires constant time. - *

- * - * @param index The index of the element to return. - * - * @return Object The element at the specified index. - */ - public Object get(int index) { - return ((Map.Entry) m_entries.get(index)).getValue(); - } - - /** - *

- * Returns the key which is stored at the specified sequential - * position in the map. May throw an IndexOutOfBoundsException - * if (index < 0 || index >= size()). - *

- * - *

- * Requires constant time. - *

- * - * @param index The index of the element to return. - * - * @return Object The key of the element at the specified index. - */ - public Object getKey(int index) { - return ((Map.Entry) m_entries.get(index)).getKey(); - } - - /** - * Associates the specified value with the specified key in this map. The - * new entry is appended at the end of the map. If an entry with the same - * key already exists, it is removed first. To change the - * value of an existing key-value pair without changing the position of - * the key, use {@link #update update}. - * - *

- * Requires time linear in the size of the map - * - * @param key key with which the specified value is to be associated. - * - * @param value value to be associated with the specified key. - * - * @return Object The previous value associated with specified key, or - * null if there was no mapping for key. A null return can also - * indicate that the map previously associated null with the - * specified key. - * - * @see #update update - */ - public Object put(Object key, Object value) { - Object result = null; - int i = indexOf(key); - - if (i != -1) { - result = ((Pair) m_entries.get(i)).getValue(); - m_entries.remove(i); - } - m_entries.add(new Pair(key, value)); - - return result; - } - - /** - *

- * Update an existing key-value pair. If an entry with key - * key already exists, it is replaced with the new - * association without changing the place in which the key appears in the - * sequence of keys. If no such entry exists, it is appended at the end. - *

- * - *

- * Requires time linear in the size of the map. - *

- * - * @param key key with which the specified value is to be associated. - * - * @param value value to be associated with the specified key. - * - * @return Object The previous value associated with specified key, or - * null if there was no mapping for key. A null return can also - * indicate that the map previously associated null with the - * specified key. - * - * @see #put put - */ - public Object update(Object key, Object value) { - Object result = null; - int i = indexOf(key); - - if (i != -1) { - result = ((Pair) m_entries.get(i)).getValue(); - m_entries.set(i, new Pair(key, value)); - } else { - m_entries.add(new Pair(key, value)); - } - - return result; - } - - /** - *

- * Removes the mapping for this key from this map if present. - *

- * - * @param key key whose mapping is to be removed from the map. - * - * @return Object The previous value associated with specified key, or null - * if there was no mapping for key. A null return can also indicate - * that the map previously associated null with the specified key. - */ - public Object remove(Object key) { - Object result = null; - int i = indexOf(key); - - if (i != -1) { - result = ((Pair) m_entries.get(i)).getValue(); - m_entries.remove(i); - } - - return result; - } - - /** - *

- * Removes all mappings from this map. - *

- */ - public void clear() { - m_entries.clear(); - } - - /** - *

- * Returns a set view of the mappings contained in this map. Each element - * in the returned set is a Map.Entry. The set is backed by - * the map, so changes to the map are reflected in the set, and - * vice-versa. If the map is modified while an iteration over the set is - * in progress, the results of the iteration are undefined. The set - * supports element removal, which removes the corresponding mapping from - * the map, via the Iterator.remove, - * Set.remove, removeAll, - * retainAll and clear operations. It does not - * support the add or addAll operations. - *

- * - * @return Set A set view of the mappings contained in this map. - * - * @post return != null - */ - public Set entrySet() { - if (m_entrySet == null) { - m_entrySet = new AbstractSet() { - public Iterator iterator() { - return m_entries.iterator(); - } - - public boolean contains(Object o) { - return m_entries.contains(o); - } - - public boolean remove(Object o) { - return m_entries.remove(o); - } - - public int size() { - return m_entries.size(); - } - - public void clear() { - m_entries.clear(); - } - }; - } - - return m_entrySet; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/StringUtils.java b/ccm-core/src/main/java/com/arsdigita/util/StringUtils.java deleted file mode 100644 index 1ef508ca2..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/StringUtils.java +++ /dev/null @@ -1,1111 +0,0 @@ -/* - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.arsdigita.util; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * A (static) class of generally-useful string utilities. - * - * @author Bill Schneider - */ -@SuppressWarnings({"PMD.GodClass", - "PMD.ExcessiveClassLength", "PMD.TooManyMethods", "PMD.CyclomaticComplexity"}) -public final class StringUtils { - - private static final Logger LOGGER = LogManager.getLogger(StringUtils.class); - - public static final String NEW_LINE = System.getProperty("line.separator"); - //html line break: - public static final String LINE_BREAK = "
"; - - private StringUtils() { - // can't instantiate me! - } - - /** - * Tests if a string is empty. - * - * @param str A string to test - * @return true if str is null or empty; otherwise - * false - * - */ - public static boolean emptyString(final String str) { - if (str != null) { - return str.isEmpty(); - } - return true; - } - - /** - * Tests if a string is empty. - * - * @param obj A string to test - * @return true if o is null or empty; otherwise - * false - */ - public static boolean emptyString(final Object obj) { - final boolean expr - = obj == null || obj instanceof String && ((String) obj).length() == 0; - return expr; - } - - /** - * If the String is null, returns an empty string. Otherwise, returns the - * string unaltered - * - * @param str - * @return empty or unalterd string - */ - public static String nullToEmptyString(final String str) { - return (str == null) ? "" : str; - } - - /** - * Escapes some "special" characters in HTML text (ampersand, angle - * brackets, quote). - * - * @param str The plain-text string to quote - * @return The string with special characters escaped. - */ - public static String quoteHtml(final String str) { - if (str == null) { - return ""; - } else { - String result; - result = str.replaceAll("&", "&"); - result = result.replaceAll("\"", """); - result = result.replaceAll("<", "<"); - result = result.replaceAll(">", ">"); - return result; - } - } - - /** - * Takes a plaintext string, and returns an HTML string that, when rendered - * by a web browser, will appear as the original input string - * - * @param str The input plaintext string - * @return A HTML string with blank lines coverted to
<p>
and - * ampersands/angle brackets escaped. - */ - public static String textToHtml(final String str) { - String result; - result = quoteHtml(str); - result = result.replaceAll("\r\n\r\n", "

"); - result = result.replaceAll("\n\n", "

"); - result = result.replaceAll("\r\r", "

"); - result = result.replaceAll("\r\n", LINE_BREAK); - result = result.replaceAll("\n", LINE_BREAK); - result = result.replaceAll("\r", LINE_BREAK); - return result; - } - - /** - * Removes tags and substitutes P tags with newlines. For much more - * extensive conversion of HTML fragments to plain text equivalents, see - * {@link HtmlToText}. - */ - public static String htmlToText(final String str) { - if (str == null) { - return ""; - } else { - // first take out new-lines - String result = str.replaceAll("\n", ""); - result = result.replaceAll("\r", ""); - result = result.replaceAll("<[pP]>", "\n\n"); - result = result.replaceAll(LINE_BREAK, "\n"); - // take out other tags - result = result.replaceAll("<[^>]*>", " "); - return result; - } - } - - /** - * Converts plain text with simple inline markup into HTML. The following - * constructs are recognised: - * - *

    - *
  • *text* generates bold text - *
  • /text/ generates italic text - *
  • =text= generates fixed text - *
  • @text(http://www.google.com) generates a titled link - * text - *
  • http://www.google.com generates an untitled link - * http://www.google.com - *
  • ---
    generates a horizontal line

    - *
  • ___
    generates a horizontal line

    - *
  • - * my item
    - * * my next item
    - * * my final item

    - * generates an bulleted list - *
      - *
    • my item - *
    • my next item - *
    • my final item - *
    - *
  • - * + my item
    - * + my next item
    - * + my final item

    - * generates an enumerated list - *
      - *
    1. my item - *
    2. my next item - *
    3. my final item - *
    - *
  • 1/2, 1/4, 3/4, (C), (TM), (R) generate entities ½, ¼, - * ¾, © TM - * ® - *
- */ - public static String smartTextToHtml(final String str) { - - //first splits the string at every new line -// String blocks2[] = str.split( "\r?\n(\r?(?<=\n))"); -// Arrays.asList(str.split( "?<=\r?\n\r?\n") -// ArrayList blocks = new ArrayList(); - final List blocks = splitUpAtNewLine(str); - -// s_re.split(blocks, "/\\r?\\n(\\r?\\n)+/", s); - final Pattern hrpattern = Pattern.compile("-{3,}|_{3,}"); - final Pattern asterisk = Pattern.compile("^\\*"); - final Pattern plus = Pattern.compile("^\\+"); - final Pattern word = Pattern.compile(".*[a-zA-Z_0-9\\*\\+].*"); // \\w - - final StringBuffer html = new StringBuffer(20); - final Iterator iter = blocks.iterator(); - while (iter.hasNext()) { - final String block = (String) iter.next(); - - final Matcher hrmatcher = hrpattern.matcher(block); - final Matcher asteriskmatcher = asterisk.matcher(block); - final Matcher plusmatcher = plus.matcher(block); - final Matcher wordmatcher = word.matcher(block); - - if (hrmatcher.find()) { // horizontal line - html.append("
"); - } else if (asteriskmatcher.find()) { - html.append(smartTextList("(?m)^\\*+\\s", "ul", block)); //bulleted list - } else if (plusmatcher.find()) { - html.append(smartTextList("(?m)^\\++\\s", "ol", block)); //numerated list - } else if (wordmatcher.find()) { - html.append("
\n" + smartTextInline(block) + "\n
"); - } - html.append('\n'); - } - return html.toString(); - } - - /** - * - * @param match - * @param type - * @param str - * @return - */ - private static String smartTextList(final String match, - final String type, - final String str) { - - final String[] blocks = str.split(match); - - final StringBuffer list = new StringBuffer("<" + type + ">\n"); - - for (int j = 0; j < blocks.length; j++) { - final String block = blocks[j]; - if ("".equals(block)) { - continue; - } - list.append("
  • \n"); - list.append(smartTextInline(block)); - list.append("
  • \n"); - } - list.append(""); - return list.toString(); - } - - /** - * dont use directly, use smartTextToHtml instead - * - * @param str - * @return - */ - private static String smartTextInline(final String str) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Input {" + str + "}"); - } - - // We're going to use the octal characters \u0001 and \u0002 for - // escaping stuff, so we'd better make sure there aren't any - // in the text. - String result; - result = str.replaceAll("[\u0001|\u0002|\u0003]", ""); - - // We transform a few common symbols - result = result.replaceAll("1/4", "¼"); - result = result.replaceAll("1/2", "½"); - result = result.replaceAll("3/4", "¾"); - result = result.replaceAll("\\([Cc]\\)", "©"); - result = result.replaceAll("\\([Rr]\\)", "®"); - result = result.replaceAll("\\(TM\\)|\\(tm\\)", "TM"); - result = result.replaceAll("^\\+", ""); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("After entities {" + result + "}"); - } - - // Next lets process italics /italic/ - result = result.replaceAll("/+([a-zA-Z_0-9]+)+/", "$1"); - // Lets process bold text *bold* - result = result.replaceAll("\\*+([a-zA-Z_0-9]+)+\\*", "$1"); - // Now we're onto the monospace stuff =monospace= - result = result.replaceAll("\\=+([a-zA-Z_0-9]+)+\\=", "$1"); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("After styles {" + result + "}"); - } - - // untitled mailto - //"mailto:dan@berrange.com" to - //"mailto:dan@berrange.com" - result = result.replaceAll("mailto:([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})\\b", - "mailto:$1"); - - //adding a '@' before every untitled link so it does not interfere with - // titled links - result = result.replaceAll("(http[s]*://www\\..+\\.[A-Za-z]{2,4})", - "@$1"); - - // titled Links - //"@google(http://www.google.com) to - //google" - result = result.replaceAll("@(\\w+)\\(@(http*[s]*:*/*/*www\\..+\\.[A-Za-z]{2,4})\\)", - "$1"); - //titled mailto - //"@Dan B(mailto:dan@@berrange.com)" to - //"Dan B" - result = result.replaceAll("@([\\w\\s]+)\\(mailto:([a-zA-Z0-9._%+-]+@@[a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})\\)", - "$1"); - //remove one of the two @'s - result = result.replaceAll("mailto:([a-zA-Z0-9._%+-]+)+@@([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})", - "mailto:$1@$2"); - - //untitled links (which got an '@' in front now) - result = result.replaceAll("@(http[s]*://www\\..+\\.[A-Za-z]{2,4})", - "$1"); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("After links {" + result + "}"); - } - - return result; - } - - /** - * Convert a string of items separated by a separator character to an - * (string)array of the items. sep is the separator character. Example: - * Input - str == "cat,house,dog,," sep==',' Output - {"cat", "house", - * "dog", "" ,""} different to java.lang.String.split(): Input - str == - * "cat,house,dog,," sep==',' Output - {"cat", "house", "dog"} - * - * @param str string contains items separated by a separator character. - * @param sep separator character. - * @return Array of items. - * - */ - public static String[] split(final String str, final char sep) { - final ArrayList arrl = new ArrayList(); - int startpos, endpos; - startpos = 0; - while (startpos < str.length()) { - endpos = str.indexOf(sep, startpos); - if (endpos == -1) { - endpos = str.length(); - } - final String found_item = str.substring(startpos, endpos); - arrl.add(found_item); - startpos = endpos + 1; - } - if (str.length() > 0 && str.charAt(str.length() - 1) == sep) { - arrl.add(""); // In case last character is separator - } - final String[] returnedArray = new String[arrl.size()]; - arrl.toArray(returnedArray); - return returnedArray; - } - - /** - *

    - * Given a string, split it into substrings matching a regular expression - * that you supply. Parts of the original string which don't match the - * regular expression also appear as substrings. The upshot of this is that - * the final substrings can be concatenated to get the original string.

    - * - *

    - * As an example, let's say the original string is:

    - * - *
    -     * str = "/packages/foo/xsl/::vhost::/foo_::locale::.xsl";
    -     * 
    - * - *

    - * We call the function like this:

    - * - *
    -     * output = splitUp (str, "::\\w+::");
    -     * 
    - * - *

    - * The result (output) will be the following list:

    - * - *
    -     * ("/packages/foo/xsl/", "::vhost::", "/foo_", "::locale::", ".xsl")
    -     * 
    - * - *

    - * Notice the important property that concatenating all these strings - * together will restore the original string.

    - * - *

    - * Here is another useful example. To split up HTML into elements and - * content, do:

    - * - *
    -     * output = splitUp (html, "/<.*?>/");
    -     * 
    - * - *

    - * You will end up with something like this:

    - * - *
    -     * ("The following text will be ", "", "bold", "", ".")
    -     * 
    - * - * @param str The original string to split. - * @param regex The regular expression. - * @return List of substrings. - * - * @author Richard W.M. Jones - * - *

    - * This is equivalent to the Perl "global match in array context", - * specifically: @a = /(RE)|(.+)/g;

    - * - */ - public static List splitUp(final String str, final String regex) { - final ArrayList list = new ArrayList(); - final Pattern pattern = Pattern.compile(regex); - String string = str; - while (string != null && string.length() > 0) { - // Find the next match. - final Matcher matcher = pattern.matcher(string); - if (matcher.find()) { - final int start = matcher.start(); - final int end = matcher.end(); - - // String up to the start of the match. - list.add(string.substring(0, start)); - - // Matching part. - list.add(string.substring(start, end)); - - // Update str to be the remainder of the string. - string = string.substring(end); - } else { - // Finished. - list.add(string); - - string = null; - } - } - - return list; - } - - /** - * Splits a String into substrings if there is a linebreak followed by - * anoter linebreak. Keeps the empty line as an own block. needed for - * smartTextToHtml. - * - * @param str The string to split - * @return List - */ - public static List splitUpAtNewLine(final String str) { - final ArrayList list = new ArrayList(); - final Pattern pattern = Pattern.compile("\r?\n\r?\n"); - String string = str; - while (string != null && string.length() > 0) { - // Find the next match. - final Matcher matcher = pattern.matcher(string); - if (matcher.find()) { - final int start = matcher.start(); - final int end = matcher.end(); - - // String up to the start of the match. first block - list.add(string.substring(0, start)); - - // second block, an empty block. - list.add("\n"); - - // Update str to be the remainder of the string. - string = string.substring(end); - } else { - // Finished. - list.add(string); - - string = null; - } - } - return list; - } - - /** - * Converts an array of Strings into a single String separated by a given - * character. Example Input: {"cat", "house", "dog"}, ',' Output - - * "cat,house,dog" - * - * @param strings The string array too join. - * @param joinChar The character to join the array members together. - * - * @pre strings != null - * - * @return Joined String - */ - public static String join(final String[] strings, final char joinChar) { - final StringBuffer result = new StringBuffer(); - final int lastIdx = strings.length - 1; - for (int idx = 0; idx < strings.length; idx++) { - result.append(strings[idx]); - if (idx < lastIdx) { - result.append(joinChar); - } - } - - return result.toString(); - } - - /** - * Converts an array of Strings into a single String separated by a given - * string. Example Input: {"cat", "house", "dog"}, ", " Output - "cat, - * house, dog" - * - * @param strings The string array too join. - * @param joinStr The string to join the array members together. - * - * @pre strings != null - * - * @return Joined String - */ - public static String join(final String[] strings, final String joinStr) { - final StringBuffer result = new StringBuffer(); - final int lastIdx = strings.length - 1; - for (int idx = 0; idx < strings.length; idx++) { - result.append(strings[idx]); - if (idx < lastIdx) { - result.append(joinStr); - } - } - - return result.toString(); - } - - /** - * Extract a parameter value from a packed list of parameter values. - * Example: input: key="age", sep=',', plist="cost=23,age=27,name=Thom" - * output = "27". This is a simple implementation that is meant for - * controlled use in which the key and values are known to be safe. - * Specifically, the equals character must be used to indicate parameter - * assignments. There is no escape character. Thus the parameter names and - * values cannot contain the equals character or the separator character. - * - * @param key the key indicating which parameter value to extract. - * @param plist packed list of key=value assignments. The character '=' must - * be used to indicate the assignment. - * @param sep separator character. - * @return the value corresponding to the key, or null if the key is not - * present. If the key appears in the list more than once, the first value - * is returned. - */ - public static String getParameter(final String key, final String plist, final char sep) { - int keyEnd; - int keyStart = 0; - String foundValue; - while (keyStart < plist.length()) { - keyStart = plist.indexOf(key, keyStart); - if (keyStart == -1) { - return null; // Did not find key - } - keyEnd = keyStart + key.length(); - if (plist.charAt(keyEnd) == '=' - && (keyStart == 0 || plist.charAt(keyStart - 1) == sep)) { - // Found isolated parameter value, this is the match - final int valueEnd = plist.indexOf(sep, keyEnd); - if (valueEnd == -1) { - // did not find another separator, return value - foundValue = plist.substring(keyEnd + 1); - } else { - // found another separator, return value - foundValue = plist.substring(keyEnd + 1, valueEnd); - } - return foundValue; - } else { - keyStart++; // did not find. Advance past current position - } - } - return null; - } - - /** - * Strip extra white space from a string. This replaces any white space - * character or consecutive white space characters with a single space. It - * is useful when comparing strings that should be equal except for possible - * differences in white space. Example: input = "I \ndo\tsee". Output = "I - * do see". - * - * @param str string that may contain extra white space - * @return string the same as the input, but with extra white space removed - * and replaced by a single space. - */ - static public String stripWhiteSpace(final String str) { - final StringBuffer stringbuf = new StringBuffer(); - boolean inSpace = true; - boolean isSpace; - char chr; - for (int i = 0; i < str.length(); i++) { - chr = str.charAt(i); - isSpace = Character.isWhitespace(chr); - if (isSpace) { - if (!inSpace) { - stringbuf.append(' '); - inSpace = true; - } - } else { - stringbuf.append(chr); - inSpace = false; - } - } - return stringbuf.toString().trim(); - } - - /** - * Get a String representation for an Object. If it has an asString method, - * use that; otherwise fall back on toString - */ - public static String toString(final Object obj) { - try { - return (String) obj.getClass().getMethod("asString", null) - .invoke(obj, new Object[0]); - } catch (NoSuchMethodException e) { - return obj.toString(); - - } catch (IllegalAccessException | InvocationTargetException e) { - throw new UncheckedWrapperException("Invoking asString() on an " + obj.getClass(), e); - } - } - - /** - * create a String representation of a map. This method is not too - * necessary, because Map.toString() does almost the same. - */ - public static String toString(final Map map) { - final StringBuffer tostr = new StringBuffer(); - if (map == null) { - tostr.append("null"); - } else { - tostr.append(map.getClass().getName()); - final Set entrySet = map.entrySet(); - if (entrySet == null) { - tostr.append("[null entrySet]"); - } else { - final Iterator entries = entrySet.iterator(); - if (entries == null) { - tostr.append("[null iterator]"); - } else { - tostr.append('{'); - String comma = NEW_LINE; - - while (entries.hasNext()) { - tostr.append(comma); - comma = "," + NEW_LINE; - final Map.Entry entry = (Map.Entry) entries.next(); - - tostr.append(toString(entry.getKey())) - .append(" => ") - .append(toString(entry.getValue())); - } - tostr.append(NEW_LINE).append('}'); - } - } - } - return tostr.toString(); - } - - /** - * Strips all new-line characters from the input string. - * - * @param str a string to strip - * @return the input string with all new-line characters removed. - * @post result.indexOf('\r') == 0 - * @post result.indexOf('\n') == 0 - */ - public static String stripNewLines(final String str) { - - return str.replaceAll("[\\n\\r]", ""); - } - - /** - *

    - * Add a possible newline for proper wrapping.

    - * - *

    - * Checks the given String to see if it ends with whitspace. If so, it - * assumes this whitespace is intentional formatting and returns a reference - * to the original string. If not, a new String object is - * created containing the original plus a platform-dependent newline - * character obtained from {@link System#getProperty(String) - * System.getProperty("line.separator")}.

    - */ - public static String addNewline(final String str) { - final int length = str.length() - 1; - if (length == -1) { - return str; - } else if (Character.isWhitespace(str.charAt(length))) { - return str; - } else { - return str.concat(NEW_LINE); - } - } - - /** - * This takes the passed in string and truncates it. It cuts the string off - * at the length specified and then goes back to the most recent space and - * truncates any word that may have been cut off. It also takes the string - * and converts it to plain text so that no HTML will be shown. - */ - public static String truncateString(final String str, final int length) { - return truncateString(str, length, true); - } - - /** - * This takes the passed in string and truncates it. It cuts the string off - * at the length specified and then goes back to the most recent space and - * truncates any word that may have been cut off. The htmlToText dictates - * whehter or not the string should be converted from HTML to text before - * being truncated - * - * @param str The string to be truncated - * @param length The length which to truncate the string - * @param removeHTML Whether or not to convert the HTML to text - * @return the truncated String - */ - public static String truncateString(final String str, final int length, - final boolean removeHTML) { - if (str == null) { - return ""; - } - - String string = str; - if (removeHTML) { - string = htmlToText(string); - } - - if (string.length() <= length) { - return string; - } - - if (string.lastIndexOf(' ', length) == -1) { - //no whitespace found, so truncate at the specified length even if - // it is in the middle of a word - return string.substring(0, length); - } - - return string.substring(0, string.lastIndexOf(' ', length)).trim(); - } - - /** - * "join" a List of Strings into a single string, with each string separated - * by a defined separator string. - * - * @param elements the strings to join together - * @param sep the separator string - * @return the strings joined together - */ - public static String join(final List elements, final String sep) { - final StringBuffer stringbuf = new StringBuffer(); - boolean first = true; - final Iterator iter = elements.iterator(); - - while (iter.hasNext()) { - final String element = (String) iter.next(); - - if (first) { - first = false; - } else { - stringbuf.append(sep); - } - - stringbuf.append(element); - } - - return stringbuf.toString(); - } - - /** - * Removes whitespace from the beginning of a string. If the string consists - * of nothing but whitespace characters, an empty string is returned. - * - * @param str the String - * @return the String without whitespaces - */ - public static String trimleft(final String str) { - for (int i = 0; i < str.length(); i++) { - if (!Character.isWhitespace(str.charAt(i))) { - return str.substring(i); - } - } - return ""; - } - - /** - * Returns a String containing the specified repeat count of a given pattern - * String. - * - * @param pattern the pattern String - * @param repeatCount the number of time to repeat it - * @return - */ - public static String repeat(final String pattern, final int repeatCount) { - final StringBuffer strb = new StringBuffer(repeatCount * pattern.length()); - for (int i = 0; i < repeatCount; i++) { - strb.append(pattern); - } - return strb.toString(); - } - - /** - * Returns a String containing the specified repeat count of a given pattern - * character. - * - * @param pattern the pattern character - * @param repeatCount the number of time to repeat it - */ - public static String repeat(final char pattern, final int repeatCount) { - return repeat(String.valueOf(pattern), repeatCount); - } - - /** - * Wrap a string to be no wider than 80 characters. This is just a - * convenience method for calling the more general method with a default - * string width. - * - * @param input the String to wrap - * - * @since 5.1.2 - */ - public static String wrap(final String input) { - return wrap(input, 80); - } - - /** - * Wrap a string to be no wider than a specified number of characters by - * inserting line breaks. If the input is null or the empty string, a string - * consisting of only the newline character will be returned. Otherwise the - * input string will be wrapped to the specified line length. In all cases - * the last character of the return value will be a single newline. - * - *

    - * Notes: - * - *

      - *
    1. line breaks in the input string are preserved - *
    2. wrapping is "soft" in that lines in the output string may be longer - * than maxLength if they consist of contiguous non-whitespace characters. - *
    - * - * @param input the String to wrap - * @param maxLength the maximum number of characters between line breaks - * - * @since 5.1.2 - */ - public static String wrap(final String input, final int maxLength) { - - final char ENDL = '\n'; - String formattedInput; - - // Make sure that we start with a string terminated by a - // newline character. Some of the index calculations below - // depend on this. - if (emptyString(input)) { - return String.valueOf(ENDL); - } else { - formattedInput = input.trim() + ENDL; - } - - final StringBuffer output = new StringBuffer(); - - int startOfLine = 0; - - while (startOfLine < formattedInput.length()) { - - final String line = formattedInput.substring(startOfLine, Math.min(formattedInput.length(), - startOfLine + maxLength)); - - if ("".equals(line)) { - break; - } - - final int firstNewLine = line.indexOf(ENDL); - if (firstNewLine != -1) { - - // there is a newline - output.append(formattedInput.substring(startOfLine, - startOfLine + firstNewLine)); - output.append(ENDL); - startOfLine += firstNewLine + 1; - continue; - } - - if (startOfLine + maxLength > formattedInput.length()) { - - // we're on the last line and it is < maxLength so - // just return it - output.append(line); - break; - } - - final char SPACE = ' '; - int lastSpace = line.lastIndexOf(SPACE); - if (lastSpace == -1) { - - // no space found! Try the first space in the whole - // rest of the string - final int nextSpace = formattedInput.indexOf(SPACE, startOfLine); - final int nextNewLine = formattedInput.indexOf(ENDL, startOfLine); - - if (nextSpace == -1) { - lastSpace = nextNewLine; - } else { - lastSpace = Math.min(nextSpace, nextNewLine); - } - - if (lastSpace == -1) { - // didn't find any more whitespace, append the - // whole thing as a line - output.append(formattedInput.substring(startOfLine)); - break; - } - - // code below will add this to the start of the line - lastSpace -= startOfLine; - } - - // append up to the last space - output.append(formattedInput.substring(startOfLine, - startOfLine + lastSpace)); - output.append(ENDL); - - startOfLine += lastSpace + 1; - } - - return output.toString(); - } - - /** - * Returns true if the String is AlphaNumeric. Obviously, this is not at all - * globalized and should only be used with English text. - * - * @param value String to check - * @return true if value is alphanumeric, false otherwise. - */ - public static boolean isAlphaNumeric(final String value) { - return !value.matches("^.*[^a-zA-Z0-9 ].*$"); - } - - /** - * This method performs interpolation on multiple variables. The keys in the - * hash table correspond directly to the placeholders in the string. The - * values in the hash table can either be plain strings, or an instance of - * the PlaceholderValueGenerator interface - * - * Variable placeholders are indicated in text by surrounding a key word - * with a pair of colons. The keys in the hash table correspond to the names - * - * eg. "::forename:: has the email address ::email::" - * - * @see java.text.MessageFormat - * - * @param text the text to interpolate - * @param vars a hash table containing key -> value mappings //// - */ - public static String interpolate(final String text, final Map vars) { - //old perl regex= "(::(?:\\w+(?:[.-]+\\w+)*)::)" - String str = text; - final Pattern pattern = Pattern.compile("::([\\w\\.\\-]+)::"); - final Matcher matcher = pattern.matcher(text); - while (matcher.find()) { - final String key = matcher.group(1); - final String value = (String) vars.get(key); - if (value != null) { - final String regex = "::" + key + "::"; - str = str.replaceAll(regex, value); - } - } - - return str; - } - - /** - * THis method performs a single variable substitution on a string. The - * placeholder takes the form of ::key:: within the sample text. - * - * @see java.text.MessageFormat - * - * @param text the text to process for substitutions - * @param key the name of the placeholder - * @param value the value to insert upon encountering a placeholder - */ - public static String interpolate(final String text, final String key, final String value) { - final String regex = "::" + key + "::"; - - return text.replaceAll(regex, value); - } - - /** - * Finds all occurrences of find in str and - * replaces them with them with replace. - * - * @pre find != null - * @pre replace != null - */ - public static String replace(final String str, - final String find, - final String replace) { - if (str == null) { - return null; - } - return str.replace(find, replace); - } - - /** - * @throws IllegalArgumentException if throwable is null - */ - public static String getStackTrace(final Throwable throwable) { - if (throwable == null) { - throw new IllegalArgumentException(); - } - - final StringWriter strw = new StringWriter(); - final PrintWriter prntw = new PrintWriter(strw); - throwable.printStackTrace(prntw); - prntw.close(); - return strw.toString(); - } - - /** - * Returns a list of lines where each line represents one level in the stack - * trace captured by throwable. - * - *

    - * For a stack trace like this:

    - * - *
    -     * java.lang.Throwable
    -     *         at Main.level3(Main.java:19)
    -     *         at Main.level2(Main.java:15)
    -     *         at Main.level1(Main.java:11)
    -     *         at Main.main(Main.java:7)
    -     * 
    - * - *

    - * the returned list looks like this:

    - * - *
    -     * ["java.lang.Throwable",
    -     *  "Main.level3(Main.java:20)",
    -     *  "Main.level2(Main.java:15)",
    -     *  "Main.level1(Main.java:11)",
    -     *  "Main.main(Main.java:7)"]
    -     * 
    - * - * @see #getStackTrace(Throwable) - * @throws NullPointerException if throwable is null - */ - public static List getStackList(final Throwable throwable) { - final StringTokenizer tkn = new StringTokenizer(getStackTrace(throwable), System.getProperty("line.separator")); - final List list = new LinkedList(); - while (tkn.hasMoreTokens()) { - final String token = tkn.nextToken().trim(); - if ("".equals(token)) { - continue; - } - if (token.startsWith("at ")) { - list.add(token.substring(3)); - } else { - list.add(token); - } - } - - return list; - } - - /** - * Convert a name into a URL form, the java equivalent of - * "manipulate-input.js" - * - * For example, "Business promotions!" will be converted to - * "business-promotions". - * - * @param name the to be converted into a URL. - * @return the converted name, possibly unchanged and null if the input is - * null. - */ - public static String urlize(final String name) { - if (name == null) { - return null; - } - final StringBuffer urlizedName = new StringBuffer(name.length()); - - for (int i = 0; i < name.length(); i++) { - final char chr = name.charAt(i); - - if (Character.isLetter(chr)) { - urlizedName.append(Character.toLowerCase(chr)); - } else if (Character.isDigit(chr) || chr == '_' || chr == '-') { - urlizedName.append(chr); - } else if (chr == ' ' || chr == '&' || chr == '/') { - urlizedName.append('-'); - } - } - return urlizedName.toString(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/SystemInformation.java b/ccm-core/src/main/java/com/arsdigita/util/SystemInformation.java deleted file mode 100644 index 7605f7e36..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/SystemInformation.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (c) 2014 Jens Pelzetter - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.stream.Stream; - -/** - * Provides the system name of the CCM Spin off (eg aplaws or ScientificCMS) and - * the version number. It's primary use is to provide the theme engine with that - * information for display. The data displayed is stored in the - * /WEB-INF/systeminformation.properties, which is usually provided by the - * bundle. The ccm-sci-bundle for example provides this file, which can be found - * in {@code ccm-sci-bundle/web/WEB-INF} directory. At the moment it is - * necessary to update this (these) file(s) manually. - * - * A {@code systeminformations.properties} should contain at least these three - * properties: - *
    - *
    version
    - *
    The version of the specific CCM distribution.
    - *
    appname
    - *
    The name of the CCM distribution, for example - * ScientificCMS - *
    apphomepage
    - *
    - * The URL of the website of the CCM distribution, for example - * {@code http://www.scientificcms.org} - *
    - *
    - * - * - * @author Jens Pelzetter - * @version $Id$ - */ -public class SystemInformation { - - /** - * Map containing all informations provided by the - * {@code systeminformation.properties} file. - */ - private final Map sysInfo = new HashMap<>(); - /** - * The one and only instance of this class - */ - private final static SystemInformation INSTANCE = new SystemInformation(); - - /** - * The constructor takes care of loading the data from the properties file - * and placing them into {@code HashMap}. - */ - public SystemInformation() { - - final Properties properties = new Properties(); - try { - final InputStream stream = getClass().getResourceAsStream( - "systeminformation.properties"); - if (stream == null) { - properties.put("version", ""); - properties.put("appname", "LibreCCM"); - properties.put("apphomepage", "http://www.libreccm.org"); - } else { - properties.load(stream); - } -// properties.load(getClass().getResourceAsStream( -// "WEB-INF/systeminformation.properties")); - } catch (IOException ex) { - throw new UncheckedWrapperException(ex); - } - - for (String key : properties.stringPropertyNames()) { - sysInfo.put(key, properties.getProperty(key)); - } - - } - - /** - * @return The instance of this class. - */ - public static SystemInformation getInstance() { - return INSTANCE; - } - - /* - * Get system informations by key. - * - * @param key Key for the map - * - * @return value for key - * - * @throws IllegalArgumentException if key is null or empty - */ - public final String get(final String key) throws IllegalArgumentException { - if (key == null || key.isEmpty()) { - throw new IllegalArgumentException( - "Parameter key must not be null or empty."); - } - return sysInfo.get(key); - } - - /** - * Get iterator of this map. - * - * @return iterator of map - */ - public final Iterator> iterator() { - return sysInfo.entrySet().iterator(); - } - - public final Set> getEntries() { - return sysInfo.entrySet(); - } - - public final Stream> getEntriesAsStream() { - return sysInfo.entrySet().stream(); - } - - public final int size() { - return sysInfo.size(); - } - - /** - * - * @return - */ - public final boolean isEmpty() { - return sysInfo.isEmpty(); - - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/Tree.java b/ccm-core/src/main/java/com/arsdigita/util/Tree.java deleted file mode 100755 index cfdc21e0a..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/Tree.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * This class a represents the tree abstraction. This - * implementation takes a recursive definition where a tree is a root node - * connected to other (sub)trees. - * - *

    This implementation allows the same node to be used in more than position - * in the tree. For example, you can do something like this:

    - * - *
    - *  Tree aa = new Tree("a");
    - *  Tree bb = aa.addChild("b");
    - *  bb.addChild("a");
    - *  aa.addChild("c");
    - * 
    - * - *

    This can be visualized as follows:

    - * - *
    - *    a
    - *   / \
    - *  /   \
    - * b     c
    - *  \
    - *   \
    - *    a
    - * 
    - * - *

    The only ways to add node to the tree is through the {@link #Tree(Object) - * constructor} and the {@link #addChild(Object)} {@link #addChild(Object, - * Object)} methods.

    - * - * @author Vadim Nasardinov (vadimn@redhat.com) - * @version $Date$ - * @since 2003-01-23 - **/ -public class Tree { - private Tree m_parent; - private final Object m_root; - private final List m_children; - private String m_label; - - /** - * @param root the root node of the tree - * @pre root != null - **/ - public Tree(Object root) { - this(null, root); - } - - private Tree(Tree parent, Object root) { - m_parent = parent; - m_root = root; - m_children = new ArrayList(); - } - - public void setLabel(String label) { - m_label = label; - } - - public String getLabel() { - return m_label; - } - - /** - * Returns the root of this tree. - **/ - public Object getRoot() { - return m_root; - } - - /** - * Adds a child element to the root of this tree. Returns the subtree rooted - * at the newly created node. - **/ - public Tree addChild(Object child, Object edge) { - Tree tree = new Tree(this, child); - m_children.add(new EdgeTreePair(edge, tree)); - return tree; - } - - /** - * A shortcut for addChild(child, null). - * - * @see #addChild(Object, Object) - **/ - public Tree addChild(Object child) { - return addChild(child, null); - } - - /** - * Adds subtree to the root node of this tree. - * - *

    Note: This doesn't check for - * cycles. If you do something like,

    - * - *
    -     * tree.addSubtree(tree);
    -     * 
    - * - *

    you're on your own. I'll add a check for cycles like this when I have - * the time. (This probably means never.)

    - * - * @pre subtree != null && subtree.getParent() == 0 - **/ - public void addSubtree(Tree subtree, Object edge) { - Assert.exists(subtree, "subtree"); - Assert.isTrue(subtree.getParent() == null, "parent must be null"); - subtree.m_parent = this; - m_children.add(new EdgeTreePair(edge, subtree)); - } - - /** - * A shortcut for addSubtree(subtree,null). - * - * @see #addSubtree(Tree, Object) - **/ - public void addSubtree(Tree subtree) { - addSubtree(subtree, null); - } - - /** - * Returns the tree rooted at the parent node of the root of this tree or - * null, if the root of this tree has no parent node. - * - **/ - public Tree getParent() { - return m_parent; - } - - /** - * Returns the list of {@link Tree.EdgeTreePair edge-tree pairs} parented to - * the root node of this tree in the order in which they were initially - * added. Manipulating the returned list does not affect this tree. For - * example, if you remove an element from the list, no changes are made to - * this tree. - **/ - public List getSubtrees() { - return new ArrayList(m_children); - } - - /** - * Returns a copy of this tree. The returned copy does not have a parent - * tree. In other words, the returned tree is no longer a part of a bigger - * tree, even if this tree was. - * - @ return.getParent() == null - **/ - public Tree copy() { - Tree result = new Tree(getRoot()); - copyRecurse(this, result); - return result; - } - - private static void copyRecurse(Tree from, Tree to) { - Iterator children = from.getSubtrees().iterator(); - while ( children.hasNext() ) { - EdgeTreePair pair = (EdgeTreePair) children.next(); - Tree result = to.addChild(pair.getTree().getRoot(), pair.getEdge()); - copyRecurse(pair.getTree(), result); - } - } - - public int nodeCount() { - return nodeCountRecurse(this); - } - - private static int nodeCountRecurse(Tree tree) { - int result = 1; - for ( Iterator ii=tree.getSubtrees().iterator(); ii.hasNext(); ) { - EdgeTreePair pair = (EdgeTreePair) ii.next(); - result += nodeCountRecurse(pair.getTree()); - } - return result; - } - - /** - * Returns the maximum depth of the tree. - **/ - public int depth() { - return depthRecurse(this); - } - - private static int depthRecurse(Tree tree) { - if ( tree.getSubtrees().size() == 0 ) { - return 1; - } - int maxDepth = 0; - for (Iterator ii=tree.getSubtrees().iterator(); ii.hasNext(); ) { - EdgeTreePair pair = (EdgeTreePair) ii.next(); - int depth = depthRecurse(pair.getTree()); - if ( depth > maxDepth ) { - maxDepth = depth; - } - } - return maxDepth + 1; - } - - /** - * Returns the list of trees such that each of the returned trees is rooted - * at the ancestor nodes of this tree or an empty list, if the root of this - * tree has no ancestors. The closer ancestors appear first in the list. - **/ - public List getAncestors() { - List result = new ArrayList(); - if ( getParent() == null ) { - return result; - } - ancestorsRecurse(getParent(), result); - return result; - } - - private static void ancestorsRecurse(Tree node, List accumulator) { - accumulator.add(node); - if ( node.getParent() != null ) { - ancestorsRecurse(node.getParent(), accumulator); - } - } - - /** - * Takes a list of trees and returns a new list where each tree from the - * passed in list is replaced with its root node. - * - * @pre trees != null - **/ - public static List treesToNodes(List trees) { - Assert.exists(trees, "trees"); - List result = new ArrayList(); - for (Iterator ii=trees.iterator(); ii.hasNext(); ) { - result.add(((Tree) ii.next()).getRoot()); - } - return result; - } - - /** - * Nodes in a tree are connected with edges. An edge can be object that - * characterizes the relationship between the parent and the child nodes. - * For example, if you use the tree to represent the composition structure - * of XSLT stylesheets, then the edge object may be a string with one of two - * possible values: "xsl:import" and "xsl:include", allowing you to - * distinguish the method by which the parent stylesheet incorporates the - * child. - * - *

    The edge-tree pair class represents an order pair where the first - * element is the edge, and the second is the subtree rooted at the head - * node of the edge.

    - **/ - public static class EdgeTreePair { - private Object m_edge; - private Tree m_tree; - - private EdgeTreePair(Object edge, Tree tree) { - m_edge = edge; - m_tree = tree; - } - - public Object getEdge() { - return m_edge; - } - - /** - * Returns the subtree rooted at the head node of the edge. - **/ - public Tree getTree() { - return m_tree; - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/URLRewriter.java b/ccm-core/src/main/java/com/arsdigita/util/URLRewriter.java deleted file mode 100644 index 7e0be612b..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/URLRewriter.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import java.net.URLEncoder; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map; -import java.util.Set; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * Re-writes URLs to include additional parameters that come from a - * set of registered ParameterProviders. This makes - * cookieless login possible, by re-writing URLs to include a session - * ID parameter. - * - */ -public class URLRewriter { - - /** Creates a s_logging category with name = to the full name of class */ - private static final Logger LOGGER = LogManager.getLogger(URLRewriter.class); - - /** The parameter providers for the system. Client classes are registered here. */ - private static LinkedList s_providers = new LinkedList(); - - /** - * Adds a parameter provider. - **/ - public static void addParameterProvider(ParameterProvider provider) { - LOGGER.debug("addParameterProvider: " - + provider.getClass().getName()); - s_providers.add(provider); - } - - /** - * Clears all parameter providers. - **/ - public static void clearParameterProviders() { - s_providers = new LinkedList(); - } - /** - * Returns the set of global parameter models, or the empty set if no - * provider is set. - * - * @return a set of bebop ParameterModels - **/ - public static Set getGlobalModels() { - if (s_providers.isEmpty()) { - LOGGER.debug("getGlobalModels: no providers set"); - return java.util.Collections.EMPTY_SET; - } - - Set rs = new HashSet(); - for (Iterator i = s_providers.iterator(); i.hasNext();) { - rs.addAll(((ParameterProvider) i.next()).getModels()); - } - return rs; - } - - /** - * Returns the set of global URL parameters for the given request, or - * the empty set if no provider is set. - * - * @return a set of bebop ParameterData - **/ - public static Set getGlobalParams(HttpServletRequest req) { - if (s_providers.isEmpty()) { - LOGGER.debug("getGlobalParams: no providers set"); - return java.util.Collections.EMPTY_SET; - } - - Set rs = new HashSet(); - for (Iterator i = s_providers.iterator(); i.hasNext();) { - rs.addAll(((ParameterProvider)i.next()).getParams(req)); - } - return rs; - } - - /** - * Encodes the given URL for redirecting the client. Adds ACS global - * parameters and servlet session parameters to the URL. The - * sendRedirect(req, resp, url) method calls this method automatically. - * - * @return the new URL - **/ - public static String encodeRedirectURL(HttpServletRequest req, - HttpServletResponse resp, - String url) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("encodeRedirectURL: before: " + url); - } - - url = resp.encodeRedirectURL(encodeParams(req, url)); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("encodeRedirectURL: after: " + url); - } - - return url; - } - - /** - * Prepares the given URL for the client. No effect if no provider is - * set. - * - * @return the prepared URL - * - * @deprecated This method does not encode the servlet session ID. Use - * encodeURL(req, res, url) instead. - **/ - public static String prepareURL(String url, HttpServletRequest req) { - return encodeParams(req, url); - } - - /** - * Encodes the given URL for the client. Adds ACS global parameters and - * servlet session parameters to the URL. If the URL will be used for - * redirection, use sendRedirect(req, resp, url) instead. - * - * @return the new URL - **/ - public static String encodeURL(HttpServletRequest req, - HttpServletResponse resp, - String url) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("encodeURL: before: " + url); - } - - url = resp.encodeURL(encodeParams(req, url)); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("encodeURL: after: " + url); - } - - return url; - } - - /** - * Adds the ACS global params to the URL. - **/ - private static String encodeParams(HttpServletRequest req, String url) { - if (s_providers.isEmpty()) { - LOGGER.debug("encodeParams: no providers set"); - return url; - } - Map params = new java.util.HashMap(); - String base = parseQueryString(url, params); - merge(getGlobalParams(req), params); - url = base + unparseQueryString(params); - return url; - } - - /** - * Merges a set of bebop ParameterData into a URL parameter map. - **/ - private static void merge(Set data, Map params) { - Iterator values = data.iterator(); - while (values.hasNext()) { - Map.Entry value = (Map.Entry)values.next(); - if (value == null) { - continue; - } - params.put(value.getKey(), value.getValue()); - } - } - - /** - * Parses the given URL into a non-query part and a URL parameter map. - * - * @param url the original URL - * - * @param params map from param name to value. Each value is a String - * if parameter is single-valued; String[] if multi-valued. Existing - * values will be blindly overwritten by this method. - * - * @return the non-query part of the URL - **/ - private static String parseQueryString(String url, Map params) { - int qmark = url.indexOf('?'); - if (qmark < 0) { - return url; - } - String base = url.substring(0, qmark); - String query = url.substring(qmark+1); - params.putAll(HttpUtils.parseQueryString(query)); - return base; - } - - /** - * Returns the query string representation of the given URL parameter - * map, including leading question mark. Should be appended to the - * return value of a previous call to parseQueryString(). Handles - * multi-valued parameters correctly. Ignores null values. - **/ - private static String unparseQueryString(Map params) { - StringBuffer buf = new StringBuffer(128); - char sep = '?'; - Iterator keys = params.keySet().iterator(); - while (keys.hasNext()) { - String key = (String)keys.next(); - Object value = params.get(key); - if (value instanceof String[]) { - String[] values = (String[])value; - for (int i = 0; i < values.length; i++) { - if (values[i] != null) { - appendParam(buf, sep, key, values[i]); - sep = '&'; - } - } - continue; - } else if (value != null) { - appendParam(buf, sep, key, value.toString()); - sep = '&'; - } - } - return buf.toString(); - } - - /** - * Appends string representation of a parameter to the given - * StringBuffer: sep + URLEncode(key) + '=' + URLEncode(value) - **/ - private static void appendParam(StringBuffer buf, char sep, - String key, String value) { - buf.append(sep).append(URLEncoder.encode(key)) - .append('=').append(URLEncoder.encode(value)); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/UncheckedWrapperException.java b/ccm-core/src/main/java/com/arsdigita/util/UncheckedWrapperException.java deleted file mode 100644 index 43ad5b8cb..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/UncheckedWrapperException.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * A wrapper exception that can be used to rethrow another exception. - * - * TODO: This should become a skeleton when/if we switch to Java 1.4. - * http://java.sun.com/j2se/1.4/docs/guide/lang/chained-exceptions.html - * - * The basic exception methods are overridden with methods that combine this - * wrapper and its root cause, so it can be treated just like any normal - * exception in actual use. - * - * Note that it is not necessary to provide a string along with a root cause; in - * particular, the following usage: - * new UncheckedWrapperException(e); is more correct than - * new UncheckedWrapperException(e.getMessage(), e); - * - * @author David Eison - */ -public class UncheckedWrapperException extends RuntimeException { - - private static final long serialVersionUID = 1473646671430756784L; - - static { - Exceptions.registerUnwrapper( - UncheckedWrapperException.class, - new ExceptionUnwrapper() { - - public Throwable unwrap(Throwable t) { - UncheckedWrapperException ex = (UncheckedWrapperException) t; - return ex.getRootCause(); - } - - }); - } - - Throwable m_rootCause; - - /** - * Constructor which only takes a msg, which will cause this - * UncheckedWrapperException to behave like a normal RuntimeException. While - * it doesn't seem to make a lot of sense to have a wrapper exception that - * doesn't wrap anything, this is needed so that it can be used as a direct - * replacement for RuntimeException. - */ - public UncheckedWrapperException(String msg) { - this(msg, null); - } - - /** - * Constructor which takes a root cause that this exception will be - * wrapping. - */ - public UncheckedWrapperException(Throwable rootCause) { - this(null, rootCause); - } - - /** - * Constructor which takes a message string and a root cause that this - * exception will be wrapping. The message string should be something - * different than rootCause.getMessage() would normally provide. - */ - public UncheckedWrapperException(String s, Throwable rootCause) { - super(s); - this.m_rootCause = rootCause; - } - - /** - * Throws an UncheckedWrapperException, and ensurs that it is logged at - * ERROR priority. - * - * @param source Class having the error. For Log4J reporting - * @param msg Error message - * @param rootCause The root cause exception - * - * @throws UncheckedWrapperException - */ - public static void throwLoggedException(Class source, String msg, - Throwable rootCause) throws - UncheckedWrapperException { - Logger log = LogManager.getLogger(source); - log.error(msg, rootCause); - - throw new UncheckedWrapperException(msg, rootCause); - } - - /** - * Indicates if this exception has a root cause. - */ - public boolean hasRootCause() { - return m_rootCause != null; - } - - /** - * Gets the root cause of this exception. - */ - public Throwable getRootCause() { - return m_rootCause; - } - - // All further methods override normal throwable behavior to - // combine information w/ the root cause. - /** - * Get a string representing this exception and the root cause. - */ - @Override - public String toString() { - return toString(this.getClass()); - } - - /** - * Get a string representing this exception and the root cause. - * - * Functions like normal toString, except that the name of the provided - * class will be used instead of the name of the unchecked wrapper - * exception. Useful when another exception class is using an unchecked - * wrapper exception to delegate to. - */ - public String toString(Class delegatingClass) { - // default toString calls getMessage, so we don't want to rely on it - // here. - StringBuffer b = new StringBuffer(delegatingClass.getName()); - String superMsg = super.getMessage(); - if (superMsg != null) { - b.append(": ").append(superMsg); - } - if (m_rootCause != null) { - b.append(" (root cause: ").append(m_rootCause.toString()); - b.append(")"); - } - return b.toString(); - } - - /** - * This exception's message and the root cause's. - */ - @Override - public String getMessage() { - if (m_rootCause != null) { - return super.getMessage() + " (root cause: " + m_rootCause. - getMessage() + ")"; - } else { - return super.getMessage(); - } - } - - /** - * Stack trace for the root cause. - */ - @Override - public void printStackTrace() { - super.printStackTrace(); - if (m_rootCause != null) { - System.err.print("Root cause: "); - m_rootCause.printStackTrace(); - } - } - - /** - * Stack trace for the root cause. - */ - @Override - public void printStackTrace(java.io.PrintStream s) { - super.printStackTrace(s); - if (m_rootCause != null) { - s.println("Root cause: "); - m_rootCause.printStackTrace(s); - } - } - - /** - * Stack trace for the root cause. - */ - @Override - public void printStackTrace(java.io.PrintWriter s) { - super.printStackTrace(s); - if (m_rootCause != null) { - s.println("Root cause: "); - m_rootCause.printStackTrace(s); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/AbstractParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/AbstractParameter.java deleted file mode 100644 index 3fcaf5573..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/AbstractParameter.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.Assert; -import org.apache.commons.beanutils.ConversionException; - -/** - * A base implementation of the Parameter interface. - * - * It offers subclasses use of the Apache BeanUtils framework, should - * they opt to use it. - * - * Methods of the form doXXX are extension points for subclasses. - * The isRequired() and getDefaultValue() - * methods may also be overriden. - * - * Subject to change. - * - * @see Parameter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public abstract class AbstractParameter implements Parameter { - - private final String m_name; - private final Class m_type; - private final int m_multiplicity; - private final Object m_default; - private ParameterInfo m_info; - - /** - * Constructs a new parameter with the default value - * defaalt and using the beanutils converter - * registered for type. - * - * @param name The name of the parameter; it cannot be null - * @param multiplicity The multiplicity type of the parameter - * @param defaalt The default value to use if the value is unset - * or is null - * @param type The Class whose beanutils converter - * will be used to unmarshal literal values - */ - protected AbstractParameter(final String name, - final int multiplicity, - final Object defaalt, - final Class type) { - if (Assert.isEnabled()) { - Assert.exists(name, String.class); - } - - m_name = name; - m_type = type; - m_multiplicity = multiplicity; - m_default = defaalt; - } - - /** - * Constructs a new parameter with the default value - * defaalt. - * - * @param name The name of the parameter; it cannot be null - * @param multiplicity The multiplicity type of the parameter - * @param defaalt The default value to use if the value is unset - * or is null - */ - protected AbstractParameter(final String name, - final int multiplicity, - final Object defaalt) { - // XXX Get rid of this constructor? - this(name, multiplicity, defaalt, null); - } - - /** - * Constructs a new parameter using the beanutils converter for - * type type. By default, the parameter is required - * and has no default. - * - * @param name The name of the parameter; it cannot be null - * @param type The Class whose beanutils converter - * will be used to unmarshal literal values - */ - protected AbstractParameter(final String name, - final Class type) { - this(name, Parameter.REQUIRED, null, type); - } - - /** - * Parameter users may override this method to make the multiplicity of - * the parameter dependent on the multiplicity of related parameters. - * - * @see Parameter#isRequired() - */ - public boolean isRequired() { - return m_multiplicity == Parameter.REQUIRED; - } - - /** - * @see Parameter#getName() - */ - public final String getName() { - return m_name; - } - - /** - * Parameter users may override this method to achieve dynamic - * defaulting. - * - * @see Parameter#getDefaultValue() - */ - public Object getDefaultValue() { - return m_default; - } - - /** - * @see Parameter#getInfo() - */ - public final ParameterInfo getInfo() { - return m_info; - } - - /** - * @see Parameter#setInfo(ParameterInfo) - */ - public final void setInfo(final ParameterInfo info) { - m_info = info; - } - - // - // Lifecycle events - // - - /** - * Gets the parameter value as a Java object. - * - * The value will have a specific runtime type and so may be - * appropriately cast. - * - * Reading typically follows the following procedure: - * - *
      - *
    • Read the literal string value associated with the - * parameter from reader
    • - * - *
    • Convert the literal string value into an approprite Java - * object
    • - *
    - * - * If at any point in the process an error is encountered, it is - * added to errors. Callers of this method will - * typically construct an ErrorList in which to - * collect errors. - * Actually calls {@link #doRead(ParameterReader,ErrorList)} (as an - * extension point for subclasses). - * - * @param reader The ParameterReader from which to - * recover a string literal value; it cannot be null - * @param errors The ErrorList in which to collect - * any errors encountered; it cannot be null - * @return The Java object value of the parameter - * - */ - public final Object read(final ParameterReader reader, - final ErrorList errors) { - if (Assert.isEnabled()) { - Assert.exists(reader, ParameterReader.class); - Assert.exists(errors, ErrorList.class); - } - - return doRead(reader, errors); - } - - /** - * Extension point to read the value of the parameter from reader. - * - * It unmarshals the value, and returns it. If any errors are encountered, - * they are added to errors. - * - * If the literal string value from reader is not null, - * this method delegates to {@link #unmarshal(String,ErrorList)}. - * - * This implementation is suited to a parameter with a singular - * scalar value. Subclasses that are compound parameters should - * override this method to delegate to child parameters. - * - * @param reader The ParameterReader that will supply - * the literal stored value for this parameter; it cannot be null - * @param errors The ErrorList that will trap any - * errors encountered; it cannot be null - */ - protected Object doRead(final ParameterReader reader, - final ErrorList errors) { - final String string = reader.read(this, errors); - - if (string == null) { - return null; - } else { - return unmarshal(string, errors); - } - } - - /** - * Converts a literal String value, - * value, to a Java object, which is returned. - * - * @param value The String value to convert from; it - * cannot be null - * @param errors An ErrorList that holds any errors - * encountered during unmarshaling; it cannot be null - */ - protected Object unmarshal(final String value, final ErrorList errors) { - if (Assert.isEnabled()) { - Assert.exists(value, String.class); - Assert.exists(errors, String.class); - } - - try { - return Converters.convert(m_type, value); - } catch (ConversionException ce) { - errors.add(new ParameterError(this, ce)); - return null; - } - } - - /** - * Calls {@link #doValidate(Object,ErrorList)} if - * value is not null. Otherwise, if the value is - * required and null, an error is added to - * errors and doValidate is not called. - * - * @see Parameter#validate(Object,ErrorList) - */ - public final void validate(final Object value, final ErrorList errors) { - Assert.exists(errors, ErrorList.class); - - if (value == null) { - // If the value is null, validation stops here. - - if (isRequired()) { - final ParameterError error = new ParameterError - (this, "The value must not be null"); - errors.add(error); - } - } else { - // Always do further validation for non-null values. - - doValidate(value, errors); - } - } - - /** - * Validates value, placing any validation errors in - * errors. This particular implementation does - * nothing. Subclasses are expected to add specific validation - * behaviors. - * - * @param value The value to validate; it cannot be null - * @param errors The ErrorList that traps validation - * errors; it cannot be null - */ - protected void doValidate(final Object value, final ErrorList errors) { - if (Assert.isEnabled()) { - Assert.exists(value, Object.class); - Assert.exists(errors, ErrorList.class); - } - - // Nothing - } - - /** - * Calls {@link #doWrite(ParameterWriter,Object)}. - * - * @see Parameter#write(ParameterWriter,Object) - */ - public final void write(final ParameterWriter writer, final Object value) { - Assert.exists(writer); - - // XXX what to do about nulls here? - - doWrite(writer, value); - } - - /** - * Marshals and writes value to writer. - * - * This implementation is suited to a parameter with a singular - * scalar value. Subclasses that are compound parameters should - * override this method to delegate to child parameters. - * - * @param writer The ParameterWriter we write to; it - * cannot be null - * @param value The value to write; it may be null - */ - protected void doWrite(final ParameterWriter writer, final Object value) { - writer.write(this, marshal(value)); - } - - /** - * Converts value to a representative - * String, which is returned. - * - * @param value The value to marshal; it may be null - * @return The String literal representation of - * value; it may be null - */ - protected String marshal(final Object value) { - if (value == null) { - return null; - } else { - return value.toString(); - } - } - - /** - * Returns a String representation of this object. - * - * @return super.toString() + "," + getName() + "," + - * isRequired() - */ - public String toString() { - return super.toString() + "," + getName() + "," + isRequired(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/AbstractParameterContext.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/AbstractParameterContext.java deleted file mode 100644 index 4dfccbe3f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/AbstractParameterContext.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.Assert; -import com.arsdigita.util.UncheckedWrapperException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - - -/** - * A base implementation of the ParameterContext - * interface. - * - * Subject to change. - * - * @see com.arsdigita.util.parameter.ParameterContext - * @author Justin Ross <jross@redhat.com> - */ -public abstract class AbstractParameterContext implements ParameterContext { - - private static final Logger LOGGER = LogManager.getLogger - (AbstractParameterContext.class); - - private final MapParameter m_param; - private final HashMap m_map; - private final Properties m_info; - - /** - * Constructs a parameter context. - */ - public AbstractParameterContext() { - m_param = new MapParameter("root"); - m_map = new HashMap(); - m_info = new Properties(); - } - - /** - * Registers param to the context. - * - * @param param The Parameter being registered; it - * cannot be null - */ - public final void register(final Parameter param) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Registering " + param + " on " + this); - } - - if (Assert.isEnabled()) { - Assert.exists(param, Parameter.class); - Assert.isTrue(!m_param.contains(param), - param + " is already registered"); - } - - m_param.add(param); - } - - /** - * @see ParameterContext#getParameters() - */ - public final Parameter[] getParameters() { - final ArrayList list = new ArrayList(); - final Iterator params = m_param.iterator(); - - while (params.hasNext()) { - list.add(params.next()); - } - - return (Parameter[]) list.toArray(new Parameter[list.size()]); - } - - /** - * Gets the unmarshaled value of param. - * - * If the loaded value is null, param.getDefaultValue() - * is returned. - * - * @param param The named Parameter whose value to - * retrieve; it cannot be null - * @return The unmarshaled Java object value of param - */ - public Object get(final Parameter param) { - return get(param, param.getDefaultValue()); - } - - /** - * Gets the unmarshaled value of param, returning - * dephalt if param's value is null. - * - * @param param The Parameter whose value to - * retrieve; it cannot be null - * @param dephalt The fallback default value; it may be null - * @return The unmarshaled Java object value of param - * or dephalt if the former is null - */ - public Object get(final Parameter param, final Object dephault) { - if (Assert.isEnabled()) { - Assert.exists(param, Parameter.class); - Assert.isTrue(m_param.contains(param), - param + " has not been registered"); - } - - // XXX check for is loaded? - - final Object value = m_map.get(param); - - if (value == null) { - return dephault; - } else { - return value; - } - } - - /** - * @see ParameterContext#get(Parameter,Object) - */ - public void set(final Parameter param, final Object value) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Setting " + param + " to " + value); - } - - Assert.exists(param, Parameter.class); - - m_map.put(param, value); - } - - /** - * Reads and unmarshals all values associated with the registered - * parameters from reader. Any errors are returned. - * - * @param reader The ParameterReader from which to - * fetch the values; it cannot be null - * @return An ErrorList containing any errors - * encountered while loading; it cannot be null - */ - public final ErrorList load(final ParameterReader reader) { - final ErrorList errors = new ErrorList(); - - load(reader, errors); - - return errors; - } - - /** - * Reads and unmarshals all values associated with the registered - * parameters from reader. If any errors are - * encountered, they are added to errors. - * - * @param reader The ParameterReader from which to - * fetch the values; it cannot be null - * @param errors The ErrorList that captures any - * errors while loading; it cannot be null - */ - public final void load(final ParameterReader reader, - final ErrorList errors) { - if (Assert.isEnabled()) { - Assert.exists(reader, ParameterReader.class); - Assert.exists(errors, ErrorList.class); - } - - m_map.putAll((Map) m_param.read(reader, errors)); - } - - /** - * Validates all values associated with the registered parameters. - * Any errors encountered are returned. - * - * @return An ErrorList containing validation errors; - * it cannot be null - */ - public final ErrorList validate() { - final ErrorList errors = new ErrorList(); - - m_param.validate(m_map, errors); - - return errors; - } - - /** - * @see ParameterContext#validate(ErrorList) - */ - public final void validate(final ErrorList errors) { - Assert.exists(errors, ErrorList.class); - - m_param.validate(m_map, errors); - } - - /** - * @see ParameterContext#save(ParameterWriter) - */ - public final void save(ParameterWriter writer) { - m_param.write(writer, m_map); - } - - /** - * Loads source data for ParameterInfo objects from - * the file YourClass_parameter.properties next to - * YourClass.class. - * - * YourClass_parameter.properties: - * - *
    -     * yourforum.notification_enabled.title=Flag to enable forum notifications
    -     * yourforum.notification_enabled.purpose=Enables or disables forum notifications
    -     * yourforum.notification_enabled.example=true
    -     * yourforum.notifiaction_enabled.format=true|false
    -     * 
    - * - * @see ParameterInfo - */ - protected final void loadInfo() { - final InputStream in = findInfo(getClass()); - - try { - m_info.load(in); - } catch (IOException ioe) { - throw new UncheckedWrapperException(ioe); - } - - final Iterator params = m_param.iterator(); - - while (params.hasNext()) { - final Parameter param = (Parameter) params.next(); - - param.setInfo(new Info(param)); - } - } - - // - // Private classes and methods - // - - private class Info implements ParameterInfo { - private final String m_name; - - Info(final Parameter param) { - m_name = param.getName(); - } - - public final String getTitle() { - return m_info.getProperty(m_name + ".title"); - } - - public final String getPurpose() { - return m_info.getProperty(m_name + ".purpose"); - } - - public final String getExample() { - return m_info.getProperty(m_name + ".example"); - } - - public final String getFormat() { - return m_info.getProperty(m_name + ".format"); - } - } - - private static InputStream findInfo(final Class klass) { - final List files = new LinkedList(); - InputStream in = findInfo(klass, files); - if ( in == null ) { - throw new IllegalStateException - ("Could not find any of the following files: " + files); - } - return in; - } - - private static InputStream findInfo(final Class klass, final List files) { - if (klass == null) { return null; } - final String name = - klass.getName().replace('.', '/') + "_parameter.properties"; - files.add(name); - if ( klass.getClassLoader() == null ) { - return null; - } - final InputStream in = klass.getClassLoader().getResourceAsStream(name); - - if (in == null) { - return findInfo(klass.getSuperclass(), files); - } else { - return in; - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/BooleanParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/BooleanParameter.java deleted file mode 100644 index 2365982cf..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/BooleanParameter.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import org.apache.commons.beanutils.converters.BooleanConverter; - -/** - * Subject to change. - * - * A parameter representing a Java Boolean. - * - * @see java.lang.Boolean - * @see Parameter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class BooleanParameter extends AbstractParameter { - - static { - Converters.set(Boolean.class, new BooleanConverter()); - } - - public BooleanParameter(final String name) { - super(name, Boolean.class); - } - - public BooleanParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt, Boolean.class); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/CSVParameterReader.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/CSVParameterReader.java deleted file mode 100644 index 7070edf58..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/CSVParameterReader.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.UncheckedWrapperException; -// import com.arsdigita.util.parameter.ErrorList; -// import com.arsdigita.util.parameter.Parameter; -// import com.arsdigita.util.parameter.ParameterLoader; -// import com.arsdigita.util.parameter.ParameterValue; -import java.io.IOException; -import java.io.LineNumberReader; -import java.io.Reader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -/** - * Processes an input stream (a set of lines, each containing a comma separated - * list of parameter values) and .... - * - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public final class CSVParameterReader implements ParameterReader { - - private final LineNumberReader m_reader; - private final Parameter[] m_params; - private final HashMap m_line; - - /** - * Constructor - * - * @param reader: input stream to read values - * @param params: array of parameter objects to store procecced values - */ - public CSVParameterReader(final Reader reader, final Parameter[] params) { - m_reader = new LineNumberReader(reader); // input stream - m_params = params; // array of parameters - m_line = new HashMap(params.length); // - } - - /** - * read - * - * - * - * @param param - * @param errors - * @return - */ - public final String read(final Parameter param, final ErrorList errors) { - return (String) m_line.get(param); - } -/* - * May 2009: Obviously a reminiscence from previous versions of code. This class - * is currently used by coreloader only and it does not use the load method - * and it works with load commented out. - * - * Code should be removed after extensive testing. - * - public final ParameterValue load(final Parameter param) { - final ParameterValue value = new ParameterValue(); - - // XXX this won't work correctly with compound parameters - value.setObject(param.read(this, value.getErrors())); - - value.getErrors().check(); - - return value; - } -*/ - /** - * Just a public visible entry point into internalNext, used to process - * an exception if thrown. - * - * @return: boolean true if any values could be processed. - */ - public final boolean next() { - try { - return internalNext(); - } catch (IOException ioe) { - throw new UncheckedWrapperException(ioe); - } - } - - /** - * Internally used worker method which processes the next() method. - * - * Reads in a line from input stream and asks parseLine to process it. The - * resulting array of strings (each containing a value) - * @return - * @throws java.io.IOException - */ - private boolean internalNext() throws IOException { - final String line = m_reader.readLine(); - - if (line == null) { - return false; - } else { - final String[] elems = parseLine(line); - - // m_params: array of parameters to store the comma separated values - // used to determine the max. number of values which can be processed. - for (int i = 0; i < m_params.length; i++) { - if (i < elems.length) { - // If for the given index into the array of parametes a - // corresponding element in the array of strings exist, - // store it in a hash map (a hash map per line) - m_line.put(m_params[i], elems[i]); - } else { - m_line.put(m_params[i], null); - } - } - - return true; - } - } - - private static final char ESCAPE = '\\'; - private static final char QUOTE = '"'; - private static final char SEPARATOR = ','; - - /** - * Internal used helper method of method parseLine. - * - * @param c - * @return - */ - private char escape(char c) { - switch (c) { - case 'n': - return '\n'; - case 't': - return '\t'; - case 'r': - return '\r'; - default: - return c; - } - } - - /** - * Takes a string and analyses it as a list of comma separated values. - * - * Internally used to store each value found in a new string and add it - * to an array of strings. - * - * @param line: string containing a comma separated list of values - * @return : array of strings, each containing a value of the list - */ - private String[] parseLine(final String line) { - int length = line.length(); - - // Check here if the last character is an escape character so - // that we don't need to check in the main loop. - if (line.charAt(length - 1) == ESCAPE) { - throw new IllegalArgumentException - (m_reader.getLineNumber() + - ": last character is an escape character\n" + line); - } - - // The set of parsed fields. - List result = new ArrayList(); - - // The characters between seperators. - StringBuffer buf = new StringBuffer(length); - // Marks the begining of the field relative to buf, - // -1 indicates the beginning of buf. - int begin = -1; - // Marks the end of the field relative to buf. - int end = 0; - - // Indicates whether or not we're in a quoted string. - boolean quote = false; - - for (int i = 0; i < length; i++) { - char c = line.charAt(i); - if (quote) { - switch (c) { - case QUOTE: - quote = false; - break; - case ESCAPE: - buf.append(escape(line.charAt(++i))); - break; - default: - buf.append(c); - break; - } - - end = buf.length(); - } else { - switch (c) { - case SEPARATOR: - result.add(field(buf, begin, end)); - buf = new StringBuffer(length); - begin = -1; - end = 0; - break; - case ESCAPE: - if (begin < 0) { begin = buf.length(); } - buf.append(escape(line.charAt(++i))); - end = buf.length(); - break; - case QUOTE: - if (begin < 0) { begin = buf.length(); } - quote = true; - end = buf.length(); - break; - default: - if (begin < 0 && - !Character.isWhitespace(c)) { - begin = buf.length(); - } - buf.append(c); - if (!Character.isWhitespace(c)) { end = buf.length(); } - break; - } - } - } - - if (quote) { - throw new IllegalArgumentException - (m_reader.getLineNumber() + ": unterminated string\n" + line); - } else { - result.add(field(buf, begin, end)); - } - - String[] fields = new String[result.size()]; - result.toArray(fields); - return fields; - } - - /** - * internal helper method for method parseLine - * - * @param field - * @param begin - * @param end - * @return - */ - private String field(StringBuffer field, int begin, int end) { - if (begin < 0) { - return field.substring(0, end); - } else { - return field.substring(begin, end); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/ClassParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/ClassParameter.java deleted file mode 100644 index be3b4f1c0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/ClassParameter.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import org.apache.commons.beanutils.converters.ClassConverter; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * A parameter representing a Java Class. - * - * Subject to change. - * - * @see java.lang.Class - * @see Parameter - * @author Justin Ross <jross@redhat.com> - */ -public class ClassParameter extends AbstractParameter { - - private static final Logger LOGGER = LogManager.getLogger( - ClassParameter.class); - - static { - LOGGER.debug("Static initalizer starting..."); - Converters.set(Class.class, new ClassConverter()); - LOGGER.debug("Static initalizer finished."); - } - - public ClassParameter(final String name) { - super(name, Class.class); - } - - public ClassParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt, Class.class); - } - - // value != null - protected Object unmarshal(String value, ErrorList errors) { - Class theClass = null; - try { - theClass = Class.forName(value); - } catch (ClassNotFoundException e) { - errors.add(new ParameterError(this, "No such class: " + value)); - } - - return theClass; - } - - protected String marshal(Object value) { - Class theClass = ((Class) value); - if (theClass == null) { - return null; - } else { - return theClass.getName(); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/CompoundParameterReader.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/CompoundParameterReader.java deleted file mode 100644 index 6fa1ea48f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/CompoundParameterReader.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.Assert; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * Aggregates a set of ParameterReaders so they may be - * treated as one. - * - * Subject to change. - * - * @see ParameterReader - * @author Rafael H. Schloming <rhs@mit.edu> - * @author Justin Ross <jross@redhat.com> - */ -public class CompoundParameterReader implements ParameterReader { - - private final List m_readers; - - /** - * Constructs a new compound parameter reader. - */ - public CompoundParameterReader() { - m_readers = new ArrayList(); - } - - /** - * Adds reader to the set of component readers. - * - * @param reader The ParameterReader being added; it - * cannot be null - */ - public void add(final ParameterReader reader) { - Assert.exists(reader, ParameterReader.class); - - m_readers.add(reader); - } - - /** - * @see ParameterReader#read(Parameter,ErrorList) - */ - public String read(final Parameter param, final ErrorList errors) { - for (final Iterator it = m_readers.iterator(); it.hasNext(); ) { - final ParameterReader reader = (ParameterReader) it.next(); - - final String result = reader.read(param, errors); - - if (result != null) { - return result; - } - } - - return null; - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/Converters.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/Converters.java deleted file mode 100644 index 0f8c4ba45..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/Converters.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.Assert; - -import java.util.Collections; -import java.util.Map; -import java.util.HashMap; - -import org.apache.commons.beanutils.Converter; - -/** - * Subject to change. - * - * Collects together BeanUtils converters for use by the base - * Parameters. - * - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class Converters { - - private static Map s_converters = Collections.synchronizedMap - (new HashMap()); - - /** - * Gets the Converter registered for - * clacc. This method will fail if no converter is - * found. - * - * @param clacc The Class of the parameter value; it - * cannot be null - * @return A Converter instance; it cannot be null - */ - public static final Converter get(final Class clacc) { - Assert.exists(clacc, Class.class); - - final Converter converter = (Converter) s_converters.get(clacc); - - Assert.exists(converter, Converter.class); - - return converter; - } - - /** - * Registers converter for clacc. - * - * @param clacc The Class of the parameter value; it - * cannot be null - * @param converter The Converter to register to - * clacc; it cannot be null - */ - public static final void set(final Class clacc, final Converter converter) { - if (Assert.isEnabled()) { - Assert.exists(clacc, Class.class); - Assert.exists(converter, Converter.class); - } - - s_converters.put(clacc, converter); - } - - /** - * Converts value using the converter registered for - * clacc. - * - * @param clacc The Class of the parameter value; it - * cannot be null - * @param value The String-encoded value of the - * parameter; it may be null - * @return The Java object conversion for value; it - * may be null - */ - public static final Object convert(final Class clacc, final String value) { - Assert.exists(clacc, Class.class); - - return get(clacc).convert(clacc, value); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/EmailParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/EmailParameter.java deleted file mode 100644 index eaa3720d1..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/EmailParameter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import org.apache.oro.text.perl.Perl5Util; - -/** - * Subject to change. - * - * A parameter representing an InternetAddress. - * - * @see javax.mail.internet.InternetAddress - * @see Parameter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class EmailParameter extends StringParameter { - - private static final Perl5Util s_perl = new Perl5Util(); - private static final String s_regex = - "/^[^@<>\"\t ]+@[^@<>\".\t]+([.][^@<>\".\n ]+)+$/"; - - public EmailParameter(final String name) { - super(name); - } - - protected Object unmarshal(final String value, final ErrorList errors) { - try { - return new InternetAddress(value); - } catch (AddressException ae) { - errors.add(new ParameterError(this, ae)); - return null; - } - } - - protected void doValidate(final Object value, final ErrorList errors) { - super.doValidate(value, errors); - - final InternetAddress email = (InternetAddress) value; - - if (!s_perl.match(s_regex, email.toString())) { - final ParameterError error = new ParameterError - (this, "The value is not a valid email address"); - - errors.add(error); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/EnumerationParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/EnumerationParameter.java deleted file mode 100644 index a250813b9..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/EnumerationParameter.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import java.util.HashMap; - -/** - * Subject to change. - * - * A parameter that maps keys to values and, given a key, marshals or unmarshals - * to the corresponding value. - * - * @see Parameter - * @author Justin Ross <jross@redhat.com> - */ -public class EnumerationParameter extends AbstractParameter { - - private final HashMap m_entries; - private final HashMap m_reverse; - - public EnumerationParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt); - - m_entries = new HashMap(); - m_reverse = new HashMap(); - } - - public EnumerationParameter(final String name) { - this(name, Parameter.REQUIRED, null); - } - - public final void put(final String name, final Object value) { - if (m_entries.containsKey(name)) { - throw new IllegalArgumentException("name already has a value: " - + name); - } - if (m_reverse.containsKey(value)) { - throw new IllegalArgumentException("value already has a name: " - + value); - } - m_entries.put(name, value); - m_reverse.put(value, name); - } - - protected Object unmarshal(final String value, final ErrorList errors) { - if (m_entries.containsKey(value)) { - return m_entries.get(value); - } else { - final ParameterError error = new ParameterError(this, - "The value must be one of " - + m_entries.keySet()); - - errors.add(error); - - return null; - } - } - - protected String marshal(Object value) { - return (String) m_reverse.get(value); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/ErrorList.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/ErrorList.java deleted file mode 100644 index 61ca7e67c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/ErrorList.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.Assert; -import com.arsdigita.util.UncheckedWrapperException; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Iterator; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - - -/** - * Subject to change. - * - * A collection to store ParameterErrors that are - * encountered during parameter reading or validation. This - * collection is used in the lifecycle methods of - * Parameter. It is ordinarily returned to the - * parameter-using code so that it can handle errors. - * - * @see ParameterError - * @see Parameter - * @author Justin Ross <jross@redhat.com> - */ -public final class ErrorList { - - private static final Logger LOGGER = LogManager.getLogger(ErrorList.class); - - private final ArrayList m_params; - - // XXX temporarily package access - final ArrayList m_errors; - - /** - * Constructs a new error list. - */ - public ErrorList() { - m_params = new ArrayList(); - m_errors = new ArrayList(); - } - - /** - * Adds error to the error list. - * - * @param error A ParameterError representing a read - * or validation error; it cannot be null - */ - public final void add(final ParameterError error) { - Assert.exists(error, ParameterError.class); - - final Parameter param = error.getParameter(); - - synchronized (m_params) { - if (!m_params.contains(param)) { - m_params.add(param); - } - } - - m_errors.add(error); - } - - /** - * Gets an iterator over the currently stored errors. - * - * @see ParameterError - * @return An Iterator of - * ParameterErrors; it cannot be null - */ - public final Iterator iterator() { - return m_errors.iterator(); - } - - /** - * Tells whether the error collection is empty or not. - * - * @return true if the collection is empty, otherwise - * false - */ - public final boolean isEmpty() { - return m_errors.isEmpty(); - } - - /** - * Throws a ParameterException containing the error - * list. This method is for use when the client code wants the - * program to fail via an exception if there are errors. - * - * @throws ParameterException if the error list is not empty - */ - public final void check() throws ParameterException { - if (!isEmpty()) { - final StringWriter writer = new StringWriter(); - report(writer); - LOGGER.error(writer.toString()); - - throw new ParameterException - ("Errors encountered while reading parameters", this); - } - } - - /** - * Prints parameter errors to out with formatting - * appropriate to the console. - * - * @param out The Writer to print the errors to - */ - public final void report(final Writer out) { - try { - Assert.exists(out, PrintWriter.class); - - final Iterator params = m_params.iterator(); - - while (params.hasNext()) { - final Parameter param = (Parameter) params.next(); - - out.write("Parameter " + param.getName() + " has the " + - "following errors:\n"); - - final Iterator errors = m_errors.iterator(); - - while (errors.hasNext()) { - final ParameterError error = - (ParameterError) errors.next(); - - if (error.getParameter().equals(param)) { - out.write("\t" + error.getMessage() + "\n"); - } - } - } - - out.flush(); - } catch (IOException ioe) { - throw new UncheckedWrapperException(ioe); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/FileParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/FileParameter.java deleted file mode 100644 index 5b9536aa0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/FileParameter.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import java.io.File; - - -/** - * A Parameter representing a File - * - * @see Parameter - * @see java.io.File - * @author bche - */ -public class FileParameter extends AbstractParameter { - - public FileParameter(final String name) { - super(name, File.class); - } - - @Override - public Object unmarshal(final String value, final ErrorList errors) { - final String sPath = value; - File file = new File(sPath); - if (file.exists()) { - return file; - } else { - return null; - } - } - - @Override - public String marshal(final Object value) { - final File file = (File) value; - if (file == null) { - return null; - } else { - return file.getAbsolutePath(); - } - } - - public void doValidate(final Object value, final ErrorList errors) { - final File file = (File) value; - if (!file.exists()) { - errors.add( - new ParameterError( - this, - "File " + file.getAbsolutePath() + " does not exist")); - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/IntegerParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/IntegerParameter.java deleted file mode 100644 index 5f3f5fe3e..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/IntegerParameter.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import org.apache.commons.beanutils.converters.IntegerConverter; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * A parameter representing a Java Integer. - * - * Subject to change. - * - * @see java.lang.Integer - * @see Parameter - * @author Justin Ross <jross@redhat.com> - */ -public class IntegerParameter extends AbstractParameter { - - private final static Logger LOGGER = LogManager.getLogger( - IntegerParameter.class); - - static { - LOGGER.debug("Static initalizer starting..."); - Converters.set(Integer.class, new IntegerConverter()); - LOGGER.debug("Static initalizer finished."); - } - - public IntegerParameter(final String name) { - super(name, Integer.class); - } - - public IntegerParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt, Integer.class); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/MapParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/MapParameter.java deleted file mode 100644 index 6972cd59b..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/MapParameter.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.Assert; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; - -/** - * A parameter that manages a collection of Parameter to - * Object value mappings. - * - * Subject to change. - * - * @see java.util.Map - * @see Parameter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class MapParameter extends AbstractParameter { - - private final ArrayList m_params; - - public MapParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt, String.class); - - m_params = new ArrayList(); - } - - public MapParameter(final String name) { - super(name, String.class); - - m_params = new ArrayList(); - } - - public final void add(final Parameter param) { - Assert.exists(param, Parameter.class); - - m_params.add(param); - } - - public final boolean contains(final Parameter param) { - Assert.exists(param, Parameter.class); - - return m_params.contains(param); - } - - public final Iterator iterator() { - return m_params.iterator(); - } - - protected Object doRead(final ParameterReader reader, - final ErrorList errors) { - final HashMap map = new HashMap(); - final Iterator params = m_params.iterator(); - - while (params.hasNext()) { - final Parameter param = (Parameter) params.next(); - final Object value = param.read(reader, errors); - - if (value != null) { - map.put(param, value); - } - } - - return map; - } - - protected void doValidate(final Object value, final ErrorList errors) { - final HashMap map = (HashMap) value; - final Iterator params = m_params.iterator(); - - while (params.hasNext()) { - final Parameter param = (Parameter) params.next(); - - if (map.containsKey(param)) { - param.validate(map.get(param), errors); - } else { - param.validate(param.getDefaultValue(), errors); - } - } - } - - protected void doWrite(final ParameterWriter writer, final Object value) { - final HashMap map = (HashMap) value; - final Iterator params = m_params.iterator(); - - while (params.hasNext()) { - final Parameter param = (Parameter) params.next(); - - if (map.containsKey(param)) { - param.write(writer, map.get(param)); - } - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/Parameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/Parameter.java deleted file mode 100644 index e94f5a4d6..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/Parameter.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -/** - * Describes a named property that can read, write, and validate its - * own value. - * - * Subject to change. - * - * See the documentation on {@link #read}, {@link #write}, and {@link #validate} - * for details. - - * They have the following features as well: - * - *
      - *
    • Multiplicity. A parameter can be nullable (0..x) or required - * (1..x) and singular (x..1) or multiple (x..n). The current - * parameter implementation only models nullablel vs. required - * parameters.
    • - * - *
    • Defaulting. A parameter can have a value to fall back on if - * none is set.
    • - * - *
    • Optional metadata. Optional extra "info" can be associated - * with a parameter.
    • - *
    - * - * The read and validate phases of a parameter collect errors into a - * list so that calling code can control error handling. This is in - * lieu of throwing exceptions that are not useful in creating - * error-recovery UIs. - * - * In contrast, the write phase of a parameter is expected to complete - * successfully or fail outright. - * - * Parameters are stateless "messages". They do not store their own - * values. Instead, a {@link com.arsdigita.util.parameter.ParameterContext} - * manages a set of parameters and keeps their values. - * - * - * Here's what it typically looks like to use a parameter: - * - *
    - * Properties props = System.getProperties(); - * ParameterReader reader = JavaPropertyReader(props); - * ParameterWriter writer = JavaPropertyWriter(props); - * ErrorList errors = new ErrorList(); - * - * Object value = param.read(reader, errors); - * errors.check(); // If errors is not empty, fails - * - * param.validate(value, errors); - * errors.check(); // If errors is not empty, fails - * - * // We now have a valid unmarshaled value, so code of actual use can - * // go here. - * - * param.write(writer, value); - *
    - * - * @see com.arsdigita.util.parameter.AbstractParameter - * @see com.arsdigita.util.parameter.ParameterContext - * @author Rafael H. Schloming <rhs@mit.edu> - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public interface Parameter { - - /** - * Flag to indicate the parameter value is nullable. - */ - public static final int OPTIONAL = 0; - - /** - * Flag to indicate the parameter value cannot be null. - */ - public static final int REQUIRED = 1; - - /** - * Tells wether the parameter is nullable or not. - * - * @return true if the parameter cannot be null; false if it can - * be null - */ - boolean isRequired(); - - /** - * Gets the name of the parameter. - * - * @return The String parameter name; it cannot be - * null - */ - String getName(); - - /** - * Gets the default value of the parameter. Implementations may - * choose to substitute this value for null. - * - * @return The fallback value; it may be null - */ - Object getDefaultValue(); - - /** - * Gets metadata associated with the parameter if it is available. - * - * @return The ParameterInfo object; it may be null - */ - ParameterInfo getInfo(); - - /** - * Sets the optional parameter metadata to info. - * - * @param info The ParameterInfo to associate; it may - * be null - */ - void setInfo(ParameterInfo info); - - /** - * Gets the parameter value as a Java object. The value will have - * a specific runtime type and so may be appropriately cast. - * - * Reading typically follows the following procedure: - * - *
      - *
    • Read the literal string value associated with the - * parameter from reader
    • - * - *
    • Convert the literal string value into an approprite Java - * object
    • - *
    - * - * If at any point in the process an error is encountered, it is - * added to errors. Callers of this method will - * typically construct an ErrorList in which to - * collect errors. - * - * @param reader The ParameterReader from which to - * recover a string literal value; it cannot be null - * @param errors The ErrorList in which to collect - * any errors encountered; it cannot be null - * @return The Java object value of the parameter - */ - Object read(ParameterReader reader, ErrorList errors); - - /** - * Validates the parameter value, value. Any - * validation errors encountered are added to errors. - * - * @param value The value to validate; this is typically the value - * returned by {@link #read}; it may be null - * @param errors The ErrorList in which to collect - * any errors encountered; it cannot be null - */ - void validate(Object value, ErrorList errors); - - /** - * Writes the parameter value as a string literal. The parameter - * marshals the object value to a string and sends it - * to writer. - * - * @param writer The ParameterWriter that will take - * the marshaled value and store it; it cannot be null - * @param value The Java object value of the parameter - */ - void write(ParameterWriter writer, Object value); -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterContext.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterContext.java deleted file mode 100644 index 9fdf4b020..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterContext.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -/** - * A container of parameters. - * - * A parameter context binds together a set of parameters and keeps their values. - * - * - * Subject to change. - * - * @see com.arsdigita.util.parameter.Parameter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public interface ParameterContext { - - /** - * Returns all the parameters registered on the parameter context. - * - * @return A Parameter[] of all the parameters; it - * cannot be null - */ - Parameter[] getParameters(); - - /** - * Gets the unmarshaled value of param. If the - * loaded value is null, param.getDefaultValue() is - * returned. - * - * @param param The named Parameter whose value to - * retrieve; it cannot be null - * @return The unmarshaled Java object value of param - */ - Object get(Parameter param); - - /** - * Gets the unmarshaled value of param, returning - * dephalt if param's value is null. - * - * @param param The Parameter whose value to - * retrieve; it cannot be null - * @param dephalt The fallback default value; it may be null - * @return The unmarshaled Java object value of param - * or dephalt if the former is null - */ - Object get(Parameter param, Object dephalt); - - /** - * Sets the value of param to value. - * - * @param param The Parameter whose value to set; it - * cannot be null - * @param value The new value of param; it may be - * null - */ - void set(Parameter param, Object value); - - /** - * Reads and unmarshals all values associated with the registered - * parameters from reader. If any errors are - * encountered, they are added to errors. - * - * @param reader The ParameterReader from which to - * fetch the values; it cannot be null - * @param errors The ErrorList that captures any - * errors while loading; it cannot be null - */ - void load(ParameterReader reader, ErrorList errors); - - /** - * Marshals and writes all values associated with the registered - * parameters to writer. - * - * @param writer The ParameterWriter to which values - * are written; it cannot be null - */ - void save(ParameterWriter writer); - - /** - * Validates all values associated with the registered parameters. - * Any errors encountered are added to errors. - * - * @param errors The ErrorList that captures - * validation errors; it cannot be null - */ - void validate(ErrorList errors); -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterError.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterError.java deleted file mode 100644 index bc01d6225..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterError.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.Assert; - -/** - * Subject to change. - * - * Information about an error for a parameter. Parameter implementors - * will add ParameterErrors to the passed in - * ErrorList when their parameters encounter error - * conditions. - * - * @see ErrorList - * @see Parameter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public final class ParameterError { - - private final Parameter m_param; - private final String m_message; - private Throwable m_throwable; - - /** - * Constructs a parameter error for param. - * - * @param param The Parameter whose value is in - * error; it cannot be null - * @param message A String description of the error - */ - public ParameterError(final Parameter param, - final String message) { - if (Assert.isEnabled()) { - Assert.exists(param, Parameter.class); - Assert.exists(message, String.class); - } - - m_param = param; - m_message = message; - } - - /** - * Constructs a parameter error for param, drawing - * its error message from throwable. - * - * @param param The Parameter whose value is in - * error; it cannot be null - * @param throwable The Throwable for the error; it - * cannot be null - */ - public ParameterError(final Parameter param, - final Throwable throwable) { - this(param, throwable.getMessage()); - - m_throwable = throwable; - } - - /** - * Gets the parameter associated with this error. - * - * @return The Parameter in error; it cannot be null - */ - public final Parameter getParameter() { - return m_param; - } - - /** - * Gets the message associated with this error. - * - * @return The String message for the error; it - * cannot be null - */ - public final String getMessage() { - // XXX this actually can be null, so need to prevent that - return m_message; - } - - /** - * Gets the throwable, if present, that corresponds to the error. - * - * @return The Throwable of this error; it may be - * null - */ - public final Throwable getThrowable() { - return m_throwable; - } - - /** - * Returns a string representation of the error suitable for - * debugging. - * - * @return super.toString() + "," + param.getName() - */ - @Override - public String toString() { - return super.toString() + "," + m_param.getName(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterException.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterException.java deleted file mode 100644 index e3c0879af..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterException.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.Assert; - -import java.util.List; - -/** - * Subject to change. - * - * An exception to indicate invalid parameter states. This exception should only - * be used when the client code of a parameter opts in to using exceptions - * rather than handling parameter errors itself. See - * {@link com.arsdigita.util.parameter.ErrorList#check()}. - * - * @see com.arsdigita.util.parameter.ErrorList - * @author Justin Ross <jross@redhat.com> - */ -public final class ParameterException extends RuntimeException { - - private static final long serialVersionUID = 1726920836531266365L; - - private final ErrorList m_errors; - - /** - * Constructs a new parameter exception with the content - * message. - * - * @param message A String describing what's wrong; it cannot - * be null - * @param errors The ErrorList containing the errors that - * prompted this exception; it cannot be null - */ - public ParameterException(final String message, final ErrorList errors) { - super(message); - - if (Assert.isEnabled()) { - Assert.exists(message, String.class); - Assert.exists(errors, List.class); - } - - m_errors = errors; - } - - /** - * Gets the set of errors associated with the exception. - * - * @return The ErrorList of errors; it cannot be null - */ - public final ErrorList getErrors() { - return m_errors; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterInfo.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterInfo.java deleted file mode 100644 index 3c6fd0087..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterInfo.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -/** - * Subject to change. - * - * Metadata for a parameter that is of use for building documentation - * or user interfaces for parameters. The fields are not required and - * thus the methods of this class may return null. - * - * @see Parameter#setInfo(ParameterInfo) - * @see Parameter#getInfo() - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public interface ParameterInfo { - - /** - * Gets the pretty name of the parameter. - * - * @return The String title of the parameter; it may - * be null - */ - String getTitle(); - - /** - * Gets the parameter's reason for being. - * - * @return The String purpose of the parameter; it - * may be null - */ - String getPurpose(); - - /** - * Gets an example value for the parameter. - * - * @return A String example value; it may be null - */ - String getExample(); - - /** - * Gets a format description. - * - * @return A format String; it may be null - */ - String getFormat(); -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterReader.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterReader.java deleted file mode 100644 index 4bf435512..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterReader.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -/** - * Reads an encoded string value for a parameter from storage. Any - * errors encountered while reading are added to an error list. - * This class is counterpart to ParameterWriter. - * - * Subject to change. - * - * @see Parameter#write(ParameterWriter, Object) - * @see ErrorList - * @see ParameterWriter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public interface ParameterReader { - - /** - * Reads an encoded String value for - * param from storage. If there are errors, they are - * added to errors. - * - * @param param The Parameter being read; it cannot - * be null - * @param errors The ErrorList that will collect any - * errors; it cannot be null - * @return The marshaled String value for - * param; it may be null - */ - String read(Parameter param, ErrorList errors); -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterWriter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterWriter.java deleted file mode 100644 index 6794bfb49..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/ParameterWriter.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -/** - * Subject to change. - * - * Writes encoded parameter values to storage. Implementors define - * the exact nature of the storage. - * - * @see Parameter#write(ParameterWriter,Object) - * @see ParameterReader - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public interface ParameterWriter { - - /** - * Writes the marshaled value for parameter - * param to storage. - * - * @param param The Parameter that is being written; - * it cannot be null - * @param value The encoded String value to store for - * param; it may be null - */ - void write(Parameter param, String value); -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/ResourceParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/ResourceParameter.java deleted file mode 100644 index e353da811..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/ResourceParameter.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.net.URL; -import java.util.Iterator; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.arsdigita.util.UncheckedWrapperException; - -/** - * A parameter representing a JEE Resource (input stream). - * - * This takes in a path and makes sure that the resource exists either - * as a File or an actual resource. If it does, it returns the - * InputStream for the given Resource. If it does not, and if it is - * required, it logs an error. Otherwise, it returns null. - * - * Development note / CHANGELOG - * Had been deprecated for a while in favour of an URLParameter and a - * application specific resource: protocol extension (c.ad.util.protocol.resource). - * As of version 6.5 reverted to ResourceParameter to avoid non-standard extensions. - * - * @author Justin Ross <jross@redhat.com> - * @author Brett <bprucha@users.sourceforge net> - * @author PBoy <pboy@users.sourceforge net> - */ -public class ResourceParameter extends AbstractParameter { - - private static final Logger LOGGER = LogManager.getLogger(ResourceParameter.class); - - private Object m_default = null; - - public ResourceParameter(final String name) { - super(name, InputStream.class); - } - - public ResourceParameter(final String name, - final int multiplicity, - final Object defaultValue) { - - super(name, multiplicity, defaultValue, InputStream.class); - m_default = defaultValue; - } - - /** - * Get default value and return it as InputStream. - * - * Developers note: - * This makes the trick to use Parameter.java interface rsp AbstractParameter - * for other types of parameter as String. If you don't overwrite this - * method, you will always get a casting error, because the parameter - * returns a string instead of the intended object! - * - * @return default value as InputStream - */ - public Object getDefaultValue() { - - if(m_default instanceof String) { - ErrorList errors = new ErrorList(); - InputStream stream = (InputStream)unmarshal((String)m_default, errors); - - if(!errors.isEmpty()) { - String strErrors = ""; - for(Iterator i = errors.iterator(); i.hasNext(); ) { - ParameterError pe = (ParameterError)i.next(); - strErrors += pe.getMessage() + "\r\n"; - } - throw new UncheckedWrapperException(strErrors); - } - - return stream; - } else - return m_default; - } - - /** - * Unmarshals the encoded string value of the parameter to get the intended - * object type. It tries first to find a file of the specified name in the - * file system. If not successful it uses the classloader to find the file - * in the class path / jar files. - * - * @param value - * @param errors - * @return parameter value as an InputStream - */ - @Override - protected Object unmarshal(String value, final ErrorList errors) { - - // NOTE: - // This implementation will never find the file in the file system. - // The name has to be specified relativ to document root. So we must - // precede value with the context path, e.g. using - // c.ad.runtime.CCMResourceManager as soon as it's implementation is - // fixed / stable (when all modifications of the runtime environment - // are done). - File file = new File(value); - - if (!file.exists()) { - // it is not a standard file so lets try to see if it - // is a resource - if (value.startsWith("/")) { - value = value.substring(1); - } - - ClassLoader cload = Thread.currentThread().getContextClassLoader(); - URL url = cload.getResource(value); - InputStream stream = cload.getResourceAsStream(value); - if (stream == null && isRequired()) { - LOGGER.error(value + " is not a valid file and is required"); - - final ParameterError error = new ParameterError - (this, "Resource not found"); - errors.add(error); - } - return stream; - } else { - try { - return new FileInputStream(file); - } catch (FileNotFoundException ioe) { - // we know the file exists so this should not - // be an issue - LOGGER.error(value + " is not a valid file and is required", ioe); - - errors.add(new ParameterError(this, ioe)); - - return null; - } - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/SingletonParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/SingletonParameter.java deleted file mode 100644 index eb6d00d2d..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/SingletonParameter.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import com.arsdigita.util.Classes; -import com.arsdigita.util.UncheckedWrapperException; - -/** - * A parameter representing an instance of a Java class. - * - * Subject to change. - * - * @see Parameter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class SingletonParameter extends ClassParameter { - - public SingletonParameter(final String name) { - super(name); - } - - public SingletonParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt); - } - - protected String marshal(Object value) { - return super.marshal(value.getClass()); - } - - protected Object unmarshal(final String value, final ErrorList errors) { - final Class clacc = (Class) super.unmarshal(value, errors); - if(clacc == null) { - return null; - } - - try { - return Classes.newInstance(clacc); - } catch (UncheckedWrapperException uwe) { - errors.add(new ParameterError(this, uwe.getRootCause())); - return null; - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/SpecificClassParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/SpecificClassParameter.java deleted file mode 100644 index b26a220e0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/SpecificClassParameter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -/** - * A parameter representing a Java Class which is checked to be - * an implementation of a required class / interface. - * - * Subject to change. - * - * @see java.lang.Class - * @see Parameter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class SpecificClassParameter extends ClassParameter { - - - private Class m_requiredClass; - - /** - * Constructor - * @param name - * @param multiplicity - * @param defaultObj - * @param requiredClass - */ - public SpecificClassParameter(final String name, - final int multiplicity, - final Object defaultObj, - final Class requiredClass) { - super(name, multiplicity, defaultObj); - m_requiredClass = requiredClass; - } - - /** - * Unmarshals a string representation of the parameter. - * - * @param value string representation of class, must be value != null - * @param errors - * @return - */ - @Override - protected Object unmarshal(String value, ErrorList errors) { - Class theClass = (Class) super.unmarshal(value,errors); - if (theClass != null) { - if (!m_requiredClass.isAssignableFrom(theClass)) { - errors.add(new ParameterError(this, "class " + value + - " must implement : " + - m_requiredClass.getName())); - } - } - - return theClass; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/StringArrayParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/StringArrayParameter.java deleted file mode 100644 index ec397cc62..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/StringArrayParameter.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -// import com.arsdigita.util.parameter.StringParameter; -// import com.arsdigita.util.parameter.ErrorList; -import com.arsdigita.util.StringUtils; - -/** - * StringArrayParameter - * - * Usage Example: - *
    - * private static parameter exampleName ;
    - * exampleName = new StringArrayParameter(
    - *                   "com.arsdigita.package.example_name",
    - *                   Parameter.REQUIRED,
    - *                   new String[] {"String Example 01","String Example 02"}
    - *                                       );
    - * 
    - * - * @version $Id$ - */ -public class StringArrayParameter extends StringParameter { - - /** - * - * @param name: String literal - * @param multiplicity Indicator wether required (1) or not (0) (nullable) - * @param defaalt default value - */ - public StringArrayParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt); - - } - - /** - * Converts a String[] object into a literal representation. - * - * @param value - * @return - */ - @Override - protected String marshal(final Object value) { - if (value == null) { - return null; - } else { - return StringUtils.join((String[])value, ','); - } - } - - /** - * - * @param literal - * @param errors - * @return - */ - @Override - protected Object unmarshal(final String literal, - final ErrorList errors) { - final String[] literals = StringUtils.split(literal, ','); - final String[] strings = new String[literals.length]; - - for (int i = 0; i < literals.length; i++) { - final String elem = literals[i]; - - strings[i] = (String) super.unmarshal(elem, errors); - - if (!errors.isEmpty()) { - break; - } - } - return strings; - } - - @Override - protected void doValidate(final Object value, - final ErrorList errors) { - if (value != null) { - final String[] strings = (String[]) value; - - for (int i = 0; i < strings.length; i++) { - super.doValidate(strings[i], errors); - - if (!errors.isEmpty()) { - break; - } - } - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/StringParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/StringParameter.java deleted file mode 100644 index fe9ce0830..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/StringParameter.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import org.apache.commons.beanutils.converters.StringConverter; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * A parameter representing a Java String. - * - * Subject to change. - * - * @see java.lang.String - * @see Parameter - * @author Justin Ross <jross@redhat.com> - */ -public class StringParameter extends AbstractParameter { - - private static final Logger LOGGER = LogManager.getLogger( - StringParameter.class); - - static { - LOGGER.debug("Static initalizer starting..."); - Converters.set(String.class, new StringConverter()); - LOGGER.debug("Static initalizer finished."); - } - - public StringParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt, String.class); - } - - public StringParameter(final String name) { - super(name, String.class); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/parameter/URLParameter.java b/ccm-core/src/main/java/com/arsdigita/util/parameter/URLParameter.java deleted file mode 100644 index 5b23eab93..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/parameter/URLParameter.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.parameter; - -import java.net.MalformedURLException; -import java.net.URL; - -/** - * Subject to change. - * - * A parameter representing a Java URL. - * - * @see java.net.URL - * @see Parameter - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class URLParameter extends StringParameter { - - public URLParameter(final String name) { - super(name); - } - - public URLParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt); - } - - protected Object unmarshal(final String value, final ErrorList errors) { - try { - return new URL(value); - } catch (MalformedURLException mue) { - errors.add(new ParameterError(this, mue)); - return null; - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/servlet/HttpHost.java b/ccm-core/src/main/java/com/arsdigita/util/servlet/HttpHost.java deleted file mode 100644 index 0b9ec0e68..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/servlet/HttpHost.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.servlet; - -import com.arsdigita.util.Assert; -import javax.servlet.http.HttpServletRequest; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * Represents a host computer. The host may in fact be a "virtual" - * host, one of several on the same physical machine. - * - * @author Dan Berrange - * @author Justin Ross <jross@redhat.com> - */ -public class HttpHost { - - private static final Logger LOGGER = LogManager.getLogger(HttpHost.class); - - private final String m_name; - private final int m_port; - - /** - * Constructs a new host named name and on port - * port. - * - * @param name A String host name, for example - * "ccm.redhat.com"; see {@link - * javax.servlet.ServletRequest#getServerName()}; it cannot be - * null - * @param port An int port number; 8080, - * for instance; see {@link - * javax.servlet.ServletRequest#getServerPort()}; it must be - * greater than 0 - */ - public HttpHost(final String name, final int port) { - if (Assert.isEnabled()) { - Assert.exists(name, String.class); - Assert.isTrue(port > 0, - "The port must be greater than 0; " + - "I got " + port); - } - - m_name = name; - m_port = port; - } - - /** - * Constructs a host representing the host-specific part of - * sreq. - * - * @param sreq An HttpServletRequest representation - * of a request; it cannot be null - */ - public HttpHost(final HttpServletRequest sreq) { - final String header = sreq.getHeader("Host"); - - if (header == null) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("No 'Host:' header present; falling back " + - "on values from servlet request"); - } - - m_name = sreq.getServerName(); // XXX use httpserver - m_port = sreq.getServerPort(); - } else { - final int colon = header.indexOf( ':' ); - - if (colon == -1) { - m_name = header; - - // Internet Explorer doesn't include the port number - // in the Host: header, so if your server *appears* to - // be on port 80, we take a look at the actual server - // port to verify. - // - // NB. So for vHosting to work, you must make sure - // your web server is using the same port as your - // squid proxy - final String agent = sreq.getHeader("User-Agent"); - - if (agent != null - && agent.toLowerCase().indexOf("msie") >= 0) { - m_port = sreq.getServerPort(); // XXX use httpserver - } else { - m_port = 80; - } - } else { - m_name = header.substring(0, colon); - m_port = Integer.parseInt - (header.substring(colon + 1, header.length())); - } - } - } - - /** - * Gets the host name. - * - * @return A String naming the host; it cannot be - * null - */ - public final String getName() { - return m_name; - } - - /** - * Gets the port of this host. - * - * @return A int port number - */ - public final int getPort() { - return m_port; - } - - final void toString(final StringBuffer buffer) { - buffer.append(getName()); - - final int port = getPort(); - - if (port != 80) { - buffer.append(":"); - buffer.append(port); - } - } - - /** - * Returns a String representation of this host. - * - * @return getName() + ":" + getPort() or simply - * getName() if the port is 80 - */ - @Override - public String toString() { - final StringBuffer buffer = new StringBuffer(24); - - toString(buffer); - - return buffer.toString(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/util/servlet/HttpHostParameter.java b/ccm-core/src/main/java/com/arsdigita/util/servlet/HttpHostParameter.java deleted file mode 100644 index 91d0e0325..000000000 --- a/ccm-core/src/main/java/com/arsdigita/util/servlet/HttpHostParameter.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.util.servlet; - -import com.arsdigita.util.parameter.ErrorList; -import com.arsdigita.util.parameter.ParameterError; -import com.arsdigita.util.parameter.StringParameter; - -/** - * This class represents info about a single host running a server in a webapp - * cluster. - */ -public class HttpHostParameter extends StringParameter { - - public HttpHostParameter(final String name) { - super(name); - } - - public HttpHostParameter(final String name, - final int multiplicity, - final Object defaalt) { - super(name, multiplicity, defaalt); - } - - protected Object unmarshal(final String value, final ErrorList errors) { - if (value.indexOf("://") != -1) { - final ParameterError error = new ParameterError(this, - "The value must not have a scheme prefix"); - errors.add(error); - } - - if (value.indexOf("/") != -1) { - final ParameterError error = new ParameterError(this, - "The value must not contain slashes"); - errors.add(error); - } - - final int sep = value.indexOf(":"); - - if (sep == -1) { - final ParameterError error = new ParameterError(this, - "The value must contain a colon"); - errors.add(error); - } - - if (!errors.isEmpty()) { - return null; - } - - try { - final String name = value.substring(0, sep); - final String port = value.substring(sep + 1); - - return new HttpHost(name, Integer.parseInt(port)); - } catch (IndexOutOfBoundsException ioobe) { - final ParameterError error = new ParameterError(this, - "The host spec is invalid; it must take the form " - + "hostname:hostport"); - errors.add(error); - - return null; - } catch (NumberFormatException nfe) { - final ParameterError error = new ParameterError(this, - "The port number must be an integer with no " - + "extraneous spaces or punctuation"); - errors.add(error); - - return null; - } - } - - protected String marshal(Object value) { - if (value == null) { - return null; - } else { - final HttpHost host = (HttpHost) value; - return host.getName() + ":" + host.getPort(); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/ApplicationFileResolver.java b/ccm-core/src/main/java/com/arsdigita/web/ApplicationFileResolver.java deleted file mode 100644 index 968aef318..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/ApplicationFileResolver.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import org.libreccm.web.CcmApplication; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.RequestDispatcher; - - -/** - * Interface specifies standard API tools to resolve an URL to a accessible - * resource, stored in file system, database of any other suitable location. - * The URL may include virtual resources, e.g. files stored in the database - * instead of the file system. The URL may include other "virtual" parts with - * must be mapped to an appropriate real path. - */ -public interface ApplicationFileResolver { - - /** - * - * @param templatePath - * @param sreq - * @param sresp - * @param app - * @return - */ - RequestDispatcher resolve(String templatePath, - HttpServletRequest sreq, - HttpServletResponse sresp, - CcmApplication app); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/BaseApplicationServlet.java b/ccm-core/src/main/java/com/arsdigita/web/BaseApplicationServlet.java deleted file mode 100644 index c289a8f2b..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/BaseApplicationServlet.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (C) 2015 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.web; - -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.dispatcher.InitialRequestContext; -import com.arsdigita.dispatcher.RequestContext; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.libreccm.web.ApplicationRepository; -import org.libreccm.web.CcmApplication; - -import java.io.IOException; - -import javax.inject.Inject; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - *

    - * The base servlet for CCM applications. It manages database transactions, - * prepares an execution context for the request, and traps and handles requests - * to redirect.

    - * - *

    - * Most CCM applications will extend this class by implementing - * {@link #doService(HttpServletRequest,HttpServletResponse,CcmApplication)} to - * perform application-private dispatch to UI code.

    - * - *

    - * The application will be available at the path - * www.example.org/ccm/applicationname, where - * applicationname is the name defined for the application and - * www.example.org the URL of the server. - *

    - * - * @see com.arsdigita.web.BaseServlet - * @see com.arsdigita.web.DispatcherServlet - * @see com.arsdigita.web.RedirectSignal - * - * @author Justin Ross - * <jross@redhat.com> - * @author - * Jens Pelzetter - */ -public abstract class BaseApplicationServlet extends BaseServlet { - - private static final long serialVersionUID = 3204787384428680311L; - - private static final Logger LOGGER = LogManager.getLogger( - BaseApplicationServlet.class); - - /** - *

    - * The ID of the application whose service is requested. This request - * attribute must be set by a previous servlet or filter before this servlet - * can proceed. In CCM, the default servlet, {@link DispatcherServlet}, sets - * this attribute using the {@link BaseDispatcher}. - * Important: This does only work if the application is - * called using an URL like - * http://www.example.org/ccm/application!

    - */ - public static final String APPLICATION_ID_ATTRIBUTE - = BaseApplicationServlet.class.getName() - + ".application_id"; - - /** - *

    - * The same as {@link #APPLICATION_ID_ATTRIBUTE}, but as a request - * parameter. This is present so applications not using the dispatcher - * servlet may accept requests directly to their servlets, provided the - * application ID is given in the URL.

    - */ - public static final String APPLICATION_ID_PARAMETER = "app-id"; - - /** - * {@link ApplicationRepository} provided by CDI. - */ - @Inject - private ApplicationRepository appRepository; - - /** - *

    - * Augments the context of the request and delegates to {@link - * #doService(HttpServletRequest,HttpServletResponse,CcmApplication)}.

    - * - * @throws javax.servlet.ServletException - * @throws java.io.IOException - * @see - * com.arsdigita.web.BaseServlet#doService(HttpServletRequest,HttpServletResponse) - */ - @Override - protected void doService(final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException { - - final CcmApplication app = getApplication(request); - - if (app == null) { - response.sendError(404, "Application not found"); - throw new IllegalStateException("Application not found"); - } - - Web.getWebContext().setApplication(app); - -// final RequestContext rc = makeLegacyContext( -// request, app, Web.getUserContext()); -// - final RequestContext context = new InitialRequestContext(request, - getServletContext()); - DispatcherHelper.setRequestContext(request, context); -// -// final ServletException[] servletException = {null}; -// final IOException[] ioException = {null}; - doService(request, response, app); - } - - /** - * The method that - * {@link #doService(HttpServletRequest,HttpServletResponse)} calls. Servlet - * authors should implement this method to perform application-specific - * request handling - * - * @see - * javax.servlet.http.HttpServlet#service(HttpServletRequest,HttpServletResponse) - * - * @param sreq - * @param sresp - * @param app - * - * @throws javax.servlet.ServletException - * @throws java.io.IOException - */ - protected abstract void doService(final HttpServletRequest sreq, - final HttpServletResponse sresp, - final CcmApplication app) - throws ServletException, IOException; - - /** - * - * @param sreq - * - * @return - */ - private CcmApplication getApplication(final HttpServletRequest request) { - LOGGER.debug("Resolving the application that will handle this request"); - - Long appId = (Long) request.getAttribute(APPLICATION_ID_ATTRIBUTE); - - if (appId == null) { - LOGGER.debug("I didn't receive an application ID with the " - + "servlet request; trying to get it from the " - + "query string"); - - final String value = request.getParameter(APPLICATION_ID_PARAMETER); - - if (value != null) { - try { - appId = Long.getLong(value); - } catch (NumberFormatException ex) { - throw new IllegalStateException("Could not parse '" + value - + "' into a long"); - } - } - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Retrieving application " + appId + " from the " - + "database"); - } - - return appRepository.findById(appId).get(); - } - - /** - * - * @param sreq - * @param app - * @param uc - * - * @return - */ -// private RequestContext makeLegacyContext(HttpServletRequest sreq, -// final CcmApplication app, -// final UserContext uc) { -// s_log.debug("Setting up a legacy context object"); -// -// sreq = DispatcherHelper.restoreOriginalRequest(sreq); -// -// final InitialRequestContext irc = new InitialRequestContext -// (sreq, getServletContext()); -// final SessionContext sc = uc.getSessionContext(); -// -// final KernelRequestContext krc = new KernelRequestContext -// (irc, sc, uc); -// -// return krc; -// } -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/BaseServlet.java b/ccm-core/src/main/java/com/arsdigita/web/BaseServlet.java deleted file mode 100644 index aa27a0b17..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/BaseServlet.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (C) 2015 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.web; - -import com.arsdigita.dispatcher.DispatcherHelper; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * - * @author Jens Pelzetter - */ -public abstract class BaseServlet extends HttpServlet { - - private static final long serialVersionUID = -3402624854177649796L; - - private static final Logger LOGGER = LogManager.getFormatterLogger( - BaseServlet.class); - - public static final String REQUEST_URL_ATTRIBUTE = BaseServlet.class - .getName() + ".request_url"; - - /** - * Initializer uses parent class's initializer to setup the servlet request, - * response and application context. Usually a user of this class will not - * overwrite this method but the user extension point doInit to perform - * local initialization tasks! - * - * @param config - * - * @throws javax.servlet.ServletException - */ - @Override - public void init(final ServletConfig config) throws ServletException { - LOGGER.info("Initialising servlet %s (class: %s)...", - config.getServletName(), - getClass().getName()); - - super.init(config); - - //Check if we not the ResourceManager for CCM NG. Also check if we - //can replace static instance with an application scoped CDI Bean - //ResourceManager.getInstance().setServletContext(getServletContext); - doInit(); - } - - protected void doInit() throws ServletException { - //Empty - } - - @Override - public final void destroy() { - LOGGER.info("Destroying servlet %s...", - getServletConfig().getServletName()); - - doDestroy(); - } - - protected void doDestroy() { - /// Empty - } - - private void internalService(final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException { - - InternalRequestLocal.prepareAll(request); - DispatcherHelper.setRequest(request); - Web.init(request, getServletContext()); - Web.getWebContext().setRequestURL(getRequestURL(request)); - - try { - doService(request, response); - } catch (RedirectSignal signal) { - redirect(response, signal); - } catch (ServletException ex) { - final RedirectSignal signal = findRedirectSignal(ex); - - if (signal == null) { - throw ex; - } else { - redirect(response, signal); - } - } - } - - /** - *

    - * The method that {@link - * #doGet(HttpServletRequest,HttpServletResponse)} and {@link - * #doPost(HttpServletRequest,HttpServletResponse)} call. This is the - * extension point for users of this class.

    - * - * @param request - * @param response - * - * @throws javax.servlet.ServletException - * @throws java.io.IOException - */ - protected abstract void doService(final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException; - - /** - *

    - * Processes HTTP GET requests.

    - * - * @param request - * @param response - * - * @throws javax.servlet.ServletException - * @throws java.io.IOException - * @see - * javax.servlet.http.HttpServlet#doGet(HttpServletRequest,HttpServletResponse) - */ - @Override - protected final void doGet(final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException { - LOGGER.info("Serving GET request path %s with servlet %s (class: %s)", - request.getPathInfo(), - getServletConfig().getServletName(), - getClass().getName()); - - internalService(request, response); - } - - /** - *

    - * Processes HTTP POST requests.

    - * - * @param request - * @param response - * - * @throws javax.servlet.ServletException - * @throws java.io.IOException - * - * @see - * javax.servlet.http.HttpServlet#doPost(HttpServletRequest,HttpServletResponse) - */ - @Override - protected final void doPost(final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException { - LOGGER.info("Serving POST request path %s with servlet %s (class: %s)", - request.getPathInfo(), - getServletConfig().getServletName(), - getClass().getName()); - - final HttpServletRequest wrappedRequest = DispatcherHelper - .maybeWrapRequest(request); - - internalService(wrappedRequest, response); - } - - private URL getRequestURL(final HttpServletRequest request) { - URL url = (URL) request.getAttribute(REQUEST_URL_ATTRIBUTE); - - if (url == null) { - url = new URL(request); - } - - return url; - } - - private RedirectSignal findRedirectSignal(final ServletException ex) { - Throwable root = ex.getRootCause(); - - while (root instanceof ServletException) { - root = ((ServletException) root).getRootCause(); - } - - if (root instanceof RedirectSignal) { - return (RedirectSignal) root; - } else { - return null; - } - } - - private void redirect(final HttpServletResponse response, - final RedirectSignal redirectSignal) - throws IOException { - final String url = response.encodeRedirectURL(redirectSignal - .getDestinationURL()); - - response.sendRedirect(url); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/CCMApplicationContextListener.java b/ccm-core/src/main/java/com/arsdigita/web/CCMApplicationContextListener.java deleted file mode 100644 index 608f8ac13..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/CCMApplicationContextListener.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2015 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.web; - -import com.arsdigita.runtime.CCMResourceManager; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; - -/** - * Listener used to initialise several parameters for legacy CCM classes. This - * class is not identical with the class with same name in old versions. It has - * been modified so that only those things are done which necessary to get the - * legacy classes, for instance the classes derived from - * {@link com.arsdigita.runtime.AbstractConfig} working. Also it is not longer - * necessary to include an entry in the {@code web.xml} for this class because - * this can be done using {@link @WebListener} annotation in the Servlet API - * 3.0. - * - * The following is the documentation from the original class which is provided - * here for reference. The information is outdated! - * - * Web application lifecycle listener, used to perform central initialisation - * tasks at CCM startup in a Servlet container / web application server, - * expecially setting the runtime context (file locations) and (in the future) - * the database connection. - * - * @author pboy - * @author Jens Pelzetter Jens - * Pelzetter - */ -@WebListener -public class CCMApplicationContextListener implements ServletContextListener { - - public static final Logger LOGGER = LogManager.getLogger( - CCMApplicationContextListener.class); - - @Override - public void contextInitialized(final ServletContextEvent event) { - final ServletContext context = event.getServletContext(); - - final String appBase = context.getRealPath("/"); - - LOGGER.info(String.format("Setting base directory to %s", appBase)); - CCMResourceManager.setBaseDirectory(appBase); - } - - @Override - public void contextDestroyed(final ServletContextEvent event) { - //Nothing yet - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/CCMDispatcherServlet.java b/ccm-core/src/main/java/com/arsdigita/web/CCMDispatcherServlet.java deleted file mode 100644 index 643635d3f..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/CCMDispatcherServlet.java +++ /dev/null @@ -1,585 +0,0 @@ -/* - * Copyright (C) 2015 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.web; - -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.dispatcher.MultipartHttpServletRequest; -import com.arsdigita.ui.UI; -import com.arsdigita.util.Assert; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.web.CcmApplication; -import org.libreccm.web.ApplicationRepository; -import org.libreccm.web.ServletPath; - -import java.io.IOException; -import java.math.BigDecimal; - -import javax.inject.Inject; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.shiro.subject.Subject; -import org.libreccm.web.ApplicationManager; -import org.libreccm.web.ApplicationType; - -import javax.servlet.http.HttpServlet; - -/** - *

    - * The CCM main dispatcher. This servlet serves as the main servlet / main entry - * point (mapped to "/someprefix/*") for requests to any CCM webapp.

    - * - *

    - * Upon finding an {@link com.arsdigita.web.Application application} at the - * requested URL, this class sets a request attribute storing the ID of the - * application and forwards to the servlet associated with that application. If - * instead no application is found, a 404 response is generated.

    - * - * For LibreCCM there a few changes to this Servlet compared to earlier versions - * of CCM: - * - *
      - *
    • - * No entries in the web.xml required anymore. We are now using the - * annotations from the Servlet API 3. - *
    • - *
    • - * The servlet in now mapped to /ccm/* and to - * /index.html. The mapping to /index.html replaces - * the index.jsp. The logic which was implemented in the - * index.jsp is now part of the - * {@link #doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)} - * method of this Servlet. - *
    • - *
    - * - * - * @author Justin Ross - * <jross@redhat.com> - * @author Peter Boy <Peter - * Boy> - * @author Jens Pelzetter - */ -@WebServlet(urlPatterns = {"/ccm/*", "/index.html"}, - loadOnStartup = 1) -public class CCMDispatcherServlet extends BaseServlet { - - private static final long serialVersionUID = 5292817856022435529L; - - private static final Logger LOGGER = LogManager.getLogger( - CCMDispatcherServlet.class); - - private static final String DISPATCHED_ATTRIBUTE - = CCMDispatcherServlet.class - .getName() + ".dispatched"; - - /** - * String containing the web context path portion of the WEB application - * where this CCMDispatcherServlet is executed. (I.e. where the WEB-INF - * directory containing the web.xml configuring this CCMDispatcherServlet is - * located in the servlet container webapps directory. - * - */ - private static String s_contextPath; - - @Inject - private ApplicationRepository appRepository; - - @Inject - private ApplicationManager appManager; - - @Inject - private Subject subject; - - /** - * Servlet initializer uses the extension point of parent class. - * - * @throws ServletException - */ - @Override - public void doInit() throws ServletException { - - ServletContext servletContext = getServletContext(); - s_contextPath = servletContext.getContextPath(); - // For backwords compatibility reasons register the web application - // context of the Core (root) application als "/" - // Web.registerServletContext("/", - // servletContext); - - } - - @Override - protected void doService(final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException { - - //This part replaces the index.jsp file - if (request.getPathInfo() == null - || request.getPathInfo().isEmpty() - || "/".equals(request.getPathInfo())) { - - if (subject.isAuthenticated()) { - // User is logged in, redirect to user redirect page - throw new RedirectSignal( - URL.there(request, - UI.getUserRedirectURL(request)), - false); - } else { - // User is *not* logged in, display public front page - throw new RedirectSignal(URL.there(request, - UI.getWorkspaceURL(request)), - true); - } - } - // index.jsp replacement end - - LOGGER.debug("Dispatching request {} [ {}, {}, {}, {} ]", - request.getRequestURI(), - request.getContextPath(), - request.getPathInfo(), - request.getQueryString()); - - final String path = request.getPathInfo(); - - if (requiresTrailingSlash(path)) { - LOGGER.debug("The request URI needs a trailing slash. Redirecting"); - - final String prefix = DispatcherHelper.getDispatcherPrefix(request); - String uri = request.getRequestURI(); - if (prefix != null && prefix.trim().length() > 0) { - uri = prefix + uri; - } - final String query = request.getQueryString(); - - if (query == null) { - response.sendRedirect(response.encodeRedirectURL(uri + "/")); - } else { - response.sendRedirect(response - .encodeRedirectURL(uri + "/?" + query)); - } - } else { - LOGGER.debug("Storing the path elements of the current request as " - + "the original path elements"); - - request.setAttribute(BaseServlet.REQUEST_URL_ATTRIBUTE, - new URL(request)); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Using path '{}' to lookup application", path); - } - - final ApplicationSpec spec = lookupApplicationSpec(path); - - if (spec == null) { - LOGGER.debug("No application was found; doing nothing"); - // return false; - // we have to create a 404 page here! - String requestUri = request.getRequestURI(); // same as ctx.getRemainingURLPart() - response.sendError(404, requestUri - + " not found on this server."); - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Found application {}; " - + "dispatching to its servlet", - spec.getAppID()); - } - - request.setAttribute( - BaseApplicationServlet.APPLICATION_ID_ATTRIBUTE, - spec.getAppID()); - request.setAttribute(DISPATCHED_ATTRIBUTE, Boolean.TRUE); - forward(spec.getTypeContextPath(), - spec.target(path), - request, - response); - // return true; - } - - } - - } - - private boolean requiresTrailingSlash(final String path) { - LOGGER.debug("Checking if the required needs a trailing slash..."); - - if (path == null) { - LOGGER.debug("The path is null; the request needs a trailing slash"); - return true; - } - - if (path.endsWith("/")) { - LOGGER.debug("The path already ends in '/'"); - return false; - } - - if (path.lastIndexOf(".") < path.lastIndexOf("/")) { - LOGGER.debug("The last fragment of the path has no '.', so we " - + "assume a directory was requested; a trailing " - + "slash is required"); - return true; - } else { - LOGGER.debug("The last fragment of the path appears to be a file " - + "name; no trailing slash is needed"); - return false; - } - } - - private void forward(final String contextPath, - final String target, - final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException { - - LOGGER.debug("Forwarding by path to target \"{}\"...", target); - LOGGER.debug("The context path is: {}", contextPath); - final String forwardContextPath; - if (contextPath == null || contextPath.isEmpty()) { - //Not compliant with Servlet specification. - //Empty context has be be "/" - forwardContextPath = "/"; - } else if (!contextPath.endsWith("/")) { - //No trailing slash, add one - forwardContextPath = String.format("%s/", contextPath); - } else { - forwardContextPath = contextPath; - } - - final ServletContext context = getServletContext().getContext( - forwardContextPath); - - LOGGER.debug("forwarding from context \"{}\" to context \"{}\"...", - getServletContext(), context); - - forward(getServletContext().getRequestDispatcher(target), - DispatcherHelper.restoreOriginalRequest(request), - response); - } - - private void forward(final RequestDispatcher dispatcher, - final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException { - LOGGER.debug("Checking if this request need to be forwarded or " - + "included: {}", request); - - if (request.getAttribute("javax.servlet.include.request_uri") == null) { - LOGGER.debug("The attribute javax.servlet.include.request_uri " - + "is not set; forwarding {}", - request); - - dispatcher.forward(request, response); - } else { - LOGGER.debug("The attribute javax.servlet.include.request_uri " - + "is set; including {}", - request); - dispatcher.include(request, response); - } - } - - /** - * - * @param path - * - * @return - */ - private ApplicationSpec lookupApplicationSpec(final String path) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("*** Starting application lookup for path '{}' ***", - path); - } - - final String pathTokens[]; - if (path.startsWith("/")) { - pathTokens = path.substring(1).split("/"); - } else { - pathTokens = path.split("/"); - } - CcmApplication application = null; - for (int i = pathTokens.length; i > 0; i--) { - final String currentPath = generatePath(i, pathTokens); - LOGGER.debug("Trying path '{}'...", currentPath); - application = appManager.findApplicationByPath(currentPath); - - if (application != null) { - LOGGER.debug("Found application for path '{}'.", currentPath); - break; - } - } - -// final CcmApplication application = appManager -// .findApplicationByPath(path); - if (application == null) { - LOGGER.warn("No application found for path \"{}\".", path); - return null; - } else { - return new ApplicationSpec(application, appManager); - } - } - - private String generatePath(final int index, final String[] pathTokens) { - final StringBuffer buffer = new StringBuffer(); - buffer.append('/'); - for (int i = 0; i < index; i++) { - buffer.append(pathTokens[i]); - buffer.append('/'); - } - - return buffer.toString(); - } - - public static String getContextPath() { - return s_contextPath; - } - - /** - * - */ - /* Nothing specifically to destroy here - @Override - protected void doDestroy() { - } - */ - /** - * Private class. - */ - private static class ApplicationSpec { - - private final long m_id; - private final String m_instanceURI; - private final String m_typeURI; - private final String m_typeContextPath; - private final ApplicationManager appManager; - - /** - * - * @param app - */ - ApplicationSpec(final CcmApplication app, - final ApplicationManager appManager) { - this.appManager = appManager; - - if (app == null) { - throw new NullPointerException("app"); - } - - m_id = app.getObjectId(); - m_instanceURI = app.getPrimaryUrl(); - if (app.getClass().isAnnotationPresent(ServletPath.class)) { - m_typeURI = app - .getClass() - .getAnnotation(ServletPath.class) - .value(); - } else { -// final ApplicationManager appManager = CDI.current().select( -// ApplicationManager.class).get(); -// final BeanManager beanManager = CDI.current().getBeanManager(); -// final Set> beans = beanManager.getBeans( -// ApplicationManager.class); -// final Iterator> iterator = beans.iterator(); -// final ApplicationManager appManager; -// if (iterator.hasNext()) { -// @SuppressWarnings("unchecked") -// final Bean bean -// = (Bean) iterator -// .next(); -// final CreationalContext ctx -// = beanManager -// .createCreationalContext(bean); -// -// appManager = (ApplicationManager) beanManager.getReference( -// bean, ApplicationManager.class, ctx); -// } else { -// LOGGER.error("Failed to find {}.", -// ApplicationManager.class.getName()); -// throw new IllegalArgumentException(String.format( -// "Failed to find %s", -// ApplicationManager.class.getName())); -// } - - final ApplicationType appType = appManager.getApplicationTypes() - .get(app.getApplicationType()); - final Class appServletClass = appType - .servlet(); - final WebServlet servletAnnotation = appServletClass - .getAnnotation(WebServlet.class); - if (servletAnnotation != null - && servletAnnotation.urlPatterns() != null - && servletAnnotation.urlPatterns().length > 0) { - if (servletAnnotation.urlPatterns()[0].endsWith("*")) { - m_typeURI = servletAnnotation - .urlPatterns()[0] - .substring(0, - servletAnnotation - .urlPatterns()[0] - .length() - 1); - } else { - m_typeURI = servletAnnotation.urlPatterns()[0]; - } - } else { - m_typeURI = appType.servletPath(); - } - } - - m_typeContextPath = ""; - - if (Assert.isEnabled()) { - Assert.exists(m_id, BigDecimal.class); - Assert.exists(m_instanceURI, String.class); - Assert.exists(m_typeURI, String.class); - Assert.exists(m_typeContextPath, String.class); - } - } - - /** - * - * @return - */ - long getAppID() { - return m_id; - } - - /** - * Provides the context the application is executing. Usually all CCM - * applications will now execute in the samme webapp context. The - * app.getContextPath() return "" in this case where an application is - * executing in no specific context but CCM's default. - * - * @return The context path of the application's url, "" in case of - * executing in the ROOT context. - */ - String getTypeContextPath() { - if (m_typeContextPath.equals("")) { - // app is running in CCM's default context, determine the - // actual one - return Web.getWebappContextPath(); - } else { - return m_typeContextPath; - } - } - - /** - * - * @param path - * - * @return - */ - String target(final String path) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Building the target path from the request " - + "path '{}' and the spec {}", - path, - this); - } - - final StringBuffer target = new StringBuffer(128); - - target.append(m_typeURI); - if (!m_typeURI.endsWith("/")) { - target.append("/"); - } - if (path.length() > (m_instanceURI.length() + 1)) { - target.append(path.substring(m_instanceURI.length())); - } - if (target.charAt(target.length() - 1) != '/' - && !path.contains(".")) { - target.append('/'); - } - target.append("?"); - target.append(BaseApplicationServlet.APPLICATION_ID_PARAMETER); - target.append("="); - target.append(m_id); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Returning target value '{}'", target); - } - - return target.toString(); - } - - /** - * - * @param obj - * - * @return - */ - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - ApplicationSpec other = (ApplicationSpec) obj; - return m_id == other.getAppID() && equal(m_instanceURI, - other.m_instanceURI) - && equal(m_typeURI, other.m_typeURI) && equal( - m_typeContextPath, other.m_typeContextPath); - - } - - /** - * - * @param s1 - * @param s2 - * - * @return - */ - private boolean equal(String s1, String s2) { - if (s1 == s2) { - return true; - } - if (s1 == null) { - return equal(s2, s1); - } - return s1.equals(s2); - } - - /** - * - * @return - */ - @Override - public int hashCode() { - return toString().hashCode(); - } - - /** - * - * @return - */ - @Override - public String toString() { - final String sep = ", "; - StringBuilder sb = new StringBuilder(); - sb.append("["); - sb.append("appID=").append(m_id).append(sep); - sb.append("instanceURI=").append(m_instanceURI).append(sep); - sb.append("typeURI=").append(m_typeURI).append(sep); - sb.append("typeContextPath=").append(m_typeContextPath); - return sb.append("]").toString(); - } - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/Debugger.java b/ccm-core/src/main/java/com/arsdigita/web/Debugger.java deleted file mode 100755 index 6b9e8af85..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/Debugger.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import com.arsdigita.kernel.KernelConfig; - -import java.util.ArrayList; -import java.util.Iterator; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * Debugger contains static methods for registering debuggers. - * Typically, debuggers are written to display the contents of - * internal CCM data structures e.g., the XML representation of a page - * prior to transformation. Subclass this class to add a particular - * type of debugger. - * - * @see TransformationDebugger - * - * @author Justin Ross - */ -public abstract class Debugger { - - private static final Logger LOGGER = LogManager.getLogger(Debugger.class); - - public static final String DEBUG_PARAMETER = "debug"; - public static final ThreadLocal s_debuggers = new DebuggerListLocal(); - - public static class DebugParameterListener implements ParameterListener { - public void run(HttpServletRequest sreq, ParameterMap map) { - if (KernelConfig.getConfig().isDebugEnabled()) { - final String value = sreq.getParameter(DEBUG_PARAMETER); - - if (value != null) { - map.setParameter(DEBUG_PARAMETER, value); - } - } - } - } - - public static final void addDebugger(Debugger debugger) { - ArrayList list = (ArrayList) s_debuggers.get(); - list.add(debugger); - } - - public static final String getDebugging(HttpServletRequest sreq) { - ArrayList list = (ArrayList) s_debuggers.get(); - Iterator iter = list.iterator(); - StringBuffer buffer = new StringBuffer(); - - while (iter.hasNext()) { - Debugger debug = (Debugger) iter.next(); - - if (debug.isRequested(sreq)) { - buffer.append(debug.debug()); - } - } - - return buffer.toString(); - } - - public abstract boolean isRequested(HttpServletRequest sreq); - - public abstract String debug(); - - private static class DebuggerListLocal extends InternalRequestLocal { - @Override - protected Object initialValue() { - if (KernelConfig.getConfig().isDebugEnabled()) { - return new ArrayList(); - } else { - return null; - } - } - - @Override - protected void clearValue() { - if (KernelConfig.getConfig().isDebugEnabled()) { - ArrayList list = (ArrayList) get(); - list.clear(); - } - } - } -} - diff --git a/ccm-core/src/main/java/com/arsdigita/web/DefaultApplicationFileResolver.java b/ccm-core/src/main/java/com/arsdigita/web/DefaultApplicationFileResolver.java deleted file mode 100644 index edfd5f8d6..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/DefaultApplicationFileResolver.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.web.CcmApplication; - -import javax.servlet.RequestDispatcher; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - - -/** - * The default implementation deals with templates files belonging to a specific - * application, e.g. cms. Because of the modular structure of CCM all file - * resources of an application are stored below that application's module - * directory. The directory structure itself is application specific. - */ -public class DefaultApplicationFileResolver implements ApplicationFileResolver { - - /** Internal logger instance to faciliate debugging. Enable logging output - * by editing /WEB-INF/conf/log4j.properties int hte runtime environment - * and set com.arsdigita.web.DefaultApplicationFileResolver=DEBUG by - * uncommenting or adding the line. */ - private static final Logger LOGGER = LogManager.getLogger - (DefaultApplicationFileResolver.class); - - /** List of alternative greeting files. Typical vales are index.jsp and - * index.html */ - private static final String[] WELCOME_FILES = new String[] { - "index.jsp", "index.html" - }; - - /** - * Determines from the passsed in request URL a suitable template file in - * the templates subdirectory. It returns an identified template wrapped - * in a RequestDispatcher enabling it to be executed (forwarded). The - * request will typically something like - *
    /[appCtx]/[webappInstance]/[webappInstInternalDir]/[template.jsp]
    - * For the content section "info" administration page installed in the - * ROOT context (i.e. [appCtx] is empty) in would be - *
    /info/admin/index.jsp
    - * The actual template is actual stored in the file system at - *
    /templates/ccm-cms/content-section/admin/index.jsp
    and the - * content-section to be administrated has to be passed in as parameter. - * - * @param templatePath - * @param sreq - * @param sresp - * @param app - * @return - */ - @Override - public RequestDispatcher resolve(String templatePath, - HttpServletRequest sreq, - HttpServletResponse sresp, - CcmApplication app) { - - String pathInfo = sreq.getPathInfo(); // effectively provides an url - if (LOGGER.isDebugEnabled()) { // with application part stripped - LOGGER.debug("Resolving resource for " + pathInfo); - } - - // determine the URL the application INSTANCE is really installed at - // will replace the application part stripped above - String node = app.getPrimaryUrl().toString(); - - do { - - // First check the complete path for the instance. Parameter - // templatePath denotes the template directory for the application - // TYPE. - String path = templatePath + node + pathInfo; - - // Just in case of a directory the list of welcome files have to be - // probed. - if (path.endsWith("/")) { - for (String welcomeFile : WELCOME_FILES) { //1.5 enhanced for-loop - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Trying welcome resource " + - path + welcomeFile); - } - RequestDispatcher rd = Web.findResourceDispatcher( - "" + path + welcomeFile); - if (rd != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Got dispatcher " + rd); - } - return rd; - } - } - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Trying resource " + path); - } - - RequestDispatcher rd = Web.findResourceDispatcher( - "" + path); - if (rd != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Got dispatcher " + rd); - } - return rd; - } - } - - // If nothing has been found at the complete path, probe variations - // of the node part by clipping element-wise - if ("".equals(node)) { - // if node is already empty we can't clip anything - fallthrough - node = null; - } else { - // clipp the last part of node retaining the first / in case - // of multiple parts or clip at all (in case of a single part) - int index = node.lastIndexOf("/", node.length() - 2); - node = node.substring(0, index); - } - } while (node != null); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("No dispatcher found"); - } - // fallthrough, no success - returning null - return null; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/DynamicHostProvider.java b/ccm-core/src/main/java/com/arsdigita/web/DynamicHostProvider.java deleted file mode 100644 index 10b6c7059..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/DynamicHostProvider.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2005 RuntimeCollective Ltd. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -public interface DynamicHostProvider { - - public String getName(); - - public int getPort(); -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/InternalRequestLocal.java b/ccm-core/src/main/java/com/arsdigita/web/InternalRequestLocal.java deleted file mode 100644 index 8c4ca70e5..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/InternalRequestLocal.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.Iterator; - -import javax.servlet.http.HttpServletRequest; - -/** - * A class that provides request-framed control over a thread-local - * value. With such control, it is possible to safely reuse - * thread-local data across requests. For example, the following - * InternalRequestLocal reuses a HashMap. - * - *
    - * class HashMapRequestLocal extends InternalRequestLocal { - * protected Object initialValue() { - * return new HashMap(); - * } - * - * // Does not override prepareValue(HttpServletRequest). - * // InternelRequestLocal's default implementation calls - * // clearValue() to prepare the value for the request. - * - * protected void clearValue() { - * ((HashMap) get()).clear(); - * } - * } - *
    - * - *

    initialValue() is called just once, when the value - * is first accessed. prepareValue(HttpServletRequest) - * is called at the start of every request serviced by {@link - * com.arsdigita.web.BaseServlet}. clearValue() is - * called at the end of every request handled by said servlet.

    - * - *

    The default implementation of clearValue() sets the - * value to null, and the default implementation of - * prepareValue(HttpServletRequest) calls - * clearValue(). As a result, an - * InternalRequestLocal as used in the following example - * is similar to using a request attribute.

    - * - *
    - * // This value is s_servletContext.set(null) at the start and end of - * // each request. - * static ThreadLocal s_servletContext = new InternalRequestLocal(); - *
    - * - *

    Be advised that errors in using this class can easily result in - * excess trash left on threads and, worse, big memory leaks. Please - * use caution.

    - * - * @see java.lang.ThreadLocal - * @see com.arsdigita.web.BaseServlet - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -class InternalRequestLocal extends ThreadLocal { - - private static final Logger LOGGER = - LogManager.getLogger(InternalRequestLocal.class); - - private static final ArrayList s_locals = new ArrayList(); - - /** - *

    Constructs a new InternalRequestLocal and registers it to be - * initialized and cleared on each request.

    - */ - public InternalRequestLocal() { - super(); - - s_locals.add(this); - } - - /** - * - * @param sreq - */ - static void prepareAll(final HttpServletRequest sreq) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Initializing all request-local objects; there are " + - s_locals.size()); - } - - final Iterator iter = s_locals.iterator(); - - while (iter.hasNext()) { - final InternalRequestLocal local = (InternalRequestLocal) iter.next(); - - local.prepareValue(sreq); - } - } - - /** - * - */ - static void clearAll() { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Clearing all request-local objects; there are " + - s_locals.size()); - } - - final Iterator iter = s_locals.iterator(); - - while (iter.hasNext()) { - final InternalRequestLocal local = (InternalRequestLocal) iter.next(); - - local.clearValue(); - } - } - - /** - *

    Called at the start of each request, this method returns the - * request-initialized value of the thread-local variable.

    - * - *

    By default this method calls clearValue().

    - * - * @param sreq the current servlet request - * @return the request-initialized value - */ - protected void prepareValue(HttpServletRequest sreq) { - clearValue(); - } - - /** - *

    Called at the end of each request, this method clears the - * thread-local value.

    - * - *

    By default this method calls set(null). Users - * of this class may override this method to better reuse the - * thread-local value.

    - */ - protected void clearValue() { - set(null); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/LoginSignal.java b/ccm-core/src/main/java/com/arsdigita/web/LoginSignal.java deleted file mode 100644 index c1f5998ad..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/LoginSignal.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import javax.servlet.http.HttpServletRequest; - -/** - *

    - * A RedirectSignal that sends the client to the login UI. - * LoginSignal encodes the origin URL so that - * ReturnSignal can return the client to its starting point.

    - * - * @see com.arsdigita.web.ReturnSignal - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class LoginSignal extends RedirectSignal { - - private static final long serialVersionUID = 6546166999255204832L; - - /** - * Constructs a signal to redirect the client to log in. This constructor - * tells the base servlet to abandon the current transaction. - * @param sreq - */ - public LoginSignal(final HttpServletRequest sreq) { - this(sreq, false); - } - - /** - * Constructs a signal to redirect the client to log in. - * - * @param sreq - * @param isCommitRequested - */ - public LoginSignal(final HttpServletRequest sreq, - final boolean isCommitRequested) { - super(URL.login(sreq), isCommitRequested); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/ParameterListener.java b/ccm-core/src/main/java/com/arsdigita/web/ParameterListener.java deleted file mode 100644 index ad85def8b..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/ParameterListener.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import javax.servlet.http.HttpServletRequest; - -/** - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public interface ParameterListener { - - void run(HttpServletRequest sreq, ParameterMap map); - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/ParameterMap.java b/ccm-core/src/main/java/com/arsdigita/web/ParameterMap.java deleted file mode 100644 index 543baffa2..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/ParameterMap.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import com.arsdigita.util.Assert; -import com.arsdigita.util.OrderedMap; -import com.arsdigita.util.UncheckedWrapperException; -import org.apache.commons.codec.net.URLCodec; -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.EncoderException; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class ParameterMap implements Cloneable { - - private static final Logger LOGGER = LogManager.getLogger(ParameterMap.class); - - private static ArrayList s_listeners = new ArrayList(); - - private OrderedMap m_params; - - public ParameterMap() { - m_params = new OrderedMap(); - } - - // Expects an *encoded* query string, just as - // request.getQueryString() returns. - private ParameterMap(final String query) { - this(); - - if (query != null) { - parseQueryString(query); - } - } - - public ParameterMap(final HttpServletRequest sreq) { - this(); - - final Enumeration keys = sreq.getParameterNames(); - - while (keys.hasMoreElements()) { - final String name = (String) keys.nextElement(); - final String[] values = (String[]) sreq.getParameterValues(name); - - setParameterValues(name, values); - } - } - - public ParameterMap(final Map params) { - this(); - - final Set keySet = params == null ? null : params.keySet(); - if (keySet != null) { - final Iterator keys = keySet.iterator(); - while (keys.hasNext()) { - final String name = (String)keys.next(); - final String[] values = (String[])params.get(name); - - setParameterValues(name, values); - } - } - } - - public static final ParameterMap fromString(final String query) { - Assert.exists(query, "String query"); - - if (query.startsWith("?")) { - return new ParameterMap(query.substring(1)); - } else { - return new ParameterMap(query); - } - } - - public static final void registerListener - (final ParameterListener listener) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Registering parameter listener " + listener); - } - - s_listeners.add(listener); - } - - public Object clone() throws CloneNotSupportedException { - final ParameterMap result = (ParameterMap) super.clone(); - - result.m_params = (OrderedMap) m_params.clone(); - - return result; - } - - private void parseQueryString(final String query) { - final int len = query.length(); - int start = 0; - - while (true) { - int end = -1; - - for (int i = start; i < len - 1; i++) { - if (query.charAt(i) == '&' || query.charAt(i) == ';') { - end = i; - - break; - } - } - - if (end == -1) { - if (len > start) { - try { - parseParameter(query, start, len); - } catch (DecoderException e) { - throw new UncheckedWrapperException(e); - } - } - - break; - } else { - try { - parseParameter(query, start, end); - } catch (DecoderException e) { - throw new UncheckedWrapperException(e); - } - start = end + 1; - } - } - } - - private void parseParameter(final String query, - final int start, - final int end) throws DecoderException { - final int sep = query.indexOf('=', start); - - if (Assert.isEnabled()) { - Assert.isTrue(start > -1); - Assert.isTrue(end > -1); - } - - if (sep > -1) { - URLCodec codec = new URLCodec(); - final String name = codec.decode(query.substring(start, sep)); - final String value = codec.decode - (query.substring(sep + 1, end)); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Parameter " + name + " = " + value); - } - - final String[] values = getParameterValues(name); - - if (values == null) { - setParameter(name, value); - } else { - final String[] newValues = new String[values.length + 1]; - - for (int i = 0; i < values.length; i++) { - newValues[i] = values[i]; - } - - newValues[values.length] = value; - - setParameterValues(name, newValues); - } - } - } - - private void validateName(final String name) { - Assert.exists(name, "String name"); - Assert.isTrue(!name.equals(""), - "The name must not be the empty string"); - Assert.isTrue(name.indexOf(" ") == -1, - "The name must not contain any spaces: '" + - name + "'"); - } - - public final void clear() { - m_params.clear(); - } - - public final String getParameter(final String name) { - final String[] values = (String[]) m_params.get(name); - - if (values == null) { - return null; - } else { - return values[0]; - } - } - - /** - * Sets the parameter name to value. If - * value is null, this method sets the value to the - * empty string. - * - * Use of this method assumes that the parameter has only one - * value; if you wish to give a parameter multiple values, use - * {@link #setParameterValues(String, String[])}. - * - * @param name The String name of the parameter - * @param value The String value of the parameter - * @see javax.servlet.ServletRequest#getParameter(String) - * @pre name != null && !name.trim().equals("") - */ - public final void setParameter(final String name, final String value) { - if (Assert.isEnabled()) { - validateName(name); - } - - if (value == null) { - m_params.put(name, new String[] {""}); - } else { - m_params.put(name, new String[] {value}); - } - } - - /** - * A convenience method that calls {@link #setParameter(String, - * String)} using value.toString(). If - * value is null, it is converted to the empty - * string. - * - * @param name The String name of the parameter - * @param value The Object value of the parameter - * @pre name != null && !name.trim().equals("") - */ - public final void setParameter(final String name, final Object value) { - if (value == null) { - setParameter(name, ""); - } else { - setParameter(name, value.toString()); - } - } - - public final String[] getParameterValues(final String name) { - return (String[]) m_params.get(name); - } - - public final void setParameterValues(final String name, - final String[] values) { - if (Assert.isEnabled()) { - validateName(name); - Assert.exists(values, "String[] values"); - Assert.isTrue(values.length > 0, - "The values array must have at least one value"); - } - - m_params.put(name, values); - } - - public final void clearParameter(final String name) { - if (Assert.isEnabled()) { - validateName(name); - } - - m_params.remove(name); - } - - public final Map getParameterMap() { - if (m_params.isEmpty()) { - return null; - } else { - return Collections.unmodifiableMap(m_params); - } - } - - public final String toString() { - if (m_params.isEmpty()) { - return ""; - } else { - return "?" + makeQueryString(); - } - } - - public final String getQueryString() { - return makeQueryString(); - } - - public final void runListeners(final HttpServletRequest sreq) { - final Iterator iter = s_listeners.iterator(); - - while (iter.hasNext()) { - final ParameterListener listener = (ParameterListener) iter.next(); - - listener.run(sreq, this); - } - } - - final String makeQueryString() { - final StringBuffer buffer = new StringBuffer(); - final Iterator iter = m_params.entrySet().iterator(); - URLCodec codec = new URLCodec(); - - while (iter.hasNext()) { - final Map.Entry entry = (Map.Entry) iter.next(); - final String key = (String) entry.getKey(); - final String[] values = (String[]) entry.getValue(); - - if (Assert.isEnabled()) { - Assert.isTrue(key.indexOf('%') == -1, - "The key '" + key + "' has already been " + - "encoded"); - } - - if (values != null) { - if (Assert.isEnabled()) { - Assert.isTrue(values.toString().indexOf('%') == -1, - "One of the values " + - Arrays.asList(values) + " has " + - "already been encoded"); - } - - for (int i = 0; i < values.length; i++) { - try { - buffer.append(codec.encode(key)); - } catch (EncoderException e) { - throw new UncheckedWrapperException(e); - } - buffer.append('='); - - final String value = values[i]; - - if (value != null) { - try { - buffer.append(codec.encode(value)); - } catch (EncoderException e) { - throw new UncheckedWrapperException(e); - } - } - - buffer.append('&'); - } - } - } - - int last = buffer.length() - 1; - - if (last > -1 && buffer.charAt(last) == '&') { - buffer.deleteCharAt(last); - } - - return buffer.toString(); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/RedirectSignal.java b/ccm-core/src/main/java/com/arsdigita/web/RedirectSignal.java deleted file mode 100644 index cba2ee04b..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/RedirectSignal.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import com.arsdigita.util.Assert; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - *

    - * A signal that requests to commit or abort the current transaction and to send - * a redirect to a new URL. BaseServlet traps this signal when it is thrown and - * finishes the transaction before it sends the redirect to the response. This - * way the client cannot see state inconsistent with work performed in the - * previous request.

    - * - *

    - * RedirectSignals are usually sent after doing work on behalf of - * the user:

    - * - *
    - * private final void saveUserSettings(final HttpServletRequest sreq) {
    - *     m_user.setGivenName("Gibbon");
    - *     m_user.setFamilyName("Homily");
    - *
    - *     m_user.save();
    - *
    - *     // The boolean argument true signifies that we want to commit
    - *     // the transaction.
    - *     throw new RedirectSignal(URL.here(sreq, "/user-detail.jsp"), true);
    - * }
    - * 
    - * - * @see com.arsdigita.web.BaseServlet - * @see com.arsdigita.web.LoginSignal - * @see com.arsdigita.web.ReturnSignal - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class RedirectSignal extends TransactionSignal { - - private static final long serialVersionUID = 102910405551194091L; - - /** - * Logger instance for debugging support. - */ - private static final Logger LOGGER= LogManager.getLogger(RedirectSignal.class); - - /** - * Destination URL where redirect to - */ - private final String m_url; - - /** - * Constructor - * - * @param url - * @param isCommitRequested - */ - public RedirectSignal(final String url, final boolean isCommitRequested) { - super(isCommitRequested); - - if (Assert.isEnabled()) { - Assert.exists(url, "String url"); - Assert.isTrue(url.startsWith("http") || url.startsWith("/"), - "The URL is relative and won't dispatch " - + "correctly under some servlet containers; " - + "the URL is '" + url + "'"); - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Request for redirect to URL '" + url + "'", - new Throwable()); - } - - m_url = url; - } - - /** - * Convenience Constructor for URL objects. - * - * @param url - * @param isCommitRequested - */ - public RedirectSignal(final URL url, final boolean isCommitRequested) { - this(url.toString(), isCommitRequested); - } - - public final String getDestinationURL() { - return m_url; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/ReturnSignal.java b/ccm-core/src/main/java/com/arsdigita/web/ReturnSignal.java deleted file mode 100644 index dec22cdb2..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/ReturnSignal.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import com.arsdigita.util.Assert; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.servlet.http.HttpServletRequest; - - -/** - *

    A signal that returns the client to a return URL encoded in the - * current URL, or if the return URL is not found, uses a fallback - * URL.

    - * - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class ReturnSignal extends RedirectSignal { - - private static final Logger LOGGER = LogManager.getLogger(ReturnSignal.class); - private static final long serialVersionUID = -2923355745770322780L; - - public ReturnSignal(final HttpServletRequest sreq) { - super(getReturnURL(sreq), true); - } - - public ReturnSignal(final HttpServletRequest sreq, final String fallback) { - super(getReturnURL(sreq, fallback), true); - } - - public ReturnSignal(final HttpServletRequest sreq, final URL fallback) { - this(sreq, fallback.toString()); - } - - private static String getReturnURL(final HttpServletRequest sreq) { - LOGGER.debug("Fetching the return URL to redirect to"); - - final String returnURL = sreq.getParameter("return_url"); - - Assert.exists(returnURL, "String returnURL"); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Redirecting to URL '" + returnURL + "'"); - } - - return returnURL; - } - - private static String getReturnURL(final HttpServletRequest sreq, - final String fallback) { - LOGGER.debug("Fetching the return URL to redirect to"); - - Assert.exists(fallback, "String fallback"); - - final String returnURL = sreq.getParameter("return_url"); - - if (returnURL == null || returnURL.equals("")) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Cannot find the return URL parameter; " + - "using the fallback URL '" + fallback + "'"); - } - - return fallback; - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Redirecting to the value in the return URL " + - "parameter, '" + returnURL + "'"); - } - - return returnURL; - } - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/TransactionSignal.java b/ccm-core/src/main/java/com/arsdigita/web/TransactionSignal.java deleted file mode 100644 index 67fa25337..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/TransactionSignal.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - *

    - * A signal to BaseServlet requesting that the current transaction - * be committed or aborted. As with all exceptions, throwing a - * TransactionSignal stops the execution of currently running - * code.

    - * - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -class TransactionSignal extends Error { - - private static final long serialVersionUID = -6081887476661858043L; - - private static final Logger LOGGER = LogManager - .getLogger(TransactionSignal.class); - - - private final boolean m_isCommitRequested; - - TransactionSignal(boolean isCommitRequested) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Constructing a transaction signal with " - + "isCommitRequested set " + isCommitRequested); - } - - m_isCommitRequested = isCommitRequested; - - } - - public final boolean isCommitRequested() { - return m_isCommitRequested; - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/TransformationDebugger.java b/ccm-core/src/main/java/com/arsdigita/web/TransformationDebugger.java deleted file mode 100755 index ae878e1c5..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/TransformationDebugger.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Document; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -/** - * - * A debugger that displays the original XML source of a document prior to - * transformation (only applies if using Bebop JSP), the generated XML document - * before transformation, and the XSL stylesheet files used for transformation. - * - * To view a page using this debugger, pass "debug=transform" in as a query - * variable. - * - * @see com.arsdigita.bebop.jsp.ShowPage - * - * @author Justin Ross - * <jross@redhat.com> - * @version $Id: TransformationDebugger.java 287 2005-02-22 00:29:02Z sskracic $ - */ -public class TransformationDebugger extends Debugger { - - private static final Logger LOGGER = LogManager.getLogger( - TransformationDebugger.class); - - // private Document m_original; - // private Document m_source; - private URL m_sheet; - private List m_dependents; - - /** - * The value passed in to the "debug" query string that activates this - * particular debugger. - */ - public static final String TRANSFORM_DEBUG_VALUE = "transform"; - - // Debuggers are per-request objects. - /** - * @pre sheet != null - * @pre dependents != null - * - */ - public TransformationDebugger(Document original, - Document source, - URL sheet, - List dependents) { - Assert.exists(sheet, URL.class); - Assert.exists(sheet, List.class); - // m_original = original; - // m_source = source; - m_sheet = sheet; - m_dependents = dependents; - } - - /** - * @see #TransformationDebugger(Document, Document, URL, List) - * - */ - public TransformationDebugger(URL sheet, List dependents) { - this(null, null, sheet, dependents); - } - - public boolean isRequested(HttpServletRequest sreq) { - String value = sreq.getParameter(DEBUG_PARAMETER); - - return value != null && value.indexOf(TRANSFORM_DEBUG_VALUE) != -1; - } - - public String debug() { - StringBuffer buffer = new StringBuffer(1024); - - buffer.append("

    The Stylesheet files

    "); - buffer.append("
      "); - - try { - Iterator sources = m_dependents.iterator(); - - File root = new File(DispatcherHelper.getRequestContext() - .getServletContext().getRealPath("/")); - String base = root.toURL().toExternalForm(); - - while (sources.hasNext()) { - String path = sources.next().toString(); - - if (path.startsWith(base)) { - path = path.substring(base.length()); - } - - buffer.append("
    • " + path - + "
    • "); - } - } catch (IOException ioe) { - throw new Error(ioe); - } - - buffer.append("
    "); - return buffer.toString(); - } - - protected String getStylesheetContents() { - try { - URLConnection con = m_sheet.openConnection(); - - StringBuffer buffer = new StringBuffer(); - - String contentType = con.getContentType(); - - String encoding = "ISO-8859-1"; - int offset = (contentType == null ? -1 : contentType.indexOf( - "charset=")); - if (offset != -1) { - encoding = contentType.substring(offset + 8).trim(); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Received content type " + contentType); - } - InputStream is = con.getInputStream(); - InputStreamReader isr = new InputStreamReader(is, encoding); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Process with character encoding " + isr - .getEncoding()); - } - BufferedReader input = new BufferedReader(isr); - - String line; - while ((line = input.readLine()) != null) { - buffer.append(line).append('\n'); - } - input.close(); - return buffer.toString(); - - } catch (MalformedURLException ex) { - ex.printStackTrace(); - return "Stylesheet contents unavailable: " + ex.getMessage(); - } catch (IOException ex) { - ex.printStackTrace(); - return "Stylesheet contents unavailable: " + ex.getMessage(); - } - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/URL.java b/ccm-core/src/main/java/com/arsdigita/web/URL.java deleted file mode 100644 index 54796fcc9..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/URL.java +++ /dev/null @@ -1,1028 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.util.Assert; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.util.servlet.HttpHost; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.web.CcmApplication; - -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import javax.enterprise.context.spi.CreationalContext; -import javax.enterprise.inject.spi.Bean; -import javax.enterprise.inject.spi.BeanManager; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.servlet.http.HttpServletRequest; - -/** - *

    - * URL models a future request according to the servlet worldview. Its principal - * uses are two: - * - *

      - *
    • To expose all the parts of a URL. To a servlet's way of thinking, these - * are the scheme, server name, server port, context path, servlet path, path - * info, and parameters.
    • - * - *
    • To generate URLs in a consistent and complete way in one place.
    • - *
    - *

    - * - *

    - * Each URL has the following accessors, here set next to an example URL - * instance, - * http://example.com:8080/ccmapp/forum/index.jsp?cat=2&cat=5:

    - * - *

    - * Atomic parts: - * - *

    - * getScheme() -> "http" - * getServerName() -> "example.com" - * getServerPort() -> 8080 - * getWebContextPath() -> "/ccmapp" - * getServletPath() -> "/forum" - * getPathInfo() -> "/index.jsp" - * getParameter("cat") -> "2" - * getParameterValues("cat") -> {"2", "5"} - *
    - * - *

    - * - *

    - * Composite parts: - * - *

    - * toString() -> "/ccmapp/forum/index.jsp?cat=2&cat=5" - * getURL() -> "http://example.com:8080/ccmapp/forum/index.jsp?cat=2&cat=5 - * getServerURI() -> "http://example.com:8080" // No trailing "/" - * getRequestURI() -> "/ccmapp/forum/index.jsp" - * getQueryString() -> "cat=2&cat=5" // No leading "?" - * getParameterMap() -> {cat={"2", "5"}} - *
    - * - *

    - * - *

    - * The toString() method returns a URL suitable for use in - * hyperlinks; since in the common case, the scheme, server name, and port are - * best left off, toString() omits them. The getURL() - * method returns a String URL which is fully qualified. Both - * getURL() and getServerURI() omit the port from - * their return values if the server port is the default, port 80.

    - * - *

    - * Creating URLs will usually be done via one of the static create methods:

    - * - *

    - * URL.root() creates a URL pointing at the server's root path, - * "/".

    - * - *

    - * URL.request(req, params) creates a URL reflecting the request - * the client made but using the passed-in parameters instead.

    - * - *

    - * URL.there(req, path, params) and its variants produce URLs that - * go through the CCM main dispatcher. The variant - * URL.there(req, app, pathInfo, params) dispatches to - * pathInfo under the specified application. The variant - * URL.here(req, pathInfo, params) dispatches to - * pathInfo under the current application.

    - * - *

    - * URL.excursion(req, path, params) produces URLs that go through - * the dispatcher to a destination but also encode and store the origin. This is - * used by LoginSignal and ReturnSignal to implement - * UI excursions.

    - * - *

    - * All static create methods taking an HttpServletRequest (1) - * preserve the request's scheme, server name, and port and (2) run parameter - * listeners if the URL's parameter map is not null. - *

    - * - *

    - * Those methods not taking an HttpServletRequest use the scheme, - * server name, and port defined in LegacyWebConfig.

    - * - *

    - * All static create methods taking a ParameterMap take null to - * mean no query string at all. URLs defined this way will have no query string - * and no "?".

    - * - *

    - * Those methods not taking a ParameterMap argument implicitly - * create an empty parameter map. Note that this is different from creating a - * URL with a null parameter map, which produces a URL with no query string.

    - * - * @see com.arsdigita.web.ParameterMap - * @see com.arsdigita.web.DispatcherServlet - * @see com.arsdigita.web.LoginSignal - * @see com.arsdigita.web.ReturnSignal - * @see com.arsdigita.web.LegacyWebConfig - * @see com.arsdigita.web.Application - * @author Justin Ross - * <jross@redhat.com> - * @version $Id$ - */ -public class URL { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int hte runtime environment and - * set com.arsdigita.web.URL=DEBUG by uncommenting or adding the line. - */ - private static final Logger LOGGER = LogManager.getLogger(URL.class); - - public static final String THEMES_DIR = "/themes"; - - /** - * Base direcotry for template files provided by packages. Each package has - * to place files into a subdirectory with its name - */ - public static final String TEMPLATE_DIR = "/templates"; - - /** - * The standard location for servlets. - */ - public static final String SERVLET_DIR = "/templates/servlet"; - - public static final String INTERNAL_THEME_DIR = THEMES_DIR + "/heirloom"; - - private static final ThreadLocal s_empty = new EmptyParameterMap(); - private StringBuffer m_url; - private ParameterMap m_params; - private int m_schemeEnd = -1; - private int m_serverNameEnd = -1; - private int m_serverPortEnd = -1; - private int m_contextPathEnd = -1; - private int m_servletPathEnd = -1; - private int m_dispatcherPrefixEnd = -1; - - private void init(final String scheme, - final String serverName, - final int serverPort, - final String contextPath, - final String servletPath, - final String dispatcherPrefix, - final String pathInfo, - final ParameterMap params) { - m_url = new StringBuffer(96); - m_params = params; - - if (Assert.isEnabled()) { - Assert.exists(scheme, "String scheme"); - Assert.isTrue(!scheme.equals(""), - "The scheme cannot be an empty string"); - - Assert.exists(serverName, "String serverName"); - Assert.isTrue(serverPort > 0, - "The serverPort must be greater than 0; " + "I got " - + serverPort); - - Assert.exists(contextPath, "String contextPath"); - - if (contextPath.startsWith("/")) { - Assert.isTrue(!contextPath.endsWith("/"), - "A contextPath starting with '/' must not end in '/'; " - + "I got '" + contextPath + "'"); - } - - Assert.exists(servletPath, "String servletPath"); - - if (pathInfo != null) { - Assert.isTrue(pathInfo.startsWith("/"), - "I expected a pathInfo starting with '/' " - + "and got '" + pathInfo + "' instead"); - } - } - - m_url.append(scheme); - m_schemeEnd = m_url.length(); - - m_url.append("://"); - - m_url.append(serverName); - m_serverNameEnd = m_url.length(); - - if (serverPort != 80) { - m_url.append(':'); - m_url.append(serverPort); - } - - m_serverPortEnd = m_url.length(); - - m_url.append(contextPath); - m_contextPathEnd = m_url.length(); - - if (dispatcherPrefix != null) { - m_url.append(dispatcherPrefix); - } - - m_dispatcherPrefixEnd = m_url.length(); - - m_url.append(servletPath); - m_servletPathEnd = m_url.length(); - - if (pathInfo != null) { - m_url.append(pathInfo); - } - - if (Assert.isEnabled()) { - Assert.isTrue(m_schemeEnd > -1); - Assert.isTrue(m_serverNameEnd > -1); - Assert.isTrue(m_serverPortEnd > -1); - Assert.isTrue(m_contextPathEnd > -1); - Assert.isTrue(m_servletPathEnd > -1); - } - } - - /** - *

    - * Assembles a fully qualified URL from its fundamental pieces. The contract - * of URL dictates that once params is passed in to this - * constructor, no parameters should be added or removed. This is to make - * URL in practice a read-only object.

    - * - * @param scheme "http", for example; see {@link - * javax.servlet.ServletRequest#getScheme()} - * - * @param serverName a valid domain name, for example - * "ccm.redhat.com"; see {@link - * javax.servlet.ServletRequest#getServerName()} - * - * @param serverPort 8080, for instance; see {@link - * javax.servlet.ServletRequest#getServerPort()} - * - * @param contextPath the path to your web app; empty string indicates the - * default context; any other values for contextPath must - * start with "/" but not end in - * "/"; contextPath cannot be null; see {@link - * javax.servlet.http.HttpServletRequest#getContextPath()} - * - * @param servletPath the path to your servlet; empty string and values - * starting with "/" are valid, but null is - * not; see {@link - * javax.servlet.http.HttpServletRequest#getServletPath()} - * - * @param pathInfo the path data remaining after the servlet path but - * before the query string; pathInfo may be null; see {@link - * javax.servlet.http.HttpServletRequest#getPathInfo()} - * - * @param params a ParameterMap representing a set of - * query parameters - * - * @return a fully specified URL - */ - public URL(final String scheme, - final String serverName, - final int serverPort, - final String contextPath, - final String servletPath, - final String pathInfo, - final ParameterMap params) { - HttpServletRequest req = Web.getRequest(); - String dispatcherPrefix = req == null ? null : DispatcherHelper. - getDispatcherPrefix(req); - - init(scheme, - serverName, - serverPort, - contextPath, - servletPath, - dispatcherPrefix, - pathInfo, - params); - } - - /** - * (private) Constructor. - * - * @param sreq - * @param params - */ - private URL(final HttpServletRequest sreq, - final ParameterMap params) { - final String dispatcherPrefix = DispatcherHelper.getDispatcherPrefix( - sreq); - final HttpHost host = new HttpHost(sreq); - - init(sreq.getScheme(), - host.getName(), - host.getPort(), - sreq.getContextPath(), - sreq.getServletPath(), - dispatcherPrefix, - sreq.getPathInfo(), - params); - } - - /** - *

    - * Constructor, produce a URL representation of the given request.

    - * - * @param sreq an HttpServletRequest from which to copy - * - * @return a URL whose contents correspond to the request used to create it - */ - public URL(final HttpServletRequest sreq) { - this(sreq, new ParameterMap(sreq)); - } - - /** - *

    - * Produces a short description of a URL suitable for debugging.

    - * - * @return a debugging representation of this URL - */ - public final String toDebugString() { - return super.toString() + " " + "[" + getScheme() + "," - + getServerName() + "," + getServerPort() + "," - + getContextPath() + "," + getServletPath() + "," - + getDispatcherPrefix() + "," + getPathInfo() + "," - + getQueryString() + "]"; - } - - /** - * Returns a String representation of the URL, fully qualified. - * The port is omitted if it is the standard HTTP port, 80. - * - * @return a String URL, with all of its parts - */ - public final String getURL() { - if (m_params == null) { - return m_url.toString(); - } else { - return m_url.toString() + m_params; - } - } - - /** - *

    - * Returns the scheme (sometimes called the protocol) of the URL. Examples - * are "http" and "https".

    - * - * @see javax.servlet.ServletRequest#getScheme() - * @return a String representing the URL's scheme - */ - public final String getScheme() { - return m_url.substring(0, m_schemeEnd); - } - - /** - *

    - * Returns the domain name part of the URL. For instance, - * "ccm.redhat.com".

    - * - * @see javax.servlet.ServletRequest#getServerName() - * @return a String representing the URL's server name - */ - public final String getServerName() { - return m_url.substring(m_schemeEnd + 3, m_serverNameEnd); - } - - /** - *

    - * Returns the port number of the URL. 8080, for example.

    - * - * @see javax.servlet.ServletRequest#getServerPort() - * @return an int for the URL's port number - */ - public final int getServerPort() { - final String port = m_url.substring(m_serverNameEnd, m_serverPortEnd); - - if (port.equals("")) { - return 80; - } else { - return Integer.parseInt(port.substring(1)); - } - } - - /** - *

    - * Returns the server half of the URL, as opposed to the "file" half. For - * example, "http://ccm.redhat.com:8080". Note that there is no trailing - * slash; any characters following the server port are considered part of - * the {@link #getRequestURI() request - * URI}.

    - * - *

    - * This method has no equivalent in the Servlet API, but it is similar in - * spirit to {@link - * javax.servlet.http.HttpServletRequest#getRequestURI()}.

    - * - *

    - * It is defined to return - * - *

    getScheme() + "://" + getServerName() + ":" - * + getServerPort()
    - * - * or, if the server port is 80, - * - *
    getScheme() + "://" + - * getServerName()
    - * - *

    - * - * @see #getRequestURI() - * @return a String comprised of the scheme, server name, and - * server port plus connecting bits - */ - public final String getServerURI() { - return m_url.substring(0, m_serverPortEnd); - } - - /** - *

    - * Returns the context path of the URL. The value cannot be null, and values - * starting with "/" do not end in "/"; empty - * string is a valid return value that stands for the default web app. - * Example values are "" and "/ccm-app".

    - * - * @see javax.servlet.http.HttpServletRequest#getContextPath() - * @return a String path to a web app context - */ - public final String getContextPath() { - return m_url.substring(m_serverPortEnd, m_contextPathEnd); - } - - /** - *

    - * Experimental

    - *

    - * Returns the dispatcher prefix of this request as set by the - * InternalPrefixerServlet - */ - public final String getDispatcherPrefix() { - if (m_dispatcherPrefixEnd < m_servletPathEnd) { - //there is no dispatcher prefix - return ""; - } else { - return m_url.substring(m_servletPathEnd, m_dispatcherPrefixEnd); - } - } - - /** - *

    - * Returns the servlet path of the URL. The value cannot be null.

    - * - * @see javax.servlet.http.HttpServletRequest#getServletPath() - * @return a String path to a servlet - */ - public final String getServletPath() { - return m_url.substring(m_dispatcherPrefixEnd, m_servletPathEnd); - } - - /** - *

    - * Returns the servlet-local path data of the URL. The value may be null. If - * it is not null, the value begins with a "/". Examples are - * null, "/", and "/remove.jsp".

    - * - * @see javax.servlet.http.HttpServletRequest#getPathInfo() - * @return a String of path data addressed to a servlet - */ - public final String getPathInfo() { - final String pathInfo = m_url.substring(m_servletPathEnd); - - if (pathInfo.equals("")) { - return null; - } else { - return pathInfo; - } - } - - /** - *

    - * Returns the "file" part of the URL, in contrast to the - * {@link #getServerURI() server part}. The value cannot be null and always - * starts with a "/". For example, "/ccm/forum/thread.jsp".

    - * - *

    - * This method is defined to return the equivalent of * getWebContextPath() + getServletPath() + - * getPathInfo().

    - * - * @see javax.servlet.http.HttpServletRequest#getRequestURI() - * @return a String comprised of the context path, servlet - * path, and path info - */ - public final String getRequestURI() { - return m_url.substring(m_serverPortEnd); - } - - /** - *

    - * Returns the query string of the URL. If the URL was constructed with a - * null ParameterMap, this method returns null. If the URL was - * constructed with an empty ParameterMap, this method returns - * the empty string. Example values are null, "", - * and "ticket-id=56&user-id=24".

    - * - * @see javax.servlet.http.HttpServletRequest#getQueryString() - * @return a String representing the query parameters of the - * URL - */ - public final String getQueryString() { - if (m_params == null) { - return null; - } else { - return m_params.getQueryString(); - } - } - - /** - *

    - * Returns the value of one query parameter. If the URL was constructed with - * a null ParameterMap, this method returns null. If the - * parameter requested has multiple values, this method will only return the - * first; use {@link - * #getParameterValues(String)} to get all of the values.

    - * - * @see javax.servlet.http.HttpServletRequest#getParameter(String) - * @param name the name of the parameter to fetch - * - * @return the String value of the parameter - */ - public final String getParameter(final String name) { - if (m_params == null) { - return null; - } else { - return m_params.getParameter(name); - } - } - - /** - *

    - * Returns the values for a parameter. If the URL was constructed with a - * null ParameterMap, this method returns null.

    - * - * @see javax.servlet.http.HttpServletRequest#getParameterValues(String) - * @param name the name of the parameter to get - * - * @return a String[] of values for the parameter - */ - public final String[] getParameterValues(final String name) { - if (m_params == null) { - return null; - } else { - return m_params.getParameterValues(name); - } - } - - /** - *

    - * Returns an immutable map of the query parameters. The map's keys are - * Strings and the map's values are String[]s. If - * the URL was constructed with a null ParameterMap, this - * method returns null.

    - * - * @see javax.servlet.http.HttpServletRequest#getParameterMap() - * @return a Map of the URL's query parameters - */ - public final Map getParameterMap() { - if (m_params == null) { - return null; - } else { - return m_params.getParameterMap(); - } - } - - /** - *

    - * Creates a URL to the site's root path. For example, - * http://somewhere.net/.

    - * - * @return a URL to your server's root path - */ - public static final URL root() { - final WebConfig config = Web.getConfig(); - - URL url = new URL(config.getDefaultScheme(), - config.getServerName(), - config.getServerPort(), - "", - "/", - null, - null); - - return url; - } - - /** - *

    - * Creates a URL using the elements of the user's original request but with - * the given set of parameters instead of the original ones.

    - * - * @param sreq the servlet request - * @param params a ParameterMap of params to replace those of - * the request - * - * @return a URL representing the original request except for - * its parameters - */ - public static final URL request(final HttpServletRequest sreq, - final ParameterMap params) { - if (params != null) { - params.runListeners(sreq); - } - - final URL url = Web.getWebContext().getRequestURL(); - - if (url == null) { - // If the URL is being generated outside of a WebContext, - // use the request to fill out the URL. - - return new URL(sreq, params); - } else { - return new URL(url.getScheme(), - url.getServerName(), - url.getServerPort(), - url.getContextPath(), - url.getServletPath(), - url.getPathInfo(), - params); - } - } - - /** - *

    - * Creates a URL to path under the CCM main dispatcher and with - * the given parameters. A null ParameterMap indicates that the - * URL has no query string at all. If the parameter map is not null, its - * parameter listeners are run and may further edit the parameter map.

    - * - * @see com.arsdigita.web.DispatcherServlet - * @param sreq the servlet request - * @param path a String path to which to dispatch - * @param params a ParameterMap of parameters to use; this - * value may be null - * - * @return a URL with a path to dispatch to - */ - public static final URL there(final HttpServletRequest sreq, - final String path, - final ParameterMap params) { - final BeanManager beanManager; - try { - final InitialContext context = new InitialContext(); - beanManager = (BeanManager) context.lookup( - "java:comp/BeanManager"); - - } catch (NamingException ex) { - throw new UncheckedWrapperException(ex); - } - - final Set> beans = beanManager.getBeans( - ConfigurationManager.class); - final Iterator> iterator = beans.iterator(); - final ConfigurationManager confManager; - if (iterator.hasNext()) { - @SuppressWarnings("unchecked") - final Bean bean - = (Bean) iterator - .next(); - final CreationalContext ctx = beanManager - .createCreationalContext(bean); - confManager = (ConfigurationManager) beanManager.getReference( - bean, ConfigurationManager.class, ctx); - } else { - throw new IllegalStateException("No configuration manager"); - } - -// final ConfigurationManager confManager = CDI.current().select( -// ConfigurationManager.class).get(); - final WebConfig config = confManager.findConfiguration(WebConfig.class); -// final WebConfig config = Web.getConfig(); - - Assert.exists(sreq, "HttpServletRequest sreq"); - Assert.exists(config, "WebConfig config"); - - if (params != null) { - params.runListeners(sreq); - } - - final HttpHost host = new HttpHost(sreq); - - return new URL(sreq.getScheme(), - host.getName(), - host.getPort(), - CCMDispatcherServlet.getContextPath(), - config.getDispatcherServletPath(), - path, - params); - } - - /** - * Method similar to there(), but which checks the - * waf.web.dynamic_host_provider parameter to generate the site name and - * port dynamically. - * - * @see com.arsdigita.web.DispatcherServlet - * @param sreq the servlet request - * @param path a String path to which to dispatch - * @param params a ParameterMap of parameters to use; this - * value may be null - * - * @return a URL with a path to dispatch to - */ - public static final URL dynamicHostThere(final HttpServletRequest sreq, - final String path, - final ParameterMap params) { - final WebConfig config = Web.getConfig(); - DynamicHostProvider provider = Web.getConfig().getDynamicHostProvider(); - if (provider == null) { - return there(sreq, path, params); - } - - Assert.exists(sreq, "HttpServletRequest sreq"); - Assert.exists(config, "WebConfig config"); - - if (params != null) { - params.runListeners(sreq); - } - - final HttpHost host = new HttpHost(sreq); - - return new URL(sreq.getScheme(), - provider.getName(), - provider.getPort(), - CCMDispatcherServlet.getContextPath(), - config.getDispatcherServletPath(), - path, - params); - } - - /** - *

    - * Creates a URL with no local parameters to path under the CCM - * main dispatcher. This method implicitly creates an empty parameter map - * (not a null one); this empty map may be altered by parameter listeners, - * for instance to include global parameters.

    - * - * @param sreq the servlet request - * @param path a String path to dispatch to - * - * @return a URL to a path under the dispatcher and with an - * empty parameter map - */ - public static final URL there(final HttpServletRequest sreq, - final String path) { - final WebConfig config = Web.getConfig(); - - Assert.exists(sreq, "HttpServletRequest sreq"); - Assert.exists(config, "WebConfig config"); - - final HttpHost host = new HttpHost(sreq); - - return new URL(sreq.getScheme(), - host.getName(), - host.getPort(), - CCMDispatcherServlet.getContextPath(), - config.getDispatcherServletPath(), - path, - (ParameterMap) s_empty.get()); - } - - /** - *

    - * Creates a URL to pathInfo under the specified application - * and using the given parameters. The parmeter map argument may be null, - * indicating that the URL has no query string.

    - * - * @param sreq the servlet request - * @param app the CcmApplication to dispatch to - * @param pathInfo a String of extra path info for the - * application - * @param params a ParameterMap of parameters to use - * - * @return a URL to an application with a particular - * pathInfo - */ - public static final URL there(final HttpServletRequest sreq, - final CcmApplication app, - final String pathInfo, - final ParameterMap params) { - if (Assert.isEnabled() && pathInfo != null) { - Assert.isTrue(pathInfo.startsWith("/"), - "pathInfo, if not null, must " + "start with a slash"); - } - - if (pathInfo == null) { - return URL.there(sreq, app.getPrimaryUrl().toString(), params); - } else { - return URL.there(sreq, app.getPrimaryUrl().toString() + pathInfo, - params); - } - } - - /** - *

    - * Creates a URL with no local parameters to pathInfo under the - * specified application. - * - * @param sreq the servlet request - * @param app the CcmApplication to dispatch to - * @param pathInfo a String of extra path info for the - * application - * - * @return a URL to an application with a particular - * pathInfo - */ - public static final URL there(final HttpServletRequest sreq, - final CcmApplication app, - final String pathInfo) { - if (Assert.isEnabled() && pathInfo != null) { - Assert.isTrue(pathInfo.startsWith("/"), - "pathInfo, if not null, must " + "start with a slash"); - } - - if (pathInfo == null) { - return URL.there(sreq, app.getPrimaryUrl().toString()); - } else { - return URL.there(sreq, app.getPrimaryUrl().toString() + pathInfo); - } - } - - /** - *

    - * Creates a URL with local parameters.

    - * - *

    - * This function should not be used unless you really don't have an - * HttpServletRequest object as it will ignore any Host header - * given by the client.

    - * - * @param path - * @param params - * - * @return - */ - public static final URL there(final String path, - final ParameterMap params) { - final WebConfig config = Web.getConfig(); - - return new URL(config.getDefaultScheme(), - config.getServerName(), - config.getServerPort(), - "", - config.getDispatcherServletPath(), - path, - params); - } - - /** - *

    - * Create a URL with local parameters to pathInfo under the - * specified application.

    - * - *

    - * This function should not be used unless you really don't have an - * HttpServletRequest object as it will ignore any Host header - * given by the client.

    - */ - public static final URL there(final CcmApplication app, - final String pathInfo, - final ParameterMap params) { - return URL.there(app.getPrimaryUrl() + pathInfo, params); - } - - public static final URL here(final HttpServletRequest sreq, - final String pathInfo, - final ParameterMap params) { - final CcmApplication app = Web.getWebContext().getApplication(); - - Assert.exists(app, "Application app"); - - return URL.there(sreq, app, pathInfo, params); - } - - public static final URL here(final HttpServletRequest sreq, - final String pathInfo) { - final CcmApplication app = Web.getWebContext().getApplication(); - - Assert.exists(app, "Application app"); - - return URL.there(sreq, app, pathInfo); - } - - public static URL excursion(final HttpServletRequest sreq, - final String path, - final ParameterMap params) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Creating excursion URL to " + path); - } - - final URL url = URL.there(sreq, path, params); - - params.setParameter("return_url", Web.getWebContext().getRequestURL()); - - return url; - } - - public static URL excursion(final HttpServletRequest sreq, - final String path) { - return URL.excursion(sreq, path, new ParameterMap()); - } - - static URL login(final HttpServletRequest sreq) { - //Replace register eventuelly... - return URL.excursion(sreq, - "/register/", - (ParameterMap) s_empty.get()); - } - - final String getReturnURL() { - return getParameter("return_url"); - } - - /** - * Returns a String representation of the URL suitable for use - * as a hyperlink. The scheme, server name, and port are omitted. - * - * @return a String URL - */ - @Override - public final String toString() { - if (m_params == null) { - return m_url.substring(m_serverPortEnd); - } else { - String str = m_url.substring(m_serverPortEnd); - if (str.contains("?")) { - return String.format("%s%s", m_url.substring(m_serverPortEnd), - m_params.toString().replace('?', '&')); - } else { - return m_url.substring(m_serverPortEnd) + m_params; - } - } - } - - /** - * - * @return - */ - public static String getDispatcherPath() { - final WebConfig config = Web.getConfig(); - final HttpServletRequest req = Web.getRequest(); - - final String context = CCMDispatcherServlet.getContextPath(); - final String servlet = config.getDispatcherServletPath(); - - if (req == null) { - return context + servlet; - } else { - final String prefix = DispatcherHelper.getDispatcherPrefix(req); - - if (prefix == null) { - return context + servlet; - } else { - return context + prefix + servlet; - } - } - } - - private static class EmptyParameterMap extends InternalRequestLocal { - - @Override - protected final Object initialValue() { - return new ParameterMap(); - } - - @Override - protected final void prepareValue(final HttpServletRequest sreq) { - ((ParameterMap) get()).runListeners(sreq); - } - - @Override - protected final void clearValue() { - ((ParameterMap) get()).clear(); - } - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/Web.java b/ccm-core/src/main/java/com/arsdigita/web/Web.java deleted file mode 100644 index bd3d3d589..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/Web.java +++ /dev/null @@ -1,760 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.arsdigita.web; - -import com.arsdigita.util.Assert; -import com.arsdigita.util.StringUtils; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - - -/** - * An entry point for functions of the web package. - * - * @author Rafael Schloming <rhs@mit.edu> - * @author Justin Ross <jross@redhat.com> - * @version $Id$ - */ -public class Web { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int the runtime environment and - * set com.arsdigita.web.Web=DEBUG by uncommenting or adding the line. - */ - private static final Logger LOGGER = LogManager.getLogger(Web.class); - -// private static final WebConfig s_config = WebConfig.getConfig(); - private static final ThreadLocal s_request = new InternalRequestLocal(); - private static final ThreadLocal s_servletContext - = new InternalRequestLocal(); - private static final ThreadLocal s_userContext = new InternalRequestLocal(); - private static ThreadLocal s_context; - - static final WebContext s_initialContext = new WebContext(); - - /** - * Internal service property to temporarly save the ServletContext as - * determined by findResource(resource) method to make it available to those - * methods of this class which use findResource to lookup a resource as a - * base for determining additional information, e.g. provide a dispatcher - * (findResourceDispatcher) - */ - static private ServletContext s_urlContext; - - /** - * String containing the webapp context path portion of the WEB application - * where this CCM instance is executed. (I.e. where the WEB-INF directory is - * located in the servlet container webapps directory). - */ - private static String s_contextPath; - - /** - * Static Initializer block. - */ - static void init(final HttpServletRequest sreq, - final ServletContext sc) { - - Assert.exists(sreq, HttpServletRequest.class); - Assert.exists(sc, ServletContext.class); - - s_request.set(sreq); - s_servletContext.set(sc); - s_contextPath = CCMDispatcherServlet.getContextPath(); - } - - /** - * Provide the configuration record for code in the web package. - * - * @return A WebConfig configuration record; it cannot be null - */ - public static WebConfig getConfig() { -// return s_config; - return WebConfig.getConfig(); - } - - /** - * Gets the web context object from the current thread. - * - * @return A WebContext object; it cannot be null Note: Rename - * from getContext() - */ - public static WebContext getWebContext() { - if (s_context == null) { - s_context = new WebContextLocal(); - } - return (WebContext) s_context.get(); - } - - /** - * Gets the servlet request object of the current thread. - * - * @return The current HttpServletRequest; it can be null - */ - public static HttpServletRequest getRequest() { - return (HttpServletRequest) s_request.get(); - } - - /** - * Gets the servlet context of the current thread. - * - * @return The current ServletContext; it can be null - */ - public static ServletContext getServletContext() { - return (ServletContext) s_servletContext.get(); - } - - /** - * Gets the webapp context path portion of the WEB application where this - * CCM instance is executed. (I.e. where the WEB-INF directory is located in - * the servlet container webapps directory, known as ServletContext in the - * Servlet API) - * - * @return web context path portion as a String, may be used to construct a - * URL (NOT the RealPath!). The ROOT context returns an empty - * String(""). - */ - public static String getWebappContextPath() { - return (String) s_contextPath; - } - - /** - * Sets the webapp context path portion of the WEB application where this - * CCM instance is executed. (I.e. where the WEB-INF directory is located in - * the servlet container webapps directory, known as ServletContext in the - * Servlet API) Meant to be executed by CCMDispatcherServlet only. - * - * @param contextPath - */ - protected static void setWebappContextPath(String contextPath) { - s_contextPath = contextPath; - } - - /** - * Processes an URL String trying to identify a corresponding recource which - * is mapped to the given path String. The method ensures that the resource - * definitely exists (using the URL returned) or definitely not (returning - * null). - * - * The resourcePath may be stored at various sources (file system, jar file, - * database, etc) depending on the implementation of the URL handlers and - * URLConnection objects. - * - * - * @param resourcePath Path to the resource as String. It may include the - * web context in its first part or may be relative to - * the current webapp document root (i.e. its context). - * Additionally, the web application component (if any) - * may be a comma separate list of webapps to search for - * the rest of the path String. So, if the - * 'resourcePath' is:
    -     *                 /myproj,ccm-cms/themes/heirloom/admin/index.xsl
    -     *                     
    then this method will look for resourcePaths at - *
    -     *                 /myproj/themes/heirloom/admin/index.xsl
    -     *                 /ccm-cms/themes/heirloom/admin/index.xsl
    -     * 
    - * - * @return the URL for the resourcePath, or null if no resource is mapped to - * the resourcePath String - */ - public static URL findResource(String resourcePath) { - - if (resourcePath == null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Parameter resource is null. Giving up."); - } - return null; - } - // ensure a leading "/" - if (!resourcePath.startsWith("/")) { - resourcePath = "/" + resourcePath; - } - if (resourcePath.length() < 2) { - if (LOGGER.isDebugEnabled()) { - LOGGER - .debug("Resource spec is too short: >" + resourcePath + "<"); - } - return null; - } - - // determine my own webapp context - ServletContext myctx = getServletContext(); - - // Check for old style resourcePath format including a comma seoarated list - // of webapps - if (resourcePath.indexOf(",") <= 0) { - // no comma separated list found, process as normal - - // just try to find the resourcePath in my own context - try { - URL url = myctx.getResource(resourcePath); - if (url != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Got URL " + url + " for " + resourcePath); - } - return url; // Return adjusted resourcePath url - } - } catch (MalformedURLException ex) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Cannot get resource for " + resourcePath); - } - // Try the first part of resourcePath as a webapp context path and - // check far a resourcePath there - int offset = resourcePath.indexOf("/", 1); // search for second "/" - String testPath = resourcePath.substring(1, offset); - String path = resourcePath.substring(offset); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Try to find a context at " + testPath); - } - // Try to achieve a context - ServletContext ctx = myctx.getContext(testPath); - if (LOGGER.isDebugEnabled()) { - LOGGER - .debug("Servlet context for " + testPath + " is " + ctx); - } - if (ctx != null) { - // successs, try to finf a resourcePath for the remaining - // string as path - try { - URL url = ctx.getResource(path); - if (url != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Got URL " + url + " for " + path); - } - return url; // Return adjusted resourcePath url - } else if (LOGGER.isDebugEnabled()) { - LOGGER.debug("No URL present for " + path); - } - } catch (MalformedURLException exc) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("cannot get resource for " + path); - } - } - } - } - - return null; // fall through - - } else { - // comma separated list found - // processing old style, comma separated webapp list - int offset = resourcePath.indexOf("/", 1); // search for second "/" - String webappList = resourcePath.substring(1, offset); - String path = resourcePath.substring(offset); - - String[] webapps = StringUtils.split(webappList, ','); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Web app list " + webappList + " path " + path); - } - - for (int i = (webapps.length - 1); i >= 0; i--) { - - String ctxPath = webapps[i]; - if (!ctxPath.startsWith("/")) { - ctxPath = "/" + ctxPath; - } - // No trailing slash allowed by servlet API! - // if (!ctxPath.endsWith("/")) { - // ctxPath = ctxPath + "/"; - // } - - ServletContext ctx = myctx.getContext(ctxPath); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Servlet context for " + ctxPath + " is " + ctx); - } - if (ctx != null) { - try { - URL url = ctx.getResource(path); - if (url != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Got URL " + url + " for " + path); - } - return url; // Return adjusted resourcePath url - } else if (LOGGER.isDebugEnabled()) { - LOGGER.debug("No URL present for " + path); - } - } catch (MalformedURLException ex) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("cannot get resource for " + path); - } - } - } - - } - - return null; // fall through when nothing found - } // end processing old style comma separated list - } - - /** - * Follows the same rules as findResource(String[], String), but instead - * returns an input stream for reading the resource - * - * @param resource Path to the resource as String. It may include the web - * context in its first part or may be relative to the - * current webapp document root (i.e. its context). - * Additionally, it the web application component (if any) - * may be a comma separate list of webapps to search for the - * rest of the path String. So, if the 'resource' is:
    -     *                 /myproj,ccm-cms/themes/heirloom/admin/index.xsl
    -     *                 
    then this method will look for resources at - *
    -     *                 /myproj/themes/heirloom/admin/index.xsl
    -     *                 /ccm-cms/themes/heirloom/admin/index.xsl
    -     * 
    - * - * @return the input stream for the resource, or null - * - * @throws java.io.IOException - */ - public static InputStream findResourceAsStream(String resource) - throws IOException { - - URL url = findResource(resource); - return url == null ? null : url.openStream(); - } - - /** - * Follows the same rules as findResource(String), but instead returns a - * request dispatcher for serving the resource. It is mainly used to find an - * application's jsp template(s) stored in the file system (or war file in - * case of unexploded distribution) and provide a handle to execute it. - * These jsp templates used to be stored a directory named "templates" and - * there within a directory carrying the modules name. As example: - * "/templates/ccm-navigation/index.jsp". Inside the modules subdirectory - * there might by a module specific subdirectory structure. It's up to the - * module. - * - * @param resourcePath Path to the resource as String. It may include the - * web context in its first part or may be relative to - * the current webapp document root (i.e. its context). - * LEGACY FORMAT: Additionally, the web application - * component (if any) may be a comma separate list of - * webapps to search for the rest of the path String. - * So, if the 'resource' is:
    -     *                 /myproj,ccm-cms/themes/heirloom/admin/index.xsl
    -     *                     
    then this method will look for resources at - *
    -     *                 /myproj/themes/heirloom/admin/index.xsl
    -     *                 /ccm-cms/themes/heirloom/admin/index.xsl
    -     * 
    LEGACY FORMAT SUPPORT NOT IMPLEMENTED YET! LEGACY FORMAT MAY BE - * COMPLETELY REMOVED IN FUTURE RELEASE - * - * @return the request dispatcher for the resource, or null - */ - public static RequestDispatcher findResourceDispatcher(String resourcePath) { - - if (resourcePath == null) { - return null; - } - ServletContext ctx = getServletContext(); - URL url = null; - - // Check for old style resource format including a comma seoarated list - // of webapps - if (resourcePath.indexOf(",") <= 0) { - // no comma separated list found, process as normal - - try { - url = ctx.getResource(resourcePath); - } catch (MalformedURLException ex) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Resource for " + resourcePath + " not found."); - } - // throw new UncheckedWrapperException( - // "No resource at " + resourcePath, ex); - return null; - } - if (url == null) { - return null; - } else { - RequestDispatcher rd = (ctx == null) ? null : ctx - .getRequestDispatcher(resourcePath); - return rd; - } - - } else { - - // old style format not implemented yet here - return null; - - } - - } - - /** - * - */ - private static class WebContextLocal extends InternalRequestLocal { - - @Override - protected Object initialValue() { - return Web.s_initialContext.copy(); - } - - @Override - protected void clearValue() { - ((WebContext) get()).clear(); - } - - } - - // /////////////////////////////////////////////////////////////////////// - // - // DEPRECATED METHODS - // ================== - // This method assume the main ccm application installed in the hosts root - // context and somme other ccm applications installed in its own context. - // It assumes futher that each ccm applications registers itself in a - // home made application directory and it is viable to query this - // directory to find the context for a given ccm application. - // - // /////////////////////////////////////////////////////////////////////// - /** - * Constant to denote the context of the ROOT application (main CCM app). - * Used by some classes to determine the application context (in terms of - * servlet specification, i.e. document root of the web application where - * all the code, specifically WEB-INF, is copied into when unpacking the WAR - * file. - * - * This results in a fixed location (context) for CCM which is no longer - * valid. Replace by invoking method getWebappContextPath - * - * @deprecated without direct replacement. See above - */ -// private static final String ROOT_WEBAPP = "ROOT"; - /** - * Map containing a list of registered ccm webapps and corresponding webapp - * context (ServletContext in JavaEE terms). - * - * @deprecated without direct replacement, see above. - */ -// private static final Map s_contexts = new HashMap(); - /** - * @deprecated renamed to getWebContext - */ -// getContext() - /** - * Gets the servlet context matching the provided URI. The URI is relative - * to the root of the server and must start and end with a '/'. It is - * provided by ContextRegistrationServlet as manually configured in web.xml - * - * This should be used in preference to ServletContext#getWebContext(String) - * since on all versions of Tomcat, this fails if the path of the context - * requested is below the current context. - * - * @param uri the context URI - * - * @return the servlet context matching uri, or null - * - * @deprecated currently without direct replacement The hash map s_contexts - * contains a kind of repository where (i.e. in which web application - * context) a resource may be found. Part of the code access the file system - * directly which is normally forbidden and violates the principle of - * isolation Previously it has been used to allow the installation of some - * modules in its own web application context (e.g. Themedirector) where - * each module used to register here via ContextRegistrationServlet. This - * mechanism has to be replaced by a inter-web-application communication, if - * modules should be enabled to execute in it's web application context. - * - */ -// public static ServletContext getServletContext(String uri) { -// Assert.isTrue(uri.startsWith("/"), "uri must start with /"); -// Assert.isTrue(uri.endsWith("/"), "uri must end with /"); -// return (ServletContext)s_contexts.get(uri); -// } - /** - * Registers a servlet context against a URI. Only intended to be used by - * ContextRegistrationServlet - * - * @deprecated without direct replacement. See getServletContext - */ -// static final void registerServletContext(String uri, -// ServletContext ctx) { -// s_log.debug("Mapping " + ctx + " to " + uri); -// Assert.isTrue(s_contexts.get(uri) == null, -// "a context mapping exists at " + uri); -// // Save the web context as manually configured in web.xml -// // along with the context as provided by ServletContext. -// s_contexts.put(uri, ctx); -// } - /** - * Unregisters the servlet context against a URI. Only intended to be used - * by ContextRegistrationServlet - * - * @deprecated without direct replacement. See getServletContext - */ -// static final void unregisterServletContext(String uri) { -// s_log.debug("Unmapping " + uri); -// s_contexts.remove(uri); -// } - /** - * Finds a concrete URL corresponding to an abstract webapp resource. The - * first argument is a list of webapp paths to search through for the path. - * So if the webapps param is { 'myproj', 'ccm-cms', 'ROOT' } and the path - * parma is '/themes/heirloom/apps/content-section/index.xsl' then the paths - * that are searched are: - *
    -     *  /myproj/themes/heirloom/apps/content-section/index.sl
    -     *  /ccm-cms/themes/heirloom/apps/content-section/index.sl
    -     *  /ROOT/themes/heirloom/apps/content-section/index.sl
    -     * 
    - * - * @param webapps the list of webapps - * @param path the resource path - * - * @return the URL for the resource, or null - * - * @deprecated without direct replacement at the moment. - */ -// public static URL findResource(String[] webapps, -// String path) { -// -// ServletContext ctx = findResourceContext(webapps, -// path); -// -// URL url = null; -// try { -// url = (ctx == null ? null : -// ctx.getResource(path)); -// } catch (IOException ex) { -// throw new UncheckedWrapperException("cannot get URL for " + path, ex); -// } -// if (s_log.isDebugEnabled()) { -// s_log.debug("URL for " + path + " is " + url); -// } -// return url; -// } - /** - * Follows the same rules as findResource(String), but instead returns an - * input stream for reading the resource - * - * @param resource the resource name - * - * @return the input stream for the resource, or null - * - * @deprecated without direct replacement at the moment. - */ -// public static InputStream findResourceAsStream(String resource) -// throws IOException { -// ResourceSpec spec = parseResource(resource); -// -// return findResourceAsStream(spec.getWebapps(), -// spec.getPath()); -// } - /** - * Follows the same rules as findResource(String[], String), but instead - * returns an input stream for reading the resource - * - * @param webapps the list of webapps - * @param path the resource path - * - * @return the input stream for the resource, or null - * - * @deprecated without direct replacement at the moment. - */ -// public static InputStream findResourceAsStream(String[] webapps, -// String path) -// throws IOException { -// -// URL url = findResource(webapps, path); -// -// return url == null ? null : -// url.openStream(); -// } - /** - * Follows the same rules as findResource(String), but instead returns a - * request dispatcher for serving the resource - * - * @param resource the resource name - * - * @return the request dispatcher for the resource, or null - * - * @deprecated without direct replacement at the moment. - */ -// public static RequestDispatcher findResourceDispatcher(String resource) { -// ResourceSpec spec = parseResource(resource); -// -// return findResourceDispatcher(spec.getWebapps(), -// spec.getPath()); -// } -// /** -// * Follows the same rules as findResource(String[], String), but -// * instead returns a request dispatcher for serving -// * the resource -// * -// * @param webapps the list of webapps -// * @param path the resource path -// * @return the request dispatcher for the resource, or null -// * @deprecated without direct replacement at the moment. -// */ -// public static RequestDispatcher findResourceDispatcher(String[] webapps, -// String path) { -// ServletContext ctx = findResourceContext(webapps, -// path); -// -// return ctx == null ? null : ctx.getRequestDispatcher(path); -// } - /** - * - * @param webapps - * @param path path to the resource, starting with "/" and relative to - * the current context root, or relative to the - * /META-INF/resources directory of a JAR file inside the web - * application's /WEB-INF/lib directory - * - * @return - * - * @deprecated without direct replacement at the moment. - */ -// private static ServletContext findResourceContext(String[] webapps, -// String path) { -// for (int i = (webapps.length - 1) ; i >= 0 ; i--) { -// // trash here, depends of a kind of "home made" list of -// // webapps/webcontexts (or ServletContexts) which are part of CCM -// // but installed in its own context (it is the structure of APLAWS -// // until 1.0.4. -// String ctxPath = ROOT_WEBAPP.equals(webapps[i]) ? -// "" : webapps[i]; -// -// if (!ctxPath.startsWith("/")) { -// ctxPath = "/" + ctxPath; -// } -// if (!ctxPath.endsWith("/")) { -// ctxPath = ctxPath + "/"; -// } -// -// ServletContext ctx = getServletContext(ctxPath); -// if (s_log.isDebugEnabled()) { -// s_log.debug("Servlet context for " + ctxPath + " is " + ctx); -// } -// -// if (ctx != null) { -// try { -// URL url = ctx.getResource(path); -// if (url != null) { -// if (s_log.isDebugEnabled()) { -// s_log.debug("Got URL " + url + " for " + path); -// } -// return ctx; -// } else { -// if (s_log.isDebugEnabled()) { -// s_log.debug("No URL present for " + path); -// } -// } -// } catch (IOException ex) { -// throw new UncheckedWrapperException( -// "cannot get resource " + path, ex); -// } -// } -// } -// return null; -// } - // ///////////////////////////////////////////////////////////////////////// - // Private classes and methods - // ///////////////////////////////////////////////////////////////////////// - /** - * Splits the resource string into a StringArray of webapps (ServletContexts - * in terms of JavaEE) and a path to a resource inside a the that webapp. - * The part between the first and the second slash is always treated as - * webapp part! This part may consist of a comma separated list in which - * case the result is an array of webapps > 1. - * - * As of version 6.6x CCM is installed into one webapp context by default - * and the assumption of the first part being a web app is nolonger - * reloiable. Therefore this routine provides invalid results in some - * circumstances! In best cases it provides redundancy specifying just the - * local webapp. - * - * Code may be refactored to ensure the first part is really a webapp by - * inquiring the servlet container using javax.management - * - * @param resource - * - * @return - * - * @deprecated without direct replacement. - */ -// private static ResourceSpec parseResource(String resource) { -// if (resource == null || resource.length() < 2) { -// throw new IllegalArgumentException( -// "Resource spec is too short: " + resource); -// } -// -// int offset = resource.indexOf("/", 1); -// if (offset == -1) { -// throw new IllegalArgumentException( -// "Cannot find second '/' in resource spec : " + resource); -// } -// -// String webappList = resource.substring(1, offset); -// String path = resource.substring(offset); -// -// String[] webapps = StringUtils.split(webappList, ','); -// -// if (s_log.isInfoEnabled()) { -// s_log.info("Web app list " + webappList + " path " + path); -// } -// -// return new ResourceSpec(webapps, path); -// } -// -// -// /** -// * Container to hold a pointer to a resource. The pointer specifically -// * consists of an array of webapps probably containing the requested -// * resource and a path to that resource that has to be equal for each -// * webapp. -// * @deprecated without direct replacement at the moment. -// */ -// private static class ResourceSpec { -// private final String[] m_webapps; -// private final String m_path; -// -// /** -// * Constructor. -// * @param webapps -// * @param path -// */ -// public ResourceSpec(String[] webapps, -// String path) { -// m_webapps = webapps; -// m_path = path; -// } -// -// public String[] getWebapps() { -// return m_webapps; -// } -// -// public String getPath() { -// return m_path; -// } -// } -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/WebConfig.java b/ccm-core/src/main/java/com/arsdigita/web/WebConfig.java deleted file mode 100644 index 090166112..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/WebConfig.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.web; - -import com.arsdigita.util.UncheckedWrapperException; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.Configuration; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.configuration.Setting; - -import java.lang.reflect.Method; -import java.util.HashSet; -import java.util.Set; -import java.util.StringJoiner; - -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.ValidatorFactory; -import javax.validation.constraints.Pattern; -import javax.validation.executable.ExecutableValidator; - -/** - * - * @author Jens Pelzetter - */ -@Configuration -public class WebConfig { - - private static final Logger LOGGER = LogManager.getLogger(WebConfig.class); - - @Setting - private String defaultScheme = "http"; - - @Setting - private String server = "localhost:8080"; - - @Setting - private String secureServer = "localhost:8443"; - - @Setting - private String siteName = "LibreCCM"; - - @Setting - private String host = "localhost:8080"; - - @Setting - private Set secureRequiredFor = new HashSet<>(); - - @Setting - private String dispatcherServletPath = "/ccm"; - - @Setting - private String resolverClass = DefaultApplicationFileResolver.class - .getName(); - - @Setting - private Boolean deactiveCacheHostNotifications = false; - - @Setting - private String dynamicHostProviderClass; - - public static WebConfig getConfig() { - - final ConfigurationManager confManager = CdiUtil.createCdiUtil() - .findBean(ConfigurationManager.class); - return confManager.findConfiguration(WebConfig.class); - } - - public String getDefaultScheme() { - return defaultScheme; - } - - public void setDefaultScheme(final String defaultScheme) { - this.defaultScheme = defaultScheme; - } - - public String getServer() { - return server; - } - - public String getServerName() { - return server.split(":")[0]; - } - - public Integer getServerPort() { - return Integer.parseInt(server.split(":")[1]); - } - - public void setServer( - @Pattern(regexp = "[\\w-.]*:[0-9]{1,5}") final String server) { - final Method method; - try { - method = getClass().getMethod("setServer", String.class); - } catch (NoSuchMethodException ex) { - throw new UncheckedWrapperException(ex); - } - - final Set> violations - = validateHostParameter( - method, server); - - if (violations.isEmpty()) { - this.server = server; - } else { - final StringJoiner joiner = new StringJoiner(", "); - violations.forEach(v -> joiner.add(v.getMessage())); - - throw new IllegalArgumentException(joiner.toString()); - } - } - - public String getSecureServer() { - return secureServer; - } - - public String getSecureServerName() { - return secureServer.split(":")[0]; - } - - public Integer getSecureServerPort() { - return Integer.parseInt(secureServer.split(":")[1]); - } - - public void setSecureServer( - @Pattern(regexp = "[\\w-.]*:[0-9]{1,5}") final String secureServer) { - final Method method; - try { - method = getClass().getMethod("setSecureServer", String.class); - } catch (NoSuchMethodException ex) { - throw new UncheckedWrapperException(ex); - } - - final Set> violations - = validateHostParameter( - method, secureServer); - - if (violations.isEmpty()) { - this.secureServer = secureServer; - } else { - final StringJoiner joiner = new StringJoiner(", "); - violations.forEach(v -> joiner.add(v.getMessage())); - - throw new IllegalArgumentException(joiner.toString()); - } - } - - public String getSiteName() { - return siteName; - } - - public void setSiteName(final String siteName) { - this.siteName = siteName; - } - - public String getHost() { - return host; - } - - public String getHostName() { - return host.split(":")[0]; - } - - public Integer getHostPort() { - return Integer.parseInt(host.split(":")[1]); - } - - public void setHost( - @Pattern(regexp = "[\\w-.]*:[0-9]{1,5}") final String host) { - - final Method method; - try { - method = getClass().getMethod("setHost", String.class); - } catch (NoSuchMethodException ex) { - throw new UncheckedWrapperException(ex); - } - - final Set> violations - = validateHostParameter( - method, host); - - if (violations.isEmpty()) { - this.host = host; - } else { - final StringJoiner joiner = new StringJoiner(", "); - violations.forEach(v -> joiner.add(v.getMessage())); - - throw new IllegalArgumentException(joiner.toString()); - } - } - - public Set getSecureRequiredFor() { - return new HashSet<>(secureRequiredFor); - } - - public void setSecureRequiredFor(final Set secureRequiredFor) { - this.secureRequiredFor = secureRequiredFor; - } - - public String getDispatcherServletPath() { - return dispatcherServletPath; - } - - public void setDispatcherServletPath(final String dispatcherServletPath) { - this.dispatcherServletPath = dispatcherServletPath; - } - - public String getResolverClass() { - return resolverClass; - } - - public ApplicationFileResolver getResolver() { - try { - @SuppressWarnings("unchecked") - final Class clazz - = (Class) Class - .forName(resolverClass); - return clazz.newInstance(); - } catch (ClassNotFoundException | - InstantiationException | - IllegalAccessException ex) { - throw new UncheckedWrapperException( - "Unable to retrieve ApplicationFileResolver", ex); - } - } - - public void setResolverClass(final String resolverClass) { - try { - final Class clazz = Class.forName(resolverClass); - if (!ApplicationFileResolver.class.isAssignableFrom(clazz)) { - throw new IllegalArgumentException( - String.format("Provided class \"%s\" is not an " - + "implementation of the interface \"%s\".", - resolverClass, - ApplicationFileResolver.class.getName())); - } - } catch (ClassNotFoundException ex) { - throw new IllegalArgumentException( - String.format("Unable to retrieve class \"%s\".", - resolverClass), - ex); - } - - this.resolverClass = resolverClass; - } - - public Boolean getDeactiveCacheHostNotifications() { - return deactiveCacheHostNotifications; - } - - public void setDeactiveCacheHostNotifications( - final Boolean deactiveCacheHostNotifications) { - this.deactiveCacheHostNotifications = deactiveCacheHostNotifications; - } - - public String getDynamicHostProviderClass() { - return dynamicHostProviderClass; - } - - public DynamicHostProvider getDynamicHostProvider() { - try { - @SuppressWarnings("unchecked") - final Class clazz - = (Class) Class - .forName(dynamicHostProviderClass); - return clazz.newInstance(); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { - throw new UncheckedWrapperException( - String.format("Failed to create instance of DynamicHostProvider" - + "implenentation \"%s\".", - dynamicHostProviderClass), - ex); - } - } - - public void setDynamicHostProviderClass( - final String dynamicHostProviderClass) { - - try { - final Class clazz = Class.forName(dynamicHostProviderClass); - if (!DynamicHostProvider.class.isAssignableFrom(clazz)) { - throw new IllegalArgumentException( - String.format("Provided class \"%s\" is not an" - + "implementation of the interface \"%s\".", - dynamicHostProviderClass, - DynamicHostProvider.class.getName())); - } - } catch (ClassNotFoundException ex) { - throw new IllegalArgumentException( - String.format("Unable to retrieve class \"%s\".", - dynamicHostProviderClass), - ex); - } - - this.dynamicHostProviderClass = dynamicHostProviderClass; - } - - private Set> validateHostParameter( - final Method method, - final String parameter) { - final Object[] parameters = new Object[1]; - parameters[0] = parameter; - - final ValidatorFactory factory = Validation - .buildDefaultValidatorFactory(); - final ExecutableValidator validator = factory.getValidator() - .forExecutables(); - return validator.validateParameters(this, method, parameters); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/web/WebContext.java b/ccm-core/src/main/java/com/arsdigita/web/WebContext.java deleted file mode 100644 index be537f358..000000000 --- a/ccm-core/src/main/java/com/arsdigita/web/WebContext.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.web; - -import com.arsdigita.util.Assert; -import com.arsdigita.util.Record; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.web.CcmApplication; - -/** - *

    - * A session object that provides an environment in which code can execute. The - * WebContext contains all session-specific variables. One session object is - * maintained per thread.

    - * - *

    - * Accessors of this class may return null. Developers should take care to trap - * null return values in their code.

    - * - * @author Rafael Schloming - * @author Justin Ross - * @version $Id$ - */ -public final class WebContext extends Record { - - /** - * Internal logger instance to faciliate debugging. Enable logging output by - * editing /WEB-INF/conf/log4j.properties int the runtime environment and - * set com.arsdigita.web.WebContext=DEBUG by uncommenting or adding the - * line. - */ - private static final Logger LOGGER = LogManager.getLogger(WebContext.class); - - private CcmApplication m_application = null; - private URL m_requestURL = null; - - /** - * List of properties making up a Web Context - */ - private static String[] s_fields = new String[]{ - "User", - "Application", - "RequestURL" - }; - - /** - * Constructor - */ - WebContext() { - super(WebContext.class, LOGGER, s_fields); - } - - /** - * Creates a copy of this WebContext - * - * @return a new WebContext as a copy of this one - */ - final WebContext copy() { - WebContext result = new WebContext(); - - result.m_application = m_application; - result.m_requestURL = m_requestURL; - - return result; - } - - /** - * Initializes this WebContext object and setting its properties. - * - * @param app - * @param requestURL - */ - final void init(final CcmApplication app, final URL requestURL) { - setApplication(app); - setRequestURL(requestURL); - } - - final void clear() { - m_application = null; - m_requestURL = null; - } - - /** - * - * @return - */ - public final CcmApplication getApplication() { - return m_application; - } - - /** - * - * @param app - */ - final void setApplication(final CcmApplication app) { - m_application = app; - - mutated("Application"); - } - - /** - * - * @return - */ - public final URL getRequestURL() { - return m_requestURL; - } - - /** - * - * @param url - */ - final void setRequestURL(final URL url) { - Assert.exists(url, "URL url"); - - m_requestURL = url; - - mutated("RequestURL"); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/CCMTransformerFactory.java b/ccm-core/src/main/java/com/arsdigita/xml/CCMTransformerFactory.java deleted file mode 100644 index af4d75b78..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/CCMTransformerFactory.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (C) 2014 Jens Pelzetter - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.xml; - -import javax.enterprise.context.ContextNotActiveException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.xml.transform.ErrorListener; -import javax.xml.transform.Source; -import javax.xml.transform.Templates; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.URIResolver; - -/** - * This class acts as a facade for the {@link TransformerFactory} implementation - * configured in {@link XMLConfig}. The current API in the Java Standard API - * does not allow to configure the implementation of {@link TransformerFactory} - * to use at runtime. Therefore we are setting this facade as implementation to - * use via {@code META-INF/services/javax.xml.transform.TransformerFactory}. - * This class uses - * {@link TransformerFactory#newInstance(java.lang.String, java.lang.ClassLoader)} - * to create an instance of the configured {@link TransformerFactory} - * implementation and delegates all calls to it. - * - * @author Jens Pelzetter - */ -public class CCMTransformerFactory extends TransformerFactory { - - private static final Logger LOGGER = LogManager.getLogger( - CCMTransformerFactory.class); - private final TransformerFactory factory; - - public CCMTransformerFactory() { - super(); - - //Get an XMLConfig instance - final XmlConfig config = retrieveXmlConfig(); - //Get the classname - final String classname = config.getXslTransformerFactoryClassname(); - LOGGER.warn(String.format("XSL Transformer Factory classname is %s", - classname)); - - if (classname == null || classname.isEmpty()) { - //To make this class errorprone we check for null and empty string. Normally this - //is not possible, but to be sure, we check the classname provided by XMLConfig and - //fallback to the default value if the string is null or empty. - LOGGER.warn( - "XSLTransformerFactory classname provided by XMLConfig is null or empty. " - + "This indicates a invalid configuration. Check your configuration! " - + "Falling back to default."); - factory = TransformerFactory.newInstance( - config.getDefaultXslTransformerFactoryClassname(), null); - } else { - factory = TransformerFactory.newInstance(classname, null); - } - - } - - private XmlConfig retrieveXmlConfig() { - try { - return XmlConfig.getConfig(); - } catch (IllegalStateException | ContextNotActiveException ex) { - LOGGER.warn( - "Failed to access registry (CDI container not available?).", - ex); - return new XmlConfig(); - } - } - - @Override - public Transformer newTransformer(final Source source) - throws TransformerConfigurationException { - return factory.newTransformer(source); - } - - @Override - public Transformer newTransformer() throws TransformerConfigurationException { - return factory.newTransformer(); - } - - @Override - public Templates newTemplates(final Source source) throws - TransformerConfigurationException { - return factory.newTemplates(source); - } - - @Override - public Source getAssociatedStylesheet(final Source source, - final String media, - final String title, - final String charset) - throws TransformerConfigurationException { - return factory.getAssociatedStylesheet(source, media, title, charset); - } - - @Override - public void setURIResolver(final URIResolver resolver) { - factory.setURIResolver(resolver); - } - - @Override - public URIResolver getURIResolver() { - return factory.getURIResolver(); - } - - @Override - public void setFeature(final String name, - final boolean value) throws - TransformerConfigurationException { - factory.setFeature(name, value); - } - - @Override - public boolean getFeature(final String name) { - return factory.getFeature(name); - } - - @Override - public void setAttribute(final String name, final Object value) { - factory.setAttribute(name, value); - } - - @Override - public Object getAttribute(final String name) { - return factory.getAttribute(name); - } - - @Override - public void setErrorListener(final ErrorListener listener) { - factory.setErrorListener(listener); - } - - @Override - public ErrorListener getErrorListener() { - return factory.getErrorListener(); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/Document.java b/ccm-core/src/main/java/com/arsdigita/xml/Document.java deleted file mode 100644 index 7532e591c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/Document.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.xml; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.ByteArrayOutputStream; -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamSource; -import javax.xml.transform.stream.StreamResult; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; - -/** - * A wrapper class that implements some functionality of - * org.jdom.Document using org.w3c.dom.Document. - * - * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - * pboy (Jan. 09) Class uses "DocumentBuilderFactory.newInstance()" to setup the - * parser (according to the javax.xml specification). This is a simple and - * straightforward, but rather thumb method. It requires a JVM wide acceptable - * configuration (using a system.property or a static JRE configuration file) - * and contrains all programms in a JVM (e.g. multiple CCM running in a - * container) to use the same configuration. - * - * Other methods are available but we have to dig deeper into the CCM code. - * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - * - * @author Patrick McNeill - * @since ACS 4.5a - * @version $Id$ - */ -public class Document { - - private static final Logger LOGGER = LogManager.getLogger(Document.class - .getName()); - /** - * this is the identity XSL stylesheet. We need to provide the identity - * transform as XSL explicitly because the default transformer - * (newTransformer()) strips XML namespace attributes. Also, this XSLT will - * strip the debugging info from the XML document if - * present. - */ - // XXX For some reason JD.XSLT doesn't copy xmlns: attributes - // to the output doc with - /* - private final static String identityXSL = - "\n" - + "\n" - + "\n" - + " " - + "\n\n" - + "\n" - + "\n" - + ""; - */ - // Explicitly create elements & attributes to avoid namespace - // problems - private final static String identityXSL = "\n" - + "\n" - + "\n" - + " \n" - + "\n" - + "\n" - + " \n" - + "\n" - + "\n" - + " \n" - + "\n" - + "\n" - + "\n" - + ""; - /** - * A single DocumentBuilderFactory to use for creating - * Documents. - */ - protected static DocumentBuilderFactory s_builder = null; - /** - * A single DocumentBuilder to use for creating Documents. - */ - protected static ThreadLocal s_db = null; - - // ToDo (pboy): we should use - // DocumentBuilderFactory.newInstance(className cname, classLoader cloader) - // instead to achieve independence from a JVM wide configuration. - // Requires additional modifications in c.ad.util.xml.XML - static { -// try { - LOGGER.debug("Static initalizer starting..."); - s_builder = DocumentBuilderFactory.newInstance(); - s_builder.setNamespaceAware(true); - s_db = new ThreadLocal() { - - @Override - public Object initialValue() { - try { - return s_builder.newDocumentBuilder(); - } catch (ParserConfigurationException pce) { - return null; - } - } - - }; - LOGGER.debug("Static initalized finished."); -// } -// catch ( e) { -// LOGGER.error(e); -// } - } - - /* Used to build the DOM Documents that this class wraps */ - /** - * The internal DOM document being wrapped. - */ - protected org.w3c.dom.Document m_document; - - /** - * Creates a new Document class with no root element. - * - * @throws javax.xml.parsers.ParserConfigurationException - */ - public Document() throws ParserConfigurationException { - DocumentBuilder db = (DocumentBuilder) s_db.get(); - if (db == null) { - throw new ParserConfigurationException( - "Unable to create a DocumentBuilder"); - } - m_document = db.newDocument(); - } - - /** - * - * Creates a new Document class based on an org.w3c.dom.Document. - * - * @param doc the org.w3c.dom.Document - * - */ - public Document(org.w3c.dom.Document doc) { - m_document = doc; - } - - /** - * Creates a new Document class with the given root element. - * - * @param rootNode the element to use as the root node - * - * @throws javax.xml.parsers.ParserConfigurationException - */ - public Document(Element rootNode) throws ParserConfigurationException { - DocumentBuilder db = (DocumentBuilder) s_db.get(); - if (db == null) { - throw new ParserConfigurationException( - "Unable to create a DocumentBuilder"); - } - - m_document = db.newDocument(); - rootNode.importInto(m_document); - m_document.appendChild(rootNode.getInternalElement()); - } - - /** - * Creates a document from the passed in string that should be properly - * formatted XML - * - * @param xmlString - * - * @throws javax.xml.parsers.ParserConfigurationException - * @throws org.xml.sax.SAXException - */ - public Document(String xmlString) - throws ParserConfigurationException, org.xml.sax.SAXException { - this(new org.xml.sax.InputSource(new java.io.StringReader(xmlString))); - } - - public Document(byte[] xmlBytes) - throws ParserConfigurationException, org.xml.sax.SAXException { - this(new org.xml.sax.InputSource(new java.io.ByteArrayInputStream( - xmlBytes))); - } - - private Document(org.xml.sax.InputSource inputSource) - throws ParserConfigurationException, org.xml.sax.SAXException { - DocumentBuilder db = (DocumentBuilder) s_db.get(); - if (db == null) { - throw new ParserConfigurationException( - "Unable to create a DocumentBuilder"); - } - - org.w3c.dom.Document domDoc; - try { - domDoc = db.parse(inputSource); - } catch (java.io.IOException e) { - throw new com.arsdigita.util.UncheckedWrapperException(e); - } - m_document = domDoc; - } - - /** - * Sets the root element. - * - * @param rootNode the element to use as the root node - * - * @return this document. - */ - public Document setRootElement(Element rootNode) { - rootNode.importInto(m_document); - m_document.appendChild(rootNode.getInternalElement()); - - return this; - } - - /** - * Creates a new element and sets it as the root. Equivalent to - *
    -     * Element root = new Element("name", NS);
    -     * doc.setRootElement(root);
    -     * 
    - * - * @param elt the element name - * @param ns the element's namespace URI - * - * @return The newly created root element. - */ - public Element createRootElement(String elt, String ns) { - org.w3c.dom.Element root = m_document.createElementNS(ns, elt); - m_document.appendChild(root); - Element wrapper = new Element(); - wrapper.m_element = root; - return wrapper; - } - - /** - * Creates a new element and sets it as the root. Equivalent to - *
    -     * Element root = new Element("name", NS);
    -     * doc.setRootElement(root);
    -     * 
    - * - * @param elt the element name - * - * @return The newly created root element. - */ - public Element createRootElement(String elt) { - org.w3c.dom.Element root = m_document.createElement(elt); - m_document.appendChild(root); - Element wrapper = new Element(); - wrapper.m_element = root; - return wrapper; - } - - /** - * Returns the root element for the document. This is the top-level element - * (the "HTML" element in an HTML document). - * - * @return the document's root element. - */ - public Element getRootElement() { - Element root = new Element(); - root.m_element = m_document.getDocumentElement(); - return root; - } - - /** - * Not a part of org.jdom.Document, this function returns the - * internal DOM representation of this document. This method should only be - * used when passing the DOM to the translator. It will require changes once - * JDOM replaces this class. - * - * @return this document. - */ - public org.w3c.dom.Document getInternalDocument() { - return m_document; - } - - /** - * General toString() method for org.w3c.domDocument. Not really related to - * xml.Document, but needed here. Converts an XML in-memory DOM to String - * representation, using an XSLT identity transformation. - * - * @param document the org.w3c.dom.Document object to convert - * to a String representation - * @param indent if true, try to indent elements according to - * normal XML/SGML indentation conventions (may only work - * with certain XSLT engines) - * - * @return a String representation of document. - */ - public static String toString(org.w3c.dom.Document document, - boolean indent) { - Transformer identity; - ByteArrayOutputStream os = new ByteArrayOutputStream(); - try { - StreamSource identitySource = new StreamSource(new StringReader( - identityXSL)); - identity = TransformerFactory - .newInstance() - .newTransformer(identitySource); - identity.setOutputProperty("method", "xml"); - identity.setOutputProperty("indent", (indent ? "yes" : "no")); - identity.setOutputProperty("encoding", "UTF-8"); - identity.transform(new DOMSource(document), new StreamResult(os)); - } catch (javax.xml.transform.TransformerException e) { - LOGGER.error("error in toString", e); - return document.toString(); - } - - try { - return os.toString("UTF-8"); - } catch (UnsupportedEncodingException ex) { - LOGGER.error("UTF-8 encoding not supported!!!"); - return os.toString(); - } - } - - /** - * Convenience wrapper for static toString(Document, boolean), without - * additional indenting. - * - * @param document the org.w3c.dom.Document to output - * - * @return a String representation of document. - */ - public static String toString(org.w3c.dom.Document document) { - return toString(document, false); - } - - /** - * Generates an XML text representation of this document. - * - * @param indent if true, try to indent XML elements according - * to XML/SGML convention - * - * @return a String representation of this. - */ - public String toString(boolean indent) { - return toString(m_document, indent); - } - - /** - * Generates an XML text representation of this document, without additional - * indenting. - * - * @return a String representation of this. - */ - @Override - public String toString() { - return toString(m_document, false); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/Element.java b/ccm-core/src/main/java/com/arsdigita/xml/Element.java deleted file mode 100644 index 50d4d737e..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/Element.java +++ /dev/null @@ -1,622 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.xml; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import com.arsdigita.util.Assert; -import com.arsdigita.util.UncheckedWrapperException; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Attr; - -/** - * A wrapper class that implements some functionality of - * org.jdom.Element using org.w3c.dom.Element. - * - * @author Patrick McNeill - * @since ACS 4.5a - * @version $Revision$ $Date: 2017-10-25 15:26:01 +0200 (Mi, 25 Okt 2017) - * $ - * @version $Id$ - */ -public class Element { - - private static final Logger LOGGER = LogManager.getLogger(Element.class - .getName()); - protected org.w3c.dom.Element m_element; - /* DOM element that is being wrapped */ - /** - * owner document - */ - private org.w3c.dom.Document m_doc; - - private static ThreadLocal s_localDocument = new ThreadLocal() { - - @Override - public Object initialValue() { - try { - DocumentBuilderFactory builder = DocumentBuilderFactory - .newInstance(); - builder.setNamespaceAware(true); - return builder.newDocumentBuilder().newDocument(); - } catch (ParserConfigurationException e) { - LOGGER.error(e); - throw new UncheckedWrapperException( - "INTERNAL: Could not create thread local DOM document.", - e); - } - } - - }; - - private static org.w3c.dom.Document getDocument() { - return (org.w3c.dom.Document) s_localDocument.get(); - } - -// public org.w3c.dom.Document getOwnerDocument() { -// if (null == m_doc) { -// m_doc = (org.w3c.dom.Document) s_localDocument.get(); -// } -// -// return m_doc; -// } -// public void importElement(final Element element) { -// element.m_element = (org.w3c.dom.Element) this.m_element -// .getOwnerDocument().importNode(element.m_element, -// true); -// } - public void syncDocs() { - if (m_doc == null) { - m_doc = (org.w3c.dom.Document) s_localDocument.get(); - } - - if (!m_element.getOwnerDocument().equals(m_doc)) { - m_element = (org.w3c.dom.Element) m_doc.importNode(m_element, true); - } - } - - /** - * Protected constructor to set up factories, etc. Does not actually create - * a new element. Used if we are programatically setting the m_element field - * later. - */ - protected Element() { - } - - /** - * Creates a new element with the given name and no assigned namespace. - * - * @param name the name of the element - */ - public Element(String name) { - this(); - Assert.exists(name, String.class); - - m_element = getDocument().createElement(name); - } - - /** - * Creates a new element with the given name, and assigns it to the - * namespace defined at uri. The namespace prefix is - * automatically determined. - * - * @param name the name of the element - * @param uri the URI for the namespace definition - */ - public Element(String name, String uri) { - Assert.exists(name, String.class); - Assert.exists(uri, String.class); - - m_element = getDocument().createElementNS(uri, name); - } - - /** - * Creates a new element and adds it as a child to this element. - * elt.newChildElement("newElt") is equivalent to - *
    -     * Element newElt = new Element("newElt");
    -     * elt.addChild(newElt);
    -     * 
    - * - * @param name the name of the element - * - * @return the created child element. - * - * @pre m_element != null - */ - public Element newChildElement(String name) { - Assert.exists(name, String.class); - - if (m_doc == null) { - m_doc = this.m_element.getOwnerDocument(); - } - - Element result = new Element(); - result.m_element = m_doc.createElement(name); - this.m_element.appendChild(result.m_element); - return result; - } - - /** - * Creates a new element. Adds it as a child to this element element and - * assigns it to the namespace defined at uri. - * elt.newChildElement("newElt", namespace) is equivalent to - *
    -     * Element newElt = new Element("newElt", namespace);
    -     * elt.addChild(newElt);
    -     * 
    - * - * @param name the name of the Element - * @param uri the URI for the namespace definition - * - * @return the created child element. - * - * @pre m_element != null - */ - public Element newChildElement(String name, String uri) { - Assert.exists(name, String.class); - Assert.exists(uri, String.class); - - if (m_doc == null) { - m_doc = this.m_element.getOwnerDocument(); - } - - Element result = new Element(); - result.m_element = m_doc.createElementNS(uri, name); - this.m_element.appendChild(result.m_element); - return result; - } - - /** - * Copies the passed in element and all of its children to a new Element. - * - * @param copyFrom - * - * @return - */ - public Element newChildElement(Element copyFrom) { - Assert.exists(copyFrom, Element.class); - - if (m_doc == null) { - m_doc = this.m_element.getOwnerDocument(); - } - - Element copyTo = new Element(); - copyTo.m_element = m_doc.createElementNS(copyFrom.m_element - .getNamespaceURI(), copyFrom.getName()); - this.m_element.appendChild(copyTo.m_element); - newChildElementHelper(copyFrom, copyTo); - return copyTo; - } - - /** - * Copies the passed in element and all of its children to a new Element - * using the passed-in name. - * - * @param name - * @param copyFrom - * - * @return - */ - public Element newChildElement(String name, Element copyFrom) { - if (m_doc == null) { - m_doc = this.m_element.getOwnerDocument(); - } - - Element copyTo = new Element(); - copyTo.m_element = m_doc.createElement(name); - this.m_element.appendChild(copyTo.m_element); - newChildElementHelper(copyFrom, copyTo); - return copyTo; - } - - /** - * Copies the passed in element and all of its children to a new Element - * using the passed-in name. - * - * @param name - * @param uri - * @param copyFrom - * - * @return - */ - public Element newChildElement(String name, String uri, Element copyFrom) { - if (m_doc == null) { - m_doc = this.m_element.getOwnerDocument(); - } - - Element copyTo = new Element(); - copyTo.m_element = m_doc.createElementNS(uri, name); - this.m_element.appendChild(copyTo.m_element); - newChildElementHelper(copyFrom, copyTo); - return copyTo; - } - - private void newChildElementHelper(Element copyFrom, Element copyTo) { - copyTo.setText(copyFrom.getText()); - - NamedNodeMap nnm = copyFrom.m_element.getAttributes(); - - if (nnm != null) { - for (int i = 0; i < nnm.getLength(); i++) { - Attr attr = (org.w3c.dom.Attr) nnm.item(i); - copyTo.addAttribute(attr.getName(), attr.getValue()); - } - } - - Iterator iter = copyFrom.getChildren().iterator(); - - while (iter.hasNext()) { - Element child = (Element) iter.next(); - copyTo.newChildElement(child); - } - - } - - /** - * Adds an attribute to the element. - * - * @param name the name of the attribute - * @param value the value of the attribute - * - * @return this element. - */ - public Element addAttribute(String name, String value) { - Assert.exists(name, String.class); - - m_element.setAttribute(name, value); - - return this; - } - - public Element addAttribute(String name, - String value, - String ns) { - Assert.exists(name, String.class); - Assert.exists(ns, String.class); - - m_element.setAttributeNS(ns, name, value); - - return this; - } - - /** - * Adds a child element to this element. - * - * @param newContent the new child element - * - * @return this element. - */ - public Element addContent(Element newContent) { - Assert.exists(newContent, Element.class); - - newContent.importInto(m_element.getOwnerDocument()); - m_element.appendChild(newContent.getInternalElement()); - - return this; - } - - /** - * Sets the text value of the current element (the part between the tags). - * If the passed in text is null then it is converted to the empty string. - * - * @param text the text to include - * - * @return this element. - */ - public Element setText(String text) { - if (text == null) { - // This converts the null to the empty string because - // org.w3c.dom does not like null and HTML does not - // differentiate between "" and null. The other option - // is to throw the NPE which causes other problems - text = ""; - } - org.w3c.dom.Text textElem = m_element.getOwnerDocument().createTextNode( - text); - m_element.appendChild(textElem); - - return this; - } - - /** - * Returns the concatenation of all the text in all child nodes of the - * current element. - * - * @return - */ - public String getText() { - StringBuilder result = new StringBuilder(); - - org.w3c.dom.NodeList nl = m_element.getChildNodes(); - - for (int i = 0; i < nl.getLength(); i++) { - org.w3c.dom.Node n = nl.item(i); - - if (n.getNodeType() == org.w3c.dom.Node.TEXT_NODE) { - result.append(((org.w3c.dom.Text) n).getData()); - } - } - - return result.toString(); - } - - public Element setCDATASection(String cdata) { - LOGGER.debug("Setting CDATA section to '" + cdata + "'."); - - if (cdata == null) { - cdata = ""; - } - - org.w3c.dom.CDATASection cdataSection = m_element.getOwnerDocument() - .createCDATASection(cdata); - - m_element.appendChild(cdataSection); - - return this; - } - - public String getCDATASection() { - StringBuilder result = new StringBuilder(); - - org.w3c.dom.NodeList nl = m_element.getChildNodes(); - - for (int i = 0; i < nl.getLength(); i++) { - org.w3c.dom.Node n = nl.item(i); - - if (n.getNodeType() == org.w3c.dom.Node.CDATA_SECTION_NODE) { - result.append(((org.w3c.dom.CDATASection) n).getData()); - } - } - - String str = result.toString(); - - LOGGER.debug("Fetched this from CDATA section: " + str); - - return str; - } - - /** - * Returns a List of all the child elements nested directly - * (one level deep) within this element, as Element objects. If - * this target element has no nested elements, an empty List is - * returned. The returned list is "live", so changes to it affect the - * element's actual contents. - *

    - * - * This performs no recursion, so elements nested two levels deep would have - * to be obtained with: - *

    -     * Iterator itr = currentElement.getChildren().iterator();
    -     * while (itr.hasNext()) {
    -     *    Element oneLevelDeep = (Element)nestedElements.next();
    -     *    List twoLevelsDeep = oneLevelDeep.getChildren();
    -     *      // Do something with these children
    -     *    }
    -     * 
    - * - * @return list of child Element objects for this element. - */ - public java.util.List getChildren() { - java.util.List retval = new java.util.ArrayList(); - org.w3c.dom.NodeList nl = m_element.getChildNodes(); - for (int i = 0; i < nl.getLength(); i++) { - org.w3c.dom.Node n = nl.item(i); - if (n instanceof org.w3c.dom.Element) { - Element elt = new Element(); - elt.m_element = (org.w3c.dom.Element) n; - retval.add(elt); - } - } - return retval; - } - - public java.util.Map getAttributes() { - // Retrieve the attributes of the DOM Element - org.w3c.dom.NamedNodeMap attributeNodeMap = m_element.getAttributes(); - - // Create the HashMap that we will return the attributes - // in - java.util.HashMap returnMap = new java.util.HashMap(); - - // Copy the attribute values in the NamedNodeMap to the - // HashMap - for (int i = 0; i < attributeNodeMap.getLength(); ++i) { - // Get the Node - org.w3c.dom.Node attributeNode = attributeNodeMap.item(i); - // Copy the name and value to the map - returnMap.put(attributeNode.getNodeName(), - attributeNode.getNodeValue()); - } - - // Return the HashMap - return returnMap; - } - - /** - * Retrieves an attribute value by name. - * - * @param name The name of the attribute to retrieve - * - * @return The Attr value as a string, or the empty string if that attribute - * does not have a specified or default value. - */ - public String getAttribute(String name) { - return m_element.getAttribute(name); - } - - public boolean hasAttribute(String name) { - return m_element.hasAttribute(name); - } - - public String getName() { - return m_element.getTagName(); - } - - /** - * Functions to allow this class to interact appropriately with the Document - * class (for example, allows nodes to be moved around, and so on). - * - * @return the internal DOM Element. - */ - protected final org.w3c.dom.Element getInternalElement() { - return m_element; - } - - /** - * Imports the internal node into another document. This could also be done - * with a combination of getInternalElement and a setInternalElement - * function. - * - * @param doc the org.w3c.dom.Document to import into - */ - protected void importInto(org.w3c.dom.Document doc) { - /* - Exception e = new Exception(); - java.io.StringWriter sw = new java.io.StringWriter(); - e.printStackTrace(new java.io.PrintWriter(sw)); - System.out.println(sw.toString().substring(0, 300)); - */ - - m_element = (org.w3c.dom.Element) doc.importNode(m_element, true); - } - - /** - * Workaround for bug in some versions of Xerces. For some reason, - * importNode doesn't also copy attribute values unless you call getValue() - * on them first. This may be fixed in a later version of Xerces. In the - * meantime, calling visitAllAttributes(node) before importNode should help. - * - * @param node the org.w3c.dom.Node about to be imported - * - * @deprecated with no replacement, 1 May 2003 - */ - public static void visitAllAttributes(org.w3c.dom.Node node) { - org.w3c.dom.NamedNodeMap nnm = node.getAttributes(); - if (nnm != null) { - for (int i = 0; i < nnm.getLength(); i++) { - org.w3c.dom.Attr attr = (org.w3c.dom.Attr) nnm.item(i); - attr.getValue(); - } - } - org.w3c.dom.NodeList nl = node.getChildNodes(); - if (nl != null) { - for (int i = 0; i < nl.getLength(); i++) { - visitAllAttributes(nl.item(i)); - } - } - } - - /** - * retrieve an unordered list of strings relating to node tree including and - * below the current element. Strings include element names, attribute - * names, attribute values, text and CData sections - * - * @return - */ - private List getXMLFragments() { - - List unsortedList = new ArrayList(); - unsortedList.add(getName()); - unsortedList.add(getText()); - // CData sections are not included in getChildren() - unsortedList.add(getCDATASection()); - Iterator it = getAttributes().entrySet().iterator(); - while (it.hasNext()) { - java.util.Map.Entry entry = (java.util.Map.Entry) it.next(); - unsortedList.add(entry.getKey()); - unsortedList.add(entry.getValue()); - } - Iterator childElements = getChildren().iterator(); - while (childElements.hasNext()) { - Element el = (Element) childElements.next(); - unsortedList.addAll(el.getXMLFragments()); - } - return unsortedList; - - } - - /** - * retrieve a string that is an ordered concatenation of all information - * describing this node and its subnodes, suitable as the basis of a - * hashCode or equals implementation. - * - * @return - */ - protected String getXMLHashString() { - // attributes and child nodes are retrieved as HashMap and List - // respectively. These make no guarantees about the order of - // iteration, and so we sort here to make sure the same element - // will return the same XMLHash - List sortedList = getXMLFragments(); - Collections.sort(sortedList); - StringBuilder xml = new StringBuilder(); - Iterator xmlFragments = sortedList.iterator(); - while (xmlFragments.hasNext()) { - xml.append(xmlFragments.next()); - } - LOGGER.debug("getXMLHashString: " + xml.toString()); - return xml.toString(); - } - - @Override - public int hashCode() { - Date start = new Date(); - String hashString = getXMLHashString(); - LOGGER.debug( - "hashCode: getXMLString took " - + (new Date().getTime() - start.getTime()) - + " millisecs"); - - return hashString.hashCode(); - - } - - @Override - public boolean equals(Object other) { - LOGGER.debug("equals invoked"); - Date start = new Date(); - if (other == null) { - return false; - } - if (!other.getClass().equals(Element.class)) { - return false; - } - Element otherElement = (Element) other; - String thisXML = getXMLHashString(); - String otherXML = otherElement.getXMLHashString(); - LOGGER.debug( - "Equals: getXMLString twice took " - + (new Date().getTime() - start.getTime()) - + " millisecs"); - return thisXML.equals(otherXML); - - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/Formatter.java b/ccm-core/src/main/java/com/arsdigita/xml/Formatter.java deleted file mode 100644 index 2876190fa..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/Formatter.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.xml; - -/** - * An interface providing an API for converting an object - * to a string. Thus instead of doing - *
    - *  Date today = new Date();
    - *  element.addAttribute("today", date.toString());
    - * 
    - * we can do: - *
    - *  Date today = new Date();
    - *  element.addAttribute("today", XML.format(date));
    - * 
    - * Or if you require a non-default format: - *
    - *  Date today = new Date();
    - *  element.addAttribute("today", new DateTimeFormatter.format(today));
    - * 
    - */ -public interface Formatter { - String format(Object value); -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/XML.java b/ccm-core/src/main/java/com/arsdigita/xml/XML.java deleted file mode 100644 index 3d1f4735c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/XML.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.xml; - -import com.arsdigita.util.UncheckedWrapperException; - -import com.arsdigita.xml.formatters.DateTimeFormatter; - -import org.apache.logging.log4j.LogManager; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - - -import org.apache.logging.log4j.Logger; - -/** - * Provides a set of static helper methods for dealing with XML, - * including file parsing & object -> string serialization - */ -public class XML { - - private static final Logger LOGGER = LogManager.getLogger(XML.class); - - // private static XMLConfig s_config; - - private static final Map s_formatters = new HashMap(); - static { - LOGGER.debug("Static initalizer starting..."); - s_formatters.put(Date.class, new DateTimeFormatter()); - LOGGER.debug("Static initalizer finished."); - } - - /** - * Constructor. All methods are static, no initialization required. - */ - private XML() {} - - /** - * Retrieves the current configuration - public static XMLConfig getConfig() { - if (s_config == null) { - s_config = new XMLConfig(); - s_config.load(); - } - return s_config; - } - */ - - /** - * Registers a formatter for serializing objects of a - * class to a String suitable for XML output. - * @param klass - * @param formatter - */ - public static void registerFormatter(Class klass, - Formatter formatter) { - s_formatters.put(klass, formatter); - } - - /** - * Unregisters a formatter against a class. - * @param klass - */ - public static void unregisterFormatter(Class klass) { - s_formatters.remove(klass); - } - - /** - * Gets a directly registered formatter for a class. - * @param klass the class to find a formatter for - * @return the formatter, or null if non is registered - */ - public static Formatter getFormatter(Class klass) { - return (Formatter)s_formatters.get(klass); - } - - /** - * Looks for the best matching formatter. - * - * @param klass the class to find a formatter for - * @return the formatter, or null if non is registered - */ - public static Formatter findFormatter(Class klass) { - Formatter formatter = null; - while (formatter == null && klass != null) { - formatter = getFormatter(klass); - klass = klass.getSuperclass(); - } - return formatter; - } - - /** - * Converts an object to a String using the closest - * matching registered Formatter implementation. Looks - * for a formatter registered against the object's - * class first, then its superclass, etc. If no formatter - * is found, uses the toString() method. - * - * @param value - * @return - */ - public static String format(Object value) { - if (value == null) { - return null; - } - - if (value instanceof String) { - return (String)value; - } - - Formatter formatter = findFormatter(value.getClass()); - if (formatter == null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("No formatter for " + value.getClass()); - } - return value.toString(); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Processing " + value.getClass() + - " with " + formatter.getClass()); - } - return formatter.format(value); - } - - /** - * Processes an XML file with the default SAX Parser, with - * namespace processing, schema validation & DTD validation - * enabled. - * - * @param path the XML file relative to the webapp root - * @param handler the content handler - */ - public static final void parseResource(String path, - DefaultHandler handler) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Processing resource " + path + - " with " + handler.getClass()); - } - - if (path.startsWith("/")) { - path = path.substring(1); - } - - ClassLoader cload = Thread.currentThread().getContextClassLoader(); - InputStream stream = cload.getResourceAsStream(path); - - if (stream == null) { - throw new IllegalArgumentException("no such resource: " + path); - } - - parse(stream, handler); - } - - /** - * Processes an XML file with the default SAX Parser, with - * namespace processing, schema validation & DTD validation - * enabled. - * - * @param source the xml input stream - * @param handler the content handler - */ - public static final void parse(InputStream source, - DefaultHandler handler) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Processing stream " + source + - " with " + handler.getClass()); - } - - try { - // ToDo (pboy): We should use - // SAXParserFactory.newInstance(String clName, ClassLoader clLoader) - // instead to achieve independence of a JVM wide acceptable - // configuration (affecting all CCM instances which may run in a - // container). - // Requires additional modifications in c.ad.util.xml.XML - SAXParserFactory spf = SAXParserFactory - .newInstance(); - spf.setFeature("http://xml.org/sax/features/namespaces", true); - SAXParser parser = spf.newSAXParser(); - parser.parse(source, handler); - } catch (ParserConfigurationException e) { - throw new UncheckedWrapperException("error parsing stream", e); - } catch (SAXException e) { - if (e.getException() != null) { - throw new UncheckedWrapperException("error parsing stream", - e.getException()); - } else { - throw new UncheckedWrapperException("error parsing stream", e); - } - } catch (IOException e) { - throw new UncheckedWrapperException("error parsing stream", e); - } - } - - /** - * This visitor is called by {@link #traverse(Element, int, XML.Action)}. - **/ - public interface Action { - void apply(Element elem, int level); - } - - /** - * Prints the skeleton structure of the element to the supplied print - * writer. - * @param element - * @param writer - **/ - public static void toSkeleton(final Element element, - final PrintWriter writer) { - - XML.traverse(element, 0, new Action() { - @Override - public void apply(Element elem, int level) { - final String padding = " "; - for (int ii=0; iiJens Pelzetter - */ -@Configuration -public final class XmlConfig { - - // supported XSL transformer implementations - private static final String RESIN = "com.caucho.xsl.Xsl"; - private static final String SAXON = "com.icl.saxon.TransformerFactoryImpl"; - private static final String SAXON_HE = "net.sf.saxon.TransformerFactoryImpl"; - private static final String XALAN - = "org.apache.xalan.processor.TransformerFactoryImpl"; - private static final String XSLTC - = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl"; - - // supported documentBuilder implementations - private static final String DOM_XERCES - = "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"; - private static final String DOM_RESIN - = "com.caucho.xml.parsers.XmlDocumentBuilderFactory"; - - // supported SAX saxParser implementations - private static final String SAX_XERCES - = "org.apache.xerces.jaxp.SAXParserFactoryImpl"; - private static final String SAX_RESIN - = "com.caucho.xml.parsers.XmlSAXParserFactory"; - - @Setting - private String xslTransformer = "saxonhe"; - - @Setting - private String domBuilder = "xerces"; - - @Setting - private String saxParser = "xerces"; - - @Setting - @SuppressWarnings("PMD.LongVariable") - private Boolean fullTimeFormatterEnabled = false; - - public static XmlConfig getConfig() { - final ConfigurationManager confManager = CdiUtil.createCdiUtil() - .findBean(ConfigurationManager.class); - return confManager.findConfiguration(XmlConfig.class); - } - - public String getXslTransformer() { - return xslTransformer; - } - - public String getXslTransformerFactoryClassname() { - switch (xslTransformer) { - case "xsltc": - return XSLTC; - case "xalan": - return XALAN; - case "resin": - return RESIN; - case "saxonhe": - return SAXON_HE; - default: - return getDefaultXslTransformerFactoryClassname(); - } - } - - /** - * Returns the class name of the default {@link TransformerFactory}. This - * method encapsulates the default value so that is easy to change. The - * method is only for use by the classes in the {@code com.arsdigita.xml} - * package, therefore the method is visible for the package. - * - * @return - */ - String getDefaultXslTransformerFactoryClassname() { - return SAXON_HE; - } - - public void setXslTransformer(final String xslTransformer) { - this.xslTransformer = xslTransformer; - } - - public String getDomBuilder() { - return domBuilder; - } - - /** - * Returns the Document Builder factory class name to use - * - * The method assures that the return value is a valid class name. - * - * Not used at the moment. - * - * @return String Document Builder factory class name - */ - public String getDomBuilderFactoryClassname() { - - if ("resin".equals(domBuilder)) { - return DOM_RESIN; - } else { - return getDefaultDomBuilderFactoryClassname(); - } - } - - /** - * Returns the class name of the default {@link DocumentBuilderFactory}. - * This method encapsulates the default value so that is easy to change. The - * method is only for use by the classes in the {@code com.arsdigita.xml} - * package, therefore the method is only accessible from the package. - * - * @return - */ - String getDefaultDomBuilderFactoryClassname() { - return DOM_XERCES; - } - - public void setDomBuilder(final String domBuilder) { - this.domBuilder = domBuilder; - } - - public String getSaxParser() { - return saxParser; - } - - /** - * Returns the Sax Parser factory class name to use. - * - * The method assures that the return value is a valid class name. - * - * Not used at the moment. - * - * @return String Sax Parser factory class name - */ - public String getSaxParserFactoryClassname() { - - if ("resin".equals(saxParser)) { - return SAX_RESIN; - } else { - return getDefaultSaxParserFactoryClassname(); - } - } - - /** - * Returns the class name of the default {@link SAXParserFactory}. This - * method encapsulates the default value so that is easy to change. The - * method is only for use by the classes in the {@code com.arsdigita.xml} - * package, therefore the method is only visible in the package. - * - * @return - */ - String getDefaultSaxParserFactoryClassname() { - return SAX_XERCES; - } - - public void setSaxParser(final String saxParser) { - this.saxParser = saxParser; - } - - public Boolean isFullTimeFormatterEnabled() { - return fullTimeFormatterEnabled; - } - - @SuppressWarnings("PMD.LongVariable") - public void setFullTimeFormatterEnabled( - final Boolean fullTimeFormatterEnabled) { - this.fullTimeFormatterEnabled = fullTimeFormatterEnabled; - } - - @Override - public int hashCode() { - int hash = 3; - hash = 19 * hash + Objects.hashCode(xslTransformer); - hash = 19 * hash + Objects.hashCode(domBuilder); - hash = 19 * hash + Objects.hashCode(saxParser); - hash = 19 * hash + Objects.hashCode(fullTimeFormatterEnabled); - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof XmlConfig)) { - return false; - } - final XmlConfig other = (XmlConfig) obj; - if (!Objects.equals(xslTransformer, other.getXslTransformer())) { - return false; - } - if (!Objects.equals(domBuilder, other.getDomBuilder())) { - return false; - } - if (!Objects.equals(saxParser, other.getSaxParser())) { - return false; - } - return Objects.equals(fullTimeFormatterEnabled, - other.isFullTimeFormatterEnabled()); - } - - @Override - public String toString() { - return String.format("%s{ " - + "xslTransformer = \"%s\", " - + "domBuilder = \"%s\", " - + "parser = \"%s\", " - + "fullTimeFormatterEnabled = %b" - + " }", - super.toString(), - xslTransformer, - domBuilder, - saxParser, - fullTimeFormatterEnabled); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/formatters/DateFormatter.java b/ccm-core/src/main/java/com/arsdigita/xml/formatters/DateFormatter.java deleted file mode 100755 index 72340948c..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/formatters/DateFormatter.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.xml.formatters; - -import com.arsdigita.xml.Formatter; -import java.util.Locale; -import java.util.Date; -import java.text.DateFormat; - -/** - * An alternate formatter for java.util.Date objects, outputting the date in - * 'medium' format. The time is omitted. - * - * @author unknown - * @author Sören Bernstein - */ -public class DateFormatter implements Formatter { - - private static DateFormatterConfig m_config; - - public static final DateFormatterConfig getConfig() { - if (m_config == null) { - m_config = DateFormatterConfig.getConfig(); - } - return m_config; - } - - @Override - public String format(Object value) { - Date date = (Date) value; - - //Locale locale = GlobalizationHelper.getNegotiatedLocale(); - final Locale locale = Locale.getDefault(); - - DateFormat format = DateFormat - .getDateInstance(DateFormat.MEDIUM, locale); - - return format.format(date); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/formatters/DateFormatterConfig.java b/ccm-core/src/main/java/com/arsdigita/xml/formatters/DateFormatterConfig.java deleted file mode 100755 index 5663fe4df..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/formatters/DateFormatterConfig.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.xml.formatters; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.Configuration; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.configuration.Setting; - -import java.util.Objects; - -/** - * - * @author Jens Pelzetter - */ -@Configuration -public final class DateFormatterConfig { - - @Setting - private String locale = null; - - public static DateFormatterConfig getConfig() { - final ConfigurationManager confManager = CdiUtil.createCdiUtil() - .findBean(ConfigurationManager.class); - return confManager.findConfiguration(DateFormatterConfig.class); - } - - public String getLocale() { - return locale; - } - - public void setLocale(final String locale) { - this.locale = locale; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 13 * hash + Objects.hashCode(this.locale); - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof DateFormatterConfig)) { - return false; - } - final DateFormatterConfig other = (DateFormatterConfig) obj; - return Objects.equals(this.locale, other.getLocale()); - } - - @Override - public String toString() { - return String.format("%s{ " - + "locale = %s" - + " }", - super.toString(), - locale); - } - -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/formatters/DateTimeFormatter.java b/ccm-core/src/main/java/com/arsdigita/xml/formatters/DateTimeFormatter.java deleted file mode 100755 index 17846aba0..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/formatters/DateTimeFormatter.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.xml.formatters; - -//import com.arsdigita.globalization.GlobalizationHelper; -import com.arsdigita.xml.Formatter; -import java.util.Locale; -import java.util.Date; -import java.text.DateFormat; - -/** - * The default formatter for java.util.Date objects, outputing the date in - * 'medium' format and the time in 'short' format. - * - * @author unknown - * @author Sören Bernstein - */ -public class DateTimeFormatter implements Formatter { - - @Override - public String format(Object value) { - Date date = (Date) value; - //Locale locale = GlobalizationHelper.getNegotiatedLocale(); - final Locale locale = Locale.getDefault(); - - DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, - DateFormat.SHORT, locale); - - return format.format(date); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/formatters/FullDateFormatter.java b/ccm-core/src/main/java/com/arsdigita/xml/formatters/FullDateFormatter.java deleted file mode 100755 index 5c11c4f85..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/formatters/FullDateFormatter.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2002-2005 Runtime Collective Ltd. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -package com.arsdigita.xml.formatters; - -//import com.arsdigita.kernel.Kernel; -import java.util.Calendar; -import java.util.Date; - -/** - * A DateFormatter which displays dates as: - *
    - * <yearNo> | <monthNo> | <dayOfMonthNo> | <dayOfWeekNo> - * | <hour> | <minute> | <second> | <apm> | <localised date> - *
    - * the numbers are padded with 0s, so the positions of the fields are always - * 0, 7, 12, 17, 21, 26, 31, 36, 41 (in Java), and 1, 8, 13, 18, 22, 27, 32, 37, 42 (in XSL). - */ -public class FullDateFormatter extends DateFormatter { - - public static String SEPARATOR = " | "; - public static String AM = "am"; - public static String PM = "pm"; - public static char ZERO = '0'; - - public String format(Object value) { - - String parentResult = super.format(value); - -// if (!XMLConfig.getConfig().getActivateFullTimeFormatter()) { -// return parentResult; -// } - - Date date = (Date) value; - Calendar cal = Calendar.getInstance(); - StringBuffer result = new StringBuffer(60); - - cal.setTime(date); - - append(result, cal.get(Calendar.YEAR)); - appendMaybeSmall(result, cal.get(Calendar.MONTH)); - appendMaybeSmall(result, cal.get(Calendar.DAY_OF_MONTH)); - append(result, cal.get(Calendar.DAY_OF_WEEK)); - appendMaybeSmall(result, cal.get(Calendar.HOUR)); - appendMaybeSmall(result, cal.get(Calendar.MINUTE)); - appendMaybeSmall(result, cal.get(Calendar.SECOND)); - - switch (cal.get(Calendar.AM_PM)) { - case Calendar.AM: result.append(AM); break; - case Calendar.PM: result.append(PM); break; - } - - result.append(SEPARATOR) - .append(parentResult); - - return result.toString(); - } - - public void appendMaybeSmall(StringBuffer sb, int value) { - if (value < 10) { - sb.append(ZERO); - } - append(sb, value); - } - - public void append(StringBuffer sb, int value) { - sb.append(value) - .append(SEPARATOR); - } -} diff --git a/ccm-core/src/main/java/com/arsdigita/xml/formatters/TimeFormatter.java b/ccm-core/src/main/java/com/arsdigita/xml/formatters/TimeFormatter.java deleted file mode 100755 index edddc81bc..000000000 --- a/ccm-core/src/main/java/com/arsdigita/xml/formatters/TimeFormatter.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.xml.formatters; - -import com.arsdigita.xml.Formatter; -import java.util.Locale; -import java.util.Date; -import java.text.DateFormat; - -/** - * An alternate formatter for java.util.Date objects, - * outputing the date in 'medium' format. The time - * is ommitted. - * - * @author unknown - * @author Sören Bernstein - */ -public class TimeFormatter implements Formatter { - - @Override - public String format(Object value) { - Date date = (Date) value; - -// Locale locale = GlobalizationHelper.getNegotiatedLocale(); - final Locale locale = Locale.getDefault(); - - DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT, locale); - - return format.format(date); - } -} diff --git a/ccm-core/src/main/java/org/libreccm/core/CcmCore.java b/ccm-core/src/main/java/org/libreccm/core/CcmCore.java index a80dddcad..7ee74f25e 100644 --- a/ccm-core/src/main/java/org/libreccm/core/CcmCore.java +++ b/ccm-core/src/main/java/org/libreccm/core/CcmCore.java @@ -43,18 +43,12 @@ import java.util.Properties; */ @Module( configurations = { - com.arsdigita.bebop.BebopConfig.class, - com.arsdigita.dispatcher.DispatcherConfig.class, com.arsdigita.globalization.GlobalizationConfig.class, com.arsdigita.kernel.KernelConfig.class, com.arsdigita.kernel.security.SecurityConfig.class, com.arsdigita.mail.MailConfig.class, com.arsdigita.notification.NotificationConfig.class, - com.arsdigita.templating.TemplatingConfig.class, - com.arsdigita.web.WebConfig.class, com.arsdigita.workflow.simple.WorkflowConfig.class, - com.arsdigita.xml.XmlConfig.class, - com.arsdigita.xml.formatters.DateFormatterConfig.class, org.libreccm.configuration.ExampleConfiguration.class, org.libreccm.files.CcmFilesConfiguration.class, org.libreccm.search.SearchConfig.class, diff --git a/ccm-core/src/main/java/org/libreccm/l10n/GlobalizationHelper.java b/ccm-core/src/main/java/org/libreccm/l10n/GlobalizationHelper.java index 350ec4e34..0108040fa 100644 --- a/ccm-core/src/main/java/org/libreccm/l10n/GlobalizationHelper.java +++ b/ccm-core/src/main/java/org/libreccm/l10n/GlobalizationHelper.java @@ -18,7 +18,6 @@ */ package org.libreccm.l10n; -import com.arsdigita.globalization.GlobalizedMessage; import com.arsdigita.kernel.KernelConfig; import org.apache.logging.log4j.LogManager; diff --git a/ccm-core/src/main/java/org/libreccm/security/ChallengeManager.java b/ccm-core/src/main/java/org/libreccm/security/ChallengeManager.java index 7b8831c44..28316a7d2 100644 --- a/ccm-core/src/main/java/org/libreccm/security/ChallengeManager.java +++ b/ccm-core/src/main/java/org/libreccm/security/ChallengeManager.java @@ -20,8 +20,6 @@ package org.libreccm.security; import com.arsdigita.kernel.KernelConfig; import com.arsdigita.mail.Mail; -import com.arsdigita.web.ParameterMap; -import com.arsdigita.web.URL; import org.apache.commons.lang.text.StrSubstitutor; import org.apache.logging.log4j.LogManager; @@ -37,14 +35,13 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; +import java.util.stream.Collectors; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; - - /** * A service class for managing several so called challenges. These challenges * are using a {@link OneTimeAuthToken} and are used to verify email addresses @@ -343,19 +340,28 @@ public class ChallengeManager { "Unsupported value \"%s\" for purpose.", purpose.toString())); } - values.put("link", - URL.there(request, - "/@login" + path, null) - .getURL()); + values.put("link", path); - final ParameterMap params = new ParameterMap(); - params.setParameter("email", user.getPrimaryEmailAddress().getAddress()); - params.setParameter("token", token.getToken()); - values.put("full_link", - URL.there(request, - "/@login" + path, params) - .getURL()); + final Map params = new HashMap<>(); + params.put("email", user.getPrimaryEmailAddress().getAddress()); + params.put("token", token.getToken()); + values.put( + "full_link", + String.format( + "%s%s", + path, + params + .entrySet() + .stream() + .map( + entry -> String.format( + "%s=%s", entry.getKey(), entry.getValue() + ) + ) + .collect(Collectors.joining("&", "?", "")) + ) + ); values.put("token", token.getToken()); final StrSubstitutor substitutor = new StrSubstitutor(values); @@ -400,7 +406,7 @@ public class ChallengeManager { } else { final KernelConfig kernelConfig = configurationManager .findConfiguration(KernelConfig.class); - final Locale defaultLocale =kernelConfig.getDefaultLocale(); + final Locale defaultLocale = kernelConfig.getDefaultLocale(); return localizedString.getValue(defaultLocale); } } @@ -497,11 +503,11 @@ public class ChallengeManager { /** * Helper method for sending emails. - * - * @param user The user to which the mail is send. + * + * @param user The user to which the mail is send. * @param subject The subject of the mail. - * @param text The text (body) of the mail. - * + * @param text The text (body) of the mail. + * * @throws MessagingException If something goes wrong when sending the mail. */ private void sendMessage(final User user, diff --git a/ccm-core/src/main/java/org/libreccm/ui/admin/systeminformation/SystemInformationModel.java b/ccm-core/src/main/java/org/libreccm/ui/admin/systeminformation/SystemInformationModel.java index 146a31ea1..d68fea798 100644 --- a/ccm-core/src/main/java/org/libreccm/ui/admin/systeminformation/SystemInformationModel.java +++ b/ccm-core/src/main/java/org/libreccm/ui/admin/systeminformation/SystemInformationModel.java @@ -18,7 +18,7 @@ */ package org.libreccm.ui.admin.systeminformation; -import com.arsdigita.util.UncheckedWrapperException; +import org.libreccm.core.UnexpectedErrorException; import java.io.IOException; import java.io.InputStream; @@ -59,7 +59,7 @@ public class SystemInformationModel { // properties.load(getClass().getResourceAsStream( // "WEB-INF/systeminformation.properties")); } catch (IOException ex) { - throw new UncheckedWrapperException(ex); + throw new UnexpectedErrorException(ex); } final Map sysInfo = new HashMap<>(); diff --git a/ccm-core/src/main/resources/META-INF/services/javax.xml.transform.TransformerFactory b/ccm-core/src/main/resources/META-INF/services/javax.xml.transform.TransformerFactory deleted file mode 100644 index 12e3fbdaf..000000000 --- a/ccm-core/src/main/resources/META-INF/services/javax.xml.transform.TransformerFactory +++ /dev/null @@ -1 +0,0 @@ -com.arsdigita.xml.CCMTransformerFactory \ No newline at end of file diff --git a/ccm-core/src/test/java/com/arsdigita/util/AssertTest.java b/ccm-core/src/test/java/com/arsdigita/util/AssertTest.java deleted file mode 100644 index 9d9b7eddf..000000000 --- a/ccm-core/src/test/java/com/arsdigita/util/AssertTest.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (C) 2015 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.util; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -/** - * - * @author Jens Pelzetter - */ -public class AssertTest { - - public AssertTest() { - } - - @BeforeClass - public static void setUpClass() { - } - - @AfterClass - public static void tearDownClass() { - } - - @Before - public void setUp() { - } - - @After - public void tearDown() { - } - - @Test(expected = AssertionError.class) - public void checkFailMessage() { - Assert.fail("errormessage"); - } - - @Test(expected = AssertionError.class) - public void checkFail() { - Assert.fail(); - } - - /** - * Check if {@link Assert#setEnabled(boolean)} works correctly. - */ - @Test - public void assertDisable() { - Assert.setEnabled(false); - - assertThat(Assert.isEnabled(), is(false)); - - Assert.setEnabled(true); - } - - /** - * Check if {@link Assert#isTrue(boolean)} fails if condition evaluates to - * {@code false}. - */ - @Test(expected = AssertionError.class) - public void checkIfIsTrueFails() { - Assert.isTrue(false); - } - - /** - * Check if {@link Assert#isTrue(boolean, java.lang.String)} succeeds if - * condition evaluates to {@code true}. - */ - @Test - public void checkIsTrue() { - Assert.isTrue(true); - } - - /** - * Check if {@link Assert#isTrue(boolean, java.lang.String)} fails if - * condition evaluates to {@code false}. - */ - @Test(expected = AssertionError.class) - public void checkIfIsTrueWithMessageFails() { - Assert.isTrue(false, "Expected true"); - } - - /** - * Check if {@link Assert#isTrue(boolean, java.lang.String)} succeeds if - * condition evaluates to {@code true}. - */ - @Test - public void checkIsTrueWithMessage() { - Assert.isTrue(true, "Expected true"); - } - - @Test(expected = AssertionError.class) - public void checkIfIsFalseFails() { - Assert.isFalse(true); - } - - @Test - public void checkIsFalse() { - Assert.isFalse(false); - } - - @Test(expected = AssertionError.class) - public void checkIfIsFalseWithMessageFails() { - Assert.isFalse(true, "Expected false"); - } - - @Test - public void checkIsFalseWithMessage() { - Assert.isFalse(false, "Expected true"); - } - - @Test(expected = AssertionError.class) - public void checkIfExistsFailsForNull() { - Assert.exists(null); - } - - @Test - public void checkExists() { - Assert.exists("foo"); - } - - @Test(expected = AssertionError.class) - public void checkIfExistsWithClassFailsForNull() { - Assert.exists(null, Object.class); - } - - @Test - public void checkExistsWithClass() { - Assert.exists("foo", Object.class); - } - - @Test(expected = AssertionError.class) - public void checkIfExistsFailsForNullWithMessage() { - Assert.exists(null, "None null object expected"); - } - - @Test - public void checkExistsWithLabel() { - Assert.exists("foo", "label"); - } - - @Test - public void checkExistsWithEmptyLabel() { - Assert.exists("foo", ""); - } - - @Test(expected = AssertionError.class) - public void checkIfIsLockedFails() { - final Lockable unlocked = new LockableImpl(); - - Assert.isLocked(unlocked); - } - - @Test - public void checkIfIsLockedDoesntThrowError() { - Assert.isLocked(null); - } - - @Test(expected = AssertionError.class) - public void checkIfIsUnLockedFails() { - final Lockable locked = new LockableImpl(); - locked.lock(); - - Assert.isUnlocked(locked); - } - - @Test - public void checkIfIsUnLockedDoesntThrowError() { - Assert.isUnlocked(null); - } - - @Test(expected = AssertionError.class) - public void checkIfIsEqualFailsForUnequalObjects() { - Assert.isEqual("foo", "bar"); - } - - @Test(expected = AssertionError.class) - public void checkIfIsEqualFailsForNullAndObject() { - Assert.isEqual(null, "bar"); - } - - @Test(expected = AssertionError.class) - public void checkIfIsEqualFailsForObjectAndNull() { - Assert.isEqual("foo", null); - } - - @Test(expected = AssertionError.class) - public void checkIfIsEqualFailsForObjectAndNullWithMessage() { - Assert.isEqual("foo", null, "second object is null"); - } - - @Test(expected = AssertionError.class) - public void checkIfIsEqualFailsForNullAndObjectWithMessage() { - Assert.isEqual(null, "foo", "first object is null"); - } - - @Test(expected = AssertionError.class) - public void checkIfIsEqualFailsForUnequalObjectsWithMessage() { - Assert.isEqual("foo", "bar", "unequal "); - } - - @Test(expected = AssertionError.class) - public void checkIfIsNotEqualFailsForEqualObjects() { - Assert.isNotEqual("foo", "foo"); - } - - @Test(expected = AssertionError.class) - public void checkIfIsNotEqualFailsIfBothAreNull() { - Assert.isNotEqual(null, null); - } - - @Test(expected = AssertionError.class) - public void checkIfAssertEqualsFailsIfObjectIsNull() { - Assert.assertEquals(null, "bar", "expectedLabel", "actualLabel"); - } - - @Test(expected = AssertionError.class) - public void checkIfAssertEqualsFails() { - Assert.assertEquals("foo", "bar", "expectedLabel", "actualLabel"); - } - - @Test - public void checkAssertEqualsIfNotEnabled() { - Assert.setEnabled(false); - Assert.assertEquals("foo", "bar", "expectedLabel", "actualLabel"); - Assert.setEnabled(true); - } - - @Test - public void checkAssertEqualsIfBothNull() { - Assert.assertEquals(null, null, "expectedLabel", "actualLabel"); - } - - @Test - public void checkAssertEqualsWithEqualObjects() { - Assert.assertEquals("foo", "foo", "expectedLabel", "actualLabel"); - } -} diff --git a/ccm-core/src/test/java/com/arsdigita/util/StringUtilsTest.java b/ccm-core/src/test/java/com/arsdigita/util/StringUtilsTest.java deleted file mode 100644 index 4f1432878..000000000 --- a/ccm-core/src/test/java/com/arsdigita/util/StringUtilsTest.java +++ /dev/null @@ -1,714 +0,0 @@ -/* - * Copyright (C) 2015 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.util; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - - -/** - * - * @author Konermann - */ -public class StringUtilsTest { - - public StringUtilsTest() { - } - - @BeforeClass - public static void setUpClass() { - } - - @AfterClass - public static void tearDownClass() { - } - - @Before - public void setUp() { - } - - @After - public void tearDown() { - } - - @Test - public void testSmartText2() { - String src = "blabla\n" - + "\n" - + "blub"; - - String expected = "
    \n" - + "blabla\n" - + "
    \n" - + "\n" - + "
    \n" - + "blub\n" - + "
    \n"; - String actual = StringUtils.smartTextToHtml(src); - String errMsg = "smartTexttoHtml2, expected = " + expected - + " found = " + actual; - assertEquals(errMsg, expected, actual); - } - -// @Test(expected = AssertionError.class) -// public void checkFailMessage() { -// Assert.fail("errormessage"); -// } - @Test - public void testSmartText() { - String src = "foo *bar* wibble /eek/\n" - + "and mailto:dan@berrange.com eek!\n" - + "\n" - + "the second =paragraph= contains\n" - + "a link to http://www.google.com\n" - + "and the fractions 1/2 3/4 1/4 and\n" - + "the symbols for copyright (C),\n" - + "trademark (TM) and rights (R)\n" - + "\n" - + "* a bullet list\n" - + "* more *bullets* in\n" - + " this list element\n" - + "* a final element\n" - + "\n" - + "-------\n" - + "\n" - + "+ now an enumerated list item\n" - + "+ and one /more/\n" - + "+ this one is split over two lines\n" - + "for testing purposes\n" - + "\n" - + "___\n" - + "\n" - + "and now the end is near, lets test\n" - + "@google(http://www.google.com) a few\n" - + "titled links, including a mailto\n" - + "@Dan B(mailto:dan@@berrange.com)"; - String expected = "
    \n" - + "foo bar wibble eek\n" - + "and mailto:dan@berrange.com eek!\n" - + "
    \n" - + "\n" - + "
    \n" - + "the second paragraph contains\n" - + "a link to http://www.google.com\n" - + "and the fractions ½ ¾ ¼ and\n" - + "the symbols for copyright ©,\n" - + "trademark TM and rights ®\n" - + "
    \n" - + "\n" - + "
      \n" - + "
    • \n" - + "a bullet list\n" - + "
    • \n" - + "
    • \n" - + "more bullets in\n" - + " this list element\n" - + "
    • \n" - + "
    • \n" - + "a final element
    • \n" - + "
    \n" - + "\n" - + "
    \n" - + "\n" - + "
      \n" - + "
    1. \n" - + "now an enumerated list item\n" - + "
    2. \n" - + "
    3. \n" - + "and one more\n" - + "
    4. \n" - + "
    5. \n" - + "this one is split over two lines\n" - + "for testing purposes
    6. \n" - + "
    \n" - + "\n" - + "
    \n" - + "\n" - + "
    \n" - + "and now the end is near, lets test\n" - + "google a few\n" - + "titled links, including a mailto\n" - + "Dan B\n" - + "
    \n"; - String actual = StringUtils.smartTextToHtml(src); - -// assertTrue(expected.equals(actual)); - String errMsg = "smartTexttoHtml, expected = " + expected - + " found = " + actual; - assertEquals(errMsg, expected, actual); - - } - - @Test - public void testSmartTextHR() { - String src = "---"; - - String expected = "
    \n"; - - String actual = StringUtils.smartTextToHtml(src); - String errMsg = "smartTexttoHtml, expected = " + expected - + " found = " + actual; - assertEquals(errMsg, expected, actual); - } - - @Test - public void testSmartTextURL() { - String src = "foo *bar* wibble /eek/\n" - + "and mailto:dan@berrange.com eek!\n" - + "\n" - + "the second =paragraph= contains\n" - + "a link to http://www.google.com\n" - + "and now the end is near, lets test\n" - + "@google(http://www.google.com) a few\n" - + "titled links, including a mailto\n" - + "@Dan B(mailto:dan@@berrange.com)"; - String expected = "
    \n" - + "foo bar wibble eek\n" - + "and mailto:dan@berrange.com eek!\n" - + "
    \n" - + "\n" - + "
    \n" - + "the second paragraph contains\n" - + "a link to http://www.google.com\n" - + "and now the end is near, lets test\n" - + "google a few\n" - + "titled links, including a mailto\n" - + "Dan B\n" - + "
    \n"; - String actual = StringUtils.smartTextToHtml(src); - String errMsg = "smartTexttoHtml, expected = " + expected - + " found = " + actual; - assertEquals(errMsg, expected, actual); - } - - @Test - public void testSmartTextLists() { - String src = "+ now an enumerated list item\n" - + "+ and one /more/\n" - + "+ this one is split over two lines\n" - + "for testing purposes\n"; - - String expected = "
      \n" - + "
    1. \n" - + "now an enumerated list item\n" - + "
    2. \n" - + "
    3. \n" - + "and one more\n" - + "
    4. \n" - + "
    5. \n" - + "this one is split over two lines\n" - + "for testing purposes\n" - + "
    6. \n" - + "
    \n"; - String actual = StringUtils.smartTextToHtml(src); - String errMsg = "smartTexttoHtml, expected = " + expected - + " found = " + actual; - assertEquals(errMsg, expected, actual); - - } - - @Test - public void testSmartTextLists2() { - String src = "* a bullet list\n" - + "* more *bullets* in\n" - + " this list element\n" - + "* a final element\n"; - - String expected = "
      \n" - + "
    • \n" - + "a bullet list\n" - + "
    • \n" - + "
    • \n" - + "more bullets in\n" - + " this list element\n" - + "
    • \n" - + "
    • \n" - + "a final element\n" - + "
    • \n" - + "
    \n"; - String actual = StringUtils.smartTextToHtml(src); - String errMsg = "smartTexttoHtml, expected = " + expected - + " found = " + actual; - assertEquals(errMsg, expected, actual); - - } - - @Test - public void testEmptyString() { - - assertTrue(StringUtils.emptyString(null)); - assertTrue(StringUtils.emptyString("")); - assertTrue(StringUtils.emptyString((Object) "")); - - assertTrue(!StringUtils.emptyString("foo")); - assertTrue(!StringUtils.emptyString((Object) "foo")); - assertTrue(!StringUtils.emptyString((Object) (new Integer(1)))); - - } - - @Test - public void testQuoteHtml() { - - assertEquals("", StringUtils.quoteHtml(null)); - assertEquals("", StringUtils.quoteHtml("")); - assertEquals("foo", StringUtils.quoteHtml("foo")); - assertEquals("foo&", StringUtils.quoteHtml("foo&")); - assertEquals("&foo", StringUtils.quoteHtml("&foo")); - assertEquals("&foo&", StringUtils.quoteHtml("&foo&")); - assertEquals("&"<>"&", - StringUtils.quoteHtml("&\"<>\"&")); - - } - - @Test - public void testGetParameter() throws Exception { - - String plist = "boyspet=play,pet=dog,play=yes,age=34,eopt=,opt=23"; - verifyGet(plist, "boyspet", "play"); - verifyGet(plist, "pet", "dog"); - verifyGet(plist, "play", "yes"); - verifyGet(plist, "age", "34"); - verifyGet(plist, "eopt", ""); - verifyGet(plist, "opt", "23"); - verifyGet(plist, "spet", null); - verifyGet(plist, "notin", null); - } - - // helper method for above test. - private static void verifyGet(String plist, String key, String expected) { - String found = StringUtils.getParameter(key, plist, ','); - assertEquals("Expected parameter not found, key=" + key - + " expected=" + expected + " found=" + found, - expected, found); - } - - @Test - public void testSplit() throws Exception { - - String plist = "cat,hat,,bat,rat"; - String[] ar = StringUtils.split(plist, ','); - verifySplit("cat", ar[0]); - verifySplit("hat", ar[1]); - verifySplit("", ar[2]); - verifySplit("bat", ar[3]); - verifySplit("rat", ar[4]); - assertEquals("expected array length 5, found=" - + ar.length, ar.length, 5); - plist = ",,dog,fish,,,"; - ar = StringUtils.split(plist, ','); - verifySplit("", ar[0]); - verifySplit("", ar[1]); - verifySplit("dog", ar[2]); - verifySplit("fish", ar[3]); - verifySplit("", ar[4]); - verifySplit("", ar[5]); - verifySplit("", ar[6]); - assertEquals("expected array length 7, found=" - + ar.length, ar.length, 7); - - } - - // helper method for above test. - private void verifySplit(String expected, String found) { - String errMsg = "Split, expected = " + expected - + " found = " + found; - assertEquals(errMsg, expected, found); - } - - @Test - public void testSplitUp() { - - String s = "/packages/foo/xsl/::vhost::/foo_::locale::.xsl"; - - List list = new ArrayList(); - list = StringUtils.splitUp(s, "::\\w+::"); -// if you want to see the result: -// assertEquals("splitup:" -// +(String)list.get(0)+", " + -// (String)list.get(1)+", " + -// (String)list.get(2)+", " -// + (String)list.get(3)+", " -// +(String)list.get(4)+", " -// +"sizekram=" -// + list.size(), list.size(), 99); - - verifySplit("/packages/foo/xsl/", (String) list.get(0)); - verifySplit("::vhost::", (String) list.get(1)); - verifySplit("/foo_", (String) list.get(2)); - verifySplit("::locale::", (String) list.get(3)); - verifySplit(".xsl", (String) list.get(4)); - assertEquals("expected array length 5, found=" - + list.size(), list.size(), 5); - } - - @Test - public void testSplitUp2() { - final String path - = "http://::host::/::webapp::/themes/::themedir::/::theme::/start.xsl"; - - @SuppressWarnings("unchecked") - final List list = StringUtils.splitUp(path, "::\\w+::"); - - assertThat(list.size(), is(9)); - assertThat(list.get(0), is(equalTo("http://"))); - assertThat(list.get(1), is(equalTo("::host::"))); - assertThat(list.get(2), is(equalTo("/"))); - assertThat(list.get(3), is(equalTo("::webapp::"))); - assertThat(list.get(4), is(equalTo("/themes/"))); - assertThat(list.get(5), is(equalTo("::themedir::"))); - assertThat(list.get(6), is(equalTo("/"))); - assertThat(list.get(7), is(equalTo("::theme::"))); - assertThat(list.get(8), is(equalTo("/start.xsl"))); - //assertThat(list.get(9), is(equalTo("start.xsl"))); - } - - @Test - public void testSplitUpAtNewLine() { - - String s = "blabla\n\nblub\n"; - - List list = new ArrayList(); - list = StringUtils.splitUpAtNewLine(s); -// if you want to see the result: -// assertEquals("splitup:" -// +(String)list.get(0)+", " + -// (String)list.get(1)+", " + -// (String)list.get(2)+", " -// + (String)list.get(3)+", " -// +(String)list.get(4)+", " -// +"sizekram=" -// + list.size(), list.size(), 99); - - verifySplit("blabla", (String) list.get(0)); - verifySplit("\n", (String) list.get(1)); - verifySplit("blub\n", (String) list.get(2)); - assertEquals("expected array length 3, found=" - + list.size(), list.size(), 3); - - } - - @Test - public void testJoinChar() { - - String[] input = {"foo", "bar", "Qux"}; - String expected = "foo,bar,Qux"; - String found = StringUtils.join(input, ','); - String errMsg = "join char, expected = " + expected - + " found = " + found; - assertEquals(errMsg, expected, found); - - } - - @Test - public void testJoinString() { - - String[] input = {"foo", "bar", "Qux"}; - String expected = "foo,bar,Qux"; - String found = StringUtils.join(input, ","); - String errMsg = "join string, expected = " + expected - + " found = " + found; - assertEquals(errMsg, expected, found); - } - - @Test - public void testStripWhiteSpace() throws Exception { - - String in = " < H> e \t\n ll/> o . \n "; - String expected_out = "< H> e ll/> o ."; - String actual_out = StringUtils.stripWhiteSpace(in); - assertEquals("stripWhiteSpace failed. Expected = '" - + expected_out + "', Found = '" + actual_out + "'", - expected_out, actual_out); - - } - - @Test - public void testAddNewline() throws Exception { - String in = "*"; - String nl = System.getProperty("line.separator"); - - String expected_out = in + nl; - String actual_out = StringUtils.addNewline(in); - assertEquals("failed to add newline", expected_out, actual_out); - - in = "* "; - expected_out = in; - actual_out = StringUtils.addNewline(in); - assertEquals("added unecessary newline", expected_out, actual_out); - - in = "*" + nl; - expected_out = in; - actual_out = StringUtils.addNewline(in); - assertEquals("added unecessary newline", expected_out, actual_out); - - in = "" + nl; - expected_out = in; - actual_out = StringUtils.addNewline(in); - assertEquals("added unecessary newline", expected_out, actual_out); - } - - @Test - public void testHtmlToText() { - - String in = "

    this is the text
    newline .

    one
    two
    "; - String expected_out = "\n\nthis is the text\nnewline . one\n two \n"; - String actual_out = StringUtils.htmlToText(in); - - String errMsg = "htmlToText, expected = " + expected_out - + " found = " + actual_out; - - assertEquals(errMsg, expected_out, actual_out); - - in = "Text with strange markup"; - expected_out = "Text with strange markup"; - actual_out = StringUtils.htmlToText(in); - - errMsg = "htmlToText, expected = " + expected_out - + " found = " + actual_out; - assertEquals(errMsg, expected_out, actual_out); - } - - @Test - public void testTrimleft() { - String in = "a"; - String expected_out = "a"; - String actual_out = StringUtils.trimleft(in); - assertEquals("trimleft invalid", expected_out, actual_out); - - in = " a"; - expected_out = "a"; - actual_out = StringUtils.trimleft(in); - assertEquals("trimleft invalid", expected_out, actual_out); - - in = " "; - expected_out = ""; - actual_out = StringUtils.trimleft(in); - assertEquals("trimleft invalid", expected_out, actual_out); - } - - @Test - public void testRepeat() { - String in = "a"; - String expected_out = "aaaaa"; - String actual_out = StringUtils.repeat(in, 5); - assertEquals("repeat invalid", expected_out, actual_out); - - actual_out = StringUtils.repeat('a', 5); - assertEquals("repeat invalid", expected_out, actual_out); - } - - @Test - public void testWrap() { - - // Identity test - String in = "a\n"; - String expected_out = in; - String actual_out = StringUtils.wrap(in); - assertEquals("wrap failed identify test", - expected_out, - actual_out); - - // Identify test with multiple words - in = "a b c d e\n"; - expected_out = in; - actual_out = StringUtils.wrap(in); - assertEquals("wrap failed identify test", - expected_out, - actual_out); - - // Simple test with short lines - in = StringUtils.repeat("1234 ", 5); - expected_out = StringUtils.repeat("1234\n", 5); - actual_out = StringUtils.wrap(in, 1); - assertEquals("wrap invalid", - expected_out, - actual_out); - - // Verify preservation of line breaks - in = StringUtils.repeat("1234\n", 5); - expected_out = in; - actual_out = StringUtils.wrap(in, 100); - assertEquals("line break preservation failed", - expected_out, - actual_out); - - // Verify a "standard" wrapping case - in = StringUtils.repeat("1234 ", 10); - expected_out - = StringUtils.repeat("1234 ", 5).trim() + "\n" - + StringUtils.repeat("1234 ", 5).trim() + "\n"; - - actual_out = StringUtils.wrap(in, 25); - assertEquals("line wrapping failed", - expected_out, - actual_out); - } - - @Test - public void testInterpolate() { - String in = "foo ::bar:: wizz"; - String expected_out = "foo eek wizz"; - String actual_out = StringUtils.interpolate(in, "bar", "eek"); - - assertEquals("interpolate failed simple placeholder", - expected_out, - actual_out); - - HashMap vars = new HashMap(); - vars.put("bar", "eek"); - vars.put("more", "wibble"); - - in = "foo ::bar:: wizz ::more:: done"; - expected_out = "foo eek wizz wibble done"; - actual_out = StringUtils.interpolate(in, vars); - assertEquals("interpolate failed hashmap test", - expected_out, - actual_out); - - } - - @Test - public void testReplace() { - String[] pairs = {null, null, - "foobar", "foobar", - ";foobar", "\\;foobar", - ";foo;bar;baz", "\\;foo\\;bar\\;baz", - ";;foobar", "\\;\\;foobar", - "f;o;obar", "f\\;o\\;obar", - "f;o;;bar", "f\\;o\\;\\;bar", - "foobar;", "foobar\\;", - "foobar;;", "foobar\\;\\;"}; - - for (int ii = 0, jj = 1; jj < pairs.length; ii += 2, jj += 2) { - System.err.println("ii=" + ii + ", pairs[ii]=" + pairs[ii] - + ", jj=" + jj + ", pairs[jj]=" + pairs[jj]); - String expected = pairs[jj]; - String actual = StringUtils.replace(pairs[ii], ";", "\\;"); - assertEquals(expected, actual); - - expected = pairs[ii]; - actual = StringUtils.replace(pairs[jj], "\\;", ";"); - assertEquals(expected, actual); - } - } - -// @Test -// public void testSmartTextReplace(){ -// String src = "this is the original text"; -// String expected = "this is the expected text"; -// String actual = StringUtils.smartTextReplace("original","original",src); -// } - @Test - public void testUrlize() { - assertEquals(null, StringUtils.urlize(null)); - assertEquals("", StringUtils.urlize("")); - assertEquals("-", StringUtils.urlize(" ")); - assertEquals("----", StringUtils.urlize(" ")); - assertEquals("abc-def", StringUtils.urlize("ABC DEF")); - assertEquals("-abc-def-", StringUtils.urlize(" ABC DEF ")); - assertEquals( - "0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz-_---", - StringUtils.urlize( - "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_ &/")); - assertEquals("helpaplawsorg", StringUtils.urlize("help@aplaws.org")); - } - - @Test - public void testIsAlphaNumeric() { - assertTrue(StringUtils.isAlphaNumeric("foo")); - assertTrue(StringUtils.isAlphaNumeric("123")); - assertTrue(StringUtils.isAlphaNumeric("bar778")); - - assertFalse(StringUtils.isAlphaNumeric("foo/bar")); - assertFalse(StringUtils.isAlphaNumeric("&")); - } - - @Test - public void testTruncateString() { - assertThat(StringUtils.truncateString("Lorem ipsum dolor sit amet", 8, - true), is("Lorem")); - assertThat(StringUtils.truncateString("Lorem ipsum dolor sit amet", 2, - true), is("Lo")); - assertThat(StringUtils.truncateString(null, 2, true), is("")); - assertThat(StringUtils.truncateString( - "Lorem ipsum dolor sit amet", 12, true), is("Lorem")); - assertThat(StringUtils.truncateString( - "Lorem ipsum dolor sit amet", 12, false), is("Lorem ")); - assertThat(StringUtils.truncateString("Lorem ipsum dolor sit amet", 99, - true), is( - "Lorem ipsum dolor sit amet")); - } - - @Test - public void testJoinElements() { - - List input = new ArrayList<>(); - input.add("foo"); - input.add("bar"); - input.add("Qux"); - String expected = "foo,bar,Qux"; - String found = StringUtils.join(input, ","); - String errMsg = "join Elements, expected = " + expected - + " found = " + found; - assertEquals(errMsg, expected, found); - } - - @Test(expected = IllegalArgumentException.class) - public void testIfGetStackTraceFails() { - StringUtils.getStackTrace(null); - } - - @Test - public void testStripNewLines() { - - assertEquals(StringUtils.stripNewLines("line1\nline2"), "line1line2"); - assertEquals(StringUtils.stripNewLines("Lorem ipsum dolor sit amet"), - "Lorem ipsum dolor sit amet"); - } - - @Test - public void testNullToEmptyString() { - assertEquals(StringUtils.nullToEmptyString(null), ""); - assertEquals(StringUtils.nullToEmptyString("foo"), "foo"); - } - - @Test - - public void testTextToHtml() { - - assertEquals(StringUtils.textToHtml("line1\nline2"), "line1
    line2"); - assertEquals(StringUtils.textToHtml("line1\n\nline2"), "line1

    line2"); - } - -} diff --git a/ccm-core/src/test/java/com/arsdigita/web/WebConfigTest.java b/ccm-core/src/test/java/com/arsdigita/web/WebConfigTest.java deleted file mode 100644 index ac6c1c7e8..000000000 --- a/ccm-core/src/test/java/com/arsdigita/web/WebConfigTest.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (C) 2016 LibreCCM Foundation. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package com.arsdigita.web; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.ArrayList; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; - -/** - * - * @author Jens Pelzetter - */ -public class WebConfigTest { - - public WebConfigTest() { - } - - @BeforeClass - public static void setUpClass() { - } - - @AfterClass - public static void tearDownClass() { - } - - @Before - public void setUp() { - } - - @After - public void tearDown() { - } - - @Test - public void setValidResolver() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setResolverClass(DefaultApplicationFileResolver.class - .getName()); - - assertThat(webConfig.getResolverClass(), - is(equalTo(DefaultApplicationFileResolver.class.getName()))); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidResolver() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setResolverClass(ArrayList.class.getName()); - - } - - @Test(expected = IllegalArgumentException.class) - public void setNotExistingResolver() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setResolverClass("org.example.resolvers.NotExisting"); - } - - @Test - public void setValidHost() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setHost("zeus.example.org:8080"); - - assertThat(webConfig.getHost(), - is(equalTo("zeus.example.org:8080"))); - assertThat(webConfig.getHostName(), - is(equalTo("zeus.example.org"))); - assertThat(webConfig.getHostPort(), - is(equalTo(8080))); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidHostWithSchema() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setHost("http://zeus.example.org:8080"); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidHostWithoutPort() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setHost("http://zeus.example.org"); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidHostLongPort() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setHost("http://zeus.example.org:999999"); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidHostWithPath() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setHost("http://zeus.example.org:8080/foo"); - } - - @Test - public void setValidServer() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setServer("zeus.example.org:8080"); - - assertThat(webConfig.getServer(), - is(equalTo("zeus.example.org:8080"))); - assertThat(webConfig.getServerName(), - is(equalTo("zeus.example.org"))); - assertThat(webConfig.getServerPort(), - is(equalTo(8080))); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidServerWithSchema() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setServer("http://zeus.example.org:8080"); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidServerWithoutPort() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setServer("http://zeus.example.org"); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidServerLongPort() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setServer("http://zeus.example.org:999999"); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidServerWithPath() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setServer("http://zeus.example.org:8080/foo"); - } - - @Test - public void setValidSecureServer() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setSecureServer("zeus.example.org:8080"); - - assertThat(webConfig.getSecureServer(), - is(equalTo("zeus.example.org:8080"))); - assertThat(webConfig.getSecureServerName(), - is(equalTo("zeus.example.org"))); - assertThat(webConfig.getSecureServerPort(), - is(equalTo(8080))); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidSecureServerWithSchema() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setSecureServer("http://zeus.example.org:8080"); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidSecureServerWithoutPort() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setSecureServer("http://zeus.example.org"); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidSecureLongPort() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setSecureServer("http://zeus.example.org:999999"); - } - - @Test(expected = IllegalArgumentException.class) - public void setInvalidSecureServerWithPath() { - final WebConfig webConfig = new WebConfig(); - - webConfig.setSecureServer("http://zeus.example.org:8080/foo"); - } - -}