code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.xmltest;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Composite;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Item;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.xmlui.wing.element.Instance;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* This is a class to test the advanced form capabilities of DRI.
* All the fields on this page will either be composite or have
* multiple instances.
*
* This class is not internationalized because it is never intended
* to be used in production. It is merely a tool to aid developers of
* aspects and themes.
*
* @author Scott Phillips
*/
public class AdvancedFormTest extends AbstractDSpaceTransformer {
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException {
pageMeta.addMetadata("title").addContent("Advanced Form Test");
pageMeta.addTrailLink(contextPath + "/", "DSpace Home");
pageMeta.addTrail().addContent("Advanced Form Test");
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException {
Request request = ObjectModelHelper.getRequest(objectModel);
boolean help = false, error = false;
if (request.getParameter("help") != null)
{
help = true;
}
if (request.getParameter("error") != null)
{
error = true;
}
Division div = body.addInteractiveDivision("test", "", "post", "primary");
div.setHead("Advanced form test");
div.addPara("There are two options you can use to control how this page is generated. First is the help parameter, if this is present then help text will be provided for all fields. Next is the error parameter, if it is provided then all fields will be generated in error conditions.");
if (help)
{
div.addPara().addXref(makeURL(false, error), "Turn help OFF");
}
else
{
div.addPara().addXref(makeURL(true, error), "Turn help ON");
}
if (error)
{
div.addPara().addXref(makeURL(help, false), "Turn errors OFF");
}
else
{
div.addPara().addXref(makeURL(help, true), "Turn errors ON");
}
List list = div.addList("fieldTest",List.TYPE_FORM);
list.setHead("Tests");
// text
Text text = list.addItem().addText("text");
text.setLabel("Text");
text.enableAddOperation();
text.enableDeleteOperation();
if (help)
{
text.setHelp("This is helpfull text.");
}
if (error)
{
text.addError("This field is in error.");
}
text.setValue("First is special");
Instance instance = text.addInstance();
instance.setValue("Second raw");
instance.setInterpretedValue("Second interpreted");
instance = text.addInstance();
instance.setValue("Third raw");
instance.setInterpretedValue("Third interpreted");
// Select
Select select = list.addItem().addSelect("select");
select.setLabel("Text");
select.enableAddOperation();
select.enableDeleteOperation();
select.setMultiple();
select.setSize(4);
if (help)
{
select.setHelp("This is helpfull text.");
}
if (error)
{
select.addError("This field is in error.");
}
select.addOption("one", "uno");
select.addOption("two", "dos");
select.addOption("three", "tres");
select.addOption("four", "cuatro");
select.addOption("five", "cinco");
instance = select.addInstance();
instance.setOptionSelected("one");
instance = select.addInstance();
instance.setOptionSelected("one");
instance.setOptionSelected("two");
instance = select.addInstance();
instance.setOptionSelected("one");
instance.setOptionSelected("two");
instance.setOptionSelected("three");
instance = select.addInstance();
instance.setOptionSelected("one");
instance.setOptionSelected("two");
instance.setOptionSelected("three");
instance.setOptionSelected("four");
instance = select.addInstance();
instance.setOptionSelected("one");
instance.setOptionSelected("two");
instance.setOptionSelected("three");
instance.setOptionSelected("four");
instance.setOptionSelected("five");
// composite two text fields
Composite composite = list.addItem().addComposite("compositeA");
composite.setLabel("Composite (two text fields)");
composite.enableAddOperation();
composite.enableDeleteOperation();
if (help)
{
composite.setHelp("This field is composed of two text fields, fill them both in.");
}
if (error)
{
composite.addError("Just the composite is in error.");
}
text = composite.addText("firstA");
if (help)
{
text.setHelp("This is helpfull text.");
}
text.addInstance().setValue("1, Raw A");
text.addInstance().setValue("2, Raw A");
text.addInstance().setValue("3, Raw A");
text = composite.addText("secondA");
if (help)
{
text.setHelp("This is helpfull text.");
}
text.addInstance().setValue("1, Raw B");
text.addInstance().setValue("2, Raw B");
text.addInstance().setValue("3, Raw B");
// composite select & text fields
composite = list.addItem().addComposite("compositeB");
composite.setLabel("Composite (select & text fields)");
composite.enableAddOperation();
composite.enableDeleteOperation();
if (help)
{
composite.setHelp("This field is composed of a select and text field, select one and type the other.");
}
select = composite.addSelect("selectB");
if (help)
{
select.setHelp("Me, me, me..... select me!");
}
if (error)
{
select.addError("The composite elements are in error.");
}
select.addOption("one","uno");
select.addOption("two","dos");
select.addOption("three","tres");
select.addOption("four","cuatro");
select.addOption("five","cinco");
select.setOptionSelected("one");
select.addInstance().addOptionValue("one");
select.addInstance().addOptionValue("two");
select.addInstance().addOptionValue("three");
text = composite.addText("TextB");
if (help)
{
text.setHelp("Yay, yet another text field");
}
if (error)
{
text.addError("The composite elements are in error.");
}
text.addInstance().setValue("1, Raw B");
text.addInstance().setValue("2, Raw B");
text.addInstance().setValue("3, Raw B");
composite.addInstance().setInterpretedValue("One interpreted.");
composite.addInstance().setInterpretedValue("Two interpreted.");
composite.addInstance().setInterpretedValue("Three interpreted.");
// Composite (date)
composite = list.addItem().addComposite("composite-date");
composite.setLabel("Composite (date)");
composite.enableAddOperation();
composite.enableDeleteOperation();
if (help)
{
composite.setHelp("The date when something happened.");
}
if (error)
{
composite.setHelp("The composite is in error.");
}
text = composite.addText("day");
if (help)
{
text.setHelp("day");
}
if (error)
{
text.setHelp("The first text field is in error.");
}
text.setSize(4,2);
text.addInstance().setValue("1");
text.addInstance().setValue("2");
text.addInstance().setValue("3");
text.addInstance().setValue("4");
text.addInstance().setValue("5");
select = composite.addSelect("month");
if (error)
{
select.setHelp("The select box is in error.");
}
select.addOption("","(Select Month)");
select.addOption(1,"January");
select.addOption(2,"Feburary");
select.addOption(3,"March");
select.addOption(4,"April");
select.addOption(5,"May");
select.addOption(6,"June");
select.addOption(7,"July");
select.addOption(8,"August");
select.addOption(9,"September");
select.addOption(10,"August");
select.addOption(11,"October");
select.addOption(12,"November");
select.addOption(13,"December");
select.addInstance().setOptionSelected(1);
select.addInstance().setOptionSelected(2);
select.addInstance().setOptionSelected(3);
select.addInstance().setOptionSelected(4);
select.addInstance().setOptionSelected(5);
text = composite.addText("year");
text.setSize(4,4);
if (help)
{
text.setHelp("year");
}
if (error)
{
text.setHelp("The second text field is in error.");
}
text.addInstance().setValue("2001");
text.addInstance().setValue("2002");
text.addInstance().setValue("2003");
text.addInstance().setValue("2004");
text.addInstance().setValue("2005");
// Buttons one typical finds at the end of forums
Item actions = list.addItem();
actions.addButton("submit_save").setValue("Save");
actions.addButton("submit_cancel").setValue("Cancel");
}
/**
* Helpfull method to generate the return url to this page given the
* error & help parameters.
*/
private String makeURL(boolean help, boolean error)
{
if (help && error)
{
return "?help&error";
}
if (help)
{
return "?help";
}
if (error)
{
return "?error";
}
return "?neither";
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.xmltest;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Button;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Composite;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.File;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Radio;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.xmlui.wing.element.TextArea;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* This is a class to test the use of form fields inline with normal
* paragraaphs, lists, or tables. Any other location besides forms.
*
* This class is not internationalized because it is never intended
* to be used in production. It is merely a tool to aid developers of
* aspects and themes.
*
* @author Scott Phillips
*/
public class InlineFormTest extends AbstractDSpaceTransformer
{
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent("Inline Form Test");
pageMeta.addTrailLink(contextPath + "/","DSpace Home");
pageMeta.addTrail().addContent("Inline form test");
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Request request = ObjectModelHelper.getRequest(objectModel);
boolean help = false, error = false;
if (request.getParameter("help") != null)
{
help = true;
}
if (request.getParameter("error") != null)
{
error = true;
}
Division div = body.addInteractiveDivision("test", "", "post", "primary");
div.setHead("Inline form test");
div.addPara("There are two options you can use to control how this page is generated. First is the help parameter, if this is present then help text will be provided for all fields. Next is the error parameter, if it is provided then all fields will be generated in error conditions.");
if (help)
{
div.addPara().addXref(makeURL(false, error), "Turn help OFF");
}
else
{
div.addPara().addXref(makeURL(true, error), "Turn help ON");
}
if (error)
{
div.addPara().addXref(makeURL(help, false), "Turn errors OFF");
}
else
{
div.addPara().addXref(makeURL(help, true), "Turn errors ON");
}
Division suited = body.addDivision("suited");
suited.setHead("Fields suited towards being used inline");
suited.addPara("Below are a list of embedded fields that are normally considered usefully in an inline context.");
// Text field
Para p = suited.addPara();
p.addContent("This is a plain 'Text' field, ");
Text text = p.addText("text");
text.setLabel("Text");
if (help)
{
text.setHelp("This is helpfull text.");
}
if (error)
{
text.addError("This field is in error.");
}
text.setValue("Current raw value");
p.addContent(", embedded in a paragraph.");
// Single Checkbox field
p = suited.addPara();
p.addContent("This is a singe 'CheckBox' field, ");
CheckBox checkBox = p.addCheckBox("yes-or-no");
if (help)
{
checkBox.setHelp("Select either yes or no.");
}
if (error)
{
checkBox.addError("You are incorrect, try again.");
}
checkBox.setLabel("Yes or no");
checkBox.addOption("yes");
p.addContent(", embedded in a paragraph.");
// File
p = suited.addPara();
p.addContent("This is a 'File' field, ");
File file = p.addFile("file");
file.setLabel("File");
if (help)
{
file.setHelp("Upload a file.");
}
if (error)
{
file.addError("This field is in error.");
}
p.addContent(", embedded in a paragraph.");
// Select (single)
p = suited.addPara();
p.addContent("This is single 'Select' (aka dropdown) field, ");
Select select = p.addSelect("select");
select.setLabel("Select (single)");
if (help)
{
select.setHelp("Select one of the options");
}
if (error)
{
select.addError("This field is in error.");
}
select.addOption("one","uno");
select.addOption("two","dos");
select.addOption("three","tres");
select.addOption("four","cuatro");
select.addOption("five","cinco");
select.setOptionSelected("one");
p.addContent(", embedded in a paragraph.");
// Button
p = suited.addPara();
p.addContent("This is a 'Button' field, ");
Button button = p.addButton("button");
button.setLabel("Button");
button.setValue("When you touch me I do things, lots of things");
if (help)
{
button.setHelp("Submit buttons allow the user to submit the form.");
}
if (error)
{
button.addError("This button is in error.");
}
p.addContent(", embedded in a paragraph.");
Division unsuited = body.addDivision("unsuited");
unsuited.setHead("Fields typicaly unsuited towards being used inline");
unsuited.addPara("Below are a list of embedded fields that are normally considered useless in an inline context. This is because there widgets normally cross multiple lines making them hard to render inline. However these are all legal, but perhaps not advisable, and in some circumstances may be needed.");
// Text Area Field
p = unsuited.addPara();
p.addContent("This is a 'Text Area' field, ");
TextArea textArea = p.addTextArea("textarea");
textArea.setLabel("Text Area");
if (help)
{
textArea.setHelp("This is helpfull text.");
}
if (error)
{
textArea.addError("This field is in error.");
}
textArea.setValue("This is the raw value");
p.addContent(", embedded in a paragraph.");
// Multi-option Checkbox field
p = unsuited.addPara();
p.addContent("This is a multi-option 'CheckBox' field, ");
checkBox = p.addCheckBox("fruit");
if (help)
{
checkBox.setHelp("Select all the fruits that you like to eat");
}
if (error)
{
checkBox.addError("You are incorrect you actualy do like Tootse Rolls.");
}
checkBox.setLabel("fruits");
checkBox.addOption("apple","Apples");
checkBox.addOption(true,"orange","Oranges");
checkBox.addOption("pear","Pears");
checkBox.addOption("tootsie","Tootsie Roll");
checkBox.addOption(true,"cherry","Cherry");
p.addContent(", embedded in a paragraph.");
// multi-option Radio field
p = unsuited.addPara();
p.addContent("This is a multi-option 'Radio' field, ");
Radio radio = p.addRadio("sex");
radio.setLabel("Football colors");
if (help)
{
radio.setHelp("Select the colors of the best (college) football team.");
}
if (error)
{
radio.addError("Error, Maroon & White is the only acceptable answer.");
}
radio.addOption("ut","Burnt Orange & White");
radio.addOption(true,"tamu","Maroon & White");
radio.addOption("ttu","Tech Red & Black");
radio.addOption("baylor","Green & Gold");
radio.addOption("rice","Blue & Gray");
radio.addOption("uh","Scarlet Red & Albino White");
p.addContent(", embedded in a paragraph.");
// Select (multiple)
p = unsuited.addPara();
p.addContent("This is multiple 'Select' field, ");
select = p.addSelect("multi-select");
select.setLabel("Select (multiple)");
select.setMultiple();
select.setSize(4);
if (help)
{
select.setHelp("Select one or more options");
}
if (error)
{
select.addError("This field is in error.");
}
select.addOption("one","uno");
select.addOption("two","dos");
select.addOption("three","tres");
select.addOption("four","cuatro");
select.addOption("five","cinco");
select.setOptionSelected("one");
select.setOptionSelected("three");
select.setOptionSelected("five");
p.addContent(", embedded in a paragraph.");
// Composite
p = unsuited.addPara();
p.addContent("This is a 'Composite' field of two text fields, ");
Composite composite = p.addComposite("composite-2text");
composite.setLabel("Composite (two text fields)");
if (help)
{
composite.setHelp("I am the help for the entire composite");
}
if (error)
{
composite.addError("Just the composite is in error");
}
text = composite.addText("partA");
text.setLabel("Part A");
text.setValue("Value for part A");
if (help)
{
text.setHelp("Part A");
}
text = composite.addText("partB");
text.setLabel("Part B");
text.setValue("Value for part B");
if (help)
{
text.setHelp("Part B");
}
p.addContent(", embedded in a paragraph.");
}
/**
* Helpfull method to generate the return url to this page given the
* error & help parameters.
*/
private String makeURL(boolean help, boolean error)
{
if (help && error)
{
return "?help&error";
}
if (help)
{
return "?help";
}
if (error)
{
return "?error";
}
return "?neither";
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.viewArtifacts;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.util.Util;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
/**
* This transform applys the basic navigational links that should be available
* on all pages generated by DSpace.
*
* @author Scott Phillips
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
*/
public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent {
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey() {
try {
Request request = ObjectModelHelper.getRequest(objectModel);
String key = request.getScheme() + request.getServerName() + request.getServerPort() + request.getSitemapURI() + request.getQueryString();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
{
key += "-" + dso.getHandle();
}
return HashUtil.hash(key);
}
catch (SQLException sqle)
{
// Ignore all errors and just return that the component is not cachable.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The cache is always valid.
*/
public SourceValidity getValidity() {
return NOPValidity.SHARED_INSTANCE;
}
public void addOptions(Options options) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
/* Create skeleton menu structure to ensure consistent order between aspects,
* even if they are never used
*/
options.addList("browse");
options.addList("account");
options.addList("context");
options.addList("administrative");
}
/**
* Insure that the context path is added to the page meta.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
// FIXME: I don't think these should be set here, but there needed and I'm
// not sure where else it could go. Perhaps the linkResolver?
Request request = ObjectModelHelper.getRequest(objectModel);
pageMeta.addMetadata("contextPath").addContent(contextPath);
pageMeta.addMetadata("request","queryString").addContent(request.getQueryString());
pageMeta.addMetadata("request","scheme").addContent(request.getScheme());
pageMeta.addMetadata("request","serverPort").addContent(request.getServerPort());
pageMeta.addMetadata("request","serverName").addContent(request.getServerName());
pageMeta.addMetadata("request","URI").addContent(request.getSitemapURI());
String dspaceVersion = Util.getSourceVersion();
if (dspaceVersion != null)
{
pageMeta.addMetadata("dspace","version").addContent(dspaceVersion);
}
String analyticsKey = ConfigurationManager.getProperty("xmlui.google.analytics.key");
if (analyticsKey != null && analyticsKey.length() > 0)
{
analyticsKey = analyticsKey.trim();
pageMeta.addMetadata("google","analytics").addContent(analyticsKey);
}
// add metadata for OpenSearch auto-discovery links if enabled
if (ConfigurationManager.getBooleanProperty("websvc.opensearch.autolink"))
{
pageMeta.addMetadata("opensearch", "shortName").addContent(
ConfigurationManager.getProperty("websvc.opensearch.shortname"));
pageMeta.addMetadata("opensearch", "context").addContent(
ConfigurationManager.getProperty("websvc.opensearch.svccontext"));
}
pageMeta.addMetadata("page","contactURL").addContent(contextPath + "/contact");
pageMeta.addMetadata("page","feedbackURL").addContent(contextPath + "/feedback");
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
{
if (dso instanceof Item)
{
pageMeta.addMetadata("focus","object").addContent("hdl:"+dso.getHandle());
this.getObjectManager().manageObject(dso);
dso = ((Item) dso).getOwningCollection();
}
if (dso instanceof Collection || dso instanceof Community)
{
pageMeta.addMetadata("focus","container").addContent("hdl:"+dso.getHandle());
this.getObjectManager().manageObject(dso);
}
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
/**
* A set of static utilities to help with EPerson workflows.
*
* @author Scott Phillips
*/
public class EPersonUtils
{
/**
* Create a progress list for the registration workflow.
*
* @param form The division of the current workflow step.
* @param step The current step of the workflow (-1 if no step)
*
*/
public static void registrationProgressList(Division form, int step) throws WingException
{
List progress = form.addList("registration-progress",
List.TYPE_PROGRESS);
new Message("default","xmlui.EPerson.EPersonUtils.register_verify_email");
progress.addItem("register-verify-email", render(step, 1)).addContent(
new Message("default","xmlui.EPerson.EPersonUtils.register_verify_email"));
progress.addItem("register-create-profile", render(step, 2)).addContent(
new Message("default","xmlui.EPerson.EPersonUtils.register_create_profile"));
progress.addItem("register-finished", render(step, 3)).addContent(
new Message("default","xmlui.EPerson.EPersonUtils.register_finished"));
}
/**
* Create a progress list for the forgot password workflow.
*
* @param form The division of the current workflow step
* @param step The current step of the workflow (-1 if no step)
*/
public static void forgottProgressList(Division form, int step) throws WingException
{
List progress = form.addList("forgot-password-progress",
List.TYPE_PROGRESS);
progress.addItem("forgot-verify-email", render(step, 1)).addContent(
new Message("default","xmlui.EPerson.EPersonUtils.forgot_verify_email"));
progress.addItem("forgot-reset-passowrd", render(step, 2)).addContent(
new Message("default","xmlui.EPerson.EPersonUtils.forgot_reset_password"));
progress.addItem("forgot-finished", render(step, 3)).addContent(
new Message("default","xmlui.EPerson.EPersonUtils.forgot_finished"));
}
private static String render(int givenStep, int step)
{
if (givenStep == step)
{
return "current";
}
else
{
return null;
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.authenticate.AuthenticationMethod;
import org.dspace.core.ConfigurationManager;
/**
* When only one login method is defined in the dspace.cfg file this class will
* redirect to the URL provided by that AuthenticationMethod class
*
* @author Jay Paz
* @author Scott Phillips
*
*/
public class LoginRedirect extends AbstractAction {
public Map act(Redirector redirector, SourceResolver resolver,
Map objectModel, String source, Parameters parameters)
throws Exception {
final HttpServletResponse httpResponse = (HttpServletResponse) objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
final HttpServletRequest httpRequest = (HttpServletRequest) objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
final Iterator<AuthenticationMethod> authMethods = AuthenticationManager
.authenticationMethodIterator();
if (authMethods == null)
{
throw new IllegalStateException(
"No explicit authentication methods found when exactly one was expected.");
}
AuthenticationMethod authMethod = null;
while (authMethods.hasNext())
{
AuthenticationMethod currAuthMethod = authMethods.next();
if (currAuthMethod.loginPageURL(ContextUtil
.obtainContext(objectModel), httpRequest, httpResponse) != null)
{
if (authMethod != null)
{
throw new IllegalStateException(
"Multiple explicit authentication methods found when only one was expected.");
}
authMethod = currAuthMethod;
}
}
final String url = ((AuthenticationMethod) authMethod).loginPageURL(
ContextUtil.obtainContext(objectModel), httpRequest,
httpResponse);
// now we want to check for the force ssl property
if (ConfigurationManager.getBooleanProperty("xmlui.force.ssl")) {
if (!httpRequest.isSecure()) {
StringBuffer location = new StringBuffer("https://");
location.append(ConfigurationManager.getProperty("dspace.hostname")).append(url).append(
httpRequest.getQueryString() == null ? ""
: ("?" + httpRequest.getQueryString()));
httpResponse.sendRedirect(location.toString());
} else {
httpResponse.sendRedirect(url);
}
} else {
httpResponse.sendRedirect(url);
}
return new HashMap();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.sitemap.PatternException;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
/**
* Attempt to authenticate the user based upon their presented shibboleth credentials.
* This action uses the http parameters as supplied by Shibboleth SP.
* Read dspace.cfg for configuration detail.
*
* If the authentication attempt is successfull then an HTTP redirect will be
* sent to the browser redirecting them to their original location in the
* system before authenticated or if none is supplied back to the DSpace
* homepage. The action will also return true, thus contents of the action will
* be excuted.
*
* If the authentication attempt fails, the action returns false.
*
* Example use:
*
* <map:act name="Shibboleth">
* <map:serialize type="xml"/>
* </map:act>
* <map:transform type="try-to-login-again-transformer">
*
* @author <a href="mailto:bliong@melcoe.mq.edu.au">Bruc Liong, MELCOE</a>
*/
public class ShibbolethAction extends AbstractAction
{
/**
* Attempt to authenticate the user.
*/
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel,
String source, Parameters parameters) throws Exception
{
try
{
//rely on implicit authN of Shib
Context context = AuthenticationUtil.authenticate(objectModel, null, null, null);
EPerson eperson = null;
if(context != null)
{
eperson = context.getCurrentUser();
}
if (eperson != null)
{
Request request = ObjectModelHelper.getRequest(objectModel);
// The user has successfully logged in
String redirectURL = request.getContextPath();
if (AuthenticationUtil.isInterupptedRequest(objectModel))
{
// Resume the request and set the redirect target URL to
// that of the originaly interrupted request.
redirectURL += AuthenticationUtil.resumeInterruptedRequest(objectModel);
}
else
{
// Otherwise direct the user to the login page
String loginRedirect = ConfigurationManager.getProperty("xmlui.user.loginredirect");
redirectURL += (loginRedirect != null) ? loginRedirect.trim() : "";
}
// Authentication successfull send a redirect.
final HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redirectURL);
// log the user out for the rest of this current request, however they will be reauthenticated
// fully when they come back from the redirect. This prevents caching problems where part of the
// request is preformed for the user was authenticated and the other half after it succedded. This
// way the user is fully authenticated from the start of the request.
//
// TODO: have no idea what this is, but leave it as it is, could be broken
context.setCurrentUser(null);
return new HashMap();
}
}
catch (SQLException sqle)
{
throw new PatternException("Unable to preform Shibboleth authentication",
sqle);
}
return null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.Serializable;
import java.sql.SQLException;
import javax.servlet.http.HttpSession;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Item;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Password;
import org.dspace.app.xmlui.wing.element.Text;
import org.xml.sax.SAXException;
/**
* Query the user for their authentication credentials.
*
* The parameter "return-url" may be passed to give a location where to redirect
* the user to after sucessfully authenticating.
*
* @author Jay Paz
*/
public class LDAPLogin extends AbstractDSpaceTransformer implements
CacheableProcessingComponent {
/** language strings */
public static final Message T_title = message("xmlui.EPerson.LDAPLogin.title");
public static final Message T_dspace_home = message("xmlui.general.dspace_home");
public static final Message T_trail = message("xmlui.EPerson.LDAPLogin.trail");
public static final Message T_head1 = message("xmlui.EPerson.LDAPLogin.head1");
public static final Message T_userName = message("xmlui.EPerson.LDAPLogin.username");
public static final Message T_error_bad_login = message("xmlui.EPerson.LDAPLogin.error_bad_login");
public static final Message T_password = message("xmlui.EPerson.LDAPLogin.password");
public static final Message T_submit = message("xmlui.EPerson.LDAPLogin.submit");
/**
* Generate the unique caching key. This key must be unique inside the space
* of this component.
*/
public Serializable getKey() {
Request request = ObjectModelHelper.getRequest(objectModel);
String previous_username = request.getParameter("username");
// Get any message parameters
HttpSession session = request.getSession();
String header = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER);
String message = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE);
String characters = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS);
// If there is a message or previous email attempt then the page is not
// cachable
if (header == null && message == null && characters == null
&& previous_username == null)
{
// cacheable
return "1";
}
else
{
// Uncachable
return "0";
}
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity() {
Request request = ObjectModelHelper.getRequest(objectModel);
String previous_username = request.getParameter("username");
// Get any message parameters
HttpSession session = request.getSession();
String header = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER);
String message = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE);
String characters = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS);
// If there is a message or previous email attempt then the page is not
// cachable
if (header == null && message == null && characters == null
&& previous_username == null)
{
// Always valid
return NOPValidity.SHARED_INSTANCE;
}
else
{
// invalid
return null;
}
}
/**
* Set the page title and trail.
*/
public void addPageMeta(PageMeta pageMeta) throws WingException {
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Display the login form.
*/
public void addBody(Body body) throws SQLException, SAXException,
WingException {
// Check if the user has previously attempted to login.
Request request = ObjectModelHelper.getRequest(objectModel);
HttpSession session = request.getSession();
String previousUserName = request.getParameter("username");
// Get any message parameters
String header = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER);
String message = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE);
String characters = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS);
if (header != null || message != null || characters != null) {
Division reason = body.addDivision("login-reason");
if (header != null)
{
reason.setHead(message(header));
}
else
{
// Always have a head.
reason.setHead("Authentication Required");
}
if (message != null)
{
reason.addPara(message(message));
}
if (characters != null)
{
reason.addPara(characters);
}
}
Division login = body.addInteractiveDivision("login", contextPath
+ "/ldap-login", Division.METHOD_POST, "primary");
login.setHead(T_head1);
List list = login.addList("ldap-login", List.TYPE_FORM);
Text email = list.addItem().addText("username");
email.setRequired();
email.setLabel(T_userName);
if (previousUserName != null) {
email.setValue(previousUserName);
email.addError(T_error_bad_login);
}
Item item = list.addItem();
Password password = item.addPassword("ldap_password");
password.setRequired();
password.setLabel(T_password);
list.addLabel();
Item submit = list.addItem("login-in", null);
submit.addButton("submit").setValue(T_submit);
}
} | Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
/**
* Display to the user that their password has been successfully reset.
*
* @author Scott Phillips
*/
public class ForgotPasswordFinished extends AbstractDSpaceTransformer
{
private static final Message T_title =
message("xmlui.EPerson.ForgotPasswordFinished.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail_forgot_password =
message("xmlui.EPerson.trail_forgot_password");
private static final Message T_head =
message("xmlui.EPerson.ForgotPasswordFinished.head");
private static final Message T_para1 =
message("xmlui.EPerson.ForgotPasswordFinished.para1");
private static final Message T_go_home =
message("xmlui.general.go_home");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail_forgot_password);
}
public void addBody(Body body) throws WingException
{
Division reset = body.addDivision("password-reset", "primary");
reset.setHead(T_head);
EPersonUtils.forgottProgressList(reset, 3);
reset.addPara(T_para1);
reset.addPara().addXref(contextPath, T_go_home);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Item;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Text;
import org.xml.sax.SAXException;
/**
* Display the new user registration form, allowing the user to enter
* in an email address and have the system verify the email address
* before allowing the user create an account
*
* There are two parameters that may be given to the form:
*
* email - The email of the new account account
*
* retry - A boolean value indicating that the previously entered email was invalid.
*
* accountExists - A boolean value indicating the email previously entered allready
* belongs to a user.
*
* @author Scott Phillips
*/
public class StartRegistration extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** language strings */
private static final Message T_title =
message("xmlui.EPerson.StartRegistration.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail_new_registration =
message("xmlui.EPerson.trail_new_registration");
private static final Message T_head1 =
message("xmlui.EPerson.StartRegistration.head1");
private static final Message T_para1 =
message("xmlui.EPerson.StartRegistration.para1");
private static final Message T_reset_password_for =
message("xmlui.EPerson.StartRegistration.reset_password_for");
private static final Message T_submit_reset =
message("xmlui.EPerson.StartRegistration.submit_reset");
private static final Message T_head2 =
message("xmlui.EPerson.StartRegistration.head2");
private static final Message T_para2 =
message("xmlui.EPerson.StartRegistration.para2");
private static final Message T_email_address =
message("xmlui.EPerson.StartRegistration.email_address");
private static final Message T_email_address_help =
message("xmlui.EPerson.StartRegistration.email_address_help");
private static final Message T_error_bad_email =
message("xmlui.EPerson.StartRegistration.error_bad_email");
private static final Message T_submit_register =
message("xmlui.EPerson.StartRegistration.submit_register");
/** The email address previously entered */
private String email;
/** Determine if the user failed on their last attempt to enter an email address */
private java.util.List<String> errors;
/**
* Determine if the last failed attempt was because an account allready
* existed for the given email address
*/
private boolean accountExists;
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver,objectModel,src,parameters);
this.email = parameters.getParameter("email","");
this.accountExists = parameters.getParameterAsBoolean("accountExists",false);
String errors = parameters.getParameter("errors","");
if (errors.length() > 0)
{
this.errors = Arrays.asList(errors.split(","));
}
else
{
this.errors = new ArrayList<String>();
}
}
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
// Only cache on the first attempt.
if (email == null && !accountExists && errors != null && errors.size() == 0)
{
// cacheable
return "1";
}
else
{
// Uncachable
return "0";
}
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity()
{
if (email == null && !accountExists && errors != null && errors.size() == 0)
{
// Always valid
return NOPValidity.SHARED_INSTANCE;
}
else
{
// invalid
return null;
}
}
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail_new_registration);
}
public void addBody(Body body) throws WingException {
if (accountExists) {
Division exists = body.addInteractiveDivision("register-account-exists",contextPath+"/register",Division.METHOD_POST,"primary");
exists.setHead(T_head1);
exists.addPara(T_para1);
List form = exists.addList("form");
form.addLabel(T_reset_password_for);
form.addItem(this.email);
form.addLabel();
Item submit = form.addItem();
submit.addButton("submit_forgot").setValue(T_submit_reset);
exists.addHidden("email").setValue(this.email);
exists.addHidden("eperson-continue").setValue(knot.getId());
}
Division register = body.addInteractiveDivision("register",
contextPath+"/register",Division.METHOD_POST,"primary");
register.setHead(T_head2);
EPersonUtils.registrationProgressList(register,1);
register.addPara(T_para2);
List form = register.addList("form",List.TYPE_FORM);
Text email = form.addItem().addText("email");
email.setRequired();
email.setLabel(T_email_address);
email.setHelp(T_email_address_help);
email.setValue(this.email);
if (errors.contains("email"))
{
email.addError(T_error_bad_email);
}
Item submit = form.addItem();
submit.addButton("submit").setValue(T_submit_register);
register.addHidden("eperson-continue").setValue(knot.getId());
}
/**
* Recycle
*/
public void recycle()
{
this.email = null;
this.errors = null;
super.recycle();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
/**
* Display to the user that they have successfully registered.
*
* @author Scott Phillips
*/
public class RegistrationFinished extends AbstractDSpaceTransformer
{
/** Language strings */
private static final Message T_title =
message("xmlui.EPerson.RegistrationFinished.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail_new_registration =
message("xmlui.EPerson.trail_new_registration");
private static final Message T_head =
message("xmlui.EPerson.RegistrationFinished.head");
private static final Message T_para1 =
message("xmlui.EPerson.RegistrationFinished.para1");
private static final Message T_go_home =
message("xmlui.general.go_home");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_trail_new_registration);
}
public void addBody(Body body) throws WingException
{
Division finished = body.addDivision("registration-finished", "primary");
finished.setHead(T_head);
EPersonUtils.registrationProgressList(finished, 3);
finished.addPara(T_para1);
finished.addPara().addXref(contextPath, T_go_home);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
public class FailedAuthentication extends AbstractDSpaceTransformer {
private static final String SESSION_ATTRIBUTE_NAME = "xmlui.Eperson.FailedAuthentication.message";
public static final Message BAD_CREDENTIALS = message("xmlui.EPerson.FailedAuthentication.BadCreds");
public static final Message BAD_ARGUMENTS = message("xmlui.EPerson.FailedAuthentication.BadArgs");
public static final Message NO_SUCH_USER = message("xmlui.EPerson.FailedAuthentication.NoSuchUser");
/**language strings */
public static final Message T_title =
message("xmlui.EPerson.FailedAuthentication.title");
public static final Message T_dspace_home =
message("xmlui.general.dspace_home");
public static final Message T_trail =
message("xmlui.EPerson.FailedAuthentication.trail");
public static final Message T_h1 =
message("xmlui.EPerson.FailedAuthentication.h1");
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException {
Request request = ObjectModelHelper.getRequest(objectModel);
Division div = body.addDivision("failed_auth");
div.setHead(T_h1);
div.addPara((Message)request.getSession().getAttribute(SESSION_ATTRIBUTE_NAME));
deRegisterErrorCode(request);
}
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException {
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
public static void registerErrorCode(Message message, HttpServletRequest request){
request.getSession().setAttribute(SESSION_ATTRIBUTE_NAME, message);
}
private static void deRegisterErrorCode(Request request){
request.getSession().removeAttribute(SESSION_ATTRIBUTE_NAME);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
/**
*
* This action will start the nessary steps to authenticate a user. After the user
* successfully authenticates the user will resume this request with all parameters
* and attributes intact. An optional message can be added that will be displayed
* on the login form. This could be used to provide a reason why the user is being
* queried for a user name and password.
*
* Possible parameter are:
*
* header: An i18n message that will be used as the header for the message.
*
* message: An i18n message tag.
*
* characters: Characters to be displayed, possibly for untranslated error messages
*
*
* <map:action name="StartAuthenticationAction" src="org.dspace.app.xmlui.eperson.StartAuthenticationAction"/>
*
*
* <map:act type="StartAuthenticationAction"/>
*
*
* Typicaly this is used in conjunction with the AuthenticatedSelector as:
*
* <map:select type="AuthenticatedSelector">
* <map:when test="eperson">
* ...
* </map:when>
* <map:otherwise>
* <map:act type="startAuthenticationAction">
* <map:parameter name="message" value="xmlui.Aspect.component.tag"/>
* </map:act>
* </map:otherwise>
* </map:select>
*
* @author Scott Phillips
*/
public class StartAuthenticationAction extends AbstractAction
{
/**
* Redirect the user to the login page.
*/
public Map act(Redirector redirector, SourceResolver resolver,
Map objectModel, String source, Parameters parameters)
throws Exception
{
String header = parameters.getParameter("header",null);
String message = parameters.getParameter("message",null);
String characters = parameters.getParameter("characters",null);
// Interupt this request
AuthenticationUtil.interruptRequest(objectModel,header,message,characters);
final HttpServletRequest httpRequest = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
final HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(httpRequest.getContextPath() + "/login");
return new HashMap();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
/**
* Unauthenticate the current user. There is no way this action will fail,
* so any components inside the action will be executed.
*
* This action will always send an HTTP redirect to the DSpace homepage.
*
* Example:
*
* <map:action name="UnAuthenticateAction" src="org.dspace.app.xmlui.eperson.UnAuthenticateAction"/>
*
* <map:act type="UnAuthenticateAction">
* <map:serialize type="xml"/>
* </map:act>
*
* @author Scott Phillips
*/
public class UnAuthenticateAction extends AbstractAction
{
/**
* Logout the current user.
*
* @param redirector
* @param resolver
* @param objectModel
* Cocoon's object model
* @param source
* @param parameters
*/
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel,
String source, Parameters parameters) throws Exception
{
Context context = ContextUtil.obtainContext(objectModel);
final HttpServletRequest httpRequest =
(HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
final HttpServletResponse httpResponse =
(HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
EPerson eperson = context.getCurrentUser();
// Actually log the user out.
AuthenticationUtil.logOut(context,httpRequest);
// Set the user as logged in for the rest of this request so that the cache does not get spoiled.
context.setCurrentUser(eperson);
// Forward the user to the home page.
if((ConfigurationManager.getBooleanProperty("xmlui.public.logout")) && (httpRequest.isSecure())) {
StringBuffer location = new StringBuffer("http://");
location.append(ConfigurationManager.getProperty("dspace.hostname")).append(
httpRequest.getContextPath());
httpResponse.sendRedirect(location.toString());
}
else{
httpResponse.sendRedirect(httpRequest.getContextPath());
}
return new HashMap();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Button;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Field;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.content.Collection;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.I18nUtil;
import org.dspace.core.LogManager;
import org.dspace.eperson.Group;
import org.dspace.eperson.Subscribe;
import org.xml.sax.SAXException;
/**
* Display a form that allows the user to edit their profile.
* There are two cases in which this can be used: 1) when an
* existing user is attempting to edit their own profile, and
* 2) when a new user is registering for the first time.
*
* There are several parameters this transformer accepts:
*
* email - The email address of the user registering for the first time.
*
* registering - A boolean value to indicate whether the user is registering for the first time.
*
* retryInformation - A boolean value to indicate whether there was an error with the user's profile.
*
* retryPassword - A boolean value to indicate whether there was an error with the user's password.
*
* allowSetPassword - A boolean value to indicate whether the user is allowed to set their own password.
*
* @author Scott Phillips
*/
public class EditProfile extends AbstractDSpaceTransformer
{
private static Logger log = Logger.getLogger(EditProfile.class);
/** Language string used: */
private static final Message T_title_create =
message("xmlui.EPerson.EditProfile.title_create");
private static final Message T_title_update =
message("xmlui.EPerson.EditProfile.title_update");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail_new_registration =
message("xmlui.EPerson.trail_new_registration");
private static final Message T_trail_update =
message("xmlui.EPerson.EditProfile.trail_update");
private static final Message T_head_create =
message("xmlui.EPerson.EditProfile.head_create");
private static final Message T_head_update =
message("xmlui.EPerson.EditProfile.head_update");
private static final Message T_email_address =
message("xmlui.EPerson.EditProfile.email_address");
private static final Message T_first_name =
message("xmlui.EPerson.EditProfile.first_name");
private static final Message T_error_required =
message("xmlui.EPerson.EditProfile.error_required");
private static final Message T_last_name =
message("xmlui.EPerson.EditProfile.last_name");
private static final Message T_telephone =
message("xmlui.EPerson.EditProfile.telephone");
private static final Message T_language =
message("xmlui.EPerson.EditProfile.Language");
private static final Message T_create_password_instructions =
message("xmlui.EPerson.EditProfile.create_password_instructions");
private static final Message T_update_password_instructions =
message("xmlui.EPerson.EditProfile.update_password_instructions");
private static final Message T_password =
message("xmlui.EPerson.EditProfile.password");
private static final Message T_error_invalid_password =
message("xmlui.EPerson.EditProfile.error_invalid_password");
private static final Message T_confirm_password =
message("xmlui.EPerson.EditProfile.confirm_password");
private static final Message T_error_unconfirmed_password =
message("xmlui.EPerson.EditProfile.error_unconfirmed_password");
private static final Message T_submit_update =
message("xmlui.EPerson.EditProfile.submit_update");
private static final Message T_submit_create =
message("xmlui.EPerson.EditProfile.submit_create");
private static final Message T_subscriptions =
message("xmlui.EPerson.EditProfile.subscriptions");
private static final Message T_subscriptions_help =
message("xmlui.EPerson.EditProfile.subscriptions_help");
private static final Message T_email_subscriptions =
message("xmlui.EPerson.EditProfile.email_subscriptions");
private static final Message T_select_collection =
message("xmlui.EPerson.EditProfile.select_collection");
private static final Message T_head_auth =
message("xmlui.EPerson.EditProfile.head_auth");
private static final Message T_head_identify =
message("xmlui.EPerson.EditProfile.head_identify");
private static final Message T_head_security =
message("xmlui.EPerson.EditProfile.head_security");
private static Locale[] supportedLocales = getSupportedLocales();
static
{
Arrays.sort(supportedLocales, new Comparator<Locale>() {
public int compare(Locale a, Locale b)
{
return a.getDisplayName().compareTo(b.getDisplayName());
}
});
}
/** The email address of the user registering for the first time.*/
private String email;
/** Determine if the user is registering for the first time */
private boolean registering;
/** Determine if the user is allowed to set their own password */
private boolean allowSetPassword;
/** A list of fields in error */
private java.util.List<String> errors;
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver,objectModel,src,parameters);
this.email = parameters.getParameter("email","unknown");
this.registering = parameters.getParameterAsBoolean("registering",false);
this.allowSetPassword = parameters.getParameterAsBoolean("allowSetPassword",false);
String errors = parameters.getParameter("errors","");
if (errors.length() > 0)
{
this.errors = Arrays.asList(errors.split(","));
}
else
{
this.errors = new ArrayList<String>();
}
// Ensure that the email variable is set.
if (eperson != null)
{
this.email = eperson.getEmail();
}
}
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
if (registering)
{
pageMeta.addMetadata("title").addContent(T_title_create);
}
else
{
pageMeta.addMetadata("title").addContent(T_title_update);
}
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
if (registering)
{
pageMeta.addTrail().addContent(T_trail_new_registration);
}
else
{
pageMeta.addTrail().addContent(T_trail_update);
}
}
public void addBody(Body body) throws WingException, SQLException
{
// Log that we are viewing a profile
log.info(LogManager.getHeader(context, "view_profile", ""));
Request request = ObjectModelHelper.getRequest(objectModel);
String defaultFirstName="",defaultLastName="",defaultPhone="";
String defaultLanguage=null;
if (request.getParameter("submit") != null)
{
defaultFirstName = request.getParameter("first_name");
defaultLastName = request.getParameter("last_name");
defaultPhone = request.getParameter("phone");
defaultLanguage = request.getParameter("language");
}
else if (eperson != null)
{
defaultFirstName = eperson.getFirstName();
defaultLastName = eperson.getLastName();
defaultPhone = eperson.getMetadata("phone");
defaultLanguage = eperson.getLanguage();
}
String action = contextPath;
if (registering)
{
action += "/register";
}
else
{
action += "/profile";
}
Division profile = body.addInteractiveDivision("information",
action,Division.METHOD_POST,"primary");
if (registering)
{
profile.setHead(T_head_create);
}
else
{
profile.setHead(T_head_update);
}
// Add the progress list if we are registering a new user
if (registering)
{
EPersonUtils.registrationProgressList(profile, 2);
}
List form = profile.addList("form",List.TYPE_FORM);
List identity = form.addList("identity",List.TYPE_FORM);
identity.setHead(T_head_identify);
// Email
identity.addLabel(T_email_address);
identity.addItem(email);
// First name
Text firstName = identity.addItem().addText("first_name");
firstName.setRequired();
firstName.setLabel(T_first_name);
firstName.setValue(defaultFirstName);
if (errors.contains("first_name"))
{
firstName.addError(T_error_required);
}
if (!registering && !ConfigurationManager.getBooleanProperty("xmlui.user.editmetadata", true))
{
firstName.setDisabled();
}
// Last name
Text lastName = identity.addItem().addText("last_name");
lastName.setRequired();
lastName.setLabel(T_last_name);
lastName.setValue(defaultLastName);
if (errors.contains("last_name"))
{
lastName.addError(T_error_required);
}
if (!registering &&!ConfigurationManager.getBooleanProperty("xmlui.user.editmetadata", true))
{
lastName.setDisabled();
}
// Phone
Text phone = identity.addItem().addText("phone");
phone.setLabel(T_telephone);
phone.setValue(defaultPhone);
if (errors.contains("phone"))
{
phone.addError(T_error_required);
}
if (!registering && !ConfigurationManager.getBooleanProperty("xmlui.user.editmetadata", true))
{
phone.setDisabled();
}
// Language
Select lang = identity.addItem().addSelect("language");
lang.setLabel(T_language);
if (supportedLocales.length > 0)
{
for (Locale lc : supportedLocales)
{
lang.addOption(lc.toString(), lc.getDisplayName());
}
}
else
{
lang.addOption(I18nUtil.DEFAULTLOCALE.toString(), I18nUtil.DEFAULTLOCALE.getDisplayName());
}
lang.setOptionSelected((defaultLanguage == null || defaultLanguage.equals("")) ?
I18nUtil.DEFAULTLOCALE.toString() : defaultLanguage);
if (!registering && !ConfigurationManager.getBooleanProperty("xmlui.user.editmetadata", true))
{
lang.setDisabled();
}
// Subscriptions
if (!registering)
{
List subscribe = form.addList("subscriptions",List.TYPE_FORM);
subscribe.setHead(T_subscriptions);
subscribe.addItem(T_subscriptions_help);
Collection[] currentList = Subscribe.getSubscriptions(context, context.getCurrentUser());
Collection[] possibleList = Collection.findAll(context);
Select subscriptions = subscribe.addItem().addSelect("subscriptions");
subscriptions.setLabel(T_email_subscriptions);
subscriptions.setHelp("");
subscriptions.enableAddOperation();
subscriptions.enableDeleteOperation();
subscriptions.addOption(-1,T_select_collection);
for (Collection possible : possibleList)
{
String name = possible.getMetadata("name");
if (name.length() > 50)
{
name = name.substring(0, 47) + "...";
}
subscriptions.addOption(possible.getID(), name);
}
for (Collection collection: currentList)
{
subscriptions.addInstance().setOptionSelected(collection.getID());
}
}
if (allowSetPassword)
{
List security = form.addList("security",List.TYPE_FORM);
security.setHead(T_head_security);
if (registering)
{
security.addItem().addContent(T_create_password_instructions);
}
else
{
security.addItem().addContent(T_update_password_instructions);
}
Field password = security.addItem().addPassword("password");
password.setLabel(T_password);
if (registering)
{
password.setRequired();
}
if (errors.contains("password"))
{
password.addError(T_error_invalid_password);
}
Field passwordConfirm = security.addItem().addPassword("password_confirm");
passwordConfirm.setLabel(T_confirm_password);
if (registering)
{
passwordConfirm.setRequired();
}
if (errors.contains("password_confirm"))
{
passwordConfirm.addError(T_error_unconfirmed_password);
}
}
Button submit = form.addItem().addButton("submit");
if (registering)
{
submit.setValue(T_submit_update);
}
else
{
submit.setValue(T_submit_create);
}
profile.addHidden("eperson-continue").setValue(knot.getId());
if (!registering)
{
// Add a list of groups that this user is apart of.
Group[] memberships = Group.allMemberGroups(context, context.getCurrentUser());
// Not a member of any groups then don't do anything.
if (!(memberships.length > 0))
{
return;
}
List list = profile.addList("memberships");
list.setHead(T_head_auth);
for (Group group: memberships)
{
list.addItem(group.getName());
}
}
}
/**
* Recycle
*/
public void recycle()
{
this.email = null;
this.errors = null;
super.recycle();
}
/**
* get the available Locales for the User Interface as defined in dspace.cfg
* property xmlui.supported.locales
* returns an array of Locales or null
*
* @return an array of supported Locales or null
*/
private static Locale[] getSupportedLocales()
{
String ll = ConfigurationManager.getProperty("xmlui.supported.locales");
if (ll != null)
{
return I18nUtil.parseLocales(ll);
}
else
{
Locale result[] = new Locale[1];
result[0] = I18nUtil.DEFAULTLOCALE;
return result;
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.Serializable;
import java.sql.SQLException;
import javax.servlet.http.HttpSession;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Item;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Password;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
/**
* Query the user for their authentication credentials.
*
* The parameter "return-url" may be passed to give a location
* where to redirect the user to after sucessfully authenticating.
*
* @author Sid
* @author Scott Phillips
*/
public class PasswordLogin extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/**language strings */
public static final Message T_title =
message("xmlui.EPerson.PasswordLogin.title");
public static final Message T_dspace_home =
message("xmlui.general.dspace_home");
public static final Message T_trail =
message("xmlui.EPerson.PasswordLogin.trail");
public static final Message T_head1 =
message("xmlui.EPerson.PasswordLogin.head1");
public static final Message T_email_address =
message("xmlui.EPerson.PasswordLogin.email_address");
public static final Message T_error_bad_login =
message("xmlui.EPerson.PasswordLogin.error_bad_login");
public static final Message T_password =
message("xmlui.EPerson.PasswordLogin.password");
public static final Message T_forgot_link =
message("xmlui.EPerson.PasswordLogin.forgot_link");
public static final Message T_submit =
message("xmlui.EPerson.PasswordLogin.submit");
public static final Message T_head2 =
message("xmlui.EPerson.PasswordLogin.head2");
public static final Message T_para1 =
message("xmlui.EPerson.PasswordLogin.para1");
public static final Message T_register_link =
message("xmlui.EPerson.PasswordLogin.register_link");
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
Request request = ObjectModelHelper.getRequest(objectModel);
String previous_email = request.getParameter("login_email");
// Get any message parameters
HttpSession session = request.getSession();
String header = (String) session.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER);
String message = (String) session.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE);
String characters = (String) session.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS);
// If there is a message or previous email attempt then the page is not cachable
if (header == null && message == null && characters == null && previous_email == null)
{
// cacheable
return "1";
}
else
{
// Uncachable
return "0";
}
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity()
{
Request request = ObjectModelHelper.getRequest(objectModel);
String previous_email = request.getParameter("login_email");
// Get any message parameters
HttpSession session = request.getSession();
String header = (String) session.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER);
String message = (String) session.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE);
String characters = (String) session.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS);
// If there is a message or previous email attempt then the page is not cachable
if (header == null && message == null && characters == null && previous_email == null)
{
// Always valid
return NOPValidity.SHARED_INSTANCE;
}
else
{
// invalid
return null;
}
}
/**
* Set the page title and trail.
*/
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Display the login form.
*/
public void addBody(Body body) throws SQLException, SAXException,
WingException
{
// Check if the user has previously attempted to login.
Request request = ObjectModelHelper.getRequest(objectModel);
HttpSession session = request.getSession();
String previousEmail = request.getParameter("login_email");
// Get any message parameters
String header = (String) session.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER);
String message = (String) session.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE);
String characters = (String) session.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS);
if (header != null || message != null || characters != null)
{
Division reason = body.addDivision("login-reason");
if (header != null)
{
reason.setHead(message(header));
}
else
{
// Always have a head.
reason.setHead("Authentication Required");
}
if (message != null)
{
reason.addPara(message(message));
}
if (characters != null)
{
reason.addPara(characters);
}
}
Division login = body.addInteractiveDivision("login", contextPath
+ "/password-login", Division.METHOD_POST, "primary");
login.setHead(T_head1);
List list = login.addList("password-login",List.TYPE_FORM);
Text email = list.addItem().addText("login_email");
email.setRequired();
email.setLabel(T_email_address);
if (previousEmail != null)
{
email.setValue(previousEmail);
email.addError(T_error_bad_login);
}
Item item = list.addItem();
Password password = item.addPassword("login_password");
password.setRequired();
password.setLabel(T_password);
item.addXref(contextPath + "/forgot", T_forgot_link);
list.addLabel();
Item submit = list.addItem("login-in", null);
submit.addButton("submit").setValue(T_submit);
if (ConfigurationManager.getBooleanProperty("xmlui.user.registration", true))
{
Division register = login.addDivision("register");
register.setHead(T_head2);
register.addPara(T_para1);
register.addPara().addXref(contextPath + "/register",T_register_link);
}
}
} | Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
/**
* Display to the user that their profile has been successfully updated.
*
* @author Scott Phillips
*/
public class ProfileUpdated extends AbstractDSpaceTransformer
{
/** Language string */
private static final Message T_title =
message("xmlui.EPerson.ProfileUpdated.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.EPerson.ProfileUpdated.trail");
private static final Message T_head =
message("xmlui.EPerson.ProfileUpdated.head");
private static final Message T_para1 =
message("xmlui.EPerson.ProfileUpdated.para1");
private static final Message T_go_home =
message("xmlui.general.go_home");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException
{
Division updated = body.addDivision("profile-updated", "primary");
updated.setHead(T_head);
updated.addPara(T_para1);
updated.addPara().addXref(contextPath + "/", T_go_home);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Item;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.authenticate.AuthenticationMethod;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
/**
* Displays a list of authentication methods. This page is displayed if more
* than one AuthenticationMethod is defined in the dpace config file.
*
* @author Jay Paz
*
*/
public class LoginChooser extends AbstractDSpaceTransformer implements
CacheableProcessingComponent {
public static final Message T_dspace_home = message("xmlui.general.dspace_home");
public static final Message T_title = message("xmlui.EPerson.LoginChooser.title");
public static final Message T_trail = message("xmlui.EPerson.LoginChooser.trail");
public static final Message T_head1 = message("xmlui.EPerson.LoginChooser.head1");
public static final Message T_para1 = message("xmlui.EPerson.LoginChooser.para1");
/**
* Generate the unique caching key. This key must be unique inside the space
* of this component.
*/
public Serializable getKey() {
Request request = ObjectModelHelper.getRequest(objectModel);
String previous_email = request.getParameter("login_email");
// Get any message parameters
HttpSession session = request.getSession();
String header = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER);
String message = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE);
String characters = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS);
// If there is a message or previous email attempt then the page is not
// cachable
if (header == null && message == null && characters == null
&& previous_email == null)
{
// cacheable
return "1";
}
else
{
// Uncachable
return "0";
}
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity() {
Request request = ObjectModelHelper.getRequest(objectModel);
String previous_email = request.getParameter("login_email");
// Get any message parameters
HttpSession session = request.getSession();
String header = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER);
String message = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE);
String characters = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS);
// If there is a message or previous email attempt then the page is not
// cachable
if (header == null && message == null && characters == null
&& previous_email == null)
{
// Always valid
return NOPValidity.SHARED_INSTANCE;
}
else
{
// invalid
return null;
}
}
/**
* Set the page title and trail.
*/
public void addPageMeta(PageMeta pageMeta) throws WingException {
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Display the login choices.
*/
public void addBody(Body body) throws SQLException, SAXException,
WingException {
Iterator authMethods = AuthenticationManager
.authenticationMethodIterator();
Request request = ObjectModelHelper.getRequest(objectModel);
HttpSession session = request.getSession();
// Get any message parameters
String header = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER);
String message = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE);
String characters = (String) session
.getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS);
if (header != null || message != null || characters != null) {
Division reason = body.addDivision("login-reason");
if (header != null)
{
reason.setHead(message(header));
}
else
{
// Allways have a head.
reason.setHead("Authentication Required");
}
if (message != null)
{
reason.addPara(message(message));
}
if (characters != null)
{
reason.addPara(characters);
}
}
Division loginChooser = body.addDivision("login-chooser");
loginChooser.setHead(T_head1);
loginChooser.addPara().addContent(T_para1);
List list = loginChooser.addList("login-options", List.TYPE_SIMPLE);
while (authMethods.hasNext()) {
final AuthenticationMethod authMethod = (AuthenticationMethod) authMethods
.next();
HttpServletRequest hreq = (HttpServletRequest) this.objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
HttpServletResponse hresp = (HttpServletResponse) this.objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
String loginURL = authMethod.loginPageURL(context, hreq, hresp);
String authTitle = authMethod.loginPageTitle(context);
if (loginURL != null && authTitle != null)
{
if (ConfigurationManager.getBooleanProperty("xmlui.force.ssl")
&& !request.isSecure())
{
StringBuffer location = new StringBuffer("https://");
location
.append(
ConfigurationManager
.getProperty("dspace.hostname"))
.append(loginURL).append(
request.getQueryString() == null ? ""
: ("?" + request.getQueryString()));
loginURL = location.toString();
}
final Item item = list.addItem();
item.addXref(loginURL, message(authTitle));
}
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.sitemap.PatternException;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
/**
* Attempt to authenticate the user based upon their presented credentials. This
* action uses the http parameters of username, ldap_password, and login_realm
* as credentials.
*
* If the authentication attempt is successfull then an HTTP redirect will be
* sent to the browser redirecting them to their original location in the system
* before authenticated or if none is supplied back to the DSpace homepage. The
* action will also return true, thus contents of the action will be excuted.
*
* If the authentication attempt fails, the action returns false.
*
* Example use:
*
* <map:act name="LDAPAuthenticate"> <map:serialize type="xml"/> </map:act>
* <map:transform type="try-to-login-again-transformer">
*
* @author Jay Paz
*/
public class LDAPAuthenticateAction extends AbstractAction {
/**
* Attempt to authenticate the user.
*/
public Map act(Redirector redirector, SourceResolver resolver,
Map objectModel, String source, Parameters parameters)
throws Exception {
// First check if we are preforming a new login
Request request = ObjectModelHelper.getRequest(objectModel);
String username = request.getParameter("username");
String password = request.getParameter("ldap_password");
String realm = request.getParameter("login_realm");
// Skip out of no name or password given.
if (username == null || password == null)
{
return null;
}
try {
Context context = AuthenticationUtil.authenticate(objectModel,username, password, realm);
EPerson eperson = context.getCurrentUser();
if (eperson != null) {
// The user has successfully logged in
String redirectURL = request.getContextPath();
if (AuthenticationUtil.isInterupptedRequest(objectModel)) {
// Resume the request and set the redirect target URL to
// that of the originaly interrupted request.
redirectURL += AuthenticationUtil
.resumeInterruptedRequest(objectModel);
}
// Authentication successfull send a redirect.
final HttpServletResponse httpResponse = (HttpServletResponse) objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redirectURL);
// log the user out for the rest of this current request,
// however they will be reauthenticated
// fully when they come back from the redirect. This prevents
// caching problems where part of the
// request is preformed fore the user was authenticated and the
// other half after it succedded. This
// way the user is fully authenticated from the start of the
// request.
context.setCurrentUser(null);
return new HashMap();
}
} catch (SQLException sqle) {
throw new PatternException("Unable to preform authentication", sqle);
}
return null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.selection.Selector;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.authenticate.AuthenticationMethod;
/**
* Selector will count the number of interactive AuthenticationMethods defined in the
* dspace configuration file
* @author Jay Paz
* @author Scott Phillips
*
*/
public class AuthenticationCountSelector implements Selector{
/**
* Returns true if the expression (in this case a number) is equal to the number
* of AuthenticationMethods defined in the dspace.cfg file
* @return
*/
public boolean select(String expression, Map objectModel, Parameters parameters) {
// get an iterator of all the AuthenticationMethods defined
final Iterator<AuthenticationMethod> authMethods = AuthenticationManager
.authenticationMethodIterator();
final HttpServletResponse httpResponse = (HttpServletResponse) objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
final HttpServletRequest httpRequest = (HttpServletRequest) objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
int authMethodCount = 0;
// iterate to count the methods
while(authMethods.hasNext()){
AuthenticationMethod auth = authMethods.next();
try
{
if (auth.loginPageURL(
ContextUtil.obtainContext(objectModel), httpRequest,
httpResponse) != null){
authMethodCount++;
}
}
catch (SQLException e)
{
// mmm... we should not never go here, anyway we convert it in an unchecked exception
throw new IllegalStateException(e);
}
}
final Integer exp = Integer.valueOf(expression);
return (authMethodCount == exp);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.SourceResolver;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Field;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.xml.sax.SAXException;
/**
* Display a reset password form allowing the user to select a new password.
*
* @author Scott Phillips
*/
public class ResetPassword extends AbstractDSpaceTransformer
{
/** Language strings */
private static final Message T_title =
message("xmlui.EPerson.ResetPassword.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail_forgot_password =
message("xmlui.EPerson.trail_forgot_password");
private static final Message T_head =
message("xmlui.EPerson.ResetPassword.head");
private static final Message T_para1 =
message("xmlui.EPerson.ResetPassword.para1");
private static final Message T_email_address =
message("xmlui.EPerson.ResetPassword.email_address");
private static final Message T_new_password =
message("xmlui.EPerson.ResetPassword.new_password");
private static final Message T_error_invalid_password =
message("xmlui.EPerson.ResetPassword.error_invalid_password");
private static final Message T_confirm_password =
message("xmlui.EPerson.ResetPassword.confirm_password");
private static final Message T_error_unconfirmed_password =
message("xmlui.EPerson.ResetPassword.error_unconfirmed_password");
private static final Message T_submit =
message("xmlui.EPerson.ResetPassword.submit");
private String email;
private java.util.List<String> errors;
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver,objectModel,src,parameters);
this.email = parameters.getParameter("email","unknown");
String errors = parameters.getParameter("errors","");
if (errors.length() > 0)
{
this.errors = Arrays.asList(errors.split(","));
}
else
{
this.errors = new ArrayList<String>();
}
}
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail_forgot_password);
}
public void addBody(Body body) throws WingException {
Division register = body.addInteractiveDivision("reset-password",
contextPath+"/register",Division.METHOD_POST,"primary");
register.setHead(T_head);
EPersonUtils.forgottProgressList(register,2);
register.addPara(T_para1);
List form = register.addList("form",List.TYPE_FORM);
form.addLabel(T_email_address);
form.addItem(email);
Field password = form.addItem().addPassword("password");
password.setRequired();
password.setLabel(T_new_password);
if (errors.contains("password"))
{
password.addError(T_error_invalid_password);
}
Field passwordConfirm = form.addItem().addPassword("password_confirm");
passwordConfirm.setRequired();
passwordConfirm.setLabel(T_confirm_password);
if (errors.contains("password_confirm"))
{
passwordConfirm.addError(T_error_unconfirmed_password);
}
form.addItem().addButton("submit").setValue(T_submit);
register.addHidden("eperson-continue").setValue(knot.getId());
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Locale;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.UserMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.xml.sax.SAXException;
/**
* Add the eperson navigation items to the document. This includes:
*
* 1) Login and Logout links
*
* 2) Navigational links to register or edit their profile based
* upon wheather the user is authenticatied or not.
*
* 3) User metadata
*
* 4) The user's language prefrences (wheather someone is logged
* in or not)
*
* @author Scott Phillips
*/
public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_my_account =
message("xmlui.EPerson.Navigation.my_account");
private static final Message T_profile =
message("xmlui.EPerson.Navigation.profile");
private static final Message T_logout =
message("xmlui.EPerson.Navigation.logout");
private static final Message T_login =
message("xmlui.EPerson.Navigation.login");
private static final Message T_register =
message("xmlui.EPerson.Navigation.register");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique key.
* This key must be unique inside the space of this component.
*
* @return The generated key hashes the src
*/
public Serializable getKey()
{
Request request = ObjectModelHelper.getRequest(objectModel);
// Special case, don't cache anything if the user is logging
// in. The problem occures because of timming, this cache key
// is generated before we know whether the operation has
// succeded or failed. So we don't know whether to cache this
// under the user's specific cache or under the anonymous user.
if (request.getParameter("login_email") != null ||
request.getParameter("login_password") != null ||
request.getParameter("login_realm") != null )
{
return null;
}
// FIXME:
// Do not cache the home page. There is a bug that is causing the
// homepage to be cached with user's data after a logout. This
// polutes the cache. As a work-around this problem we just won't
// cache this page.
if (request.getSitemapURI().length() == 0)
{
return null;
}
StringBuilder key;
if (context.getCurrentUser() != null)
{
key = new StringBuilder(context.getCurrentUser().getEmail());
}
else
{
key = new StringBuilder("anonymous");
}
// Add the user's language
Enumeration locales = request.getLocales();
while (locales.hasMoreElements())
{
Locale locale = (Locale) locales.nextElement();
key.append("-").append(locale.toString());
}
return HashUtil.hash(key.toString());
}
/**
* Generate the validity object.
*
* @return The generated validity object or <code>null</code> if the
* component is currently not cacheable.
*/
public SourceValidity getValidity()
{
if (this.validity == null)
{
// Only use the DSpaceValidity object is someone is logged in.
if (context.getCurrentUser() != null)
{
try {
DSpaceValidity validity = new DSpaceValidity();
validity.add(eperson);
Group[] groups = Group.allMemberGroups(context, eperson);
for (Group group : groups)
{
validity.add(group);
}
this.validity = validity.complete();
}
catch (SQLException sqle)
{
// Just ignore it and return invalid.
}
}
else
{
this.validity = NOPValidity.SHARED_INSTANCE;
}
}
return this.validity;
}
/**
* Add the eperson aspect navigational options.
*/
public void addOptions(Options options) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
/* Create skeleton menu structure to ensure consistent order between aspects,
* even if they are never used
*/
options.addList("browse");
List account = options.addList("account");
options.addList("context");
options.addList("administrative");
account.setHead(T_my_account);
EPerson eperson = this.context.getCurrentUser();
if (eperson != null)
{
String fullName = eperson.getFullName();
account.addItemXref(contextPath+"/logout",T_logout);
account.addItemXref(contextPath+"/profile",T_profile.parameterize(fullName));
}
else
{
account.addItemXref(contextPath+"/login",T_login);
if (ConfigurationManager.getBooleanProperty("xmlui.user.registration", true))
{
account.addItemXref(contextPath + "/register", T_register);
}
}
}
/**
* Add the user metadata
*/
public void addUserMeta(UserMeta userMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
EPerson eperson = context.getCurrentUser();
if (eperson != null)
{
userMeta.setAuthenticated(true);
userMeta.addMetadata("identifier").addContent(eperson.getID());
userMeta.addMetadata("identifier","email").addContent(eperson.getEmail());
userMeta.addMetadata("identifier","firstName").addContent(eperson.getFirstName());
userMeta.addMetadata("identifier","lastName").addContent(eperson.getLastName());
userMeta.addMetadata("identifier","logoutURL").addContent(contextPath+"/logout");
userMeta.addMetadata("identifier","url").addContent(contextPath+"/profile");
}
else
{
userMeta.setAuthenticated(false);
}
// Allways have a login URL.
userMeta.addMetadata("identifier","loginURL").addContent(contextPath+"/login");
// Allways add language information
Request request = ObjectModelHelper.getRequest(objectModel);
Enumeration locales = request.getLocales();
while (locales.hasMoreElements())
{
Locale locale = (Locale) locales.nextElement();
userMeta.addMetadata("language","RFC3066").addContent(locale.toString());
}
}
/**
* recycle
*/
public void recycle()
{
this.validity = null;
super.recycle();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.core.ConfigurationManager;
/**
* Display to the user that the token provided was invalid.
*
* @author Scott Phillips
*/
public class InvalidToken extends AbstractDSpaceTransformer
{
/** language strings */
private static final Message T_title =
message("xmlui.EPerson.InvalidToken.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.EPerson.InvalidToken.trail");
private static final Message T_head =
message("xmlui.EPerson.InvalidToken.head");
private static final Message T_para1 =
message("xmlui.EPerson.InvalidToken.para1");
private static final Message T_para2 =
message("xmlui.EPerson.InvalidToken.para2");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException {
Division invalid = body.addDivision("invalid-token","primary");
invalid.setHead(T_head);
invalid.addPara(T_para1);
Para example1 = invalid.addPara("invalid-token-examlpe","code");
example1.addContent(ConfigurationManager.getProperty("dspace.url") + "/register?token=ABCDEFGHIJK");
Para example2 = invalid.addPara("invalid-token-examlpe","code");
example2.addContent("LMNOP");
invalid.addPara(T_para2);
Para example3 = invalid.addPara("valid-token-examlpe","code");
example3.addContent(ConfigurationManager.getProperty("dspace.url") + "/register?token=ABCDEFGHIJKLMNOP");
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
/**
* Inform the user that the email address they entered cannot be registered
* with DSpace. This is a state within the new user registration flow.
*
* @author Scott Phillips
*/
public class CannotRegister extends AbstractDSpaceTransformer
{
/** Language strings */
private static final Message T_title =
message("xmlui.EPerson.CannotRegister.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace-home");
private static final Message T_trail_new_registration =
message("xmlui.EPerson.trail-new-registration");
private static final Message T_head =
message("xmlui.EPerson.CannotRegister.head");
private static final Message T_para1 =
message("xmlui.EPerson.CannotRegister.para1");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail_new_registration);
}
public void addBody(Body body) throws WingException
{
Division cannot = body.addDivision("register-cannot","primary");
cannot.setHead(T_head);
EPersonUtils.registrationProgressList(cannot, 0);
cannot.addPara(T_para1);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.SourceResolver;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Item;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Text;
import org.xml.sax.SAXException;
/**
* Display the forgot password form, allowing the user to enter
* in an email address and have the system verify the email address
* before allowing the user to reset their password.
*
* There are two parameters that may be given to the form:
*
* email - The email of the forgotten account
*
* retry - A boolean value indicating that the previously entered email was invalid.
*
* @author Scott Phillips
*/
public class StartForgotPassword extends AbstractDSpaceTransformer
{
/** Language strings */
private static final Message T_title =
message("xmlui.EPerson.StartForgotPassword.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail_forgot_password =
message("xmlui.EPerson.trail_forgot_password");
private static final Message T_head =
message("xmlui.EPerson.StartForgotPassword.head");
private static final Message T_para1 =
message("xmlui.EPerson.StartForgotPassword.para1");
private static final Message T_email_address =
message("xmlui.EPerson.StartForgotPassword.email_address");
private static final Message T_email_address_help =
message("xmlui.EPerson.StartForgotPassword.email_address_help");
private static final Message T_error_not_found =
message("xmlui.EPerson.StartForgotPassword.error_not_found");
private static final Message T_submit =
message("xmlui.EPerson.StartForgotPassword.submit");
/** The email of the forgotten account */
private String email;
/** A list of fields in error */
private java.util.List<String> errors;
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver,objectModel,src,parameters);
this.email = parameters.getParameter("email","");
String errors = parameters.getParameter("errors","");
if (errors.length() > 0)
{
this.errors = Arrays.asList(errors.split(","));
}
else
{
this.errors = new ArrayList<String>();
}
}
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail_forgot_password);
}
public void addBody(Body body) throws WingException {
Division forgot = body.addInteractiveDivision("start-forgot-password",
contextPath+"/forgot",Division.METHOD_POST,"primary");
forgot.setHead(T_head);
EPersonUtils.forgottProgressList(forgot,1);
forgot.addPara(T_para1);
List form = forgot.addList("form",List.TYPE_FORM);
Text email = form.addItem().addText("email");
email.setRequired();
email.setLabel(T_email_address);
email.setHelp(T_email_address_help);
// Prefill with invalid email if this is a retry attempt.
if (email != null)
{
email.setValue(this.email);
}
if (errors.contains("email"))
{
email.addError(T_error_not_found);
}
Item submit = form.addItem();
submit.addButton("submit").setValue(T_submit);
forgot.addHidden("eperson-continue").setValue(knot.getId());
}
/**
* Recycle
*/
public void recycle()
{
this.email = null;
super.recycle();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.sitemap.PatternException;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
/**
* Attempt to authenticate the user based upon their presented credentials.
* This action uses the http parameters of login_email, login_password, and
* login_realm as credentials.
*
* If the authentication attempt is successfull then an HTTP redirect will be
* sent to the browser redirecting them to their original location in the
* system before authenticated or if none is supplied back to the DSpace
* homepage. The action will also return true, thus contents of the action will
* be excuted.
*
* If the authentication attempt fails, the action returns false.
*
* Example use:
*
* <map:act name="Authenticate">
* <map:serialize type="xml"/>
* </map:act>
* <map:transform type="try-to-login-again-transformer">
*
* @author Scott Phillips
*/
public class AuthenticateAction extends AbstractAction
{
/**
* Attempt to authenticate the user.
*/
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel,
String source, Parameters parameters) throws Exception
{
// First check if we are preforming a new login
Request request = ObjectModelHelper.getRequest(objectModel);
String email = request.getParameter("login_email");
String password = request.getParameter("login_password");
String realm = request.getParameter("login_realm");
// Protect against NPE errors inside the authentication
// class.
if ((email == null) || (password == null))
{
return null;
}
try
{
Context context = AuthenticationUtil.authenticate(objectModel, email,password, realm);
EPerson eperson = context.getCurrentUser();
if (eperson != null)
{
// The user has successfully logged in
String redirectURL = request.getContextPath();
if (AuthenticationUtil.isInterupptedRequest(objectModel))
{
// Resume the request and set the redirect target URL to
// that of the originaly interrupted request.
redirectURL += AuthenticationUtil.resumeInterruptedRequest(objectModel);
}
else
{
// Otherwise direct the user to the login page
String loginRedirect = ConfigurationManager.getProperty("xmlui.user.loginredirect");
redirectURL += (loginRedirect != null) ? loginRedirect.trim() : "";
}
// Authentication successfull send a redirect.
final HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redirectURL);
// log the user out for the rest of this current request, however they will be reauthenticated
// fully when they come back from the redirect. This prevents caching problems where part of the
// request is preformed fore the user was authenticated and the other half after it succedded. This
// way the user is fully authenticated from the start of the request.
context.setCurrentUser(null);
return new HashMap();
}
}
catch (SQLException sqle)
{
throw new PatternException("Unable to preform authentication",
sqle);
}
return null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.eperson;
import java.io.IOException;
import java.util.Map;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.SourceResolver;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.xml.sax.SAXException;
/**
* Display to the user that a verification email has been set.
*
* There are two parameters this transformer expects:
*
* email - The email of the to-be-verrified account.
*
* forgot - A boolean value indicating that this is part of the forgotten password workflow.
*
* @author Scott Phillips
*/
public class VerifyEmail extends AbstractDSpaceTransformer
{
/** language strings */
private static final Message T_title =
message("xmlui.EPerson.VerifyEmail.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail_forgot_password =
message("xmlui.EPerson.trail_forgot_password");
private static final Message T_trail_new_registration =
message("xmlui.EPerson.trail_new_registration");
private static final Message T_head =
message("xmlui.EPerson.VerifyEmail.head");
private static final Message T_para =
message("xmlui.EPerson.VerifyEmail.para");
/** The email address being verrified */
private String email;
/** Determine if this is part of the forgot password workflow */
private boolean forgot;
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver,objectModel,src,parameters);
try
{
this.email = parameters.getParameter("email");
this.forgot = parameters.getParameterAsBoolean("forgot");
}
catch (ParameterException pe)
{
throw new ProcessingException(pe);
}
}
public void addPageMeta(PageMeta pageMeta) throws WingException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
if (forgot)
{
pageMeta.addTrail().addContent(T_trail_forgot_password);
}
else
{
pageMeta.addTrail().addContent(T_trail_new_registration);
}
}
public void addBody(Body body) throws WingException
{
Division verify = body.addDivision("verify-email","primary");
verify.setHead(T_head);
if (forgot)
{
EPersonUtils.forgottProgressList(verify, 1);
}
else
{
EPersonUtils.registrationProgressList(verify,1);
}
verify.addPara(T_para.parameterize(email));
}
/**
* Recycle
*/
public void recycle()
{
this.email = null;
super.recycle();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.aspect.administrative.SystemwideAlerts;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.authenticate.AuthenticationMethod;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
/**
* Methods for authenticating the user. This is DSpace platform code, as opposed
* to the site-specific authentication code, that resides in implementations of
* the org.dspace.eperson.AuthenticationMethod interface.
*
* @author Scott Phillips
* @author Robert Tansley
*/
public class AuthenticationUtil
{
private static final Logger log = Logger.getLogger(AuthenticationUtil.class);
/**
* Session attribute name for storing the return URL where the user should
* be redirected too once successfully authenticated.
*/
public static final String REQUEST_INTERRUPTED = "dspace.request.interrupted";
public static final String REQUEST_RESUME = "dspace.request.resume";
/**
* These store a message giving a reason for why the request is being interrupted.
*/
public static final String REQUEST_INTERRUPTED_HEADER = "dspace.request.interrupted.header";
public static final String REQUEST_INTERRUPTED_MESSAGE = "dspace.request.interrupted.message";
public static final String REQUEST_INTERRUPTED_CHARACTERS = "dspace.request.interrupted.characters";
/**
* The IP address this user first logged in from, do not allow this session for
* other IP addresses.
*/
private static final String CURRENT_IP_ADDRESS = "dspace.user.ip";
/**
* The effective user id, typically this will never change. However if an administrator
* has assumed login as this user then they will differ.
*/
private static final String EFFECTIVE_USER_ID = "dspace.user.effective";
private static final String AUTHENTICATED_USER_ID = "dspace.user.authenticated";
/**
* Authenticate the current DSpace content based upon given authentication
* credentials. The AuthenticationManager will consult the configured
* authentication stack to determine the best method.
*
* @param objectModel
* Cocoon's object model.
* @param email
* The email credentials provided by the user.
* @param password
* The password credentials provided by the user.
* @param realm
* The realm credentials provided by the user.
* @return Return a current context with either the eperson attached if the
* authentication was successful or or no eperson attached if the
* attempt failed.
*/
public static Context authenticate(Map objectModel, String email, String password, String realm)
throws SQLException
{
// Get the real HttpRequest
HttpServletRequest request = (HttpServletRequest) objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
Context context = ContextUtil.obtainContext(objectModel);
int implicitStatus = AuthenticationManager.authenticateImplicit(
context, null, null, null, request);
if (implicitStatus == AuthenticationMethod.SUCCESS)
{
log.info(LogManager.getHeader(context, "login", "type=implicit"));
AuthenticationUtil.logIn(context, request, context.getCurrentUser());
}
else
{
// If implicit authentication failed, fall over to explicit.
int explicitStatus = AuthenticationManager.authenticate(context,
email, password, realm, request);
if (explicitStatus == AuthenticationMethod.SUCCESS)
{
// Logged in OK.
log.info(LogManager
.getHeader(context, "login", "type=explicit"));
AuthenticationUtil.logIn(context, request, context
.getCurrentUser());
}
else
{
log.info(LogManager.getHeader(context, "failed_login", "email="
+ email + ", realm=" + realm + ", result="
+ explicitStatus));
}
}
return context;
}
/**
* Perform implicit authentication. The authenticationManager will consult
* the authentication stack for any methods that can implicitly authenticate
* this session. If the attempt was successful then the returned context
* will have an eperson attached other wise the context will not have an
* eperson attached.
*
* @param objectModel
* Cocoon's object model.
* @return This requests DSpace context.
*/
public static Context authenticateImplicit(Map objectModel)
throws SQLException
{
// Get the real HttpRequest
final HttpServletRequest request = (HttpServletRequest) objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
Context context = ContextUtil.obtainContext(objectModel);
int implicitStatus = AuthenticationManager.authenticateImplicit(
context, null, null, null, request);
if (implicitStatus == AuthenticationMethod.SUCCESS)
{
log.info(LogManager.getHeader(context, "login", "type=implicit"));
AuthenticationUtil.logIn(context, request, context.getCurrentUser());
}
return context;
}
/**
* Log the given user in as a real authenticated user. This should only be used after
* a user has presented credentials and they have been validated.
*
* @param context
* DSpace context
* @param request
* HTTP request
* @param eperson
* the eperson logged in
*/
private static void logIn(Context context, HttpServletRequest request,
EPerson eperson) throws SQLException
{
if (eperson == null)
{
return;
}
HttpSession session = request.getSession();
context.setCurrentUser(eperson);
// Check to see if systemwide alerts is restricting sessions
if (!AuthorizeManager.isAdmin(context) && !SystemwideAlerts.canUserStartSession())
{
// Do not allow this user to login because sessions are being restricted by a systemwide alert.
context.setCurrentUser(null);
return;
}
// Set any special groups - invoke the authentication manager.
int[] groupIDs = AuthenticationManager.getSpecialGroups(context,
request);
for (int groupID : groupIDs)
{
context.setSpecialGroup(groupID);
}
// and the remote IP address to compare against later requests
// so we can detect session hijacking.
session.setAttribute(CURRENT_IP_ADDRESS, request.getRemoteAddr());
// Set both the effective and authenticated user to the same.
session.setAttribute(EFFECTIVE_USER_ID, eperson.getID());
session.setAttribute(AUTHENTICATED_USER_ID,eperson.getID());
}
/**
* Log the given user in as a real authenticated user. This should only be used after
* a user has presented credentials and they have been validated. This method
* signature is provided to be easier to call from flow scripts.
*
* @param objectModel
* The cocoon object model.
* @param eperson
* the eperson logged in
*
*/
public static void logIn(Map objectModel, EPerson eperson) throws SQLException
{
final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
Context context = ContextUtil.obtainContext(objectModel);
logIn(context,request,eperson);
}
/**
* Check to see if there are any session attributes indicating a currently authenticated
* user. If there is then log this user in.
*
* @param context
* DSpace context
* @param request
* HTTP Request
*/
public static void resumeLogin(Context context, HttpServletRequest request)
throws SQLException
{
HttpSession session = request.getSession(false);
if (session != null)
{
Integer id = (Integer) session.getAttribute(EFFECTIVE_USER_ID);
Integer realid = (Integer) session.getAttribute(AUTHENTICATED_USER_ID);
if (id != null)
{
String address = (String)session.getAttribute(CURRENT_IP_ADDRESS);
if (address != null && address.equals(request.getRemoteAddr()))
{
EPerson eperson = EPerson.find(context, id);
context.setCurrentUser(eperson);
// Check to see if systemwide alerts is restricting sessions
if (!AuthorizeManager.isAdmin(context) && !SystemwideAlerts.canUserMaintainSession())
{
// Normal users can not maintain their sessions, check to see if this is really an
// administrator logging in as someone else.
EPerson realEPerson = EPerson.find(context, realid);
Group administrators = Group.find(context,1);
if (!administrators.isMember(realEPerson))
{
// Log this user out because sessions are being restricted by a systemwide alert.
context.setCurrentUser(null);
return;
}
}
// Set any special groups - invoke the authentication mgr.
int[] groupIDs = AuthenticationManager.getSpecialGroups(context, request);
for (int groupID : groupIDs)
{
context.setSpecialGroup(groupID);
}
}
else
{
// Possible hack attempt.
}
} // if id
} // if session
}
/**
* Assume the login as another user. Only site administrators may perform the action.
*
* @param context
* The current DSpace context logged in as a site administrator
* @param request
* The real HTTP request.
* @param loginAs
* Whom to login as.
* @throws SQLException
* @throws AuthorizeException using an I18nTransformer key as the message
*/
public static void loginAs(Context context, HttpServletRequest request, EPerson loginAs )
throws SQLException, AuthorizeException
{
// Only allow loginAs if the administrator has allowed it.
if (!ConfigurationManager.getBooleanProperty("xmlui.user.assumelogin", false))
{
return;
}
// Only super administrators can login as someone else.
if (!AuthorizeManager.isAdmin(context))
{
throw new AuthorizeException("xmlui.utils.AuthenticationUtil.onlyAdmins");
}
// Just to be double be sure, make sure the administrator
// is the one who actually authenticated himself.
HttpSession session = request.getSession(false);
Integer authenticatedID = (Integer) session.getAttribute(AUTHENTICATED_USER_ID);
if (context.getCurrentUser().getID() != authenticatedID)
{
throw new AuthorizeException("xmlui.utils.AuthenticationUtil.onlyAuthenticatedAdmins");
}
// You may not assume the login of another super administrator
if (loginAs == null)
{
return;
}
Group administrators = Group.find(context,1);
if (administrators.isMember(loginAs))
{
throw new AuthorizeException("xmlui.utils.AuthenticationUtil.notAnotherAdmin");
}
// Success, allow the user to login as another user.
context.setCurrentUser(loginAs);
// Set any special groups - invoke the authentication mgr.
int[] groupIDs = AuthenticationManager.getSpecialGroups(context,request);
for (int groupID : groupIDs)
{
context.setSpecialGroup(groupID);
}
// Set both the effective and authenticated user to the same.
session.setAttribute(EFFECTIVE_USER_ID, loginAs.getID());
}
/**
* Log the user out.
*
* @param context
* DSpace context
* @param request
* HTTP request
*/
public static void logOut(Context context, HttpServletRequest request) throws SQLException
{
HttpSession session = request.getSession();
if (session.getAttribute(EFFECTIVE_USER_ID) != null &&
session.getAttribute(AUTHENTICATED_USER_ID) != null)
{
Integer effectiveID = (Integer) session.getAttribute(EFFECTIVE_USER_ID);
Integer authenticatedID = (Integer) session.getAttribute(AUTHENTICATED_USER_ID);
if (effectiveID.intValue() != authenticatedID.intValue())
{
// The user has login in as another user, instead of logging them out,
// revert back to their previous login name.
EPerson authenticatedUser = EPerson.find(context, authenticatedID);
context.setCurrentUser(authenticatedUser);
session.setAttribute(EFFECTIVE_USER_ID, authenticatedID);
return;
}
}
// Otherwise, just log the person out as normal.
context.setCurrentUser(null);
session.removeAttribute(EFFECTIVE_USER_ID);
session.removeAttribute(AUTHENTICATED_USER_ID);
session.removeAttribute(CURRENT_IP_ADDRESS);
}
/**
* Determine if the email can register itself or needs to be
* created by a site administrator first.
*
* @param objectModel
* The Cocoon object model
* @param email
* The email of the person to be registered.
* @return true if the email can register, otherwise false.
*/
public static boolean canSelfRegister(Map objectModel, String email) throws SQLException
{
final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
Context context = ContextUtil.obtainContext(objectModel);
if (SystemwideAlerts.canUserStartSession())
{
return AuthenticationManager.canSelfRegister(context, request, email);
}
else
{
// System wide alerts is preventing new sessions.
return false;
}
}
/**
* Determine if the EPerson (to be created or already created) has the
* ability to set their own password.
*
* @param objectModel
* The Cocoon object model
* @param email
* The email address of the EPerson.
* @return
*/
public static boolean allowSetPassword(Map objectModel, String email) throws SQLException
{
final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
Context context = ContextUtil.obtainContext(objectModel);
return AuthenticationManager.allowSetPassword(context, request, email);
}
/**
* Construct a new, mostly blank, eperson for the given email address. This should
* only be called once the email address has been verified.
*
* @param objectModel
* The Cocoon object model.
* @param email
* The email address of the new eperson.
* @return A newly created EPerson object.
*/
public static EPerson createNewEperson(Map objectModel, String email) throws
SQLException, AuthorizeException
{
final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
Context context = ContextUtil.obtainContext(objectModel);
// Need to create new eperson
// FIXME: TEMPORARILY need to turn off authentication, as usually
// only site admins can create e-people
context.setIgnoreAuthorization(true);
EPerson eperson = EPerson.create(context);
eperson.setEmail(email);
eperson.setCanLogIn(true);
eperson.setSelfRegistered(true);
eperson.update();
context.setIgnoreAuthorization(false);
// Give site auth a chance to set/override appropriate fields
AuthenticationManager.initEPerson(context, request, eperson);
return eperson;
}
/**
* Is there a currently interrupted request?
*
* @param objectModel The Cocoon object Model
*/
public static boolean isInterupptedRequest(Map objectModel)
{
final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
HttpSession session = request.getSession();
Object interruptedObject = session.getAttribute(REQUEST_INTERRUPTED);
if (interruptedObject instanceof RequestInfo)
{
// There is currently either an interrupted or yet-to-be resumed request.
return true;
}
// There are not interrupted requests.
return false;
}
/**
* Interrupt the current request and store if for later resumption. This request will
* send an HTTP redirect telling the client to authenticate first. Once that has been finished
* then the request can be resumed.
*
* @param objectModel The Cocoon object Model
* @param header A message header (i18n tag)
* @param message A message for why the request was interrupted (i18n tag)
* @param characters An untranslated message, perhaps an error message?
*/
public static void interruptRequest(Map objectModel, String header, String message, String characters)
{
final HttpServletRequest request =
(HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
HttpSession session = request.getSession();
// Store this interrupted request until after the user successfully authenticates.
RequestInfo interruptedRequest = new RequestInfo(request);
// Set the request as interrupted
session.setAttribute(REQUEST_INTERRUPTED,interruptedRequest);
session.setAttribute(REQUEST_RESUME, null); // just to be clear.
// Set the interrupt message
session.setAttribute(REQUEST_INTERRUPTED_HEADER, header);
session.setAttribute(REQUEST_INTERRUPTED_MESSAGE, message);
session.setAttribute(REQUEST_INTERRUPTED_CHARACTERS, characters);
}
/**
* Set the interrupted request to a resumable state. The
* next request that the server receives (for this session) that
* has the same servletPath will be replaced with the previously
* interrupted request.
*
* @param objectModel The Cocoon object Model
* @return
*/
public static String resumeInterruptedRequest(Map objectModel)
{
final HttpServletRequest request =
(HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
HttpSession session = request.getSession();
// Clear the interrupt message
session.setAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER, null);
session.setAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE, null);
session.setAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS, null);
// Set the request as interrupted
Object interruptedObject = session.getAttribute(REQUEST_INTERRUPTED);
if (interruptedObject instanceof RequestInfo)
{
RequestInfo interruptedRequest = (RequestInfo) interruptedObject;
session.setAttribute(REQUEST_INTERRUPTED, null);
session.setAttribute(REQUEST_RESUME, interruptedRequest);
// Return the path for which this request belongs too. Only URLs
// for this path may be resumed.
if (interruptedRequest.getServletPath() == null || interruptedRequest.getServletPath().length() == 0) {
return interruptedRequest.getActualPath();
} else {
return interruptedRequest.getServletPath();
}
}
// No request was interrupted.
return null;
}
/**
* Check to see if this request should be resumed.
*
* @param realHttpRequest The current real request
* @return Either the current real request or a stored request that was previously interrupted.
*/
public static HttpServletRequest resumeRequest(HttpServletRequest realHttpRequest)
{
// First check to see if there is a resumed request.
HttpSession session = realHttpRequest.getSession();
//session.setMaxInactiveInterval(60);
Object object = session.getAttribute(REQUEST_RESUME);
// Next check to make sure it's the right type of object,
// there should be no condition where it is not - but always
// safe to check.
if (object instanceof RequestInfo)
{
RequestInfo interruptedRequest = (RequestInfo) object;
// Next, check to make sure this real request if for the same URL
// path, if so then resume the previous request.
String interruptedServletPath = interruptedRequest.getServletPath();
String realServletPath = realHttpRequest.getServletPath();
if (realServletPath != null &&
realServletPath.equals(interruptedServletPath))
{
// Clear the resumed request and send the request back to be resumed.
session.setAttribute(REQUEST_INTERRUPTED, null);
session.setAttribute(REQUEST_RESUME, null);
return interruptedRequest.wrapRequest(realHttpRequest);
}
}
// Otherwise return the real request.
return realHttpRequest;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
import java.util.ArrayList;
import java.util.List;
import org.apache.cocoon.environment.Request;
/**
* General utilities for common operations on Request objects.
*
* @author Scott Phillips
*/
public class RequestUtils {
/**
* Get values for a field from a DRI multi value field, since a field may
* have multiple values this method will check for fieldName + "_n" untill
* it does not find any more values. The result is a list of all values
* for a field.
*
* If the value has been seleted to be removed then it is removed from
* the list.
*
* @param request
* the request containing the form information
* @param compositeFieldName
* The fieldName of the composite field.
* @param componentFieldName
* The fieldName of the component field
* @return a List of Strings
*/
public static List<String> getCompositeFieldValues(Request request, String compositeFieldName, String componentFieldName)
{
List<String> values = new ArrayList<String>();
int i = -1;
// Iterate through the values in the form.
valueLoop: while (1 == 1)
{
i++;
String value = null;
// Get the component field's name
if (i == 0)
{
value = request.getParameter(componentFieldName);
}
else
{
value = request.getParameter(componentFieldName + "_" + i);
}
// If this is null then it's the last one.
if (value == null)
{
break valueLoop;
}
// Check to make sure that this value is not selected to be removed.
String[] selected = request.getParameterValues(compositeFieldName + "_selected");
if (selected != null)
{
for (String select : selected)
{
if (select.equals(compositeFieldName + "_" + i))
{
// Found, the user has requested that this value be deleted.
continue valueLoop;
}
}
}
// Only add non blank items to the list
if (value.length() == 0)
{
continue valueLoop;
}
// Finaly add it to the list
values.add(value.trim());
}
return values;
}
/**
* Get values from a DRI multi value field, since a field may have multiple
* values this method will check for fieldName + "_n" untill it does not
* find any more values. The result is a list of all values for a field.
*
* If the value has been seleted to be removed then it is removed from
* the list.
*
* @param request
* the request containing the form information
* @param fieldName
* The fieldName of the composite field.
* @return a List of Strings
*/
public static List<String> getFieldValues(Request request, String fieldName)
{
List<String> values = new ArrayList<String>();
int i = -1;
// Iterate through the values in the form.
valueLoop: while (1 == 1)
{
i++;
String value = null;
// Get the component field's name
if (i == 0)
{
value = request.getParameter(fieldName);
}
else
{
value = request.getParameter(fieldName + "_" + i);
}
// If this is null then it's the last one.
if (value == null)
{
break valueLoop;
}
// Check to make sure that this value is not selected to be removed.
String[] selected = request.getParameterValues(fieldName + "_selected");
if (selected != null)
{
for (String select : selected)
{
if (select.equals(fieldName + "_" + i))
{
// Found, the user has requested that this value be deleted.
continue valueLoop;
}
}
}
// Only add non blank items to the list
if (value.length() == 0)
{
continue valueLoop;
}
// Finaly add it to the list
values.add(value.trim());
}
return values;
}
/**
* Obtain a parameter from the given request as an int. <code>-1</code> is
* returned if the parameter is garbled or does not exist.
*
* @param request
* the HTTP request
* @param param
* the name of the parameter
*
* @return the integer value of the parameter, or -1
*/
public static int getIntParameter(Request request, String param)
{
String val = request.getParameter(param);
try
{
return Integer.parseInt(val.trim());
}
catch (Exception e)
{
// Problem with parameter
return -1;
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
/**
* Utilities that are needed in XSL transformations.
*
* @author Art Lowel (art dot lowel at atmire dot com)
*/
public class XSLUtils {
/*
* Cuts off the string at the space nearest to the targetLength if there is one within
* maxDeviation chars from the targetLength, or at the targetLength if no such space is
* found
*/
public static String shortenString(String string, int targetLength, int maxDeviation) {
targetLength = Math.abs(targetLength);
maxDeviation = Math.abs(maxDeviation);
if (string == null || string.length() <= targetLength + maxDeviation)
{
return string;
}
int currentDeviation = 0;
while (currentDeviation <= maxDeviation) {
try {
if (string.charAt(targetLength) == ' ')
{
return string.substring(0, targetLength) + " ...";
}
if (string.charAt(targetLength + currentDeviation) == ' ')
{
return string.substring(0, targetLength + currentDeviation) + " ...";
}
if (string.charAt(targetLength - currentDeviation) == ' ')
{
return string.substring(0, targetLength - currentDeviation) + " ...";
}
} catch (Exception e) {
//just in case
}
currentDeviation++;
}
return string.substring(0, targetLength) + " ...";
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.log4j.Logger;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
/**
* Miscellaneous UI utility methods methods for managing DSpace context.
*
* This class was "adapted" from the UIUtil.java in the DSpace webui.
*
* @author Robert Tansley
* @author Scott Phillips
*/
public class ContextUtil
{
/** Whether to look for x-forwarded headers for logging IP addresses */
private static Boolean useProxies;
/** The log4j logger */
private static final Logger log = Logger.getLogger(ContextUtil.class);
/** Where the context is stored on an HTTP Request object */
public static final String DSPACE_CONTEXT = "dspace.context";
/**
* Obtain a new context object. If a context object has already been created
* for this HTTP request, it is re-used, otherwise it is created.
*
* @param objectModel
* the cocoon Objectmodel
*
* @return a context object
*/
public static Context obtainContext(Map objectModel) throws SQLException
{
return obtainContext(ObjectModelHelper.getRequest(objectModel));
}
/**
* Obtain a new context object. If a context object has already been created
* for this HTTP request, it is re-used, otherwise it is created.
*
* @param request
* the cocoon or servlet request object
*
* @return a context object
*/
public static Context obtainContext(HttpServletRequest request) throws SQLException
{
Context context = (Context) request.getAttribute(DSPACE_CONTEXT);
if (context == null)
{
// No context for this request yet
context = new Context();
// Set the session ID
context.setExtraLogInfo("session_id="
+ request.getSession().getId());
AuthenticationUtil.resumeLogin(context, request);
// Set any special groups - invoke the authentication mgr.
int[] groupIDs = AuthenticationManager.getSpecialGroups(context, request);
for (int i = 0; i < groupIDs.length; i++)
{
context.setSpecialGroup(groupIDs[i]);
log.debug("Adding Special Group id="+String.valueOf(groupIDs[i]));
}
// Set the session ID and IP address
String ip = request.getRemoteAddr();
if (useProxies == null) {
useProxies = ConfigurationManager.getBooleanProperty("useProxies", false);
}
if(useProxies && request.getHeader("X-Forwarded-For") != null)
{
/* This header is a comma delimited list */
for(String xfip : request.getHeader("X-Forwarded-For").split(","))
{
if(!request.getHeader("X-Forwarded-For").contains(ip))
{
ip = xfip.trim();
}
}
}
context.setExtraLogInfo("session_id=" + request.getSession().getId() + ":ip_addr=" + ip);
// Store the context in the request
request.setAttribute(DSPACE_CONTEXT, context);
}
return context;
}
/**
* Check if a context exists for this request, if so complete the context.
*
* @param request
* The request object
*/
public static void completeContext(HttpServletRequest request) throws ServletException
{
Context context = (Context) request.getAttribute(DSPACE_CONTEXT);
if (context != null && context.isValid())
{
try
{
context.complete();
}
catch (SQLException e)
{
throw new ServletException(e);
}
}
}
public static void abortContext(HttpServletRequest request)
{
Context context = (Context) request.getAttribute(DSPACE_CONTEXT);
if (context != null && context.isValid())
{
context.abort();
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
import java.util.Map;
import java.util.HashMap;
import org.dspace.app.util.SyndicationFeed;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Utility functions and data in common to all producers of syndication feeds
* in the XMLUI -- e.g. DSpaceFeedGenerator, OpenSearchGenerator.
*
* Currently just implements the I18N mechanism: since the feed producer
* is shared with the JSPUI, and that UI employs a completely different i18n
* mechanism, the SyndicationFeed abstraction takes its own map of message
* keys to localized values. For the XMLUI, the "localized value" is actually
* a string with a special sentinal prefix (defined here as I18N_PREFIX). This
* is really just a marker; the DOM has to be post-processed later and the
* prefixed text is replaced by a Cocoon i18n element (whose key attribute
* is the text following the prefix).
*
* Note that the keys in the initial i18n message table are dictated by
* the SyndicationFeed class.
*
* @see SyndicationFeed
* @author Larry Stone
*/
public class FeedUtils
{
public static final Map<String, String> i18nLabels = makeI18NLabels();
/** The prefix used to differentate i18n keys */
private static final String I18N_PREFIX = "I18N:";
/** Cocoon's i18n namespace */
private static final String I18N_NAMESPACE = "http://apache.org/cocoon/i18n/2.1";
/**
* Returns a map of localizable labels whose values are themselves keys that are
* unmangled into a true i18n element for later localization.
*
* @return A map of mangled labels.
*/
private static Map<String, String> makeI18NLabels()
{
Map<String, String> labelMap = new HashMap<String, String>();
labelMap.put(SyndicationFeed.MSG_UNTITLED, I18N_PREFIX+"xmlui.feed.untitled");
labelMap.put(SyndicationFeed.MSG_LOGO_TITLE, I18N_PREFIX+"xmlui.feed.logo_title");
labelMap.put(SyndicationFeed.MSG_FEED_DESCRIPTION, I18N_PREFIX+"xmlui.feed.general_description");
labelMap.put(SyndicationFeed.MSG_UITYPE, SyndicationFeed.UITYPE_XMLUI);
return labelMap;
}
/**
* Scan the document and replace any text nodes that begin
* with the i18n prefix with an actual i18n element that
* can be processed by the i18n transformer.
*
* @param dom
*/
public static void unmangleI18N(Document dom)
{
NodeList elementNodes = dom.getElementsByTagName("*");
for (int i = 0; i < elementNodes.getLength(); i++)
{
NodeList textNodes = elementNodes.item(i).getChildNodes();
for (int j = 0; j < textNodes.getLength(); j++)
{
Node oldNode = textNodes.item(j);
// Check to see if the node is a text node, its value is not null, and it starts with the i18n prefix.
if (oldNode.getNodeType() == Node.TEXT_NODE && oldNode.getNodeValue() != null && oldNode.getNodeValue().startsWith(I18N_PREFIX))
{
Node parent = oldNode.getParentNode();
String key = oldNode.getNodeValue().substring(I18N_PREFIX.length());
Element newNode = dom.createElementNS(I18N_NAMESPACE, "text");
newNode.setAttribute("key", key);
newNode.setAttribute("catalogue", "default");
parent.replaceChild(newNode,oldNode);
}
}
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
import java.sql.SQLException;
import java.util.Map;
import java.util.Stack;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.handle.HandleManager;
/**
* Simple utility class for extracting handles.
*
* @author Scott Phillips
*/
public class HandleUtil
{
/** The URL prefix of all handle */
protected static final String HANDLE_PREFIX = "handle/";
protected static final String DSPACE_OBJECT = "dspace.object";
/**
* Obtain the current DSpace handle for the specified request.
*
* @param objectModel
* The cocoon model.
* @return A DSpace handle, or null if none found.
*/
public static DSpaceObject obtainHandle(Map objectModel)
throws SQLException
{
Request request = ObjectModelHelper.getRequest(objectModel);
DSpaceObject dso = (DSpaceObject) request.getAttribute(DSPACE_OBJECT);
if (dso == null)
{
String uri = request.getSitemapURI();
if (!uri.startsWith(HANDLE_PREFIX))
{
// Dosn't start with the prefix then no match
return null;
}
String handle = uri.substring(HANDLE_PREFIX.length());
int firstSlash = handle.indexOf('/');
if (firstSlash < 0)
{
// If there is no first slash then no match
return null;
}
int secondSlash = handle.indexOf('/', firstSlash + 1);
if (secondSlash < 0)
{
// A trailing slash is not nesssary if there is nothing after
// the handle.
secondSlash = handle.length();
}
handle = handle.substring(0, secondSlash);
Context context = ContextUtil.obtainContext(objectModel);
dso = HandleManager.resolveToObject(context, handle);
request.setAttribute(DSPACE_OBJECT, dso);
}
return dso;
}
/**
* Determine if the given DSO is an ancestor of the the parent handle.
*
* @param dso
* The child DSO object.
* @param parent
* The Handle to test against.
* @return The matched DSO object or null if none found.
*/
public static boolean inheritsFrom(DSpaceObject dso, String parent)
throws SQLException
{
DSpaceObject current = dso;
while (current != null)
{
// Check if the current object has the handle we are looking for.
if (current.getHandle().equals(parent))
{
return true;
}
if (current.getType() == Constants.ITEM)
{
current = ((Item) current).getOwningCollection();
}
else if (current.getType() == Constants.COLLECTION)
{
current = ((Collection) current).getCommunities()[0];
}
else if (current.getType() == Constants.COMMUNITY)
{
current = ((Community) current).getParentCommunity();
}
}
// If the loop finished then we searched the entire parant-child chain
// and did not find this handle, so the object was not found.
return false;
}
/**
* Build a list of trail metadata starting with the owning collection and
* ending with the root level parent. If the Object is an item the item is
* not included but all it's parents are. However if the item is a community
* or collection then it is included along with all parents.
*
* @param dso
* @param pageMeta
*/
public static void buildHandleTrail(DSpaceObject dso, PageMeta pageMeta,
String contextPath) throws SQLException, WingException
{
// Add the trail back to the repository root.
Stack<DSpaceObject> stack = new Stack<DSpaceObject>();
if (dso instanceof Bitstream)
{
Bitstream bitstream = (Bitstream) dso;
Bundle[] bundles = bitstream.getBundles();
dso = bundles[0];
}
if (dso instanceof Bundle)
{
Bundle bundle = (Bundle) dso;
Item[] items = bundle.getItems();
dso = items[0];
}
if (dso instanceof Item)
{
Item item = (Item) dso;
Collection collection = item.getOwningCollection();
dso = collection;
}
if (dso instanceof Collection)
{
Collection collection = (Collection) dso;
stack.push(collection);
Community[] communities = collection.getCommunities();
dso = communities[0];
}
if (dso instanceof Community)
{
Community community = (Community) dso;
stack.push(community);
for (Community parent : community.getAllParents())
{
stack.push(parent);
}
}
while (!stack.empty())
{
DSpaceObject pop = stack.pop();
if (pop instanceof Collection)
{
Collection collection = (Collection) pop;
String name = collection.getMetadata("name");
if (name == null || name.length() == 0)
{
pageMeta.addTrailLink(contextPath + "/handle/" + pop.getHandle(), new Message("default", "xmlui.general.untitled"));
}
else
{
pageMeta.addTrailLink(contextPath + "/handle/" + pop.getHandle(), name);
}
}
else if (pop instanceof Community)
{
Community community = (Community) pop;
String name = community.getMetadata("name");
if (name == null || name.length() == 0)
{
pageMeta.addTrailLink(contextPath + "/handle/" + pop.getHandle(), new Message("default", "xmlui.general.untitled"));
}
else
{
pageMeta.addTrailLink(contextPath + "/handle/" + pop.getHandle(), name);
}
}
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.reading.AbstractReader;
import org.xml.sax.SAXException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/**
* Loads in the jquery javascript library if it hasn't been loaded in already
*
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
*/
public class JQueryLoaderReader extends AbstractReader {
@Override
public void generate() throws IOException, SAXException, ProcessingException {
String contextPath = ObjectModelHelper.getRequest(objectModel).getContextPath();
String script = "!window.jQuery && document.write('<script type=\"text/javascript\" src=\"" + contextPath + "/static/js/jquery-1.4.2.min.js\"> </script>');";
ByteArrayInputStream inputStream = new ByteArrayInputStream(script.getBytes("UTF-8"));
byte[] buffer = new byte[8192];
ObjectModelHelper.getResponse(objectModel).setHeader("Content-Length", String.valueOf(script.length()));
int length;
while ((length = inputStream.read(buffer)) > -1)
{
out.write(buffer, 0, length);
}
out.flush();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
import java.util.Map;
import org.apache.cocoon.components.flow.javascript.fom.FOM_Cocoon;;
public class FlowscriptUtils {
public static Map getObjectModel(FOM_Cocoon cocoon) {
return cocoon.getObjectModel();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.browse.BrowseItem;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
/**
* This is a validity object specifically implemented for the caching
* needs of DSpace, Manakin, and Cocoon.
*
* The basic idea is that each time a DSpace object rendered by a cocoon
* component the object and everything about it that makes it unique should
* be reflected in the validity object for the component. By following this
* principle if the object has been updated externally then the cache will be
* invalidated.
*
* This DSpaceValidity object makes this processes easier by abstracting out
* the processes of determining what is unique about a DSpace object. A class
* is expected to create a new DSpaceValidity object and add() to it all
* DSpaceObjects that are rendered by the component. This validity object will
* serialize all those objects to a string, take a hash of the string and compare
* the hash of the string for any updates.
*
*
* @author Scott Phillips
*/
public class DSpaceValidity implements SourceValidity
{
private static final long serialVersionUID = 1L;
/** The validityKey while it is being build, once it is completed. */
protected StringBuffer validityKey;
/** Simple flag to note if the object has been completed. */
protected boolean completed = false;
/** A hash of the validityKey taken after completetion */
protected long hash;
/** The time when the validity is no longer assumed to be valid */
protected long assumedValidityTime = 0;
/** The length of time that a cache is assumed to be valid */
protected long assumedValidityDelay = 0;
/**
* Create a new DSpace validity object.
*
* @param initialValidityKey
* The initial string
*/
public DSpaceValidity(String initialValidityKey)
{
this.validityKey = new StringBuffer();
if (initialValidityKey != null)
{
this.validityKey.append(initialValidityKey);
}
}
public DSpaceValidity()
{
this(null);
}
/**
* Complete this validity object. After the completion no more
* objects may be added to the validity object and the object
* will return as valid.
*/
public DSpaceValidity complete()
{
this.completed = true;
this.hash = HashUtil.hash(validityKey);
this.validityKey = null;
// Set the forced validity time.
if (assumedValidityDelay > 0)
{
resetAssumedValidityTime();
}
return this;
}
/**
* Set the time delay for how long this cache will be assumed
* to be valid. When it is assumed valid no other checks will be
* made to consider it's validity, and once the time has expired
* a full validation will occure on the next cache hit. If the
* cache proves to be validated on this hit then the assumed
* validity timer is reset.
*
* @param milliseconds The delay time in millieseconds.
*/
public void setAssumedValidityDelay(long milliseconds )
{
// record the delay time.
this.assumedValidityDelay = milliseconds;
// Also add the delay time to the validity hash so if the
// admin changes the delay time then all the previous caches
// are invalidated.
this.validityKey.append("AssumedValidityDelay:"+milliseconds);
}
/**
* Set the time delay for how long this cache will be assumed to be valid.
*
* This method takes a string which is parsed for the delay time, the string
* must be of the following form: "<integer> <scale>" where scale is days,
* hours, minutes, or seconds.
*
* Examples: "1 day" or "12 hours" or "1 hour" or "30 minutes"
*
* See the setAssumedValidityDelay(long) for more information.
*
* @param delay The delay time in a variable scale.
*/
public void setAssumedValidityDelay(String delay)
{
if (delay == null || delay.length() == 0)
{
return;
}
String[] parts = delay.split(" ");
if (parts == null || parts.length != 2)
{
throw new IllegalArgumentException("Error unable to parse the assumed validity delay time: \"" + delay + "\". All delays must be of the form \"<integer> <scale>\" where scale is either seconds, minutes, hours, or days.");
}
long milliseconds = 0;
long value = 0;
try { value = Long.valueOf(parts[0]); }
catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Error unable to parse the assumed validity delay time: \""+delay+"\". All delays must be of the form \"<integer> <scale>\" where scale is either seconds, minutes, hours, or days.",nfe);
}
String scale = parts[1].toLowerCase();
if (scale.equals("weeks") || scale.equals("week"))
{
// milliseconds * seconds * minutes * hours * days * weeks
// 1000 * 60 * 60 * 24 * 7 * 1 = 604,800,000
milliseconds = value * 604800000;
}
else if (scale.equals("days") || scale.equals("day"))
{
// milliseconds * seconds * minutes * hours * days
// 1000 * 60 * 60 * 24 * 1 = 86,400,000
milliseconds = value * 86400000;
}
else if (scale.equals("hours") || scale.equals("hour"))
{
// milliseconds * seconds * minutes * hours
// 1000 * 60 * 60 * 1 = 3,600,000
milliseconds = value * 3600000;
}
else if (scale.equals("minutes") || scale.equals("minute"))
{
// milliseconds * second * minute
// 1000 * 60 * 1 = 60,000
milliseconds = value * 60000;
}
else if (scale.equals("seconds") || scale.equals("second"))
{
// milliseconds * second
// 1000 * 1 = 1000
milliseconds = value * 1000;
}
else
{
throw new IllegalArgumentException("Error unable to parse the assumed validity delay time: \""+delay+"\". All delays must be of the form \"<integer> <scale>\" where scale is either seconds, minutes, hours, or days.");
}
// Now set the actualy delay.
setAssumedValidityDelay(milliseconds);
}
/**
* Add a DSpace object to the validity. The order inwhich objects
* are added to the validity object is important, insure that
* objects are added in the *exact* same order each time a
* validity object is created.
*
* Below are the following transative rules for adding
* objects, i.e. if an item is added then all the items
* bundles & bitstreams will also be added.
*
* Communities -> logo bitstream
* Collection -> logo bitstream
* Item -> bundles -> bitstream
* Bundles -> bitstreams
* EPeople -> groups
*
* @param dso
* The object to add to the validity.
*/
public void add(DSpaceObject dso) throws SQLException
{
if (this.completed)
{
throw new IllegalStateException("Can not add DSpaceObject to a completed validity object");
}
if (dso == null)
{
this.validityKey.append("null");
}
else if (dso instanceof Community)
{
Community community = (Community) dso;
validityKey.append("Community:");
validityKey.append(community.getHandle());
validityKey.append(community.getMetadata("introductory_text"));
validityKey.append(community.getMetadata("short_description"));
validityKey.append(community.getMetadata("side_bar_text"));
validityKey.append(community.getMetadata("copyright_text"));
validityKey.append(community.getMetadata("name"));
// Add the communities logo
this.add(community.getLogo());
}
else if (dso instanceof Collection)
{
Collection collection = (Collection) dso;
validityKey.append("Collection:");
validityKey.append(collection.getHandle());
validityKey.append(collection.getMetadata("introductory_text"));
validityKey.append(collection.getMetadata("short_description"));
validityKey.append(collection.getMetadata("side_bar_text"));
validityKey.append(collection.getMetadata("provenance_description"));
validityKey.append(collection.getMetadata("copyright_text"));
validityKey.append(collection.getMetadata("license"));
validityKey.append(collection.getMetadata("name"));
// Add the logo also;
this.add(collection.getLogo());
}
else if (dso instanceof Item)
{
Item item = (Item) dso;
validityKey.append("Item:");
validityKey.append(item.getHandle());
validityKey.append(item.getOwningCollection());
validityKey.append(item.getLastModified());
// Include all metadata values in the validity key.
DCValue[] dcvs = item.getDC(Item.ANY,Item.ANY,Item.ANY);
for (DCValue dcv : dcvs)
{
validityKey.append(dcv.schema).append(".");
validityKey.append(dcv.element).append(".");
validityKey.append(dcv.qualifier).append(".");
validityKey.append(dcv.language).append("=");
validityKey.append(dcv.value);
}
for(Bundle bundle : item.getBundles())
{
// Add each of the items bundles & bitstreams.
this.add(bundle);
}
}
else if (dso instanceof BrowseItem)
{
BrowseItem browseItem = (BrowseItem) dso;
validityKey.append("BrowseItem:");
validityKey.append(browseItem.getHandle());
DCValue[] dcvs = browseItem.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (DCValue dcv : dcvs)
{
validityKey.append(dcv.schema).append(".");
validityKey.append(dcv.element).append(".");
validityKey.append(dcv.qualifier).append(".");
validityKey.append(dcv.language).append("=");
validityKey.append(dcv.value);
}
}
else if (dso instanceof Bundle)
{
Bundle bundle = (Bundle) dso;
validityKey.append("Bundle:");
validityKey.append(bundle.getID());
validityKey.append(bundle.getName());
validityKey.append(bundle.getPrimaryBitstreamID());
for(Bitstream bitstream : bundle.getBitstreams())
{
this.add(bitstream);
}
}
else if (dso instanceof Bitstream)
{
Bitstream bitstream = (Bitstream) dso;
validityKey.append("Bundle:");
validityKey.append(bitstream.getID());
validityKey.append(bitstream.getSequenceID());
validityKey.append(bitstream.getName());
validityKey.append(bitstream.getSource());
validityKey.append(bitstream.getDescription());
validityKey.append(bitstream.getChecksum());
validityKey.append(bitstream.getChecksumAlgorithm());
validityKey.append(bitstream.getSize());
validityKey.append(bitstream.getUserFormatDescription());
validityKey.append(bitstream.getFormat().getDescription());
}
else if (dso instanceof EPerson)
{
EPerson eperson = (EPerson) dso;
validityKey.append("Bundle:");
validityKey.append(eperson.getID());
validityKey.append(eperson.getEmail());
validityKey.append(eperson.getNetid());
validityKey.append(eperson.getFirstName());
validityKey.append(eperson.getLastName());
validityKey.append(eperson.canLogIn());
validityKey.append(eperson.getRequireCertificate());
}
else if (dso instanceof Group)
{
Group group = (Group) dso;
validityKey.append("Group:");
validityKey.append(group.getID());
validityKey.append(group.getName());
}
else
{
throw new IllegalArgumentException("DSpaceObject of type '"+dso.getClass().getName()+"' is not supported by the DSpaceValidity object.");
}
}
/**
* Add a non DSpaceObject to the validity, the object should be
* seralized into a string form. The order inwhich objects
* are added to the validity object is important, insure that
* objects are added in the *exact* same order each time a
* validity object is created.
*
* @param nonDSpaceObject
* The non DSpace object to add to the validity.
*/
public void add(String nonDSpaceObject) throws SQLException
{
validityKey.append("String:");
validityKey.append(nonDSpaceObject);
}
/**
* This method is used during serializion. When tomcat is shutdown cocoon's in-memory
* cache is serialized and written to disk to later be read back into memory on start
* up. When this class is read back into memory the readObject(stream) method will be
* called.
*
* This method will re-read the serialization back into memory but it will then set
* the assume validity time to zero. This means the next cache hit after a server startup
* will never be assumed valid. Only after it has been checked once will the regular assume
* validity mechanism be used.
*
* @param in
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
// Read in this object as normal.
in.defaultReadObject();
// After reading from serialization do not assume validity anymore until it
// has been checked at least once.
this.assumedValidityTime = 0;
}
/**
* Reset the assume validity time. This should be called only when the validity of this cache
* has been confirmed to be accurate. This will reset the assume valid timer based upon the
* configured delay.
*/
private void resetAssumedValidityTime()
{
this.assumedValidityTime = System.currentTimeMillis() + this.assumedValidityDelay;
}
/**
* Determine if the cache is still valid
*/
public int isValid()
{
// Return true if we have a hash.
if (this.completed)
{
// Check if we are configured to assume validity for a period of time.
if (this.assumedValidityDelay > 0)
{
// Check if we should assume validitity.
if (System.currentTimeMillis() < this.assumedValidityTime)
{
// Assume the cache is valid with out rechecking another validity object.
return SourceValidity.VALID;
}
}
return SourceValidity.UNKNOWN;
}
else
{
// This is an error, state. We are being asked whether we are valid before
// we have been initialized.
return SourceValidity.INVALID;
}
}
/**
* Determine if the cache is still valid based
* upon the other validity object.
*
* @param otherObject
* The other validity object.
*/
public int isValid(SourceValidity otherObject)
{
if (this.completed && otherObject instanceof DSpaceValidity)
{
DSpaceValidity otherSSV = (DSpaceValidity) otherObject;
if (hash == otherSSV.hash)
{
// Both caches have been checked are are considered valid,
// now we reset their assumed validity timers for both cache
// objects.
if (this.assumedValidityDelay > 0)
{
this.resetAssumedValidityTime();
}
if (otherSSV.assumedValidityDelay > 0)
{
otherSSV.resetAssumedValidityTime();
}
return SourceValidity.VALID;
}
}
return SourceValidity.INVALID;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.utils;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Stores information about an HTTP request. This is used so that the request
* can be replicated during a later request, once authentication has
* successfully occurred.
*
* This class is the same as found in the JSPUI however a few extra methods were added to
* remember the original path information (info,translated, uri, url, etc..) that coocoon
* needs inorder to be able to resume a request.
*
* @author Robert Tansley
* @author Scott Phillips
* @version $Revision: 5845 $
*/
public class RequestInfo
{
/** Request characteristics that are stored for later resumption */
private final String authType;
private final String contextPath;
private final String method;
private final String pathInfo;
private final String pathTranslated;
private final String queryString;
private final String requestURI;
private final StringBuffer requestURL;
private final String servletPath;
private final String scheme;
private final boolean secure;
private final Map<String,String[]> parameters;
/**
* Construct a request info object storing information about the given
* request
*
* @param request
* the request to get information from
*/
public RequestInfo(HttpServletRequest request)
{
this.authType = request.getAuthType();
this.contextPath = request.getContextPath();
this.method = request.getMethod();
this.pathInfo = request.getPathInfo();
this.pathTranslated = request.getPathTranslated();
this.queryString = request.getQueryString();
this.requestURI = request.getRequestURI();
this.requestURL = request.getRequestURL();
this.servletPath = request.getServletPath();
this.scheme = request.getScheme();
this.secure = request.isSecure();
// Copy the parameters
this.parameters = new HashMap<String,String[]>();
Enumeration enumeration = request.getParameterNames();
while (enumeration.hasMoreElements())
{
String key = (String) enumeration.nextElement();
String[] values = request.getParameterValues(key);
this.parameters.put(key, values);
}
}
/**
* Return the servlet path that this request is for.
*/
public String getServletPath()
{
return this.servletPath;
}
/**
* Return the servlet path that this request is for.
*/
public String getActualPath()
{
return this.pathInfo + ((queryString == null || queryString.length() == 0) ? "" : "?"+queryString);
}
/**
* Wrap an incoming request to make it look like the request that the
* constructor was called with
*
* @param request
* the request to wrap
*
* @return a wrapper around the request passed into this method, wrapped so
* that it looks like the request passed into the constructor
*/
public HttpServletRequest wrapRequest(HttpServletRequest request)
{
return new RequestWrapper(request);
}
/**
* Our own flavour of HTTP request wrapper, that uses information from this
* RequestInfo object
*/
class RequestWrapper extends HttpServletRequestWrapper
{
public RequestWrapper(HttpServletRequest request) {
super(request);
}
public String getAuthType() {
return authType;
}
public String getContextPath() {
return contextPath;
}
public String getMethod() {
return method;
}
public String getPathInfo() {
return pathInfo;
}
public String getPathTranslated() {
return pathTranslated;
}
public String getQueryString() {
return queryString;
}
public String getRequestURI() {
return requestURI;
}
public StringBuffer getRequestURL() {
return requestURL;
}
public String getServletPath() {
return servletPath;
}
public String getParameter(String arg0) {
String[] values = parameters.get(arg0);
if (values == null || values.length == 0)
{
return null;
}
else
{
return values[0];
}
}
public Map getParameterMap() {
return parameters;
}
public Enumeration getParameterNames() {
Iterator parameterIterator = parameters.keySet().iterator();
return new EnumIterator(parameterIterator);
}
public String[] getParameterValues(String arg0) {
return parameters.get(arg0);
}
public String getScheme() {
return scheme;
}
public boolean isSecure() {
return secure;
}
// Here are other prototypes that are included in the 2.3 servlet spec:
//
// public Cookie[] getCookies()
// public long getDateHeader(String arg0)
// public String getHeader(String arg0)
// public Enumeration getHeaderNames()
// public Enumeration getHeaders(String arg0)
// public int getIntHeader(String arg0)
// public String getRemoteUser()
// public String getRequestedSessionId()
// public HttpSession getSession()
// public HttpSession getSession(boolean arg0)
// public Principal getUserPrincipal()
// public boolean isRequestedSessionIdFromCookie()
// public boolean isRequestedSessionIdFromURL()
// public boolean isRequestedSessionIdFromUrl()
// public boolean isRequestedSessionIdValid()
// public boolean isUserInRole(String arg0)
// public Object getAttribute(String arg0)
// public Enumeration getAttributeNames()
// public String getCharacterEncoding()
// public int getContentLength()
// public String getContentType()
// public ServletInputStream getInputStream() throws IOException
// public Locale getLocale()
// public Enumeration getLocales()
// public String getProtocol()
// public BufferedReader getReader() throws IOException
// public String getRealPath(String arg0)
// public String getRemoteAddr()
// public String getRemoteHost()
// public RequestDispatcher getRequestDispatcher(String arg0)
// public String getServerName()
// public int getServerPort()
// public void removeAttribute(String arg0)
// public void setAttribute(String arg0, Object arg1)
// public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException
/**
* This class converts an interator into an enumerator. This is done
* because we have the parameters as a Map (JDK 1.2 style), but for some
* weird reason the HttpServletRequest interface returns an Enumeration
* from getParameterNames() (JDK1.0 style.) JDK apparently offers no way
* of simply changing between the new styles.
*/
class EnumIterator implements Enumeration
{
private Iterator iterator;
public EnumIterator(Iterator i)
{
iterator = i;
}
public boolean hasMoreElements()
{
return iterator.hasNext();
}
public Object nextElement()
{
return iterator.next();
}
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.objectmanager;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
* This is a Swiss army like SAX Filter, its purpose is to filter out
* undesirable SAX events from the stream. The primary application of
* this is for inserting SAX fragment into an existing SAX pipeline,
* under this scenario you would not want new startDocument or
* endDocument events interfering with the existing pipeline thus
* this class can filter those out.
*
* The Swiss army part comes in because it's configurable. Instead of
* defining a static set of events that are filled out by default all
* events are filled out and must be turned on to allow each type
* Individually.
*
* Primarily you can filter events based upon their type, i.e. start/end
* elements or start/end documents. However there is one special control,
* and that is to only allow elements below a minimum level.
* .
*
* @author Scott Phillips
*/
public class SAXFilter implements ContentHandler, LexicalHandler
{
/** Control for which type of SAX events to allow */
private boolean allowDocuments = false;
private boolean allowDocumentLocators = false;
private boolean allowProcessingInstructions = false;
private boolean allowPrefixMappings = false;
private boolean allowElements = false;
private boolean allowIgnorableWhitespace = false;
private boolean allowSkippedEntities = false;
private boolean allowCharacters = false;
private boolean allowDTDs = false;
private boolean allowEntities = false;
private boolean allowCDATA = false;
private boolean allowComments = false;
/** The minimum level an element must be before it will be allowed */
private int minimumElementLevel = -1;
/**
* The current XML level, each time start element is encountered this
* is increased, and each time an end element is encountered it is
* decreased.
*/
private int currentElementLevel = 0;
/**
* If no URI is provided then substitute this default prefix and URI:
*/
private String defaultURI;
/** The SAX handlers and namespace support */
private ContentHandler contentHandler;
private LexicalHandler lexicalHandler;
private NamespaceSupport namespaces;
/**
* Construct a new SAXFilter such that the allowed events will be routed
* to the corresponding content and lexical handlers.
*
* @param contentHandler The SAX content handler.
* @param lexicalHandler The SAX lexical handler.
* @param namespaces Namespace support which records what prefixes have been defined.
*/
public SAXFilter(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces)
{
this.contentHandler = contentHandler;
this.lexicalHandler = lexicalHandler;
this.namespaces = namespaces;
}
/** Allow start/end document events */
public SAXFilter allowDocuments() {
this.allowDocuments = true;
return this;
}
/** Allow document locator events */
public SAXFilter allowDocumentLocators() {
this.allowDocumentLocators = true;
return this;
}
/** Allow processing instruction events */
public SAXFilter allowProcessingInstructions() {
this.allowProcessingInstructions = true;
return this;
}
/** allow start/end prefix mapping events */
public SAXFilter allowPrefixMappings() {
this.allowPrefixMappings = true;
return this;
}
/** allow start/end element events */
public SAXFilter allowElements() {
this.allowElements = true;
return this;
}
/**
* Allow start/end element events.
*
* However only allow those start / end events if
* they are below the given XML level. I.e. each nested
* element is a new level.
*
* @param minimumElementLevel
* the minimum level required.
* @return
*/
public SAXFilter allowElements(int minimumElementLevel)
{
this.allowElements = true;
this.minimumElementLevel = minimumElementLevel;
return this;
}
/** Allow ignorable whitespace events */
public SAXFilter allowIgnorableWhitespace() {
this.allowIgnorableWhitespace = true;
return this;
}
/** Allow start / end events for skipped entities */
public SAXFilter allowSkippedEntities() {
this.allowSkippedEntities = true;
return this;
}
/** Allow character events */
public SAXFilter allowCharacters() {
this.allowCharacters = true;
return this;
}
/** Allow DTD events */
public SAXFilter allowDTDs() {
this.allowDTDs = true;
return this;
}
/** Allow XML entities events */
public SAXFilter allowEntities() {
this.allowEntities = true;
return this;
}
/** Allow CDATA events */
public SAXFilter allowCDATA() {
this.allowCDATA = true;
return this;
}
/** Allow comment events */
public SAXFilter allowComments() {
this.allowComments = true;
return this;
}
/**
* Add a default namespace is none is provided. The namespace
* should have allready been declared (add added to the
* namespace support object
*
* @param uri the default namespace uri.
*/
public SAXFilter setDefaultNamespace(String uri)
{
this.defaultURI = uri;
return this;
}
/**
* SAX Content events
*/
public void startDocument() throws SAXException
{
if (allowDocuments)
{
contentHandler.startDocument();
}
}
public void endDocument() throws SAXException
{
if (allowDocuments)
{
contentHandler.endDocument();
}
}
public void setDocumentLocator(Locator locator)
{
if (allowDocumentLocators)
{
contentHandler.setDocumentLocator(locator);
}
}
public void processingInstruction(String target, String data)
throws SAXException
{
if (allowProcessingInstructions)
{
contentHandler.processingInstruction(target, data);
}
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
if (allowPrefixMappings)
{
contentHandler.startPrefixMapping(prefix, uri);
}
}
public void endPrefixMapping(String prefix) throws SAXException
{
if (allowPrefixMappings)
{
contentHandler.endPrefixMapping(prefix);
}
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException
{
if (allowElements)
{
currentElementLevel++;
// check if we are past the minimum level requirement
if (minimumElementLevel < currentElementLevel)
{
if (defaultURI != null && (uri == null || "".equals(uri)))
{
// No namespace provided, use the default namespace.
String prefix = namespaces.getPrefix(defaultURI);
if (!(prefix == null || "".equals(prefix)))
{
qName = prefix+":"+localName;
}
contentHandler.startElement(defaultURI, localName, qName, atts);
}
else
{
// let the event pass through unmodified.
contentHandler.startElement(uri, localName, localName, atts);
}
}
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException
{
if (allowElements)
{
// check if we are past the minimum level requirements
if (minimumElementLevel < currentElementLevel)
{
if (defaultURI != null && (uri == null || "".equals(uri)))
{
// No namespace provided, use the default namespace.
String prefix = namespaces.getPrefix(defaultURI);
if (!(prefix == null || "".equals(prefix)))
{
qName = prefix+":"+localName;
}
contentHandler.endElement(defaultURI, localName, qName);
}
else
{
// Let the event pass through unmodified.
contentHandler.endElement(uri, localName, localName);
}
}
currentElementLevel--;
}
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException
{
if (allowIgnorableWhitespace)
{
contentHandler.ignorableWhitespace(ch, start, length);
}
}
public void skippedEntity(String name) throws SAXException
{
if (allowSkippedEntities)
{
contentHandler.skippedEntity(name);
}
}
public void characters(char[] ch, int start, int length)
throws SAXException
{
if (allowCharacters)
{
contentHandler.characters(ch, start, length);
}
}
/**
* SAX Lexical events
*/
public void startDTD(String name, String publicId, String systemId)
throws SAXException
{
if (allowDTDs)
{
lexicalHandler.startDTD(name, publicId, systemId);
}
}
public void endDTD() throws SAXException
{
if (allowDTDs)
{
lexicalHandler.endDTD();
}
}
public void startEntity(String name)
throws SAXException
{
if (allowEntities)
{
lexicalHandler.startEntity(name);
}
}
public void endEntity(String name)
throws SAXException
{
if (allowEntities)
{
lexicalHandler.endEntity(name);
}
}
public void startCDATA()
throws SAXException
{
if (allowCDATA)
{
lexicalHandler.startCDATA();
}
}
public void endCDATA()
throws SAXException
{
if (allowCDATA)
{
lexicalHandler.endCDATA();
}
}
public void comment(char[] ch, int start, int length)
throws SAXException
{
if (allowComments)
{
lexicalHandler.comment(ch, start, length);
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.objectmanager;
import java.sql.SQLException;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.Namespace;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.handle.HandleManager;
import org.xml.sax.SAXException;
/**
* This is an an adapter which translates a DSpace repository into a METS
* document. Unfortunately there is no real definition of what this is. So
* we just kind of made it up based upon what we saw for the item profile.
*
* The basic structure is simply two parts, the descriptive metadata and a
* structural map. The descriptive metadata is a place to put metadata about
* the whole repository. The structural map is used to map relationships
* between communities & collections in dspace.
*
* @author Scott Phillips
*/
public class RepositoryAdapter extends AbstractAdapter
{
/** MODS namespace */
public static final String MODS_URI = "http://www.loc.gov/mods/v3";
public static final Namespace MODS = new Namespace(MODS_URI);
/** A space separated list of descriptive metadata sections */
private String dmdSecIDS;
/** Dspace context to be able to look up additional objects */
private Context context;
/**
* Construct a new RepositoryAdapter
*
* @param context
* The DSpace context to look up communities / collections.
*
* @param contextPath
* The contextPath of this webapplication.
*/
public RepositoryAdapter(Context context, String contextPath)
{
super(contextPath);
this.context = context;
}
/**
*
*
*
* Abstract methods
*
*
*
*/
/**
* Return the handle prefix as the identifier.
*/
protected String getMETSID()
{
return HandleManager.getPrefix();
}
/**
* The OBJID is used to encode the URL to the object, in this
* case the repository which is just at the contextPath.
*/
protected String getMETSOBJID() throws WingException {
if (contextPath == null)
{
return "/";
}
else
{
return contextPath + "/";
}
}
/**
* @return Return the URL for editing this item
*/
protected String getMETSOBJEDIT()
{
return null;
}
/**
* Return the profile this METS document conforms too...
*
* FIXME: It dosn't conform to a profile. This needs to be fixed.
*/
protected String getMETSProfile()
{
return "DRI DSPACE Repository Profile 1.0";
}
/**
* Return a friendly label for the METS document stating that this is a
* DSpace repository.
*/
protected String getMETSLabel()
{
return "DSpace Repository";
}
/**
*
*
*
* METS structural methods
*
*
*
*/
/**
* Render the repository's descriptive metadata section.
*
* For a the DSPace repository we just grab a few items
* from the config file and put them into the descriptive
* section, such as the name, hostname, handle prefix, and
* default language.
*
*/
protected void renderDescriptiveSection() throws SAXException
{
AttributeMap attributes;
// Generate our ids
String dmdID = getGenericID("dmd_");
String groupID = getGenericID("group_dmd_");
// ////////////////////////////////
// Start a single dmdSec
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS,"dmdSec",attributes);
// ////////////////////////////////
// Start a metadata wrapper (hardcoded to mods)
attributes = new AttributeMap();
attributes.put("MDTYPE", "OTHER");
attributes.put("OTHERMDTYPE", "DIM");
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
/////////////////////////////////
// Start the DIM element
attributes = new AttributeMap();
attributes.put("dspaceType", Constants.typeText[Constants.SITE]);
startElement(DIM,"dim",attributes);
// Entry for dspace.name
attributes = new AttributeMap();
attributes.put("mdschema","dspace");
attributes.put("element", "name");
startElement(DIM,"field",attributes);
sendCharacters(ConfigurationManager.getProperty("dspace.name"));
endElement(DIM,"field");
// Entry for dspace.hostname
attributes = new AttributeMap();
attributes.put("mdschema","dspace");
attributes.put("element", "hostname");
startElement(DIM,"field",attributes);
sendCharacters(ConfigurationManager.getProperty("dspace.hostname"));
endElement(DIM,"field");
// Entry for handle.prefix
attributes = new AttributeMap();
attributes.put("mdschema","dspace");
attributes.put("element", "handle");
startElement(DIM,"field",attributes);
sendCharacters(HandleManager.getPrefix());
endElement(DIM,"field");
// Entry for default.language
attributes = new AttributeMap();
attributes.put("mdschema","dspace");
attributes.put("element", "default");
attributes.put("qualifier", "language");
startElement(DIM,"field",attributes);
sendCharacters(ConfigurationManager.getProperty("default.language"));
endElement(DIM,"field");
// ///////////////////////////////
// End the DIM element
endElement(DIM,"dim");
// End all the open elements.
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS,"dmdSec");
// Remember the IDS
this.dmdSecIDS = dmdID;
}
/**
* Render the repository's structure map. This map will include a reference to
* all the community and collection objects showing how they are related to
* one another.
*/
protected void renderStructureMap() throws SQLException, SAXException
{
AttributeMap attributes;
// //////////////////////////
// Start the new struct map
attributes = new AttributeMap();
attributes.put("TYPE", "LOGICAL");
attributes.put("LABEL", "DSpace");
startElement(METS,"structMap",attributes);
// ////////////////////////////////
// Start the special first division
attributes = new AttributeMap();
attributes.put("TYPE", "DSpace Repository");
// add references to the Descriptive metadata
if (dmdSecIDS != null)
{
attributes.put("DMDID", dmdSecIDS);
}
startElement(METS,"div",attributes);
// Put each root level node into the document.
for (Community community : Community.findAllTop(context))
{
renderStructuralDiv(community);
}
// //////////////////
// Close special first division and structural map
endElement(METS,"div");
endElement(METS,"structMap");
}
/**
*
*
*
* private helpful methods
*
*
*
*/
/**
* Recursively the DSpace hierarchy rendering each container and subcontainers.
*
* @param dso
* The DSpace Object to be rendered.
*/
private void renderStructuralDiv(DSpaceObject dso) throws SAXException, SQLException
{
AttributeMap attributes;
// ////////////////////////////////
// Start the new div for this repository container
attributes = new AttributeMap();
if (dso instanceof Community)
{
attributes.put("TYPE", "DSpace Community");
}
else if (dso instanceof Collection)
{
attributes.put("TYPE", "DSpace Collection");
}
startElement(METS,"div",attributes);
// //////////////////////////////////
// Start a metadata pointer for this container
attributes = new AttributeMap();
AttributeMap attributesXLINK = new AttributeMap();
attributesXLINK.setNamespace(XLINK);
attributes.put("LOCTYPE", "URL");
attributesXLINK.put("href", "/metadata/handle/"+ dso.getHandle() +"/mets.xml");
startElement(METS,"mptr",attributes,attributesXLINK);
endElement(METS,"mptr");
// Recurse to insure that our children are also included even if this
// node already existed in the div structure.
if (dso instanceof Community)
{
for (DSpaceObject child : ((Community)dso).getCollections())
{
renderStructuralDiv(child);
}
for (DSpaceObject child : ((Community)dso).getSubcommunities())
{
renderStructuralDiv(child);
}
}
// ////////////////////
// Close division
endElement(METS,"div");
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.objectmanager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dspace.app.util.Util;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.Namespace;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Item;
import org.dspace.content.crosswalk.CrosswalkException;
import org.dspace.content.crosswalk.DisseminationCrosswalk;
import org.dspace.core.PluginManager;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.NamespaceSupport;
/**
* This is the abstract adapter containing all the common elements between
* the three types of adapters: item, container, and repository. Each adapter
* translate a given type of DSpace object into a METS document for rendering
* into the DRI document.
*
* This class provides the chassis for those unique parts of the document to be
* build upon, there are seven rendering methods that may be overridden for each
* section of the METS document.
*
* Header
* Descriptive Section
* Administrative Section
* File Section
* Structure Map
* Structural Link
* Behavioral Section
*
* @author Scott Phillips
*/
public abstract class AbstractAdapter
{
/** Namespace declaration for METS & XLINK */
public static final String METS_URI = "http://www.loc.gov/METS/";
public static final Namespace METS = new Namespace(METS_URI);
public static final String XLINK_URI = "http://www.w3.org/TR/xlink/";
public static final Namespace XLINK = new Namespace(XLINK_URI);
public static final String XSI_URI = "http://www.w3.org/2001/XMLSchema-instance";
public static final Namespace XSI = new Namespace(XSI_URI);
public static final String DIM_URI = "http://www.dspace.org/xmlns/dspace/dim";
public static final Namespace DIM = new Namespace(DIM_URI);
/**
* A sequence used to generate unique mets ids.
*/
private int idSequence = 0;
/**
* The contextPath of this web application, used for generating URLs.
*/
protected String contextPath;
/**
* The SAX handlers for content and lexical events. Also the support
* element for namespaces which knows the prefixes for each declared
* namespace.
*/
protected ContentHandler contentHandler;
protected LexicalHandler lexicalHandler;
protected NamespaceSupport namespaces;
/**
* Construct a new adapter, implementers must use call this method so
* the appropriate internal values are insured to be set correctly.
*
* @param contextPath
* The contextPath of this web application.
*/
public AbstractAdapter(String contextPath)
{
this.contextPath = contextPath;
}
/** The variables that dictate what part of the METS document to render */
List<String> sections = new ArrayList<String>();
List<String> dmdTypes = new ArrayList<String>();
Map<String,List> amdTypes = new HashMap<String,List>();
List<String> fileGrpTypes = new ArrayList<String>();
List<String> structTypes = new ArrayList<String>();
/**
* A comma separated list of METS sections to render. If no value
* is provided then all METS sections are rendered.
*
* @param sections Comma separated list of METS sections.
*/
public final void setSections(String sections)
{
if (sections == null)
{
return;
}
for (String section : sections.split(","))
{
this.sections.add(section);
}
}
/**
* A comma separated list of METS descriptive metadata formats to
* render. If no value is provided then only the DIM format is used.
*
* @param dmdTypes Comma separated list of METS metadata types.
*/
public final void setDmdTypes(String dmdTypes)
{
if (dmdTypes == null)
{
return;
}
for (String dmdType : dmdTypes.split(","))
{
this.dmdTypes.add(dmdType);
}
}
/**
* Store information about what will be rendered in the METS administrative
* metadata section. HashMap format: keys = amdSec, value = List of mdTypes
*
* @param amdSec Section of <amdSec> where this administrative metadata
* will be rendered
* @param mdTypes Comma separated list of METS metadata types.
*/
public final void setAmdTypes(String amdSec, String mdTypes)
{
if (mdTypes == null)
{
return;
}
List<String> mdTypeList = new ArrayList<String>();
for (String mdType : mdTypes.split(","))
{
mdTypeList.add(mdType);
}
this.amdTypes.put(amdSec, mdTypeList);
}
/**
* A comma separated list of METS technical metadata formats to
* render.
*
* @param techMDTypes Comma separated list of METS metadata types.
*/
public final void setTechMDTypes(String techMDTypes)
{
setAmdTypes("techMD", techMDTypes);
}
/**
* A comma separated list of METS intellectual property rights metadata
* formats to render.
*
* @param rightsMDTypes Comma separated list of METS metadata types.
*/
public final void setRightsMDTypes(String rightsMDTypes)
{
setAmdTypes("rightsMD", rightsMDTypes);
}
/**
* A comma separated list of METS source metadata
* formats to render.
*
* @param sourceMDTypes Comma separated list of METS metadata types.
*/
public final void setSourceMDTypes(String sourceMDTypes)
{
setAmdTypes("sourceMD", sourceMDTypes);
}
/**
* A comma separated list of METS digital provenance metadata
* formats to render.
*
* @param digiprovMDTypes Comma separated list of METS metadata types.
*/
public final void setDigiProvMDTypes(String digiprovMDTypes)
{
setAmdTypes("digiprovMD", digiprovMDTypes);
}
/**
* A comma separated list of METS fileGrps to render. If no value
* is provided then all groups are rendered.
*
* @param fileGrpTypes Comma separated list of METS file groups.
*/
public final void setFileGrpTypes(String fileGrpTypes)
{
if (fileGrpTypes == null)
{
return;
}
for (String fileGrpType : fileGrpTypes.split(","))
{
this.fileGrpTypes.add(fileGrpType);
}
}
/**
* A comma separated list of METS structural types to render. If no
* value is provided then only the DIM format is used.
*
* @param structTypes Comma separated list of METS structure types.
*/
public final void setStructTypes(String structTypes)
{
if (structTypes == null)
{
return;
}
for (String structType : structTypes.split(","))
{
this.structTypes.add(structType);
}
}
/**
*
*
*
*
*
* METS methods
*
*
*
*
*
*
*/
/**
* @return the URL for this item in the interface
*/
protected abstract String getMETSOBJID() throws WingException;
/**
* @return Return the URL for editing this item
*/
protected abstract String getMETSOBJEDIT();
/**
* @return the METS ID of the mets document.
*/
protected abstract String getMETSID() throws WingException;
/**
* @return The Profile this METS document conforms too.
*/
protected abstract String getMETSProfile() throws WingException;
/**
* @return The label of this METS document.
*/
protected abstract String getMETSLabel() throws WingException;
/**
* Render the complete METS document.
*/
public final void renderMETS(ContentHandler contentHandler, LexicalHandler lexicalHandler) throws WingException, SAXException, CrosswalkException, IOException, SQLException
{
this.contentHandler = contentHandler;
this.lexicalHandler = lexicalHandler;
this.namespaces = new NamespaceSupport();
// Declare our namespaces
namespaces.pushContext();
namespaces.declarePrefix("mets", METS.URI);
namespaces.declarePrefix("xlink", XLINK.URI);
namespaces.declarePrefix("xsi", XSI.URI);
namespaces.declarePrefix("dim", DIM.URI);
contentHandler.startPrefixMapping("mets", METS.URI);
contentHandler.startPrefixMapping("xlink", XLINK.URI);
contentHandler.startPrefixMapping("xsi", XSI.URI);
contentHandler.startPrefixMapping("dim", DIM.URI);
// Send the METS element
AttributeMap attributes = new AttributeMap();
attributes.put("ID", getMETSID());
attributes.put("PROFILE", getMETSProfile());
attributes.put("LABEL", getMETSLabel());
String objid = getMETSOBJID();
if (objid != null)
{
attributes.put("OBJID", objid);
}
// Include the link for editing the item
objid = getMETSOBJEDIT();
if (objid != null)
{
attributes.put("OBJEDIT", objid);
}
startElement(METS,"METS",attributes);
// If the user requested no specific sections then render them all.
boolean all = (sections.size() == 0);
if (all || sections.contains("metsHdr"))
{
renderHeader();
}
if (all || sections.contains("dmdSec"))
{
renderDescriptiveSection();
}
if (all || sections.contains("amdSec"))
{
renderAdministrativeSection();
}
if (all || sections.contains("fileSec"))
{
renderFileSection();
}
if (all || sections.contains("structMap"))
{
renderStructureMap();
}
if (all || sections.contains("structLink"))
{
renderStructuralLink();
}
if (all || sections.contains("behaviorSec"))
{
renderBehavioralSection();
}
// FIXME: this is not a met's section, it should be removed
if (all || sections.contains("extraSec"))
{
renderExtraSections();
}
endElement(METS,"METS");
contentHandler.endPrefixMapping("mets");
contentHandler.endPrefixMapping("xlink");
contentHandler.endPrefixMapping("dim");
namespaces.popContext();
}
/**
* Each of the METS sections
*/
protected void renderHeader() throws WingException, SAXException, CrosswalkException, IOException, SQLException {}
protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {}
protected void renderAdministrativeSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {}
protected void renderFileSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {}
protected void renderStructureMap() throws WingException, SAXException, CrosswalkException, IOException, SQLException {}
protected void renderStructuralLink() throws WingException, SAXException, CrosswalkException, IOException, SQLException {}
protected void renderBehavioralSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {}
protected void renderExtraSections() throws WingException, SAXException, CrosswalkException, SQLException, IOException {}
/**
* Generate a METS file element for a given bitstream.
*
* @param item
* If the bitstream is associated with an item provide the item
* otherwise leave null.
* @param bitstream
* The bitstream to build a file element for.
* @param fileID
* The unique file id for this file.
* @param groupID
* The group id for this file, if it is derived from another file
* then they should share the same groupID.
*/
protected final void renderFile(Item item, Bitstream bitstream, String fileID, String groupID) throws SAXException
{
renderFile(item, bitstream, fileID, groupID, null);
}
/**
* Generate a METS file element for a given bitstream.
*
* @param item
* If the bitstream is associated with an item provide the item
* otherwise leave null.
* @param bitstream
* The bitstream to build a file element for.
* @param fileID
* The unique file id for this file.
* @param groupID
* The group id for this file, if it is derived from another file
* then they should share the same groupID.
* @param admID
* The IDs of the administrative metadata sections which pertain
* to this file
*/
protected final void renderFile(Item item, Bitstream bitstream, String fileID, String groupID, String admID) throws SAXException
{
AttributeMap attributes;
// //////////////////////////////
// Determine the file attributes
BitstreamFormat format = bitstream.getFormat();
String mimeType = null;
if (format != null)
{
mimeType = format.getMIMEType();
}
String checksumType = bitstream.getChecksumAlgorithm();
String checksum = bitstream.getChecksum();
long size = bitstream.getSize();
// ////////////////////////////////
// Start the actual file
attributes = new AttributeMap();
attributes.put("ID", fileID);
attributes.put("GROUPID",groupID);
if (admID != null && admID.length()>0)
{
attributes.put("ADMID", admID);
}
if (mimeType != null && mimeType.length()>0)
{
attributes.put("MIMETYPE", mimeType);
}
if (checksumType != null && checksum != null)
{
attributes.put("CHECKSUM", checksum);
attributes.put("CHECKSUMTYPE", checksumType);
}
attributes.put("SIZE", String.valueOf(size));
startElement(METS,"file",attributes);
// ////////////////////////////////////
// Determine the file location attributes
String name = bitstream.getName();
String description = bitstream.getDescription();
// If possible reference this bitstream via a handle, however this may
// be null if a handle has not yet been assigned. In this case reference the
// item its internal id. In the last case where the bitstream is not associated
// with an item (such as a community logo) then reference the bitstreamID directly.
String identifier = null;
if (item != null && item.getHandle() != null)
{
identifier = "handle/" + item.getHandle();
}
else if (item != null)
{
identifier = "item/" + item.getID();
}
else
{
identifier = "id/" + bitstream.getID();
}
String url = contextPath + "/bitstream/"+identifier+"/";
// If we can put the pretty name of the bitstream on the end of the URL
try
{
if (bitstream.getName() != null)
{
url += Util.encodeBitstreamName(bitstream.getName(), "UTF-8");
}
}
catch (UnsupportedEncodingException uee)
{
// just ignore it, we don't have to have a pretty
// name on the end of the URL because the sequence id will
// locate it. However it means that links in this file might
// not work....
}
url += "?sequence="+bitstream.getSequenceID();
// //////////////////////
// Start the file location
attributes = new AttributeMap();
AttributeMap attributesXLINK = new AttributeMap();
attributesXLINK.setNamespace(XLINK);
attributes.put("LOCTYPE", "URL");
attributesXLINK.put("type","locator");
attributesXLINK.put("title", name);
if (description != null)
{
attributesXLINK.put("label", description);
}
attributesXLINK.put("href", url);
startElement(METS,"FLocat",attributes,attributesXLINK);
// ///////////////////////
// End file location
endElement(METS,"FLocate");
// ////////////////////////////////
// End the file
endElement(METS,"file");
}
/**
*
* Generate a unique METS id. For consistency, all prefixes should probably
* end in an underscore, "_".
*
* @param prefix
* Prefix to prepend to the id for readability.
*
* @return A unique METS id.
*/
protected final String getGenericID(String prefix)
{
return prefix + (idSequence++);
}
/**
* Return a dissemination crosswalk for the given name.
*
* @param crosswalkName
* @return The crosswalk or throw an exception if not found.
*/
public final DisseminationCrosswalk getDisseminationCrosswalk(String crosswalkName) throws WingException
{
// FIXME add some caching here
DisseminationCrosswalk crosswalk = (DisseminationCrosswalk) PluginManager.getNamedPlugin(DisseminationCrosswalk.class, crosswalkName);
if (crosswalk == null)
{
throw new WingException("Unable to find named DisseminationCrosswalk: " + crosswalkName);
}
return crosswalk;
}
/**
* The METS defined types of Metadata, if a format is not listed here
* then it should use the string "OTHER" and provide additional
* attributes describing the metadata type
*/
public static final String[] METS_DEFINED_TYPES =
{"MARC","MODS","EAD","DC","NISOIMG","LC-AV","VRA","TEIHDR","DDI","FGDC","PREMIS"/*,"OTHER"*/};
/**
* Determine if the provided metadata type is a standard METS
* defined type. If it is not, use the other string.
*
* @param metadataType type name
* @return True if METS defined
*/
public final boolean isDefinedMETStype(String metadataType)
{
for (String definedType : METS_DEFINED_TYPES)
{
if (definedType.equals(metadataType))
{
return true;
}
}
return false;
}
/**
*
*
* SAX Helper methods
*
*
*
*/
/**
* Send the SAX events to start this element.
*
* @param namespace
* (Required) The namespace of this element.
* @param name
* (Required) The local name of this element.
* @param attributes
* (May be null) Attributes for this element
*/
protected final void startElement(Namespace namespace, String name,
AttributeMap... attributes) throws SAXException
{
contentHandler.startElement(namespace.URI, name, qName(namespace, name),
map2sax(namespace,attributes));
}
/**
* Send the SAX event for these plain characters, not wrapped in any
* elements.
*
* @param characters
* (May be null) Characters to send.
*/
protected final void sendCharacters(String characters) throws SAXException
{
if (characters != null)
{
char[] contentArray = characters.toCharArray();
contentHandler.characters(contentArray, 0, contentArray.length);
}
}
/**
* Send the SAX events to end this element.
*
* @param namespace
* (Required) The namespace of this element.
* @param name
* (Required) The local name of this element.
*/
protected final void endElement(Namespace namespace, String name)
throws SAXException
{
contentHandler.endElement(namespace.URI, name, qName(namespace, name));
}
/**
* Build the SAX attributes object based upon Java's String map. This
* convenience method will build, or add to an existing attributes object,
* the attributes detailed in the AttributeMap.
*
* @param elementNamespace
* SAX Helper class to keep track of namespaces able to determine
* the correct prefix for a given namespace URI.
* @param attributes
* An existing SAX AttributesImpl object to add attributes too.
* If the value is null then a new attributes object will be
* created to house the attributes.
* @param attributeMap
* A map of attributes and values.
* @return
*/
private AttributesImpl map2sax(Namespace elementNamespace, AttributeMap ... attributeMaps)
{
AttributesImpl attributes = new AttributesImpl();
for (AttributeMap attributeMap : attributeMaps)
{
boolean diffrentNamespaces = false;
Namespace attributeNamespace = attributeMap.getNamespace();
if (attributeNamespace != null && !(attributeNamespace.URI.equals(elementNamespace.URI)))
{
diffrentNamespaces = true;
}
// copy each one over.
for (Map.Entry<String, String> attr : attributeMap.entrySet())
{
if (attr.getValue() == null)
{
continue;
}
if (diffrentNamespaces)
{
attributes.addAttribute(attributeNamespace.URI, attr.getKey(),
qName(attributeNamespace, attr.getKey()), "CDATA", attr.getValue());
}
else
{
attributes.addAttribute("", attr.getKey(), attr.getKey(), "CDATA", attr.getValue());
}
}
}
return attributes;
}
/**
* Create the qName for the element with the given localName and namespace
* prefix.
*
* @param namespace
* (May be null) The namespace prefix.
* @param localName
* (Required) The element's local name.
* @return
*/
private String qName(Namespace namespace, String localName)
{
String prefix = namespaces.getPrefix(namespace.URI);
if (prefix == null || prefix.equals(""))
{
return localName;
}
else
{
return prefix + ":" + localName;
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.objectmanager;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.ItemCounter;
import org.dspace.browse.ItemCountException;
import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.crosswalk.CrosswalkException;
import org.dspace.content.crosswalk.DisseminationCrosswalk;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.SAXOutputter;
import org.xml.sax.SAXException;
/**
* This is an adapter which translates DSpace containers
* (communities & collections) into METS documents. This adapter follows
* the DSpace METS profile however that profile does not define how a
* community or collection should be described, but we make the obvious
* decisions to deviate when nessasary from the profile.
*
* The METS document consists of three parts: descriptive metadata section,
* file section, and a structural map. The descriptive metadata sections holds
* metadata about the item being adapted using DSpace crosswalks. This is the
* same way the item adapter works.
*
* However the file section and structural map are a bit different. In these
* casses the the only files listed is the one logo that may be attached to
* a community or collection.
*
* @author Scott Phillips
*/
public class ContainerAdapter extends AbstractAdapter
{
private static final Logger log = Logger.getLogger(ContainerAdapter.class);
/** The community or collection this adapter represents. */
private DSpaceObject dso;
/** A space seperated list of descriptive metadata sections */
private StringBuffer dmdSecIDS;
/** Current DSpace context **/
private Context dspaceContext;
/**
* Construct a new CommunityCollectionMETSAdapter.
*
* @param dso
* A DSpace Community or Collection to adapt.
* @param contextPath
* The contextPath of this webapplication.
*/
public ContainerAdapter(Context context, DSpaceObject dso,String contextPath)
{
super(contextPath);
this.dso = dso;
this.dspaceContext = context;
}
/** Return the container, community or collection, object */
public DSpaceObject getContainer()
{
return this.dso;
}
/**
*
*
*
* Required abstract methods
*
*
*
*/
/**
* Return the URL of this community/collection in the interface
*/
protected String getMETSOBJID()
{
if (dso.getHandle() != null)
{
return contextPath + "/handle/" + dso.getHandle();
}
return null;
}
/**
* @return Return the URL for editing this item
*/
protected String getMETSOBJEDIT()
{
return null;
}
/**
* Use the handle as the id for this METS document
*/
protected String getMETSID()
{
if (dso.getHandle() == null)
{
if (dso instanceof Collection)
{
return "collection:" + dso.getID();
}
else
{
return "community:" + dso.getID();
}
}
else
{
return "hdl:" + dso.getHandle();
}
}
/**
* Return the profile to use for communities and collections.
*
*/
protected String getMETSProfile() throws WingException
{
return "DSPACE METS SIP Profile 1.0";
}
/**
* Return a friendly label for the METS document to say we are a community
* or collection.
*/
protected String getMETSLabel()
{
if (dso instanceof Community)
{
return "DSpace Community";
}
else
{
return "DSpace Collection";
}
}
/**
* Return a unique id for the given bitstream
*/
protected String getFileID(Bitstream bitstream)
{
return "file_" + bitstream.getID();
}
/**
* Return a group id for the given bitstream
*/
protected String getGroupFileID(Bitstream bitstream)
{
return "group_file_" + bitstream.getID();
}
/**
*
*
*
* METS structural methods
*
*
*
*/
/**
* Render the METS descriptive section. This will create a new metadata
* section for each crosswalk configured.
*
* Example:
* <dmdSec>
* <mdWrap MDTYPE="MODS">
* <xmlData>
* ... content from the crosswalk ...
* </xmlDate>
* </mdWrap>
* </dmdSec
*/
protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException
{
AttributeMap attributes;
String groupID = getGenericID("group_dmd_");
dmdSecIDS = new StringBuffer();
// Add DIM descriptive metadata if it was requested or if no metadata types
// were specified. Further more since this is the default type we also use a
// faster rendering method that the crosswalk API.
if(dmdTypes.size() == 0 || dmdTypes.contains("DIM"))
{
// Metadata element's ID
String dmdID = getGenericID("dmd_");
// Keep track of all descriptive sections
dmdSecIDS.append(dmdID);
// ////////////////////////////////
// Start a new dmdSec for each crosswalk.
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS,"dmdSec",attributes);
// ////////////////////////////////
// Start metadata wrapper
attributes = new AttributeMap();
attributes.put("MDTYPE", "OTHER");
attributes.put("OTHERMDTYPE", "DIM");
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Start the DIM element
attributes = new AttributeMap();
attributes.put("dspaceType", Constants.typeText[dso.getType()]);
startElement(DIM,"dim",attributes);
// Add each field for this collection
if (dso.getType() == Constants.COLLECTION)
{
Collection collection = (Collection) dso;
String description = collection.getMetadata("introductory_text");
String description_abstract = collection.getMetadata("short_description");
String description_table = collection.getMetadata("side_bar_text");
String identifier_uri = "http://hdl.handle.net/" + collection.getHandle();
String provenance = collection.getMetadata("provenance_description");
String rights = collection.getMetadata("copyright_text");
String rights_license = collection.getMetadata("license");
String title = collection.getMetadata("name");
createField("dc","description",null,null,description);
createField("dc","description","abstract",null,description_abstract);
createField("dc","description","tableofcontents",null,description_table);
createField("dc","identifier","uri",null,identifier_uri);
createField("dc","provenance",null,null,provenance);
createField("dc","rights",null,null,rights);
createField("dc","rights","license",null,rights_license);
createField("dc","title",null,null,title);
boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache");
//To improve scalability, XMLUI only adds item counts if they are cached
if (useCache)
{
try
{ //try to determine Collection size (i.e. # of items)
int size = new ItemCounter(this.dspaceContext).getCount(collection);
createField("dc","format","extent",null, String.valueOf(size));
}
catch(ItemCountException e)
{
throw new IOException("Could not obtain Collection item-count", e);
}
}
}
else if (dso.getType() == Constants.COMMUNITY)
{
Community community = (Community) dso;
String description = community.getMetadata("introductory_text");
String description_abstract = community.getMetadata("short_description");
String description_table = community.getMetadata("side_bar_text");
String identifier_uri = "http://hdl.handle.net/" + community.getHandle();
String rights = community.getMetadata("copyright_text");
String title = community.getMetadata("name");
createField("dc","description",null,null,description);
createField("dc","description","abstract",null,description_abstract);
createField("dc","description","tableofcontents",null,description_table);
createField("dc","identifier","uri",null,identifier_uri);
createField("dc","rights",null,null,rights);
createField("dc","title",null,null,title);
boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache");
//To improve scalability, XMLUI only adds item counts if they are cached
if (useCache)
{
try
{ //try to determine Community size (i.e. # of items)
int size = new ItemCounter(this.dspaceContext).getCount(community);
createField("dc","format","extent",null, String.valueOf(size));
}
catch(ItemCountException e)
{
throw new IOException("Could not obtain Collection item-count", e);
}
}
}
// ///////////////////////////////
// End the DIM element
endElement(DIM,"dim");
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
}
for (String dmdType : dmdTypes)
{
// If DIM was requested then it was generated above without using
// the crosswalk API. So we can skip this one.
if ("DIM".equals(dmdType))
{
continue;
}
DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType);
if (crosswalk == null)
{
continue;
}
String dmdID = getGenericID("dmd_");
// Add our id to the list.
dmdSecIDS.append(" ").append(dmdID);
// ////////////////////////////////
// Start a new dmdSec for each crosswalk.
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS,"dmdSec",attributes);
// ////////////////////////////////
// Start metadata wrapper
attributes = new AttributeMap();
if (isDefinedMETStype(dmdType))
{
attributes.put("MDTYPE", dmdType);
}
else
{
attributes.put("MDTYPE", "OTHER");
attributes.put("OTHERMDTYPE", dmdType);
}
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Send the actual XML content
try {
Element dissemination = crosswalk.disseminateElement(dso);
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
SAXOutputter outputter = new SAXOutputter();
outputter.setContentHandler(filter);
outputter.setLexicalHandler(filter);
outputter.output(dissemination);
}
catch (JDOMException jdome)
{
throw new WingException(jdome);
}
catch (AuthorizeException ae)
{
// just ignore the authorize exception and continue on with
//out parsing the xml document.
}
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
// Record keeping
if (dmdSecIDS == null)
{
dmdSecIDS = new StringBuffer(dmdID);
}
else
{
dmdSecIDS.append(" ").append(dmdID);
}
}
}
/**
* Render the METS file section. If a logo is present for this
* container then that single bitstream is listed in the
* file section.
*
* Example:
* <fileSec>
* <fileGrp USE="LOGO">
* <file ... >
* <fLocate ... >
* </file>
* </fileGrp>
* </fileSec>
*/
protected void renderFileSection() throws SAXException
{
AttributeMap attributes;
// Get the Community or Collection logo.
Bitstream logo = getLogo();
if (logo != null)
{
// ////////////////////////////////
// Start the file section
startElement(METS,"fileSec");
// ////////////////////////////////
// Start a new fileGrp for the logo.
attributes = new AttributeMap();
attributes.put("USE", "LOGO");
startElement(METS,"fileGrp",attributes);
// ////////////////////////////////
// Add the actual file element
String fileID = getFileID(logo);
String groupID = getGroupFileID(logo);
renderFile(null, logo, fileID, groupID);
// ////////////////////////////////
// End th file group and file section
endElement(METS,"fileGrp");
endElement(METS,"fileSec");
}
}
/**
* Render the container's structural map. This includes a refrence
* to the container's logo, if available, otherwise it is an empty
* division that just states it is a DSpace community or Collection.
*
* Examlpe:
* <structMap TYPE="LOGICAL" LABEL="DSpace">
* <div TYPE="DSpace Collection" DMDID="space seperated list of ids">
* <fptr FILEID="logo id"/>
* </div>
* </structMap>
*/
protected void renderStructureMap() throws SQLException, SAXException
{
AttributeMap attributes;
// ///////////////////////
// Start a new structure map
attributes = new AttributeMap();
attributes.put("TYPE", "LOGICAL");
attributes.put("LABEL", "DSpace");
startElement(METS,"structMap",attributes);
// ////////////////////////////////
// Start the special first division
attributes = new AttributeMap();
attributes.put("TYPE", getMETSLabel());
// add references to the Descriptive metadata
if (dmdSecIDS != null)
{
attributes.put("DMDID", dmdSecIDS.toString());
}
startElement(METS,"div",attributes);
// add a fptr pointer to the logo.
Bitstream logo = getLogo();
if (logo != null)
{
// ////////////////////////////////
// Add a refrence to the logo as the primary bitstream.
attributes = new AttributeMap();
attributes.put("FILEID",getFileID(logo));
startElement(METS,"fptr",attributes);
endElement(METS,"fptr");
// ///////////////////////////////////////////////
// Add a div for the publicaly viewable bitstreams (i.e. the logo)
attributes = new AttributeMap();
attributes.put("ID", getGenericID("div_"));
attributes.put("TYPE", "DSpace Content Bitstream");
startElement(METS,"div",attributes);
// ////////////////////////////////
// Add a refrence to the logo as the primary bitstream.
attributes = new AttributeMap();
attributes.put("FILEID",getFileID(logo));
startElement(METS,"fptr",attributes);
endElement(METS,"fptr");
// //////////////////////////
// End the logo division
endElement(METS,"div");
}
// ////////////////////////////////
// End the special first division
endElement(METS,"div");
// ///////////////////////
// End the structure map
endElement(METS,"structMap");
}
/**
*
*
*
* Private helpfull methods
*
*
*
*/
/**
* Return the logo bitstream associated with this community or collection.
* If there is no logo then null is returned.
*/
private Bitstream getLogo()
{
if (dso instanceof Community)
{
Community community = (Community) dso;
return community.getLogo();
}
else if (dso instanceof Collection)
{
Collection collection = (Collection) dso;
return collection.getLogo();
}
return null;
}
/**
* Count how many occurance there is of the given
* character in the given string.
*
* @param string The string value to be counted.
* @param character the character to count in the string.
*/
private int countOccurances(String string, char character)
{
if (string == null || string.length() == 0)
{
return 0;
}
int fromIndex = -1;
int count = 0;
while (true)
{
fromIndex = string.indexOf('>', fromIndex+1);
if (fromIndex == -1)
{
break;
}
count++;
}
return count;
}
/**
* Check if the given character sequence is located in the given
* string at the specified index. If it is then return true, otherwise false.
*
* @param string The string to test against
* @param index The location within the string
* @param characters The character sequence to look for.
* @return true if the character sequence was found, otherwise false.
*/
private boolean substringCompare(String string, int index, char ... characters)
{
// Is the string long enough?
if (string.length() <= index + characters.length)
{
return false;
}
// Do all the characters match?
for (char character : characters)
{
if (string.charAt(index) != character)
{
return false;
}
index++;
}
return false;
}
/**
* Create a new DIM field element with the given attributes.
*
* @param schema The schema the DIM field belongs too.
* @param element The element the DIM field belongs too.
* @param qualifier The qualifier the DIM field belongs too.
* @param language The language the DIM field belongs too.
* @param value The value of the DIM field.
* @return A new DIM field element
* @throws SAXException
*/
private void createField(String schema, String element, String qualifier, String language, String value) throws SAXException
{
// ///////////////////////////////
// Field element for each metadata field.
AttributeMap attributes = new AttributeMap();
attributes.put("mdschema",schema);
attributes.put("element", element);
if (qualifier != null)
{
attributes.put("qualifier", qualifier);
}
if (language != null)
{
attributes.put("language", language);
}
startElement(DIM,"field",attributes);
// Only try and add the metadata's value, but only if it is non null.
if (value != null)
{
// First, preform a queck check to see if the value may be XML.
int countOpen = countOccurances(value,'<');
int countClose = countOccurances(value, '>');
// If it passed the quick test, then try and parse the value.
Element xmlDocument = null;
if (countOpen > 0 && countOpen == countClose)
{
// This may be XML, First try and remove any bad entity refrences.
int amp = -1;
while ((amp = value.indexOf('&', amp+1)) > -1)
{
// Is it an xml entity named by number?
if (substringCompare(value,amp+1,'#'))
{
continue;
}
// &
if (substringCompare(value,amp+1,'a','m','p',';'))
{
continue;
}
// '
if (substringCompare(value,amp+1,'a','p','o','s',';'))
{
continue;
}
// "
if (substringCompare(value,amp+1,'q','u','o','t',';'))
{
continue;
}
// <
if (substringCompare(value,amp+1,'l','t',';'))
{
continue;
}
// >
if (substringCompare(value,amp+1,'g','t',';'))
{
continue;
}
// Replace the ampersand with an XML entity.
value = value.substring(0,amp) + "&" + value.substring(amp+1);
}
// Second try and parse the XML into a mini-dom
try {
// Wrap the value inside a root element (which will be trimed out
// by the SAX filter and set the default namespace to XHTML.
String xml = "<?xml version='1.0' encoding='UTF-8'?><fragment xmlns=\"http://www.w3.org/1999/xhtml\">"+value+"</fragment>";
ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(inputStream);
xmlDocument = document.getRootElement();
}
catch (Exception e)
{
log.trace("Caught exception", e);
}
}
// Third, If we have xml, attempt to serialize the dom.
if (xmlDocument != null)
{
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
// Special option, only allow elements below the second level to pass through. This
// will trim out the METS declaration and only leave the actual METS parts to be
// included.
filter.allowElements(1);
SAXOutputter outputter = new SAXOutputter();
outputter.setContentHandler(filter);
outputter.setLexicalHandler(filter);
try {
outputter.output(xmlDocument);
}
catch (JDOMException jdome)
{
// serialization failed so let's just fallback sending the plain characters.
sendCharacters(value);
}
}
else
{
// We don't have XML, so just send the plain old characters.
sendCharacters(value);
}
}
// //////////////////////////////
// Close out field
endElement(DIM,"field");
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.objectmanager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dspace.app.xmlui.wing.ObjectManager;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.browse.BrowseItem;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.handle.HandleManager;
/**
* The Wing ObjectManager implemented specificaly for DSpace. This manager
* is able identify all DSpace items, communities, and collections.
*
* @author Scott Phillips
*/
public class DSpaceObjectManager implements ObjectManager
{
/** List of all managed DSpaceObjects */
private List<DSpaceObject> dsos = new ArrayList<DSpaceObject>();
/**
* Manage the given object, if this manager is unable to manage the object then false must be returned.
*
* @param object
* The object to be managed.
* @return The object identifiers
*/
public boolean manageObject(Object object) throws WingException
{
// First check that the object is of a type we can manage.
if (object instanceof BrowseItem)
{
dsos.add((BrowseItem) object);
return true;
}
else if (object instanceof Item)
{
dsos.add((Item) object);
return true;
}
else if (object instanceof Collection)
{
dsos.add((Collection) object);
return true;
}
else if (object instanceof Community)
{
dsos.add((Community) object);
return true;
}
// We are unable to manage this object.
return false;
}
/**
* Return the metadata URL of the supplied object, assuming
* it's a DSpace item, community or collection.
*
*/
public String getObjectURL(Object object) throws WingException
{
if (object instanceof DSpaceObject)
{
DSpaceObject dso = (DSpaceObject) object;
String handle = dso.getHandle();
// If the object has a handle then refrence it by it's handle.
if (handle != null)
{
return "/metadata/handle/" + handle + "/mets.xml";
}
else
{
// No handle then refrence it by an internal ID.
if (dso instanceof Item || dso instanceof BrowseItem)
{
return "/metadata/internal/item/" + dso.getID() + "/mets.xml";
}
else if (object instanceof Collection)
{
return "/metadata/internal/collection/" + dso.getID() + "/mets.xml";
}
else if (object instanceof Community)
{
return "/metadata/internal/community/" + dso.getID() + "/mets.xml";
}
}
}
return null;
}
/**
* Return a pretty specific string giving a hint to the theme as to what
* type of DSpace object is being refrenced.
*/
public String getObjectType(Object object) throws WingException
{
if (object instanceof Item || object instanceof BrowseItem)
{
return "DSpace Item";
}
else if (object instanceof Collection)
{
return "DSpace Collection";
}
else if (object instanceof Community)
{
return "DSpace Community";
}
return null;
}
/**
* Return a globally unique identifier for the repository. For dspace, we
* use the handle prefix.
*/
public String getRepositoryIdentifier(Object object) throws WingException
{
return HandleManager.getPrefix();
}
/**
* Return the metadata URL for this repository.
*/
public String getRepositoryURL(Object object) throws WingException
{
String handlePrefix = ConfigurationManager.getProperty("handel.prefix");
return "/metadata/internal/repository/"+handlePrefix +"/mets.xml";
}
/**
* For the DSpace implementation we just return a hash of one entry which contains
* a reference to this repository's metadata.
*/
public Map<String,String> getAllManagedRepositories() throws WingException
{
String handlePrefix = HandleManager.getPrefix();
Map<String,String> allRepositories = new HashMap<String,String>();
allRepositories.put(handlePrefix, "/metadata/internal/repository/"+handlePrefix +"/mets.xml");
return allRepositories;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.objectmanager;
import org.dspace.app.util.MetadataExposure;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.authority.Choices;
import org.dspace.content.crosswalk.CrosswalkException;
import org.dspace.content.crosswalk.DisseminationCrosswalk;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.SAXOutputter;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.*;
import org.dspace.content.DSpaceObject;
/**
* This is an adapter which translate a DSpace item into a METS document
* following the DSpace METS profile, err well mostly. At least if you use
* the proper configuration it will be fully complaint with the profile,
* however this adapter will allow you to configure it to be incorrect.
*
* When we are configured to be non-complaint with the profile the MET's
* profile is changed to reflect the diviation. The DSpace profile states
* that metadata should be given in MODS format. However you can configure
* this adapter to use any metadata crosswalk. When that case is detected we
* change the profile to say that we are divating from the standard profile
* and it lists what metadata has been added.
*
* There are four parts to an item's METS document: descriptive metadata,
* file section, structural map, and extra sections.
*
* @author Scott Phillips
*/
public class ItemAdapter extends AbstractAdapter
{
/** The item this METS adapter represents */
private Item item;
/** List of bitstreams which should be publicaly viewable */
private List<Bitstream> contentBitstreams = new ArrayList<Bitstream>();
/** The primary bitstream, or null if none specified */
private Bitstream primaryBitstream;
/** A space seperated list of descriptive metadata sections */
private StringBuffer dmdSecIDS;
/** A space seperated list of administrative metadata sections (for item)*/
private StringBuffer amdSecIDS;
/** A hashmap of all Files and their corresponding space separated list of
administrative metadata sections */
private Map<String,StringBuffer> fileAmdSecIDs = new HashMap<String,StringBuffer>();
// DSpace DB context
private Context context;
/**
* Construct a new ItemAdapter
*
* @param item
* The DSpace item to adapt.
* @param contextPath
* The contextpath for this webapplication.
*/
public ItemAdapter(Context context, Item item,String contextPath)
{
super(contextPath);
this.item = item;
this.context = context;
}
/** Return the item */
public Item getItem()
{
return this.item;
}
/**
*
*
*
* Required abstract methods
*
*
*
*/
/**
* Return the URL of this item in the interface
*/
protected String getMETSOBJID()
{
if (item.getHandle() != null)
{
return contextPath + "/handle/" + item.getHandle();
}
return null;
}
/**
* @return Return the URL for editing this item
*/
protected String getMETSOBJEDIT()
{
return contextPath+"/admin/item?itemID=" + item.getID();
}
/**
* Return the item's handle as the METS ID
*/
protected String getMETSID()
{
if (item.getHandle() == null)
{
return "item:" + item.getID();
}
else
{
return "hdl:" + item.getHandle();
}
}
/**
* Return the official METS SIP Profile.
*/
protected String getMETSProfile() throws WingException
{
return "DSPACE METS SIP Profile 1.0";
}
/**
* Return a helpfull label that this is a DSpace Item.
*/
protected String getMETSLabel()
{
return "DSpace Item";
}
/**
* Return a unique id for a bitstream.
*/
protected String getFileID(Bitstream bitstream)
{
return "file_" + bitstream.getID();
}
/**
* Return a group id for a bitstream.
*/
protected String getGroupFileID(Bitstream bitstream)
{
return "group_file_" + bitstream.getID();
}
/**
* Return a techMD id for a bitstream.
*/
protected String getAmdSecID(String admSecName, String mdType, DSpaceObject dso)
{
if (dso.getType() == Constants.BITSTREAM)
{
return admSecName + "_" + getFileID((Bitstream) dso) + "_" + mdType;
}
else
{
return admSecName + "_" + dso.getID() + "_" + mdType;
}
}
/**
* Render the METS descriptive section. This will create a new metadata
* section for each crosswalk configured. Futher more, a special check
* has been aded that will add mods descriptive metadata if it is
* available in DSpace.
*
* Example:
* <dmdSec>
* <mdWrap MDTYPE="MODS">
* <xmlData>
* ... content from the crosswalk ...
* </xmlDate>
* </mdWrap>
* </dmdSec
*/
protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException
{
AttributeMap attributes;
String groupID = getGenericID("group_dmd_");
dmdSecIDS = new StringBuffer();
// Add DIM descriptive metadata if it was requested or if no metadata types
// were specified. Further more since this is the default type we also use a
// faster rendering method that the crosswalk API.
if(dmdTypes.size() == 0 || dmdTypes.contains("DIM"))
{
// Metadata element's ID
String dmdID = getGenericID("dmd_");
// Keep track of all descriptive sections
dmdSecIDS.append(dmdID);
////////////////////////////////
// Start a metadata wrapper
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS, "dmdSec", attributes);
////////////////////////////////
// Start a metadata wrapper
attributes = new AttributeMap();
attributes.put("MDTYPE","OTHER");
attributes.put("OTHERMDTYPE", "DIM");
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Start the DIM element
attributes = new AttributeMap();
attributes.put("dspaceType", Constants.typeText[item.getType()]);
if (item.isWithdrawn())
{
attributes.put("withdrawn", "y");
}
startElement(DIM,"dim",attributes);
DCValue[] dcvs = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (DCValue dcv : dcvs)
{
if (!MetadataExposure.isHidden(context, dcv.schema, dcv.element, dcv.qualifier))
{
// ///////////////////////////////
// Field element for each metadata field.
attributes = new AttributeMap();
attributes.put("mdschema",dcv.schema);
attributes.put("element", dcv.element);
if (dcv.qualifier != null)
{
attributes.put("qualifier", dcv.qualifier);
}
if (dcv.language != null)
{
attributes.put("language", dcv.language);
}
if (dcv.authority != null || dcv.confidence != Choices.CF_UNSET)
{
attributes.put("authority", dcv.authority);
attributes.put("confidence", Choices.getConfidenceText(dcv.confidence));
}
startElement(DIM,"field",attributes);
sendCharacters(dcv.value);
endElement(DIM,"field");
}
}
// ///////////////////////////////
// End the DIM element
endElement(DIM,"dim");
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
}
// Add any extra crosswalks that may configured.
for (String dmdType : dmdTypes)
{
// If DIM was requested then it was generated above without using
// the crosswalk API. So we can skip this one.
if ("DIM".equals(dmdType))
{
continue;
}
DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType);
if (crosswalk == null)
{
continue;
}
String dmdID = getGenericID("dmd_");
// Add our id to the list.
dmdSecIDS.append(" ").append(dmdID);
////////////////////////////////
// Start a metadata wrapper
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID);
startElement(METS, "dmdSec", attributes);
////////////////////////////////
// Start a metadata wrapper
attributes = new AttributeMap();
if (isDefinedMETStype(dmdType))
{
attributes.put("MDTYPE", dmdType);
}
else
{
attributes.put("MDTYPE","OTHER");
attributes.put("OTHERMDTYPE", dmdType);
}
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Send the actual XML content
try {
Element dissemination = crosswalk.disseminateElement(item);
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
SAXOutputter outputter = new SAXOutputter();
outputter.setContentHandler(filter);
outputter.setLexicalHandler(filter);
outputter.output(dissemination);
}
catch (JDOMException jdome)
{
throw new WingException(jdome);
}
catch (AuthorizeException ae)
{
// just ignore the authorize exception and continue on with
//out parsing the xml document.
}
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
}
// Check to see if there is an in-line MODS document
// stored as a bitstream. If there is then we should also
// include these metadata in our METS document. However
// we don't really know what the document describes, so we
// but it in it's own dmd group.
Boolean include = ConfigurationManager.getBooleanProperty("xmlui.bitstream.mods");
if (include && dmdTypes.contains("MODS"))
{
// Generate a second group id for any extra metadata added.
String groupID2 = getGenericID("group_dmd_");
Bundle[] bundles = item.getBundles("METADATA");
for (Bundle bundle : bundles)
{
Bitstream bitstream = bundle.getBitstreamByName("MODS.xml");
if (bitstream == null)
{
continue;
}
String dmdID = getGenericID("dmd_");
////////////////////////////////
// Start a metadata wrapper
attributes = new AttributeMap();
attributes.put("ID", dmdID);
attributes.put("GROUPID", groupID2);
startElement(METS, "dmdSec", attributes);
////////////////////////////////
// Start a metadata wrapper
attributes = new AttributeMap();
attributes.put("MDTYPE", "MODS");
startElement(METS,"mdWrap",attributes);
// ////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
// ///////////////////////////////
// Send the actual XML content
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(filter);
reader.setProperty("http://xml.org/sax/properties/lexical-handler", filter);
try {
InputStream is = bitstream.retrieve();
reader.parse(new InputSource(is));
}
catch (AuthorizeException ae)
{
// just ignore the authorize exception and continue on with
//out parsing the xml document.
}
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS, "dmdSec");
}
}
}
/**
* Render the METS administrative section.
*
* Example:
* <amdSec>
* <mdWrap MDTYPE="OTHER" OTHERMDTYPE="METSRights">
* <xmlData>
* ... content from the crosswalk ...
* </xmlDate>
* </mdWrap>
* </amdSec>
*/
protected void renderAdministrativeSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException
{
AttributeMap attributes;
String groupID;
//Only create an <amdSec>, if we have amdTypes (or sub-sections) specified...
// (this keeps our METS file small, by default, and hides all our admin metadata)
if(amdTypes.size() > 0)
{
////////////////////////////////
// Start an administrative wrapper
// Administrative element's ID
String amdID = getGenericID("amd_");
attributes = new AttributeMap();
attributes.put("ID", amdID);
startElement(METS, "amdSec", attributes);
groupID = getGenericID("group_amd_");
attributes.put("GROUPID", groupID);
}
// For each administrative metadata section specified
for (String amdSecName : amdTypes.keySet())
{
//get a list of metadata crosswalks which will be used to build
// this administrative metadata section
List<String> mdTypes = amdTypes.get(amdSecName);
// For each crosswalk
for (String mdType : mdTypes)
{
//get our dissemination crosswalk
DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(mdType);
//skip, if we cannot find this crosswalk in config file
if (crosswalk == null)
{
continue;
}
//First, check if this crosswalk can handle disseminating Item-level Administrative metadata
if(crosswalk.canDisseminate(item))
{
//Since this crosswalk works with items, first render a section for entire item
renderAmdSubSection(amdSecName, mdType, crosswalk, item);
}
//Next, we'll try and render Bitstream-level administrative metadata
// (Although, we're only rendering this metadata for the bundles specified)
List<Bundle> bundles = findEnabledBundles();
for (Bundle bundle : bundles)
{
Bitstream[] bitstreams = bundle.getBitstreams();
//Create a sub-section of <amdSec> for each bitstream in bundle
for(Bitstream bitstream : bitstreams)
{
//Only render the section if crosswalk works with bitstreams
if(crosswalk.canDisseminate(bitstream))
{
renderAmdSubSection(amdSecName, mdType, crosswalk, bitstream);
}
}//end for each bitstream
}//end for each bundle
}//end for each crosswalk
}//end for each amdSec
if(amdTypes.size() > 0)
{
//////////////////////////////////
// End administrative section
endElement(METS,"amdSec");
}
}
/**
* Render a sub-section of the administrative metadata section.
* Valid sub-sections include: techMD, rightsMD, sourceMD, digiprovMD
*
* Example:
* <techMD>
* <mdWrap MDTYPE="PREMIS">
* <xmlData>
* [PREMIS content ... ]
* </xmlData>
* </mdWrap>
* </techMD>
*
* @param amdSecName Name of administrative metadata section
* @param mdType Type of metadata section (e.g. PREMIS)
* @param crosswalk The DisseminationCrosswalk to use to generate this section
* @param dso The current DSpace object to use the crosswalk on
*/
protected void renderAmdSubSection(String amdSecName, String mdType, DisseminationCrosswalk crosswalk, DSpaceObject dso)
throws WingException, SAXException, CrosswalkException, IOException, SQLException
{
/////////////////////////////////
// Start administrative metadata section wrapper
String amdSecID = getAmdSecID(amdSecName, mdType, dso);
AttributeMap attributes = new AttributeMap();
attributes.put("ID", amdSecID);
startElement(METS, amdSecName, attributes);
//If this is a bitstream
if (dso.getType() == Constants.BITSTREAM)
{
// Add this to our list of each file's administrative section IDs
String fileID = getFileID((Bitstream) dso);
if(fileAmdSecIDs.containsKey(fileID))
{
fileAmdSecIDs.get(fileID).append(" " + amdSecID);
}
else
{
fileAmdSecIDs.put(fileID, new StringBuffer(amdSecID));
}
}//else if an Item
else if (dso.getType() == Constants.ITEM)
{
//Add this to our list of item's administrative section IDs
if(amdSecIDS==null)
{
amdSecIDS = new StringBuffer(amdSecID);
}
else
{
amdSecIDS.append(" ").append(amdSecID);
}
}
////////////////////////////////
// Start a metadata wrapper
attributes = new AttributeMap();
if (isDefinedMETStype(mdType))
{
attributes.put("MDTYPE", mdType);
}
else
{
attributes.put("MDTYPE","OTHER");
attributes.put("OTHERMDTYPE", mdType);
}
startElement(METS,"mdWrap",attributes);
//////////////////////////////////
// Start the xml data
startElement(METS,"xmlData");
/////////////////////////////////
// Send the actual XML content,
// using the PREMIS crosswalk for each bitstream
try {
Element dissemination = crosswalk.disseminateElement(dso);
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
SAXOutputter outputter = new SAXOutputter();
outputter.setContentHandler(filter);
outputter.setLexicalHandler(filter);
outputter.output(dissemination);
}
catch (JDOMException jdome)
{
throw new WingException(jdome);
}
catch (AuthorizeException ae)
{
// just ignore the authorize exception and continue on with
//out parsing the xml document.
}
// ////////////////////////////////
// End elements
endElement(METS,"xmlData");
endElement(METS,"mdWrap");
endElement(METS,amdSecName);
}
/**
* Render the METS file section. This will contain a list of all bitstreams in the
* item. Each bundle, even those that are not typically displayed will be listed.
*
* Example:
* <fileSec>
* <fileGrp USE="CONTENT">
* <file ... >
* <fLocate ... >
* </file>
* </fileGrp>
* <fileGrp USE="TEXT">
* <file ... >
* <fLocate ... >
* </file>
* </fileGrp>
* </fileSec>
*/
protected void renderFileSection() throws SQLException, SAXException
{
AttributeMap attributes;
// //////////////////////
// Start a new file section
startElement(METS,"fileSec");
// Check if the user is requested a specific bundle or
// the all bundles.
List<Bundle> bundles = findEnabledBundles();
// Suppress license?
Boolean showLicense = ConfigurationManager.getBooleanProperty("webui.licence_bundle.show");
// Loop over all requested bundles
for (Bundle bundle : bundles)
{
// Use the bitstream's name as the use parameter unless we
// are the original bundle. In this case rename it to
// content.
String use = bundle.getName();
boolean isContentBundle = false; // remember the content bundle.
boolean isDerivedBundle = false;
if ("ORIGINAL".equals(use))
{
use = "CONTENT";
isContentBundle = true;
}
if ("TEXT".equals(bundle.getName()) || "THUMBNAIL".equals(bundle.getName()))
{
isDerivedBundle = true;
}
if ("LICENSE".equals(bundle.getName()) && ! showLicense)
{
continue;
}
// ///////////////////
// Start bundle's file group
attributes = new AttributeMap();
attributes.put("USE", use);
startElement(METS,"fileGrp",attributes);
for (Bitstream bitstream : bundle.getBitstreams())
{
// //////////////////////////////
// Determine the file's IDs
String fileID = getFileID(bitstream);
Bitstream originalBitstream = null;
if (isDerivedBundle)
{
originalBitstream = findOriginalBitstream(item, bitstream);
}
String groupID = getGroupFileID((originalBitstream == null) ? bitstream : originalBitstream );
//Check if there were administrative metadata sections corresponding to this file
String admIDs = null;
if(fileAmdSecIDs.containsKey(fileID))
{
admIDs = fileAmdSecIDs.get(fileID).toString();
}
// Render the actual file & flocate elements.
renderFile(item, bitstream, fileID, groupID, admIDs);
// Remember all the viewable content bitstreams for later in the
// structMap.
if (isContentBundle)
{
contentBitstreams.add(bitstream);
if (bundle.getPrimaryBitstreamID() == bitstream.getID())
{
primaryBitstream = bitstream;
}
}
}
// ///////////////////
// End the bundle's file group
endElement(METS,"fileGrp");
}
// //////////////////////
// End the file section
endElement(METS,"fileSec");
}
/**
* Render the item's structural map. This includes a list of
* content bitstreams, those are bistreams that are typicaly
* viewable by the end user.
*
* Examlpe:
* <structMap TYPE="LOGICAL" LABEL="DSpace">
* <div TYPE="DSpace Item" DMDID="space seperated list of ids">
* <fptr FILEID="primary bitstream"/>
* ... a div for each content bitstream.
* </div>
* </structMap>
*/
protected void renderStructureMap() throws SQLException, SAXException
{
AttributeMap attributes;
// ///////////////////////
// Start a new structure map
attributes = new AttributeMap();
attributes.put("TYPE", "LOGICAL");
attributes.put("LABEL", "DSpace");
startElement(METS,"structMap",attributes);
// ////////////////////////////////
// Start the special first division
attributes = new AttributeMap();
attributes.put("TYPE", "DSpace Item");
// add references to the Descriptive metadata
if (dmdSecIDS != null)
{
attributes.put("DMDID", dmdSecIDS.toString());
}
// add references to the Administrative metadata
if (amdSecIDS != null)
{
attributes.put("AMDID", amdSecIDS.toString());
}
startElement(METS,"div",attributes);
// add a fptr pointer to the primary bitstream.
if (primaryBitstream != null)
{
// ////////////////////////////////
// Start & end a refrence to the primary bistream.
attributes = new AttributeMap();
String fileID = getFileID(primaryBitstream);
attributes.put("FILEID", fileID);
startElement(METS,"fptr",attributes);
endElement(METS,"fptr");
}
for (Bitstream bitstream : contentBitstreams)
{
// ////////////////////////////////////
// Start a div for each publicaly viewable bitstream
attributes = new AttributeMap();
attributes.put("ID", getGenericID("div_"));
attributes.put("TYPE", "DSpace Content Bitstream");
startElement(METS,"div",attributes);
// ////////////////////////////////
// Start a the actualy pointer to the bitstream
attributes = new AttributeMap();
String fileID = getFileID(bitstream);
attributes.put("FILEID", fileID);
startElement(METS,"fptr",attributes);
endElement(METS,"fptr");
// ///////////////////////////////
// End the div
endElement(METS,"div");
}
// ////////////////////////////////
// End the special first division
endElement(METS,"div");
// ///////////////////////
// End the structure map
endElement(METS,"structMap");
}
/**
* Render any extra METS section. If the item contains a METS.xml document
* then all of that document's sections are included in this document's
* METS document.
*/
protected void renderExtraSections() throws SAXException, SQLException, IOException
{
Boolean include = ConfigurationManager.getBooleanProperty("xmlui.bitstream.mets");
if (!include)
{
return;
}
Bundle[] bundles = item.getBundles("METADATA");
for (Bundle bundle : bundles)
{
Bitstream bitstream = bundle.getBitstreamByName("METS.xml");
if (bitstream == null)
{
continue;
}
// ///////////////////////////////
// Send the actual XML content
try {
SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
// Allow the basics for XML
filter.allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
// Special option, only allow elements below the second level to pass through. This
// will trim out the METS declaration and only leave the actual METS parts to be
// included.
filter.allowElements(1);
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(filter);
reader.setProperty("http://xml.org/sax/properties/lexical-handler", filter);
reader.parse(new InputSource(bitstream.retrieve()));
}
catch (AuthorizeException ae)
{
// just ignore the authorize exception and continue on with
//out parsing the xml document.
}
}
}
/**
* Checks which Bundles of current item a user has requested.
* If none specifically requested, then all Bundles are returned.
*
* @return List of enabled bundles
*/
protected List<Bundle> findEnabledBundles() throws SQLException
{
// Check if the user is requested a specific bundle or
// the all bundles.
List<Bundle> bundles;
if (fileGrpTypes.size() == 0)
{
bundles = Arrays.asList(item.getBundles());
}
else
{
bundles = new ArrayList<Bundle>();
for (String fileGrpType : fileGrpTypes)
{
for (Bundle newBundle : item.getBundles(fileGrpType))
{
bundles.add(newBundle);
}
}
}
return bundles;
}
/**
* For a bitstream that's a thumbnail or extracted text, find the
* corresponding bitstream it was derived from, in the ORIGINAL bundle.
*
* @param item
* the item we're dealing with
* @param derived
* the derived bitstream
*
* @return the corresponding original bitstream (or null)
*/
protected static Bitstream findOriginalBitstream(Item item,Bitstream derived) throws SQLException
{
// FIXME: this method is a copy of the one found below. However the
// original method is protected so we can't use it here. I think that
// perhaps this should be folded into the DSpace bitstream API. Untill
// then a good final solution can be determined I am just going to copy
// the method here.
//
// return org.dspace.content.packager.AbstractMetsDissemination
// .findOriginalBitstream(item, derived);
Bundle[] bundles = item.getBundles();
// Filename of original will be filename of the derived bitstream
// minus the extension (last 4 chars - .jpg or .txt)
String originalFilename = derived.getName().substring(0,
derived.getName().length() - 4);
// First find "original" bundle
for (int i = 0; i < bundles.length; i++)
{
if ((bundles[i].getName() != null)
&& bundles[i].getName().equals("ORIGINAL"))
{
// Now find the corresponding bitstream
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int bsnum = 0; bsnum < bitstreams.length; bsnum++)
{
if (bitstreams[bsnum].getName().equals(originalFilename))
{
return bitstreams[bsnum];
}
}
}
}
// Didn't find it
return null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.configuration;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
/**
* This class reads the XMLUI configuration file.
*
* @author Scott Phillips
*/
public class XMLUIConfiguration
{
/** log4j category */
private static Logger log = Logger.getLogger(XMLUIConfiguration.class);
/** The configured Aspects */
private static List<Aspect> aspects = new ArrayList<Aspect>();
/** The configured Theme rules */
private static List<Theme> themes = new ArrayList<Theme>();
/**
* Initialize the XMLUI Configuration.
*
* Load and parse the xmlui.xconf configuration file for a list of
* installed aspects and themes. Multiple configuration paths may be
* supplied but only the first valid file (exists and readable) will
* be used.
*
* @param configPaths Multiple paths configuration paths may be specified
*/
public static void loadConfig(String ... configPaths) throws IOException,
JDOMException
{
if (configPaths == null || configPaths.length == 0)
{
throw new IllegalStateException("The xmlui configuration path must be defined.");
}
File configFile = null;
for (String configPath : configPaths )
{
if (configPath != null)
{
configFile = new File(configPath);
}
if (configFile != null && configFile.exists() && configFile.canRead())
{
log.info("Loading XMLUI configuration from: "+configPath);
break;
}
else
{
log.debug("Faild to load XMLUI configuration from: "+configPath);
}
}
if (configFile == null)
{
StringBuilder allPaths = new StringBuilder();
for (String configPath : configPaths)
{
if (allPaths.length() > 0)
{
allPaths.append(", ");
}
allPaths.append(configPath);
}
throw new IllegalStateException("None of the xmlui configuration paths were valid: "+ allPaths);
}
// FIXME: Sometime in the future require that the xmlui.xconf be valid.
// SAXBuilder builder = new SAXBuilder(true);
SAXBuilder builder = new SAXBuilder();
Document config = builder.build(configFile);
@SuppressWarnings("unchecked") // This cast is correct
List<Element> aspectElements = XPath.selectNodes(config,
"//xmlui/aspects/aspect");
@SuppressWarnings("unchecked") // This cast is correct
List<Element> themeElements = XPath.selectNodes(config,
"//xmlui/themes/theme");
for (Element aspectElement : aspectElements)
{
String path = aspectElement.getAttributeValue("path");
String name = aspectElement.getAttributeValue("name");
if (path == null || path.length() == 0)
{
throw new IllegalStateException("All aspects muth define a path");
}
aspects.add(new Aspect(name, path));
log.info("Aspect Installed: name='"+name+"', path='"+path+"'.");
}
// Put them in the order that people expect.
Collections.reverse(aspects);
for (Element themeElement : themeElements)
{
String name = themeElement.getAttributeValue("name");
String path = themeElement.getAttributeValue("path");
String id = themeElement.getAttributeValue("id");
String regex = themeElement.getAttributeValue("regex");
String handle = themeElement.getAttributeValue("handle");
if (path == null || path.length() == 0)
{
throw new IllegalStateException("All themes muth define a path");
}
themes.add(new Theme(name, path, id, regex, handle));
log.info("Theme Installed: name='"+name+"', path='"+path+"', id='"+id+"', regex='"+regex+"', handle='"+handle+"'.");
}
}
/**
*
* @return The configured Aspect chain.
*/
public static List<Aspect> getAspectChain() {
return aspects;
}
/**
*
* @return The configured Theme rules.
*/
public static List<Theme> getThemeRules() {
return themes;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.configuration;
import java.util.regex.Pattern;
/**
* This class represents a theme.
*
* @author Scott Phillips
*/
public class Theme
{
/** The unique name of the theme */
private final String name;
/** The directory path of the theme */
private final String path;
/** The unique id of the theme */
private final String id;
/** The regular exrpession for this theme rule, if supplied */
private final String regex;
/** The handle expression for this theme rule, if supplied */
private final String handle;
/** The compiled regex expression */
private final Pattern pattern;
/**
* Create a new theme rule.
*
* @param name A unique name of the theme
* @param path The directory path to the theme
* @param id The unique ID of the theme
* @param regex The regular exrpession for this theme rule
* @param handle handle expression for this theme rule
*/
public Theme(String name, String path, String id, String regex, String handle) {
this.name = name;
this.path = path;
this.id = id;
this.regex = regex;
if (regex != null && regex.length() > 0)
{
this.pattern = Pattern.compile(regex);
}
else
{
this.pattern = null;
}
this.handle = handle;
}
/**
*
* @return If there is a handle component to this theme rule.
*/
public boolean hasHandle() {
return (handle != null && handle.length() > 0);
}
/**
*
* @return If there is a regex component to this theme rule.
*/
public boolean hasRegex() {
return (regex != null && regex.length() > 0);
}
/**
*
* @return The unique name of this theme.
*/
public String getName() {
return name;
}
/**
*
* @return The directory path to this theme.
*/
public String getPath() {
return path;
}
/**
*
* @return The regex component of this theme rule.
*/
public String getRegex() {
return regex;
}
/**
*
* @return The regex component of this theme rule, compiled as a regex Pattern.
*/
public Pattern getPattern() {
return pattern;
}
/**
*
* @return The handle component of this theme rule.
*/
public String getHandle() {
return handle;
}
/**
* @return The theme's unique ID
*/
public String getId(){
return id;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.configuration;
/**
* This class represents an Aspect in the XMLUI system.
*
* @author Scott Phillips
*/
public class Aspect
{
/** A unique name for this Aspect */
private final String name;
/** The directory path */
private final String path;
/**
* Create a new Aspect with the given name, and path.
*
* @param name A unique name for the Aspect.
* @param path The directory path to the Aspect.
*/
public Aspect(String name,String path) {
this.path= path;
this.name = name;
}
/**
*
* @return The Aspects unique name.
*/
public String getName() {
return name;
}
/**
*
* @return The Aspect's directory path.
*/
public String getPath() {
return path;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.util.Map;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.xml.sax.SAXException;
import org.apache.avalon.excalibur.pool.Recyclable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Response;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.reading.AbstractReader;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.handle.HandleManager;
import org.dspace.core.Context;
import org.dspace.core.Constants;
import org.dspace.core.LogManager;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.ItemIterator;
import org.dspace.app.bulkedit.DSpaceCSV;
import org.dspace.app.bulkedit.MetadataExport;
/**
*
* AbstractReader that generates a CSV of item, collection
* or community metadata using MetadataExport
*
* @author Kim Shepherd
*/
public class MetadataExportReader extends AbstractReader implements Recyclable
{
/**
* Messages to be sent when the user is not authorized to view
* a particular bitstream. They will be redirected to the login
* where this message will be displayed.
*/
private static final String AUTH_REQUIRED_HEADER = "xmlui.ItemExportDownloadReader.auth_header";
private static final String AUTH_REQUIRED_MESSAGE = "xmlui.ItemExportDownloadReader.auth_message";
/**
* How big of a buffer should we use when reading from the bitstream before
* writting to the HTTP response?
*/
protected static final int BUFFER_SIZE = 8192;
/**
* When should a download expire in milliseconds. This should be set to
* some low value just to prevent someone hitting DSpace repeatily from
* killing the server. Note: 60000 milliseconds are in a second.
*
* Format: minutes * seconds * milliseconds
*/
protected static final int expires = 60 * 60 * 60000;
/** The Cocoon response */
protected Response response;
/** The Cocoon request */
protected Request request;
private static Logger log = Logger.getLogger(MetadataExportReader.class);
DSpaceCSV csv = null;
MetadataExport exporter = null;
String filename = null;
/**
* Set up the export reader.
*
* See the class description for information on configuration options.
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters par) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver, objectModel, src, par);
try
{
this.request = ObjectModelHelper.getRequest(objectModel);
this.response = ObjectModelHelper.getResponse(objectModel);
Context context = ContextUtil.obtainContext(objectModel);
if(AuthorizeManager.isAdmin(context))
{
/* Get our parameters that identify the item, collection
* or community to be exported
*
*/
String handle = par.getParameter("handle");
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
java.util.List<Integer> itemmd = new ArrayList<Integer>();
if(dso.getType() == Constants.ITEM)
{
itemmd.add(dso.getID());
exporter = new MetadataExport(context, new ItemIterator(context, itemmd),true);
}
else if(dso.getType() == Constants.COLLECTION)
{
Collection collection = (Collection)dso;
ItemIterator toExport = collection.getAllItems();
exporter = new MetadataExport(context, toExport,true);
}
else if(dso.getType() == Constants.COMMUNITY)
{
exporter = new MetadataExport(context, (Community)dso, false);
}
log.info(LogManager.getHeader(context, "metadataexport", "exporting_handle:" + handle));
csv = exporter.export();
filename = handle.replaceAll("/", "-") + ".csv";
log.info(LogManager.getHeader(context, "metadataexport", "exported_file:" + filename));
}
else {
/*
* Auth should ge done by MetadataExport -- pass context through
* we should just be catching exceptions and displaying errors here
*
*/
if(this.request.getSession().getAttribute("dspace.current.user.id")!=null) {
String redictURL = request.getContextPath() + "/restricted-resource";
HttpServletResponse httpResponse = (HttpServletResponse)
objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redictURL);
return;
}
else {
String redictURL = request.getContextPath() + "/login";
AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null);
HttpServletResponse httpResponse = (HttpServletResponse)
objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redictURL);
return;
}
}
}
catch (RuntimeException e)
{
throw e;
}
catch (Exception e)
{
throw new ProcessingException("Unable to read bitstream.",e);
}
}
/**
* Write the CSV.
*
*/
public void generate() throws IOException, SAXException,
ProcessingException
{
response.setContentType("text/csv; charset=UTF-8");
response.setHeader("Content-Disposition","attachment; filename=" + filename);
out.write(csv.toString().getBytes("UTF-8"));
out.flush();
out.close();
}
/**
* Recycle
*/
public void recycle() {
this.response = null;
this.request = null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.excalibur.pool.Recyclable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.ResourceNotFoundException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Response;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.reading.AbstractReader;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
import org.apache.log4j.Logger;
import org.dspace.core.Utils;
/**
* Class will read a generated Sitemap (www.sitemaps.org or HTML sitemap)
* from [dspace]/sitemaps/ and serve it up to the requesting Search Engine.
*
* Sitemaps are generated by running the [dspace]/bin/generate-sitemaps script.
*
* There are essentially two types of Sitemaps:
*
* (1) Basic HTML Sitemaps
*
* path = "/htmlmap"
*
* <map:read type="SitemapReader">
* <map:parameter name="type" value="html"/>
* </map:read>
*
* (2) Sitemaps.org XML Sitemaps
*
* path = "/sitemap"
*
* <map:read type="SitemapReader">
* <map:parameter name="type" value="sitemaps.org"/>
* </map:read>
*
* @author Tim Donohue
*/
public class SitemapReader extends AbstractReader implements Recyclable
{
private static Logger log = Logger.getLogger(SitemapReader.class);
/** The Cocoon response */
protected Response response;
/** The Cocoon request */
protected Request request;
/** The sitemap's mime-type */
protected String sitemapMimeType;
/** true if we are for serving sitemap.org sitemaps, false otherwise */
private boolean forSitemapsOrg = false;
/**
* Set up the bitstream reader.
*
* See the class description for information on configuration options.
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters par) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver, objectModel, src, par);
this.request = ObjectModelHelper.getRequest(objectModel);
this.response = ObjectModelHelper.getResponse(objectModel);
this.forSitemapsOrg = false;
// Get our parameter that identifies type of sitemap (default to HTML sitemap)
String type = par.getParameter("type", "html");
if (type != null && type.equalsIgnoreCase("sitemaps.org"))
{
this.forSitemapsOrg = true;
}
else if (type == null || !type.equalsIgnoreCase("html"))
{
log.warn("Invalid initialization parameter for sitemapReader: assuming basic HTML");
}
}
/**
* Generate the output. Determine which type of sitemap is being
* requested and setup the main request parameters
*/
public void generate() throws IOException, ProcessingException
{
String param = this.request.getParameter("map");
String ext = (this.forSitemapsOrg ? ".xml.gz" : ".html");
this.sitemapMimeType = (this.forSitemapsOrg ? "text/xml" : "text/html");
String fileStem = (param == null ? "sitemap_index" : "sitemap" + param);
sendFile(fileStem + ext, this.forSitemapsOrg);
}
/**
* Write the actual pre-generated Sitemap data out to the response.
*
* @param file the actual file to send
* @param compressed true if file should be compressed
*/
private void sendFile(String file,
boolean compressed) throws IOException, ResourceNotFoundException
{
File f = new File(ConfigurationManager.getProperty("sitemap.dir"), file);
HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
if (!f.exists())
{
httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
throw new ResourceNotFoundException("Unable to locate sitemap");
}
long lastMod = f.lastModified();
this.response.setDateHeader("Last-Modified", lastMod);
// Check for if-modified-since header
long modSince = this.request.getDateHeader("If-Modified-Since");
if (modSince != -1 && lastMod < modSince)
{
// Sitemap file has not been modified since requested date,
// hence bitstream has not; return 304
httpResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
if (compressed)
{
this.response.setHeader("Content-Encoding", "gzip");
}
// Pipe the bits
InputStream is = new FileInputStream(f);
// Set the response MIME type
response.setHeader("Content-Type", this.sitemapMimeType);
// Response length
this.response.setHeader("Content-Length", String.valueOf(f.length()));
Utils.bufferedCopy(is, this.out);
is.close();
this.out.flush();
}
/**
* Returns the mime-type of the sitemap
*/
public String getMimeType()
{
return this.sitemapMimeType;
}
/**
* Recycle
*/
public void recycle() {
this.response = null;
this.request = null;
this.sitemapMimeType = null;
this.forSitemapsOrg = false;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Map;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.excalibur.pool.Recyclable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.ResourceNotFoundException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Response;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.environment.http.HttpResponse;
import org.apache.cocoon.reading.AbstractReader;
import org.apache.cocoon.util.ByteRange;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.handle.HandleManager;
import org.dspace.usage.UsageEvent;
import org.dspace.utils.DSpace;
import org.xml.sax.SAXException;
import org.apache.log4j.Logger;
import org.dspace.core.LogManager;
/**
* The BitstreamReader will query DSpace for a particular bitstream and transmit
* it to the user. There are several method of specifing the bitstream to be
* develivered. You may refrence a bitstream by either it's id or attempt to
* resolve the bitstream's name.
*
* /bitstream/{handle}/{sequence}/{name}
*
* <map:read type="BitstreamReader">
* <map:parameter name="handle" value="{1}/{2}"/>
* <map:parameter name="sequence" value="{3}"/>
* <map:parameter name="name" value="{4}"/>
* </map:read>
*
* When no handle is assigned yet you can access a bistream
* using it's internal ID.
*
* /bitstream/id/{bitstreamID}/{sequence}/{name}
*
* <map:read type="BitstreamReader">
* <map:parameter name="bitstreamID" value="{1}"/>
* <map:parameter name="sequence" value="{2}"/>
* </map:read>
*
* Alternativly, you can access the bitstream via a name instead
* of directly through it's sequence.
*
* /html/{handle}/{name}
*
* <map:read type="BitstreamReader">
* <map:parameter name="handle" value="{1}/{2}"/>
* <map:parameter name="name" value="{3}"/>
* </map:read>
*
* Again when no handle is available you can also access it
* via an internal itemID & name.
*
* /html/id/{itemID}/{name}
*
* <map:read type="BitstreamReader">
* <map:parameter name="itemID" value="{1}"/>
* <map:parameter name="name" value="{2}"/>
* </map:read>
*
* @author Scott Phillips
*/
public class BitstreamReader extends AbstractReader implements Recyclable
{
private static Logger log = Logger.getLogger(BitstreamReader.class);
/**
* Messages to be sent when the user is not authorized to view
* a particular bitstream. They will be redirected to the login
* where this message will be displayed.
*/
private static final String AUTH_REQUIRED_HEADER = "xmlui.BitstreamReader.auth_header";
private static final String AUTH_REQUIRED_MESSAGE = "xmlui.BitstreamReader.auth_message";
/**
* How big of a buffer should we use when reading from the bitstream before
* writting to the HTTP response?
*/
protected static final int BUFFER_SIZE = 8192;
/**
* When should a bitstream expire in milliseconds. This should be set to
* some low value just to prevent someone hiting DSpace repeatily from
* killing the server. Note: 1000 milliseconds are in a second.
*
* Format: minutes * seconds * milliseconds
* 60 * 60 * 1000 == 1 hour
*/
protected static final int expires = 60 * 60 * 1000;
/** The Cocoon response */
protected Response response;
/** The Cocoon request */
protected Request request;
/** The bitstream file */
protected InputStream bitstreamInputStream;
/** The bitstream's reported size */
protected long bitstreamSize;
/** The bitstream's mime-type */
protected String bitstreamMimeType;
/** The bitstream's name */
protected String bitstreamName;
/** True if bitstream is readable by anonymous users */
protected boolean isAnonymouslyReadable;
/** Item containing the Bitstream */
private Item item = null;
/** True if user agent making this request was identified as spider. */
private boolean isSpider = false;
/**
* Set up the bitstream reader.
*
* See the class description for information on configuration options.
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters par) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver, objectModel, src, par);
try
{
this.request = ObjectModelHelper.getRequest(objectModel);
this.response = ObjectModelHelper.getResponse(objectModel);
Context context = ContextUtil.obtainContext(objectModel);
// Get our parameters that identify the bitstream
int itemID = par.getParameterAsInteger("itemID", -1);
int bitstreamID = par.getParameterAsInteger("bitstreamID", -1);
String handle = par.getParameter("handle", null);
int sequence = par.getParameterAsInteger("sequence", -1);
String name = par.getParameter("name", null);
this.isSpider = par.getParameter("userAgent", "").equals("spider");
// Reslove the bitstream
Bitstream bitstream = null;
DSpaceObject dso = null;
if (bitstreamID > -1)
{
// Direct refrence to the individual bitstream ID.
bitstream = Bitstream.find(context, bitstreamID);
}
else if (itemID > -1)
{
// Referenced by internal itemID
item = Item.find(context, itemID);
if (sequence > -1)
{
bitstream = findBitstreamBySequence(item, sequence);
}
else if (name != null)
{
bitstream = findBitstreamByName(item, name);
}
}
else if (handle != null)
{
// Reference by an item's handle.
dso = HandleManager.resolveToObject(context,handle);
if (dso instanceof Item)
{
item = (Item)dso;
if (sequence > -1)
{
bitstream = findBitstreamBySequence(item,sequence);
}
else if (name != null)
{
bitstream = findBitstreamByName(item,name);
}
}
}
//if initial search was by sequence number and found nothing,
//then try to find bitstream by name (assuming we have a file name)
if((sequence > -1 && bitstream==null) && name!=null)
{
bitstream = findBitstreamByName(item,name);
//if we found bitstream by name, send a redirect to its new sequence number location
if(bitstream!=null)
{
String redirectURL = "";
//build redirect URL based on whether item has a handle assigned yet
if(item.getHandle()!=null && item.getHandle().length()>0)
{
redirectURL = request.getContextPath() + "/bitstream/handle/" + item.getHandle();
}
else
{
redirectURL = request.getContextPath() + "/bitstream/item/" + item.getID();
}
redirectURL += "/" + name + "?sequence=" + bitstream.getSequenceID();
HttpServletResponse httpResponse = (HttpServletResponse)
objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redirectURL);
return;
}
}
// Was a bitstream found?
if (bitstream == null)
{
throw new ResourceNotFoundException("Unable to locate bitstream");
}
// Is there a User logged in and does the user have access to read it?
boolean isAuthorized = AuthorizeManager.authorizeActionBoolean(context, bitstream, Constants.READ);
if (item != null && item.isWithdrawn() && !AuthorizeManager.isAdmin(context))
{
isAuthorized = false;
log.info(LogManager.getHeader(context, "view_bitstream", "handle=" + item.getHandle() + ",withdrawn=true"));
}
if (!isAuthorized)
{
if(context.getCurrentUser() != null){
// A user is logged in, but they are not authorized to read this bitstream,
// instead of asking them to login again we'll point them to a friendly error
// message that tells them the bitstream is restricted.
String redictURL = request.getContextPath() + "/handle/";
if (item!=null){
redictURL += item.getHandle();
}
else if(dso!=null){
redictURL += dso.getHandle();
}
redictURL += "/restricted-resource?bitstreamId=" + bitstream.getID();
HttpServletResponse httpResponse = (HttpServletResponse)
objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redictURL);
return;
}
else{
// The user does not have read access to this bitstream. Inturrupt this current request
// and then forward them to the login page so that they can be authenticated. Once that is
// successfull they will request will be resumed.
AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null);
// Redirect
String redictURL = request.getContextPath() + "/login";
HttpServletResponse httpResponse = (HttpServletResponse)
objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redictURL);
return;
}
}
// Success, bitstream found and the user has access to read it.
// Store these for later retreval:
this.bitstreamInputStream = bitstream.retrieve();
this.bitstreamSize = bitstream.getSize();
this.bitstreamMimeType = bitstream.getFormat().getMIMEType();
this.bitstreamName = bitstream.getName();
if (context.getCurrentUser() == null)
{
this.isAnonymouslyReadable = true;
}
else
{
this.isAnonymouslyReadable = false;
for (ResourcePolicy rp : AuthorizeManager.getPoliciesActionFilter(context, bitstream, Constants.READ))
{
if (rp.getGroupID() == 0)
{
this.isAnonymouslyReadable = true;
}
}
}
// Trim any path information from the bitstream
if (bitstreamName != null && bitstreamName.length() >0 )
{
int finalSlashIndex = bitstreamName.lastIndexOf('/');
if (finalSlashIndex > 0)
{
bitstreamName = bitstreamName.substring(finalSlashIndex+1);
}
}
else
{
// In-case there is no bitstream name...
bitstreamName = "bitstream";
}
// Log that the bitstream has been viewed, this is none-cached and the complexity
// of adding it to the sitemap for every possible bitstre uri is not very tractable
new DSpace().getEventService().fireEvent(
new UsageEvent(
UsageEvent.Action.VIEW,
ObjectModelHelper.getRequest(objectModel),
ContextUtil.obtainContext(ObjectModelHelper.getRequest(objectModel)),
bitstream));
// Force close of database connection in case sending a large file
context.complete();
}
catch (SQLException sqle)
{
throw new ProcessingException("Unable to read bitstream.",sqle);
}
catch (AuthorizeException ae)
{
throw new ProcessingException("Unable to read bitstream.",ae);
}
}
/**
* Find the bitstream identified by a sequence number on this item.
*
* @param item A DSpace item
* @param sequence The sequence of the bitstream
* @return The bitstream or null if none found.
*/
private Bitstream findBitstreamBySequence(Item item, int sequence) throws SQLException
{
if (item == null)
{
return null;
}
Bundle[] bundles = item.getBundles();
for (Bundle bundle : bundles)
{
Bitstream[] bitstreams = bundle.getBitstreams();
for (Bitstream bitstream : bitstreams)
{
if (bitstream.getSequenceID() == sequence)
{
return bitstream;
}
}
}
return null;
}
/**
* Return the bitstream from the given item that is identified by the
* given name. If the name has prepended directories they will be removed
* one at a time until a bitstream is found. Note that if two bitstreams
* have the same name then the first bitstream will be returned.
*
* @param item A DSpace item
* @param name The name of the bitstream
* @return The bitstream or null if none found.
*/
private Bitstream findBitstreamByName(Item item, String name) throws SQLException
{
if (name == null || item == null)
{
return null;
}
// Determine our the maximum number of directories that will be removed for a path.
int maxDepthPathSearch = 3;
if (ConfigurationManager.getProperty("xmlui.html.max-depth-guess") != null)
{
maxDepthPathSearch = ConfigurationManager.getIntProperty("xmlui.html.max-depth-guess");
}
// Search for the named bitstream on this item. Each time through the loop
// a directory is removed from the name until either our maximum depth is
// reached or the bitstream is found. Note: an extra pass is added on to the
// loop for a last ditch effort where all directory paths will be removed.
for (int i = 0; i < maxDepthPathSearch+1; i++)
{
// Search through all the bitstreams and see
// if the name can be found
Bundle[] bundles = item.getBundles();
for (Bundle bundle : bundles)
{
Bitstream[] bitstreams = bundle.getBitstreams();
for (Bitstream bitstream : bitstreams)
{
if (name.equals(bitstream.getName()))
{
return bitstream;
}
}
}
// The bitstream was not found, so try removing a directory
// off of the name and see if we lost some path information.
int indexOfSlash = name.indexOf('/');
if (indexOfSlash < 0)
{
// No more directories to remove from the path, so return null for no
// bitstream found.
return null;
}
name = name.substring(indexOfSlash+1);
// If this is our next to last time through the loop then
// trim everything and only use the trailing filename.
if (i == maxDepthPathSearch-1)
{
int indexOfLastSlash = name.lastIndexOf('/');
if (indexOfLastSlash > -1)
{
name = name.substring(indexOfLastSlash + 1);
}
}
}
// The named bitstream was not found and we exausted our the maximum path depth that
// we search.
return null;
}
/**
* Write the actual data out to the response.
*
* Some implementation notes,
*
* 1) We set a short expires time just in the hopes of preventing someone
* from overloading the server by clicking reload a bunch of times. I
* realize that this is nowhere near 100% effective but it may help in some
* cases and shouldn't hurt anything.
*
* 2) We accept partial downloads, thus if you lose a connection half way
* through most web browser will enable you to resume downloading the
* bitstream.
*/
public void generate() throws IOException, SAXException,
ProcessingException
{
if (this.bitstreamInputStream == null)
{
return;
}
// Only allow If-Modified-Since protocol if request is from a spider
// since response headers would encourage a browser to cache results
// that might change with different authentication..
if (isSpider)
{
// Check for if-modified-since header -- ONLY if not authenticated
long modSince = request.getDateHeader("If-Modified-Since");
if (modSince != -1 && item != null && item.getLastModified().getTime() < modSince)
{
// Item has not been modified since requested date,
// hence bitstream has not; return 304
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
}
// Only set Last-Modified: header for spiders or anonymous
// access, since it might encourage browse to cache the result
// which might leave a result only available to authenticated
// users in the cache for a response later to anonymous user.
try
{
if (item != null && (isSpider || ContextUtil.obtainContext(request).getCurrentUser() == null))
{
// TODO: Currently just borrow the date of the item, since
// we don't have last-mod dates for Bitstreams
response.setDateHeader("Last-Modified", item.getLastModified()
.getTime());
}
}
catch (SQLException e)
{
throw new ProcessingException(e);
}
byte[] buffer = new byte[BUFFER_SIZE];
int length = -1;
// Only encourage caching if this is not a restricted resource, i.e.
// if it is accessed anonymously or is readable by Anonymous:
if (isAnonymouslyReadable)
{
response.setDateHeader("Expires", System.currentTimeMillis() + expires);
}
// If this is a large bitstream then tell the browser it should treat it as a download.
int threshold = ConfigurationManager.getIntProperty("xmlui.content_disposition_threshold");
if (bitstreamSize > threshold && threshold != 0)
{
String name = bitstreamName;
// Try and make the download file name formated for each browser.
try {
String agent = request.getHeader("USER-AGENT");
if (agent != null && agent.contains("MSIE"))
{
name = URLEncoder.encode(name, "UTF8");
}
else if (agent != null && agent.contains("Mozilla"))
{
name = MimeUtility.encodeText(name, "UTF8", "B");
}
}
catch (UnsupportedEncodingException see)
{
// do nothing
}
response.setHeader("Content-Disposition", "attachment;filename=" + name);
}
ByteRange byteRange = null;
// Turn off partial downloads, they cause problems
// and are only rarely used. Specifically some windows pdf
// viewers are incapable of handling this request. You can
// uncomment the following lines to turn this feature back on.
// response.setHeader("Accept-Ranges", "bytes");
// String ranges = request.getHeader("Range");
// if (ranges != null)
// {
// try
// {
// ranges = ranges.substring(ranges.indexOf('=') + 1);
// byteRange = new ByteRange(ranges);
// }
// catch (NumberFormatException e)
// {
// byteRange = null;
// if (response instanceof HttpResponse)
// {
// // Respond with status 416 (Request range not
// // satisfiable)
// response.setStatus(416);
// }
// }
// }
try
{
if (byteRange != null)
{
String entityLength;
String entityRange;
if (this.bitstreamSize != -1)
{
entityLength = "" + this.bitstreamSize;
entityRange = byteRange.intersection(
new ByteRange(0, this.bitstreamSize)).toString();
}
else
{
entityLength = "*";
entityRange = byteRange.toString();
}
response.setHeader("Content-Range", entityRange + "/" + entityLength);
if (response instanceof HttpResponse)
{
// Response with status 206 (Partial content)
response.setStatus(206);
}
int pos = 0;
int posEnd;
while ((length = this.bitstreamInputStream.read(buffer)) > -1)
{
posEnd = pos + length - 1;
ByteRange intersection = byteRange.intersection(new ByteRange(pos, posEnd));
if (intersection != null)
{
out.write(buffer, (int) intersection.getStart() - pos, (int) intersection.length());
}
pos += length;
}
}
else
{
response.setHeader("Content-Length", String.valueOf(this.bitstreamSize));
while ((length = this.bitstreamInputStream.read(buffer)) > -1)
{
out.write(buffer, 0, length);
}
out.flush();
}
}
finally
{
try
{
// Close the bitstream input stream so that we don't leak a file descriptor
this.bitstreamInputStream.close();
// Close the output stream as per Cocoon docs: http://cocoon.apache.org/2.2/core-modules/core/2.2/681_1_1.html
out.close();
}
catch (IOException ioe)
{
// Closing the stream threw an IOException but do we want this to propagate up to Cocoon?
// No point since the user has already got the bitstream contents.
log.warn("Caught IO exception when closing a stream: " + ioe.getMessage());
}
}
}
/**
* Returns the mime-type of the bitstream.
*/
public String getMimeType()
{
return this.bitstreamMimeType;
}
/**
* Recycle
*/
public void recycle() {
this.response = null;
this.request = null;
this.bitstreamInputStream = null;
this.bitstreamSize = 0;
this.bitstreamMimeType = null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.matching.Matcher;
import org.apache.cocoon.sitemap.PatternException;
import org.dspace.app.xmlui.configuration.Aspect;
import org.dspace.app.xmlui.configuration.XMLUIConfiguration;
/**
* This class determines the correct Aspect to use. This is determined by the
* url string, if it is prepended with a number followed by a slash (such as 1/
* or 3/) then the Aspect identified by the number is used. When the URL does
* not start with an integer then the first Aspect (aspect zero) is loaded.
*
* Once the Aspect has been identified the following sitemap parameters are
* provided: {ID} is the Aspect ID, {aspect} is the path to the aspect,
* {aspectName} is a unique name for the aspect, and {prefix} is the aspect
* identifier prepending the URL (if one exists!).
*
* @author Scott Phillips
*/
public class AspectMatcher extends AbstractLogEnabled implements Matcher
{
/**
* Determine the correct aspect to load.
*
* @param pattern
* name of sitemap parameter to find
* @param objectModel
* environment passed through via cocoon
* @return null or map containing value of sitemap parameter 'pattern'
*/
public Map match(String pattern, Map objectModel, Parameters parameters)
throws PatternException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String uri = request.getSitemapURI();
String[] parts = uri.split("/");
int aspectID;
try
{
aspectID = Integer.valueOf(parts[0]);
}
catch (NumberFormatException nfe)
{
aspectID = 0;
}
// If this is the first aspect then allow the aspect sitemap to do some post
// processing like PageNotFound.
if (aspectID == 0)
{
// Initial aspect
Map<String, String> result = new HashMap<String, String>();
result.put("aspectID",String.valueOf(aspectID));
return result;
}
// Obtain the aspect
List<Aspect> chain = XMLUIConfiguration.getAspectChain();
// Note: because we add a zero initial aspect our aspectIDs are one
// off from the aspect chain's.
if (chain.size() + 1> aspectID)
{
// Chain the next Aspect
Aspect aspect = chain.get(aspectID - 1);
Map<String, String> result = new HashMap<String, String>();
result.put("aspectID", String.valueOf(aspectID));
result.put("aspect", aspect.getPath());
result.put("aspectName", aspect.getName());
result.put("prefix", aspectID + "/");
return result;
}
else
{
// No more aspects to chain, the match fails.
return null;
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.*;
import org.apache.cocoon.reading.ResourceReader;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.TimeStampValidity;
import org.apache.log4j.Logger;
import org.dspace.core.ConfigurationManager;
import org.mozilla.javascript.EvaluatorException;
import org.xml.sax.SAXException;
import java.io.*;
import java.util.*;
/**
* Concatenates and Minifies CSS, JS and JSON files
*
* The URL of the resource can contain references to multiple
* files: e.g."themes/Mirage/lib/css/reset,base,helper,style,print.css"
* The Reader will concatenate all these files, and output them as
* a single resource.
*
* If "xmlui.theme.enableMinification" is set to true, the
* output will also be minified prior to returning the resource.
*
* Validity is determined based upon last modified date of
* the most recently edited file.
*
* @author Roel Van Reeth (roel at atmire dot com)
* @author Art Lowel (art dot lowel at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
*/
public class ConcatenationReader extends ResourceReader {
private static final int MINIFY_LINEBREAKPOS = 8000;
protected List<Source> inputSources;
private String key;
private StreamEnumeration streamEnumeration;
private static Logger log = Logger.getLogger(ConcatenationReader.class);
private boolean doMinify = true;
/**
* Setup the reader.
* The resource is opened to get an <code>InputStream</code>,
* the length and the last modification date
*/
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par)
throws ProcessingException, SAXException, IOException {
// save key
this.key = src;
// don't support byte ranges (resumed downloads)
this.setByteRanges(false);
// setup list of sources, get relevant parts of path
this.inputSources = new ArrayList<Source>();
String path = src.substring(0, src.lastIndexOf('/'));
String file = src.substring(src.lastIndexOf('/')+1);
// now build own list of inputsources
String[] files = file.split(",");
for (String f : files) {
if (file.endsWith(".json") && !f.endsWith(".json")) {
f += ".json";
}
if (file.endsWith(".js") && !f.endsWith(".js")) {
f += ".js";
}
if (file.endsWith(".css") && !f.endsWith(".css")) {
f += ".css";
}
String fullPath = path + "/" + f;
this.inputSources.add(resolver.resolveURI(fullPath));
}
// do super stuff
super.setup(resolver, objectModel, path+"/"+files[files.length-1], par);
// add stream enumerator
this.streamEnumeration = new StreamEnumeration();
// check minify parameter
try {
if("nominify".equals(par.getParameter("requestQueryString"))) {
this.doMinify = false;
} else {
// modify key!
this.key += "?minify";
}
} catch (ParameterException e) {
log.error("ParameterException in setup when retrieving parameter requestQueryString", e);
}
}
/**
* Recyclable
*/
public void recycle() {
if (this.inputSources != null) {
for(Source s : this.inputSources) {
super.resolver.release(s);
}
this.inputSources = null;
this.streamEnumeration = null;
this.key = null;
}
super.recycle();
}
/**
* Generate the unique key.
* This key must be unique inside the space of this component.
*
* @return The generated key hashes the src
*/
public Serializable getKey() {
return key;
}
/**
* Generate the validity object.
*
* @return The generated validity object or <code>null</code> if the
* component is currently not cacheable.
*/
public SourceValidity getValidity() {
final long lm = getLastModified();
if(lm > 0) {
return new TimeStampValidity(lm);
}
return null;
}
/**
* @return the time the read source was last modified or 0 if it is not
* possible to detect
*/
public long getLastModified() {
// get latest modified value
long modified = 0;
for(Source s : this.inputSources) {
if(s.getLastModified() > modified) {
modified = s.getLastModified();
}
}
return modified;
}
/**
* Generates the requested resource.
*/
public void generate() throws IOException, ProcessingException {
InputStream inputStream;
// create one single inputstream from all files
inputStream = new SequenceInputStream(streamEnumeration);
try {
if (ConfigurationManager.getBooleanProperty("xmlui.theme.enableMinification",false) && this.doMinify) {
compressedOutput(inputStream);
} else {
normalOutput(inputStream);
}
// Bugzilla Bug #25069: Close inputStream in finally block.
} finally {
if (inputStream != null) {
inputStream.close();
}
}
out.flush();
}
private void compressedOutput(InputStream inputStream) throws IOException {
// prepare streams
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Writer outWriter = new OutputStreamWriter(bytes);
// do compression
Reader in = new BufferedReader(new InputStreamReader(inputStream));
if (this.key.endsWith(".js?minify") || this.key.endsWith(".json?minify")) {
try {
JavaScriptCompressor compressor = new JavaScriptCompressor(in, null);
// boolean options: munge, verbose, preserveAllSemiColons, disableOptimizations
compressor.compress(outWriter, MINIFY_LINEBREAKPOS, true, false, false, false);
} catch (EvaluatorException e) {
// fail gracefully on malformed javascript: send it without compressing
normalOutput(inputStream);
return;
}
} else if (this.key.endsWith(".css?minify")) {
CssCompressor compressor = new CssCompressor(in);
compressor.compress(outWriter, MINIFY_LINEBREAKPOS);
} else {
// or not if not right type
normalOutput(inputStream);
return;
}
// first send content-length header
outWriter.flush();
response.setHeader("Content-Length", Long.toString(bytes.size()));
// then send output and clean up
bytes.writeTo(out);
in.close();
}
private void normalOutput(InputStream inputStream) throws IOException {
boolean validContentLength = true;
byte[] buffer = new byte[bufferSize];
int length;
long contentLength = 0;
// calculate content length
for (Source s : this.inputSources) {
if(s.getContentLength() < 0) {
validContentLength = false;
}
contentLength += s.getContentLength();
}
if(validContentLength) {
response.setHeader("Content-Length", Long.toString(contentLength));
}
// send contents
while ((length = inputStream.read(buffer)) > -1) {
out.write(buffer, 0, length);
}
}
private final class StreamEnumeration implements Enumeration {
private int index;
private StreamEnumeration() {
this.index = 0;
}
public boolean hasMoreElements() {
return index < inputSources.size();
}
public InputStream nextElement() {
try {
InputStream elem = inputSources.get(index).getInputStream();
index++;
return elem;
} catch (IOException e) {
log.error("IOException in StreamEnumeration.nextElement when retrieving InputStream of a Source; index = "
+ index + ", inputSources.size = " + inputSources.size(), e);
return null;
}
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.ServiceableAction;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.i18n.I18nUtils;
import org.apache.cocoon.i18n.I18nUtils.LocaleValidator;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.I18nUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* This action looks at several places to determine what locale should be used for
* this request. We use cocoon's i18nUtils find local method which will look in
* several places continuing to the next step if no local is found.:
*
* 1. HTTP Request parameter 'locale'
* 2. Session attribute 'locale'
* 3. First matching cookie parameter 'locale' within each cookie sent
* 4. Sitemap parameter "locale"
* 5. Locale setting of the requesting browser or server default
* 6. Default
* 7. Blank
* 8. Fail
*
* Only those locales which are listed in xmlui.supported.locales will be identified,
* if no acceptable locales are found then the default locale will be used.
*
* @author Scott Phillips
*/
public class DSpaceLocaleAction extends ServiceableAction implements Configurable {
/** A validator class which tests if a local is a supported locale */
private static DSpaceLocaleValidator localeValidator;
/** The default locale if no acceptable locales are identified */
private static Locale defaultLocale;
/**
* Configure the action.
*/
public void configure(Configuration config)
{
if (localeValidator == null)
{
localeValidator = new DSpaceLocaleValidator();
}
if (defaultLocale == null)
{
defaultLocale = I18nUtil.getDefaultLocale();
}
}
/**
* Action which obtains the current environments locale information, and
* places it in the objectModel (and optionally in a session/cookie).
*/
public Map act(Redirector redirector,
SourceResolver resolver,
Map objectModel,
String source,
Parameters parameters)
throws Exception {
Locale locale = I18nUtils.findLocale(objectModel, "locale-attribute", parameters, defaultLocale, false, true, false, localeValidator);
if (locale == null) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("No locale found, using default");
}
locale = I18nUtil.getDefaultLocale();
}
String localeStr = locale.toString();
if (getLogger().isDebugEnabled()) {
getLogger().debug("Found locale: " + localeStr);
}
I18nUtils.storeLocale(objectModel,
"locale-attribute",
localeStr,
false,
false,
false,
false);
// Set up a map for sitemap parameters
Map<String, String> map = new HashMap<String, String>();
map.put("language", locale.getLanguage());
map.put("country", locale.getCountry());
map.put("variant", locale.getVariant());
map.put("locale", localeStr);
return map;
}
/**
* This validator class works with cocoon's i18nutils class to test if locales are valid.
* For dspace we define a locale as valid if it is listed in xmlui.supported.locales config
* parameter.
*/
public static class DSpaceLocaleValidator implements LocaleValidator {
/** the list of supported locales that may be used. */
private List<Locale> supportedLocales;
/**
* Build a list supported locales to validate against upon object construction.
*/
public DSpaceLocaleValidator()
{
if (ConfigurationManager.getProperty("xmlui.supported.locales") != null)
{
supportedLocales = new ArrayList<Locale>();
String supportedLocalesConfig = ConfigurationManager.getProperty("xmlui.supported.locales");
String[] parts = supportedLocalesConfig.split(",");
for (String part : parts)
{
Locale supportedLocale = I18nUtils.parseLocale(part.trim(), null);
if (supportedLocale != null)
{
supportedLocales.add(supportedLocale);
}
}
}
}
/**
* @param name name of the locale (for debugging)
* @param test locale to test
* @return true if locale satisfies validator's criteria
*/
public boolean test(String name, Locale test)
{
// If there are no configured locales the accept them all.
if (supportedLocales == null)
{
return true;
}
// Otherwise check if they are listed
for (Locale locale : supportedLocales)
{
if (locale.equals(test))
{
return true;
}
}
// Fail if not found
return false;
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.excalibur.pool.Recyclable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Response;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.reading.AbstractReader;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.handle.HandleManager;
import org.dspace.search.DSQuery;
import org.dspace.search.QueryArgs;
import org.dspace.search.QueryResults;
import org.xml.sax.SAXException;
/**
* Simple servlet for open URL support. Presently, simply extracts terms from
* open URL and redirects to search.
*
* @author Robert Tansley
* @author Mark Diggory (mdiggory at mire.be)
* @version $Revision: 5845 $
*/
public class OpenURLReader extends AbstractReader implements Recyclable {
private static final String Z39882004 = "Z39.88-2004";
private static final String Z39882004DC = "info:ofi/fmt:kev:mtx:dc";
private static final String Z39882004CTX = "info:ofi/fmt:kev:mtx:ctx";
/** The Cocoon response */
protected Response response;
/** The Cocoon request */
protected Request request;
/** The Servlet Response */
protected HttpServletResponse httpResponse;
protected Context context;
/** Logger */
private static Logger log = Logger.getLogger(OpenURLReader.class);
public void generate() throws IOException, SAXException,
ProcessingException {
}
@Override
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters par) throws ProcessingException, SAXException,
IOException {
super.setup(resolver, objectModel, src, par);
try {
this.httpResponse = (HttpServletResponse) objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
this.request = ObjectModelHelper.getRequest(objectModel);
this.response = ObjectModelHelper.getResponse(objectModel);
this.context = ContextUtil.obtainContext(objectModel);
if (Z39882004.equals(request.getParameter("url_ver"))) {
handleZ39882004();
} else {
handleLegacy();
}
} catch (SQLException sqle) {
throw new ProcessingException("Unable to resolve OpenURL.", sqle);
}
}
@Override
public void recycle() {
super.recycle();
this.response = null;
this.request = null;
this.httpResponse = null;
this.context = null;
}
public void handleLegacy() throws IOException {
String query = "";
String title = request.getParameter("title");
String authorFirst = request.getParameter("aufirst");
String authorLast = request.getParameter("aulast");
String logInfo = "";
if (title != null) {
query = query + " " + title;
logInfo = logInfo + "title=\"" + title + "\",";
}
if (authorFirst != null) {
query = query + " " + authorFirst;
logInfo = logInfo + "aufirst=\"" + authorFirst + "\",";
}
if (authorLast != null) {
query = query + " " + authorLast;
logInfo = logInfo + "aulast=\"" + authorLast + "\",";
}
log.info(LogManager.getHeader(context, "openURL", logInfo
+ "dspacequery=" + query));
httpResponse.sendRedirect(httpResponse.encodeRedirectURL(request
.getContextPath()
+ "/simple-search?query=" + query));
}
private String getFirstHandle(String query) throws IOException {
List<String> handles = getHandles(query);
for (String handle : handles) {
return handle;
}
return null;
}
private List<String> getHandles(String query) throws IOException {
QueryArgs args = new QueryArgs();
args.setQuery(query);
QueryResults results = DSQuery.doQuery(context, args);
return results.getHitHandles();
}
/**
* Validate supported formats
*
* We can deal with various formats if they exist such as journals and
* books, but we currently do not have specific needs represent
* different formats, thus it may be more appropriate to use dublin core
* here directly.
*
* rft_val_fmt=info:ofi/fmt:kev:mtx:dc
*
* See Dublin Core OpenURL Profile Citation Guidelines:
* http://dublincore.org/documents/dc-citation-guidelines/
* http://alcme.oclc
* .org/openurl/servlet/OAIHandler/extension?verb=GetMetadata
* &metadataPrefix=mtx&identifier=info:ofi/fmt:kev:mtx:dc
*
* What happens when we use Context Objects of different versions? Do
* they exist? ctx_ver=Z39.88-2004
*
* COinS will be implemented as:
*
* <span class="Z3988" title="ctx_ver=Z39.88-2004&rft_val_fmt=info:ofi/fmt:kev:mtx:journal&rft.issn=1045-4438"
* > <A HREF="http://library.example.edu/?url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rft_val_fmt=info:ofi/fmt:kev:mtx:journal&rft.issn=1045-4438"
* >Find at Example Library</A> </span>
*
* If an ctx_id is present use it to resolve the item directly.
* Otherwise, use the search mechanism. Our ctx_id are going to be local
* handle identifiers like the following
*
* ctx_id=10255/dryad.111
*
* Global identifiers will be any other valid dc.identifier present
* within that field. Thus:
*
* dc.identifier.uri http://dx.doi.org/10.1080/106351598260806
* dc.identifier.uri http://hdl.handle.net/10255/dryad.111
*
* will lead to
*
* rft.identifier=http%3A%2F%2Fdx.doi.org%2F10.1080%2F106351598260806
* rft.identifier=http%3A%2F%2Fhdl.handle.net%2F10255%2Fdryad.111
*
* And Thus be resolvable as well
* @throws SQLException
*/
public void handleZ39882004() throws IOException, ProcessingException, SQLException {
String rft_val_fmt = request.getParameter("rft_val_fmt");
if (rft_val_fmt != null && !rft_val_fmt.equals(Z39882004DC))
{
throw new ProcessingException(
"DSpace 1.0 OpenURL Service only supports rft_val_fmt="
+ Z39882004DC);
}
String url_ctx_fmt = request.getParameter("url_ctx_fmt");
if (url_ctx_fmt != null && !url_ctx_fmt.equals(Z39882004CTX))
{
throw new ProcessingException(
"DSpace 1.0 OpenURL Service only supports url_ctx_fmt="
+ Z39882004CTX);
}
/**
* First attempt to resolve an rft_id identifier as a handle
*/
String[] rft_ids = request.getParameterValues("rft_id");
if(rft_ids != null)
{
for (String rft_id : rft_ids) {
DSpaceObject obj = HandleManager.resolveToObject(context, rft_id);
if (obj != null) {
httpResponse.sendRedirect(httpResponse
.encodeRedirectURL(request.getContextPath()
+ "/handle/" + obj.getHandle()));
return;
}
}
}
String[] identifiers = request.getParameterValues("rtf.identifier");
/**
* Next attempt to resolve an identifier in search
*/
if(identifiers != null)
{
for (String identifier : identifiers) {
String handle = getFirstHandle("identifier: " + identifier);
if (handle != null) {
httpResponse.sendRedirect(httpResponse
.encodeRedirectURL(request.getContextPath()
+ "/handle/" + handle));
return;
}
}
}
/**
* Otherwise, attempt to full text search for the item
*/
StringBuilder queryBuilder = new StringBuilder();
Enumeration<String> e = request.getParameterNames();
while (e.hasMoreElements()) {
String name = e.nextElement();
if (name.startsWith("rft.")) {
for (String value : request.getParameterValues(name)) {
queryBuilder.append(value).append(" ");
}
}
}
String query = queryBuilder.toString().trim();
if(query.length() == 0)
{
httpResponse.sendError(httpResponse.SC_BAD_REQUEST, "OpenURL Request requires a valid rtf_id, rtf.identifier or other rtf.<dublincore> search fields" );
}
httpResponse.sendRedirect(httpResponse.encodeRedirectURL(request
.getContextPath()
+ "/simple-search?query=" + java.net.URLEncoder.encode(query, request.getCharacterEncoding())));
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.core.Context;
import org.dspace.core.ConfigurationManager;
import org.dspace.usage.UsageEvent;
import org.dspace.utils.DSpace;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Bitstream;
import org.dspace.content.Item;
import org.dspace.content.Bundle;
import org.dspace.handle.HandleManager;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.avalon.framework.parameters.Parameters;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* Created by IntelliJ IDEA.
* User: kevinvandevelde
* Date: 22-dec-2008
* Time: 15:00:55
* To change this template use File | Settings | File Templates.
*/
public class UsageLoggerAction extends AbstractAction {
public Map act(Redirector redirector, SourceResolver sourceResolver, Map objectModel, String string, Parameters parameters) throws Exception {
try{
Request request = ObjectModelHelper.getRequest(objectModel);
Context context = ContextUtil.obtainContext(objectModel);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if(dso == null){
//We might have a bitstream
dso = findBitstream(context, parameters);
}
logDspaceObject(request, dso, context);
}catch(Exception e){
//Ignore we cannot let this crash
//TODO: log this
e.printStackTrace();
}
// Finished, allow to pass.
return null;
}
public static void logDspaceObject(Request request, DSpaceObject dso, Context context){
if(dso == null)
{
return;
}
try {
new DSpace().getEventService().fireEvent(
new UsageEvent(
UsageEvent.Action.VIEW,
(HttpServletRequest)request,
ContextUtil.obtainContext((HttpServletRequest)request),
dso));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Bitstream findBitstream(Context context, Parameters par) throws SQLException {
// Get our parameters that identify the bitstream
int itemID = par.getParameterAsInteger("itemID", -1);
int bitstreamID = par.getParameterAsInteger("bitstreamID", -1);
String handle = par.getParameter("handle", null);
int sequence = par.getParameterAsInteger("sequence", -1);
String name = par.getParameter("name", null);
// Reslove the bitstream
Bitstream bitstream = null;
Item item;
DSpaceObject dso;
if (bitstreamID > -1)
{
// Direct refrence to the individual bitstream ID.
bitstream = Bitstream.find(context, bitstreamID);
}
else if (itemID > -1)
{
// Referenced by internal itemID
item = Item.find(context, itemID);
if (sequence > -1)
{
bitstream = findBitstreamBySequence(item, sequence);
}
else if (name != null)
{
bitstream = findBitstreamByName(item, name);
}
}
else if (handle != null)
{
// Reference by an item's handle.
dso = HandleManager.resolveToObject(context,handle);
if (dso instanceof Item)
{
item = (Item)dso;
if (sequence > -1)
{
bitstream = findBitstreamBySequence(item,sequence);
}
else if (name != null)
{
bitstream = findBitstreamByName(item,name);
}
}
}
return bitstream;
}
/**
* Find the bitstream identified by a sequence number on this item.
*
* @param item A DSpace item
* @param sequence The sequence of the bitstream
* @return The bitstream or null if none found.
*/
private Bitstream findBitstreamBySequence(Item item, int sequence) throws SQLException
{
if (item == null)
{
return null;
}
Bundle[] bundles = item.getBundles();
for (Bundle bundle : bundles)
{
Bitstream[] bitstreams = bundle.getBitstreams();
for (Bitstream bitstream : bitstreams)
{
if (bitstream.getSequenceID() == sequence)
{
return bitstream;
}
}
}
return null;
}
/**
* Return the bitstream from the given item that is identified by the
* given name. If the name has prepended directories they will be removed
* one at a time until a bitstream is found. Note that if two bitstreams
* have the same name then the first bitstream will be returned.
*
* @param item A DSpace item
* @param name The name of the bitstream
* @return The bitstream or null if none found.
*/
private Bitstream findBitstreamByName(Item item, String name) throws SQLException
{
if (name == null || item == null)
{
return null;
}
// Determine our the maximum number of directories that will be removed for a path.
int maxDepthPathSearch = 3;
if (ConfigurationManager.getProperty("xmlui.html.max-depth-guess") != null)
{
maxDepthPathSearch = ConfigurationManager.getIntProperty("xmlui.html.max-depth-guess");
}
// Search for the named bitstream on this item. Each time through the loop
// a directory is removed from the name until either our maximum depth is
// reached or the bitstream is found. Note: an extra pass is added on to the
// loop for a last ditch effort where all directory paths will be removed.
for (int i = 0; i < maxDepthPathSearch+1; i++)
{
// Search through all the bitstreams and see
// if the name can be found
Bundle[] bundles = item.getBundles();
for (Bundle bundle : bundles)
{
Bitstream[] bitstreams = bundle.getBitstreams();
for (Bitstream bitstream : bitstreams)
{
if (name.equals(bitstream.getName()))
{
return bitstream;
}
}
}
// The bitstream was not found, so try removing a directory
// off of the name and see if we lost some path information.
int indexOfSlash = name.indexOf('/');
if (indexOfSlash < 0)
{
// No more directories to remove from the path, so return null for no
// bitstream found.
return null;
}
name = name.substring(indexOfSlash+1);
// If this is our next to last time through the loop then
// trim everything and only use the trailing filename.
if (i == maxDepthPathSearch-1)
{
int indexOfLastSlash = name.lastIndexOf('/');
if (indexOfLastSlash > -1)
{
name = name.substring(indexOfLastSlash + 1);
}
}
}
// The named bitstream was not found and we exausted our the maximum path depth that
// we search.
return null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* <p>Example filter that sets the character encoding to be used in parsing the
* incoming request, either unconditionally or only if the client did not
* specify a character encoding. Configuration of this filter is based on
* the following initialization parameters:</p>
* <ul>
* <li><strong>encoding</strong> - The character encoding to be configured
* for this request, either conditionally or unconditionally based on
* the <code>ignore</code> initialization parameter. This parameter
* is required, so there is no default.</li>
* <li><strong>ignore</strong> - If set to "true", any character encoding
* specified by the client is ignored, and the value returned by the
* <code>selectEncoding()</code> method is set. If set to "false,
* <code>selectEncoding()</code> is called <strong>only</strong> if the
* client has not already specified an encoding. By default, this
* parameter is set to "true".</li>
* </ul>
*
* <p>Although this filter can be used unchanged, it is also easy to
* subclass it and make the <code>selectEncoding()</code> method more
* intelligent about what encoding to choose, based on characteristics of
* the incoming request (such as the values of the <code>Accept-Language</code>
* and <code>User-Agent</code> headers, or a value stashed in the current
* user's session.</p>
*
* <p>This filter was borrowed from:
* http://wiki.apache.org/cocoon/SetCharacterEncodingFilter</p>
*
* @author Craig McClanahan - Apache
* @author Tim Donohue (minor modifications)
* @version $Revision: 5845 $ $Date: 2010-11-12 00:34:07 -0500 (Fri, 12 Nov 2010) $
*/
public class SetCharacterEncodingFilter implements Filter
{
/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;
/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;
/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;
/**
* Take this filter out of service.
*/
public void destroy()
{
this.encoding = null;
this.filterConfig = null;
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null))
{
String currentEncoding = selectEncoding(request);
if (currentEncoding != null)
{
request.setCharacterEncoding(currentEncoding);
}
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
/**
* Place this filter into service.
*
* @param filterConfig The filter configuration object
* @throws ServletException
*/
public void init(FilterConfig filterConfig) throws ServletException
{
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
{
this.ignore = true;
}
else if ("true".equalsIgnoreCase(value))
{
this.ignore = true;
}
else if ("yes".equalsIgnoreCase(value))
{
this.ignore = true;
}
else
{
this.ignore = false;
}
}
/**
* Select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. If no character encoding should be set, return
* <code>null</code>.
* <p>
* The default implementation unconditionally returns the value configured
* by the <strong>encoding</strong> initialization parameter for this
* filter.
*
* @param request The servlet request we are processing
* @return encoding
*/
protected String selectEncoding(ServletRequest request)
{
return (this.encoding);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.configuration.XMLUIConfiguration;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.core.ConfigurationManager;
import org.dspace.harvest.OAIHarvester;
/**
* This is a wrapper servlet around the cocoon servlet that prefroms two functions, 1) it
* initializes DSpace / XML UI configuration parameters, and 2) it will preform inturrupted
* request resumption.
*
* @author scott philips
*/
public class DSpaceCocoonServletFilter implements Filter
{
private static final Logger LOG = Logger.getLogger(DSpaceCocoonServletFilter.class);
private static final long serialVersionUID = 1L;
/**
* The DSpace config paramater, this is where the path to the DSpace
* configuration file can be obtained
*/
public static final String DSPACE_CONFIG_PARAMETER = "dspace-config";
/**
* This method holds code to be removed in the next version
* of the DSpace XMLUI, it is now managed by a Shared Context
* Listener inthe dspace-api project.
*
* It is deprecated, rather than removed to maintain backward
* compatibility for local DSpace 1.5.x customized overlays.
*
* TODO: Remove in trunk
*
* @deprecated Use Servlet Context Listener provided
* in dspace-api (remove in > 1.5.x)
* @throws ServletException
*/
private void initDSpace(FilterConfig arg0) throws ServletException
{
// On Windows, URL caches can cause problems, particularly with undeployment
// So, here we attempt to disable them if we detect that we are running on Windows
try
{
String osName = System.getProperty("os.name");
if (osName != null)
{
osName = osName.toLowerCase();
}
if (osName != null && osName.contains("windows"))
{
URL url = new URL("http://localhost/");
URLConnection urlConn = url.openConnection();
urlConn.setDefaultUseCaches(false);
}
}
// Any errors thrown in disabling the caches aren't significant to
// the normal execution of the application, so we ignore them
catch (RuntimeException e)
{
LOG.error(e.getMessage(), e);
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
}
/**
* Previous stages moved to shared ServletListener available in dspace-api
*/
String dspaceConfig = null;
/**
* Stage 1
*
* Locate the dspace config
*/
// first check the local per webapp parameter, then check the global parameter.
dspaceConfig = arg0.getInitParameter(DSPACE_CONFIG_PARAMETER);
if (dspaceConfig == null)
{
dspaceConfig = arg0.getServletContext().getInitParameter(DSPACE_CONFIG_PARAMETER);
}
// Finaly, if no config parameter found throw an error
if (dspaceConfig == null || "".equals(dspaceConfig))
{
throw new ServletException(
"\n\nDSpace has failed to initialize. This has occurred because it was unable to determine \n" +
"where the dspace.cfg file is located. The path to the configuration file should be stored \n" +
"in a context variable, '"+DSPACE_CONFIG_PARAMETER+"', in either the local servlet or global contexts. \n" +
"No context variable was found in either location.\n\n");
}
/**
* Stage 2
*
* Load the dspace config. Also may load log4j configuration.
* (Please rely on ConfigurationManager or Log4j to configure logging)
*
*/
try
{
if(!ConfigurationManager.isConfigured())
{
// Load in DSpace config
ConfigurationManager.loadConfig(dspaceConfig);
}
}
catch (RuntimeException e)
{
throw e;
}
catch (Exception e)
{
throw new ServletException(
"\n\nDSpace has failed to initialize, during stage 2. Error while attempting to read the \n" +
"DSpace configuration file (Path: '"+dspaceConfig+"'). \n" +
"This has likely occurred because either the file does not exist, or it's permissions \n" +
"are set incorrectly, or the path to the configuration file is incorrect. The path to \n" +
"the DSpace configuration file is stored in a context variable, 'dspace-config', in \n" +
"either the local servlet or global context.\n\n",e);
}
}
/**
* Before this servlet will become functional replace
*/
public void init(FilterConfig arg0) throws ServletException {
this.initDSpace(arg0);
// Paths to the various config files
String webappConfigPath = null;
String installedConfigPath = null;
/**
* Stage 3
*
* Load the XML UI configuration
*/
try
{
// There are two places we could find the XMLUI configuration,
// 1) inside the webapp's WEB-INF directory, or 2) inside the
// installed dspace config directory along side the dspace.cfg.
webappConfigPath = arg0.getServletContext().getRealPath("/")
+ File.separator + "WEB-INF" + File.separator + "xmlui.xconf";
installedConfigPath = ConfigurationManager.getProperty("dspace.dir")
+ File.separator + "config" + File.separator + "xmlui.xconf";
XMLUIConfiguration.loadConfig(webappConfigPath,installedConfigPath);
}
catch (RuntimeException e)
{
throw e;
}
catch (Exception e)
{
throw new ServletException(
"\n\nDSpace has failed to initialize, during stage 3. Error while attempting to read \n" +
"the XML UI configuration file (Path: "+webappConfigPath+" or '"+installedConfigPath+"').\n" +
"This has likely occurred because either the file does not exist, or it's permissions \n" +
"are set incorrectly, or the path to the configuration file is incorrect. The XML UI \n" +
"configuration file should be named \"xmlui.xconf\" and located inside the standard \n" +
"DSpace configuration directory. \n\n",e);
}
if (ConfigurationManager.getBooleanProperty("harvester.autoStart"))
{
try {
OAIHarvester.startNewScheduler();
}
catch (RuntimeException e)
{
LOG.error(e.getMessage(), e);
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
}
}
}
/**
* Before passing off a request to the cocoon servlet check to see if there is a request that
* should be resumed? If so replace the real request with a faked request and pass that off to
* cocoon.
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest realRequest = (HttpServletRequest)request;
HttpServletResponse realResponse = (HttpServletResponse) response;
try {
// Check if there is a request to be resumed.
realRequest = AuthenticationUtil.resumeRequest(realRequest);
// Send the real request or the resumed request off to
// cocoon....
// if force ssl is on and the user has authenticated and the request is not secure redirect to https
if ((ConfigurationManager.getBooleanProperty("xmlui.force.ssl")) && (realRequest.getSession().getAttribute("dspace.current.user.id")!=null) && (!realRequest.isSecure())) {
StringBuffer location = new StringBuffer("https://");
location.append(ConfigurationManager.getProperty("dspace.hostname")).append(realRequest.getContextPath()).append(realRequest.getServletPath()).append(
realRequest.getQueryString() == null ? ""
: ("?" + realRequest.getQueryString()));
realResponse.sendRedirect(location.toString());
}
arg2.doFilter(realRequest, realResponse);
} catch (RuntimeException e) {
ContextUtil.abortContext(realRequest);
LOG.error("Serious Runtime Error Occurred Processing Request!", e);
throw e;
} catch (Exception e) {
ContextUtil.abortContext(realRequest);
LOG.error("Serious Error Occurred Processing Request!", e);
} finally {
// Close out the DSpace context no matter what.
ContextUtil.completeContext(realRequest);
}
}
public void destroy() {
// TODO Auto-generated method stub
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.Map;
import org.apache.avalon.excalibur.pool.Recyclable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.generation.AbstractGenerator;
import org.apache.cocoon.util.HashUtil;
import org.apache.cocoon.xml.dom.DOMStreamer;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.ExpiresValidity;
import org.dspace.app.util.OpenSearch;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.FeedUtils;
import org.dspace.search.DSQuery;
import org.dspace.search.QueryArgs;
import org.dspace.search.QueryResults;
import org.dspace.sort.SortOption;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.handle.HandleManager;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
*
* Generate an OpenSearch-compliant search results document for DSpace, either
* a community or collection or the whole repository.
*
* Once thing that has been modified from DSpace's JSP implementation is what
* is placed inside an item's description, we've changed it so that the list
* of metadata fields is scanned until a value is found and the first one
* found is used as the description. This means that we look at the abstract,
* description, alternative title, title, etc... to and the first metadata
* value found is used.
*
* I18N: Feed's are internationalized, meaning that they may contain references
* to messages contained in the global messages.xml file using cocoon's i18n
* schema. However the library used to build the feeds does not understand
* this schema to work around this limitation I created a little hack. It
* basically works like this, when text that needs to be localized is put into
* the feed it is always mangled such that a prefix is added to the messages's
* key. Thus if the key were "xmlui.feed.text" then the resulting text placed
* into the feed would be "I18N:xmlui.feed.text". After the library is finished
* and produced it's final result the output is traversed to find these
* occurrences and replace them with proper cocoon i18n elements.
*
* @author Richard Rodgers
*/
public class OpenSearchGenerator extends AbstractGenerator
implements CacheableProcessingComponent, Recyclable
{
/** Cache of this object's validity */
private ExpiresValidity validity = null;
/** The results requested format */
private String format = null;
/** the search query string */
private String query = null;
/** optional search scope (= handle of container) or null */
private String scope = null;
/** optional sort specification */
private int sort = 0;
/** sort order, see SortOption **/
private String sortOrder = null;
/** results per page */
private int rpp = 0;
/** first result index */
private int start = 0;
/** request type */
private String type = null;
/** the results document (cached) */
private Document resultsDoc = null;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
StringBuffer key = new StringBuffer("key:");
if (scope != null)
{
key.append(scope);
}
key.append(query);
if (format != null)
{
key.append(format);
}
key.append(sort);
key.append(start);
key.append(rpp);
key.append(sortOrder);
return HashUtil.hash(key.toString());
}
/**
* Generate the cache validity object.
*
*/
public SourceValidity getValidity()
{
if (this.validity == null)
{
long expiry = System.currentTimeMillis() +
ConfigurationManager.getLongProperty("websvc.opensearch.validity") * 60 * 60 * 1000;
this.validity = new ExpiresValidity(expiry);
}
return this.validity;
}
/**
* Setup configuration for this request
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters par) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver, objectModel, src, par);
Request request = ObjectModelHelper.getRequest(objectModel);
this.query = request.getParameter("query");
if (query == null)
{
query = "";
}
query = URLDecoder.decode(query, "UTF-8");
this.format = request.getParameter("format");
if (format == null || format.length() == 0)
{
format = "atom";
}
this.scope = request.getParameter("scope");
String srt = request.getParameter("sort_by");
this.sort = (srt == null || srt.length() == 0) ? 0 : Integer.valueOf(srt);
String order = request.getParameter("order");
this.sortOrder = (order == null || order.length() == 0 || order.toLowerCase().startsWith("asc")) ?
SortOption.ASCENDING : SortOption.DESCENDING;
String st = request.getParameter("start");
this.start = (st == null || st.length() == 0) ? 0 : Integer.valueOf(st);
String pp = request.getParameter("rpp");
this.rpp = (pp == null || pp.length() == 0) ? 0 : Integer.valueOf(pp);
try
{
this.type = par.getParameter("type");
}
catch(ParameterException e)
{
this.type = "results";
}
}
/**
* Generate the search results document.
*/
public void generate() throws IOException, SAXException, ProcessingException
{
Document retDoc = null;
try
{
if (type != null && type.equals("description"))
{
retDoc = OpenSearch.getDescriptionDoc(scope);
}
else if (resultsDoc != null)
{
// use cached document if available
retDoc = resultsDoc;
}
else
{
Context context = ContextUtil.obtainContext(objectModel);
QueryArgs qArgs = new QueryArgs();
// can't start earlier than 0 in the results!
if (start < 0)
{
start = 0;
}
qArgs.setStart(start);
if (rpp > 0)
{
qArgs.setPageSize(rpp);
}
qArgs.setSortOrder(sortOrder);
if (sort > 0)
{
try
{
qArgs.setSortOption(SortOption.getSortOption(sort));
}
catch(Exception e)
{
// invalid sort id - do nothing
}
}
qArgs.setSortOrder(sortOrder);
// If there is a scope parameter, attempt to dereference it
// failure will only result in its being ignored
DSpaceObject container = null;
if ((scope != null) && !scope.equals(""))
{
container = HandleManager.resolveToObject(context, scope);
}
qArgs.setQuery(query);
// Perform the search
QueryResults qResults = null;
if (container == null)
{
qResults = DSQuery.doQuery(context, qArgs);
}
else if (container instanceof Collection)
{
qResults = DSQuery.doQuery(context, qArgs, (Collection)container);
}
else if (container instanceof Community)
{
qResults = DSQuery.doQuery(context, qArgs, (Community)container);
}
else
{
throw new IllegalStateException("Invalid container for search context");
}
// now instantiate the results
DSpaceObject[] results = new DSpaceObject[qResults.getHitHandles().size()];
for (int i = 0; i < qResults.getHitHandles().size(); i++)
{
String myHandle = qResults.getHitHandles().get(i);
DSpaceObject dso = HandleManager.resolveToObject(context, myHandle);
if (dso == null)
{
throw new SQLException("Query \"" + query
+ "\" returned unresolvable handle: " + myHandle);
}
results[i] = dso;
}
resultsDoc = OpenSearch.getResultsDoc(format, query, qResults,
container, results, FeedUtils.i18nLabels);
FeedUtils.unmangleI18N(resultsDoc);
retDoc = resultsDoc;
}
if (retDoc != null)
{
DOMStreamer streamer = new DOMStreamer(contentHandler, lexicalHandler);
streamer.stream(retDoc);
}
}
catch (IOException e)
{
throw new SAXException(e);
}
catch (SQLException sqle)
{
throw new SAXException(sqle);
}
}
/**
* Recycle
*/
public void recycle()
{
this.format = null;
this.query = null;
this.scope = null;
this.sort = 0;
this.rpp = 0;
this.start = 0;
this.type = null;
this.sortOrder = null;
this.resultsDoc = null;
this.validity = null;
super.recycle();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.util.HashMap;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.dspace.core.ConfigurationManager;
/**
* Class will read the DSpace configuration file via the ConfigurationManager
*
* It accepts the name of the property to read and the name of the variable to
* use in the sitemap scope.
* For example:
* <map:act type="DSpacePropertyFileReader">
* <map:parameter name="dspace.dir" value="dspace_dir" />
* <map:transform type="Include" src="{dspace_dir}/config/news.xml" />
* </map:act>
* Will place the value of the "dspace.dir" property in the "dspace_dir" variable to be
* used in the sitemap.
*
* @author Jay Paz
*
*/
public class DSpacePropertyFileReader extends AbstractAction {
public Map act(Redirector redirector, SourceResolver resolver,
Map objectModel, String source, Parameters parameters)
throws Exception {
Map<String, String> map = new HashMap<String, String>();
final String[] parameterNames = parameters.getNames();
for (int i = 0; i < parameterNames.length; i++) {
final String paramName = parameterNames[i];
map.put(parameters.getParameter(paramName),
ConfigurationManager.getProperty(paramName));
}
return map;
}
} | Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
/**
* Class will read the the specified configuration file via the property-file parameter
*
* It accepts the name of the property file to read and the properties to set to the sitemap scope
* For example:
* <map:act type="PropertyFileReader">
* <map:parameter name="property-file" value="/absolute/path/to/property/file />
* <map:parameter name="some.property" value="some_property" />
* ...
* </map:act>
* Will place the value of the "some.property" property in the "some_property" variable to be
* used in the sitemap using the {some_property} syntax.
*
* @author Jay Paz
*
*/
public class PropertyFileReader {
public Map act(Redirector redirector, SourceResolver resolver,
Map objectModel, String source, Parameters parameters)
throws Exception {
Map<String, String> map = new HashMap<String, String>();
String propertyFile = parameters.getParameter("property-file");
Properties props = new Properties();
InputStream in = new FileInputStream(propertyFile);
try {
props.load(in);
} finally {
in.close();
}
final String[] parameterNames = parameters.getNames();
for (int i = 0; i < parameterNames.length; i++) {
final String paramName = parameterNames[i];
if ("property-file".equals(paramName)) {
continue;
}
map.put(parameters.getParameter(paramName), props
.getProperty(paramName));
}
return map;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.configuration.MutableConfiguration;
import org.apache.cocoon.transformation.I18nTransformer;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.configuration.Aspect;
import org.dspace.app.xmlui.configuration.XMLUIConfiguration;
/**
* This is a simple extension to the stardand Cocoon I18N transformer
* that specializes the configuration based upon currently installed
* aspects.
*
* This transformer modified the base configuration by adding two
* <location/> parameters for each aspect into the default catalogue.
* The first location parameter is contained within the catalogue's
* base location + the aspect path. The second location parameter is
* located inside the aspect's path + "/i18n/"
*
* This allows aspect developers to place their default messages files
* inside the aspect, and place translations into various languages inside
* the base i18n/ directory.
*
* EXAMPLE:
*
* For instance let's say there the i18n transformer's configuration
* were as follows:
* <catalogues default="default">
* <catalogue id="default" name="messages" aspects="true">
* <location>context://i18n</location>
* </catalogue>
* </catalogues>
*
* And there were two aspects installed:
* <aspect name="Artifact Browser" path="resource://aspects/ArtifactBrowser/" />
* <aspect name="Administration" path="resource://aspects/Administrative/" />
*
* The effective configuration would be:
* <catalogues default="default">
* <catalogue id="default" name="messages" aspects="true">
* <location>context://i18n/</location>
* <location>context://i18n/aspects/ArtifactBrowser</location>
* <location>resource://aspects/ArtifactBrowser/i18n/</location>
* <location>context://i18n/aspects/Administrative</location>
* <location>resource://aspects/Administrative/i18n/</location>
* </catalogue>
* </catalogues>
*
*
* @author Scott Phillips
*/
public class DSpaceI18NTransformer extends I18nTransformer {
/** log4j category */
private static Logger log = Logger.getLogger(DSpaceI18NTransformer.class);
// If we can't find a base location, use this one by default.
public static final String DEFAULT_BASE_LOCATION ="context://i18n/";
/**
* Intercept the configuration parameters comming from the cocoon sitemap before
* they are read by the cocoon i18n transformer. We want to add in <location> parameters
* for each
*/
public void configure(Configuration originalConf) throws ConfigurationException
{
MutableConfiguration modifiedConf = new DefaultConfiguration(originalConf,true);
MutableConfiguration cataloguesConf = modifiedConf.getMutableChild("catalogues", true);
// Find the default catalogue and add our new locations to it.
for (MutableConfiguration catalogueConf : cataloguesConf.getMutableChildren())
{
if (!"false".equals(catalogueConf.getAttribute("aspects","false")))
{
// Get the first location element to determine what the base path is.
String baseCatalogueLocationPath = DEFAULT_BASE_LOCATION;
Configuration baseCatalogueLocationConf = catalogueConf.getChild("location");
if (baseCatalogueLocationConf != null)
{
baseCatalogueLocationPath = baseCatalogueLocationConf.getValue();
}
if (!baseCatalogueLocationPath.endsWith("/"))
{
baseCatalogueLocationPath += "/";
} // Add a trailing slash if one dosn't exist
String catalogueId = catalogueConf.getAttribute("id","unknown");
// For each aspect add two new locations one inside the aspect's directory
// and another inside the base location for i18n files.
for (Aspect aspect : XMLUIConfiguration.getAspectChain())
{
// Add a catalogue location inside the default i18n directory in the webapp
// this will be of the form: "context://i18n/<aspectpath>/" thus for the artifact
// browser aspect it will be "context://i18n/aspects/ArtifactBrowser/"
String baseLocationPath = aspect.getPath();
int idx = baseLocationPath.indexOf("://");
if (idx > 0)
{
// remove the module directive from the aspect's path so it's just a normal path
baseLocationPath = baseLocationPath.substring(idx + 3, baseLocationPath.length());
}
// Now that the module directive has been removed from the path, add in the base i18npath
baseLocationPath = baseCatalogueLocationPath + baseLocationPath;
MutableConfiguration baseLocation = new DefaultConfiguration("location");
baseLocation.setValue(baseLocationPath);
catalogueConf.addChild(baseLocation);
// Add a catalogue location inside the aspect's directory
// (most likely in the jar's resources but if it's not that's okay)
// For the artifact browser this would be:
// "resource://aspects/ArtifactBrowser/i18n/"
String aspectLocationPath = aspect.getPath();
if (!aspectLocationPath.endsWith("/"))
{
aspectLocationPath += "/"; // Add a trailing slash if one dosn't exist
}
aspectLocationPath += "i18n/";
MutableConfiguration aspectLocation = new DefaultConfiguration("location");
aspectLocation.setValue(aspectLocationPath);
catalogueConf.addChild(aspectLocation);
log.info("Adding i18n location path for '"+catalogueId+"' catalogue: "+baseLocationPath);
log.info("Adding i18n location path for '"+catalogueId+"' catalogue: "+aspectLocationPath);
} // for each aspect
} // if catalogue has the aspect parameter
} // for each catalogue
// Pass off to cocoon's i18n transformer our modified configuration with new aspect locations.
super.configure(modifiedConf);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.ResourceNotFoundException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.generation.AbstractGenerator;
import org.dspace.app.xmlui.objectmanager.AbstractAdapter;
import org.dspace.app.xmlui.objectmanager.ContainerAdapter;
import org.dspace.app.xmlui.objectmanager.ItemAdapter;
import org.dspace.app.xmlui.objectmanager.RepositoryAdapter;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.crosswalk.CrosswalkException;
import org.dspace.core.Context;
import org.dspace.handle.HandleManager;
import org.xml.sax.SAXException;
/**
* Generate a METS document for the identified item, community or collection. The object to be rendered should be
* identified by passing in one of the two parameters: handle or internal. If an internal ID is given then it must
* be of the form "type:id" i.g. item:255 or community:4 or repository:123456789. In the case of a repository the
* id must be the handle prefix.
*
* In addition to rendering a METS document there are several options which can be specified for how the mets
* document should be rendered. All parameters are a comma separated list of values, here is a list:
*
*
* sections:
*
* A comma separated list of METS sections to included. The possible values are: "metsHdr", "dmdSec",
* "amdSec", "fileSec", "structMap", "structLink", "behaviorSec", and "extraSec". If no list is provided then *ALL*
* sections are rendered.
*
*
* dmdTypes:
*
* A comma separated list of metadata formats to provide as descriptive metadata. The list of available metadata
* types is defined in the dspace.cfg, dissemination crosswalks. If no formats are provided them DIM - DSpace
* Intermediate Format - is used.
*
*
* amdTypes:
*
* A comma separated list of metadata formats to provide administrative metadata. DSpace does not currently
* support this type of metadata.
*
*
* fileGrpTypes:
*
* A comma separated list of file groups to render. For DSpace a bundle is translated into a METS fileGrp, so
* possible values are "THUMBNAIL","CONTENT", "METADATA", etc... If no list is provided then all groups are
* rendered.
*
*
* structTypes:
*
* A comma separated list of structure types to render. For DSpace there is only one structType: LOGICAL. If this
* is provided then the logical structType will be rendered, otherwise none will. The default operation is to
* render all structure types.
*
* @author scott phillips
*/
public class DSpaceMETSGenerator extends AbstractGenerator
{
/**
* Generate the METS Document.
*/
public void generate() throws IOException, SAXException,
ProcessingException {
try {
// Open a new context.
Context context = ContextUtil.obtainContext(objectModel);
// Determine which adapter to use
AbstractAdapter adapter = resolveAdapter(context);
if (adapter == null)
{
throw new ResourceNotFoundException("Unable to locate object.");
}
// Configure the adapter for this request.
configureAdapter(adapter);
// Generate the METS document
contentHandler.startDocument();
adapter.renderMETS(contentHandler,lexicalHandler);
contentHandler.endDocument();
} catch (WingException we) {
throw new ProcessingException(we);
} catch (CrosswalkException ce) {
throw new ProcessingException(ce);
} catch (SQLException sqle) {
throw new ProcessingException(sqle);
}
}
/**
* Determine which type of adapter to use for this object, either a community, collection, item, or
* repository adapter. The decision is based upon the two supplied identifiers: a handle or an
* internal id. If the handle is supplied then this is resolved and the appropriate adapter is
* picked. Otherwise the internal identifier is used to resolve the correct type of adapter.
*
* The internal identifier must be of the form "type:id" i.g. item:255 or collection:99. In the
* case of a repository the handle prefix must be used.
*
* @return Return the correct adaptor or null if none found.
*/
private AbstractAdapter resolveAdapter(Context context) throws SQLException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String contextPath = request.getContextPath();
// Determine the correct adapter to use for this item
String handle = parameters.getParameter("handle",null);
String internal = parameters.getParameter("internal",null);
AbstractAdapter adapter = null;
if (handle != null)
{
// Specified using a regular handle.
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
// Handles can be either items or containers.
if (dso instanceof Item)
{
adapter = new ItemAdapter(context, (Item) dso, contextPath);
}
else if (dso instanceof Collection || dso instanceof Community)
{
adapter = new ContainerAdapter(context, dso, contextPath);
}
}
else if (internal != null)
{
// Internal identifier, format: "type:id".
String[] parts = internal.split(":");
if (parts.length == 2)
{
String type = parts[0];
String strid = parts[1];
int id = 0;
// Handle prefixes must be treated as strings
// all non-repository types need integer IDs
if ("repository".equals(type))
{
if (HandleManager.getPrefix().equals(strid))
{
adapter = new RepositoryAdapter(context, contextPath);
}
}
else
{
id = Integer.valueOf(parts[1]);
if ("item".equals(type))
{
Item item = Item.find(context,id);
if (item != null)
{
adapter = new ItemAdapter(context, item, contextPath);
}
}
else if ("collection".equals(type))
{
Collection collection = Collection.find(context,id);
if (collection != null)
{
adapter = new ContainerAdapter(context, collection, contextPath);
}
}
else if ("community".equals(type))
{
Community community = Community.find(context,id);
if (community != null)
{
adapter = new ContainerAdapter(context, community, contextPath);
}
}
}
}
}
return adapter;
}
/**
* Configure the adapter according to the supplied parameters.
*/
public void configureAdapter(AbstractAdapter adapter)
{
// Configure the adapter based upon the passed parameters
Request request = ObjectModelHelper.getRequest(objectModel);
String sections = request.getParameter("sections");
String dmdTypes = request.getParameter("dmdTypes");
String techMDTypes = request.getParameter("techMDTypes");
String rightsMDTypes = request.getParameter("rightsMDTypes");
String sourceMDTypes = request.getParameter("sourceMDTypes");
String digiprovMDTypes = request.getParameter("digiprovMDTypes");
String fileGrpTypes = request.getParameter("fileGrpTypes");
String structTypes = request.getParameter("structTypes");
adapter.setSections(sections);
adapter.setDmdTypes(dmdTypes);
adapter.setTechMDTypes(techMDTypes);
adapter.setRightsMDTypes(rightsMDTypes);
adapter.setSourceMDTypes(sourceMDTypes);
adapter.setDigiProvMDTypes(digiprovMDTypes);
adapter.setFileGrpTypes(fileGrpTypes);
adapter.setStructTypes(structTypes);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.excalibur.pool.Recyclable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Response;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.environment.http.HttpResponse;
import org.apache.cocoon.reading.AbstractReader;
import org.apache.cocoon.util.ByteRange;
import org.dspace.app.itemexport.ItemExport;
import org.dspace.app.xmlui.utils.AuthenticationUtil;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.core.Context;
import org.xml.sax.SAXException;
/**
* @author Jay Paz
*/
public class ItemExportDownloadReader extends AbstractReader implements Recyclable
{
/**
* Messages to be sent when the user is not authorized to view
* a particular bitstream. They will be redirected to the login
* where this message will be displayed.
*/
private static final String AUTH_REQUIRED_HEADER = "xmlui.ItemExportDownloadReader.auth_header";
private static final String AUTH_REQUIRED_MESSAGE = "xmlui.ItemExportDownloadReader.auth_message";
/**
* How big of a buffer should we use when reading from the bitstream before
* writting to the HTTP response?
*/
protected static final int BUFFER_SIZE = 8192;
/**
* When should a download expire in milliseconds. This should be set to
* some low value just to prevent someone hiting DSpace repeatily from
* killing the server. Note: 60000 milliseconds are in a second.
*
* Format: minutes * seconds * milliseconds
*/
protected static final int expires = 60 * 60 * 60000;
/** The Cocoon response */
protected Response response;
/** The Cocoon request */
protected Request request;
/** The bitstream file */
protected InputStream compressedExportInputStream;
/** The compressed export's reported size */
protected long compressedExportSize;
protected String compressedExportName;
/**
* Set up the export reader.
*
* See the class description for information on configuration options.
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters par) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver, objectModel, src, par);
try
{
this.request = ObjectModelHelper.getRequest(objectModel);
this.response = ObjectModelHelper.getResponse(objectModel);
Context context = ContextUtil.obtainContext(objectModel);
// Get our parameters that identify the bitstream
String fileName = par.getParameter("fileName", null);
// Is there a User logged in and does the user have access to read it?
if (!ItemExport.canDownload(context, fileName))
{
if(context.getCurrentUser()!=null){
// A user is logged in, but they are not authorized to read this bitstream,
// instead of asking them to login again we'll point them to a friendly error
// message that tells them the bitstream is restricted.
String redictURL = request.getContextPath() + "/restricted-resource?name=" + fileName;
HttpServletResponse httpResponse = (HttpServletResponse)
objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redictURL);
return;
}
else{
// The user does not have read access to this bitstream. Inturrupt this current request
// and then forward them to the login page so that they can be authenticated. Once that is
// successfull they will request will be resumed.
AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null);
// Redirect
String redictURL = request.getContextPath() + "/login";
HttpServletResponse httpResponse = (HttpServletResponse)
objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
httpResponse.sendRedirect(redictURL);
return;
}
}
// Success, bitstream found and the user has access to read it.
// Store these for later retreval:
this.compressedExportInputStream = ItemExport.getExportDownloadInputStream(fileName, context.getCurrentUser());
this.compressedExportSize = ItemExport.getExportFileSize(fileName);
this.compressedExportName = fileName;
}
catch (Exception e)
{
throw new ProcessingException("Unable to read bitstream.",e);
}
}
/**
* Write the actual data out to the response.
*
* Some implementation notes,
*
* 1) We set a short expires time just in the hopes of preventing someone
* from overloading the server by clicking reload a bunch of times. I
* realize that this is nowhere near 100% effective but it may help in some
* cases and shouldn't hurt anything.
*
*/
public void generate() throws IOException, SAXException,
ProcessingException
{
if (this.compressedExportInputStream == null)
{
return;
}
byte[] buffer = new byte[BUFFER_SIZE];
int length = -1;
response.setDateHeader("Expires", System.currentTimeMillis()
+ expires);
response.setHeader("Content-disposition","attachement; filename=" + this.compressedExportName );
ByteRange byteRange = null;
// Turn off partial downloads, they cause problems
// and are only rarely used. Specifically some windows pdf
// viewers are incapable of handling this request. You can
// uncomment the following lines to turn this feature back on.
// response.setHeader("Accept-Ranges", "bytes");
// String ranges = request.getHeader("Range");
// if (ranges != null)
// {
// try
// {
// ranges = ranges.substring(ranges.indexOf('=') + 1);
// byteRange = new ByteRange(ranges);
// }
// catch (NumberFormatException e)
// {
// byteRange = null;
// if (response instanceof HttpResponse)
// {
// // Respond with status 416 (Request range not
// // satisfiable)
// response.setStatus(416);
// }
// }
// }
if (byteRange != null)
{
String entityLength;
String entityRange;
if (this.compressedExportSize != -1)
{
entityLength = "" + this.compressedExportSize;
entityRange = byteRange.intersection(
new ByteRange(0, this.compressedExportSize)).toString();
}
else
{
entityLength = "*";
entityRange = byteRange.toString();
}
response.setHeader("Content-Range", entityRange + "/"
+ entityLength);
if (response instanceof HttpResponse)
{
// Response with status 206 (Partial content)
((HttpResponse) response).setStatus(206);
}
int pos = 0;
int posEnd;
while ((length = this.compressedExportInputStream.read(buffer)) > -1)
{
posEnd = pos + length - 1;
ByteRange intersection = byteRange
.intersection(new ByteRange(pos, posEnd));
if (intersection != null)
{
out.write(buffer, (int) intersection.getStart()
- pos, (int) intersection.length());
}
pos += length;
}
}
else
{
response.setHeader("Content-Length", String
.valueOf(this.compressedExportSize));
while ((length = this.compressedExportInputStream.read(buffer)) > -1)
{
out.write(buffer, 0, length);
}
out.flush();
}
}
/**
* Returns the mime-type of the bitstream.
*/
public String getMimeType()
{
return ItemExport.COMPRESSED_EXPORT_MIME_TYPE;
}
/**
* Recycle
*/
public void recycle() {
this.response = null;
this.request = null;
this.compressedExportInputStream = null;
this.compressedExportSize = 0;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.avalon.excalibur.pool.Recyclable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.ResourceNotFoundException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.generation.AbstractGenerator;
import org.apache.cocoon.util.HashUtil;
import org.apache.cocoon.xml.dom.DOMStreamer;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.FeedUtils;
import org.dspace.app.util.SyndicationFeed;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowserScope;
import org.dspace.sort.SortException;
import org.dspace.sort.SortOption;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.eperson.Group;
import org.dspace.handle.HandleManager;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.sun.syndication.io.FeedException;
/**
*
* Generate a syndication feed for DSpace, either a community or collection
* or the whole repository. This code was adapted from the syndication found
* in DSpace's JSP implementation, "org.dspace.app.webui.servlet.FeedServlet".
*
* Once thing that has been modified from DSpace's JSP implementation is what
* is placed inside an item's description, we've changed it so that the list
* of metadata fields is scanned until a value is found and the first one
* found is used as the description. This means that we look at the abstract,
* description, alternative title, title, etc... to and the first metadata
* value found is used.
*
* I18N: Feed's are internationalized, meaning that they may contain refrences
* to messages contained in the global messages.xml file using cocoon's i18n
* schema. However the library used to build the feeds does not understand
* this schema to work around this limitation I created a little hack. It
* basicaly works like this, when text that needs to be localized is put into
* the feed it is allways mangled such that a prefix is added to the messages's
* key. Thus if the key were "xmlui.feed.text" then the resulting text placed
* into the feed would be "I18N:xmlui.feed.text". After the library is finished
* and produced it's final result the output is traversed to find these
* occurances ande replace them with proper cocoon i18n elements.
*
*
*
* @author Scott Phillips, Ben Bosman, Richard Rodgers
*/
public class DSpaceFeedGenerator extends AbstractGenerator
implements Configurable, CacheableProcessingComponent, Recyclable
{
private static final Logger log = Logger.getLogger(DSpaceFeedGenerator.class);
/** The feed's requested format */
private String format = null;
/** The feed's scope, null if no scope */
private String handle = null;
/** number of DSpace items per feed */
private static final int ITEM_COUNT = ConfigurationManager.getIntProperty("webui.feed.items");
/**
* How long should RSS feed cache entries be valid? milliseconds * seconds *
* minutes * hours default to 24 hours if config parameter is not present or
* wrong
*/
private static final long CACHE_AGE;
static
{
final String ageCfgName = "webui.feed.cache.age";
final long ageCfg = ConfigurationManager.getIntProperty(ageCfgName, 24);
CACHE_AGE = 1000 * 60 * 60 * ageCfg;
}
/** configuration option to include Item which does not have READ by Anonymous enabled **/
private static boolean includeRestrictedItems = ConfigurationManager.getBooleanProperty("harvest.includerestricted.rss", true);
/** Cache of this object's validitity */
private DSpaceValidity validity = null;
/** The cache of recently submitted items */
private Item recentSubmissionItems[];
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
String key = "key:" + this.handle + ":" + this.format;
return HashUtil.hash(key);
}
/**
* Generate the cache validity object.
*
* The validity object will include the collection being viewed and
* all recently submitted items. This does not include the community / collection
* hierarch, when this changes they will not be reflected in the cache.
*/
public SourceValidity getValidity()
{
if (this.validity == null)
{
try
{
DSpaceValidity validity = new FeedValidity();
Context context = ContextUtil.obtainContext(objectModel);
DSpaceObject dso = null;
if (handle != null && !handle.contains("site"))
{
dso = HandleManager.resolveToObject(context, handle);
}
validity.add(dso);
// add reciently submitted items
for(Item item : getRecentlySubmittedItems(context,dso))
{
validity.add(item);
}
this.validity = validity.complete();
}
catch (RuntimeException e)
{
throw e;
}
catch (Exception e)
{
return null;
}
}
return this.validity;
}
/**
* Setup component wide configuration
*/
public void configure(Configuration conf) throws ConfigurationException
{
}
/**
* Setup configuration for this request
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters par) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver, objectModel, src, par);
this.format = par.getParameter("feedFormat", null);
this.handle = par.getParameter("handle",null);
}
/**
* Generate the syndication feed.
*/
public void generate() throws IOException, SAXException, ProcessingException
{
try
{
Context context = ContextUtil.obtainContext(objectModel);
DSpaceObject dso = null;
if (handle != null && !handle.contains("site"))
{
dso = HandleManager.resolveToObject(context, handle);
if (dso == null)
{
// If we were unable to find a handle then return page not found.
throw new ResourceNotFoundException("Unable to find DSpace object matching the given handle: "+handle);
}
if (!(dso.getType() == Constants.COLLECTION || dso.getType() == Constants.COMMUNITY))
{
// The handle is valid but the object is not a container.
throw new ResourceNotFoundException("Unable to syndicate DSpace object: "+handle);
}
}
SyndicationFeed feed = new SyndicationFeed(SyndicationFeed.UITYPE_XMLUI);
feed.populate(ObjectModelHelper.getRequest(objectModel),
dso, getRecentlySubmittedItems(context,dso), FeedUtils.i18nLabels);
feed.setType(this.format);
Document dom = feed.outputW3CDom();
FeedUtils.unmangleI18N(dom);
DOMStreamer streamer = new DOMStreamer(contentHandler, lexicalHandler);
streamer.stream(dom);
}
catch (IllegalArgumentException iae)
{
throw new ResourceNotFoundException("Syndication feed format, '"+this.format+"', is not supported.", iae);
}
catch (FeedException fe)
{
throw new SAXException(fe);
}
catch (SQLException sqle)
{
throw new SAXException(sqle);
}
}
/**
* @return recently submitted Items within the indicated scope
*/
@SuppressWarnings("unchecked")
private Item[] getRecentlySubmittedItems(Context context, DSpaceObject dso)
throws SQLException
{
if (recentSubmissionItems != null)
{
return recentSubmissionItems;
}
String source = ConfigurationManager.getProperty("recent.submissions.sort-option");
BrowserScope scope = new BrowserScope(context);
if (dso instanceof Collection)
{
scope.setCollection((Collection) dso);
}
else if (dso instanceof Community)
{
scope.setCommunity((Community) dso);
}
scope.setResultsPerPage(ITEM_COUNT);
// FIXME Exception handling
try
{
scope.setBrowseIndex(BrowseIndex.getItemBrowseIndex());
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(source))
{
scope.setSortBy(so.getNumber());
scope.setOrder(SortOption.DESCENDING);
}
}
BrowseEngine be = new BrowseEngine(context);
this.recentSubmissionItems = be.browseMini(scope).getItemResults(context);
// filter out Items taht are not world-readable
if (!includeRestrictedItems)
{
List<Item> result = new ArrayList<Item>();
for (Item item : this.recentSubmissionItems)
{
checkAccess:
for (Group group : AuthorizeManager.getAuthorizedGroups(context, item, Constants.READ))
{
if ((group.getID() == 0))
{
result.add(item);
break checkAccess;
}
}
}
this.recentSubmissionItems = result.toArray(new Item[result.size()]);
}
}
catch (BrowseException bex)
{
log.error("Caught browse exception", bex);
}
catch (SortException e)
{
log.error("Caught sort exception", e);
}
return this.recentSubmissionItems;
}
/**
* Recycle
*/
public void recycle()
{
this.format = null;
this.handle = null;
this.validity = null;
this.recentSubmissionItems = null;
super.recycle();
}
/**
* Extend the standard DSpaceValidity object to support assumed
* caching. Since feeds will constantly be requested we want to
* assume that a feed is still valid instead of checking it
* against the database anew everytime.
*
* This validity object will assume that a cache is still valid,
* without rechecking it, for 24 hours.
*
*/
private static class FeedValidity extends DSpaceValidity
{
private static final long serialVersionUID = 1L;
/** When the cache's validity expires */
private long expires = 0;
/**
* When the validity is completed record a timestamp to check later.
*/
public DSpaceValidity complete()
{
this.expires = System.currentTimeMillis() + CACHE_AGE;
return super.complete();
}
/**
* Determine if the cache is still valid
*/
public int isValid()
{
// Return true if we have a hash.
if (this.completed)
{
if (System.currentTimeMillis() < this.expires)
{
// If the cache hasn't expired the just assume that it is still valid.
return SourceValidity.VALID;
}
else
{
// The cache is past its age
return SourceValidity.UNKNOWN;
}
}
else
{
// This is an error, state. We are being asked whether we are valid before
// we have been initialized.
return SourceValidity.INVALID;
}
}
/**
* Determine if the cache is still valid based
* upon the other validity object.
*
* @param other
* The other validity object.
*/
public int isValid(SourceValidity otherValidity)
{
if (this.completed && otherValidity instanceof FeedValidity)
{
FeedValidity other = (FeedValidity) otherValidity;
if (hash == other.hash)
{
// Update both cache's expiration time.
this.expires = System.currentTimeMillis() + CACHE_AGE;
other.expires = System.currentTimeMillis() + CACHE_AGE;
return SourceValidity.VALID;
}
}
return SourceValidity.INVALID;
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.generation.FileGenerator;
import org.xml.sax.SAXException;
/**
* This Cocoon generator will generate an internal cocoon request for the next
* DRI Aspect in the chain.
*
* The first time this generator is called it will issue a request for Aspect 2,
* while it dose this it will store the aspect number in the request object.
* Every time after the initial use the aspect number is increased and used to
* generate the next Aspect url.
*
* This class extends the FileGenerator and simple intercepts the setup method
* ignoring anything passed in as the generators source and determines it's own
* source based upon the current Aspect state.
*
* @author Scott Phillips
*/
public class AspectGenerator extends FileGenerator implements
CacheableProcessingComponent
{
/** The URI Prefix of all aspect URIs */
public static final String PREFIX = "/DRI/";
/** The Protocol to use, in this case an internal cocoon request */
public static final String PROTOCOL = "cocoon";
/** The name of the Aspect_ID attribute */
public static final String ASPECT_ID = "org.dspace.app.xmlui.AspectGenerator.AspectID";
/**
* Setup the AspectGenerator.
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters par) throws ProcessingException, SAXException,
IOException
{
Request request = ObjectModelHelper.getRequest(objectModel);
Integer aspectID = (Integer) request.getAttribute(ASPECT_ID);
// If no aspect ID found, assume it's the first one.
if (aspectID == null)
{
aspectID = 0;
}
// Get the aspect ID of the next aspect & store it for later.
aspectID++;
request.setAttribute(ASPECT_ID, aspectID);
// Get the original path
String path = request.getSitemapURI();
// Build the final path to the next Aspect.
String aspectPath = PROTOCOL + ":/" + PREFIX + aspectID + "/" + path;
getLogger().debug("aspectgenerator path: "+aspectPath);
// Use the standard FileGenerator to get the next Aspect.
super.setup(resolver, objectModel, aspectPath, par);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.WingTransformer;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.UserMeta;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
*
* The WingTransformer is a simple framework for dealing with DSpace based SAX
* events. The implementing class is responsable for catching the approprate
* events and filtering them into these method calls. This allows implementors
* to have easy access to the document without dealing with the messyness of the
* sax event system.
*
* @author Scott Phillips
*/
public interface DSpaceTransformer extends WingTransformer
{
/** What to add at the end of the body */
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException;
/** What to add to the options list */
public void addOptions(Options options) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException;
/** What user metadata to add to the document */
public void addUserMeta(UserMeta userMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException;
/** What page metadata to add to the document */
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException;
/** What is a unique name for this component? */
public String getComponentName();
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
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.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
/**
* This is a wrapper class that translates a Cocoon request object back
* into an HttpServletRequest object. The main purpose of this class is to
* support form encoding in libraries that require a real HttpServletRequest
* object. If they are given the real request object then any parameters they
* obtain from it will not take into account the form encoding. Thus this
* method, by proxing everything back through the cocoon object will not
* be hindered by this problem.
*
*
* Some methods are unsupported, see below for a list.
* getCookies(),getInputStream(),getParameterMap(),getReader(),
* getRealPath(String arg0),getRequestDispatcher(String arg0)
*
* @author Scott Phillips
*/
public class HttpServletRequestCocoonWrapper implements HttpServletRequest{
private Request cocoonRequest;
//private HttpServletRequest realRequest;
public HttpServletRequestCocoonWrapper(Map objectModel) {
// Get the two requests objects the cocoon one, and the real request object as a fall back.
this.cocoonRequest = ObjectModelHelper.getRequest(objectModel);
// If the real request is needed in the future to fall back to when the
// cocoon request object dosn't support those methods use the following line.
//this.realRequest = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
}
public String getAuthType() {
return this.cocoonRequest.getAuthType();
}
public String getContextPath() {
return this.cocoonRequest.getContextPath();
}
public Cookie[] getCookies() {
throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support cookies.");
}
public long getDateHeader(String arg0) {
return this.cocoonRequest.getDateHeader(arg0);
}
public String getHeader(String arg0) {
return this.cocoonRequest.getHeader(arg0);
}
public Enumeration getHeaderNames() {
return this.cocoonRequest.getHeaderNames();
}
public Enumeration getHeaders(String arg0) {
return this.cocoonRequest.getHeaders(arg0);
}
public int getIntHeader(String arg0) {
Enumeration e = getHeaders(arg0);
if (e.hasMoreElements())
{
Object v = e.nextElement();
if (v instanceof String)
{
try {
return Integer.valueOf((String)v);
} catch (NumberFormatException nfe)
{
// do nothing
}
}
}
return -1;
}
public String getMethod() {
return this.cocoonRequest.getMethod();
}
public String getPathInfo() {
return this.cocoonRequest.getPathInfo();
}
public String getPathTranslated() {
return this.cocoonRequest.getPathTranslated();
}
public String getQueryString() {
return this.cocoonRequest.getQueryString();
}
public String getRemoteUser() {
return this.cocoonRequest.getRemoteUser();
}
public String getRequestURI() {
return this.cocoonRequest.getRequestURI();
}
public StringBuffer getRequestURL() {
return new StringBuffer(this.cocoonRequest.getRequestURI());
}
public String getRequestedSessionId() {
return this.cocoonRequest.getRequestedSessionId();
}
public String getServletPath() {
return this.cocoonRequest.getServletPath();
}
public HttpSession getSession() {
return (HttpSession) this.cocoonRequest.getSession();
}
public HttpSession getSession(boolean arg0) {
return (HttpSession) this.cocoonRequest.getSession(arg0);
}
public Principal getUserPrincipal() {
return this.cocoonRequest.getUserPrincipal();
}
public boolean isRequestedSessionIdFromCookie() {
return this.cocoonRequest.isRequestedSessionIdFromCookie();
}
public boolean isRequestedSessionIdFromURL() {
return this.cocoonRequest.isRequestedSessionIdFromURL();
}
public boolean isRequestedSessionIdFromUrl() {
return this.cocoonRequest.isRequestedSessionIdFromURL();
}
public boolean isRequestedSessionIdValid() {
return this.cocoonRequest.isRequestedSessionIdValid();
}
public boolean isUserInRole(String arg0) {
return this.cocoonRequest.isUserInRole(arg0);
}
public Object getAttribute(String arg0) {
return this.cocoonRequest.getAttribute(arg0);
}
public Enumeration getAttributeNames() {
return this.cocoonRequest.getAttributeNames();
}
public String getCharacterEncoding() {
return this.cocoonRequest.getCharacterEncoding();
}
public int getContentLength() {
return this.cocoonRequest.getContentLength();
}
public String getContentType() {
return this.cocoonRequest.getContentType();
}
public ServletInputStream getInputStream() throws IOException {
throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getInputStream().");
}
public Locale getLocale() {
return this.cocoonRequest.getLocale();
}
public Enumeration getLocales() {
return this.cocoonRequest.getLocales();
}
public String getParameter(String arg0) {
return this.cocoonRequest.getParameter(arg0);
}
public Map getParameterMap() {
throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getParameterMap().");
}
public Enumeration getParameterNames() {
return this.cocoonRequest.getParameterNames();
}
public String[] getParameterValues(String arg0) {
return this.cocoonRequest.getParameterValues(arg0);
}
public String getProtocol() {
return this.cocoonRequest.getProtocol();
}
public BufferedReader getReader() throws IOException {
throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getReader().");
}
public String getRealPath(String arg0) {
throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getRealPath().");
}
public String getRemoteAddr() {
return this.cocoonRequest.getRemoteAddr();
}
public String getRemoteHost() {
return this.cocoonRequest.getRemoteHost();
}
public RequestDispatcher getRequestDispatcher(String arg0) {
throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getRequestDispatcher(arg0).");
}
public String getScheme() {
return this.cocoonRequest.getScheme();
}
public String getServerName() {
return this.cocoonRequest.getServerName();
}
public int getServerPort() {
return this.cocoonRequest.getServerPort();
}
public boolean isSecure() {
return this.cocoonRequest.isSecure();
}
public void removeAttribute(String arg0) {
this.cocoonRequest.removeAttribute(arg0);
}
public void setAttribute(String arg0, Object arg1) {
this.cocoonRequest.setAttribute(arg0, arg1);
}
public void setCharacterEncoding(String arg0)
throws UnsupportedEncodingException {
this.cocoonRequest.setCharacterEncoding(arg0);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.ResourceNotFoundException;
import org.apache.cocoon.generation.AbstractGenerator;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.crosswalk.CrosswalkException;
import org.dspace.content.crosswalk.DisseminationCrosswalk;
import org.dspace.core.Context;
import org.dspace.core.PluginManager;
import org.dspace.handle.HandleManager;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.SAXOutputter;
import org.xml.sax.SAXException;
/**
* Generate an ORE aggregation of a DSpace Item. The object to be rendered should be an item identified by pasing
* in one of the two parameters: handle or internal. The fragment parameter determines the encoding format for
* the aggregation; only Atom is supported at this time.
* @author Alexey Maslov
*/
public class DSpaceOREGenerator extends AbstractGenerator
{
/**
* Generate the ORE Aggregation.
*/
public void generate() throws IOException, SAXException,
ProcessingException {
try {
// Grab the context.
Context context = ContextUtil.obtainContext(objectModel);
Item item = getItem(context);
if (item == null)
{
throw new ResourceNotFoundException("Unable to locate object.");
}
// Instantiate and execute the ORE plugin
SAXOutputter out = new SAXOutputter(contentHandler);
DisseminationCrosswalk xwalk = (DisseminationCrosswalk)PluginManager.getNamedPlugin(DisseminationCrosswalk.class,"ore");
Element ore = xwalk.disseminateElement(item);
out.output(ore);
/* Generate the METS document
contentHandler.startDocument();
adapter.renderMETS(contentHandler,lexicalHandler);
contentHandler.endDocument();*/
} catch (JDOMException je) {
throw new ProcessingException(je);
} catch (AuthorizeException ae) {
throw new ProcessingException(ae);
} catch (CrosswalkException ce) {
throw new ProcessingException(ce);
} catch (SQLException sqle) {
throw new ProcessingException(sqle);
}
}
private Item getItem(Context context) throws SQLException, CrosswalkException
{
// Determine the correct adatper to use for this item
String handle = parameters.getParameter("handle",null);
String internal = parameters.getParameter("internal",null);
if (handle != null)
{
// Specified using a regular handle.
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
// Handles can be either items or containers.
if (dso instanceof Item)
{
return (Item) dso;
}
else
{
throw new CrosswalkException("ORE dissemination only available for DSpace Items.");
}
}
else if (internal != null)
{
// Internal identifier, format: "type:id".
String[] parts = internal.split(":");
if (parts.length == 2)
{
String type = parts[0];
int id = Integer.valueOf(parts[1]);
if ("item".equals(type))
{
return Item.find(context,id);
}
else
{
throw new CrosswalkException("ORE dissemination only available for DSpace Items.");
}
}
}
return null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.generation.AbstractGenerator;
import org.dspace.content.authority.Choices;
import org.dspace.content.authority.ChoiceAuthorityManager;
import org.dspace.content.authority.ChoicesXMLGenerator;
import org.xml.sax.SAXException;
import org.apache.log4j.Logger;
/**
* Generate XML description of Choice values to be used by
* AJAX UI client.
*
* @author Larry Stone
*/
public class AJAXMenuGenerator extends AbstractGenerator
{
private static Logger log = Logger.getLogger(AJAXMenuGenerator.class);
/**
* Generate the AJAX response Document.
*
* Looks for request paraemters:
* field - MD field key, i.e. form key, REQUIRED.
* start - index to start from, default 0.
* limit - max number of lines, default 1000.
* format - opt. result XML/XHTML format: "select", "ul", "xml"(default)
* locale - explicit locale, pass to choice plugin
*/
public void generate()
throws IOException, SAXException, ProcessingException
{
int start = 0;
int limit = 1000;
int collection = -1;
String format = parameters.getParameter("format",null);
String field = parameters.getParameter("field",null);
String sstart = parameters.getParameter("start",null);
if (sstart != null && sstart.length() > 0)
{
start = Integer.parseInt(sstart);
}
String slimit = parameters.getParameter("limit",null);
if (slimit != null && slimit.length() > 0)
{
limit = Integer.parseInt(slimit);
}
String scoll = parameters.getParameter("collection",null);
if (scoll != null && scoll.length() > 0)
{
collection = Integer.parseInt(scoll);
}
String query = parameters.getParameter("query",null);
// localization
String locale = parameters.getParameter("locale",null);
log.debug("AJAX menu generator: field="+field+", query="+query+", start="+sstart+", limit="+slimit+", format="+format+", field="+field+", query="+query+", start="+sstart+", limit="+slimit+", format="+format+", locale = "+locale);
Choices result =
ChoiceAuthorityManager.getManager().getMatches(field, query, collection, start, limit, locale);
log.debug("Result count = "+result.values.length+", default="+result.defaultSelected);
ChoicesXMLGenerator.generate(result, format, contentHandler);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.transformation.AbstractTransformer;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.ext.Attributes2Impl;
/**
* Filter out an unwanted namespace from the pipeline. Any elements or attributes
* which use this namespaces will be removed from pipeline.
*
* <map:transformer type="NamespaceFilterTransformer" src="http://apache.org/cocoon/i18n/2.1"/>
*
* @author Scott Phillips
*/
public class NamespaceFilterTransformer extends AbstractTransformer implements CacheableProcessingComponent
{
/** The namespace to be filtered out of the document */
private String filterNamespace;
/** The prefixes used to identified the namespace */
private Stack<String> filterPrefixes = new Stack<String>();
/**
* Return the cache key
*/
public Serializable getKey() {
if (filterNamespace != null)
{
return filterNamespace;
}
else
{
return "1";
}
}
/**
* This cache never invalidates, always return a validating cache.
*/
public SourceValidity getValidity() {
// Always returned cached;
return NOPValidity.SHARED_INSTANCE;
}
/**
* Setup the processing instruction transformer. The only parameter that
* matters in the src parameter which should be the path to an XSL
* stylesheet to be applied by the clients browser.
*
* Setup the namespace filter by getting a list of namespaces to be filtered
* from the pipeline.
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
filterNamespace = src;
filterPrefixes.clear();
}
/** Should this namespace be filtered out of the document? */
private boolean filter(String test)
{
return (filterNamespace != null && filterNamespace.equals(test));
}
/** Should this prefix be filtered out of the document? */
private boolean filterPrefix(String test)
{
if (filterPrefixes.isEmpty())
{
return false;
}
String peek = filterPrefixes.peek();
return (peek != null && peek.equals(test));
}
/**
* Begin the scope of a prefix-URI Namespace mapping.
*
* @param prefix The Namespace prefix being declared.
* @param uri The Namespace URI the prefix is mapped to.
*/
public void startPrefixMapping(String prefix, String uri) throws SAXException
{
if (filter(uri))
{
filterPrefixes.push(prefix);
}
else
{
contentHandler.startPrefixMapping(prefix, uri);
}
}
/**
* End the scope of a prefix-URI mapping.
*
* @param prefix The prefix that was being mapping.
*/
public void endPrefixMapping(String prefix) throws SAXException
{
if (filterPrefix(prefix))
{
filterPrefixes.pop();
}
else
{
contentHandler.endPrefixMapping(prefix);
}
}
/**
* Receive notification of the beginning of an element.
*/
public void startElement(String uri, String loc, String raw, Attributes a) throws SAXException
{
// Reset the namespace context flag.
if (!filter(uri))
{
List<Integer> filterAttributeIndexs = new ArrayList<Integer>();
for (int i = 0; i < a.getLength(); i++)
{
if (filter(a.getURI(i)))
{
// Add it to the list of filtered indexes.
filterAttributeIndexs.add(i);
}
}
// Check if any of the attributes are to be filtered if so, filter them out.
if (!filterAttributeIndexs.isEmpty())
{
// New set of attributes.
Attributes2Impl a2 = new Attributes2Impl();
for (int i = 0; i < a.getLength(); i++)
{
if (filterAttributeIndexs.contains(i))
{
// This index is to be filtered.
continue;
}
String a_uri = a.getURI(i);
String a_localName = a.getLocalName(i);
String a_qName = a.getQName(i);
String a_type = a.getType(i);
String a_value = a.getValue(i);
// Add the new attribute
a2.addAttribute(a_uri, a_localName, a_qName, a_type, a_value);
}
// Use our new filtered attributes.
a = a2;
}
contentHandler.startElement(uri, loc, raw, a);
}
}
/**
* Receive notification of the end of an element.
*/
public void endElement(String uri, String loc, String raw) throws SAXException
{
if (!filter(uri))
{
contentHandler.endElement(uri, loc, raw);
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.transformation.AbstractTransformer;
import org.xml.sax.SAXException;
public class StylesheetInstructionTransformer extends AbstractTransformer
{
/** The location of the XSL stylesheet relative to the application */
private String stylesheet;
/**
* Setup the processing instruction transformer. The only parameter that
* matters in the src parameter which should be the path to an XSL
* stylesheet to be applied by the clients browser.
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String contextPath = request.getContextPath();
this.stylesheet = contextPath + src;
}
/**
* Receive notification of the beginning of a document.
*/
public void startDocument() throws SAXException
{
super.startDocument();
// <?xml-stylesheet type="text/xsl" href="<stylesheet>"?>
super.processingInstruction("xml-stylesheet",
"type=\"text/xsl\" href=\"" + stylesheet + "\"");
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.components.flow.FlowHelper;
import org.apache.cocoon.components.flow.WebContinuation;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.dspace.app.xmlui.objectmanager.DSpaceObjectManager;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.AbstractWingTransformer;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.UserMeta;
import org.dspace.app.xmlui.wing.ObjectManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.xml.sax.SAXException;
/**
* @author Scott Phillips
*/
public abstract class AbstractDSpaceTransformer extends AbstractWingTransformer
implements DSpaceTransformer
{
private static final String NAME_TRIM = "org.dspace.app.xmlui.";
protected Map objectModel;
protected Context context;
protected String contextPath;
protected String servletPath;
protected String sitemapURI;
protected String url;
protected Parameters parameters;
protected EPerson eperson;
protected WebContinuation knot;
// Only access this through getObjectManager, so that we don't have to create one if we don't want too.
private ObjectManager objectManager;
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
this.objectModel = objectModel;
this.parameters = parameters;
try
{
this.context = ContextUtil.obtainContext(objectModel);
this.eperson = context.getCurrentUser();
Request request = ObjectModelHelper.getRequest(objectModel);
this.contextPath = request.getContextPath();
if (contextPath == null)
{
contextPath = "/";
}
this.servletPath = request.getServletPath();
this.sitemapURI = request.getSitemapURI();
this.knot = FlowHelper.getWebContinuation(objectModel);
}
catch (SQLException sqle)
{
handleException(sqle);
}
// Initialize the Wing framework.
try
{
this.setupWing();
}
catch (WingException we)
{
throw new ProcessingException(we);
}
}
protected void handleException(Exception e) throws SAXException
{
throw new SAXException(
"An error was encountered while processing the '"+this.getComponentName()+"' Wing based component: "
+ this.getClass().getName(), e);
}
/** What to add at the end of the body */
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Do nothing
}
/** What to add to the options list */
public void addOptions(Options options) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Do nothing
}
/** What user metadata to add to the document */
public void addUserMeta(UserMeta userMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
// Do nothing
}
/** What page metadata to add to the document */
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
// Do nothing
}
public ObjectManager getObjectManager()
{
if (this.objectManager == null)
{
this.objectManager = new DSpaceObjectManager();
}
return this.objectManager;
}
/** What is a unique name for this component? */
public String getComponentName()
{
String name = this.getClass().getName();
if (name.startsWith(NAME_TRIM))
{
name = name.substring(NAME_TRIM.length());
}
return name;
}
/**
* Encode the given string for URL transmission.
*
* @param unencodedString
* The unencoded string.
* @return The encoded string
*/
public static String encodeForURL(String unencodedString) throws UIException
{
if (unencodedString == null)
{
return "";
}
try
{
return URLEncoder.encode(unencodedString,Constants.DEFAULT_ENCODING);
}
catch (UnsupportedEncodingException uee)
{
throw new UIException(uee);
}
}
/**
* Decode the given string from URL transmission.
*
* @param encodedString
* The encoded string.
* @return The unencoded string
*/
public static String decodeFromURL(String encodedString) throws UIException
{
if (encodedString == null)
{
return null;
}
try
{
// Percent(%) is a special character, and must first be escaped as %25
if (encodedString.contains("%"))
{
encodedString = encodedString.replace("%", "%25");
}
return URLDecoder.decode(encodedString, Constants.DEFAULT_ENCODING);
}
catch (UnsupportedEncodingException uee)
{
throw new UIException(uee);
}
}
/**
* Generate a URL for the given base URL with the given parameters. This is
* a convenance method to make it easier to generate URL refrences with
* parameters.
*
* Example
* Map<String,String> parameters = new Map<String,String>();
* parameters.put("arg1","value1");
* parameters.put("arg2","value2");
* parameters.put("arg3","value3");
* String url = genrateURL("/my/url",parameters);
*
* would result in the string:
* url == "/my/url?arg1=value1&arg2=value2&arg3=value3"
*
* @param baseURL The baseURL without any parameters.
* @param parameters The parameters to be encoded on in the URL.
* @return The parameterized Post URL.
*/
public static String generateURL(String baseURL,
Map<String, String> parameters)
{
StringBuilder urlBuffer = new StringBuilder();
for (Map.Entry<String, String> param : parameters.entrySet())
{
if (urlBuffer.length() == 0)
{
urlBuffer.append(baseURL).append('?');
}
else
{
urlBuffer.append( '&');
}
urlBuffer.append(param.getKey()).append("=").append(param.getValue());
}
return urlBuffer.length() > 0 ? urlBuffer.toString() : baseURL;
}
/**
* Recyle
*/
public void recycle() {
this.objectModel = null;
this.context = null;
this.contextPath = null;
this.servletPath = null;
this.sitemapURI = null;
this.url=null;
this.parameters=null;
this.eperson=null;
this.knot=null;
this.objectManager=null;
super.recycle();
}
/**
* Dispose
*/
public void dispose() {
this.objectModel = null;
this.context = null;
this.contextPath = null;
this.servletPath = null;
this.sitemapURI = null;
this.url=null;
this.parameters=null;
this.eperson=null;
this.knot=null;
this.objectManager=null;
super.dispose();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.cocoon;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.matching.Matcher;
import org.apache.cocoon.sitemap.PatternException;
import org.dspace.app.xmlui.configuration.XMLUIConfiguration;
import org.dspace.app.xmlui.configuration.Theme;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
/**
* This class determines the correct Theme to apply to the URL. This is
* determined by the Theme rules defined in the xmlui.xml configuration file.
* Each rule is evaluated in order and the first rule to match is the selected
* Theme.
*
* Once the Theme has been selected the following sitemap parameters are
* provided: {themeName} is a unique name for the Theme, and {theme} is the
* theme's path.
*
* @author Scott Phillips
*/
public class ThemeMatcher extends AbstractLogEnabled implements Matcher {
/**
* @param src
* name of sitemap parameter to find (ignored)
* @param objectModel
* environment passed through via cocoon
* @param parameters
* parameters passed to this matcher in the sitemap
* @return null or map containing value of sitemap parameter 'src'
*/
public Map match(String src, Map objectModel, Parameters parameters)
throws PatternException {
try {
Request request = ObjectModelHelper.getRequest(objectModel);
String uri = request.getSitemapURI();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
// Allow the user to override the theme configuration
if (ConfigurationManager.getBooleanProperty("xmlui.theme.allowoverrides",false))
{
String themePathOverride = request.getParameter("themepath");
if (themePathOverride != null && themePathOverride.length() > 0)
{
// Allowing the user to specify the theme path is a security risk because it
// allows the user to direct which sitemap is executed next. An attacker could
// use this in combination with another attack execute code on the server.
// Ultimately this option should not be turned on in a production system and
// only used in development. However lets do some simple sanity checks to
// protect us a little even when under development.
// Allow: allow all letters and numbers plus periods (but not consecutive),
// dashes, underscores, and forward slashes
if (!themePathOverride.matches("^[a-zA-V0-9][a-zA-Z0-9/_\\-]*/?$")) {
throw new IllegalArgumentException("The user specified theme path, \""+themePathOverride+"\", may be " +
"an exploit attempt. To use this feature please limit your theme paths to only letters " +
"(a-Z), numbers(0-9), dashes(-), underscores (_), and trailing forward slashes (/).");
}
// The user is selecting to override a theme, ignore any set
// rules to apply and use the one specified.
String themeNameOverride = request.getParameter("themename");
String themeIdOverride = request.getParameter("themeid");
if (themeNameOverride == null || themeNameOverride.length() == 0)
{
themeNameOverride = "User specified theme";
}
getLogger().debug("User as specified to override theme selection with theme "+
"(name=\""+themeNameOverride+"\", path=\""+themePathOverride+"\", id=\""+themeIdOverride+"\")");
Map<String, String> result = new HashMap<String, String>();
result.put("themeName", themeNameOverride);
result.put("theme", themePathOverride);
result.put("themeID", themeIdOverride);
return result;
}
}
List<Theme> rules = XMLUIConfiguration.getThemeRules();
getLogger().debug("Checking if URL=" + uri + " matches any theme rules.");
for (Theme rule : rules) {
getLogger().debug("rule=" + rule.getName());
if (!(rule.hasRegex() || rule.hasHandle()))
{
// Skip any rule with out a pattern or handle
continue;
}
getLogger().debug("checking for patterns");
if (rule.hasRegex()) {
// If the rule has a pattern insure that the URL matches it.
Pattern pattern = rule.getPattern();
if (!pattern.matcher(uri).find())
{
continue;
}
}
getLogger().debug("checking for handles");
if (rule.hasHandle() && !HandleUtil.inheritsFrom(dso, rule.getHandle()))
{
continue;
}
getLogger().debug("rule selected!!");
Map<String, String> result = new HashMap<String, String>();
result.put("themeName", rule.getName());
result.put("theme", rule.getPath());
result.put("themeID", rule.getId());
request.getSession().setAttribute("themeName", rule.getName());
request.getSession().setAttribute("theme", rule.getPath());
request.getSession().setAttribute("themeID", rule.getId());
return result;
}
} catch (SQLException sqle) {
throw new PatternException(sqle);
}
// No themes matched.
return null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing;
/**
* A class representing the framework's context, what component is generationg
* content, where should we log. It's basicaly a grab bag for framework wide
* communication, if all elements need to know about something then it should go
* here.
*
* @author Scott Phillips
*/
import org.apache.commons.logging.Log;
public class WingContext
{
/** The nameing divider */
public static final char DIVIDER = '.';
/**
* What is the component name for this transformer, this is used to generate
* unique ids.
*/
private String componentName;
/** Cocoon logger for debugging Wing elements */
private Log logger;
/**
* The repository specefic object manager.
*/
private ObjectManager objectManager;
/**
* Set the current transformer's name
*
* @param componentName
* the current transformer's name.
*/
public void setComponentName(String componentName)
{
this.componentName = componentName;
}
/**
* Return the current transformer's name.
*
* @return
*/
public String getComponentName()
{
return this.componentName;
}
/**
* Return the cocoon logger
*
* @return the current logger
*/
public Log getLogger()
{
return this.logger;
}
/**
* Set the cocoon logger
*
* @param log
* A new logger.
*/
public void setLogger(Log log)
{
this.logger = log;
}
/**
* Generate a unique id based upon the locally unique name and the
* application.
*
* The format of the unique id typically is:
*
* <componentName> dot <application> dot <unique name>
*
* typically the componentName is the Java class path of the Wing component.
*
* @param application
* The application of this element, typically this is the element
* type that is being identified. Such as p, div, table, field,
* etc...
* @param name
* A locally unique name that distinguished this element from
* among its siblings.
* @return A globally unique identifier.
*/
public String generateID(String application, String name)
{
return combine(componentName, application, name);
}
/**
* Generate a unique id with a sub name. Like the other form of generateID
* this will append another sub-name. This is typically used for when
* duplicate names are used but further identification is needed for
* globally unique names.
*
* @param application
* The application of this element, typically this is the element
* type that is being identified. Such as p, div, table, field,
* etc...
* @param name
* A locally unique name that distinguished this element from
* among its siblings.
* @param subName
* An additional name to the original name to further identify it
* in cases when just the name alone does not accomplish this.
* @return
*/
public String generateID(String application, String name, String subName)
{
return combine(componentName, application, name, subName);
}
/**
* Generate a specialized name based on the callers name. This is typically
* used in situations where two namespaces are being merged together so that
* each namespace is prepended with the current scope's name.
*
* @param name
* A locally unique name that distinguished this element from
* among it's siblings.
*/
public String generateName(String name)
{
return combine(componentName, name);
}
/**
* Simple utility function to join the parts into one string separated by a
* DOT.
*
* @param parts
* The input parts.
* @return The combined string.
*/
private String combine(String... parts)
{
StringBuilder combine = new StringBuilder();
boolean skipDivider = true;
for (String part : parts)
{
if (part == null)
{
skipDivider = true;
continue;
}
if (skipDivider)
{
skipDivider = false;
}
else
{
combine.append(DIVIDER);
}
combine.append(part);
}
return combine.toString();
}
/**
* Set the objectManager which is repsonsible for managing the object store in the DRI document.
*
* @param objectManager The new objectManager
*/
public void setObjectManager(ObjectManager objectManager) {
this.objectManager = objectManager;
}
/**
* Get the objectManager.
*
* @return Return the objectManager associated with this component.
*/
public ObjectManager getObjectManager() {
return this.objectManager;
}
/**
* Check that the context is valid, and able to be used. An error should be
* thrown if it is not in a valid sate.
*/
public void checkValidity() throws WingException
{
// FIXME: There use to be invalid states for wing contexts however they
// were removed. I think in the future however additions could require
// this check so I do not want to remove it just yet.
}
/**
* Recycle this context for future use by another wing element
*/
public void dispose()
{
this.componentName = null;
this.objectManager = null;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing;
import java.io.Serializable;
/**
* This simple class just provides the Namespace datatype. It stores a URI that
* is publicly accessible. The actually definitions of namespaces is found in
* WingConstants.java.
*
* @author Scott Phillips
*/
public class Namespace implements Serializable
{
/** The URI for this namespace */
public final String URI;
/**
* Construct a new Namespace for the given URI.
*
* @param URI
* The namespaces URI
*/
public Namespace(String URI)
{
this.URI = URI;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing;
import java.util.HashMap;
/**
* A simplified Wing version of an AttributeMap. If a namespace is set it is
* applied to all attributes in the Map. This is typically not what one would
* expect but it makes the syntax easier for Wing Elements. Either all the
* attributes come from one namespace or the other, but never two at the same
* time.
*
* @author Scott Phillips
*/
public class AttributeMap extends HashMap<String, String>
{
/** Just so there are no compile warnings */
private static final long serialVersionUID = 1;
/** The namespace of ALL the attributes contained within this map */
private Namespace namespace;
/**
* Set the namespace for all attributes contained within this map.
*
* @param namespace
* The new namespace.
*/
public void setNamespace(Namespace namespace)
{
this.namespace = namespace;
}
/**
*
* @return The namespace for all the attributes contained within this map.
*/
public Namespace getNamespace()
{
return this.namespace;
}
/**
* Another variation of the put method to convert integer values into
* strings.
*
* @param key
* The attribute's name.
* @param value
* The value of the attribute.
* @return
*/
public String put(String key, int value)
{
return this.put(key, String.valueOf(value));
}
/**
* Another variation of the put method to convert boolean values into
* strings. The values "yes" or "no" will be used in replacement of the
* boolean value.
*
* @param key
* @param value
* @return
*/
public String put(String key, boolean value)
{
return this.put(key, (value ? "yes" : "no"));
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing;
import java.util.Map;
/**
* The object manager is a class that must be implemented by each specific repository
* implementation that identifies refrenced objects. Since the DRI document includes
* refrences to external resources implementers of this class must know how objects
* are refrenced.
*
* The specefic implementation of ObjectManager that is used is determened by the
* WingComponent that is creating the refrence.
*
* @author Scott Phillips
*/
public interface ObjectManager
{
/**
* Determine if the supplied object is manageable by this implementation of
* ObjectManager. If the object is manageable then manage it, and return true.
*
* @param object
* The object to be managed.
* @return true if the object can be managed, otherwise false.
*/
public boolean manageObject(Object object) throws WingException;
/**
* Return a url refrencing the object's metadata. If this is unabvailable
* return null.
*
* @param object The object being managed.
*/
public String getObjectURL(Object object) throws WingException;
/**
* Return a descriptive, repository specfic, type for the object. If
* this is unabvailable return null.
*
* @param object The object being managed.
*/
public String getObjectType(Object object) throws WingException;
/**
* Return a unique identifier of the repository this object is contained
* in. If this is unabvailable return null.
*
* @param object The object being managed.
*/
public String getRepositoryIdentifier(Object object) throws WingException;
/**
* Return a list of all repositories managed by this manager. The
* hash should be of the form repository identifier as the key,
* and the value for each key is a metadata URL.
*/
public Map<String,String> getAllManagedRepositories() throws WingException;
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing;
import java.util.Stack;
import org.apache.cocoon.transformation.AbstractTransformer;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.UserMeta;
import org.dspace.app.xmlui.wing.element.WingDocument;
import org.dspace.app.xmlui.wing.element.WingMergeableElement;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.NamespaceSupport;
/**
* This class handles receiving SAX events and translating them into DRI events.
* These DRI events are then routed to the individual implementing components
* where they fill in and construct the DRI document. The document they
* construct is known as the feeder document, this is merged into the main
* document that was generated from the previous component in the Cocoon
* pipeline. The merge takes place in accordance with the DRI schema's rules for
* merging two DRI documents.
*
*
* @author Scott Phillips
*/
public abstract class AbstractWingTransformer extends AbstractTransformer
implements WingTransformer
{
/**
* Simple variable to indicate weather a new namespace context is needed. If
* several namespaces are declared on the same attribute then they are
* considered in the same 'context'. Each time an element is opened this
* flag is reset to true, and each time a new namespace is declared it is
* set to false. Using this information new contexts are opened
* conservatively.
*/
private boolean needNewNamespaceContext = true;
/**
* The namespace support object keeps track of registered URI prefixes. This
* is used by the WingElements so that they may attach the correctp prefix
* when assigning elements to namespaces.
*/
private NamespaceSupport namespaces;
/**
* The feeder document is the document being merged into the main,
* pre-existing document, that is the result of the previous Cocoon
* component in the pipeline.
*/
private WingDocument feederDocument;
/**
* The wing context is where the namespace support is stored along with the
* content and lexical handlers so that the wing elements can have access to
* them when they perform their toSAX() method.
*/
private WingContext wingContext;
/**
* This is a stack to the current location in the merge while it is in
* progress.
*/
private Stack<WingMergeableElement> stack;
/**
* Set up the transformer so that it can build a feeder Wing document and
* merge it into the main document
*
* FIXME: Update document: - this method must be called to initialize the
* framework. It must be called after the component's setup has been called
* and the implementing object setup.
*
*/
public void setupWing() throws WingException
{
this.wingContext = new WingContext();
this.wingContext.setLogger(this.getLogger());
this.wingContext.setComponentName(this.getComponentName());
this.wingContext.setObjectManager(this.getObjectManager());
feederDocument = this.createWingDocument(wingContext);
this.stack = new Stack<WingMergeableElement>();
}
/**
* Receive notification of the beginning of a document.
*/
public void startDocument() throws SAXException
{
needNewNamespaceContext = true;
namespaces = new NamespaceSupport();
super.startDocument();
}
/**
* Receive notification of the end of a document.
*/
public void endDocument() throws SAXException
{
wingContext.dispose();
super.endDocument();
}
/**
* Begin the scope of a prefix-URI Namespace mapping.
*
* @param prefix
* The Namespace prefix being declared.
* @param uri
* The Namespace URI the prefix is mapped to.
*/
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
if (needNewNamespaceContext)
{
namespaces.pushContext();
needNewNamespaceContext = false;
}
namespaces.declarePrefix(prefix, uri);
super.startPrefixMapping(prefix, uri);
}
/**
* End the scope of a prefix-URI mapping.
*
* @param prefix
* The prefix that was being mapping.
*/
public void endPrefixMapping(String prefix) throws SAXException
{
if (!needNewNamespaceContext)
{
namespaces.popContext();
needNewNamespaceContext = true;
}
super.endPrefixMapping(prefix);
}
/**
* Receive notification of the beginning of an element.
*
* @param namespaceURI
* The Namespace URI, or the empty string if the element has no
* Namespace URI or if Namespace processing is not being
* performed.
* @param localName
* The local name (without prefix), or the empty string if
* Namespace processing is not being performed.
* @param qName
* The raw XML 1.0 name (with prefix), or the empty string if raw
* names are not available.
* @param attributes
* The attributes attached to the element. If there are no
* attributes, it shall be an empty Attributes object.
*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes attributes) throws SAXException
{
// Reset the namespace context flag.
needNewNamespaceContext = true;
try
{
if (stack == null)
{
throw new WingException("Stack not initialized.");
}
// Deal with the stack jump start issue of having a document all
// ready on the stack.
if (stack.size() == 0)
{
if (feederDocument.mergeEqual(namespaceURI, localName, qName,
attributes))
{
attributes = feederDocument.merge(attributes);
stack.push(feederDocument);
}
else
{
throw new WingException(
"Attempting to merge DRI documents but the source document is not compatable with the feeder document.");
}
}
else if (stack.size() > 0)
{
WingMergeableElement peek = stack.peek();
WingMergeableElement child = null;
if (peek != null)
{
child = peek.mergeChild(namespaceURI, localName, qName,
attributes);
}
// Check if we should construct a new portion of the document.
if (child instanceof UserMeta)
{
// Create the UserMeta
this.addUserMeta((UserMeta) child);
}
else if (child instanceof PageMeta)
{
// Create the PageMeta
this.addPageMeta((PageMeta) child);
}
else if (child instanceof Body)
{
// Create the Body
this.addBody((Body) child);
}
else if (child instanceof Options)
{
// Create the Options
this.addOptions((Options) child);
}
// Update any attributes of this merged element.
if (child != null)
{
attributes = child.merge(attributes);
}
stack.push(child);
}
// Send off the event with nothing modified except for the
// attributes (possibly)
super.startElement(namespaceURI, localName, qName, attributes);
}
catch (SAXException saxe)
{
throw saxe;
}
catch (Exception e)
{
handleException(e);
}
}
/**
* Receive notification of the end of an element.
*
* @param namespaceURI
* The Namespace URI, or the empty string if the element has no
* Namespace URI or if Namespace processing is not being
* performed.
* @param localName
* The local name (without prefix), or the empty string if
* Namespace processing is not being performed.
* @param qName
* The raw XML 1.0 name (with prefix), or the empty string if raw
* names are not available.
*/
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException
{
try
{
if (stack.size() > 0)
{
WingMergeableElement poped = stack.pop();
if (poped != null)
{
poped.toSAX(contentHandler, lexicalHandler, namespaces);
poped.dispose();
}
}
// Send the event on unmodified
super.endElement(namespaceURI, localName, qName);
}
catch (SAXException saxe)
{
throw saxe;
}
catch (Exception e)
{
handleException(e);
}
}
/**
* Handle exceptions that occurred during the document's creation. When
* errors occur a SAX event is being processed it will be sent through this
* method. This allows implementing classes to override this method for
* specific error handling hooks.
*
* @param e
* The thrown exception
*/
protected void handleException(Exception e) throws SAXException
{
throw new SAXException(
"An error was incountered while processing the Wing based component: "
+ this.getClass().getName(), e);
}
/**
* Construct a new WingDocument.
*
* @param wingContext
* The current wing context this transformer is operating under.
*/
protected WingDocument createWingDocument(WingContext wingContext)
throws WingException
{
return new WingDocument(wingContext);
}
/** Abstract implementations of WingTransformer */
public void addBody(Body body) throws Exception
{
// Do nothing
}
public void addOptions(Options options) throws Exception
{
// do nothing
}
public void addUserMeta(UserMeta userMeta) throws Exception
{
// Do nothing
}
public void addPageMeta(PageMeta pageMeta) throws Exception
{
// Do nothing
}
/**
* Return the ObjectManager associated with this component. If no
* objectManager needed then return null.
*/
public ObjectManager getObjectManager()
{
return null;
}
/**
* Return the name of this component. Typicaly the name is just
* the class name of the component.
*/
public String getComponentName()
{
return this.getClass().getName();
}
/**
* Return the default i18n message catalogue that should be used
* when no others are specified.
*/
public static String getDefaultMessageCatalogue()
{
return "default";
}
/**
* This is a short cut method for creating a new message object, this
* allows them to be created with one simple method call that uses
* the default catalogue.
*
* @param key
* The catalogue key used to look up a message.
* @return A new message object.
*/
public static Message message(String key)
{
return message(getDefaultMessageCatalogue(), key);
}
/**
* This is a short cut method for creating a new message object. This
* version allows the callie to specify a particular catalogue overriding
* the default catalogue supplied.
*
* @param catalogue
* The catalogue where translations will be located.
* @param key
* The catalogue key used to look up a translation within the
* catalogue.
* @return A new message object.
*/
public static Message message(String catalogue, String key)
{
return new Message(catalogue, key);
}
/**
* Recyle
*/
public void recycle()
{
this.namespaces = null;
this.feederDocument = null;
this.wingContext=null;
this.stack =null;
super.recycle();
}
/**
* Dispose
*/
public void dispose() {
this.namespaces = null;
this.feederDocument = null;
this.wingContext=null;
this.stack =null;
//super.dispose(); super dosn't dispose.
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.components.source.SourceUtil;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.transformation.AbstractTransformer;
import org.apache.cocoon.xml.dom.DOMStreamer;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Meta;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.UserMeta;
import org.dspace.app.xmlui.wing.element.WingDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* The Include class reads an DRI XML file from and merges it into the existing
* document stream using the Wing framework.
*
* If the file is not present at the source provided a blank document is merged,
* allowing the pipeline to continue excecution. This is also logged as a warning.
*
* @author Scott Phillips
*/
public class Include extends AbstractTransformer implements CacheableProcessingComponent
{
/**
* A data structure describing what elements are to be merged and upon what
* key. The first map's key is the name of a mergeable element's name while
* the value is a list of all attributes that the element must match on to
* be considered the same element.
*/
private static final Map<String, String[]> mergeableMap;
/** Construct the mergeableMap from constant data */
static
{
Map<String, String[]> buildMap = new HashMap<String, String[]>();
buildMap.put(WingDocument.E_DOCUMENT, null);
buildMap.put(Meta.E_META, null);
buildMap.put(UserMeta.E_USER_META, null);
buildMap.put(PageMeta.E_PAGE_META, null);
buildMap.put("artifactmeta", null);
buildMap.put("repositoryMeta", null);
buildMap.put("community",
new String[] { "repositoryIdentifier" });
buildMap.put("collection",
new String[] { "repositoryIdentifier" });
buildMap.put(Body.E_BODY, null);
buildMap.put(Options.E_OPTIONS, null);
buildMap.put(org.dspace.app.xmlui.wing.element.List.E_LIST,
new String[] { org.dspace.app.xmlui.wing.element.List.A_NAME });
mergeableMap = buildMap;
}
/** The source document */
private Document w3cDocument;
/** Helper class to stream the w3c DOM into SAX events */
private DOMStreamer streamer;
/** Stack of our current location within the document */
private Stack<Element> stack;
/** The Cocoon source for the included XML document */
private Source source;
/** The src attribute to the cocoon source */
private String src;
/**
* Read in the given src path into an internal DOM for later processing when
* needed.
*
* @param resolver
* Resolver for cocoon pipelines.
* @param objectModel
* The pipelines's object model.
* @param src
* The source parameter
* @param parameters
* The transformer's parameters.
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
this.src = src;
this.source = resolver.resolveURI(src);
}
/**
* Generate the unique key.
* This key must be unique inside the space of this component.
*
* @return The generated key hashes the src
*/
public Serializable getKey()
{
return this.src;
}
/**
* Generate the validity object.
*
* @return The generated validity object or <code>null</code> if the
* component is currently not cacheable.
*/
public SourceValidity getValidity()
{
if (source != null)
{
if (source.exists())
// The file exists so return it's validity.
{
return source.getValidity();
}
else
{
// The file does not exist so we will just return always valid. This
// will have an nastly side effect that if a file is removed from a
// running system the cache will remain valid. However if the other
// option is to always invalidate the cache if the file is not present
// which is not desirable either.
return NOPValidity.SHARED_INSTANCE;
}
}
else
{
return null;
}
}
/**
* Receive notification of the beginning of a document.
*/
public void startDocument() throws SAXException
{
try
{
w3cDocument = SourceUtil.toDOM(source);
}
catch (Exception e)
{
// since we were unable to parce an XML document from the source given we will
// simply log the error as a warning and create a null stack
getLogger().warn("File to be included from " + source.toString() +" not found.");
stack = null;
super.startDocument();
return;
}
stack = new Stack<Element>();
streamer = new DOMStreamer(contentHandler, lexicalHandler);
super.startDocument();
}
/**
* Receive notification of the end of a document.
*/
public void endDocument() throws SAXException
{
stack = null;
super.endDocument();
}
/**
* Receive notification of the beginning of an element.
*
* @param uri
* The Namespace URI, or the empty string if the element has no
* Namespace URI or if Namespace processing is not being
* performed.
* @param localName
* The local name (without prefix), or the empty string if
* Namespace processing is not being performed.
* @param qName
* The raw XML 1.0 name (with prefix), or the empty string if raw
* names are not available.
* @param attributes
* The attributes attached to the element. If there are no
* attributes, it shall be an empty Attributes object.
*/
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
//getLogger().debug("startElement: " + localName);
if(stack == null){
// do nothing fall thru to the call to super.startElement
// this means that the document to be read was not parsable
// or not found in startDocument()
}
else if (stack.size() == 0)
{
stack.push(w3cDocument.getDocumentElement());
}
else
{
Element peek = stack.peek();
Element foundChild = null;
for (Element child : getElementList(peek))
{
if (isEqual(child, uri, localName, qName, attributes))
{
foundChild = child;
}
}
if (foundChild != null)
{
peek.removeChild(foundChild);
}
stack.push(foundChild);
}
super.startElement(uri, localName, qName, attributes);
}
/**
* Receive notification of the end of an element.
*
* @param uri
* The Namespace URI, or the empty string if the element has no
* Namespace URI or if Namespace processing is not being
* performed.
* @param localName
* The local name (without prefix), or the empty string if
* Namespace processing is not being performed.
* @param qName
* The raw XML 1.0 name (with prefix), or the empty string if raw
* names are not available.
*/
public void endElement(String uri, String localName, String qName)
throws SAXException
{
//getLogger().debug("endElement: " + localName);
// if the stack is null do nothing fall thru to the call to
// super.endElement
// this means that the document to be read was not parsable
// or not found in startDocument()
if(stack!=null){
Element poped = stack.pop();
if (poped != null)
{
//getLogger().debug("startElement: streaming");
for (Node node : getNodeList(poped))
{
streamer.stream(node);
}
}
}
super.endElement(uri, localName, qName);
}
/**
* Receive notification of character data.
*
* @param c
* The characters from the XML document.
* @param start
* The start position in the array.
* @param len
* The number of characters to read from the array.
*/
public void characters(char c[], int start, int len) throws SAXException
{
super.characters(c, start, len);
}
/**
* Determine if the given SAX event is the same as the given w3c DOM
* element. If so then return true, otherwise false.
*
* @param child
* W3C DOM element to compare with the SAX event.
* @param uri
* The namespace URI of the SAX event.
* @param localName
* The localName of the SAX event.
* @param qName
* The qualified name of the SAX event.
* @param attributes
* The attributes of the SAX event.
* @return if equal.
*/
private boolean isEqual(Element child, String uri, String localName,
String qName, Attributes attributes)
{
if (child == null)
{
return false;
}
if (uri != null && !uri.equals(child.getNamespaceURI()))
{
return false;
}
if (localName != null && !localName.equals(child.getLocalName()))
{
return false;
}
if (!mergeableMap.containsKey(localName))
{
return false;
}
String[] attributeIdentities = mergeableMap.get(localName);
if (attributeIdentities != null)
{
for (String attributeIdentity : attributeIdentities)
{
String testIdentity = attributes.getValue(attributeIdentity);
String childIdentity = child.getAttribute(attributeIdentity);
if (childIdentity != null && childIdentity.equals(testIdentity))
{
continue;
}
if (childIdentity == null && testIdentity == null)
{
continue;
}
return false;
}
}
return true;
}
/**
* DOM Helper method - Get a list of all child elements.
*
* @param element
* The parent element
* @return a list of all child elements.
*/
private static List<Element> getElementList(Element element)
{
if (element == null)
{
return new ArrayList<Element>();
}
NodeList nodeList = element.getChildNodes();
List<Element> resultList = new ArrayList<Element>();
for (int i = 0; i < nodeList.getLength(); i++)
{
if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE)
{
resultList.add((Element) nodeList.item(i));
}
}
return resultList;
}
/**
* DOM Helper method - Get a list of all child nodes.
*
* @param element
* The parent element
* @return a list of all child nodes.
*/
private static List<Node> getNodeList(Element element)
{
if (element == null)
{
return new ArrayList<Node>();
}
NodeList nodeList = element.getChildNodes();
List<Node> resultList = new ArrayList<Node>();
for (int i = 0; i < nodeList.getLength(); i++)
{
resultList.add((Node) nodeList.item(i));
}
return resultList;
}
/**
* Recycle
*/
public void recycle()
{
this.w3cDocument = null;
this.streamer = null;
this.stack = null;
this.source = null;
super.recycle();
}
} | Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import java.text.DateFormat;
import java.util.Date;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingConstants;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
* This class represents data, by data we mean the translated and untranslated
* characters in between XML elements.
*
* When data needs to be translated it is enclosed inside the cocoon i18n schema
* while untranslated data is enclosed inside nothing.
*
* @author Scott Phillips
*/
public class Data extends AbstractWingElement
{
/** The name of the text element */
public static final String E_TEXT = "text";
/** The name of the translate element */
public static final String E_TRANSLATE = "translate";
/** The name of the param element */
public static final String E_PARAM = "param";
/** The name of the catalogue attribute (used inside text or i18n message) */
public static final String A_CATALOGUE = "catalogue";
/** The name of the type attribute (used inside params) */
public static final String A_TYPE = "type";
/** The name of the value attribute (used inside params) */
public static final String A_VALUE = "value";
/** The date parameter type */
private static final String TYPE_DATE = "date";
/** The number parameter type */
private static final String TYPE_NUMBER = "number";
/** Translated data key. */
private final Message message;
/** Untranslated data */
private final String characters;
/**
* Construct a new data element using translated content.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
* @param message
* (Required) translatable data
* @throws WingException
*/
protected Data(WingContext context, Message message)
throws WingException
{
super(context);
this.message = message;
this.characters = null;
}
/**
* Construct a new data element with untranslated content.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
* @param characters
* (Required) Untranslated character data.
* @throws WingException
*/
protected Data(WingContext context, String characters) throws WingException
{
super(context);
this.message = null;
this.characters = characters;
}
/**
* Translate this element into SAX
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces)throws SAXException
{
if (this.characters != null)
{
sendCharacters(contentHandler, this.characters);
}
else if (this.message != null)
{
String catalogue = message.getCatalogue();
Object[] dictionaryParameters = message.getDictionaryParameters();
if (dictionaryParameters == null
|| dictionaryParameters.length == 0)
{
// No parameters, we can use the simple method
// <i18n:text> Text to be translated </i18n:text>
AttributeMap attributes = new AttributeMap();
attributes.setNamespace(WingConstants.I18N);
attributes.put(A_CATALOGUE, catalogue);
startElement(contentHandler, namespaces, WingConstants.I18N,
E_TEXT, attributes);
sendCharacters(contentHandler, message.getKey());
endElement(contentHandler, namespaces, WingConstants.I18N,
E_TEXT);
}
else
{
// There are parameters, we need to us the complex method.
// <i18n:translate>
// <i18n:text> some {0} was inserted {1}. </i18n:text>
// <i18n:param> text </i18n:param>
// <i18n:param> here </i18n:param>
// </i18n:translate>
startElement(contentHandler, namespaces, WingConstants.I18N,
E_TRANSLATE, null);
AttributeMap attributes = new AttributeMap();
attributes.setNamespace(WingConstants.I18N);
attributes.put(A_CATALOGUE, catalogue);
startElement(contentHandler, namespaces, WingConstants.I18N,
E_TEXT, attributes);
sendCharacters(contentHandler, message.getKey());
endElement(contentHandler, namespaces, WingConstants.I18N,
E_TEXT);
// i18n:param tags
for (Object dictionaryParameter : dictionaryParameters)
{
if (dictionaryParameter != null)
{
toSAX(contentHandler, namespaces, dictionaryParameter);
}
}
endElement(contentHandler, namespaces, WingConstants.I18N,
E_TRANSLATE);
}
}
}
/**
* Build the the correct param element for the given dictionaryParameter
* based upon the class type. This method can deal with Dates, numbers, and
* strings.
*
* @param dictionaryParameter
* A dictionary parameter.
*/
private void toSAX(ContentHandler contentHandler,
NamespaceSupport namespaces, Object dictionaryParameter)
throws SAXException
{
AttributeMap attributes = new AttributeMap();
attributes.setNamespace(WingConstants.I18N);
if (dictionaryParameter instanceof Date)
{
Date date = (Date) dictionaryParameter;
DateFormat dateFormater = DateFormat
.getDateInstance(DateFormat.DEFAULT);
attributes.put(A_TYPE, TYPE_DATE);
attributes.put(A_VALUE, dateFormater.format(date));
// If no pattern is given then the default format is assumed.
}
else if (dictionaryParameter instanceof Integer)
{
Integer value = (Integer) dictionaryParameter;
attributes.put(A_TYPE, TYPE_NUMBER);
attributes.put(A_VALUE, String.valueOf(value));
}
else if (dictionaryParameter instanceof Double)
{
Double value = (Double) dictionaryParameter;
attributes.put(A_TYPE, TYPE_NUMBER);
attributes.put(A_VALUE, String.valueOf(value));
}
else if (dictionaryParameter instanceof Long)
{
Long value = (Long) dictionaryParameter;
attributes.put(A_TYPE, TYPE_NUMBER);
attributes.put(A_VALUE, String.valueOf(value));
}
else if (dictionaryParameter instanceof Short)
{
Short value = (Short) dictionaryParameter;
attributes.put(A_TYPE, TYPE_NUMBER);
attributes.put(A_VALUE, String.valueOf(value));
}
else if (dictionaryParameter instanceof Float)
{
Float value = (Float) dictionaryParameter;
attributes.put(A_TYPE, TYPE_NUMBER);
attributes.put(A_VALUE, String.valueOf(value));
}
startElement(contentHandler, namespaces, WingConstants.I18N, E_PARAM, attributes);
// If the type is unknown then the value is not included as an attribute
// and instead is sent as the contents of the elements.
// NOTE: Used to only do this if unknownType was true. However, due to flaw in logic above,
// it was always true, and so always called.
// In order not to break anything, we will now call sendCharacters regardless of whether we matched a Type
sendCharacters(contentHandler, dictionaryParameter.toString());
endElement(contentHandler, namespaces, WingConstants.I18N, E_PARAM);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* This interface represents all elements that are Metadata elements.
*
* There are two broad types of wing elements: structural and metadata. The
* metadata elements describe information about the page, while structural
* elements describe how to layout the page.
*
* @author Scott Phillips
*/
public interface MetadataElement
{
//FIXME: delete me?????????
/** The name of the repository identifier attribute */
public static final String A_REPOSITORY_IDENTIFIER = "repositoryIdentifier";
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
* This class represents field values.
*
* @author Scott Phillips
*/
public class Value extends RichTextContainer
{
/** The name of the value element */
public static final String E_VALUE = "value";
/** The name of the value type attribute */
public static final String A_TYPE = "type";
/** The name of the option value attribute */
public static final String A_OPTION = "option";
/** The name of the checked attribute */
public static final String A_CHECKED = "checked";
/** The name of the confidence attribute */
public static final String A_CONFIDENCE = "confidence";
/** The possible value types */
public static final String TYPE_RAW = "raw";
public static final String TYPE_INTERPRETED = "interpreted";
public static final String TYPE_OPTION = "option";
/** value of the metadata authority code associated with a raw value */
public static final String TYPE_AUTHORITY = "authority";
/** All the possible value types collected into one array. */
public static final String[] TYPES = { TYPE_RAW, TYPE_INTERPRETED,
TYPE_OPTION, TYPE_AUTHORITY};
/** The type of this value element */
private String type;
/** The submited value for this option */
private String option;
/** The checked attribute */
private boolean checked;
/** The confidence attribute, for authority values; must be symbolic value in org.dspace.content.authority.Choices */
private String confidence = null;
/**
* Construct a new field value, when used in a multiple value context
*
* @param context
* (Required) The context this element is contained in
* @param type
* (may be null) Determine the value's type, raw, default or
* interpreted. If the value is null, then raw is used.
*/
protected Value(WingContext context, String type) throws WingException
{
super(context);
if (type == null)
{
// if no type specified just default to raw.
type = TYPE_RAW;
}
restrict(type,TYPES,
"The 'type' parameter must be one of these values: 'raw', 'interpreted', or 'option'");
this.type = type;
}
/**
* Construct a new field value, when used in a multiple value context
*
* @param context
* (Required) The context this element is contained in
* @param type
* (may be null) Determine the value's type, raw, default or
* interpreted. If the value is null, then raw is used.
* @param optionOrConfidence
* (May be null) when type is TYPE_AUTHORITY, this is the
* symbolic confidence value, otherwise it is the option value.
*/
protected Value(WingContext context, String type, String optionOrConfidence) throws WingException
{
super(context);
if (type == null)
{
// if no type specified just default to raw.
type = TYPE_RAW;
}
restrict(type,TYPES,
"The 'type' parameter must be one of these values: 'raw', 'interpreted', or 'option'.");
this.type = type;
if (type.equals(TYPE_AUTHORITY))
{
this.confidence = optionOrConfidence;
}
else
{
this.option = optionOrConfidence;
}
}
/**
* Construct a new field value, when used in a multiple value context
*
* @param context
* (Required) The context this element is contained in
* @param type
* (may be null) Determine the value's type, raw, default or
* interpreted. If the value is null, then raw is used.
* @param checked
* (Required) Determine if the value is checked, only valid for
* checkboxes and radio buttons
*/
protected Value(WingContext context, String type, boolean checked) throws WingException
{
super(context);
if (type == null)
{
// if no type specified just default to raw.
type = TYPE_RAW;
}
restrict(type,TYPES,
"The 'type' parameter must be one of these values: 'raw', 'interpreted', or 'option'.");
this.type = type;
this.checked = checked;
}
/**
* @return the type of this value.
*/
protected String getType()
{
return type;
}
/**
* Translate this element and all contained elements into SAX events. The
* events should be routed to the contentHandler found in the WingContext.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical events
* (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler,
LexicalHandler lexicalHandler, NamespaceSupport namespaces)
throws SAXException
{
AttributeMap attributes = new AttributeMap();
attributes.put(A_TYPE, this.type);
if (this.option != null)
{
attributes.put(A_OPTION, this.option);
}
if (this.checked)
{
attributes.put(A_CHECKED, this.checked);
}
if (this.type.equals(TYPE_AUTHORITY))
{
attributes.put(A_CONFIDENCE, this.confidence);
}
startElement(contentHandler, namespaces, E_VALUE, attributes);
super.toSAX(contentHandler, lexicalHandler, namespaces);
endElement(contentHandler, namespaces, E_VALUE);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* A class representing a hidden input control. The hidden input control is
* never displayed to the user but is passed back to the server when the user
* submits a form.
*
* @author Scott Phillips
*/
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
public class Hidden extends Field
{
/**
* Construct a new field.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected Hidden(WingContext context, String name, String rend)
throws WingException
{
super(context, name, Field.TYPE_HIDDEN, rend);
this.params = new Params(context);
}
/** ******************************************************************** */
/** Values * */
/** ******************************************************************** */
/**
* Set the raw value of the field removing any previous raw values.
*/
public Value setValue() throws WingException
{
removeValueOfType(Value.TYPE_RAW);
Value value = new Value(context, Value.TYPE_RAW);
values.add(value);
return value;
}
/**
* Set the raw value of the field removing any previous raw values.
*
* @param characters
* (May be null) Field value as a string
*/
public void setValue(String characters) throws WingException
{
Value value = this.setValue();
value.addContent(characters);
}
/**
* Set the raw value of the field removing any previous raw values.
*
* @param integer
* Field value as an integer
*/
public void setValue(int integer) throws WingException
{
setValue(String.valueOf(integer));
}
/**
* Set the raw value of the field removing any previous raw values.
*
* @param message
* (Required) A key into the i18n catalogue for translation into
* the user's preferred language.
*/
public void setValue(Message message) throws WingException
{
Value value = this.setValue();
value.addContent(message);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
*
* A class representing a select input control. The select input control allows
* the user to select from a list of available options.
*
* @author Scott Phillips
*/
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
public class Select extends Field
{
/**
* Construct a new field.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected Select(WingContext context, String name, String rend)
throws WingException
{
super(context, name, Field.TYPE_SELECT, rend);
this.params = new Params(context);
}
/**
* Enable the user to select multiple options.
*
*/
public void setMultiple()
{
this.params.setMultiple(true);
}
/**
* Set whether the user is able to select multiple options.
*
* @param multiple
* (Required) The multiple state.
*/
public void setMultiple(boolean multiple)
{
this.params.setMultiple(multiple);
}
/**
* Set the number of options visible at any one time.
*
* @param size
* (Required) The number of options to display.
*/
public void setSize(int size)
{
this.params.setSize(size);
}
/**
* Enable the add operation for this field. When this is enabled the
* front end will add a button to add more items to the field.
*
*/
public void enableAddOperation() throws WingException
{
this.params.enableAddOperation();
}
/**
* Enable the delete operation for this field. When this is enabled then
* the front end will provide a way for the user to select fields (probably
* checkboxes) along with a submit button to delete the selected fields.
*
*/
public void enableDeleteOperation()throws WingException
{
this.params.enableDeleteOperation();
}
/**
* Add a select option.
*
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
*/
public Option addOption(String returnValue)
throws WingException
{
Option option = new Option(context, returnValue);
options.add(option);
return option;
}
/**
* Add a select option.
*
* @param selected
* (Required) Set the field as selected.
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
*/
public Option addOption(boolean selected, String returnValue)
throws WingException
{
if (selected)
{
setOptionSelected(returnValue);
}
return addOption(returnValue);
}
/**
* Add a select option.
*
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
* @param characters
* (Required) The text to set as the visible option.
*/
public void addOption(String returnValue, String characters) throws WingException
{
Option option = this.addOption(returnValue);
option.addContent(characters);
}
/**
* Add a select option.
*
* @param selected
* (Required) Set the field as selected.
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
* @param characters
* (Required) The text to set as the visible option.
*/
public void addOption(boolean selected,String returnValue, String characters) throws WingException
{
if (selected)
{
setOptionSelected(returnValue);
}
addOption(returnValue,characters);
}
/**
* Add a select option.
*
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
* @param characters
* (Required) The text to set as the visible option.
*/
public void addOption(int returnValue, String characters) throws WingException
{
Option option = this.addOption(String.valueOf(returnValue));
option.addContent(characters);
}
/**
* Add a select option.
*
* @param selected
* (Required) Set the field as selected.
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
* @param characters
* (Required) The text to set as the visible option.
*/
public void addOption(boolean selected, int returnValue, String characters) throws WingException
{
if (selected)
{
setOptionSelected(returnValue);
}
addOption(returnValue,characters);
}
/**
* Add a select option.
*
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
* @param message
* (Required) The transalted text to set as the visible option.
*/
public void addOption(String returnValue, Message message) throws WingException
{
Option option = this.addOption(returnValue);
option.addContent(message);
}
/**
* Add a select option.
*
* @param selected
* (Required) Set the field as selected.
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
* @param message
* (Required) The transalted text to set as the visible option.
*/
public void addOption(boolean selected, String returnValue, Message message) throws WingException
{
if (selected)
{
setOptionSelected(returnValue);
}
addOption(returnValue,message);
}
/**
* Add a select option.
*
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
* @param message
* (Required) The transalted text to set as the visible option.
*/
public void addOption(int returnValue, Message message) throws WingException
{
Option option = this.addOption(String.valueOf(returnValue));
option.addContent(message);
}
/**
* Add a select option.
*
* @param selected
* (Required) Set the field as selected.
* @param returnValue
* (Required) The value to be passed back if this option is
* selected.
* @param message
* (Required) The transalted text to set as the visible option.
*/
public void addOption(boolean selected, int returnValue, Message message) throws WingException
{
if (selected)
{
setOptionSelected(returnValue);
}
addOption(returnValue,message);
}
/**
* Set the given option as selected.
*
* @param returnValue
* (Required) The return value of the option to be selected.
*/
public void setOptionSelected(String returnValue) throws WingException
{
Value value = new Value(context,Value.TYPE_OPTION,returnValue);
values.add(value);
}
/**
* Set the given option as selected.
*
* @param returnValue
* (Required) The return value of the option to be selected.
*/
public void setOptionSelected(int returnValue) throws WingException
{
Value value = new Value(context,Value.TYPE_OPTION,String.valueOf(returnValue));
values.add(value);
}
/**
* Add a field instance
* @return instance
*/
public Instance addInstance() throws WingException
{
Instance instance = new Instance(context);
instances.add(instance);
return instance;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* A class representing a text area input control. The text area control enables
* to user to enter multiple lines of text.
*
* @author Scott Phillips
*/
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
public class TextArea extends Field
{
/**
* Construct a new field.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected TextArea(WingContext context, String name, String rend)
throws WingException
{
super(context, name, Field.TYPE_TEXTAREA, rend);
this.params = new Params(context);
}
/**
* Set the size of the text area.
*
* @param rows
* (May be zero for no defined value) The default number of rows
* that the text area should span.
* @param cols
* (May be zero for no defined value) The default number of
* columns that the text area should span.
*/
public void setSize(int rows, int cols)
{
this.params.setRows(rows);
this.params.setCols(cols);
}
/**
* Set the maximum length of the field.
*
* @param maxLength
* (May be zero for no defined value) The maximum length that the
* theme should accept for form input.
*/
public void setMaxLength(int maxLength)
{
this.params.setMaxLength(maxLength);
}
/**
* Enable the add operation for this field. When this is enabled the
* front end will add a button to add more items to the field.
*
*/
public void enableAddOperation() throws WingException
{
this.params.enableAddOperation();
}
/**
* Enable the delete operation for this field. When this is enabled then
* the front end will provide a way for the user to select fields (probably
* checkboxes) along with a submit button to delete the selected fields.
*
*/
public void enableDeleteOperation()throws WingException
{
this.params.enableDeleteOperation();
}
/** ******************************************************************** */
/** Raw Values * */
/** ******************************************************************** */
/**
* Set the raw value of the field removing any previous raw values.
*/
public Value setValue() throws WingException
{
removeValueOfType(Value.TYPE_RAW);
Value value = new Value(context, Value.TYPE_RAW);
values.add(value);
return value;
}
/**
* Set the raw value of the field removing any previous raw values.
*
* @param characters
* (May be null) Field value as a string
*/
public void setValue(String characters) throws WingException
{
Value value = this.setValue();
value.addContent(characters);
}
/**
* Set the raw value of the field removing any previous raw values.
*
* @param message
* (Required) A key into the i18n catalogue for translation into
* the user's preferred language.
*/
public void setValue(Message message) throws WingException
{
Value value = this.setValue();
value.addContent(message);
}
/**
* Set the authority value of the field removing any previous authority values.
* Initialized to an empty value.
*/
public Value setAuthorityValue() throws WingException
{
return setAuthorityValue("", "UNSET");
}
/**
* Set the authority value of the field removing any previous authority values.
*
* @param characters
* (May be null) Field value as a string
* @param confidence symbolic confidence value
*/
public Value setAuthorityValue(String characters, String confidence) throws WingException
{
this.removeValueOfType(Value.TYPE_AUTHORITY);
Value value = new Value(context, Value.TYPE_AUTHORITY, confidence);
value.addContent(characters);
values.add(value);
return value;
}
/**
* Add a field instance
* @return instance
*/
public Instance addInstance() throws WingException
{
Instance instance = new Instance(context);
instances.add(instance);
return instance;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import org.dspace.app.xmlui.wing.WingConstants;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
* A class representing the page division.
*
* The body contains any number of divisions (div elements) which group content
* into interactive and non interactive display blocks.
*
* @author Scott Phillips
*/
public class Meta extends AbstractWingElement implements WingMergeableElement
{
/** The name of the meta element */
public static final String E_META = "meta";
/** The divisions contained within this body */
private boolean merged = false;
/** User oriented metadata associated with this document */
private UserMeta userMeta;
/** Page oriented metadata associated with this document */
private PageMeta pageMeta;
/** Repository oriented metadata associated with this document */
private RepositoryMeta repositoryMeta;
protected Meta(WingContext context) throws WingException
{
// FIXME: don't statically assign authenticated status or
// repositoryIdentifier.
super(context);
userMeta = new UserMeta(context);
pageMeta = new PageMeta(context);
repositoryMeta = new RepositoryMeta(context);
}
/**
* Set a new user oriented metadata set.
*
* @return The user oriented metadata set.
*/
public UserMeta setUserMeta() throws WingException
{
return this.userMeta;
}
/**
* Set a new page oriented metadata set.
*
* @return The page oriented metadata set.
*/
public PageMeta setPageMeta() throws WingException
{
return this.pageMeta;
}
/**
* Set a new repository oriented metadata set.
*
* @return The repository oriented metadata set.
*/
public RepositoryMeta setRepositoryMeta() throws WingException
{
return this.repositoryMeta;
}
/**
* Determine if the given SAX event is a Meta element.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return True if this WingElement is equivalent to the given SAX Event.
*/
public boolean mergeEqual(String namespace, String localName, String qName,
Attributes attributes) throws SAXException, WingException
{
if (!WingConstants.DRI.URI.equals(namespace))
{
return false;
}
if (!E_META.equals(localName))
{
return false;
}
return true;
}
/**
* Merge the given sub-domain of metadata elements.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element *
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return The child element
*/
public WingMergeableElement mergeChild(String namespace, String localName,
String qName, Attributes attributes) throws SAXException,
WingException
{
// User
if (this.userMeta != null
&& this.userMeta.mergeEqual(namespace, localName, qName,
attributes))
{
UserMeta userMeta = this.userMeta;
this.userMeta = null;
return userMeta;
}
// page
if (this.pageMeta != null
&& this.pageMeta.mergeEqual(namespace, localName, qName,
attributes))
{
PageMeta pageMeta = this.pageMeta;
this.pageMeta = null;
return pageMeta;
}
// repository
if (this.repositoryMeta != null
&& this.repositoryMeta.mergeEqual(namespace, localName, qName,
attributes))
{
RepositoryMeta repositoryMeta = this.repositoryMeta;
this.repositoryMeta = null;
return repositoryMeta;
}
return null;
}
/**
* Notify this element that it is being merged.
*
* @return The attributes for this merged element
*/
public Attributes merge(Attributes attributes) throws SAXException,
WingException
{
this.merged = true;
return attributes;
}
/**
* Translate to SAX events
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces) throws SAXException
{
if (!merged)
{
startElement(contentHandler, namespaces, E_META, null);
}
if (this.userMeta != null)
{
this.userMeta.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (this.pageMeta != null)
{
this.pageMeta.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (this.repositoryMeta != null)
{
this.repositoryMeta.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (!merged)
{
endElement(contentHandler, namespaces, E_META);
}
}
/**
* dispose
*/
public void dispose()
{
if (this.userMeta != null)
{
this.userMeta.dispose();
}
if (this.pageMeta != null)
{
this.pageMeta.dispose();
}
if (this.repositoryMeta != null)
{
this.repositoryMeta.dispose();
}
this.userMeta = null;
this.pageMeta = null;
this.repositoryMeta = null;
super.dispose();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import java.util.ArrayList;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.ObjectManager;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
* Refrence a repository object that is referenced in the ObjectMeta portion of
* the DRI document. These are internal refrences distinct from the xref element
* which is used for extrenal refrences.
*
* @author Scott Phillips
*/
public class Reference extends AbstractWingElement implements
StructuralElement
{
/** The name of the reference element */
public static final String E_REFERENCE = "reference";
/** The name of the repositoryIdentifier attribute */
public static final String A_REPOSITORY_ID = "repositoryID";
/** An optional type of the refrenced object. */
public static final String A_TYPE = "type";
/** The name of the objectIdentifier attribute */
public static final String A_URL = "url";
/** The unique identifier of the repository this object is identified with */
private String repository;
/** The unique identifier of the object within the specified repository */
private String url;
/** An optional type of the referenced object */
private String type;
/** All content of this container */
private java.util.List<AbstractWingElement> contents = new ArrayList<AbstractWingElement>();
/**
* Construct a new object reference.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*
* @param object
* (Required) The referenced object.
*/
protected Reference(WingContext context, Object object)
throws WingException
{
super(context);
ObjectManager objectManager = context.getObjectManager();
if (objectManager == null)
{
throw new WingException(
"Unable to reference object because no object manager has been defined.");
}
if (!objectManager.manageObject(object))
{
throw new WingException(
"The available object manager is unable to manage the give object.");
}
this.url = objectManager.getObjectURL(object);
this.repository = objectManager.getRepositoryIdentifier(object);
this.type = objectManager.getObjectType(object);
}
/**
* Add a nested reference set.
*
* @param type
* (required) The reference type, see referenceSet.TYPES
* @param orderBy
* (May be null) A statement of ordering for reference sets.
* @param render
* (May be null) a rendering hint used to override the default
* display of the element.
*/
public ReferenceSet addReferenceSet(String type, String orderBy, String render)
throws WingException
{
ReferenceSet referenceSet = new ReferenceSet(context, true, null, type,
orderBy, render);
contents.add(referenceSet);
return referenceSet;
}
/**
* Add a nested reference set
*
* @param type
* (required) The reference type, see referenceSet.TYPES
* @param orderBy
* (May be null) A statement of ordering for reference sets.
*/
public ReferenceSet addReferenceSet(String type, String orderBy)
throws WingException
{
return addReferenceSet(type, orderBy, null);
}
/**
* Add a nested include set
*
* @param type
* (required) The include type, see includeSet.TYPES
*/
public ReferenceSet addReferenceSet(String type) throws WingException
{
return addReferenceSet(type, null, null);
}
/**
* Translate this metadata inclusion set to SAX
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces) throws SAXException
{
AttributeMap attributes = new AttributeMap();
attributes.put(A_REPOSITORY_ID, this.repository);
attributes.put(A_URL, this.url);
if (type != null)
{
attributes.put(A_TYPE, type);
}
startElement(contentHandler, namespaces, E_REFERENCE, attributes);
for (AbstractWingElement content : contents)
{
content.toSAX(contentHandler, lexicalHandler, namespaces);
}
endElement(contentHandler, namespaces, E_REFERENCE);
}
/**
* dispose
*/
public void dispose()
{
if (contents != null)
{
for (AbstractWingElement content : contents)
{
content.dispose();
}
contents.clear();
}
contents = null;
super.dispose();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* A class representing a composite input control. The composite input control
* enables multiple input conrols to be combined together into a single control.
* Some example uses would be names, that are broken up into both a first and
* last name. Together they represent a single value but the user can interacts
* two seperate text boxes for each part of the name.
*
* @author Scott Phillips
*/
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
public class Composite extends Field
{
/**
* Construct a new field.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected Composite(WingContext context, String name, String rend)
throws WingException
{
super(context, name, Field.TYPE_COMPOSITE, rend);
this.params = new Params(context);
}
/**
* Enable the add operation for this field. When this is enabled the
* front end will add a button to add more items to the field.
*
*/
public void enableAddOperation() throws WingException
{
this.params.enableAddOperation();
}
/**
* Enable the delete operation for this field. When this is enabled then
* the front end will provide a way for the user to select fields (probably
* checkboxes) along with a submit button to delete the selected fields.
*
*/
public void enableDeleteOperation()throws WingException
{
this.params.enableDeleteOperation();
}
/**
* Add a boolean input control which may be toggled by the user. A checkbox
* may have several fields which share the same name and each of those
* fields may be toggled independently. This is distinct from a radio button
* where only one field may be toggled.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new checkbox field
*/
public CheckBox addCheckBox(String name, String rend) throws WingException
{
CheckBox checkbox = new CheckBox(context, name, rend);
fields.add(checkbox);
return checkbox;
}
/**
* Add a boolean input control which may be toggled by the user. A checkbox
* may have several fields which share the same name and each of those
* fields may be toggled independently. This is distinct from a radio button
* where only one field may be toggled.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return A new checkbox field
*/
public CheckBox addCheckBox(String name) throws WingException
{
return addCheckBox(name, null);
}
/**
* Add a boolean input control which may be toggled by the user. Multiple
* radio button fields may share the same name. When this occurs only one
* field may be selected to be true. This is distinct from a checkbox where
* multiple fields may be toggled.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new radio field.
*/
public Radio addRadio(String name, String rend) throws WingException
{
Radio radio = new Radio(context, name, rend);
fields.add(radio);
return radio;
}
/**
* Add a boolean input control which may be toggled by the user. Multiple
* radio button fields may share the same name. When this occurs only one
* field may be selected to be true. This is distinct from a checkbox where
* multiple fields may be toggled.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
*
* @return a new radio field
*/
public Radio addRadio(String name) throws WingException
{
return addRadio(name, null);
}
/**
* Add a menu input control which allows the user to select from a list of
* available options.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new select field
*/
public Select addSelect(String name, String rend) throws WingException
{
Select select = new Select(context, name, rend);
fields.add(select);
return select;
}
/**
* Add a menu input control which allows the user to select from a list of
* available options.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return a new select field
*/
public Select addSelect(String name) throws WingException
{
return addSelect(name, null);
}
/**
* Add a single-line text input control.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return A new text field
*/
public Text addText(String name, String rend) throws WingException
{
Text text = new Text(context, name, rend);
fields.add(text);
return text;
}
/**
* Add a single-line text input control.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return a new text field
*/
public Text addText(String name) throws WingException
{
return addText(name, null);
}
/**
* Add a multi-line text input control.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new text area field
*/
public TextArea addTextArea(String name, String rend) throws WingException
{
TextArea textarea = new TextArea(context, name, rend);
fields.add(textarea);
return textarea;
}
/**
* Add a multi-line text input control.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return a new text area field
*/
public TextArea addTextArea(String name) throws WingException
{
return addTextArea(name, null);
}
/**
* Add a field instance
* @return instance
*/
public Instance addInstance() throws WingException
{
Instance instance = new Instance(context);
instances.add(instance);
return instance;
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* A class representing the Button input control. The button input control
* allows the user to activate a form submit, where the form information is sent
* back to the server.
*
* @author Scott Phillips
*/
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
public class Button extends Field
{
/**
* Construct a new field.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected Button(WingContext context, String name, String rend)
throws WingException
{
super(context, name, Field.TYPE_BUTTON, rend);
params = new Params(context);
}
/**
* Set the button's label, removing any previous label's
*
* @return A button label's value.
*/
public Value setValue() throws WingException
{
removeValueOfType(Value.TYPE_RAW);
Value value = new Value(context, Value.TYPE_RAW);
values.add(value);
return value;
}
/**
* Set the button's label, removing any previous label's
*
* @param characters
* (May be null) The button's label as a string.
*/
public void setValue(String characters) throws WingException
{
Value value = this.setValue();
value.addContent(characters);
}
/**
* Set the button's label, removing any previous labels.
*
* @param translated
* (Required) A key into the i18n catalogue for translation into
* the user's preferred language.
*/
public void setValue(Message translated) throws WingException
{
Value value = this.setValue();
value.addContent(translated);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
*
* This class represents a xref link to an external document. The text within
* the tag itself will be used as part of the link's visual body.
*
* @author Scott Phillips
*/
public class Xref extends TextContainer implements StructuralElement
{
/** The name of the xref element */
public static final String E_XREF = "xref";
/** The name of the target attribute */
public static final String A_TARGET = "target";
/** The link's target */
private String target;
/** Special rendering instructions for this link */
private String rend;
/** The link's name */
private String name;
/**
* Construct a new xref link.
*
* @param context
* (Required) The context this element is contained in
* @param target
* (Required) A target URL for the references a destination for
* the xref.
* @param rend
* (May be null) A special rendering instruction for this xref.
* @param name
* (May be null) a local identifier used to differentiate the
* element from its siblings.
*/
protected Xref(WingContext context, String target, String rend, String name) throws WingException
{
super(context);
// Instead of validating the target field for null values we'll just assume that the caller
// meant to have a "/" but didn't quite handle this case. Ideal no one should call this
// method with a null value but sometimes it happens. What we are seeing is that it is
// common for developers to just call it using something like <ContextPath + "/link">.
// However in the case where the caller just wants a link back to DSpace home they just pass
// <ContextPath>, in cases where we are installed at the root of the servlet's url path this
// is null. To correct for this common mistake we'll just change all null values to a plain
// old "/", assuming they meant the root.
//require(target, "The 'target' parameter is required for all xrefs.");
if (target == null)
{
target = "/";
}
this.target = target;
this.rend = rend;
this.name = name;
}
/**
* Construct a new xref link.
*
* @param context
* (Required) The context this element is contained in
* @param target
* (Required) A target URL for the references a destination for
* the xref.
* @param rend
* (May be null) A special rendering instruction for this xref.
*/
protected Xref(WingContext context, String target, String rend) throws WingException
{
this(context, target, rend, null);
}
/**
* Construct a new xref link.
*
* @param context
* (Required) The context this element is contained in
* @param target
* (Required) A target URL for the references a destination for
* the xref.
*/
protected Xref(WingContext context, String target) throws WingException
{
this(context, target, null, null);
}
/**
* Translate this element and all contained elements into SAX events. The
* events should be routed to the contentHandler found in the WingContext.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces) throws SAXException
{
AttributeMap attributes = new AttributeMap();
attributes.put(A_TARGET, target);
if (name != null)
{
attributes.put(A_NAME, name);
attributes.put(A_ID, context.generateID(E_XREF, name));
}
if(this.rend!=null){
attributes.put(A_RENDER, this.rend);
}
startElement(contentHandler, namespaces, E_XREF, attributes);
super.toSAX(contentHandler, lexicalHandler, namespaces);
endElement(contentHandler, namespaces, E_XREF);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import java.util.HashMap;
import java.util.Map;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.ObjectManager;
import org.dspace.app.xmlui.wing.WingConstants;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
* A class representing a set of all referenced repositories in the DRI document.
*
* @author Scott Phillips
*/
public class RepositoryMeta extends AbstractWingElement implements WingMergeableElement, MetadataElement
{
/** The name of the ObjectMeta element */
public static final String E_REPOSITORY_META = "repositoryMeta";
/** The name of the repository element */
public static final String E_REPOSITORY = "repository";
/** The name of this repository identifier attribute*/
public static final String A_REPOSITORY_ID = "repositoryID";
/** The unique url of this repository */
public static final String A_REPOSITORY_URL = "url";
/** Has this repositoryMeta element been merged? */
private boolean merged = false;
/** The registered repositories on this page */
private Map<String,String> repositories = new HashMap<String,String>();
/**
* Construct a new RepositoryMeta
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*/
protected RepositoryMeta(WingContext context) throws WingException
{
super(context);
ObjectManager objectManager = context.getObjectManager();
if (!(objectManager == null))
{
this.repositories = objectManager.getAllManagedRepositories();
}
}
/**
* Determine if the given SAX event is a ObjectMeta element.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return True if this WingElement is equivalent to the given SAX Event.
*/
public boolean mergeEqual(String namespace, String localName, String qName,
Attributes attributes) throws SAXException, WingException
{
if (!WingConstants.DRI.URI.equals(namespace))
{
return false;
}
if (!E_REPOSITORY_META.equals(localName))
{
return false;
}
return true;
}
/**
* Since we will only add to the object set and never modify an existing
* object we do not merge any child elements.
*
* However we will notify the object manager of each identifier we
* encounter.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element *
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return The child element
*/
public WingMergeableElement mergeChild(String namespace, String localName,
String qName, Attributes attributes) throws SAXException,
WingException
{
// Check if it's in our name space and an options element.
if (!WingConstants.DRI.URI.equals(namespace))
{
return null;
}
if (!E_REPOSITORY.equals(localName))
{
return null;
}
// Get the repositoryIdentefier
String repositoryIdentifier = attributes.getValue(A_REPOSITORY_ID);
if (repositories.containsKey(repositoryIdentifier))
{
repositories.remove(repositoryIdentifier);
}
return null;
}
/**
* Inform this element that it is being merged with an existing element.
*/
public Attributes merge(Attributes attributes) throws SAXException,
WingException
{
this.merged = true;
return attributes;
}
/**
* Translate this element into SAX events.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler,
LexicalHandler lexicalHandler, NamespaceSupport namespaces)
throws SAXException
{
if (!merged)
{
startElement(contentHandler, namespaces, E_REPOSITORY_META, null);
}
for (String identifier : repositories.keySet())
{
// add the repository XML
AttributeMap attributes = new AttributeMap();
attributes.put(A_REPOSITORY_ID, identifier);
attributes.put(A_REPOSITORY_URL, repositories.get(identifier));
startElement(contentHandler,namespaces,E_REPOSITORY,attributes);
endElement(contentHandler,namespaces,E_REPOSITORY);
}
if (!merged)
{
endElement(contentHandler, namespaces, E_REPOSITORY_META);
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
/**
* A class representing all the containers that contain unformatted text, such
* as head, label, help, value, etc...
*
* This class may not be instantiated on it's own instead you must use one of
* the extending classes listed above. This abstract class implements the
* methods common to each of those elements.
*
* @author Scott Phillips
*/
public abstract class TextContainer extends Container
{
/**
* Construct a new text container.
*
* This method doesn't do anything but because the inheriting abstract class
* mandates a constructor for this class to compile it must ensure that the
* parent constructor is called. Just as implementors of this class must
* ensure that this constructor is called, thus is the chain of life. :)
*
* @param context
* (Required) The context this element is contained in.
*/
protected TextContainer(WingContext context) throws WingException
{
super(context);
}
/**
* Add character content to container.
*
* @param characters
* (Required) Direct content or a dictionary tag to be inserted
* into the element.
*/
public void addContent(String characters) throws WingException
{
Data data = new Data(context, characters);
contents.add(data);
}
/**
* Add integer content to container.
*
* @param integer
* (Required) Add the integer into the element's container.
*/
public void addContent(int integer) throws WingException
{
Data data = new Data(context, String.valueOf(integer));
contents.add(data);
}
/**
* Add translated content to container.
*
* @param message
* (Required) A key into the i18n catalogue for translation into
* the user's preferred language.
*/
public void addContent(Message message) throws WingException
{
Data data = new Data(context, message);
contents.add(data);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import java.util.ArrayList;
import java.util.List;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingConstants;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.NamespaceSupport;
/**
* A class representing a set of metadata about the user generating this page.
*
* @author Scott Phillips
*/
public class UserMeta extends AbstractWingElement implements
WingMergeableElement, MetadataElement
{
/** The name of the userMeta element */
public static final String E_USER_META = "userMeta";
/** The name of the authenticated attribute */
public static final String A_AUTHENTICATED = "authenticated";
/** Has this UserMeta element been merged? */
private boolean merged = false;
/** Has this user been authenticated? */
private boolean authenticated = false;
/** The metadata contents of this UserMeta element */
private List<Metadata> metadatum = new ArrayList<Metadata>();
/**
* Construct a new userMeta
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*/
protected UserMeta(WingContext context) throws WingException
{
super(context);
}
/**
* Set the user described in the meta object as authenticated.
*
* @param authenticated
* (Required) True if the user is authenticated, false otherwise.
*/
public void setAuthenticated(boolean authenticated)
{
this.authenticated = authenticated;
}
/**
* Add metadata about the requesting user to the document.
*
* @param element
* (Required) The metadata element.
* @param qualifier
* (May be null) The metadata qualifier.
* @param language
* (May be null) The metadata's language
* @param allowMultiple
* (Required) determine if multiple metadata elements with the same
* element, qualifier and language are allowed.
* @return A new metadata
*/
public Metadata addMetadata(String element, String qualifier,
String language, boolean allowMultiple) throws WingException
{
Metadata metadata = new Metadata(context, element, qualifier, language, allowMultiple);
metadatum.add(metadata);
return metadata;
}
/**
* Add metadata about the requesting user to the document.
*
* @param element
* (Required) The metadata element.
* @param qualifier
* (May be null) The metadata qualifier.
* @param language
* (May be null) The metadata's language
* @return A new metadata
*/
public Metadata addMetadata(String element, String qualifier,
String language) throws WingException
{
return addMetadata(element, qualifier, null, false);
}
/**
* Add metadata about the requesting user to the document.
*
* @param element
* (Required) The metadata element.
* @param qualifier
* (May be null) The metadata qualifier.
* @return A new metadata
*/
public Metadata addMetadata(String element, String qualifier)
throws WingException
{
return addMetadata(element, qualifier, null, false);
}
/**
* Add metadata about the requesting user to the document.
*
* @param element
* (Required) The metadata element.
* @return A new metadata
*/
public Metadata addMetadata(String element) throws WingException
{
return addMetadata(element, null, null, false);
}
/**
* Determine if the given SAX event is a UserMeta element.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return True if this WingElement is equivalent to the given SAX Event.
*/
public boolean mergeEqual(String namespace, String localName, String qName,
Attributes attributes) throws SAXException, WingException
{
if (!WingConstants.DRI.URI.equals(namespace))
{
return false;
}
if (!E_USER_META.equals(localName))
{
return false;
}
return true;
}
/**
* Since metadata can not be merged there are no mergeable children. This
* just return's null.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element *
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return The child element
*/
public WingMergeableElement mergeChild(String namespace, String localName,
String qName, Attributes attributes) throws SAXException,
WingException
{
// We don't merge our children but we do have one special optimization:
// if a metadata is already in the document and it is tagged as not allowing
// multiples then we do not add the new metadata to the document.
if (WingConstants.DRI.URI.equals(namespace) && Metadata.E_METADATA.equals(localName))
{
String element = attributes.getValue(Metadata.A_ELEMENT);
String qualifier = attributes.getValue(Metadata.A_QUALIFIER);
String language = attributes.getValue(Metadata.A_LANGUAGE);
List<Metadata> remove = new ArrayList<Metadata>();
for (Metadata metadata : metadatum)
{
if (metadata.equals(element,qualifier,language) && !metadata.allowMultiple())
{
remove.add(metadata);
}
}
// Remove all the metadata elements we found.
for (Metadata metadata : remove)
{
metadata.dispose();
metadatum.remove(metadata);
}
}
return null;
}
/**
* Inform this element that it is being merged with an existing element.
*/
public Attributes merge(Attributes attributes) throws SAXException,
WingException
{
this.merged = true;
String mergedAuthenticated = attributes.getValue(A_AUTHENTICATED);
if ("yes".equals(mergedAuthenticated))
{
// The user has already been set to authenticated.
// Do nothing.
}
else if ("no".equals(mergedAuthenticated))
{
// No authenticated user yet.
if (this.authenticated)
{
// Original no, but we've been told that the user is
// authenticated.
AttributesImpl attributesImpl = new AttributesImpl(attributes);
int index = attributesImpl.getIndex(A_AUTHENTICATED);
if (index >= 0)
{
attributesImpl.setValue(index,"yes");
}
else
{
attributesImpl.addAttribute("",
A_AUTHENTICATED, A_AUTHENTICATED, "CDATA", "yes");
}
attributes = attributesImpl;
}
}
else
{
// Authenticated value does not conform to the schema.
AttributesImpl attributesImpl = new AttributesImpl(attributes);
attributesImpl.addAttribute("", A_AUTHENTICATED,
A_AUTHENTICATED, "CDATA", (this.authenticated ? "yes" : "no"));
attributes = attributesImpl;
}
return attributes;
}
/**
* Translate this element into SAX events.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces) throws SAXException
{
if (!merged)
{
AttributeMap attributes = new AttributeMap();
if (authenticated)
{
attributes.put(A_AUTHENTICATED, "yes");
}
else
{
attributes.put(A_AUTHENTICATED, "no");
}
startElement(contentHandler, namespaces, E_USER_META, attributes);
}
for (Metadata metadata : metadatum)
{
metadata.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (!merged)
{
endElement(contentHandler, namespaces, E_USER_META);
}
}
/**
* dispose
*/
public void dispose()
{
for (AbstractWingElement content : metadatum)
{
content.dispose();
}
metadatum.clear();
metadatum = null;
super.dispose();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* A class representing a paragraph, the "p" element.
*
* The p element presents text in paragraph format. Its primary purpose is to
* display textual data, possibly enhanced with hyperlinks, emphasized blocks of
* text, images and form fields.
*
* @author Scott Phillips
*/
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
public class Para extends RichTextContainer implements StructuralElement
{
/** The name of the para element */
public static final String E_PARA = "p";
/** The para's name */
private String name;
/** Any special rendering instructions for the para */
private String rend;
/**
* Construct a new paragraph. Typically names for paragraphs are not
* assigned by the java developer instead they are automatically generated
* by the parent container. However the only real constraint is that the be
* unique among other sibling paragraph elements.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*
* @param name
* (May be null) a local identifier used to differentiate the
* element from its siblings. *
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected Para(WingContext context, String name, String rend)
throws WingException
{
super(context);
this.name = name;
this.rend = rend;
}
/**
* Translate this element and all contained elements into SAX events. The
* events should be routed to the contentHandler found in the WingContext.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces) throws SAXException
{
AttributeMap attributes = new AttributeMap();
if (name != null)
{
attributes.put(A_NAME, name);
attributes.put(A_ID, context.generateID(E_PARA, name));
}
if (rend != null)
{
attributes.put("rend", rend);
}
startElement(contentHandler, namespaces, E_PARA, attributes);
super.toSAX(contentHandler, lexicalHandler, namespaces);
endElement(contentHandler, namespaces, E_PARA);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
*
* @author Scott Phillips
*/
public class Option extends TextContainer
{
/** The name of the value element */
public static final String E_OPTION = "option";
/** The name of the return value attribute */
public static final String A_RETURN_VALUE = "returnValue";
/** The submited value for this option */
private String returnValue;
/**
*
*
* @param context
* (Required) The context this element is contained in
* @param returnValue
* (may be null) The options return value.
*/
protected Option(WingContext context, String returnValue) throws WingException
{
super(context);
this.returnValue = returnValue;
}
/**
* Translate this element and all contained elements into SAX events. The
* events should be routed to the contentHandler found in the WingContext.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical events
* (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler,
LexicalHandler lexicalHandler, NamespaceSupport namespaces)
throws SAXException
{
AttributeMap attributes = new AttributeMap();
attributes.put(A_RETURN_VALUE, this.returnValue);
startElement(contentHandler, namespaces, E_OPTION, attributes);
super.toSAX(contentHandler, lexicalHandler, namespaces);
endElement(contentHandler, namespaces, E_OPTION);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import java.util.ArrayList;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
* Class representing a set of referenced metadata.
*
* @author Scott Phillips
*/
public class ReferenceSet extends AbstractWingElement implements
StructuralElement
{
/** The name of the referenceSet element */
public static final String E_REFERENCE_SET = "referenceSet";
/** The name of the orderBy attribute */
public static final String A_ORDER_BY = "orderBy";
/** The name of the type attribute */
public static final String A_TYPE = "type";
/** The possible interactive division methods: get,post, or multipart. */
public static final String TYPE_SUMMARY_LIST = "summaryList";
public static final String TYPE_SUMMARY_VIEW = "summaryView";
public static final String TYPE_DETAIL_LIST = "detailList";
public static final String TYPE_DETAIL_VIEW = "detailView";
/** The possible interactive division methods names collected into one array */
public static final String[] TYPES = { TYPE_SUMMARY_LIST, TYPE_SUMMARY_VIEW, TYPE_DETAIL_LIST, TYPE_DETAIL_VIEW };
/** The name assigned to this metadata set */
private String name;
/** The ordering mechanism to use. */
private String orderBy;
/** The reference type, see TYPES defined above */
private String type;
/** Special rendering instructions */
private String rend;
/** The head label for this referenceset */
private Head head;
/** All content of this container, items & lists */
private java.util.List<AbstractWingElement> contents = new ArrayList<AbstractWingElement>();
/**
* Construct a new referenceSet
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
* @param childreference
* Whether this is a child reference (not requiring a name).
* @param name
* (May be null) a local identifier used to differentiate the
* element from its siblings.
* @param type
* (Required) The type of reference set which determines the level
* of detail for the metadata rendered. See TYPES for a list of
* available types.
* @param orderBy
* (May be null) Determines the ordering of referenced metadata.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected ReferenceSet(WingContext context, boolean childreference, String name, String type, String orderBy, String rend)
throws WingException
{
super(context);
// Names are only required for parent reference sets.
if (!childreference)
{
require(name, "The 'name' parameter is required for reference sets.");
}
restrict(
type,
TYPES,
"The 'method' parameter must be one of these values: 'summaryList', 'summaryView', 'detailList', or 'detailView'.");
this.name = name;
this.type = type;
this.orderBy = orderBy;
this.rend = rend;
}
/**
* Set the head element which is the label associated with this referenceset.
*/
public Head setHead() throws WingException
{
this.head = new Head(context, null);
return head;
}
/**
* Set the head element which is the label associated with this referenceset.
*
* @param characters
* (May be null) Unprocessed characters to be referenced
*/
public void setHead(String characters) throws WingException
{
Head head = this.setHead();
head.addContent(characters);
}
/**
* Set the head element which is the label associated with this referenceset.
*
* @param message
* (Required) A key into the i18n catalogue for translation into
* the user's preferred language.
*/
public void setHead(Message message) throws WingException
{
Head head = this.setHead();
head.addContent(message);
}
/**
* Add an object reference.
*
* @param object
* (Required) The referenced object.
*/
public Reference addReference(Object object)
throws WingException
{
Reference reference = new Reference(context, object);
contents.add(reference);
return reference;
}
/**
* Translate this metadata inclusion set to SAX
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces) throws SAXException
{
AttributeMap attributes = new AttributeMap();
if (name != null)
{
attributes.put(A_NAME, name);
}
if (name != null)
{
attributes.put(A_ID, context.generateID(E_REFERENCE_SET, name));
}
attributes.put(A_TYPE, type);
if (orderBy != null)
{
attributes.put(A_ORDER_BY, orderBy);
}
if (rend != null)
{
attributes.put(A_RENDER, rend);
}
startElement(contentHandler, namespaces, E_REFERENCE_SET, attributes);
if (head != null)
{
head.toSAX(contentHandler, lexicalHandler, namespaces);
}
for (AbstractWingElement content : contents)
{
content.toSAX(contentHandler, lexicalHandler, namespaces);
}
endElement(contentHandler, namespaces, E_REFERENCE_SET);
}
/**
* dispose
*/
public void dispose()
{
if (contents != null)
{
for (AbstractWingElement content : contents)
{
content.dispose();
}
contents.clear();
}
contents = null;
super.dispose();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* Class representing a Division, or the div element, in the XML UI schema.
*
* The div element represents a major section of content and can contain a wide
* variety of other elements to present that content to the user. It can contain
* TEI style paragraphs, tables, and lists, as well as references to artifact
* information stored in artifactMeta. The div element is also recursive,
* allowing it to be further divided into other divs.
*
* @author Scott Phillips
*/
import java.util.ArrayList;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingConstants;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
public class Division extends AbstractWingElement implements StructuralElement, WingMergeableElement
{
/** The name of the division element */
public static final String E_DIVISION = "div";
/** The name of the interactive attribute */
public static final String A_INTERACTIVE = "interactive";
/** The name of the action attribute */
public static final String A_ACTION = "action";
/** The name of the method attribute */
public static final String A_METHOD = "method";
/** The name of the method attribute */
public static final String A_BEHAVIOR = "behavior";
/** The name of the continuation name attribute. */
public static final String A_BEHVIOR_SENSITIVE_FIELDS = "behaviorSensitiveFields";
/** The name of the pagination attribute */
public static final String A_PAGINATION = "pagination";
/** The name of the previous page attribute */
public static final String A_PREVIOUS_PAGE = "previousPage";
/** The name of the next page attribute */
public static final String A_NEXT_PAGE = "nextPage";
/** The name of the items total attribute */
public static final String A_ITEMS_TOTAL = "itemsTotal";
/** The name of the first item index attribute */
public static final String A_FIRST_ITEM_INDEX = "firstItemIndex";
/** The name of the last item index attribute */
public static final String A_LAST_ITEM_INDEX = "lastItemIndex";
/** The name of the current page attribute */
public static final String A_CURRENT_PAGE = "currentPage";
/** The name of the pages total attribute */
public static final String A_PAGES_TOTAL = "pagesTotal";
/** The name of the page url mask attribute */
public static final String A_PAGE_URL_MASK = "pageURLMask";
/** Determines weather this division is being merged */
private boolean merged = false;
/** The name assigned to this div */
private String name;
/** Is this division interactive if so then action & method must be defined */
private boolean interactive;
/** Where should the result of this interactive division be posted to? */
private String action;
/** What method should this interactive division use for posting the result? */
private String method;
/** Does this interactive division support the AJAX behavior? */
private boolean behaviorAJAXenabled = false;
/** A list of fields which need to be handled specially when using behavior */
private String behaviorSensitiveFields;
/** Special rendering instructions */
private String rend;
/** The head, or label of this division */
private Head head;
/** A paragraph that contains hidden fields */
private Para hiddenFieldsPara;
/**
* The pagination type of this div, either simple or masked. If null then
* this div is not paginated
*/
private String paginationType;
/** URL to the previousPage. (used by simple pagination) */
private String previousPage;
/** URL to the nextPage. (used by simple pagination) */
private String nextPage;
/**
* How many items exist across all paginated divs. (used by both pagination
* types)
*/
private int itemsTotal;
/**
* The index of the first item included in this div. (used by both
* pagination types)
*/
private int firstItemIndex;
/**
* The index of the first item included in this div. (used by both
* pagination types)
*/
private int lastItemIndex;
/**
* The index the current page being displayed. (used by masked pagination
* type)
*/
private int currentPage;
/**
* The total number of pages in the pagination set. (used by masked
* pagination type)
*/
private int pagesTotal;
/** The pagination URL mask. (used by masked pagination type) */
private String pageURLMask;
/** The possible interactive division methods: get,post, or multipart. */
public static final String METHOD_GET = "get";
public static final String METHOD_POST = "post";
public static final String METHOD_MULTIPART = "multipart";
/** The possible interactive division methods names collected into one array */
public static final String[] METHODS = { METHOD_GET, METHOD_POST,
METHOD_MULTIPART };
/** The possible pagination types: simple & masked */
public static final String PAGINATION_SIMPLE = "simple";
public static final String PAGINATION_MASKED = "masked";
/** The possible pagination division types collected into one array */
public static final String[] PAGINATION_TYPES = { PAGINATION_SIMPLE,
PAGINATION_MASKED };
/** All content of this container, items & lists */
private java.util.List<AbstractWingElement> contents = new ArrayList<AbstractWingElement>();
/**
* Construct a non interactive division.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected Division(WingContext context, String name, String rend)
throws WingException
{
super(context);
require(name, "The 'name' parameter is required for divisions.");
this.name = name;
this.rend = rend;
}
/**
* Construct an interactive division. Interactive divisions must be
* accompanied by both an action and method to determine how to process form
* data.
*
* The valid values for method may be found in the static variable METHODS.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
* @param action
* (Required) The form action attribute determines where the form
* information should be sent for processing.
* @param method
* (Required) Accepted values are "get", "post", and "multipart".
* Determines the method used to pass gathered field values to
* the handler specified by the action attribute. The multipart
* method should be used if there are any file fields used within
* the division.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected Division(WingContext context, String name, String action,
String method, String rend) throws WingException
{
super(context);
require(name, "The 'name' parameter is required for divisions.");
// Blank actions are okay:
// require(action,
// "The 'action' parameter is required for interactive divisions.");
require(method, "The 'method' parameter is required for divisions.");
restrict(
method,
METHODS,
"The 'method' parameter must be one of these values: 'get', 'post', or 'multipart'.");
this.name = name;
this.interactive = true;
this.action = action;
this.method = method;
this.rend = rend;
}
/**
* Enable AJAX behaviors on this interactive division.
*/
public void enableAJAX()
{
this.behaviorAJAXenabled = true;
}
/**
* Add to the list of behavior sensitive fields, these fields should be
* updated each time a request partial page is submitted.
*
* @param fieldName
* (Required) The name of a single field (with no spaces).
*/
public void addBehaviorSensitiveField(String fieldName) throws WingException
{
require(fieldName, "The fieldName parameter is required for the behaviorSensitiveFields attribute.");
if (this.behaviorSensitiveFields == null)
{
this.behaviorSensitiveFields = fieldName;
}
else
{
this.behaviorSensitiveFields += " " + fieldName;
}
}
/**
* Make this div paginated ( a div that spans multiple pages ) using the
* simple page paradigm.
*
* @param itemsTotal
* (Required) How many items exist across all paginated divs.
* @param firstItemIndex
* (Required) The index of the first item included in this div.
* @param lastItemIndex
* (Required) The index of the last item included in this div.
* @param previousPage
* (May be null) The URL of the previous page of the div, if it
* exists.
* @param nextPage
* (May be null) The URL of the previous page of the div, if it
* exists.
*/
public void setSimplePagination(int itemsTotal, int firstItemIndex,
int lastItemIndex, String previousPage, String nextPage)
{
this.paginationType = PAGINATION_SIMPLE;
this.previousPage = previousPage;
this.nextPage = nextPage;
this.itemsTotal = itemsTotal;
this.firstItemIndex = firstItemIndex;
this.lastItemIndex = lastItemIndex;
}
/**
* Make this div paginated ( a div that spans multiple pages ) using the
* masked page paradigm.
*
* @param itemsTotal
* (Required) How many items exist across all paginated divs.
* @param firstItemIndex
* (Required) The index of the first item included in this div.
* @param lastItemIndex
* (Required) The index of the last item included in this div.
* @param currentPage
* (Required) The index of the page currently displayed for this
* div.
* @param pagesTotal
* (Required) How many pages the paginated div spans.
* @param pageURLMask
* (Required) The mask of a URL to a particular within the
* paginated set. The destination page's number should replace
* the {pageNum} string in the URL mask to generate a full URL to
* that page.
*/
public void setMaskedPagination(int itemsTotal, int firstItemIndex,
int lastItemIndex, int currentPage, int pagesTotal,
String pageURLMask)
{
this.paginationType = PAGINATION_MASKED;
this.itemsTotal = itemsTotal;
this.firstItemIndex = firstItemIndex;
this.lastItemIndex = lastItemIndex;
this.currentPage = currentPage;
this.pagesTotal = pagesTotal;
this.pageURLMask = pageURLMask;
}
/**
* Set the head element which is the label associated with this division.
*/
public Head setHead() throws WingException
{
this.head = new Head(context, null);
return head;
}
/**
* Set the head element which is the label associated with this division.
*
* @param characters
* (May be null) Unprocessed characters to be included
*/
public void setHead(String characters) throws WingException
{
Head head = this.setHead();
head.addContent(characters);
}
/**
* Set the head element which is the label associated with this division.
*
* @param message
* (Required) A key into the i18n catalogue for translation into
* the user's preferred language.
*/
public void setHead(Message message) throws WingException
{
Head head = this.setHead();
head.addContent(message);
}
/**
* Add a sub division for further logical grouping of content.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return A new sub Division
*/
public Division addDivision(String name, String rend) throws WingException
{
Division division = new Division(context, name, rend);
contents.add(division);
return division;
}
/**
* Add a sub division for further logical grouping of content.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
* @return A new sub division
*/
public Division addDivision(String name) throws WingException
{
return this.addDivision(name, null);
}
/**
* Add an interactive sub division for further logical grouping of content.
*
* The valid values for method may be found in the static variable METHODS.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
* @param action
* (Required) The form action attribute determines where the form
* information should be sent for processing.
* @param method
* (Required) Accepted values are "get", "post", and "multipart".
* Determines the method used to pass gathered field values to
* the handler specified by the action attribute. The multipart
* method should be used if there are any file fields used within
* the division.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return A new interactive sub division
*/
public Division addInteractiveDivision(String name, String action,
String method, String rend) throws WingException
{
Division division = new Division(context, name, action, method, rend);
contents.add(division);
return division;
}
/**
* Add an interactive sub division for further logical grouping of content
* without specifying special rendering instructions.
*
* The valid values for method may be found in the static variable METHODS.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
* @param action
* (Required) The form action attribute determines where the form
* information should be sent for processing.
* @param method
* (Required) Accepted values are "get", "post", and "multipart".
* Determines the method used to pass gathered field values to
* the handler specified by the action attribute. The multipart
* method should be used if there are any file fields used within
* the division.
* @return A new interactive sub division
*/
public Division addInteractiveDivision(String name, String action,
String method) throws WingException
{
return addInteractiveDivision(name, action, method, null);
}
/**
* Append a paragraph to the division
*
* @param name
* (May be null) a local identifier used to differentiate the
* element from its siblings.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return A new paragraph.
*/
public Para addPara(String name, String rend) throws WingException
{
Para para = new Para(context, name, rend);
contents.add(para);
return para;
}
/**
* Append an unnamed paragraph to the division
*
* @return A new unnamed paragraph.
*/
public Para addPara() throws WingException
{
return addPara(null, null);
}
/**
* Append a paragraph to the division and set the content of the paragraph.
*
* @param characters
* (May be null) Untranslated character data to be included as
* the contents of this para.
*/
public void addPara(String characters) throws WingException
{
Para para = this.addPara();
para.addContent(characters);
}
/**
* Append a paragraph to the division and set the content of the paragraph.
*
* @param message
* (Required) Key to the i18n catalogue to translate the content
* into the language preferred by the user.
*/
public void addPara(Message message) throws WingException
{
Para para = this.addPara();
para.addContent(message);
}
/**
* append a list to the division.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
*
* @param type
* (May be null) an optional attribute to explicitly specify the
* type of list. In the absence of this attribute, the type of a
* list will be inferred from the presence and content of labels
* on its items. Accepted values are found at
* org.dspace.app.xmlui.xmltool.List.TYPES
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*
* @return A new List
*/
public List addList(String name, String type, String rend)
throws WingException
{
List list = new List(context, name, type, rend);
contents.add(list);
return list;
}
/**
* Append a list to the division.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
*
* @param type
* (May be null) an optional attribute to explicitly specify the
* type of list. In the absence of this attribute, the type of a
* list will be inferred from the presence and content of labels
* on its items. Accepted values are found at
* org.dspace.app.xmlui.xmltool.List.TYPES
*
* @return A new List
*/
public List addList(String name, String type) throws WingException
{
return this.addList(name, type, null);
}
/**
* Append a list to the division. The list type will be inferred by the
* presence and contents of labels and items.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
* @return A new List
*/
public List addList(String name) throws WingException
{
return this.addList(name, null, null);
}
/**
* Append a table to the division. When creating a table the number of rows
* and columns contained in the table must be pre computed and provided
* here.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
*
* @param rows
* (Required) The number of rows in the table.
* @param cols
* (Required) The number of columns in the table.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*
* @return A new table.
*/
public Table addTable(String name, int rows, int cols, String rend)
throws WingException
{
Table table = new Table(context, name, rows, cols, rend);
contents.add(table);
return table;
}
/**
* Append a table to the division. When creating a table the number of rows
* and columns contained in the table must be pre computed and provided
* here.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
*
* @param rows
* (Required) The number of rows in the table.
* @param cols
* (Required) The number of columns in the table.
*
* @return A new table.
*/
public Table addTable(String name, int rows, int cols) throws WingException
{
return this.addTable(name, rows, cols, null);
}
/**
* Add a reference set for metadata references.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
* @param type
* (Required) The include type, see IncludeSet.TYPES
* @param orderBy
* (May be null) An statement of ordering within the include set.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
public ReferenceSet addReferenceSet(String name, String type, String orderBy,
String rend) throws WingException
{
ReferenceSet referenceSet = new ReferenceSet(context, false, name, type, orderBy, rend);
contents.add(referenceSet);
return referenceSet;
}
/**
* Add a reference set for metadata references.
*
* @param name
* (Required) a local identifier used to differentiate the
* element from its siblings.
* @param type
* (Required) The include type, see IncludeSet.TYPES
*/
public ReferenceSet addReferenceSet(String name, String type)
throws WingException
{
return addReferenceSet(name, type, null, null);
}
/**
* Add a hidden field to the division, this is a common operation that is
* not directly supported by DRI. To create support for it a new paragraph
* will be created with the name "hidden-fields" and a render attribute of
* "hidden".
*
* @param name
* (Required) The hidden fields name.
* @return A new hidden field.
*/
public Hidden addHidden(String name) throws WingException
{
if (hiddenFieldsPara == null)
{
hiddenFieldsPara = addPara("hidden-fields","hidden");
}
return hiddenFieldsPara.addHidden(name);
}
/**
* Add a section of translated HTML to the DRI document. This will only handle
* simple transformations such as <p>,<b>,<i>,and <a> tags.
*
* Depending on the given HTML this may result in multiple paragraphs being
* opened and several bold tags being included.
*
* @param blankLines
* (Required) Treat blank lines as paragraphs delimiters.
* @param HTML
* (Required) The HTML content
*/
public void addSimpleHTMLFragment(boolean blankLines, String HTML) throws WingException
{
contents.add(new SimpleHTMLFragment(context,blankLines,HTML));
}
/**
* Determine if the given SAX event is the same division element. This method
* will compare interactiveness, and rendering.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return True if this WingElement is equivalent to the given SAX Event.
*/
public boolean mergeEqual(String namespace, String localName, String qName,
Attributes attributes) throws SAXException, WingException
{
if (!WingConstants.DRI.URI.equals(namespace))
{
return false;
}
if (!E_DIVISION.equals(localName))
{
return false;
}
context.getLogger().debug("Merding a division");
String name = attributes.getValue(A_NAME);
String interactive = attributes.getValue(A_INTERACTIVE);
String action = attributes.getValue(A_ACTION);
String method = attributes.getValue(A_METHOD);
String render = attributes.getValue(A_RENDER);
String pagination = attributes.getValue(A_PAGINATION);
String behavior = attributes.getValue(A_BEHAVIOR);
context.getLogger().debug("Merging got the parameters name="+name+", interactive="+interactive+", action="+action+", method="+method+", render="+render+", pagination="+pagination);
// The name must be identical (but id's can differ)
if (!this.name.equals(name))
{
return false;
}
// Insure the render attributes are identical.
if (this.rend == null)
{
if (render != null)
{
return false;
}
}
else if (!this.rend.equals(render))
{
return false;
}
if (this.interactive)
{
// Insure all the interactive fields are identical.
if (!"yes".equals(interactive))
{
return false;
}
if (!this.action.equals(action))
{
return false;
}
if (!this.method.equals(method))
{
return false;
}
// For now lets just not merge divs that have behavior.
if (!(behavior == null || behavior.equals("")))
{
return false;
}
} else {
// Else, insure that it is also not interactive.
if (!(interactive == null || "no".equals(interactive)))
{
return false;
}
}
return true;
}
/**
* Merge the given sub-domain of metadata elements.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element *
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return The child element
*/
public WingMergeableElement mergeChild(String namespace, String localName,
String qName, Attributes attributes) throws SAXException,
WingException
{
WingMergeableElement found = null;
for (AbstractWingElement content : contents)
{
if (content instanceof WingMergeableElement)
{
WingMergeableElement candidate = (WingMergeableElement) content;
if (candidate.mergeEqual(namespace, localName, qName,
attributes))
{
found = candidate;
}
}
}
contents.remove(found);
return found;
}
/**
* Notify this element that it is being merged.
*
* @return The attributes for this merged element
*/
public Attributes merge(Attributes attributes) throws SAXException,
WingException
{
this.merged = true;
return attributes;
}
/**
* Translate this division to SAX
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces) throws SAXException
{
if (!merged)
{
AttributeMap divAttributes = new AttributeMap();
divAttributes.put(A_NAME, name);
divAttributes.put(A_ID, context.generateID(E_DIVISION, name));
if (interactive)
{
divAttributes.put(A_INTERACTIVE, "yes");
divAttributes.put(A_ACTION, action);
divAttributes.put(A_METHOD, method);
if (behaviorAJAXenabled)
{
divAttributes.put(A_BEHAVIOR,"ajax");
}
if (behaviorSensitiveFields != null)
{
divAttributes.put(A_BEHVIOR_SENSITIVE_FIELDS,behaviorSensitiveFields);
}
}
if (PAGINATION_SIMPLE.equals(paginationType))
{
divAttributes.put(A_PAGINATION, paginationType);
if (previousPage != null)
{
divAttributes.put(A_PREVIOUS_PAGE, previousPage);
}
if (nextPage != null)
{
divAttributes.put(A_NEXT_PAGE, nextPage);
}
divAttributes.put(A_ITEMS_TOTAL, itemsTotal);
divAttributes.put(A_FIRST_ITEM_INDEX, firstItemIndex);
divAttributes.put(A_LAST_ITEM_INDEX, lastItemIndex);
}
else if (PAGINATION_MASKED.equals(paginationType))
{
divAttributes.put(A_PAGINATION, paginationType);
divAttributes.put(A_ITEMS_TOTAL, itemsTotal);
divAttributes.put(A_FIRST_ITEM_INDEX, firstItemIndex);
divAttributes.put(A_LAST_ITEM_INDEX, lastItemIndex);
divAttributes.put(A_CURRENT_PAGE, currentPage);
divAttributes.put(A_PAGES_TOTAL, pagesTotal);
divAttributes.put(A_PAGE_URL_MASK, pageURLMask);
}
if (rend != null)
{
divAttributes.put(A_RENDER, rend);
}
startElement(contentHandler, namespaces, E_DIVISION, divAttributes);
if (head != null)
{
head.toSAX(contentHandler, lexicalHandler, namespaces);
}
}
for (AbstractWingElement content : contents)
{
content.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (!merged) {
endElement(contentHandler, namespaces, E_DIVISION);
}
}
/**
* dispose
*/
public void dispose()
{
if (head != null)
{
head.dispose();
head = null;
}
if (contents != null)
{
for (AbstractWingElement content : contents)
{
content.dispose();
}
contents.clear();
contents = null;
}
super.dispose();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingConstants;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
* A class representing a WingDocument.
*
* Documents contain three elements and they are all mandatory: meta, body, and
* options. Because they are all mandatory they are created at construction
* time.
*
* Note: We called the class "WingDocument" instead of just plain old "Document"
* so that it won't conflict with all the other documents out there like DOM's
* document.
*
* @author Scott Phillips
*/
public class WingDocument extends AbstractWingElement implements
WingMergeableElement
{
/** The name of the document element */
public static final String E_DOCUMENT = "document";
/** The name of the version attribute */
public static final String A_VERSION = "version";
/** The document version Wing prefer */
public static final String DOCUMENT_VERSION = "1.1";
/** The divisions contained within this body */
private boolean merged = false;
/** The meta element */
private Meta meta;
/** The body element */
private Body body;
/** The options element */
private Options options;
/**
* Generate a new wing document element.
*
* @param context
* (Required) The context this element is contained in.
*/
public WingDocument(WingContext context) throws WingException
{
super(context);
// These are all required so we just create them now.
this.meta = new Meta(context);
this.body = new Body(context);
this.options = new Options(context);
}
/**
* Set the meta element of this Document containing all the metadata
* associated with this document.
*
* @return The Meta element
*/
public Meta setMeta() throws WingException
{
return this.meta;
}
/**
* Set the body element containing the structural elements associated with
* this document.
*
* @return The Body element.
*/
public Body setBody() throws WingException
{
return this.body;
}
/**
* Set the Options element containing the structural navigational structure
* associated with this document.
*
* @return The Options element.
*/
public Options setOptions() throws WingException
{
return this.options;
}
/**
* Is this document the same as the given SAX event.
*
* Note: this method will throw an error if the given event's document
* version number is out of bounds for this implementation of Wing.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return True if this WingElement is equivalent to the given SAX Event.
*/
public boolean mergeEqual(String namespace, String localName, String qName,
Attributes attributes) throws SAXException, WingException
{
if (!WingConstants.DRI.URI.equals(namespace))
{
return false;
}
if (!E_DOCUMENT.equals(localName))
{
return false;
}
String version = attributes.getValue(A_VERSION);
if (!(DOCUMENT_VERSION.equals(version)))
{
throw new WingException("Incompatable DRI versions, " + DOCUMENT_VERSION + " != " + version);
}
return true;
}
/**
* Merge the given event into this document.
*
* @param namespace
* The element's name space
* @param localName
* The local, unqualified, name for this element *
* @param qName
* The qualified name for this element
* @param attributes
* The element's attributes
* @return The child element
*/
public WingMergeableElement mergeChild(String namespace, String localName,
String qName, Attributes attributes) throws SAXException,
WingException
{
if (this.meta != null && this.meta.mergeEqual(namespace, localName, qName, attributes))
{
Meta child = this.meta;
this.meta = null;
return child;
}
if (this.body != null && this.body.mergeEqual(namespace, localName, qName, attributes))
{
Body child = this.body;
this.body = null;
return child;
}
if (this.options != null && this.options.mergeEqual(namespace, localName, qName, attributes))
{
Options options = this.options;
this.options = null;
return options;
}
return null;
}
/**
* Notify the element that this document is being merged.
*
* @return The attributes for this merged element
*/
public Attributes merge(Attributes attributes) throws SAXException,
WingException
{
this.merged = true;
return attributes;
}
/**
* Translate this document to SAX events.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces)
throws SAXException
{
if (!this.merged)
{
AttributeMap attributes = new AttributeMap();
attributes.put(A_VERSION, DOCUMENT_VERSION);
startElement(contentHandler, namespaces, E_DOCUMENT, attributes);
}
if (this.meta != null)
{
meta.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (this.body != null)
{
body.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (this.options != null)
{
options.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (!this.merged)
{
endElement(contentHandler, namespaces, E_DOCUMENT);
}
}
/**
* dispose
*/
public void dispose()
{
if (this.meta != null)
{
meta.dispose();
}
if (this.body != null)
{
body.dispose();
}
if (this.options != null)
{
options.dispose();
}
this.meta = null;
this.body = null;
this.options = null;
super.dispose();
}
//
// /**
// * Check the version string and make sure the given version is within the
// * minimum and maximum allowed document version. If it is out side these
// * bounds then a WingException is thrown.
// *
// * @param version
// * The DRI version to test against.
// */
// private void checkVersionString(String version) throws WingException
// {
// try
// {
// double version_double = Double.valueOf(version);
// if (version_double < DOCUMENT_VERSION_MINIMUM
// || version_double >= DOCUMENT_VERSION_MAXIMUM)
// throw new WingException(
// "Incomptable DRI document merge, unable to merge '"
// + version + "' into '"
// + DOCUMENT_VERSION_STRING + "'.");
// }
// catch (RuntimeException re)
// {
// throw new WingException(
// "Unable to verrify the DRI document version number.", re);
// }
// }
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
/**
* This class represents a figure element used to embed a reference to an image
* or graphic element. Any text within the element will be used as an
* alternative descriptor or a caption.
*
* @author Scott Phillips
*/
public class Figure extends TextContainer implements StructuralElement
{
/** The name of the figure element */
public static final String E_FIGURE = "figure";
/** The name of the source attribute */
public static final String A_SOURCE = "source";
/** The name of the target attribute */
public static final String A_TARGET = "target";
/** The figure's source */
private String source;
/** The figure's xref target */
private String target;
/** Special rendering hints */
private String rend;
/**
* Construct a new figure.
*
* @param context
* (Required) The context this element is contained in
* @param source
* (Required) The figure's image source.
* @param target
* (May be null) The figure's external reference, if present then
* the figure is also a link.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @throws WingException
*/
protected Figure(WingContext context, String source, String target,
String rend) throws WingException
{
super(context);
require(source, "The 'source' parameter is required for all figures.");
this.source = source;
this.target = target;
this.rend = rend;
}
/**
* Translate this element and all contained elements into SAX events. The
* events should be routed to the contentHandler found in the WingContext.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical
* events (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
NamespaceSupport namespaces) throws SAXException
{
AttributeMap attributes = new AttributeMap();
attributes.put(A_SOURCE, this.source);
if (this.target != null)
{
attributes.put(A_TARGET, this.target);
}
if (this.rend != null)
{
attributes.put(A_RENDER, this.rend);
}
startElement(contentHandler, namespaces, E_FIGURE, attributes);
super.toSAX(contentHandler, lexicalHandler, namespaces);
endElement(contentHandler, namespaces, E_FIGURE);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* A class representing a character container, such as "p", "hi", "item", or
* "cell"
*
* This class may not be instantiated on it's own instead you must use one of
* the extending classes listed above. This abstract class implements the
* methods common to each of those elements.
*
* @author Scott Phillips
*/
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
public abstract class RichTextContainer extends TextContainer
{
/**
* Construct a new rich text container.
*
* This method doesn't do anything but because the inheriting abstract class
* mandates a constructor for this class to compile it must ensure that the
* parent constructor is called. Just as implementors of this class must
* ensure that this constructor is called, thus is the chain of life. :)
*
* @param context
* (Required) The context this element is contained in.
*/
protected RichTextContainer(WingContext context) throws WingException
{
super(context);
}
/**
* Add highlighted content to the character container.
*
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return A new Highlight
*/
public Highlight addHighlight(String rend) throws WingException
{
Highlight highlight = new Highlight(context, rend);
contents.add(highlight);
return highlight;
}
/**
* Add a new reference to the character container. The xref element is a
* reference to an external document. The content will be used as part of
* the link's visual body.
*
* @param target
* (Required) A target URL for the references a destination for
* the xref.
*/
public Xref addXref(String target) throws WingException
{
Xref xref = new Xref(context, target);
contents.add(xref);
return xref;
}
/**
* Add a new reference to the character container. The xref element is a
* reference to an external document. The characters will be used as the
* visual part of the link's body
*
* @param target
* (Required) A target URL for the references a destination for
* the xref.
* @param characters
* (May be null) The link's body
*/
public void addXref(String target, String characters) throws WingException
{
Xref xref = addXref(target);
xref.addContent(characters);
}
/**
* Add a new reference to the character container. The xref element is a
* reference to an external document. The characters will be used as the
* visual part of the link's body
*
* @param target
* (Required) A target URL for the references a destination for
* the xref.
* @param characters
* (May be null) The link's body
* @param rend
* (May be null) Special rendering instructions.
*/
public void addXref(String target, String characters, String rend) throws WingException
{
Xref xref = new Xref(context, target, rend);
xref.addContent(characters);
contents.add(xref);
}
/**
* Add a new reference to the character container. The xref element is a
* reference to an external document. The characters will be used as the
* visual part of the link's body
*
* @param target
* (Required) A target URL for the references a destination for
* the xref.
* @param characters
* (May be null) The link's body
* @param rend
* (May be null) Special rendering instructions.
* @param name
* (May be null) local identifier
*/
public void addXref(String target, String characters, String rend, String name) throws WingException
{
Xref xref = new Xref(context, target, rend, name);
xref.addContent(characters);
contents.add(xref);
}
/**
* Add a new reference to the character container. The xref element is a
* reference to an external document. The translated i18n key will be used
* as the visual part of the link's body
*
* @param target
* (Required) A target URL for the references a destination for
* the xref.
* @param key
* (Required) The link's body
*/
public void addXref(String target, Message key) throws WingException
{
Xref xref = addXref(target);
xref.addContent(key);
}
/**
* Add a new reference to the character container. The xref element is a
* reference to an external document. The translated i18n key will be used
* as the visual part of the link's body
*
* @param target
* (Required) A target URL for the references a destination for
* the xref.
* @param key
* (Required) The link's body
* @param rend
* (May be null) Special rendering instructions
*/
public void addXref(String target, Message key, String rend) throws WingException
{
Xref xref = new Xref(context, target, rend);
xref.addContent(key);
contents.add(xref);
}
/**
* Add a new reference to the character container. The xref element is a
* reference to an external document. The translated i18n key will be used
* as the visual part of the link's body
*
* @param target
* (Required) A target URL for the references a destination for
* the xref.
* @param key
* (Required) The link's body
* @param rend
* (May be null) Special rendering instructions
*/
public void addXref(String target, Message key, String rend, String name) throws WingException
{
Xref xref = new Xref(context, target, rend, name);
xref.addContent(key);
contents.add(xref);
}
/**
* Add a figure element to the character container.
*
* The figure element is used to embed a reference to an image or a graphic
* element. The content of a figure will be use as an alternative descriptor
* or a caption.
*
* @param source
* (Required) The source for the image, using a URL or a
* pre-defined XML entity.
* @param target
* (May be null) The target reference for the image if the image
* is to operate as a link.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
public Figure addFigure(String source, String target, String rend)
throws WingException
{
Figure figure = new Figure(context, source, target, rend);
contents.add(figure);
return figure;
}
/**
* Add a button input control that when activated by the user will submit
* the form, including all the fields, back to the server for processing.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return A new button field.
*/
public Button addButton(String name, String rend) throws WingException
{
Button button = new Button(context, name, rend);
contents.add(button);
return button;
}
/**
* Add a button input control that when activated by the user will submit
* the form, including all the fields, back to the server for processing.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return a new button field
*/
public Button addButton(String name) throws WingException
{
return addButton(name, null);
}
/**
* Add a boolean input control which may be toggled by the user. A checkbox
* may have several fields which share the same name and each of those
* fields may be toggled independently. This is distinct from a radio button
* where only one field may be toggled.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new checkbox field
*/
public CheckBox addCheckBox(String name, String rend) throws WingException
{
CheckBox checkbox = new CheckBox(context, name, rend);
contents.add(checkbox);
return checkbox;
}
/**
* Add a boolean input control which may be toggled by the user. A checkbox
* may have several fields which share the same name and each of those
* fields may be toggled independently. This is distinct from a radio button
* where only one field may be toggled.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return A new checkbox field
*/
public CheckBox addCheckBox(String name) throws WingException
{
return addCheckBox(name, null);
}
/**
* Add a composite input control. Composite controls are composed of multiple
* individual input controls that combine to form a single value. Example, a
* composite field might be used to represent a name which is broken up into
* first and last names. In this case there would be a composite field that
* consists of two text fields.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new composite field.
*/
public Composite addComposite(String name, String rend) throws WingException
{
Composite composite = new Composite(context, name, rend);
contents.add(composite);
return composite;
}
/**
* Add a composite input control. Composite controls are composed of multiple
* individual input controls that combine to form a single value. Example, a
* composite field might be used to represent a name which is broken up into
* first and last names. In this case there would be a composite field that
* consists of two text fields.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* @return a new composite field.
*/
public Composite addComposite(String name) throws WingException
{
return addComposite(name, null);
}
/**
* Add an input control that allows the user to select files to be submitted
* with the form. Note that a form which uses a file field must use the
* multipart method.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return A new file field
*/
public File addFile(String name, String rend) throws WingException
{
File file = new File(context, name, rend);
contents.add(file);
return file;
}
/**
* Add an input control that allows the user to select files to be submitted
* with the form. Note that a form which uses a file field must use the
* multipart method.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return a new file field
*/
public File addFile(String name) throws WingException
{
return addFile(name, null);
}
/**
* Add an input control that is not rendered on the screen and hidden from
* the user.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new hidden field
*/
public Hidden addHidden(String name, String rend) throws WingException
{
Hidden hidden = new Hidden(context, name, rend);
contents.add(hidden);
return hidden;
}
/**
* Add an input control that is not rendered on the screen and hidden from
* the user.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return
*/
public Hidden addHidden(String name) throws WingException
{
return addHidden(name, null);
}
/**
* Add a single-line text input control where the input text is rendered in
* such a way as to hide the characters from the user.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return A new password field
*/
public Password addPassword(String name, String rend) throws WingException
{
Password password = new Password(context, name, rend);
contents.add(password);
return password;
}
/**
* Add a single-line text input control where the input text is rendered in
* such a way as to hide the characters from the user.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return a new password field
*/
public Password addPassword(String name) throws WingException
{
return addPassword(name, null);
}
/**
* Add a boolean input control which may be toggled by the user. Multiple
* radio button fields may share the same name. When this occurs only one
* field may be selected to be true. This is distinct from a checkbox where
* multiple fields may be toggled.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new radio field.
*/
public Radio addRadio(String name, String rend) throws WingException
{
Radio radio = new Radio(context, name, rend);
contents.add(radio);
return radio;
}
/**
* Add a boolean input control which may be toggled by the user. Multiple
* radio button fields may share the same name. When this occurs only one
* field may be selected to be true. This is distinct from a checkbox where
* multiple fields may be toggled.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
*
* @return a new radio field
*/
public Radio addRadio(String name) throws WingException
{
return addRadio(name, null);
}
/**
* Add a menu input control which allows the user to select from a list of
* available options.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new select field
*/
public Select addSelect(String name, String rend) throws WingException
{
Select select = new Select(context, name, rend);
contents.add(select);
return select;
}
/**
* Add a menu input control which allows the user to select from a list of
* available options.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return a new select field
*/
public Select addSelect(String name) throws WingException
{
return addSelect(name, null);
}
/**
* Add a single-line text input control.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return A new text field
*/
public Text addText(String name, String rend) throws WingException
{
Text text = new Text(context, name, rend);
contents.add(text);
return text;
}
/**
* Add a single-line text input control.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return a new text field
*/
public Text addText(String name) throws WingException
{
return addText(name, null);
}
/**
* Add a multi-line text input control.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
* @return a new text area field
*/
public TextArea addTextArea(String name, String rend) throws WingException
{
TextArea textarea = new TextArea(context, name, rend);
contents.add(textarea);
return textarea;
}
/**
* Add a multi-line text input control.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @return a new text area field
*/
public TextArea addTextArea(String name) throws WingException
{
return addTextArea(name, null);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* This class represents a generic Wing Container. The Container class adds a
* simlpe contents list which may be modified by the extending concret classes.
* When it comes time to process the element a toSAX method is provided that
* will iterate over the contents.
*
* @author Scott Phillips
*/
import java.util.ArrayList;
import java.util.List;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
public abstract class Container extends AbstractWingElement
{
/** The internal contents of this container */
protected List<AbstractWingElement> contents = new ArrayList<AbstractWingElement>();
/**
* @param context
* (Required) The context this element is contained in.
*/
protected Container(WingContext context) throws WingException
{
super(context);
}
/**
* Translate this element and all contained elements into SAX events. The
* events should be routed to the contentHandler found in the WingContext.
*
* This method does not create an inclosing block, the implementors of
* container class need to implement a method of toSAX() that provides the
* surrounding element block for that specific application.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical events
* (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler,
LexicalHandler lexicalHandler, NamespaceSupport namespaces)
throws SAXException
{
for (AbstractWingElement content : contents)
{
content.toSAX(contentHandler, lexicalHandler, namespaces);
}
}
/**
* Dispose
*/
public void dispose()
{
if (this.contents != null)
{
for (AbstractWingElement element : contents)
{
element.dispose();
}
this.contents.clear();
}
this.contents = null;
super.dispose();
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.wing.element;
/**
* A class representing an an abstract input control (which is just a fancy name
* for a field :) )
*
* The field element is a container for all information necessary to create a
* form field. The required "type" attribute determines the type of the field,
* while the children tags carry the information on how to build it. Fields can
* only occur in divisions of type "interactive".
*
* There are several types of possible fields and each of these field types
* determine the appropriate parameters on the parameter object. This is the
* only place in the schema where this design pattern is used. It limits the
* proliferation of elements, such as a special element for textarea, select
* lists, text fields etc... as HTML does. It also forces us to treat all fields
* the same.
*
* text: A single-line text input control.
*
* textarea: A multi-line text input control.
*
* password: A single-line text input control where the input text is rendered
* in such a way as to hide the characters from the user.
*
* hidden: An input control that is not rendered on the screen and hidden from
* the user.
*
* button: A button input control that when activated by the user will submit
* the form, including all the fields, back to the server for processing.
*
* checkbox: A boolean input control which may be toggled by the user. A
* checkbox may have several fields which share the same name and each of those
* fields may be toggled independently. This is distinct from a radio button
* where only one field may be toggled.
*
* file: An input control that allows the user to select files to be submitted
* with the form. Note that a form which uses a file field must use the
* multipart method.
*
* radio: A boolean input control which may be toggled by the user. Multiple
* radio button fields may share the same name. When this occurs only one field
* may be selected to be true. This is distinct from a checkbox where multiple
* fields may be toggled.
*
* select: A menu input control which allows the user to select from a list of
* available options.
*
* composite: A combination of multile fields into one input control.
*
* @author Scott Phillips
*/
import java.util.ArrayList;
import java.util.List;
import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;
public abstract class Field extends AbstractWingElement implements
StructuralElement
{
/** The name of the field element */
public static final String E_FIELD = "field";
/** The name of the field type attribute */
public static final String A_FIELD_TYPE = "type";
/** The name of the disabled attribute */
public static final String A_DISABLED = "disabled";
/** The name of the required attribute */
public static final String A_REQUIRED = "required";
/** The possible field types */
public static final String TYPE_BUTTON = "button";
public static final String TYPE_CHECKBOX = "checkbox";
public static final String TYPE_FILE = "file";
public static final String TYPE_HIDDEN = "hidden";
public static final String TYPE_PASSWORD = "password";
public static final String TYPE_RADIO = "radio";
public static final String TYPE_SELECT = "select";
public static final String TYPE_TEXT = "text";
public static final String TYPE_TEXTAREA = "textarea";
public static final String TYPE_COMPOSITE = "composite";
/** All the possible field types collected into one array. */
public static final String[] TYPES = { TYPE_BUTTON, TYPE_CHECKBOX,
TYPE_FILE, TYPE_HIDDEN, TYPE_PASSWORD, TYPE_RADIO, TYPE_SELECT,
TYPE_TEXT, TYPE_TEXTAREA, TYPE_COMPOSITE };
/** Possible field behavioral operations */
public static final String OPERATION_ADD = "add";
public static final String OPERATION_DELETE = "delete";
public static final String[] OPERATIONS = {OPERATION_ADD, OPERATION_DELETE};
/** The field's name */
protected String name;
/** The type of field, see TYPES above */
protected String type;
/** Weather this field is disabled */
protected boolean disabled;
/** Weather this field is required */
protected boolean required;
/** Any special rendering instructions */
protected String rend;
/** Additional field parameters */
protected Params params;
/** The fields Label */
protected Label label;
/** Help instructions for this field */
protected Help help;
/** Error instructions for this field */
protected List<Error> errors = new ArrayList<Error>();
/** All sub fields contained within a composite field */
protected List<Field> fields = new ArrayList<Field>();
/** The value of this field */
protected List<Option> options = new ArrayList<Option>();
/** The value of this field */
protected List<Value> values = new ArrayList<Value>();
/** The set of stored values */
protected List<Instance> instances = new ArrayList<Instance>();
/**
* Construct a new field.
*
* @param context
* (Required) The context this element is contained in, such as
* where to route SAX events and what i18n catalogue to use.
*
* @param name
* (Required) a non-unique local identifier used to differentiate
* the element from its siblings within an interactive division.
* This is the name of the field use when data is submitted back
* to the server.
* @param type
* (Required) Specify the type of field, must be one of the field
* types defined in the static variable TYPES.
* @param rend
* (May be null) a rendering hint used to override the default
* display of the element.
*/
protected Field(WingContext context, String name, String type,
String rend) throws WingException
{
super(context);
require(name, "The 'name' parameter is required for all fields.");
require(type, "The 'type' parameter is required for all fields.");
restrict(
type,
TYPES,
"The 'type' parameter must be one of these values: 'button', 'checkbox', 'file', 'hidden', 'password', 'radio', 'select', 'text', 'textarea'.");
this.name = name;
this.type = type;
this.disabled = false;
this.required = false;
this.rend = rend;
}
/** Parameters available on all fields */
/**
* Set this field as required.
*/
public void setRequired()
{
this.required = true;
}
/**
* Set this field to either be required or not required as determined by the
* required parameter.
*
* @param required
* Determine if the field is required or not.
*/
public void setRequired(boolean required)
{
this.required = required;
}
/**
* Set this field to be disabled.
*
*/
public void setDisabled()
{
this.disabled = true;
}
/**
* Set this field to either be disabled or enabled as determined by the
* disabled parameter.
*
* @param disabled
* Determine if the field is required or not.
*/
public void setDisabled(boolean disabled)
{
this.disabled = disabled;
}
/**
* Set this field to be authority-controlled.
*
*/
public void setAuthorityControlled()
{
this.params.setAuthorityControlled(true);
}
/**
* Set this field to be authority-controlled.
*
* @param value true if field is authority-controlled.
*/
public void setAuthorityControlled(boolean value)
{
this.params.setAuthorityControlled(value);
}
/**
* Set this field as authority_required.
*/
public void setAuthorityRequired()
{
this.params.setAuthorityRequired();
}
/**
* Set this field to either be required or not required as determined by the
* required parameter.
*
* @param value
* Determine if the authority control is required or not on this field.
*/
public void setAuthorityRequired(boolean value)
{
this.params.setAuthorityRequired(value);
}
/**
* Declare that this field has a value to be chosen from a choice
* provider (see ChoicesManager). Value is a metadata field key
* naming the field whose choices to use.
*
* @param fieldKey pre-determined metadata field key
*/
public void setChoices(String fieldKey)
{
params.setChoices(fieldKey);
}
/**
* Set the kind of UI presentation requested for this choice, e.g.
* select vs. suggest. Value must match one of the PRESENTATIONS.
*
* @param value pre-determined metadata field key
*/
public void setChoicesPresentation(String value)
throws WingException
{
params.setChoicesPresentation(value);
}
/**
* Set whether set of choices is "closed" to just the values
* in menu, or allows arbitrary user-supplied values.
*
* @param value true if it is closed
*/
public void setChoicesClosed(boolean value)
{
params.setChoicesClosed(value);
}
public void setChoicesClosed()
{
params.setChoicesClosed();
}
/** ******************************************************************** */
/** Help * */
/** ******************************************************************** */
/**
* The help element provides help instructions to assist the user in using
* this field.
*
*/
public Help setHelp() throws WingException
{
this.help = new Help(context);
return this.help;
}
/**
* The help element provides help instructions to assist the user in using
* this field.
*
* @param characters
* (May be null) Direct content or a dictionary tag to be
* inserted into the element.
*/
public void setHelp(String characters) throws WingException
{
this.help = new Help(context);
this.help.addContent(characters);
}
/**
* The help element provides help instructions to assist the user in using
* this field.
*
* @param message
* (Required) A key into the i18n catalogue for translation into
* the user's preferred language.
*/
public void setHelp(Message message) throws WingException
{
this.help = new Help(context);
this.help.addContent(message);
}
/** ******************************************************************** */
/** Errors * */
/** ******************************************************************** */
/**
* The error elements denotes that the fields value is invalid for the given
* context. The message contained within the error message will provide
* assistance to the user in correcting the problem.
*
*/
public Error addError() throws WingException
{
Error error = new Error(context);
errors.add(error);
return error;
}
/**
* The error elements denotes that the fields value is invalid for the given
* context. The message contained within the error message will provide
* assistance to the user in correcting the problem.
*
* @param characters
* (May be null) Direct content or a dictionary tag to be
* inserted into the element.
*/
public void addError(String characters) throws WingException
{
Error error = new Error(context);
error.addContent(characters);
errors.add(error);
}
/**
* The error elements denotes that the fields value is invalid for the given
* context. The message contained within the error message will provide
* assistance to the user in correcting the problem.
*
* @param message
* (Required) A key into the i18n catalogue for translation into
* the user's preferred language.
*/
public void addError(Message message) throws WingException
{
Error error = new Error(context);
error.addContent(message);
errors.add(error);
}
/** ******************************************************************** */
/** Label * */
/** ******************************************************************** */
/**
* The help element provides help instructions to assist the user in using
* this field.
*
*/
public Label setLabel() throws WingException
{
this.label = new Label(context,null,null);
return this.label;
}
/**
* The help element provides help instructions to assist the user in using
* this field.
*
* @param characters
* (May be null) Direct content or a dictionary tag to be
* inserted into the element.
*/
public void setLabel(String characters) throws WingException
{
this.label = new Label(context,null,null);
this.label.addContent(characters);
}
/**
* The help element provides help instructions to assist the user in using
* this field.
*
* @param message
* (Required) A key into the i18n catalogue for translation into
* the user's preferred language.
*/
public void setLabel(Message message) throws WingException
{
this.label = new Label(context,null,null);
this.label.addContent(message);
}
/**
* Private function to remove all values of a particular type.
*
* @param removeType
* The type to be removed.
*/
protected void removeValueOfType(String removeType)
{
List<Value> found = new ArrayList<Value>();
for (Value value : values)
{
if (value.getType().equals(removeType))
{
found.add(value);
}
}
for (Value remove : found)
{
values.remove(remove);
remove.dispose();
}
}
/**
* Translate this element and all contained elements into SAX events. The
* events should be routed to the contentHandler found in the WingContext.
*
* @param contentHandler
* (Required) The registered contentHandler where SAX events
* should be routed too.
* @param lexicalHandler
* (Required) The registered lexicalHandler where lexical events
* (such as CDATA, DTD, etc) should be routed too.
* @param namespaces
* (Required) SAX Helper class to keep track of namespaces able
* to determine the correct prefix for a given namespace URI.
*/
public void toSAX(ContentHandler contentHandler,
LexicalHandler lexicalHandler, NamespaceSupport namespaces)
throws SAXException
{
AttributeMap attributes = new AttributeMap();
attributes.put(A_NAME, this.name);
attributes.put(A_ID, this.context.generateID(E_FIELD, this.name));
attributes.put(A_FIELD_TYPE, this.type);
if (this.disabled)
{
attributes.put(A_DISABLED, this.disabled);
}
if (this.required)
{
attributes.put(A_REQUIRED, this.required);
}
if (this.rend != null)
{
attributes.put(A_RENDER, this.rend);
}
startElement(contentHandler, namespaces, E_FIELD, attributes);
if (params != null)
{
params.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (label != null)
{
label.toSAX(contentHandler, lexicalHandler, namespaces);
}
if (help != null)
{
help.toSAX(contentHandler, lexicalHandler, namespaces);
}
for (Error error : errors)
{
error.toSAX(contentHandler, lexicalHandler, namespaces);
}
for (Field field : fields)
{
field.toSAX(contentHandler, lexicalHandler, namespaces);
}
for (Option option : options)
{
option.toSAX(contentHandler, lexicalHandler, namespaces);
}
for (Value value : values)
{
value.toSAX(contentHandler, lexicalHandler, namespaces);
}
for (Instance instance : instances)
{
instance.toSAX(contentHandler, lexicalHandler, namespaces);
}
endElement(contentHandler, namespaces, E_FIELD);
}
/**
* Dispose
*/
public void dispose()
{
if (params != null)
{
params.dispose();
}
if (label != null)
{
label.dispose();
}
if (help != null)
{
help.dispose();
}
if (errors != null)
{
for (Error error : errors)
{
error.dispose();
}
errors.clear();
}
if (fields != null)
{
for (Field field : fields)
{
field.dispose();
}
fields.clear();
}
if (options != null)
{
for (Option option : options)
{
option.dispose();
}
options.clear();
}
if (values != null)
{
for (Value value : values)
{
value.dispose();
}
values.clear();
}
if (instances != null)
{
for (Instance instance : instances)
{
instance.dispose();
}
instances.clear();
}
params = null;
label = null;
help = null;
errors = null;
fields = null;
options = null;
values = null;
instances = null;
super.dispose();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.