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.administrative.authorization;
import java.sql.SQLException;
import java.util.ArrayList;
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.Cell;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Highlight;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.eperson.Group;
/**
* @author Alexey Maslov
*/
public class EditItemPolicies extends AbstractDSpaceTransformer
{
private static final Message T_title =
message("xmlui.administrative.authorization.EditItemPolicies.title");
private static final Message T_policyList_trail =
message("xmlui.administrative.authorization.general.policyList_trail");
private static final Message T_authorize_trail =
message("xmlui.administrative.authorization.general.authorize_trail");
private static final Message T_main_head =
message("xmlui.administrative.authorization.EditItemPolicies.main_head");
private static final Message T_main_para1 =
message("xmlui.administrative.authorization.EditItemPolicies.main_para1");
private static final Message T_main_para2 =
message("xmlui.administrative.authorization.EditItemPolicies.main_para2");
private static final Message T_subhead_item =
message("xmlui.administrative.authorization.EditItemPolicies.subhead_item");
private static final Message T_subhead_bundle =
message("xmlui.administrative.authorization.EditItemPolicies.subhead_bundle");
private static final Message T_subhead_bitstream =
message("xmlui.administrative.authorization.EditItemPolicies.subhead_bitstream");
private static final Message T_add_itemPolicy_link =
message("xmlui.administrative.authorization.EditItemPolicies.add_itemPolicy_link");
private static final Message T_add_bundlePolicy_link =
message("xmlui.administrative.authorization.EditItemPolicies.add_bundlePolicy_link");
private static final Message T_add_bitstreamPolicy_link =
message("xmlui.administrative.authorization.EditItemPolicies.add_bitstreamPolicy_link");
private static final Message T_head_id =
message("xmlui.administrative.authorization.EditContainerPolicies.head_id");
private static final Message T_head_action =
message("xmlui.administrative.authorization.EditContainerPolicies.head_action");
private static final Message T_head_group =
message("xmlui.administrative.authorization.EditContainerPolicies.head_group");
private static final Message T_group_edit =
message("xmlui.administrative.authorization.EditContainerPolicies.group_edit");
private static final Message T_submit_delete =
message("xmlui.administrative.authorization.EditContainerPolicies.submit_delete");
private static final Message T_submit_return =
message("xmlui.general.return");
private static final Message T_no_policies =
message("xmlui.administrative.authorization.EditContainerPolicies.no_policies");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/authorize", T_authorize_trail);
pageMeta.addTrail().addContent(T_policyList_trail);
}
public void addBody(Body body) throws WingException, SQLException
{
/* Get and setup our parameters */
int itemID = parameters.getParameterAsInteger("itemID",-1);
int highlightID = parameters.getParameterAsInteger("highlightID",-1);
String baseURL = contextPath+"/admin/epeople?administrative-continue="+knot.getId();
/* First, set up our various data structures */
Item item = Item.find(context, itemID);
Bundle[] bundles = item.getBundles();
Bitstream[] bitstreams;
ArrayList<ResourcePolicy> itemPolicies = (ArrayList<ResourcePolicy>)AuthorizeManager.getPolicies(context, item);
// DIVISION: main
Division main = body.addInteractiveDivision("edit-item-policies",contextPath+"/admin/authorize",Division.METHOD_POST,"primary administrative authorization");
main.setHead(T_main_head.parameterize(item.getHandle(),item.getID()));
main.addPara().addHighlight("italic").addContent(T_main_para1);
main.addPara().addHighlight("italic").addContent(T_main_para2);
Table table = main.addTable("policies-confirm-delete",itemPolicies.size() + 3, 5);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell();
header.addCell().addContent(T_head_id);
header.addCell().addContent(T_head_action);
header.addCell().addContent(T_head_group);
header.addCell();
// First, the item's policies are listed
Row subheader = table.addRow(null,Row.ROLE_HEADER,"subheader");
subheader.addCell(1, 4).addHighlight("bold").addContent(T_subhead_item);
subheader.addCell().addHighlight("bold").addXref(baseURL + "&submit_add_item", T_add_itemPolicy_link);
this.rowBuilder(baseURL, table, itemPolicies, item.getID(), Constants.ITEM, highlightID);
// Next, one by one, we get the bundles
for (Bundle bundle : bundles) {
subheader = table.addRow(null,Row.ROLE_HEADER,"subheader");
subheader.addCell(null, null, 1, 4, "indent").addHighlight("bold").addContent(T_subhead_bundle.parameterize(bundle.getName(),bundle.getID()));
subheader.addCell().addHighlight("bold").addXref(baseURL + "&submit_add_bundle_" + bundle.getID(), T_add_bundlePolicy_link);
ArrayList<ResourcePolicy> bundlePolicies = (ArrayList<ResourcePolicy>)AuthorizeManager.getPolicies(context, bundle);
this.rowBuilder(baseURL, table, bundlePolicies, bundle.getID(), Constants.BUNDLE, highlightID);
// And eventually to the bundle's bitstreams
bitstreams = bundle.getBitstreams();
for (Bitstream bitstream : bitstreams) {
subheader = table.addRow(null,Row.ROLE_HEADER,"subheader");
subheader.addCell(null, null, 1, 4, "doubleIndent").addContent(T_subhead_bitstream.parameterize(bitstream.getName(),bitstream.getID()));
subheader.addCell().addXref(baseURL + "&submit_add_bitstream_" + bitstream.getID(), T_add_bitstreamPolicy_link);
ArrayList<ResourcePolicy> bitstreamPolicies = (ArrayList<ResourcePolicy>)AuthorizeManager.getPolicies(context, bitstream);
this.rowBuilder(baseURL, table, bitstreamPolicies, bitstream.getID(), Constants.BITSTREAM, highlightID);
}
}
Para buttons = main.addPara();
buttons.addButton("submit_delete").setValue(T_submit_delete);
buttons.addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-continue").setValue(knot.getId());
}
private void rowBuilder(String baseURL, Table table, java.util.List<ResourcePolicy> policies, int objectID, int objectType, int highlightID) throws WingException, SQLException
{
// If the list of policies is empty, say so
if (policies == null || policies.size() == 0) {
table.addRow().addCell(1, 4).addHighlight("italic").addContent(T_no_policies);
}
// Otherwise, iterate over the given policies, creating a new table row for each one
else {
for (ResourcePolicy policy : policies)
{
Row row;
if (policy.getID() == highlightID)
{
row = table.addRow(null, null, "highlight");
}
else
{
row = table.addRow();
}
Cell cell;
if (objectType == Constants.BUNDLE)
{
cell = row.addCell(null, null, "indent");
}
else if (objectType == Constants.BITSTREAM)
{
cell = row.addCell(null, null, "doubleIndent");
}
else
{
cell = row.addCell();
}
CheckBox select = cell.addCheckBox("select_policy");
select.setLabel(String.valueOf(policy.getID()));
select.addOption(String.valueOf(policy.getID()));
// Accounting for the funky case of an empty policy
Group policyGroup = policy.getGroup();
row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + policy.getID() +
"&object_id=" + objectID + "&object_type=" + objectType, String.valueOf(policy.getID()));
row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + policy.getID() +
"&object_id=" + objectID + "&object_type=" + objectType, policy.getActionText());
if (policyGroup != null) {
Cell groupCell = row.addCell(1,2);
groupCell.addContent(policyGroup.getName());
Highlight groupHigh = groupCell.addHighlight("fade");
groupHigh.addContent(" [");
groupHigh.addXref(baseURL + "&submit_edit_group&group_id=" + policyGroup.getID(), T_group_edit);
groupHigh.addContent("]");
}
else {
row.addCell(1,2).addContent("...");
}
}
}
}
}
| 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.administrative.authorization;
import java.sql.SQLException;
import java.util.ArrayList;
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.Cell;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Highlight;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.Constants;
import org.dspace.eperson.Group;
/**
* @author Alexey Maslov
*/
public class EditContainerPolicies extends AbstractDSpaceTransformer
{
private static final Message T_title =
message("xmlui.administrative.authorization.EditContainerPolicies.title");
private static final Message T_policyList_trail =
message("xmlui.administrative.authorization.general.policyList_trail");
private static final Message T_authorize_trail =
message("xmlui.administrative.authorization.general.authorize_trail");
private static final Message T_main_head_collection =
message("xmlui.administrative.authorization.EditContainerPolicies.main_head_collection");
private static final Message T_main_head_community =
message("xmlui.administrative.authorization.EditContainerPolicies.main_head_community");
private static final Message T_add_link =
message("xmlui.administrative.authorization.EditContainerPolicies.main_add_link");
private static final Message T_head_id =
message("xmlui.administrative.authorization.EditContainerPolicies.head_id");
private static final Message T_head_action =
message("xmlui.administrative.authorization.EditContainerPolicies.head_action");
private static final Message T_head_group =
message("xmlui.administrative.authorization.EditContainerPolicies.head_group");
private static final Message T_group_edit =
message("xmlui.administrative.authorization.EditContainerPolicies.group_edit");
private static final Message T_submit_delete =
message("xmlui.administrative.authorization.EditContainerPolicies.submit_delete");
private static final Message T_submit_return =
message("xmlui.general.return");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/authorize", T_authorize_trail);
pageMeta.addTrail().addContent(T_policyList_trail);
}
public void addBody(Body body) throws WingException, SQLException
{
/* Get and setup our parameters */
int containerType = parameters.getParameterAsInteger("containerType",-1);
int containerID = parameters.getParameterAsInteger("containerID",-1);
int highlightID = parameters.getParameterAsInteger("highlightID",-1);
String baseURL = contextPath+"/admin/epeople?administrative-continue="+knot.getId();
ArrayList<ResourcePolicy> policies;
// DIVISION: edit-container-policies
Division main = body.addInteractiveDivision("edit-container-policies",contextPath+"/admin/authorize",Division.METHOD_POST,"primary administrative authorization");
if (containerType == Constants.COLLECTION)
{
Collection col = Collection.find(context, containerID);
main.setHead(T_main_head_collection.parameterize(col.getMetadata("name"),col.getHandle(),col.getID()));
policies = (ArrayList<ResourcePolicy>)AuthorizeManager.getPolicies(context, col);
}
else
{
Community com = Community.find(context, containerID);
main.setHead(T_main_head_community.parameterize(com.getMetadata("name"),com.getHandle(),com.getID()));
policies = (ArrayList<ResourcePolicy>)AuthorizeManager.getPolicies(context, com);
}
/* Adding a new policy link */
main.addPara().addXref(baseURL + "&submit_add", T_add_link);
Table table = main.addTable("container-policy-list",policies.size() + 1, 4);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell();
header.addCell().addContent(T_head_id);
header.addCell().addContent(T_head_action);
header.addCell().addContent(T_head_group);
if (policies != null)
{
for (ResourcePolicy policy : policies)
{
Row row;
if (policy.getID() == highlightID)
{
row = table.addRow(null, null, "highlight");
}
else
{
row = table.addRow();
}
CheckBox select = row.addCell().addCheckBox("select_policy");
select.setLabel(String.valueOf(policy.getID()));
select.addOption(String.valueOf(policy.getID()));
// Accounting for the funky case of an empty policy
Group policyGroup = policy.getGroup();
row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + policy.getID(), String.valueOf(policy.getID()));
row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + policy.getID(), policy.getActionText());
if (policyGroup != null) {
Cell groupCell = row.addCell();
groupCell.addContent(policyGroup.getName());
Highlight groupHigh = groupCell.addHighlight("fade");
groupHigh.addContent(" [");
groupHigh.addXref(baseURL + "&submit_edit_group&group_id=" + policyGroup.getID(), T_group_edit);
groupHigh.addContent("]");
}
else {
row.addCell().addContent("...");
}
}
}
Para buttons = main.addPara();
buttons.addButton("submit_delete").setValue(T_submit_delete);
buttons.addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-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.administrative.authorization;
import java.sql.SQLException;
import java.util.ArrayList;
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.dspace.content.Collection;
import org.dspace.content.Community;
/**
* @author Alexey Maslov
*/
public class AuthorizationMain extends AbstractDSpaceTransformer
{
private static final Message T_title =
message("xmlui.administrative.authorization.AuthorizationMain.title");
private static final Message T_authorize_trail =
message("xmlui.administrative.authorization.general.authorize_trail");
private static final Message T_main_head =
message("xmlui.administrative.authorization.AuthorizationMain.main_head");
private static final Message T_actions_head =
message("xmlui.administrative.authorization.AuthorizationMain.actions_head");
private static final Message T_actions_item_lookup =
message("xmlui.administrative.authorization.AuthorizationMain.actions_item_lookup");
private static final Message T_bad_name =
message("xmlui.administrative.authorization.AuthorizationMain.bad_name");
private static final Message T_search_help =
message("xmlui.administrative.authorization.AuthorizationMain.search_help");
private static final Message T_submit_find =
message("xmlui.administrative.authorization.AuthorizationMain.submit_find");
private static final Message T_actions_advanced =
message("xmlui.administrative.authorization.AuthorizationMain.actions_advanced");
private static final Message T_actions_advanced_link =
message("xmlui.administrative.authorization.AuthorizationMain.actions_advanced_link");
private static final Message T_containerList_head =
message("xmlui.administrative.authorization.AuthorizationMain.containerList_head");
private static final Message T_containerList_para =
message("xmlui.administrative.authorization.AuthorizationMain.containerList_para");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_untitled =
message("xmlui.general.untitled");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/authorize", T_authorize_trail);
}
public void addBody(Body body) throws WingException, SQLException
{
/* Get and setup our parameters */
String query = decodeFromURL(parameters.getParameter("query",null));
String baseURL = contextPath+"/admin/epeople?administrative-continue="+knot.getId();
String errorString = parameters.getParameter("errors",null);
ArrayList<String> errors = new ArrayList<String>();
if (errorString != null)
{
for (String error : errorString.split(","))
{
errors.add(error);
}
}
Division main = body.addInteractiveDivision("authorization-main",contextPath+"/admin/authorize",Division.METHOD_POST,"primary administrative authorization");
main.setHead(T_main_head);
//main.addPara(T_main_para);
// DIVISION: authorization-actions
Division actions = main.addDivision("authorization-actions");
actions.setHead(T_actions_head);
List actionsList = actions.addList("actions");
actionsList.addLabel(T_actions_item_lookup);
Item actionItem = actionsList.addItem();
Text queryField = actionItem.addText("identifier");
if (query != null)
{
queryField.setValue(query);
}
if (errors.contains("identifier"))
{
queryField.addError(T_bad_name);
}
queryField.setHelp(T_search_help);
actionItem.addButton("submit_edit").setValue(T_submit_find);
actionsList.addLabel(T_actions_advanced);
actionsList.addItemXref(baseURL+"&submit_wildcard", T_actions_advanced_link);
// DIVISION: authorization-containerList
Division containers = main.addDivision("authorization-containerList");
containers.setHead(T_containerList_head);
containers.addPara(T_containerList_para);
List containerList = containers.addList("containerList");
this.containerListBuilder(baseURL,containerList,null);
main.addHidden("administrative-continue").setValue(knot.getId());
}
/* A recursive helper method to build the community/collection hierarchy list */
private void containerListBuilder (String baseURL, List parentList, Community currentCommunity)
throws SQLException, WingException
{
if (currentCommunity == null) {
for (Community topLevel : Community.findAllTop(context)) {
containerListBuilder(baseURL,parentList,topLevel);
}
}
else {
parentList.addItem().addHighlight("bold").addXref(baseURL+"&submit_edit&community_id="+currentCommunity.getID(), currentCommunity.getMetadata("name"));
List containerSubList = null;
for (Collection subCols : currentCommunity.getCollections())
{
if (containerSubList == null)
{
containerSubList = parentList.addList("subList" + currentCommunity.getID());
}
String name = subCols.getMetadata("name");
if (name == null || name.length() == 0)
{
containerSubList.addItemXref(baseURL + "&submit_edit&collection_id=" + subCols.getID(), T_untitled);
}
else
{
containerSubList.addItemXref(baseURL + "&submit_edit&collection_id=" + subCols.getID(), name);
}
}
for (Community subComs : currentCommunity.getSubcommunities())
{
if (containerSubList == null)
{
containerSubList = parentList.addList("subList" + currentCommunity.getID());
}
containerListBuilder(baseURL,containerSubList,subComs);
}
}
}
}
| 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.administrative.authorization;
import java.sql.SQLException;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.content.Collection;
import org.dspace.core.Constants;
import org.dspace.eperson.Group;
/**
* @author Alexey Maslov
*/
public class AdvacedAuthorizationsForm extends AbstractDSpaceTransformer
{
private static final Message T_title =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.title");
private static final Message T_trail =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.trail");
private static final Message T_authorize_trail =
message("xmlui.administrative.authorization.general.authorize_trail");
private static final Message T_main_head =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.main_head");
private static final Message T_main_para =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.main_para");
private static final Message T_actions_groupSentence =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.actions_groupSentence");
private static final Message T_actions_actionSentence =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.actions_actionSentence");
private static final Message T_actions_resourceSentence =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.actions_resourceSentence");
private static final Message T_actions_collectionSentence =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.actions_collectionSentence");
private static final Message T_actions_policyGroup =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.actions_policyGroup");
private static final Message T_actions_policyAction =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.actions_policyAction");
private static final Message T_actions_policyResource =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.actions_policyResource");
private static final Message T_actions_policyCollections =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.actions_policyCollections");
private static final Message T_submit_add =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.submit_add");
private static final Message T_submit_remove_all =
message("xmlui.administrative.authorization.AdvacedAuthorizationsForm.submit_remove_all");
private static final Message T_submit_return =
message("xmlui.general.return");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/authorize", T_authorize_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException
{
Division main = body.addInteractiveDivision("advanced-authorization",contextPath+"/admin/authorize",Division.METHOD_POST,"primary administrative authorization");
main.setHead(T_main_head);
main.addPara(T_main_para);
List actionsList = main.addList("actions","form");
// For all of the selected groups...
actionsList.addItem().addContent(T_actions_groupSentence);
actionsList.addLabel(T_actions_policyGroup);
Select groupSelect = actionsList.addItem().addSelect("group_id");
groupSelect.setMultiple(true);
groupSelect.setSize(15);
for (Group group : Group.findAll(context, Group.NAME))
{
groupSelect.addOption(false, group.getID(), group.getName());
}
// Grant the ability to perform the following action...
actionsList.addItem().addContent(T_actions_actionSentence);
actionsList.addLabel(T_actions_policyAction);
Select actionSelect = actionsList.addItem().addSelect("action_id");
for( int i = 0; i < Constants.actionText.length; i++ )
{
actionSelect.addOption(i, Constants.actionText[i]);
}
// For all following object types...
actionsList.addItem().addContent(T_actions_resourceSentence);
actionsList.addLabel(T_actions_policyResource);
Select resourceSelect = actionsList.addItem().addSelect("resource_id");
resourceSelect.addOption(true, Constants.ITEM, "item");
resourceSelect.addOption(false, Constants.BITSTREAM, "bitstream");
// Across the following collections...
actionsList.addItem().addContent(T_actions_collectionSentence);
actionsList.addLabel(T_actions_policyCollections);
Select collectionsSelect = actionsList.addItem().addSelect("collection_id");
collectionsSelect.setMultiple(true);
collectionsSelect.setSize(15);
for (Collection collection : Collection.findAll(context))
{
collectionsSelect.addOption(false, collection.getID(), collection.getMetadata("name"));
}
Para buttons = main.addPara();
buttons.addButton("submit_add").setValue(T_submit_add);
buttons.addButton("submit_remove_all").setValue(T_submit_remove_all);
buttons.addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-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.administrative.community;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.Arrays;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Community;
import org.dspace.core.ConfigurationManager;
/**
*
* @author wbossons
*/
public class CurateCommunityForm extends AbstractDSpaceTransformer {
/** Common Package Language Strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_community_trail = message("xmlui.administrative.community.general.community_trail");
private static final Message T_options_metadata = message("xmlui.administrative.community.general.options_metadata");
private static final Message T_options_roles = message("xmlui.administrative.community.general.options_roles");
private static final Message T_options_curate = message("xmlui.administrative.community.general.options_curate");
private static final Message T_submit_perform = message("xmlui.general.perform");
private static final Message T_submit_queue = message("xmlui.general.queue");
private static final Message T_submit_return = message("xmlui.general.return");
// End common package language strings
// Page/Form specific language strings
private static final Message T_main_head = message("xmlui.administrative.community.CurateCommunityForm.main_head");
private static final Message T_title = message("xmlui.administrative.community.CurateCommunityForm.title");
private static final Message T_trail = message("xmlui.administrative.community.CurateCommunityForm.trail");
private static final Message T_label_name = message("xmlui.administrative.community.CurateCommunityForm.label_name");
/**
* common package method for initializing form gui elements
* Could be refactored.
*
* @param pageMeta
* @throws WingException
*/
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_community_trail);
pageMeta.addTrail().addContent(T_trail);
}
/** addBody
*
* @param body
* @throws WingException
* @throws SQLException
* @throws AuthorizeException
*/
public void addBody(Body body)
throws WingException, SQLException,
AuthorizeException, UnsupportedEncodingException
{
int communityID = parameters.getParameterAsInteger("communityID", -1);
Community thisCommunity = Community.find(context, communityID);
String baseURL = contextPath + "/admin/community?administrative-continue=" + knot.getId();
// DIVISION: main
Division main = body.addInteractiveDivision("community-curate",contextPath+"/admin/community",Division.METHOD_MULTIPART,"primary administrative community");
main.setHead(T_main_head.parameterize(thisCommunity.getName()));
List options = main.addList("options",List.TYPE_SIMPLE,"horizontal");
options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata);
options.addItem().addXref(baseURL+"&submit_roles",T_options_roles);
options.addItem().addHighlight("bold").addXref(baseURL+"&submit_curate",T_options_curate);
List curationTaskList = main.addList("curationTaskList", "form");
curationTaskList.addLabel(T_label_name);
Select select = curationTaskList.addItem().addSelect("curate_task");
select = getCurationOptions(select);
select.setSize(1);
select.setRequired();
// need submit_curate_task and submit_return
Para buttonList = main.addPara();
buttonList.addButton("submit_curate_task").setValue(T_submit_perform);
buttonList.addButton("submit_queue_task").setValue(T_submit_queue);
buttonList.addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-continue").setValue(knot.getId());
}
private Select getCurationOptions(Select select)
throws WingException, UnsupportedEncodingException {
String tasksString = ConfigurationManager.getProperty("curate", "ui.tasknames");
String[] tasks = tasksString.split(",");
java.util.List<String> taskList = Arrays.asList(tasks);
for (String task : taskList)
{
String[] keyValuePair = task.split("=");
select.addOption(URLDecoder.decode(keyValuePair[0].trim(), "UTF-8"), URLDecoder.decode(keyValuePair[1].trim(), "UTF-8"));
}
return select;
}
// Add a method here to build it into the dspace.cfg ... ui.curation_tasks = estimate = "Estate"
// Mapping the task name to either the description or the mapping key
}
| 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.administrative.community;
import java.sql.SQLException;
import org.dspace.app.util.AuthorizeUtil;
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.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Community;
import org.dspace.eperson.Group;
/**
* Presents the user (most likely a global administrator) with the form to edit
* the community's special authorization groups (or roles). The only role
* support at the moment is that of community administrator.
* @author Alexey Maslov
* @author Nicholas Riley
*/
public class AssignCommunityRoles extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_community_trail = message("xmlui.administrative.community.general.community_trail");
private static final Message T_options_metadata = message("xmlui.administrative.community.general.options_metadata");
private static final Message T_options_roles = message("xmlui.administrative.community.general.options_roles");
private static final Message T_options_curate = message("xmlui.administrative.community.general.options_curate");
private static final Message T_submit_return = message("xmlui.general.return");
private static final Message T_title = message("xmlui.administrative.community.AssignCommunityRoles.title");
private static final Message T_trail = message("xmlui.administrative.community.AssignCommunityRoles.trail");
private static final Message T_main_head = message("xmlui.administrative.community.AssignCommunityRoles.main_head");
private static final Message T_no_role = message("xmlui.administrative.community.AssignCommunityRoles.no_role");
private static final Message T_create = message("xmlui.administrative.community.AssignCommunityRoles.create");
private static final Message T_delete = message("xmlui.general.delete");
private static final Message T_help_admins = message("xmlui.administrative.community.AssignCommunityRoles.help_admins");
private static final Message T_edit_authorizations = message("xmlui.administrative.community.EditCommunityMetadataForm.edit_authorizations");
private static final Message T_role_name = message("xmlui.administrative.community.AssignCommunityRoles.role_name");
private static final Message T_role_group = message("xmlui.administrative.community.AssignCommunityRoles.role_group");
private static final Message T_role_buttons = message("xmlui.administrative.community.AssignCommunityRoles.role_buttons");
private static final Message T_label_admins = message("xmlui.administrative.community.AssignCommunityRoles.label_admins");
private static final Message T_sysadmins_only = message("xmlui.administrative.community.AssignCommunityRoles.sysadmins_only");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_community_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
int communityID = parameters.getParameterAsInteger("communityID", -1);
Community thisCommunity = Community.find(context, communityID);
String baseURL = contextPath + "/admin/community?administrative-continue=" + knot.getId();
Group admins = thisCommunity.getAdministrators();
// DIVISION: main
Division main = body.addInteractiveDivision("community-assign-roles",contextPath+"/admin/community",Division.METHOD_POST,"primary administrative community");
main.setHead(T_main_head.parameterize(thisCommunity.getName()));
List options = main.addList("options", List.TYPE_SIMPLE, "horizontal");
options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata);
options.addItem().addHighlight("bold").addXref(baseURL+"&submit_roles",T_options_roles);
options.addItem().addXref(baseURL+"&submit_curate",T_options_curate);
// The table of admin roles
Table rolesTable = main.addTable("roles-table", 6, 5);
Row tableRow;
// The header row
Row tableHeader = rolesTable.addRow(Row.ROLE_HEADER);
tableHeader.addCell().addContent(T_role_name);
tableHeader.addCell().addContent(T_role_group);
tableHeader.addCell().addContent(T_role_buttons);
rolesTable.addRow();
/*
* The community admins
*/
// data row
tableRow = rolesTable.addRow(Row.ROLE_DATA);
tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_admins);
if (admins != null)
{
try
{
AuthorizeUtil.authorizeManageAdminGroup(context, thisCommunity);
tableRow.addCell().addXref(baseURL + "&submit_edit_admin", admins.getName());
}
catch (AuthorizeException authex) {
// add a notice, the user is not authorized to create/edit community's admin group
tableRow.addCell().addContent(T_sysadmins_only);
}
try
{
AuthorizeUtil.authorizeRemoveAdminGroup(context, thisCommunity);
tableRow.addCell().addButton("submit_delete_admin").setValue(T_delete);
}
catch (AuthorizeException authex)
{
// nothing to add, the user is not allowed to delete the group
}
}
else
{
tableRow.addCell().addContent(T_no_role);
Cell commAdminCell = tableRow.addCell();
try
{
AuthorizeUtil.authorizeManageAdminGroup(context, thisCommunity);
commAdminCell.addButton("submit_create_admin").setValue(T_create);
}
catch (AuthorizeException authex)
{
// add a notice, the user is not authorized to create/edit community's admin group
addAdministratorOnlyButton(commAdminCell, "submit_create_admin", T_create);
}
}
// help and directions row
tableRow = rolesTable.addRow(Row.ROLE_DATA);
tableRow.addCell();
tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_admins);
try
{
AuthorizeUtil.authorizeManageCommunityPolicy(context, thisCommunity);
// add one last link to edit the raw authorizations
Cell authCell =rolesTable.addRow().addCell(1,3);
authCell.addXref(baseURL + "&submit_authorizations", T_edit_authorizations);
}
catch (AuthorizeException authex) {
// nothing to add, the user is not authorized to manage community's policies
}
Para buttonList = main.addPara();
buttonList.addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-continue").setValue(knot.getId());
}
private void addAdministratorOnlyButton(Cell cell, String buttonName, Message buttonLabel) throws WingException, SQLException
{
Button button = cell.addButton(buttonName);
button.setValue(buttonLabel);
if (!AuthorizeManager.isAdmin(context))
{
// Only admins can create or delete
button.setDisabled();
cell.addHighlight("fade").addContent(T_sysadmins_only);
}
}
}
| 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.administrative.community;
import java.sql.SQLException;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.xmlui.wing.element.TextArea;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Community;
/**
* Presents the user with a form to enter the initial metadata for creation of a new community
* @author Alexey Maslov
*/
public class CreateCommunityForm extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_title = message("xmlui.administrative.community.CreateCommunityForm.title");
private static final Message T_trail = message("xmlui.administrative.community.CreateCommunityForm.trail");
private static final Message T_main_head_sub = message("xmlui.administrative.community.CreateCommunityForm.main_head_sub");
private static final Message T_main_head_top = message("xmlui.administrative.community.CreateCommunityForm.main_head_top");
private static final Message T_label_name = message("xmlui.administrative.community.EditCommunityMetadataForm.label_name");
private static final Message T_label_short_description = message("xmlui.administrative.community.EditCommunityMetadataForm.label_short_description");
private static final Message T_label_introductory_text = message("xmlui.administrative.community.EditCommunityMetadataForm.label_introductory_text");
private static final Message T_label_copyright_text = message("xmlui.administrative.community.EditCommunityMetadataForm.label_copyright_text");
private static final Message T_label_side_bar_text = message("xmlui.administrative.community.EditCommunityMetadataForm.label_side_bar_text");
private static final Message T_label_logo = message("xmlui.administrative.community.EditCommunityMetadataForm.label_logo");
private static final Message T_submit_save = message("xmlui.administrative.community.CreateCommunityForm.submit_save");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
int communityID = parameters.getParameterAsInteger("communityID", -1);
Community parentCommunity = Community.find(context, communityID);
// DIVISION: main
Division main = body.addInteractiveDivision("create-community",contextPath+"/admin/community",Division.METHOD_MULTIPART,"primary administrative community");
/* Whether the parent community is null is what determines if
we are creating a top-level community or a sub-community */
if (parentCommunity != null)
{
main.setHead(T_main_head_sub.parameterize(parentCommunity.getMetadata("name")));
}
else
{
main.setHead(T_main_head_top);
}
// The grand list of metadata options
List metadataList = main.addList("metadataList", "form");
// community name
metadataList.addLabel(T_label_name);
Text name = metadataList.addItem().addText("name");
name.setSize(40);
// short description
metadataList.addLabel(T_label_short_description);
Text short_description = metadataList.addItem().addText("short_description");
short_description.setSize(40);
// introductory text
metadataList.addLabel(T_label_introductory_text);
TextArea introductory_text = metadataList.addItem().addTextArea("introductory_text");
introductory_text.setSize(6, 40);
// copyright text
metadataList.addLabel(T_label_copyright_text);
TextArea copyright_text = metadataList.addItem().addTextArea("copyright_text");
copyright_text.setSize(6, 40);
// legacy sidebar text; may or may not be used for news
metadataList.addLabel(T_label_side_bar_text);
TextArea side_bar_text = metadataList.addItem().addTextArea("side_bar_text");
side_bar_text.setSize(6, 40);
// the row to upload a new logo
metadataList.addLabel(T_label_logo);
metadataList.addItem().addFile("logo");
Para buttonList = main.addPara();
buttonList.addButton("submit_save").setValue(T_submit_save);
buttonList.addButton("submit_cancel").setValue(T_submit_cancel);
main.addHidden("administrative-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.administrative.community;
import java.sql.SQLException;
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.authorize.AuthorizeException;
import org.dspace.eperson.Group;
/**
* Confirmation step for the deletion of a community's role
* @author Alexey Maslov
*/
public class DeleteCommunityRoleConfirm extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_title = message("xmlui.administrative.community.DeleteCommunityRoleConfirm.title");
private static final Message T_trail = message("xmlui.administrative.community.DeleteCommunityRoleConfirm.trail");
private static final Message T_main_head = message("xmlui.administrative.community.DeleteCommunityRoleConfirm.main_head");
private static final Message T_main_para = message("xmlui.administrative.community.DeleteCommunityRoleConfirm.main_para");
private static final Message T_submit_confirm = message("xmlui.general.delete");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
String role = parameters.getParameter("role", null);
int groupID = parameters.getParameterAsInteger("groupID", -1);
Group toBeDeleted = Group.find(context, groupID);
// DIVISION: main
Division main = body.addInteractiveDivision("community-role-delete",contextPath+"/admin/community",Division.METHOD_POST,"primary administrative community");
main.setHead(T_main_head.parameterize(role));
main.addPara(T_main_para.parameterize(toBeDeleted.getName()));
Para buttonList = main.addPara();
buttonList.addButton("submit_confirm").setValue(T_submit_confirm);
buttonList.addButton("submit_cancel").setValue(T_submit_cancel);
main.addHidden("administrative-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.administrative.community;
import java.sql.SQLException;
import org.dspace.app.xmlui.aspect.administrative.FlowContainerUtils;
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.Para;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.xmlui.wing.element.TextArea;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Community;
import org.dspace.core.Constants;
/**
* Presents the user (in this case an administrator over the community) with the
* form to edit that community's metadata and logo.
* @author Alexey Maslov
*/
public class EditCommunityMetadataForm extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_community_trail = message("xmlui.administrative.community.general.community_trail");
private static final Message T_options_metadata = message("xmlui.administrative.community.general.options_metadata");
private static final Message T_options_roles = message("xmlui.administrative.community.general.options_roles");
private static final Message T_options_curate = message("xmlui.administrative.community.general.options_curate");
private static final Message T_title = message("xmlui.administrative.community.EditCommunityMetadataForm.title");
private static final Message T_trail = message("xmlui.administrative.community.EditCommunityMetadataForm.trail");
private static final Message T_main_head = message("xmlui.administrative.community.EditCommunityMetadataForm.main_head");
private static final Message T_label_name = message("xmlui.administrative.community.EditCommunityMetadataForm.label_name");
private static final Message T_label_short_description = message("xmlui.administrative.community.EditCommunityMetadataForm.label_short_description");
private static final Message T_label_introductory_text = message("xmlui.administrative.community.EditCommunityMetadataForm.label_introductory_text");
private static final Message T_label_copyright_text = message("xmlui.administrative.community.EditCommunityMetadataForm.label_copyright_text");
private static final Message T_label_side_bar_text = message("xmlui.administrative.community.EditCommunityMetadataForm.label_side_bar_text");
private static final Message T_label_logo = message("xmlui.administrative.community.EditCommunityMetadataForm.label_logo");
private static final Message T_label_existing_logo = message("xmlui.administrative.community.EditCommunityMetadataForm.label_existing_logo");
private static final Message T_submit_delete_logo = message("xmlui.administrative.community.EditCommunityMetadataForm.submit_delete_logo");
private static final Message T_submit_delete = message("xmlui.administrative.community.EditCommunityMetadataForm.submit_delete");
private static final Message T_submit_update = message("xmlui.general.update");
private static final Message T_submit_return = message("xmlui.general.return");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_community_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
int communityID = parameters.getParameterAsInteger("communityID", -1);
Community thisCommunity = Community.find(context, communityID);
String baseURL = contextPath + "/admin/community?administrative-continue=" + knot.getId();
String short_description_error = FlowContainerUtils.checkXMLFragment(thisCommunity.getMetadata("short_description"));
String introductory_text_error = FlowContainerUtils.checkXMLFragment(thisCommunity.getMetadata("introductory_text"));
String copyright_text_error = FlowContainerUtils.checkXMLFragment(thisCommunity.getMetadata("copyright_text"));
String side_bar_text_error = FlowContainerUtils.checkXMLFragment(thisCommunity.getMetadata("side_bar_text"));
// DIVISION: main
Division main = body.addInteractiveDivision("community-metadata-edit",contextPath+"/admin/community",Division.METHOD_MULTIPART,"primary administrative community");
main.setHead(T_main_head.parameterize(thisCommunity.getName()));
List options = main.addList("options",List.TYPE_SIMPLE,"horizontal");
options.addItem().addHighlight("bold").addXref(baseURL+"&submit_metadata",T_options_metadata);
options.addItem().addXref(baseURL+"&submit_roles",T_options_roles);
options.addItem().addXref(baseURL+"&submit_curate",T_options_curate);
// The grand list of metadata options
List metadataList = main.addList("metadataList", "form");
// community name
metadataList.addLabel(T_label_name);
Text name = metadataList.addItem().addText("name");
name.setSize(40);
name.setValue(thisCommunity.getMetadata("name"));
// short description
metadataList.addLabel(T_label_short_description);
Text short_description = metadataList.addItem().addText("short_description");
short_description.setValue(thisCommunity.getMetadata("short_description"));
short_description.setSize(40);
if (short_description_error != null)
{
short_description.addError(short_description_error);
}
// introductory text
metadataList.addLabel(T_label_introductory_text);
TextArea introductory_text = metadataList.addItem().addTextArea("introductory_text");
introductory_text.setValue(thisCommunity.getMetadata("introductory_text"));
introductory_text.setSize(6, 40);
if (introductory_text_error != null)
{
introductory_text.addError(introductory_text_error);
}
// copyright text
metadataList.addLabel(T_label_copyright_text);
TextArea copyright_text = metadataList.addItem().addTextArea("copyright_text");
copyright_text.setValue(thisCommunity.getMetadata("copyright_text"));
copyright_text.setSize(6, 40);
if (copyright_text_error != null)
{
copyright_text.addError(copyright_text_error);
}
// legacy sidebar text; may or may not be used for news
metadataList.addLabel(T_label_side_bar_text);
TextArea side_bar_text = metadataList.addItem().addTextArea("side_bar_text");
side_bar_text.setValue(thisCommunity.getMetadata("side_bar_text"));
side_bar_text.setSize(6, 40);
if (side_bar_text_error != null)
{
side_bar_text.addError(side_bar_text_error);
}
// the row to upload a new logo
metadataList.addLabel(T_label_logo);
metadataList.addItem().addFile("logo");
// the row displaying an existing logo
Item item;
if (thisCommunity.getLogo() != null) {
metadataList.addLabel(T_label_existing_logo);
item = metadataList.addItem();
item.addFigure(contextPath + "/bitstream/id/" + thisCommunity.getLogo().getID() + "/bob.jpg", null, null);
item.addButton("submit_delete_logo").setValue(T_submit_delete_logo);
}
Para buttonList = main.addPara();
buttonList.addButton("submit_save").setValue(T_submit_update);
if (AuthorizeManager.authorizeActionBoolean(context, thisCommunity, Constants.DELETE))
{
buttonList.addButton("submit_delete").setValue(T_submit_delete);
}
buttonList.addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-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.administrative.community;
import java.sql.SQLException;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Community;
/**
* Confirmation step for the deletion of an entire community
* @author Alexey Maslov
*/
public class DeleteCommunityConfirm extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_title = message("xmlui.administrative.community.DeleteCommunityConfirm.title");
private static final Message T_trail = message("xmlui.administrative.community.DeleteCommunityConfirm.trail");
private static final Message T_main_head = message("xmlui.administrative.community.DeleteCommunityConfirm.main_head");
private static final Message T_main_para = message("xmlui.administrative.community.DeleteCommunityConfirm.main_para");
private static final Message T_confirm_item1 = message("xmlui.administrative.community.DeleteCommunityConfirm.confirm_item1");
private static final Message T_confirm_item2 = message("xmlui.administrative.community.DeleteCommunityConfirm.confirm_item2");
private static final Message T_confirm_item3 = message("xmlui.administrative.community.DeleteCommunityConfirm.confirm_item3");
private static final Message T_confirm_item4 = message("xmlui.administrative.community.DeleteCommunityConfirm.confirm_item4");
private static final Message T_submit_confirm = message("xmlui.general.delete");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
int communityID = parameters.getParameterAsInteger("communityID", -1);
Community thisCommunity = Community.find(context, communityID);
// DIVISION: main
Division main = body.addInteractiveDivision("community-confirm-delete",contextPath+"/admin/community",Division.METHOD_POST,"primary administrative community");
main.setHead(T_main_head.parameterize(communityID));
main.addPara(T_main_para.parameterize(thisCommunity.getMetadata("name")));
List deleteConfirmHelp = main.addList("consequences",List.TYPE_BULLETED);
deleteConfirmHelp.addItem(T_confirm_item1);
deleteConfirmHelp.addItem(T_confirm_item2);
deleteConfirmHelp.addItem(T_confirm_item3);
deleteConfirmHelp.addItem(T_confirm_item4);
Para buttonList = main.addPara();
buttonList.addButton("submit_confirm").setValue(T_submit_confirm);
buttonList.addButton("submit_cancel").setValue(T_submit_cancel);
main.addHidden("administrative-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.administrative;
import java.io.Serializable;
import org.apache.cocoon.caching.CacheableProcessingComponent;
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.Metadata;
import org.dspace.app.xmlui.wing.element.PageMeta;
/**
* This class maintains any system-wide alerts. If any alerts are activated then
* they are added to the page's metadata for display by the theme.
*
* This class also creates an interface for the alert system to be maintained.
*
* @author Scott Phillips
*/
public class SystemwideAlerts extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_COUNTDOWN = message("xmlui.administrative.SystemwideAlerts.countdown");
/** Possible user restricted states */
public static final int STATE_ALL_SESSIONS = 1;
public static final int STATE_CURRENT_SESSIONS = 2;
public static final int STATE_ONLY_ADMINISTRATIVE_SESSIONS = 3;
// Is an alert activated?
private static boolean active;
// The alert's message
private static String message;
// If a count down time is present, what time are we counting down too?
private static long countDownToo;
// Can users use the website?
private static int restrictsessions = STATE_ALL_SESSIONS;
/**
* Generate the unique caching key.
*/
public Serializable getKey()
{
if (active)
{
// Don't cache any alert messages
return null;
}
else
{
return "1";
}
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity()
{
if (active)
{
return null;
}
else
{
return NOPValidity.SHARED_INSTANCE;
}
}
/**
* If an alert is activated then add a count down message.
*/
public void addPageMeta(PageMeta pageMeta) throws WingException
{
if (active)
{
Metadata alert = pageMeta.addMetadata("alert","message");
long time = countDownToo - System.currentTimeMillis();
if (time > 0)
{
// from milliseconds to minutes
time = time / (60*1000);
alert.addContent(T_COUNTDOWN.parameterize(time));
}
alert.addContent(message);
}
}
/**
* Check whether an alert is active.
*/
public static boolean isAlertActive()
{
return SystemwideAlerts.active;
}
/**
* Activate the current alert.
*/
public static void activateAlert()
{
SystemwideAlerts.active = true;
}
/**
* Deactivate the current alert.
*/
public static void deactivateAlert()
{
SystemwideAlerts.active = false;
}
/**
* Set the current alert's message.
* @param message The new message
*/
public static void setMessage(String message)
{
SystemwideAlerts.message = message;
}
/**
* @return the current alert's message
*/
public static String getMessage()
{
return SystemwideAlerts.message;
}
/**
* Get the time, in millieseconds, when the countdown timer is scheduled to end.
*/
public static long getCountDownToo()
{
return SystemwideAlerts.countDownToo;
}
/**
* Set the time, in millieseconds, to which the countdown timer should end.
*
* Note, that once the countdown has expried, the alert is
* still active. However the countdown will disappear.
*/
public static void setCountDownToo(long countDownTo)
{
SystemwideAlerts.countDownToo = countDownTo;
}
// Can users login or continue to use the system?
public static int getRestrictSessions()
{
return SystemwideAlerts.restrictsessions;
}
// Set the ability to restrict use of the system
public static void setRestrictSessions(int restrictsessions)
{
if (restrictsessions == STATE_ALL_SESSIONS ||
restrictsessions == STATE_CURRENT_SESSIONS ||
restrictsessions == STATE_ONLY_ADMINISTRATIVE_SESSIONS)
{
SystemwideAlerts.restrictsessions = restrictsessions;
}
}
/**
* Are users able to start a new session, will return false if there is
* a current alert activated and sessions are restricted.
*
* @return if false do not allow user to start a new session, otherwise no restriction.
*/
public static boolean canUserStartSession()
{
return !SystemwideAlerts.active ||
(restrictsessions != STATE_ONLY_ADMINISTRATIVE_SESSIONS &&
restrictsessions != STATE_CURRENT_SESSIONS);
}
/**
* Are users able to maintain a session, will return false if there is
* a current alert activated and sessions are restricted.
*
* @return if false do not allow user to maintain their current session
* or start a new session, otherwise no restriction.
*/
public static boolean canUserMaintainSession()
{
return !SystemwideAlerts.active || restrictsessions != STATE_ONLY_ADMINISTRATIVE_SESSIONS;
}
}
| 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.administrative;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.servlet.multipart.Part;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.content.FormatIdentifier;
import org.dspace.content.Item;
import org.dspace.content.MetadataField;
import org.dspace.content.MetadataSchema;
import org.dspace.content.authority.Choices;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.curate.Curator;
import org.dspace.handle.HandleManager;
/**
* Utility methods to processes actions on Groups. These methods are used
* exclusivly from the administrative flow scripts.
*
* @author Jay Paz
* @author Scott Phillips
*/
public class FlowItemUtils
{
/** Language Strings */
private static final Message T_metadata_updated = new Message("default","The Item's metadata was successfully updated.");
private static final Message T_metadata_added = new Message("default","New metadata was added.");
private static final Message T_item_withdrawn = new Message("default","The item has been withdrawn.");
private static final Message T_item_reinstated = new Message("default","The item has been reinstated.");
private static final Message T_item_moved = new Message("default","The item has been moved.");
private static final Message T_item_move_destination_not_found = new Message("default","The selected destination collection could not be found.");
private static final Message T_bitstream_added = new Message("default","The new bitstream was successfully uploaded.");
private static final Message T_bitstream_failed = new Message("default","Error while uploading file.");
private static final Message T_bitstream_updated = new Message("default","The bitstream has been updated.");
private static final Message T_bitstream_delete = new Message("default","The selected bitstreams have been deleted.");
/**
* Resolve the given identifier to an item. The identifier may be either an
* internal ID or a handle. If an item is found then the result the internal
* ID of the item will be placed in the result "itemID" parameter.
*
* If the identifier was unable to be resolved to an item then the "identifier"
* field is placed in error.
*
* @param context The current DSpace context.
* @param identifier An Internal ID or a handle
* @return A flow result
*/
public static FlowResult resolveItemIdentifier(Context context, String identifier) throws SQLException
{
FlowResult result = new FlowResult();
result.setContinue(false);
// Check whether it's a handle or internal id (by check ing if it has a slash inthe string)
if (identifier.contains("/"))
{
DSpaceObject dso = HandleManager.resolveToObject(context, identifier);
if (dso != null && dso.getType() == Constants.ITEM)
{
result.setParameter("itemID", dso.getID());
result.setParameter("type", Constants.ITEM);
result.setContinue(true);
return result;
}
}
else
{
Item item = null;
try {
item = Item.find(context, Integer.valueOf(identifier));
} catch (NumberFormatException e) {
// ignoring the exception
}
if (item != null)
{
result.setParameter("itemID", item.getID());
result.setParameter("type", Constants.ITEM);
result.setContinue(true);
return result;
}
}
result.addError("identifier");
return result;
}
/**
* Process the request parameters to update the item's metadata and remove any selected bitstreams.
*
* Each metadata entry will have three fields "name_X", "value_X", and "language_X" where X is an
* integer that relates all three of the fields together. The name parameter stores the metadata name
* that is used by the entry (i.e schema_element_qualifier). The value and language paramaters are user
* inputed fields. If the optional parameter "remove_X" is given then the metadata value is removed.
*
* To support AJAX operations on this page an aditional parameter is considered, the "scope". The scope
* is the set of metadata entries that are being updated during this request. It the metadata name,
* schema_element_qualifier, only fields that have this name are considered! If all fields are to be
* considered then scope should be set to "*".
*
* When creating an AJAX query include all the name_X, value_X, language_X, and remove_X for the fields
* in the set, and then set the scope parameter to be the metadata field.
*
* @param context The current DSpace context
* @param itemID internal item id
* @param request the Cocoon request
* @return A flow result
*/
public static FlowResult processEditItem(Context context, int itemID, Request request) throws SQLException, AuthorizeException, UIException, IOException
{
FlowResult result = new FlowResult();
result.setContinue(false);
Item item = Item.find(context, itemID);
// STEP 1:
// Clear all metadata within the scope
// Only metadata values within this scope will be considered. This
// is so ajax request can operate on only a subset of the values.
String scope = request.getParameter("scope");
if ("*".equals(scope))
{
item.clearMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
}
else
{
String[] parts = parseName(scope);
item.clearMetadata(parts[0],parts[1],parts[2],Item.ANY);
}
// STEP 2:
// First determine all the metadata fields that are within
// the scope parameter
ArrayList<Integer> indexes = new ArrayList<Integer>();
Enumeration parameters = request.getParameterNames();
while(parameters.hasMoreElements())
{
// Only consider the name_ fields
String parameterName = (String) parameters.nextElement();
if (parameterName.startsWith("name_"))
{
// Check if the name is within the scope
String parameterValue = request.getParameter(parameterName);
if ("*".equals(scope) || scope.equals(parameterValue))
{
// Extract the index from the name.
String indexString = parameterName.substring("name_".length());
Integer index = Integer.valueOf(indexString);
indexes.add(index);
}
}
}
// STEP 3:
// Iterate over all the indexes within the scope and add them back in.
for (Integer index=1; index <= indexes.size(); ++index)
{
String name = request.getParameter("name_"+index);
String value = request.getParameter("value_"+index);
String authority = request.getParameter("value_"+index+"_authority");
String confidence = request.getParameter("value_"+index+"_confidence");
String lang = request.getParameter("language_"+index);
String remove = request.getParameter("remove_"+index);
// the user selected the remove checkbox.
if (remove != null)
{
continue;
}
// get the field's name broken up
String[] parts = parseName(name);
// probe for a confidence value
int iconf = Choices.CF_UNSET;
if (confidence != null && confidence.length() > 0)
{
iconf = Choices.getConfidenceValue(confidence);
}
// upgrade to a minimum of NOVALUE if there IS an authority key
if (authority != null && authority.length() > 0 && iconf == Choices.CF_UNSET)
{
iconf = Choices.CF_NOVALUE;
}
item.addMetadata(parts[0], parts[1], parts[2], lang,
value, authority, iconf);
}
item.update();
context.commit();
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_metadata_updated);
return result;
}
/**
* Process the request paramaters to add a new metadata entry for the item.
*
* @param context The current DSpace context
* @param itemID internal item id
* @param request the Cocoon request
* @return A flow result
*/
public static FlowResult processAddMetadata(Context context, int itemID, Request request) throws SQLException, AuthorizeException, UIException, IOException
{
FlowResult result = new FlowResult();
result.setContinue(false);
Item item = Item.find(context, itemID);
String fieldID = request.getParameter("field");
String value = request.getParameter("value");
String language = request.getParameter("language");
MetadataField field = MetadataField.find(context,Integer.valueOf(fieldID));
MetadataSchema schema = MetadataSchema.find(context,field.getSchemaID());
item.addMetadata(schema.getName(), field.getElement(), field.getQualifier(), language, value);
item.update();
context.commit();
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_metadata_added);
return result;
}
/**
* Withdraw the specified item, this method assumes that the action has been confirmed.
*
* @param context The DSpace context
* @param itemID The id of the to-be-withdrawn item.
* @return A result object
*/
public static FlowResult processWithdrawItem(Context context, int itemID) throws SQLException, AuthorizeException, IOException
{
FlowResult result = new FlowResult();
result.setContinue(false);
Item item = Item.find(context, itemID);
item.withdraw();
context.commit();
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_item_withdrawn);
return result;
}
/**
* Reinstate the specified item, this method assumes that the action has been confirmed.
*
* @param context The DSpace context
* @param itemID The id of the to-be-reinstated item.
* @return A result object
*/
public static FlowResult processReinstateItem(Context context, int itemID) throws SQLException, AuthorizeException, IOException
{
FlowResult result = new FlowResult();
result.setContinue(false);
Item item = Item.find(context, itemID);
item.reinstate();
context.commit();
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_item_reinstated);
return result;
}
/**
* Move the specified item to another collection.
*
* @param context The DSpace context
* @param itemID The id of the to-be-moved item.
* @param collectionID The id of the destination collection.
* @param inherit Whether to inherit the policies of the destination collection
* @return A result object
*/
public static FlowResult processMoveItem(Context context, int itemID, int collectionID, boolean inherit) throws SQLException, AuthorizeException, IOException
{
FlowResult result = new FlowResult();
result.setContinue(false);
Item item = Item.find(context, itemID);
if(AuthorizeManager.isAdmin(context, item))
{
//Add an action giving this user *explicit* admin permissions on the item itself.
//This ensures that the user will be able to call item.update() even if he/she
// moves it to a Collection that he/she doesn't administer.
if (item.canEdit())
{
AuthorizeManager.authorizeAction(context, item, Constants.WRITE);
}
Collection destination = Collection.find(context, collectionID);
if (destination == null)
{
result.setOutcome(false);
result.setContinue(false);
result.setMessage(T_item_move_destination_not_found);
return result;
}
Collection owningCollection = item.getOwningCollection();
if (destination.equals(owningCollection))
{
// nothing to do
result.setOutcome(false);
result.setContinue(false);
return result;
}
// note: an item.move() method exists, but does not handle several cases:
// - no preexisting owning collection (first arg is null)
// - item already in collection, but not an owning collection
// (works, but puts item in collection twice)
// Don't re-add the item to a collection it's already in.
boolean alreadyInCollection = false;
for (Collection collection : item.getCollections())
{
if (collection.equals(destination))
{
alreadyInCollection = true;
break;
}
}
// Remove item from its owning collection and add to the destination
if (!alreadyInCollection)
{
destination.addItem(item);
}
if (owningCollection != null)
{
owningCollection.removeItem(item);
}
item.setOwningCollection(destination);
// Inherit policies of destination collection if required
if (inherit)
{
item.inheritCollectionDefaultPolicies(destination);
}
item.update();
context.commit();
result.setOutcome(true);
result.setContinue(true);
result.setMessage(T_item_moved);
}
return result;
}
/**
* Permanently delete the specified item, this method assumes that
* the action has been confirmed.
*
* @param context The DSpace context
* @param itemID The id of the to-be-deleted item.
* @return A result object
*/
public static FlowResult processDeleteItem(Context context, int itemID) throws SQLException, AuthorizeException, IOException
{
FlowResult result = new FlowResult();
result.setContinue(false);
Item item = Item.find(context, itemID);
Collection[] collections = item.getCollections();
// Remove item from all the collections it's in
for (Collection collection : collections)
{
collection.removeItem(item);
}
// Note: when removing an item from the last collection it will
// be removed from the system. So there is no need to also call
// an item.delete() method.
context.commit();
result.setContinue(true);
return result;
}
/**
* Add a new bitstream to the item. The bundle, bitstream (aka file), and description
* will be used to create a new bitstream. If the format needs to be adjusted then they
* will need to access the edit bitstream form after it has been uploaded.
*
* @param context The DSpace content
* @param itemID The item to add a new bitstream too
* @param request The request.
* @return A flow result
*/
public static FlowResult processAddBitstream(Context context, int itemID, Request request) throws SQLException, AuthorizeException, IOException
{
FlowResult result = new FlowResult();
result.setContinue(false);
// Upload a new file
Item item = Item.find(context, itemID);
Object object = request.get("file");
Part filePart = null;
if (object instanceof Part)
{
filePart = (Part) object;
}
if (filePart != null && filePart.getSize() > 0)
{
InputStream is = filePart.getInputStream();
String bundleName = request.getParameter("bundle");
Bitstream bitstream;
Bundle[] bundles = item.getBundles(bundleName);
if (bundles.length < 1)
{
// set bundle's name to ORIGINAL
bitstream = item.createSingleBitstream(is, bundleName);
// set the permission as defined in the owning collection
Collection owningCollection = item.getOwningCollection();
if (owningCollection != null)
{
Bundle bnd = bitstream.getBundles()[0];
bnd.inheritCollectionDefaultPolicies(owningCollection);
}
}
else
{
// we have a bundle already, just add bitstream
bitstream = bundles[0].createBitstream(is);
}
// Strip all but the last filename. It would be nice
// to know which OS the file came from.
String name = filePart.getUploadName();
while (name.indexOf('/') > -1)
{
name = name.substring(name.indexOf('/') + 1);
}
while (name.indexOf('\\') > -1)
{
name = name.substring(name.indexOf('\\') + 1);
}
bitstream.setName(name);
bitstream.setSource(filePart.getUploadName());
bitstream.setDescription(request.getParameter("description"));
// Identify the format
BitstreamFormat format = FormatIdentifier.guessFormat(context, bitstream);
bitstream.setFormat(format);
// Update to DB
bitstream.update();
item.update();
context.commit();
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_bitstream_added);
}
else
{
result.setContinue(false);
result.setOutcome(false);
result.setMessage(T_bitstream_failed);
}
return result;
}
/**
* Update a bitstream's metadata.
*
* @param context The DSpace content
* @param itemID The item to which the bitstream belongs
* @param bitstreamID The bitstream being updated.
* @param description The new description of the bitstream
* @param formatID The new format ID of the bitstream
* @param userFormat Any user supplied formats.
* @return A flow result object.
*/
public static FlowResult processEditBitstream(Context context, int itemID, int bitstreamID, String primary, String description, int formatID, String userFormat) throws SQLException, AuthorizeException
{
FlowResult result = new FlowResult();
result.setContinue(false);
Bitstream bitstream = Bitstream.find(context, bitstreamID);
BitstreamFormat currentFormat = bitstream.getFormat();
//Step 1:
// Update the bitstream's description
if (description != null)
{
bitstream.setDescription(description);
}
//Step 2:
// Check if the primary bitstream status has changed
Bundle[] bundles = bitstream.getBundles();
if (bundles != null && bundles.length > 0)
{
if (bitstreamID == bundles[0].getPrimaryBitstreamID())
{
// currently the bitstream is primary
if ("no".equals(primary))
{
// However the user has removed this bitstream as a primary bitstream.
bundles[0].unsetPrimaryBitstreamID();
bundles[0].update();
}
}
else
{
// currently the bitstream is non-primary
if ("yes".equals(primary))
{
// However the user has set this bitstream as primary.
bundles[0].setPrimaryBitstreamID(bitstreamID);
bundles[0].update();
}
}
}
//Step 2:
// Update the bitstream's format
if (formatID > 0)
{
if (currentFormat == null || currentFormat.getID() != formatID)
{
BitstreamFormat newFormat = BitstreamFormat.find(context, formatID);
if (newFormat != null)
{
bitstream.setFormat(newFormat);
}
}
}
else
{
if (userFormat != null && userFormat.length() > 0)
{
bitstream.setUserFormatDescription(userFormat);
}
}
//Step 3:
// Save our changes
bitstream.update();
context.commit();
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_bitstream_updated);
return result;
}
/**
* Delete the given bitstreams from the bundle and item. If there are no more bitstreams
* left in a bundle then also remove it.
*
* @param context Current dspace content
* @param itemID The item id from which to remove bitstreams
* @param bitstreamIDs A bundle slash bitstream id pair of bitstreams to be removed.
* @return A flow result
*/
public static FlowResult processDeleteBitstreams(Context context, int itemID, String[] bitstreamIDs) throws SQLException, AuthorizeException, IOException, UIException
{
FlowResult result = new FlowResult();
result.setContinue(false);
Item item = Item.find(context, itemID);
for (String id : bitstreamIDs)
{
String[] parts = id.split("/");
if (parts.length != 2)
{
throw new UIException("Unable to parse id into bundle and bitstream id: "+id);
}
int bundleID = Integer.valueOf(parts[0]);
int bitstreamID = Integer.valueOf(parts[1]);
Bundle bundle = Bundle.find(context, bundleID);
Bitstream bitstream = Bitstream.find(context,bitstreamID);
bundle.removeBitstream(bitstream);
if (bundle.getBitstreams().length == 0)
{
item.removeBundle(bundle);
}
}
item.update();
context.commit();
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_bitstream_delete);
return result;
}
/**
* processCurateDSO
*
* Utility method to process curation tasks
* submitted via the DSpace GUI
*
* @param context
* @param itemID
* @param request
*
*/
public static FlowResult processCurateItem(Context context, int itemID, Request request)
throws AuthorizeException, IOException, SQLException, Exception
{
String task = request.getParameter("curate_task");
Curator curator = FlowCurationUtils.getCurator(task);
Item item = Item.find(context, itemID);
if (item != null)
{
curator.curate(item);
}
return FlowCurationUtils.getRunFlowResult(task, curator);
}
/**
* queues curation tasks
*/
public static FlowResult processQueueItem(Context context, int itemID, Request request)
throws AuthorizeException, IOException, SQLException, Exception
{
String task = request.getParameter("curate_task");
Curator curator = FlowCurationUtils.getCurator(task);
String objId = String.valueOf(itemID);
String taskQueueName = ConfigurationManager.getProperty("curate", "ui.queuename");
boolean status = false;
Item item = Item.find(context, itemID);
if (item != null)
{
objId = item.getHandle();
try
{
curator.queue(context, objId, taskQueueName);
status = true;
}
catch (IOException ioe)
{
// no-op
}
}
return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName);
}
/**
* Parse the given name into three parts, divided by an _. Each part should represent the
* schema, element, and qualifier. You are guaranteed that if no qualifier was supplied the
* third entry is null.
*
* @param name The name to be parsed.
* @return An array of name parts.
*/
private static String[] parseName(String name) throws UIException
{
String[] parts = new String[3];
String[] split = name.split("_");
if (split.length == 2) {
parts[0] = split[0];
parts[1] = split[1];
parts[2] = null;
} else if (split.length == 3) {
parts[0] = split[0];
parts[1] = split[1];
parts[2] = split[2];
} else {
throw new UIException("Unable to parse metedata field name: "+name);
}
return parts;
}
}
| 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.administrative;
import java.sql.SQLException;
import java.util.List;
import org.dspace.app.util.AuthorizeUtil;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.authorize.PolicySet;
import org.dspace.authorize.ResourcePolicy;
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.Context;
import org.dspace.eperson.Group;
import org.dspace.handle.HandleManager;
import org.dspace.core.Constants;
/**
*
* FIXME: add documentation
*
* @author Alexey maslov
*/
public class FlowAuthorizationUtils {
/** Language Strings */
//example language string
// private static final Message T_add_eperson_success_notice =
// new Message("default","xmlui.administrative.FlowUtils.add-eperson-success-notice");
/**
* Resolve an identifier submitted into the item lookup box. If it contains a slash, it's assumed to be a
* handle and is resolved by that mechanism into an item, collection or community. Otherwise, it's assumed
* to be an item and looked up by ID.
*
* @param context The current DSpace context.
* @param identifier The identifier that is to be resolved.
* @return A process result's object.
*/
public static FlowResult resolveItemIdentifier(Context context, String identifier) throws SQLException
{
FlowResult result = new FlowResult();
result.setContinue(false);
//Check whether it's a handle or internal id (by check ing if it has a slash in the string)
if (identifier.contains("/")) {
DSpaceObject dso = HandleManager.resolveToObject(context, identifier);
if (dso != null && dso.getType() == Constants.ITEM) {
result.setParameter("itemID", dso.getID());
result.setParameter("type", Constants.ITEM);
result.setContinue(true);
return result;
}
else if (dso != null && dso.getType() == Constants.COLLECTION) {
result.setParameter("collectionID", dso.getID());
result.setParameter("type", Constants.COLLECTION);
result.setContinue(true);
return result;
}
else if (dso != null && dso.getType() == Constants.COMMUNITY) {
result.setParameter("communityID", dso.getID());
result.setParameter("type", Constants.COMMUNITY);
result.setContinue(true);
return result;
}
}
// Otherwise, it's assumed to be a DSpace Item
else {
Item item = null;
try {
item = Item.find(context, Integer.valueOf(identifier));
} catch (NumberFormatException e) {
// ignoring the exception in case of a malformed input string
}
if (item != null) {
result.setParameter("itemID", item.getID());
result.setParameter("type", Constants.ITEM);
result.setContinue(true);
return result;
}
}
result.addError("identifier");
return result;
}
/**
* Process the editing of an existing or a newly created policy.
*
* @param context The current DSpace context.
* @param objectType The type of the policy's parent object (ITEM, COLLECTION, COMMUNITY)
* @param objectID The ID of the policy's parent object
* @param policyID The ID of the policy being edited (-1 if a new policy is being created)
* @param groupID The ID of the group to be associated with this policy
* @param actionID The ID of the action (dependent on the objectType) to be associated with this policy
* @return A process result's object.
*/
public static FlowResult processEditPolicy(Context context, int objectType, int objectID, int policyID, int groupID, int actionID) throws SQLException, AuthorizeException
{
FlowResult result = new FlowResult();
boolean added = false;
ResourcePolicy policy = ResourcePolicy.find(context, policyID);
// check authorization to edit an existent policy
if (policy != null)
{
AuthorizeUtil.authorizeManagePolicy(context, policy);
}
/* First and foremost, if no group or action was selected, throw an error back to the user */
if (actionID == -1) {
result.setContinue(false);
result.addError("action_id");
return result;
}
if (groupID == -1) {
result.setContinue(false);
result.addError("group_id");
return result;
}
/* If the policy doesn't exist, cretae a new one and set its parent resource */
DSpaceObject policyParent = null;
if (policy == null)
{
switch (objectType) {
case Constants.COMMUNITY:
{
policyParent = Community.find(context, objectID);
AuthorizeUtil.authorizeManageCommunityPolicy(context, (Community)policyParent);
break;
}
case Constants.COLLECTION:
{
policyParent = Collection.find(context, objectID);
AuthorizeUtil.authorizeManageCollectionPolicy(context, (Collection)policyParent);
break;
}
case Constants.ITEM:
{
policyParent = Item.find(context, objectID);
AuthorizeUtil.authorizeManageItemPolicy(context, (Item) policyParent);
break;
}
case Constants.BUNDLE:
{
policyParent = Bundle.find(context, objectID);
AuthorizeUtil.authorizeManageItemPolicy(context, (Item) (policyParent.getParentObject()));
break;
}
case Constants.BITSTREAM:
{
policyParent = Bitstream.find(context, objectID);
AuthorizeUtil
.authorizeManageItemPolicy(context, (Item) (policyParent
.getParentObject()));
break;
}
}
policy = ResourcePolicy.create(context);
policy.setResource(policyParent);
added = true;
}
Group group = Group.find(context, groupID);
// modify the policy
policy.setAction(actionID);
policy.setGroup(group);
// propagate the changes to the logo, which is treated on the same level as the parent object
Bitstream logo = null;
DSpaceObject logoContainer = null;
if (objectType == Constants.COLLECTION)
{
logoContainer = Collection.find(context, objectID);
logo = ((Collection)logoContainer).getLogo();
}
else if (objectType == Constants.COMMUNITY)
{
logoContainer = Community.find(context, objectID);
logo = ((Community)logoContainer).getLogo();
}
if (logo != null)
{
List policySet = AuthorizeManager.getPolicies(context, logoContainer);
AuthorizeManager.removeAllPolicies(context, logo);
AuthorizeManager.addPolicies(context, policySet, logo);
}
// Perform the update action
policy.update();
context.commit();
result.setContinue(true);
result.setOutcome(true);
if (added)
{
result.setMessage(new Message("default", "A new policy was created successfully"));
}
else
{
result.setMessage(new Message("default", "The policy was edited successfully"));
}
result.setParameter("policyID", policy.getID());
return result;
}
/**
* Delete the policies specified by the policyIDs parameter. This assumes that the
* deletion has been confirmed.
*
* @param context The current DSpace context
* @param policyIDs The unique ids of the policies being deleted.
* @return A process result's object.
*/
public static FlowResult processDeletePolicies(Context context, String[] policyIDs) throws NumberFormatException, SQLException, AuthorizeException
{
FlowResult result = new FlowResult();
for (String id : policyIDs)
{
ResourcePolicy policyDeleted = ResourcePolicy.find(context, Integer.valueOf(id));
// check authorization
AuthorizeUtil.authorizeManagePolicy(context, policyDeleted);
policyDeleted.delete();
}
result.setContinue(true);
result.setOutcome(true);
result.setMessage(new Message("default","The policies were deleted successfully"));
return result;
}
/**
* Process addition of a several authorizations at once, as entered in the wildcard/advanced authorizations tool
*
* @param context The current DSpace context.
* @param groupIDs The IDs of the groups to be associated with the newly created policies
* @param actionID The ID of the action to be associated with the policies
* @param resourceID Whether the policies will apply to Items or Bitstreams
* @param collectionIDs The IDs of the collections that the policies will be applied to
* @return A process result's object.
*/
public static FlowResult processAdvancedPolicyAdd(Context context, String[] groupIDs, int actionID,
int resourceID, String [] collectionIDs) throws NumberFormatException, SQLException, AuthorizeException
{
AuthorizeUtil.requireAdminRole(context);
FlowResult result = new FlowResult();
for (String groupID : groupIDs)
{
for (String collectionID : collectionIDs)
{
PolicySet.setPolicies(context, Constants.COLLECTION, Integer.valueOf(collectionID),
resourceID, actionID, Integer.valueOf(groupID), false, false);
// if it's a bitstream, do it to the bundle too
if (resourceID == Constants.BITSTREAM)
{
PolicySet.setPolicies(context, Constants.COLLECTION, Integer.valueOf(collectionID),
Constants.BUNDLE, actionID, Integer.valueOf(groupID), false, false);
}
}
}
result.setContinue(true);
result.setOutcome(true);
result.setMessage(new Message("default","The policies were added successfully!"));
return result;
}
/**
* Process the deletion of all authorizations across a set of collections, regardless of associated
* actions or groups. This functionality should probably not be used, ever, unless the goal to
* completely reset a collection for one reason or another.
*
* @param context The current DSpace context.
* @param resourceID Whether the policies will apply to Items or Bitstreams
* @param collectionIDs The IDs of the collections that the policy wipe will be applied to
* @return A process result's object.
*/
public static FlowResult processAdvancedPolicyDelete(Context context, int resourceID, String [] collectionIDs)
throws NumberFormatException, SQLException, AuthorizeException
{
AuthorizeUtil.requireAdminRole(context);
FlowResult result = new FlowResult();
for (String collectionID : collectionIDs)
{
PolicySet.setPolicies(context, Constants.COLLECTION, Integer.valueOf(collectionID),
resourceID, 0, 0, false, true);
// if it's a bitstream, do it to the bundle too
if (resourceID == Constants.BITSTREAM)
{
PolicySet.setPolicies(context, Constants.COLLECTION, Integer.valueOf(collectionID),
Constants.BUNDLE, 0, 0, false, true);
}
}
result.setContinue(true);
result.setOutcome(true);
result.setMessage(new Message("default","The policies for the selected collections were cleared."));
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.administrative;
import java.io.IOException;
import java.sql.SQLException;
import java.io.File;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.servlet.multipart.Part;
import org.apache.cocoon.servlet.multipart.PartOnDisk;
import org.dspace.app.bulkedit.BulkEditChange;
import org.dspace.app.bulkedit.DSpaceCSV;
import org.dspace.app.bulkedit.MetadataImport;
import org.dspace.app.bulkedit.MetadataImportException;
import org.dspace.app.bulkedit.MetadataImportInvalidHeadingException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.LogManager;
/**
* Utility methods to processes MetadataImport actions. These methods are used
* exclusively from the administrative flow scripts.
*
* @author Kim Shepherd
*/
public class FlowMetadataImportUtils
{
/** Language Strings */
private static final Message T_upload_successful = new Message("default", "xmlui.administrative.metadataimport.flow.upload_successful");
private static final Message T_upload_failed = new Message("default", "xmlui.administrative.metadataimport.flow.upload_failed");
private static final Message T_upload_badschema = new Message("default", "xmlui.administrative.metadataimport.flow.upload_badschema");
private static final Message T_upload_badelement = new Message("default", "xmlui.administrative.metadataimport.flow.upload_badelement");
private static final Message T_import_successful = new Message("default", "xmlui.administrative.metadataimport.flow.import_successful");
private static final Message T_import_failed = new Message("default", "xmlui.administrative.metadataimport.flow.import_failed");
private static final Message T_over_limit = new Message("default", "xmlui.administrative.metadataimport.flow.over_limit");
private static final Message T_no_changes = new Message("default", "xmlui.administrative.metadataimport.general.no_changes");
// Other variables
private static final int limit = ConfigurationManager.getIntProperty("bulkedit.gui-item-limit", 20);
private static Logger log = Logger.getLogger(FlowMetadataImportUtils.class);
public static FlowResult processMetadataImport(Context context,Request request) throws SQLException, AuthorizeException, IOException, Exception
{
FlowResult result = new FlowResult();
result.setContinue(false);
DSpaceCSV csv = (DSpaceCSV)request.getSession().getAttribute("csv");
if(csv != null)
{
try {
// Run the import
MetadataImport mImport = new MetadataImport(context, csv.getCSVLines());
List<BulkEditChange> changes = mImport.runImport(true, false, false, false);
// Commit the changes
context.commit();
request.setAttribute("changes",changes);
request.getSession().removeAttribute("csv");
log.debug(LogManager.getHeader(context, "metadataimport", changes.size() + " items changed"));
if(changes.size() > 0) {
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_import_successful);
}
else {
result.setContinue(false);
result.setOutcome(false);
result.setMessage(T_no_changes);
}
}
catch(MetadataImportException e) {
result.setContinue(false);
result.setOutcome(false);
result.addError(e.getLocalizedMessage());
result.setMessage(T_import_failed);
log.debug(LogManager.getHeader(context, "metadataimport", "Error encountered while making changes - " + e.getMessage()));
}
}
else {
result.setContinue(false);
result.setOutcome(false);
result.setMessage(T_import_failed);
log.debug(LogManager.getHeader(context, "metadataimport", "Changes cancelled"));
}
return result;
}
public static FlowResult processUploadCSV(Context context, Request request) throws SQLException, AuthorizeException, IOException, Exception
{
FlowResult result = new FlowResult();
result.setContinue(false);
Object object = null;
if(request.get("file") != null) {
object = request.get("file");
}
Part filePart = null;
File file = null;
if (object instanceof Part)
{
filePart = (Part) object;
file = ((PartOnDisk)filePart).getFile();
}
if (filePart != null && filePart.getSize() > 0)
{
String name = filePart.getUploadName();
while (name.indexOf('/') > -1)
{
name = name.substring(name.indexOf('/') + 1);
}
while (name.indexOf('\\') > -1)
{
name = name.substring(name.indexOf('\\') + 1);
}
try {
log.info(LogManager.getHeader(context, "metadataimport", "loading file"));
// Process CSV without import
DSpaceCSV csv = new DSpaceCSV(file, context);
if (!file.delete())
{
log.error("Unable to delete CSV file");
}
MetadataImport mImport = new MetadataImport(context, csv.getCSVLines());
List<BulkEditChange> changes = mImport.runImport(false, false, false, false);
log.debug(LogManager.getHeader(context, "metadataimport", changes.size() + " items with changes identified"));
if(changes.size() > 0)
{
if(changes.size() > limit)
{
result.setContinue(false);
result.setOutcome(false);
result.setMessage(T_over_limit);
log.info(LogManager.getHeader(context, "metadataimport", "too many changes - " +
changes.size() + " (" + limit + " allowed)"));
}
else
{
// Success!
// Set session and request attributes
request.setAttribute("changes", changes);
request.getSession().setAttribute("csv", csv);
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_upload_successful);
}
}
else
{
result.setContinue(false);
result.setOutcome(false);
result.setMessage(T_no_changes);
}
}
catch(MetadataImportInvalidHeadingException mihe) {
result.setContinue(false);
result.setOutcome(false);
if (mihe.getType().equals("" + MetadataImportInvalidHeadingException.SCHEMA))
{
result.setMessage(T_upload_badschema);
}
else
{
result.setMessage(T_upload_badelement);
}
result.setCharacters(mihe.getBadHeader());
}
catch(MetadataImportException e) {
result.setContinue(false);
result.setOutcome(false);
result.setMessage(T_upload_failed);
log.debug(LogManager.getHeader(context, "metadataimport", "Error encountered while looking for changes - " + e.getMessage()));
}
}
else
{
result.setContinue(false);
result.setOutcome(false);
result.setMessage(T_upload_failed);
}
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.administrative;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
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.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.RequestUtils;
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.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseItem;
import org.dspace.browse.BrowserScope;
import org.dspace.sort.SortOption;
import org.dspace.sort.SortException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCDate;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.xml.sax.SAXException;
/**
* Implements all the browse functionality (browse by title, subject, authors,
* etc.) The types of browse available are configurable by the implementor. See
* dspace.cfg and documentation for instructions on how to configure.
*
* @author Graham Triggs
*/
public class WithdrawnItems extends AbstractDSpaceTransformer implements
CacheableProcessingComponent
{
private static final Logger log = Logger.getLogger(WithdrawnItems.class);
/**
* Static Messages for common text
*/
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_go = message("xmlui.general.go");
private static final Message T_update = message("xmlui.general.update");
private static final Message T_choose_month = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.choose_month");
private static final Message T_choose_year = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.choose_year");
private static final Message T_jump_year = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_year");
private static final Message T_jump_year_help = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_year_help");
private static final Message T_jump_select = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_select");
private static final Message T_starts_with = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.starts_with");
private static final Message T_starts_with_help = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.starts_with_help");
private static final Message T_sort_by = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.sort_by");
private static final Message T_order = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.order");
private static final Message T_rpp = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.rpp");
private static final Message T_order_asc = message("xmlui.ArtifactBrowser.ConfigurableBrowse.order.asc");
private static final Message T_order_desc = message("xmlui.ArtifactBrowser.ConfigurableBrowse.order.desc");
private static final String WITHDRAWN_URL_BASE = "withdrawn";
/**
* These variables dictate when the drop down list of years is to break from
* 1 year increments, to 5 year increments, to 10 year increments, and
* finally to stop.
*/
private static final int ONE_YEAR_LIMIT = 10;
private static final int FIVE_YEAR_LIMIT = 30;
private static final int TEN_YEAR_LIMIT = 100;
/** Cached validity object */
private SourceValidity validity;
/** Cached UI parameters, results and messages */
private BrowseParams userParams;
private BrowseInfo browseInfo;
private Message titleMessage = null;
private Message trailMessage = null;
public Serializable getKey()
{
try
{
BrowseParams params = getUserParams();
String key = params.getKey();
if (key != null)
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
{
key += "-" + dso.getHandle();
}
return HashUtil.hash(key);
}
}
catch (SQLException e)
{
log.error("Database error", e);
}
catch (UIException e)
{
log.error("UI error", e);
}
return "0";
}
public SourceValidity getValidity()
{
if (validity == null)
{
try
{
DSpaceValidity newValidity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
{
newValidity.add(dso);
}
BrowseInfo info = getBrowseInfo();
// Are we browsing items, or unique metadata?
if (isItemBrowse(info))
{
// Add the browse items to the validity
for (BrowseItem item : (java.util.List<BrowseItem>) info.getResults())
{
newValidity.add(item);
}
}
else
{
// Add the metadata to the validity
for (String[] singleEntry : browseInfo.getStringResults())
{
newValidity.add(singleEntry[0]+"#"+singleEntry[1]);
}
}
validity = newValidity;
}
catch (SQLException e)
{
log.error("Database error", e);
}
catch (UIException e)
{
log.error("UI error", e);
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException,
SQLException, IOException, AuthorizeException
{
BrowseInfo info = getBrowseInfo();
pageMeta.addMetadata("title").addContent(getTitleMessage(info));
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
if (dso != null)
{
HandleUtil.buildHandleTrail(dso, pageMeta, contextPath);
}
pageMeta.addTrail().addContent(getTrailMessage(info));
}
/**
* Add the browse-title division.
*/
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException,
IOException, AuthorizeException
{
BrowseParams params = getUserParams();
BrowseInfo info = getBrowseInfo();
String type = "withdrawn";
// Build the DRI Body
Division div = body.addDivision("browse-by-" + type, "primary");
div.setHead(getTitleMessage(info));
// Build the internal navigation (jump lists)
addBrowseJumpNavigation(div, info, params);
// Build the sort and display controls
addBrowseControls(div, info, params);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-" + type + "-results", "primary");
// Add the pagination
if (info.getTotal() <= 0)
{
results.setSimplePagination(0, 0, 0, null, null);
}
else
{
results.setSimplePagination(info.getTotal(), browseInfo.getOverallPosition() + 1,
browseInfo.getOverallPosition() + browseInfo.getResultCount(), getPreviousPageURL(
params, info), getNextPageURL(params, info));
}
// Reference all the browsed items
ReferenceSet referenceSet = results.addReferenceSet("browse-by-" + type,
ReferenceSet.TYPE_SUMMARY_LIST, type, null);
// Are we browsing items, or unique metadata?
if (isItemBrowse(info))
{
// Add the items to the browse results
for (BrowseItem item : (java.util.List<BrowseItem>) info.getResults())
{
referenceSet.addReference(item);
}
}
else // browsing a list of unique metadata entries
{
// Create a table for the results
Table singleTable = results.addTable("browse-by-" + type + "-results",
browseInfo.getResultCount() + 1, 1);
// Add the column heading
singleTable.addRow(Row.ROLE_HEADER).addCell().addContent(
message("xmlui.ArtifactBrowser.ConfigurableBrowse." + type + ".column_heading"));
// Iterate each result
for (String[] singleEntry : browseInfo.getStringResults())
{
// Create a Map of the query parameters for the link
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put(BrowseParams.TYPE, encodeForURL(type));
if (singleEntry[1] != null)
{
queryParams.put(BrowseParams.FILTER_VALUE[1], encodeForURL(
singleEntry[1]));
}
else
{
queryParams.put(BrowseParams.FILTER_VALUE[0], encodeForURL(
singleEntry[0]));
}
// Create an entry in the table, and a linked entry
Cell cell = singleTable.addRow().addCell();
cell.addXref(super.generateURL(WITHDRAWN_URL_BASE, queryParams), singleEntry[0]);
}
}
}
/**
* Recycle
*/
public void recycle()
{
this.validity = null;
this.userParams = null;
this.browseInfo = null;
this.titleMessage = null;
this.trailMessage = null;
super.recycle();
}
/**
* Makes the jump-list navigation for the results
*
* @param div
* @param info
* @param params
* @throws WingException
*/
private void addBrowseJumpNavigation(Division div, BrowseInfo info, BrowseParams params)
throws WingException
{
// Prepare a Map of query parameters required for all links
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.putAll(params.getCommonParameters());
queryParams.putAll(params.getControlParameters());
// Navigation aid (really this is a poor version of pagination)
Division jump = div.addInteractiveDivision("browse-navigation", WITHDRAWN_URL_BASE,
Division.METHOD_POST, "secondary navigation");
// Add all the query parameters as hidden fields on the form
for (Map.Entry<String, String> param : queryParams.entrySet())
{
jump.addHidden(param.getKey()).setValue(param.getValue());
}
// If this is a date based browse, render the date navigation
if (isSortedByDate(info))
{
Para jumpForm = jump.addPara();
// Create a select list to choose a month
jumpForm.addContent(T_jump_select);
Select month = jumpForm.addSelect(BrowseParams.MONTH);
month.addOption(false, "-1", T_choose_month);
for (int i = 1; i <= 12; i++)
{
month.addOption(false, String.valueOf(i), DCDate.getMonthName(i, Locale
.getDefault()));
}
// Create a select list to choose a year
Select year = jumpForm.addSelect(BrowseParams.YEAR);
year.addOption(false, "-1", T_choose_year);
int currentYear = DCDate.getCurrent().getYear();
int i = currentYear;
// Calculate where to move from 1, 5 to 10 year jumps
int oneYearBreak = ((currentYear - ONE_YEAR_LIMIT) / 5) * 5;
int fiveYearBreak = ((currentYear - FIVE_YEAR_LIMIT) / 10) * 10;
int tenYearBreak = (currentYear - TEN_YEAR_LIMIT);
do
{
year.addOption(false, String.valueOf(i), String.valueOf(i));
if (i <= fiveYearBreak)
{
i -= 10;
}
else if (i <= oneYearBreak)
{
i -= 5;
}
else
{
i--;
}
}
while (i > tenYearBreak);
// Create a free text entry box for the year
jumpForm = jump.addPara();
jumpForm.addContent(T_jump_year);
jumpForm.addText(BrowseParams.STARTS_WITH).setHelp(T_jump_year_help);
jumpForm.addButton("submit").setValue(T_go);
}
else
{
// Create a clickable list of the alphabet
List jumpList = jump.addList("jump-list", List.TYPE_SIMPLE, "alphabet");
for (char c = 'A'; c <= 'Z'; c++)
{
Map<String, String> cQuery = new HashMap<String, String>(queryParams);
cQuery.put(BrowseParams.STARTS_WITH, Character.toString(c));
jumpList.addItemXref(super.generateURL(WITHDRAWN_URL_BASE, cQuery), Character
.toString(c));
}
// Create a free text field for the initial characters
Para jumpForm = jump.addPara();
jumpForm.addContent(T_starts_with);
jumpForm.addText(BrowseParams.STARTS_WITH).setHelp(T_starts_with_help);
jumpForm.addButton("submit").setValue(T_go);
}
}
/**
* Add the controls to changing sorting and display options.
*
* @param div
* @param info
* @param params
* @throws WingException
*/
private void addBrowseControls(Division div, BrowseInfo info, BrowseParams params)
throws WingException
{
// Prepare a Map of query parameters required for all links
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.putAll(params.getCommonParameters());
Division controls = div.addInteractiveDivision("browse-controls", WITHDRAWN_URL_BASE,
Division.METHOD_POST, "browse controls");
// Add all the query parameters as hidden fields on the form
for (Map.Entry<String, String> param : queryParams.entrySet())
{
controls.addHidden(param.getKey()).setValue(param.getValue());
}
Para controlsForm = controls.addPara();
// If we are browsing a list of items
if (isItemBrowse(info)) // && info.isSecondLevel()
{
try
{
// Create a drop down of the different sort columns available
Set<SortOption> sortOptions = SortOption.getSortOptions();
// Only generate the list if we have multiple columns
if (sortOptions.size() > 1)
{
controlsForm.addContent(T_sort_by);
Select sortSelect = controlsForm.addSelect(BrowseParams.SORT_BY);
for (SortOption so : sortOptions)
{
sortSelect.addOption(so.equals(info.getSortOption()), so.getNumber(),
message("xmlui.ArtifactBrowser.ConfigurableBrowse.sort_by." + so.getName()));
}
}
}
catch (SortException se)
{
throw new WingException("Unable to get sort options", se);
}
}
// Create a control to changing ascending / descending order
controlsForm.addContent(T_order);
Select orderSelect = controlsForm.addSelect(BrowseParams.ORDER);
orderSelect.addOption("ASC".equals(params.scope.getOrder()), "ASC", T_order_asc);
orderSelect.addOption("DESC".equals(params.scope.getOrder()), "DESC", T_order_desc);
// Create a control for the number of records to display
controlsForm.addContent(T_rpp);
Select rppSelect = controlsForm.addSelect(BrowseParams.RESULTS_PER_PAGE);
for (int i = 5; i <= 100; i += 5)
{
rppSelect.addOption((i == info.getResultsPerPage()), i, Integer.toString(i));
}
// Create a control for the number of authors per item to display
// FIXME This is currently disabled, as the supporting functionality
// is not currently present in xmlui
//if (isItemBrowse(info))
//{
// controlsForm.addContent(T_etal);
// Select etalSelect = controlsForm.addSelect(BrowseParams.ETAL);
//
// etalSelect.addOption((info.getEtAl() < 0), 0, T_etal_all);
// etalSelect.addOption(1 == info.getEtAl(), 1, Integer.toString(1));
//
// for (int i = 5; i <= 50; i += 5)
// {
// etalSelect.addOption(i == info.getEtAl(), i, Integer.toString(i));
// }
//}
controlsForm.addButton("update").setValue(T_update);
}
/**
* The URL query string of of the previous page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as appropriate by the caller.
*/
private String getPreviousPageURL(BrowseParams params, BrowseInfo info) throws SQLException,
UIException
{
// Don't create a previous page link if this is the first page
if (info.isFirst())
{
return null;
}
Map<String, String> parameters = new HashMap<String, String>();
parameters.putAll(params.getCommonParameters());
parameters.putAll(params.getControlParameters());
if (info.hasPrevPage())
{
parameters.put(BrowseParams.OFFSET, encodeForURL(String.valueOf(info.getPrevOffset())));
}
return super.generateURL(WITHDRAWN_URL_BASE, parameters);
}
/**
* The URL query string of of the next page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as appropriate by the caller.
*/
private String getNextPageURL(BrowseParams params, BrowseInfo info) throws SQLException,
UIException
{
// Don't create a next page link if this is the last page
if (info.isLast())
{
return null;
}
Map<String, String> parameters = new HashMap<String, String>();
parameters.putAll(params.getCommonParameters());
parameters.putAll(params.getControlParameters());
if (info.hasNextPage())
{
parameters.put(BrowseParams.OFFSET, encodeForURL(String.valueOf(info.getNextOffset())));
}
return super.generateURL(WITHDRAWN_URL_BASE, parameters);
}
/**
* Get the query parameters supplied to the browse.
*
* @return
* @throws SQLException
* @throws UIException
*/
private BrowseParams getUserParams() throws SQLException, UIException
{
if (this.userParams != null)
{
return this.userParams;
}
Context context = ContextUtil.obtainContext(objectModel);
Request request = ObjectModelHelper.getRequest(objectModel);
BrowseParams params = new BrowseParams();
params.month = request.getParameter(BrowseParams.MONTH);
params.year = request.getParameter(BrowseParams.YEAR);
params.etAl = RequestUtils.getIntParameter(request, BrowseParams.ETAL);
params.scope = new BrowserScope(context);
// Are we in a community or collection?
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso instanceof Community)
{
params.scope.setCommunity((Community) dso);
}
if (dso instanceof Collection)
{
params.scope.setCollection((Collection) dso);
}
try
{
int sortBy = RequestUtils.getIntParameter(request, BrowseParams.SORT_BY);
BrowseIndex bi = BrowseIndex.getWithdrawnBrowseIndex();
// If we don't have a sort column
if (sortBy == -1)
{
// Get the default one
SortOption so = bi.getSortOption();
if (so != null)
{
sortBy = so.getNumber();
}
}
params.scope.setBrowseIndex(bi);
params.scope.setSortBy(sortBy);
params.scope.setJumpToItem(RequestUtils.getIntParameter(request, BrowseParams.JUMPTO_ITEM));
params.scope.setOrder(request.getParameter(BrowseParams.ORDER));
params.scope.setOffset(RequestUtils.getIntParameter(request, BrowseParams.OFFSET));
params.scope.setResultsPerPage(RequestUtils.getIntParameter(request,
BrowseParams.RESULTS_PER_PAGE));
params.scope.setStartsWith(request.getParameter(BrowseParams.STARTS_WITH));
String filterValue = request.getParameter(BrowseParams.FILTER_VALUE[0]);
if (filterValue == null)
{
filterValue = request.getParameter(BrowseParams.FILTER_VALUE[1]);
}
else
{
params.scope.setAuthorityValue(filterValue);
}
params.scope.setFilterValue(filterValue);
params.scope.setJumpToValue(request.getParameter(BrowseParams.JUMPTO_VALUE));
params.scope.setJumpToValueLang(request.getParameter(BrowseParams.JUMPTO_VALUE_LANG));
params.scope.setFilterValueLang(request.getParameter(BrowseParams.FILTER_VALUE_LANG));
// Filtering to a value implies this is a second level browse
if (params.scope.getFilterValue() != null)
{
params.scope.setBrowseLevel(1);
}
// if year and perhaps month have been selected, we translate these
// into "startsWith"
// if startsWith has already been defined then it is overwritten
if (params.year != null && !"".equals(params.year) && !"-1".equals(params.year))
{
String startsWith = params.year;
if ((params.month != null) && !"-1".equals(params.month)
&& !"".equals(params.month))
{
// subtract 1 from the month, so the match works
// appropriately
if ("ASC".equals(params.scope.getOrder()))
{
params.month = Integer.toString((Integer.parseInt(params.month) - 1));
}
// They've selected a month as well
if (params.month.length() == 1)
{
// Ensure double-digit month number
params.month = "0" + params.month;
}
startsWith = params.year + "-" + params.month;
if ("ASC".equals(params.scope.getOrder()))
{
startsWith = startsWith + "-32";
}
}
params.scope.setStartsWith(startsWith);
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to create browse parameters", bex);
}
this.userParams = params;
return params;
}
/**
* Get the results of the browse. If the results haven't been generated yet,
* then this will perform the browse.
*
* @return
* @throws SQLException
* @throws UIException
*/
private BrowseInfo getBrowseInfo() throws SQLException, UIException
{
if (this.browseInfo != null)
{
return this.browseInfo;
}
Context context = ContextUtil.obtainContext(objectModel);
// Get the parameters we will use for the browse
// (this includes a browse scope)
BrowseParams params = getUserParams();
try
{
// Create a new browse engine, and perform the browse
BrowseEngine be = new BrowseEngine(context);
this.browseInfo = be.browse(params.scope);
// figure out the setting for author list truncation
if (params.etAl < 0)
{
// there is no limit, or the UI says to use the default
int etAl = ConfigurationManager.getIntProperty("webui.browse.author-limit");
if (etAl != 0)
{
this.browseInfo.setEtAl(etAl);
}
}
else if (params.etAl == 0) // 0 is the user setting for unlimited
{
this.browseInfo.setEtAl(-1); // but -1 is the application
// setting for unlimited
}
else
// if the user has set a limit
{
this.browseInfo.setEtAl(params.etAl);
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to process browse", bex);
}
return this.browseInfo;
}
/**
* Is this a browse on a list of items, or unique metadata values?
*
* @param info
* @return
*/
private boolean isItemBrowse(BrowseInfo info)
{
return info.getBrowseIndex().isItemIndex() || info.isSecondLevel();
}
/**
* Is this browse sorted by date?
* @param info
* @return
*/
private boolean isSortedByDate(BrowseInfo info)
{
return info.getSortOption().isDate() ||
(info.getBrowseIndex().isDate() && info.getSortOption().isDefault());
}
private Message getTitleMessage(BrowseInfo info)
{
if (titleMessage == null)
{
BrowseIndex bix = info.getBrowseIndex();
// For a second level browse (ie. items for author),
// get the value we are focussing on (ie. author).
// (empty string if none).
String value = (info.hasValue() ? "\"" + info.getValue() + "\"" : "");
// Get the name of any scoping element (collection / community)
String scopeName = "";
if (info.getBrowseContainer() != null)
{
scopeName = info.getBrowseContainer().getName();
}
else
{
scopeName = "";
}
if (bix.isMetadataIndex())
{
titleMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.title.metadata." + bix.getName())
.parameterize(scopeName, value);
}
else if (info.getSortOption() != null)
{
titleMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.title.item." + info.getSortOption().getName())
.parameterize(scopeName, value);
}
else
{
titleMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.title.item." + bix.getSortOption().getName())
.parameterize(scopeName, value);
}
}
return titleMessage;
}
private Message getTrailMessage(BrowseInfo info)
{
if (trailMessage == null)
{
BrowseIndex bix = info.getBrowseIndex();
// Get the name of any scoping element (collection / community)
String scopeName = "";
if (info.getBrowseContainer() != null)
{
scopeName = info.getBrowseContainer().getName();
}
else
{
scopeName = "";
}
if (bix.isMetadataIndex())
{
trailMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.trail.metadata." + bix.getName())
.parameterize(scopeName);
}
else if (info.getSortOption() != null)
{
trailMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.trail.item." + info.getSortOption().getName())
.parameterize(scopeName);
}
else
{
trailMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.trail.item." + bix.getSortOption().getName())
.parameterize(scopeName);
}
}
return trailMessage;
}
}
/*
* Helper class to track browse parameters
*/
class BrowseParams
{
String month;
String year;
int etAl;
BrowserScope scope;
static final String MONTH = "month";
static final String YEAR = "year";
static final String ETAL = "etal";
static final String TYPE = "type";
static final String JUMPTO_ITEM = "focus";
static final String JUMPTO_VALUE = "vfocus";
static final String JUMPTO_VALUE_LANG = "vfocus_lang";
static final String ORDER = "order";
static final String OFFSET = "offset";
static final String RESULTS_PER_PAGE = "rpp";
static final String SORT_BY = "sort_by";
static final String STARTS_WITH = "starts_with";
static final String[] FILTER_VALUE = new String[]{"value","authority"};
static final String FILTER_VALUE_LANG = "value_lang";
/*
* Creates a map of the browse options common to all pages (type / value /
* value language)
*/
Map<String, String> getCommonParameters() throws UIException
{
Map<String, String> paramMap = new HashMap<String, String>();
if (scope.getFilterValue() != null)
{
paramMap.put(scope.getAuthorityValue() != null?
BrowseParams.FILTER_VALUE[1]:BrowseParams.FILTER_VALUE[0],
AbstractDSpaceTransformer.encodeForURL(
scope.getFilterValue()));
}
if (scope.getFilterValueLang() != null)
{
paramMap.put(BrowseParams.FILTER_VALUE_LANG, AbstractDSpaceTransformer.encodeForURL(
scope.getFilterValueLang()));
}
return paramMap;
}
/*
* Creates a Map of the browse control options (sort by / ordering / results
* per page / authors per item)
*/
Map<String, String> getControlParameters() throws UIException
{
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put(BrowseParams.SORT_BY, Integer.toString(this.scope.getSortBy()));
paramMap.put(BrowseParams.ORDER, AbstractDSpaceTransformer.encodeForURL(this.scope.getOrder()));
paramMap.put(BrowseParams.RESULTS_PER_PAGE, Integer
.toString(this.scope.getResultsPerPage()));
paramMap.put(BrowseParams.ETAL, Integer.toString(this.etAl));
return paramMap;
}
String getKey()
{
try
{
String key = "";
key += "-" + scope.getBrowseIndex().getName();
key += "-" + scope.getBrowseLevel();
key += "-" + scope.getStartsWith();
key += "-" + scope.getResultsPerPage();
key += "-" + scope.getSortBy();
key += "-" + scope.getSortOption().getNumber();
key += "-" + scope.getOrder();
key += "-" + scope.getOffset();
key += "-" + scope.getJumpToItem();
key += "-" + scope.getFilterValue();
key += "-" + scope.getFilterValueLang();
key += "-" + scope.getJumpToValue();
key += "-" + scope.getJumpToValueLang();
key += "-" + etAl;
return key;
}
catch (BrowseException e)
{
return null; // ignore exception and return no key
}
}
};
| 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.administrative;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dspace.app.xmlui.wing.Message;
/**
* This class represents the results that may be generated during a flow script
* in this administrative section. Typicaly, some method preforms an operation
* and returns an object of type FlowResult, then the flow script can inspect
* the results object to determine what the next course of action is.
*
* Basicaly, this results object stores all the errors and contiunation states
* that need to be represented. There are four types of information stored:
*
* 1) Continuation, this is a simple boolean variable that indicates wheather
* the required operation is complete and the user may continue on to the next step.
*
* 2) Notice information, this is a simple encoding of a notice message to be displayed
* to the user on their next step. There are four parts: outcome, header, message, and
* characters. See each field for more description on each part. Note: either a message
* or characters are required.
*
* 3) Errors, this is a list of errors that were encountered during processing.
* Typical, it just consists of a list of errored fields. However occasionaly there
* may be other specialized errors listed.
*
* 4) Parameters, this is a map of attached parameters that may be relevnt to the
* result. This should be used for things such as generated id's when objects are newly
* created.
*
* @author Scott Phillips
*/
public class FlowResult {
/**
* Determine wheather the operation has been completed enough that the user
* may successufully continue on to the next step.
*/
private boolean continuep;
/**
* Notice parameters:
*
* Outcome: The outcome of the notice, may be either success, failure, or netural.
*
* Header: The notice's label, an i18n dictionary key.
*
* message: The main body of the notice, an i18n dictionary key.
*
* characters: Supplementaiol information for the notice, plain text. This is
* typicaly used for exepctions.
*
*/
private enum Outcome{ SUCCESS, FAILURE, NETURAL};
private Outcome outcome = Outcome.NETURAL;
private Message header;
private Message message;
private String characters;
/**
* A list of errors encountered while processing this operation.
*/
private List<String> errors;
/**
* Any parameters that may be attached to this result.
*/
private Map<String,Object> parameters;
/**
* Set the continuation parameter determining if the
* user should progress to the next step in the flow.
*/
public void setContinue(boolean continuep)
{
this.continuep = continuep;
}
/**
* Determine if the user should progress to the
* next step in the flow.
*
* @return the continuation parameter
*/
public boolean getContinue()
{
return this.continuep;
}
/**
* Set the notice outcome to either success or failure. Note,
* the default outcome is netural, once an outcome is set the
* netural outcome can never be atained again.
*
* @param success True for success, false for failure.
*/
public void setOutcome(boolean success)
{
if (success)
{
outcome = Outcome.SUCCESS;
}
else
{
outcome = Outcome.FAILURE;
}
}
/**
* Get the notice outcome in string form, either success
* or failure. If the outcome is netural then null is returned.
*/
public String getOutcome()
{
if (outcome == Outcome.SUCCESS)
{
return "success";
}
else if (outcome == Outcome.FAILURE)
{
return "failure";
}
return null;
}
/**
* Set the notice header.
*
* This must be an i18n dictionary key
*/
public void setHeader(Message header)
{
this.header = header;
}
/**
* Return the notice header
*/
public String getHeader()
{
if (this.header != null)
{
return this.header.getKey();
}
return null;
}
/**
* Set the notice message
*
* This must be an i18n dictionary key
*/
public void setMessage(Message message)
{
this.message = message;
}
/**
* return the notice message
*/
public String getMessage()
{
if (this.message != null)
{
return this.message.getKey();
}
return null;
}
/**
* Set the notice characters
*/
public void setCharacters(String characters)
{
this.characters = characters;
}
/**
* Return the notice characters
*/
public String getCharacters()
{
return this.characters;
}
/**
* Set the results errors, note this will remove any previous errors.
*
* @param errors New error list.
*/
public void setErrors(List<String> errors)
{
this.errors = errors;
}
/**
* Add a new single error to the error list.
*
* @param newError New error.
*/
public void addError(String newError)
{
if (this.errors == null)
{
this.errors = new ArrayList<String>();
}
this.errors.add(newError);
}
/**
* Return the current list of errors.
*/
public List<String> getErrors()
{
return this.errors;
}
/**
* Return the list of errors in string form, i.e. a comma seperated list
* of errors. If there are no errors then null is returned.
*/
public String getErrorString()
{
if (errors == null || errors.size() == 0)
{
return null;
}
String errorString = null;
for (String error : errors)
{
if (errorString == null)
{
errorString = error;
}
else
{
errorString += "," + error;
}
}
return errorString;
}
/**
* Attatch a new parameter to this result object with the specified
* name & value.
*
* @param name The parameter's name
* @param value The parameter's value.
*/
public void setParameter(String name, Object value)
{
if (this.parameters == null)
{
this.parameters = new HashMap<String, Object>();
}
this.parameters.put(name, value);
}
/**
* Find the attached parameter with the given name. If no parameter is
* found for the specified name then null is returned.
*
* @param name The parameter's name.
* @return The parameter's value.
*/
public Object getParameter(String name)
{
if (this.parameters == null)
{
return null;
}
return this.parameters.get(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.administrative;
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.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.dspace.harvest.OAIHarvester;
/**
* Update the alert system based upon the form submitted from the control panel.
*
* @author Scott Phillips
*/
public class ControlPanelAction extends AbstractAction
{
/**
* Either activate or deactivate the alert system.
*/
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel,
String source, Parameters parameters) throws Exception
{
Request request = ObjectModelHelper.getRequest(objectModel);
// In any case update the system-wide alert system
String message = request.getParameter("message");
String countdownString = request.getParameter("countdown");
String restrictsessions = request.getParameter("restrictsessions");
int countdown = -1;
if (countdownString != null)
{
try {
countdown = Integer.valueOf(countdownString);
}
catch (NumberFormatException nfe)
{
// just ignore it.
}
}
// Update the message
if (message != null)
{
SystemwideAlerts.setMessage(message);
}
if (countdown >= 0)
{
// Convert from minutes to milliseconds;
countdown = countdown * 60 * 1000;
// Figure out when the count down is.
long countDownTo = System.currentTimeMillis() + countdown;
// set it.
SystemwideAlerts.setCountDownToo(countDownTo);
}
if (restrictsessions != null && restrictsessions.length() > 0)
{
try {
int newState = Integer.valueOf(restrictsessions);
SystemwideAlerts.setRestrictSessions(newState);
}
catch (NumberFormatException nfe)
{
// ignore it
}
}
if (request.getParameter("submit_activate") != null)
{
SystemwideAlerts.activateAlert();
// Ensure the alert is active for this request, return
// a success so the sitemap can add the alert in.
return new HashMap();
}
else if (request.getParameter("submit_deactivate") != null)
{
SystemwideAlerts.deactivateAlert();
}
else if (request.getParameter("submit_harvest_start") != null) {
OAIHarvester.startNewScheduler();
}
else if (request.getParameter("submit_harvest_resume") != null) {
OAIHarvester.resumeScheduler();
}
else if (request.getParameter("submit_harvest_pause") != null) {
OAIHarvester.pauseScheduler();
}
else if (request.getParameter("submit_harvest_stop") != null) {
OAIHarvester.stopScheduler();
}
else if (request.getParameter("submit_harvest_reset") != null) {
OAIHarvester.resetScheduler();
}
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.administrative;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
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.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.itemexport.ItemExport;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
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.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
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.eperson.Group;
import org.xml.sax.SAXException;
/**
*
* Create the navigation options for everything in the administrative aspects. This includes
* Epeople, group, item, access control, and registry management.
*
* @author Scott Phillips
* @author Afonso Araujo Neto (internationalization)
* @author Alexey Maslov
* @author Jay Paz
*/
public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
private static final Message T_context_head = message("xmlui.administrative.Navigation.context_head");
private static final Message T_context_edit_item = message("xmlui.administrative.Navigation.context_edit_item");
private static final Message T_context_edit_collection = message("xmlui.administrative.Navigation.context_edit_collection");
private static final Message T_context_item_mapper = message("xmlui.administrative.Navigation.context_item_mapper");
private static final Message T_context_edit_community = message("xmlui.administrative.Navigation.context_edit_community");
private static final Message T_context_create_collection = message("xmlui.administrative.Navigation.context_create_collection");
private static final Message T_context_create_subcommunity = message("xmlui.administrative.Navigation.context_create_subcommunity");
private static final Message T_context_create_community = message("xmlui.administrative.Navigation.context_create_community");
private static final Message T_context_export_metadata = message("xmlui.administrative.Navigation.context_export_metadata");
private static final Message T_administrative_import_metadata = message("xmlui.administrative.Navigation.administrative_import_metadata");
private static final Message T_administrative_head = message("xmlui.administrative.Navigation.administrative_head");
private static final Message T_administrative_access_control = message("xmlui.administrative.Navigation.administrative_access_control");
private static final Message T_administrative_people = message("xmlui.administrative.Navigation.administrative_people");
private static final Message T_administrative_groups = message("xmlui.administrative.Navigation.administrative_groups");
private static final Message T_administrative_authorizations = message("xmlui.administrative.Navigation.administrative_authorizations");
private static final Message T_administrative_registries = message("xmlui.administrative.Navigation.administrative_registries");
private static final Message T_administrative_metadata = message("xmlui.administrative.Navigation.administrative_metadata");
private static final Message T_administrative_format = message("xmlui.administrative.Navigation.administrative_format");
private static final Message T_administrative_items = message("xmlui.administrative.Navigation.administrative_items");
private static final Message T_administrative_withdrawn = message("xmlui.administrative.Navigation.administrative_withdrawn");
private static final Message T_administrative_control_panel = message("xmlui.administrative.Navigation.administrative_control_panel");
private static final Message T_statistics = message("xmlui.administrative.Navigation.statistics");
private static final Message T_context_export_item = message("xmlui.administrative.Navigation.context_export_item");
private static final Message T_context_export_collection = message("xmlui.administrative.Navigation.context_export_collection");
private static final Message T_context_export_community = message("xmlui.administrative.Navigation.context_export_community");
private static final Message T_account_export = message("xmlui.administrative.Navigation.account_export");
private static final Message T_my_account = message("xmlui.EPerson.Navigation.my_account");
/** Cached validity object */
private SourceValidity validity;
/** exports available for download */
java.util.List<String> availableExports = null;
/**
* Generate the unique cache key.
*
* @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 "0";
}
if (context.getCurrentUser() == null)
{
return HashUtil.hash("anonymous");
}
if (availableExports != null && availableExports.size()>0) {
StringBuilder key = new StringBuilder(context.getCurrentUser().getEmail());
for(String fileName : availableExports){
key.append(":").append(fileName);
}
return HashUtil.hash(key.toString());
}
return HashUtil.hash(context.getCurrentUser().getEmail());
}
/**
* 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;
}
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) throws ProcessingException, SAXException, IOException {
super.setup(resolver, objectModel, src, parameters);
availableExports = null;
if (context.getCurrentUser() != null)
{
try
{
availableExports = ItemExport.getExportsAvailable(context.getCurrentUser());
}
catch (Exception e)
{
throw new ProcessingException("Error getting available exports", e);
}
}
}
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");
List context = options.addList("context");
List admin = options.addList("administrative");
account.setHead(T_my_account);
// My Account options
if(availableExports!=null && availableExports.size()>0){
account.addItem().addXref(contextPath+"/admin/export", T_account_export);
}
//Check if a system administrator
boolean isSystemAdmin = AuthorizeManager.isAdmin(this.context);
// Context Administrative options
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso instanceof Item)
{
Item item = (Item) dso;
if (item.canEdit())
{
context.setHead(T_context_head);
context.addItem().addXref(contextPath+"/admin/item?itemID="+item.getID(), T_context_edit_item);
if (AuthorizeManager.isAdmin(this.context, dso))
{
context.addItem().addXref(contextPath+"/admin/export?itemID="+item.getID(), T_context_export_item );
context.addItem().addXref(contextPath+ "/csv/handle/"+dso.getHandle(),T_context_export_metadata );
}
}
}
else if (dso instanceof Collection)
{
Collection collection = (Collection) dso;
// can they admin this collection?
if (collection.canEditBoolean(true))
{
context.setHead(T_context_head);
context.addItemXref(contextPath+"/admin/collection?collectionID=" + collection.getID(), T_context_edit_collection);
context.addItemXref(contextPath+"/admin/mapper?collectionID="+collection.getID(), T_context_item_mapper);
if (AuthorizeManager.isAdmin(this.context, dso))
{
context.addItem().addXref(contextPath+"/admin/export?collectionID="+collection.getID(), T_context_export_collection );
context.addItem().addXref(contextPath+ "/csv/handle/"+dso.getHandle(),T_context_export_metadata );
}
}
}
else if (dso instanceof Community)
{
Community community = (Community) dso;
// can they admin this collection?
if (community.canEditBoolean())
{
context.setHead(T_context_head);
context.addItemXref(contextPath+"/admin/community?communityID=" + community.getID(), T_context_edit_community);
if (AuthorizeManager.isAdmin(this.context, dso))
{
context.addItem().addXref(contextPath + "/admin/export?communityID=" + community.getID(), T_context_export_community);
}
context.addItem().addXref(contextPath+ "/csv/handle/"+dso.getHandle(),T_context_export_metadata );
}
// can they add to this community?
if (AuthorizeManager.authorizeActionBoolean(this.context, community,Constants.ADD))
{
context.setHead(T_context_head);
context.addItemXref(contextPath+"/admin/collection?createNew&communityID=" + community.getID(), T_context_create_collection);
context.addItemXref(contextPath+"/admin/community?createNew&communityID=" + community.getID(), T_context_create_subcommunity);
}
}
if (isSystemAdmin && ("community-list".equals(this.sitemapURI) || "".equals(this.sitemapURI)))
{
// Only System administrators can create top-level communities
context.setHead(T_context_head);
context.addItemXref(contextPath+"/admin/community?createNew", T_context_create_community);
}
// System Administrator options!
if (isSystemAdmin)
{
admin.setHead(T_administrative_head);
List epeople = admin.addList("epeople");
List registries = admin.addList("registries");
epeople.setHead(T_administrative_access_control);
epeople.addItemXref(contextPath+"/admin/epeople", T_administrative_people);
epeople.addItemXref(contextPath+"/admin/groups", T_administrative_groups);
epeople.addItemXref(contextPath+"/admin/authorize", T_administrative_authorizations);
registries.setHead(T_administrative_registries);
registries.addItemXref(contextPath+"/admin/metadata-registry",T_administrative_metadata);
registries.addItemXref(contextPath+"/admin/format-registry",T_administrative_format);
admin.addItemXref(contextPath+"/admin/item", T_administrative_items);
admin.addItemXref(contextPath+"/admin/withdrawn", T_administrative_withdrawn);
admin.addItemXref(contextPath+"/admin/panel", T_administrative_control_panel);
admin.addItemXref(contextPath+"/statistics", T_statistics);
admin.addItemXref(contextPath+ "/admin/metadataimport", T_administrative_import_metadata);
}
}
public int addContextualOptions(List context) throws SQLException, WingException
{
// How many options were added.
int options = 0;
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso instanceof Item)
{
Item item = (Item) dso;
if (item.canEdit())
{
context.addItem().addXref(contextPath+"/admin/item?itemID="+item.getID(), T_context_edit_item);
options++;
}
}
else if (dso instanceof Collection)
{
Collection collection = (Collection) dso;
// can they admin this collection?
if (AuthorizeManager.authorizeActionBoolean(this.context, collection, Constants.ADMIN))
{
context.addItemXref(contextPath+"/admin/collection?collectionID=" + collection.getID(), T_context_edit_collection);
context.addItemXref(contextPath+"/admin/mapper?collectionID="+collection.getID(), T_context_item_mapper);
options++;
}
}
else if (dso instanceof Community)
{
Community community = (Community) dso;
// can they admin this collection?
if (community.canEditBoolean())
{
context.addItemXref(contextPath+"/admin/community?communityID=" + community.getID(), T_context_edit_community);
options++;
}
// can they add to this community?
if (AuthorizeManager.authorizeActionBoolean(this.context, community,Constants.ADD))
{
context.addItemXref(contextPath+"/admin/collection?createNew&communityID=" + community.getID(), T_context_create_collection);
context.addItemXref(contextPath+"/admin/community?createNew&communityID=" + community.getID(), T_context_create_subcommunity);
options++;
}
}
if (("community-list".equals(this.sitemapURI) || "".equals(this.sitemapURI)) && AuthorizeManager.isAdmin(this.context))
{
context.addItemXref(contextPath+"/admin/community?createNew", T_context_create_community);
options++;
}
return options;
}
/**
* 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.administrative;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.commons.lang.StringUtils;
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.Item;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.app.xmlui.wing.element.TextArea;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.harvest.HarvestedCollection;
import org.dspace.harvest.OAIHarvester.HarvestScheduler;
import org.dspace.core.ConfigurationManager;
import org.dspace.eperson.EPerson;
import org.xml.sax.SAXException;
/**
* This page displays important (and some not-so important) systems
* type information about your running dspace.
*
* @author Jay Paz
* @author Scott Phillips
*/
public class ControlPanel extends AbstractDSpaceTransformer implements Serviceable{
/** Language Strings */
private static final Message T_DSPACE_HOME =
message("xmlui.general.dspace_home");
private static final Message T_title = message("xmlui.administrative.ControlPanel.title");
private static final Message T_trail = message("xmlui.administrative.ControlPanel.trail");
private static final Message T_head = message("xmlui.administrative.ControlPanel.head");
private static final Message T_option_java = message("xmlui.administrative.ControlPanel.option_java");
private static final Message T_option_dspace = message("xmlui.administrative.ControlPanel.option_dspace");
private static final Message T_option_alerts = message("xmlui.administrative.ControlPanel.option_alerts");
private static final Message T_seconds = message("xmlui.administrative.ControlPanel.seconds");
private static final Message T_hours = message("xmlui.administrative.ControlPanel.hours");
private static final Message T_minutes = message("xmlui.administrative.ControlPanel.minutes");
private static final Message T_JAVA_HEAD = message("xmlui.administrative.ControlPanel.java_head");
private static final Message T_JAVA_VERSION = message("xmlui.administrative.ControlPanel.java_version");
private static final Message T_JAVA_VENDOR = message("xmlui.administrative.ControlPanel.java_vendor");
private static final Message T_OS_NAME = message("xmlui.administrative.ControlPanel.os_name");
private static final Message T_OS_ARCH = message("xmlui.administrative.ControlPanel.os_arch");
private static final Message T_OS_VERSION = message("xmlui.administrative.ControlPanel.os_version");
private static final Message T_RUNTIME_HEAD = message("xmlui.administrative.ControlPanel.runtime_head");
private static final Message T_RUNTIME_PROCESSORS = message("xmlui.administrative.ControlPanel.runtime_processors");
private static final Message T_RUNTIME_MAX = message("xmlui.administrative.ControlPanel.runtime_max");
private static final Message T_RUNTIME_TOTAL = message("xmlui.administrative.ControlPanel.runtime_total");
private static final Message T_RUNTIME_USED = message("xmlui.administrative.ControlPanel.runtime_used");
private static final Message T_RUNTIME_FREE = message("xmlui.administrative.ControlPanel.runtime_free");
private static final Message T_DSPACE_HEAD = message("xmlui.administrative.ControlPanel.dspace_head");
private static final Message T_DSPACE_DIR = message("xmlui.administrative.ControlPanel.dspace_dir");
private static final Message T_DSPACE_URL = message("xmlui.administrative.ControlPanel.dspace_url");
private static final Message T_DSPACE_HOST_NAME = message("xmlui.administrative.ControlPanel.dspace_hostname");
private static final Message T_DSPACE_NAME = message("xmlui.administrative.ControlPanel.dspace_name");
private static final Message T_DB_NAME = message("xmlui.administrative.ControlPanel.db_name");
private static final Message T_DB_URL = message("xmlui.administrative.ControlPanel.db_url");
private static final Message T_DB_DRIVER = message("xmlui.administrative.ControlPanel.db_driver");
private static final Message T_DB_MAX_CONN = message("xmlui.administrative.ControlPanel.db_maxconnections");
private static final Message T_DB_MAX_WAIT = message("xmlui.administrative.ControlPanel.db_maxwait");
private static final Message T_DB_MAX_IDLE = message("xmlui.administrative.ControlPanel.db_maxidle");
private static final Message T_MAIL_SERVER = message("xmlui.administrative.ControlPanel.mail_server");
private static final Message T_MAIL_FROM_ADDRESS = message("xmlui.administrative.ControlPanel.mail_from_address");
private static final Message T_FEEDBACK_RECIPIENT = message("xmlui.administrative.ControlPanel.mail_feedback_recipient");
private static final Message T_MAIL_ADMIN = message("xmlui.administrative.ControlPanel.mail_admin");
private static final Message T_alerts_head = message("xmlui.administrative.ControlPanel.alerts_head");
private static final Message T_alerts_warning = message("xmlui.administrative.ControlPanel.alerts_warning");
private static final Message T_alerts_message_label = message("xmlui.administrative.ControlPanel.alerts_message_label");
private static final Message T_alerts_message_default = message("xmlui.administrative.ControlPanel.alerts_message_default");
private static final Message T_alerts_countdown_label = message("xmlui.administrative.ControlPanel.alerts_countdown_label");
private static final Message T_alerts_countdown_none = message("xmlui.administrative.ControlPanel.alerts_countdown_none");
private static final Message T_alerts_countdown_5 = message("xmlui.administrative.ControlPanel.alerts_countdown_5");
private static final Message T_alerts_countdown_15 = message("xmlui.administrative.ControlPanel.alerts_countdown_15");
private static final Message T_alerts_countdown_30 = message("xmlui.administrative.ControlPanel.alerts_countdown_30");
private static final Message T_alerts_countdown_60 = message("xmlui.administrative.ControlPanel.alerts_countdown_60");
private static final Message T_alerts_countdown_keep = message("xmlui.administrative.ControlPanel.alerts_countdown_keep");
private static final Message T_alerts_session_label = message("xmlui.administrative.ControlPanel.alerts_session_label");
private static final Message T_alerts_session_all_sessions = message("xmlui.administrative.ControlPanel.alerts_session_all_sessions");
private static final Message T_alerts_session_current_sessions = message("xmlui.administrative.ControlPanel.alerts_session_current_sessions");
private static final Message T_alerts_session_only_administrative = message("xmlui.administrative.ControlPanel.alerts_session_only_administrative_sessions");
private static final Message T_alerts_session_note = message("xmlui.administrative.ControlPanel.alerts_session_note");
private static final Message T_alerts_submit_activate = message("xmlui.administrative.ControlPanel.alerts_submit_activate");
private static final Message T_alerts_submit_deactivate = message("xmlui.administrative.ControlPanel.alerts_submit_deactivate");
private static final Message T_activity_head = message("xmlui.administrative.ControlPanel.activity_head");
private static final Message T_stop_anonymous = message("xmlui.administrative.ControlPanel.stop_anonymous");
private static final Message T_start_anonymous = message("xmlui.administrative.ControlPanel.start_anonymous");
private static final Message T_stop_bot = message("xmlui.administrative.ControlPanel.stop_bot");
private static final Message T_start_bot = message("xmlui.administrative.ControlPanel.start_bot");
private static final Message T_activity_sort_time = message("xmlui.administrative.ControlPanel.activity_sort_time");
private static final Message T_activity_sort_user = message("xmlui.administrative.ControlPanel.activity_sort_user");
private static final Message T_activity_sort_ip = message("xmlui.administrative.ControlPanel.activity_sort_ip");
private static final Message T_activity_sort_url = message("xmlui.administrative.ControlPanel.activity_sort_url");
private static final Message T_activity_sort_agent = message("xmlui.administrative.ControlPanel.activity_sort_Agent");
private static final Message T_activity_anonymous = message("xmlui.administrative.ControlPanel.activity_anonymous");
private static final Message T_activity_none = message("xmlui.administrative.ControlPanel.activity_none");
private static final Message T_select_panel = message("xmlui.administrative.ControlPanel.select_panel");
private static final Message T_option_harvest = message("xmlui.administrative.ControlPanel.option_harvest");
private static final Message T_harvest_scheduler_head = message("xmlui.administrative.ControlPanel.harvest_scheduler_head");
private static final Message T_harvest_label_status = message("xmlui.administrative.ControlPanel.harvest_label_status");
private static final Message T_harvest_label_actions = message("xmlui.administrative.ControlPanel.harvest_label_actions");
private static final Message T_harvest_submit_start = message("xmlui.administrative.ControlPanel.harvest_submit_start");
private static final Message T_harvest_submit_reset = message("xmlui.administrative.ControlPanel.harvest_submit_reset");
private static final Message T_harvest_submit_resume = message("xmlui.administrative.ControlPanel.harvest_submit_resume");
private static final Message T_harvest_submit_pause = message("xmlui.administrative.ControlPanel.harvest_submit_pause");
private static final Message T_harvest_submit_stop = message("xmlui.administrative.ControlPanel.harvest_submit_stop");
private static final Message T_harvest_label_collections = message("xmlui.administrative.ControlPanel.harvest_label_collections");
private static final Message T_harvest_label_active = message("xmlui.administrative.ControlPanel.harvest_label_active");
private static final Message T_harvest_label_queued = message("xmlui.administrative.ControlPanel.harvest_label_queued");
private static final Message T_harvest_label_oai_errors = message("xmlui.administrative.ControlPanel.harvest_label_oai_errors");
private static final Message T_harvest_label_internal_errors = message("xmlui.administrative.ControlPanel.harvest_label_internal_errors");
private static final Message T_harvest_head_generator_settings = message("xmlui.administrative.ControlPanel.harvest_head_generator_settings");
private static final Message T_harvest_label_oai_url = message("xmlui.administrative.ControlPanel.harvest_label_oai_url");
private static final Message T_harvest_label_oai_source = message("xmlui.administrative.ControlPanel.harvest_label_oai_source");
private static final Message T_harvest_head_harvester_settings = message("xmlui.administrative.ControlPanel.harvest_head_harvester_settings");
/**
* The service manager allows us to access the continuation's
* manager, it is obtained from the servicable API
*/
private ServiceManager serviceManager;
/**
* The five states that this page can be in.
*/
private enum OPTIONS {java, dspace, alerts, activity, harvest};
/**
* From the servicable api, give us a service manager.
*/
public void service(ServiceManager serviceManager) throws ServiceException
{
this.serviceManager = serviceManager;
}
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.addTrailLink(contextPath + "/admin/panel", T_trail);
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException {
if (!AuthorizeManager.isAdmin(context))
{
throw new AuthorizeException("You are not authorized to view this page.");
}
Request request = ObjectModelHelper.getRequest(objectModel);
OPTIONS option = null;
if (request.getParameter("java") != null)
{
option = OPTIONS.java;
}
if (request.getParameter("dspace") != null)
{
option = OPTIONS.dspace;
}
if (request.getParameter("alerts") != null)
{
option = OPTIONS.alerts;
}
if (request.getParameter("activity") != null)
{
option = OPTIONS.activity;
}
if (request.getParameter("harvest") != null)
{
option = OPTIONS.harvest;
}
Division div = body.addInteractiveDivision("control-panel", contextPath+"/admin/panel", Division.METHOD_POST, "primary administrative");
div.setHead(T_head);
// LIST: options
List options = div.addList("options",List.TYPE_SIMPLE,"horizontal");
// our options, selected or not....
if (option == OPTIONS.java)
{
options.addItem().addHighlight("bold").addXref("?java", T_option_java);
}
else
{
options.addItemXref("?java", T_option_java);
}
if (option == OPTIONS.dspace)
{
options.addItem().addHighlight("bold").addXref("?dspace", T_option_dspace);
}
else
{
options.addItemXref("?dspace", T_option_dspace);
}
if (option == OPTIONS.alerts)
{
options.addItem().addHighlight("bold").addXref("?alerts", T_option_alerts);
}
else
{
options.addItemXref("?alerts", T_option_alerts);
}
if (option == OPTIONS.harvest)
{
options.addItem().addHighlight("bold").addXref("?harvest", T_option_harvest);
}
else
{
options.addItemXref("?harvest", T_option_harvest);
}
String userSortTarget = "?activity";
if (request.getParameter("sortBy") != null)
{
userSortTarget += "&sortBy=" + request.getParameter("sortBy");
}
if (option == OPTIONS.activity)
{
options.addItem().addHighlight("bold").addXref(userSortTarget, "Current Activity");
}
else
{
options.addItemXref(userSortTarget, "Current Activity");
}
// The main content:
if (option == OPTIONS.java)
{
addJavaInformation(div);
}
else if (option == OPTIONS.dspace)
{
addDSpaceConfiguration(div);
}
else if (option == OPTIONS.alerts)
{
addAlerts(div);
}
else if (option == OPTIONS.activity)
{
addActivity(div);
}
else if (option == OPTIONS.harvest)
{
addHarvest(div);
}
else
{
div.addPara(T_select_panel);
}
}
/**
* Add specific java information including JRE, OS, and runtime memory statistics.
*/
private void addJavaInformation(Division div) throws WingException
{
// Get memory statistics
int processors = Runtime.getRuntime().availableProcessors();
long maxMemory = Runtime.getRuntime().maxMemory();
long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
long usedMemory = totalMemory-freeMemory;
// Convert bytes into MiB
maxMemory = maxMemory / 1024 / 1024;
totalMemory = totalMemory / 1024 / 1024;
usedMemory = usedMemory / 1024 / 1024;
freeMemory = freeMemory / 1024 / 1024;
// LIST: Java
List list = div.addList("javaOs");
list.setHead(T_JAVA_HEAD);
list.addLabel(T_JAVA_VERSION);
list.addItem(System.getProperty("java.version"));
list.addLabel(T_JAVA_VENDOR);
list.addItem(System.getProperty("java.vendor"));
list.addLabel(T_OS_NAME);
list.addItem(System.getProperty("os.name"));
list.addLabel(T_OS_ARCH);
list.addItem(System.getProperty("os.arch"));
list.addLabel(T_OS_VERSION);
list.addItem(System.getProperty("os.version"));
// LIST: memory
List runtime = div.addList("runtime");
runtime.setHead(T_RUNTIME_HEAD);
runtime.addLabel(T_RUNTIME_PROCESSORS);
runtime.addItem(String.valueOf(processors));
runtime.addLabel(T_RUNTIME_MAX);
runtime.addItem(String.valueOf(maxMemory) + " MiB");
runtime.addLabel(T_RUNTIME_TOTAL);
runtime.addItem(String.valueOf(totalMemory) + " MiB");
runtime.addLabel(T_RUNTIME_USED);
runtime.addItem(String.valueOf(usedMemory) + " MiB");
runtime.addLabel(T_RUNTIME_FREE);
runtime.addItem(String.valueOf(freeMemory) + " MiB");
}
/**
* List important DSpace configuration parameters.
*/
private void addDSpaceConfiguration(Division div) throws WingException
{
// LIST: DSpace
List dspace = div.addList("dspace");
dspace.setHead(T_DSPACE_HEAD);
dspace.addLabel(T_DSPACE_DIR);
dspace.addItem(ConfigurationManager.getProperty("dspace.dir"));
dspace.addLabel(T_DSPACE_URL);
dspace.addItem(ConfigurationManager.getProperty("dspace.url"));
dspace.addLabel(T_DSPACE_HOST_NAME);
dspace.addItem(ConfigurationManager.getProperty("dspace.hostname"));
dspace.addLabel(T_DSPACE_NAME);
dspace.addItem(ConfigurationManager.getProperty("dspace.name"));
dspace.addLabel(T_DB_NAME);
dspace.addItem(ConfigurationManager.getProperty("db.name"));
dspace.addLabel(T_DB_URL);
dspace.addItem(ConfigurationManager.getProperty("db.url"));
dspace.addLabel(T_DB_DRIVER);
dspace.addItem(ConfigurationManager.getProperty("db.driver"));
dspace.addLabel(T_DB_MAX_CONN);
dspace.addItem(ConfigurationManager.getProperty("db.maxconnections"));
dspace.addLabel(T_DB_MAX_WAIT);
dspace.addItem(ConfigurationManager.getProperty("db.maxwait"));
dspace.addLabel(T_DB_MAX_IDLE);
dspace.addItem(ConfigurationManager.getProperty("db.maxidle"));
dspace.addLabel(T_MAIL_SERVER);
dspace.addItem(ConfigurationManager.getProperty("mail.server"));
dspace.addLabel(T_MAIL_FROM_ADDRESS);
dspace.addItem(ConfigurationManager.getProperty("mail.from.address"));
dspace.addLabel(T_FEEDBACK_RECIPIENT);
dspace.addItem(ConfigurationManager.getProperty("feedback.recipient"));
dspace.addLabel(T_MAIL_ADMIN);
dspace.addItem(ConfigurationManager.getProperty("mail.admin"));
}
/**
* Add a section that allows administrators to activate or deactivate system-wide alerts.
*/
private void addAlerts(Division div) throws WingException
{
// Remember we're in the alerts section
div.addHidden("alerts").setValue("true");
List form = div.addList("system-wide-alerts",List.TYPE_FORM);
form.setHead(T_alerts_head);
form.addItem(T_alerts_warning);
TextArea message = form.addItem().addTextArea("message");
message.setLabel(T_alerts_message_label);
message.setSize(5, 45);
if (SystemwideAlerts.getMessage() == null)
{
message.setValue(T_alerts_message_default);
}
else
{
message.setValue(SystemwideAlerts.getMessage());
}
Select countdown = form.addItem().addSelect("countdown");
countdown.setLabel(T_alerts_countdown_label);
countdown.addOption(0,T_alerts_countdown_none);
countdown.addOption(5,T_alerts_countdown_5);
countdown.addOption(15,T_alerts_countdown_15);
countdown.addOption(30,T_alerts_countdown_30);
countdown.addOption(60,T_alerts_countdown_60);
// Is there a current count down active?
if (SystemwideAlerts.isAlertActive() && SystemwideAlerts.getCountDownToo() - System.currentTimeMillis() > 0)
{
countdown.addOption(true, -1, T_alerts_countdown_keep);
}
else
{
countdown.setOptionSelected(0);
}
Select restrictsessions = form.addItem().addSelect("restrictsessions");
restrictsessions.setLabel(T_alerts_session_label);
restrictsessions.addOption(SystemwideAlerts.STATE_ALL_SESSIONS,T_alerts_session_all_sessions);
restrictsessions.addOption(SystemwideAlerts.STATE_CURRENT_SESSIONS,T_alerts_session_current_sessions);
restrictsessions.addOption(SystemwideAlerts.STATE_ONLY_ADMINISTRATIVE_SESSIONS,T_alerts_session_only_administrative);
restrictsessions.setOptionSelected(SystemwideAlerts.getRestrictSessions());
form.addItem(T_alerts_session_note);
Item actions = form.addItem();
actions.addButton("submit_activate").setValue(T_alerts_submit_activate);
actions.addButton("submit_deactivate").setValue(T_alerts_submit_deactivate);
}
/** The possible sorting parameters */
private static enum EventSort { TIME, URL, SESSION, AGENT, IP };
/**
* Create a list of all activity.
*/
private void addActivity(Division div) throws WingException, SQLException
{
// 0) Update recording settings
Request request = ObjectModelHelper.getRequest(objectModel);
// Toggle anonymous recording
String recordAnonymousString = request.getParameter("recordanonymous");
if (recordAnonymousString != null)
{
if ("ON".equals(recordAnonymousString))
{
CurrentActivityAction.setRecordAnonymousEvents(true);
}
if ("OFF".equals(recordAnonymousString))
{
CurrentActivityAction.setRecordAnonymousEvents(false);
}
}
// Toggle bot recording
String recordBotString = request.getParameter("recordbots");
if (recordBotString != null)
{
if ("ON".equals(recordBotString))
{
CurrentActivityAction.setRecordBotEvents(true);
}
if ("OFF".equals(recordBotString))
{
CurrentActivityAction.setRecordBotEvents(false);
}
}
// 1) Determine how to sort
EventSort sortBy = EventSort.TIME;
String sortByString = request.getParameter("sortBy");
if (EventSort.TIME.toString().equals(sortByString))
{
sortBy = EventSort.TIME;
}
if (EventSort.URL.toString().equals(sortByString))
{
sortBy = EventSort.URL;
}
if (EventSort.SESSION.toString().equals(sortByString))
{
sortBy = EventSort.SESSION;
}
if (EventSort.AGENT.toString().equals(sortByString))
{
sortBy = EventSort.AGENT;
}
if (EventSort.IP.toString().equals(sortByString))
{
sortBy = EventSort.IP;
}
// 2) Sort the events by the requested sorting parameter
java.util.List<CurrentActivityAction.Event> events = CurrentActivityAction.getEvents();
Collections.sort(events, new ActivitySort<CurrentActivityAction.Event>(sortBy));
Collections.reverse(events);
// 3) Toggle controls for anonymous and bot activity
if (CurrentActivityAction.getRecordAnonymousEvents())
{
div.addPara().addXref("?activity&sortBy=" + sortBy + "&recordanonymous=OFF").addContent(T_stop_anonymous);
}
else
{
div.addPara().addXref("?activity&sortBy=" + sortBy + "&recordanonymous=ON").addContent(T_start_anonymous);
}
if (CurrentActivityAction.getRecordBotEvents())
{
div.addPara().addXref("?activity&sortBy=" + sortBy + "&recordbots=OFF").addContent(T_stop_bot);
}
else
{
div.addPara().addXref("?activity&sortBy=" + sortBy + "&recordbots=ON").addContent(T_start_bot);
}
// 4) Display the results Table
// TABLE: activeUsers
Table activeUsers = div.addTable("users",1,1);
activeUsers.setHead(T_activity_head.parameterize(CurrentActivityAction.MAX_EVENTS));
Row row = activeUsers.addRow(Row.ROLE_HEADER);
if (sortBy == EventSort.TIME)
{
row.addCell().addHighlight("bold").addXref("?activity&sortBy=" + EventSort.TIME).addContent(T_activity_sort_time);
}
else
{
row.addCell().addXref("?activity&sortBy=" + EventSort.TIME).addContent(T_activity_sort_time);
}
if (sortBy == EventSort.SESSION)
{
row.addCell().addHighlight("bold").addXref("?activity&sortBy=" + EventSort.SESSION).addContent(T_activity_sort_user);
}
else
{
row.addCell().addXref("?activity&sortBy=" + EventSort.SESSION).addContent(T_activity_sort_user);
}
if (sortBy == EventSort.IP)
{
row.addCell().addHighlight("bold").addXref("?activity&sortBy=" + EventSort.IP).addContent(T_activity_sort_ip);
}
else
{
row.addCell().addXref("?activity&sortBy=" + EventSort.IP).addContent(T_activity_sort_ip);
}
if (sortBy == EventSort.URL)
{
row.addCell().addHighlight("bold").addXref("?activity&sortBy=" + EventSort.URL).addContent(T_activity_sort_url);
}
else
{
row.addCell().addXref("?activity&sortBy=" + EventSort.URL).addContent(T_activity_sort_url);
}
if (sortBy == EventSort.AGENT)
{
row.addCell().addHighlight("bold").addXref("?activity&sortBy=" + EventSort.AGENT).addContent(T_activity_sort_agent);
}
else
{
row.addCell().addXref("?activity&sortBy=" + EventSort.AGENT).addContent(T_activity_sort_agent);
}
// Keep track of how many individual anonymous users there are, each unique anonymous
// user is assigned an index based upon the servlet session id.
HashMap<String,Integer> anonymousHash = new HashMap<String,Integer>();
int anonymousCount = 1;
int shown = 0;
for (CurrentActivityAction.Event event : events)
{
if (event == null)
{
continue;
}
shown++;
Message timeStampMessage = null;
long ago = System.currentTimeMillis() - event.getTimeStamp();
if (ago > 2*60*60*1000)
{
timeStampMessage = T_hours.parameterize((ago / (60 * 60 * 1000)));
}
else if (ago > 60*1000)
{
timeStampMessage = T_minutes.parameterize((ago / (60 * 1000)));
}
else
{
timeStampMessage = T_seconds.parameterize((ago / (1000)));
}
Row eventRow = activeUsers.addRow();
eventRow.addCellContent(timeStampMessage);
int eid = event.getEPersonID();
EPerson eperson = EPerson.find(context, eid);
if (eperson != null)
{
String name = eperson.getFullName();
eventRow.addCellContent(name);
}
else
{
// Is this a new anonymous user?
if (!anonymousHash.containsKey(event.getSessionID()))
{
anonymousHash.put(event.getSessionID(), anonymousCount++);
}
eventRow.addCellContent(T_activity_anonymous.parameterize(anonymousHash.get(event.getSessionID())));
}
eventRow.addCellContent(event.getIP());
eventRow.addCell().addXref(contextPath+"/"+event.getURL()).addContent("/"+event.getURL());
eventRow.addCellContent(event.getDectectedBrowser());
}
if (shown == 0)
{
activeUsers.addRow().addCell(1, 5).addContent(T_activity_none);
}
}
/**
* Comparator to sort activity events by their access times.
*/
public static class ActivitySort<E extends CurrentActivityAction.Event> implements Comparator<E>, Serializable
{
// Sort parameter
private EventSort sortBy;
public ActivitySort(EventSort sortBy)
{
this.sortBy = sortBy;
}
/**
* Compare these two activity events based upon the given sort parameter. In the case of a tie,
* allways fallback to sorting based upon the timestamp.
*/
public int compare(E a, E b)
{
// Protect against null events while sorting
if (a != null && b == null)
{
return 1; // A > B
}
else if (a == null && b != null)
{
return -1; // B > A
}
else if (a == null && b == null)
{
return 0; // A == B
}
// Sort by the given ordering matrix
if (EventSort.URL == sortBy)
{
String aURL = a.getURL();
String bURL = b.getURL();
int cmp = aURL.compareTo(bURL);
if (cmp != 0)
{
return cmp;
}
}
else if (EventSort.AGENT == sortBy)
{
String aAgent = a.getDectectedBrowser();
String bAgent = b.getDectectedBrowser();
int cmp = aAgent.compareTo(bAgent);
if (cmp != 0)
{
return cmp;
}
}
else if (EventSort.IP == sortBy)
{
String aIP = a.getIP();
String bIP = b.getIP();
int cmp = aIP.compareTo(bIP);
if (cmp != 0)
{
return cmp;
}
}
else if (EventSort.SESSION == sortBy)
{
// Ensure that all sessions with an EPersonID associated are
// ordered to the top. Otherwise fall back to comparing session
// IDs. Unfortunitaly we can not compare eperson names because
// we do not have access to a context object.
if (a.getEPersonID() > 0 && b.getEPersonID() < 0)
{
return 1; // A > B
}
else if (a.getEPersonID() < 0 && b.getEPersonID() > 0)
{
return -1; // B > A
}
String aSession = a.getSessionID();
String bSession = b.getSessionID();
int cmp = aSession.compareTo(bSession);
if (cmp != 0)
{
return cmp;
}
}
// All ways fall back to sorting by time, when events are equal.
if (a.getTimeStamp() > b.getTimeStamp())
{
return 1; // A > B
}
else if (a.getTimeStamp() > b.getTimeStamp())
{
return -1; // B > A
}
return 0; // A == B
}
}
/**
* Add a section that allows management of the OAI harvester.
* @throws SQLException
*/
private void addHarvest(Division div) throws WingException, SQLException
{
// Remember we're in the harvest section
div.addHidden("harvest").setValue("true");
List harvesterControls = div.addList("oai-harvester-controls",List.TYPE_FORM);
harvesterControls.setHead(T_harvest_scheduler_head);
harvesterControls.addLabel(T_harvest_label_status);
Item status = harvesterControls.addItem();
status.addContent(HarvestScheduler.getStatus());
status.addXref(contextPath + "/admin/panel?harvest", "(refresh)");
harvesterControls.addLabel(T_harvest_label_actions);
Item actionsItem = harvesterControls.addItem();
if (HarvestScheduler.hasStatus(HarvestScheduler.HARVESTER_STATUS_STOPPED)) {
actionsItem.addButton("submit_harvest_start").setValue(T_harvest_submit_start);
actionsItem.addButton("submit_harvest_reset").setValue(T_harvest_submit_reset);
}
if (HarvestScheduler.hasStatus(HarvestScheduler.HARVESTER_STATUS_PAUSED))
{
actionsItem.addButton("submit_harvest_resume").setValue(T_harvest_submit_resume);
}
if (HarvestScheduler.hasStatus(HarvestScheduler.HARVESTER_STATUS_RUNNING) ||
HarvestScheduler.hasStatus(HarvestScheduler.HARVESTER_STATUS_SLEEPING))
{
actionsItem.addButton("submit_harvest_pause").setValue(T_harvest_submit_pause);
}
if (!HarvestScheduler.hasStatus(HarvestScheduler.HARVESTER_STATUS_STOPPED))
{
actionsItem.addButton("submit_harvest_stop").setValue(T_harvest_submit_stop);
}
// Can be retrieved via "{context-path}/admin/collection?collectionID={id}"
String baseURL = contextPath + "/admin/collection?collectionID=";
harvesterControls.addLabel(T_harvest_label_collections);
Item allCollectionsItem = harvesterControls.addItem();
java.util.List<Integer> allCollections = HarvestedCollection.findAll(context);
for (Integer oaiCollection : allCollections) {
allCollectionsItem.addXref(baseURL + oaiCollection, oaiCollection.toString());
}
harvesterControls.addLabel(T_harvest_label_active);
Item busyCollectionsItem = harvesterControls.addItem();
java.util.List<Integer> busyCollections = HarvestedCollection.findByStatus(context, HarvestedCollection.STATUS_BUSY);
for (Integer busyCollection : busyCollections) {
busyCollectionsItem.addXref(baseURL + busyCollection, busyCollection.toString());
}
harvesterControls.addLabel(T_harvest_label_queued);
Item queuedCollectionsItem = harvesterControls.addItem();
java.util.List<Integer> queuedCollections = HarvestedCollection.findByStatus(context, HarvestedCollection.STATUS_QUEUED);
for (Integer queuedCollection : queuedCollections) {
queuedCollectionsItem.addXref(baseURL + queuedCollection, queuedCollection.toString());
}
harvesterControls.addLabel(T_harvest_label_oai_errors);
Item oaiErrorsItem = harvesterControls.addItem();
java.util.List<Integer> oaiErrors = HarvestedCollection.findByStatus(context, HarvestedCollection.STATUS_OAI_ERROR);
for (Integer oaiError : oaiErrors) {
oaiErrorsItem.addXref(baseURL + oaiError, oaiError.toString());
}
harvesterControls.addLabel(T_harvest_label_internal_errors);
Item internalErrorsItem = harvesterControls.addItem();
java.util.List<Integer> internalErrors = HarvestedCollection.findByStatus(context, HarvestedCollection.STATUS_UNKNOWN_ERROR);
for (Integer internalError : internalErrors) {
internalErrorsItem.addXref(baseURL + internalError, internalError.toString());
}
// OAI Generator settings
List generatorSettings = div.addList("oai-generator-settings");
generatorSettings.setHead(T_harvest_head_generator_settings);
generatorSettings.addLabel(T_harvest_label_oai_url);
String oaiUrl = ConfigurationManager.getProperty("dspace.oai.url");
if (!StringUtils.isEmpty(oaiUrl))
{
generatorSettings.addItem(oaiUrl);
}
generatorSettings.addLabel(T_harvest_label_oai_source);
String oaiAuthoritativeSource = ConfigurationManager.getProperty("ore.authoritative.source");
if (!StringUtils.isEmpty(oaiAuthoritativeSource))
{
generatorSettings.addItem(oaiAuthoritativeSource);
}
else
{
generatorSettings.addItem("oai");
}
// OAI Harvester settings (just iterate over all the values that start with "harvester")
List harvesterSettings = div.addList("oai-harvester-settings");
harvesterSettings.setHead(T_harvest_head_harvester_settings);
String metaString = "harvester.";
Enumeration pe = ConfigurationManager.propertyNames();
while (pe.hasMoreElements())
{
String key = (String)pe.nextElement();
if (key.startsWith(metaString)) {
harvesterSettings.addLabel(key);
harvesterSettings.addItem(ConfigurationManager.getProperty(key) + " ");
}
}
}
}
| 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.administrative.eperson;
import java.sql.SQLException;
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.Cell;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.eperson.EPerson;
/**
* The manage epeople page is the starting point page for managing
* epeople. From here the user is able to browse or search for epeople,
* once identified the user can selected them for deletition by selecting
* the checkboxes and clicking delete or click their name to edit the
* eperson.
*
* @author Alexey Maslov
* @author Scott Phillips
*/
public class ManageEPeopleMain extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_title =
message("xmlui.administrative.eperson.ManageEPeopleMain.title");
private static final Message T_eperson_trail =
message("xmlui.administrative.eperson.general.epeople_trail");
private static final Message T_main_head =
message("xmlui.administrative.eperson.ManageEPeopleMain.main_head");
private static final Message T_actions_head =
message("xmlui.administrative.eperson.ManageEPeopleMain.actions_head");
private static final Message T_actions_create =
message("xmlui.administrative.eperson.ManageEPeopleMain.actions_create");
private static final Message T_actions_create_link =
message("xmlui.administrative.eperson.ManageEPeopleMain.actions_create_link");
private static final Message T_actions_browse =
message("xmlui.administrative.eperson.ManageEPeopleMain.actions_browse");
private static final Message T_actions_browse_link =
message("xmlui.administrative.eperson.ManageEPeopleMain.actions_browse_link");
private static final Message T_actions_search =
message("xmlui.administrative.eperson.ManageEPeopleMain.actions_search");
private static final Message T_search_help =
message("xmlui.administrative.eperson.ManageEPeopleMain.search_help");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_go =
message("xmlui.general.go");
private static final Message T_search_head =
message("xmlui.administrative.eperson.ManageEPeopleMain.search_head");
private static final Message T_search_column1 =
message("xmlui.administrative.eperson.ManageEPeopleMain.search_column1");
private static final Message T_search_column2 =
message("xmlui.administrative.eperson.ManageEPeopleMain.search_column2");
private static final Message T_search_column3 =
message("xmlui.administrative.eperson.ManageEPeopleMain.search_column3");
private static final Message T_search_column4 =
message("xmlui.administrative.eperson.ManageEPeopleMain.search_column4");
private static final Message T_submit_delete =
message("xmlui.administrative.eperson.ManageEPeopleMain.submit_delete");
private static final Message T_no_results =
message("xmlui.administrative.eperson.ManageEPeopleMain.no_results");
/**
* The total number of entries to show on a page
*/
private static final int PAGE_SIZE = 15;
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/epeople",T_eperson_trail);
}
public void addBody(Body body) throws WingException, SQLException
{
/* Get and setup our parameters */
int page = parameters.getParameterAsInteger("page",0);
int highlightID = parameters.getParameterAsInteger("highlightID",-1);
String query = decodeFromURL(parameters.getParameter("query",null));
String baseURL = contextPath+"/admin/epeople?administrative-continue="+knot.getId();
int resultCount = EPerson.searchResultCount(context, query);
EPerson[] epeople = EPerson.search(context, query, page*PAGE_SIZE, PAGE_SIZE);
// DIVISION: eperson-main
Division main = body.addInteractiveDivision("epeople-main",contextPath+"/admin/epeople",Division.METHOD_POST,"primary administrative eperson");
main.setHead(T_main_head);
// DIVISION: eperson-actions
Division actions = main.addDivision("epeople-actions");
actions.setHead(T_actions_head);
List actionsList = actions.addList("actions");
actionsList.addLabel(T_actions_create);
actionsList.addItemXref(baseURL+"&submit_add", T_actions_create_link);
actionsList.addLabel(T_actions_browse);
actionsList.addItemXref(baseURL+"&query&submit_search",
T_actions_browse_link);
actionsList.addLabel(T_actions_search);
org.dspace.app.xmlui.wing.element.Item actionItem = actionsList.addItem();
Text queryField = actionItem.addText("query");
if (query != null)
{
queryField.setValue(query);
}
queryField.setHelp(T_search_help);
actionItem.addButton("submit_search").setValue(T_go);
// DIVISION: eperson-search
Division search = main.addDivision("eperson-search");
search.setHead(T_search_head);
// If there are more than 10 results the paginate the division.
if (resultCount > PAGE_SIZE)
{
// If there are enough results then paginate the results
int firstIndex = page*PAGE_SIZE+1;
int lastIndex = page*PAGE_SIZE + epeople.length;
String nextURL = null, prevURL = null;
if (page < (resultCount / PAGE_SIZE))
{
nextURL = baseURL + "&page=" + (page + 1);
}
if (page > 0)
{
prevURL = baseURL + "&page=" + (page - 1);
}
search.setSimplePagination(resultCount,firstIndex,lastIndex,prevURL, nextURL);
}
Table table = search.addTable("eperson-search-table", epeople.length + 1, 1);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell().addContent(T_search_column1);
header.addCell().addContent(T_search_column2);
header.addCell().addContent(T_search_column3);
header.addCell().addContent(T_search_column4);
CheckBox selectEPerson;
for (EPerson person : epeople)
{
String epersonID = String.valueOf(person.getID());
String fullName = person.getFullName();
String email = person.getEmail();
String url = baseURL+"&submit_edit&epersonID="+epersonID;
java.util.List<String> deleteConstraints = person.getDeleteConstraints();
Row row;
if (person.getID() == highlightID)
{
// This is a highlighted eperson
row = table.addRow(null, null, "highlight");
}
else
{
row = table.addRow();
}
selectEPerson = row.addCell().addCheckBox("select_eperson");
selectEPerson.setLabel(epersonID);
selectEPerson.addOption(epersonID);
if (deleteConstraints != null && deleteConstraints.size() > 0)
{
selectEPerson.setDisabled();
}
row.addCellContent(epersonID);
row.addCell().addXref(url, fullName);
row.addCell().addXref(url, email);
}
if (epeople.length <= 0)
{
Cell cell = table.addRow().addCell(1, 4);
cell.addHighlight("italic").addContent(T_no_results);
}
else
{
search.addPara().addButton("submit_delete").setValue(T_submit_delete);
}
main.addHidden("administrative-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.administrative.eperson;
import java.sql.SQLException;
import java.util.ArrayList;
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.Button;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Highlight;
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.Para;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
/**
* Edit an existing EPerson, display all the eperson's metadata
* along with two special options two reset the eperson's
* password and delete this user.
*
* @author Alexey Maslov
*/
public class EditEPersonForm extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_submit_save =
message("xmlui.general.save");
private static final Message T_submit_cancel =
message("xmlui.general.cancel");
private static final Message T_title =
message("xmlui.administrative.eperson.EditEPersonForm.title");
private static final Message T_eperson_trail =
message("xmlui.administrative.eperson.general.epeople_trail");
private static final Message T_trail =
message("xmlui.administrative.eperson.EditEPersonForm.trail");
private static final Message T_head1 =
message("xmlui.administrative.eperson.EditEPersonForm.head1");
private static final Message T_email_taken =
message("xmlui.administrative.eperson.EditEPersonForm.email_taken");
private static final Message T_head2 =
message("xmlui.administrative.eperson.EditEPersonForm.head2");
private static final Message T_error_email_unique =
message("xmlui.administrative.eperson.EditEPersonForm.error_email_unique");
private static final Message T_error_email =
message("xmlui.administrative.eperson.EditEPersonForm.error_email");
private static final Message T_error_fname =
message("xmlui.administrative.eperson.EditEPersonForm.error_fname");
private static final Message T_error_lname =
message("xmlui.administrative.eperson.EditEPersonForm.error_lname");
private static final Message T_req_certs =
message("xmlui.administrative.eperson.EditEPersonForm.req_certs");
private static final Message T_can_log_in =
message("xmlui.administrative.eperson.EditEPersonForm.can_log_in");
private static final Message T_submit_reset_password =
message("xmlui.administrative.eperson.EditEPersonForm.submit_reset_password");
private static final Message T_special_help =
message("xmlui.administrative.eperson.EditEPersonForm.special_help");
private static final Message T_submit_delete =
message("xmlui.administrative.eperson.EditEPersonForm.submit_delete");
private static final Message T_submit_login_as =
message("xmlui.administrative.eperson.EditEPersonForm.submit_login_as");
private static final Message T_delete_constraint =
message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint");
private static final Message T_constraint_last_conjunction =
message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.last_conjunction");
private static final Message T_constraint_item =
message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.item");
private static final Message T_constraint_workflowitem =
message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.workflowitem");
private static final Message T_constraint_tasklistitem =
message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.tasklistitem");
private static final Message T_constraint_unknown =
message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.unknown");
private static final Message T_member_head =
message("xmlui.administrative.eperson.EditEPersonForm.member_head");
private static final Message T_indirect_member =
message("xmlui.administrative.eperson.EditEPersonForm.indirect_member");
private static final Message T_member_none =
message("xmlui.administrative.eperson.EditEPersonForm.member_none");
/** Language string used: */
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_last_name =
message("xmlui.EPerson.EditProfile.last_name");
private static final Message T_telephone =
message("xmlui.EPerson.EditProfile.telephone");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/epeople",T_eperson_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
// Get all our parameters
boolean admin = AuthorizeManager.isAdmin(context);
Request request = ObjectModelHelper.getRequest(objectModel);
// Get our parameters;
int epersonID = parameters.getParameterAsInteger("epersonID",-1);
String errorString = parameters.getParameter("errors",null);
ArrayList<String> errors = new ArrayList<String>();
if (errorString != null)
{
for (String error : errorString.split(","))
{
errors.add(error);
}
}
// Grab the person in question
EPerson eperson = EPerson.find(context, epersonID);
if (eperson == null)
{
throw new UIException("Unable to find eperson for id:" + epersonID);
}
String emailValue = eperson.getEmail();
String firstValue = eperson.getFirstName();
String lastValue = eperson.getLastName();
String phoneValue = eperson.getMetadata("phone");
boolean canLogInValue = eperson.canLogIn();
boolean certificatValue = eperson.getRequireCertificate();
java.util.List<String> deleteConstraints = eperson.getDeleteConstraints();
if (request.getParameter("email_address") != null)
{
emailValue = request.getParameter("email_address");
}
if (request.getParameter("first_name") != null)
{
firstValue = request.getParameter("first_name");
}
if (request.getParameter("last_name") != null)
{
lastValue = request.getParameter("last_name");
}
if (request.getParameter("phone") != null)
{
phoneValue = request.getParameter("phone");
}
// DIVISION: eperson-edit
Division edit = body.addInteractiveDivision("eperson-edit",contextPath+"/admin/epeople",Division.METHOD_POST,"primary administrative eperson");
edit.setHead(T_head1);
if (errors.contains("eperson_email_key")) {
Para problem = edit.addPara();
problem.addHighlight("bold").addContent(T_email_taken);
}
List identity = edit.addList("form",List.TYPE_FORM);
identity.setHead(T_head2.parameterize(eperson.getFullName()));
if (admin)
{
Text email = identity.addItem().addText("email_address");
email.setRequired();
email.setLabel(T_email_address);
email.setValue(emailValue);
if (errors.contains("eperson_email_key"))
{
email.addError(T_error_email_unique);
}
else if (errors.contains("email_address"))
{
email.addError(T_error_email);
}
}
else
{
identity.addLabel(T_email_address);
identity.addItem(emailValue);
}
if (admin)
{
Text firstName = identity.addItem().addText("first_name");
firstName.setRequired();
firstName.setLabel(T_first_name);
firstName.setValue(firstValue);
if (errors.contains("first_name"))
{
firstName.addError(T_error_fname);
}
}
else
{
identity.addLabel(T_first_name);
identity.addItem(firstValue);
}
if (admin)
{
Text lastName = identity.addItem().addText("last_name");
lastName.setRequired();
lastName.setLabel(T_last_name);
lastName.setValue(lastValue);
if (errors.contains("last_name"))
{
lastName.addError(T_error_lname);
}
}
else
{
identity.addLabel(T_last_name);
identity.addItem(lastValue);
}
if (admin)
{
Text phone = identity.addItem().addText("phone");
phone.setLabel(T_telephone);
phone.setValue(phoneValue);
}
else
{
identity.addLabel(T_telephone);
identity.addItem(phoneValue);
}
if (admin)
{
// Administrative options:
CheckBox canLogInField = identity.addItem().addCheckBox("can_log_in");
canLogInField.setLabel(T_can_log_in);
canLogInField.addOption(canLogInValue, "true");
CheckBox certificateField = identity.addItem().addCheckBox("certificate");
certificateField.setLabel(T_req_certs);
certificateField.addOption(certificatValue,"true");
// Buttons to reset, delete or login as
identity.addItem().addHighlight("italic").addContent(T_special_help);
Item special = identity.addItem();
special.addButton("submit_reset_password").setValue(T_submit_reset_password);
Button submitDelete = special.addButton("submit_delete");
submitDelete.setValue(T_submit_delete);
Button submitLoginAs = special.addButton("submit_login_as");
submitLoginAs.setValue(T_submit_login_as);
if (!ConfigurationManager.getBooleanProperty("xmlui.user.assumelogin", false))
{
submitLoginAs.setDisabled();
}
if (deleteConstraints != null && deleteConstraints.size() > 0)
{
submitDelete.setDisabled();
Highlight hi = identity.addItem("eperson-delete-constraint","eperson-delete-constraint").addHighlight("error");
hi.addContent(T_delete_constraint);
hi.addContent(" ");
for (String constraint : deleteConstraints)
{
int idx = deleteConstraints.indexOf(constraint);
if (idx > 0 && idx == deleteConstraints.size() -1 )
{
hi.addContent(", ");
hi.addContent(T_constraint_last_conjunction);
hi.addContent(" ");
}
else if (idx > 0)
{
hi.addContent(", ");
}
if ("item".equals(constraint))
{
hi.addContent(T_constraint_item);
}
else if ("workflowitem".equals(constraint))
{
hi.addContent(T_constraint_workflowitem);
}
else if ("tasklistitem".equals(constraint))
{
hi.addContent(T_constraint_tasklistitem);
}
else
{
hi.addContent(T_constraint_unknown);
}
}
hi.addContent(".");
}
}
Item buttons = identity.addItem();
if (admin)
{
buttons.addButton("submit_save").setValue(T_submit_save);
}
buttons.addButton("submit_cancel").setValue(T_submit_cancel);
if (admin)
{
List member = edit.addList("eperson-member-of");
member.setHead(T_member_head);
Group[] groups = Group.allMemberGroups(context, eperson);
for (Group group : groups)
{
String url = contextPath + "/admin/groups?administrative-continue="+knot.getId()+"&submit_edit_group&groupID="+group.getID();
Item item = member.addItem();
item.addXref(url,group.getName());
// Check if this membership is via another group or not, if so then add a note.
Group via = findViaGroup(eperson, group);
if (via != null)
{
item.addHighlight("fade").addContent(T_indirect_member.parameterize(via.getName()));
}
}
if (groups.length <= 0)
{
member.addItem().addHighlight("italic").addContent(T_member_none);
}
}
edit.addHidden("administrative-continue").setValue(knot.getId());
}
/**
* Determine if the given eperson is a direct member of this group if
* they are not the return the group that membership is implied
* through (the via group!). This will only find one possible relation
* path, there may be multiple.
*
*
* @param eperson The source group to search from
* @param group The target group to search for.
* @return The group this member is related through or null if none found.
*/
private Group findViaGroup(EPerson eperson, Group group) throws SQLException
{
// First check if this eperson is a direct member of the group.
for (EPerson direct : group.getMembers())
{
if (direct.getID() == eperson.getID())
{
// Direct membership
return null;
}
}
// Otherwise check what group this eperson is a member through
Group[] targets = group.getMemberGroups();
Group[] groups = Group.allMemberGroups(context, eperson);
for (Group member : groups)
{
for (Group target : targets)
{
if (member.getID() == target.getID())
{
return member;
}
}
}
// This should never happen, but let's just say we couldn't find the relationship.
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.administrative.eperson;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
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.CheckBox;
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.Para;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.authorize.AuthorizeException;
/**
* Present the user with all the eperson metadata fields so that they
* can describe the new eperson before being created. If the user's
* input is incorrect in someway then they may be returning here with
* some fields in error. In particular there is a special case for the
* condition when the email-adress entered is allready in use by
* another user.
*
* @author Alexey Maslov
*/
public class AddEPersonForm extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_eperson_trail =
message("xmlui.administrative.eperson.general.epeople_trail");
private static final Message T_title =
message("xmlui.administrative.eperson.AddEPersonForm.title");
private static final Message T_trail =
message("xmlui.administrative.eperson.AddEPersonForm.trail");
private static final Message T_head1 =
message("xmlui.administrative.eperson.AddEPersonForm.head1");
private static final Message T_email_taken =
message("xmlui.administrative.eperson.AddEPersonForm.email_taken");
private static final Message T_head2 =
message("xmlui.administrative.eperson.AddEPersonForm.head2");
private static final Message T_error_email_unique =
message("xmlui.administrative.eperson.AddEPersonForm.error_email_unique");
private static final Message T_error_email =
message("xmlui.administrative.eperson.AddEPersonForm.error_email");
private static final Message T_error_fname =
message("xmlui.administrative.eperson.AddEPersonForm.error_fname");
private static final Message T_error_lname =
message("xmlui.administrative.eperson.AddEPersonForm.error_lname");
private static final Message T_req_certs =
message("xmlui.administrative.eperson.AddEPersonForm.req_certs");
private static final Message T_can_log_in =
message("xmlui.administrative.eperson.AddEPersonForm.can_log_in");
private static final Message T_submit_create =
message("xmlui.administrative.eperson.AddEPersonForm.submit_create");
private static final Message T_submit_cancel =
message("xmlui.general.cancel");
/** Language string used from other aspects: */
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_last_name =
message("xmlui.EPerson.EditProfile.last_name");
private static final Message T_telephone =
message("xmlui.EPerson.EditProfile.telephone");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/epeople",T_eperson_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
// Get all our parameters
Request request = ObjectModelHelper.getRequest(objectModel);
String errorString = parameters.getParameter("errors",null);
ArrayList<String> errors = new ArrayList<String>();
if (errorString != null)
{
for (String error : errorString.split(","))
{
errors.add(error);
}
}
String emailValue = request.getParameter("email_address");
String firstValue = request.getParameter("first_name");
String lastValue = request.getParameter("last_name");
String phoneValue = request.getParameter("phone");
boolean canLogInValue = (request.getParameter("can_log_in") == null) ? false : true;
boolean certificateValue = (request.getParameter("certificate") == null) ? false : true;
// DIVISION: eperson-add
Division add = body.addInteractiveDivision("eperson-add",contextPath+"/admin/epeople",Division.METHOD_POST,"primary administrative eperson");
add.setHead(T_head1);
if (errors.contains("eperson_email_key")) {
Para problem = add.addPara();
problem.addHighlight("bold").addContent(T_email_taken);
}
List identity = add.addList("identity",List.TYPE_FORM);
identity.setHead(T_head2);
Text email = identity.addItem().addText("email_address");
email.setRequired();
email.setLabel(T_email_address);
email.setValue(emailValue);
if (errors.contains("eperson_email_key")) {
email.addError(T_error_email_unique);
}
else if (errors.contains("email_address")) {
email.addError(T_error_email);
}
Text firstName = identity.addItem().addText("first_name");
firstName.setRequired();
firstName.setLabel(T_first_name);
firstName.setValue(firstValue);
if (errors.contains("first_name")) {
firstName.addError(T_error_fname);
}
Text lastName = identity.addItem().addText("last_name");
lastName.setRequired();
lastName.setLabel(T_last_name);
lastName.setValue(lastValue);
if (errors.contains("last_name")) {
lastName.addError(T_error_lname);
}
Text phone = identity.addItem().addText("phone");
phone.setLabel(T_telephone);
phone.setValue(phoneValue);
CheckBox canLogIn = identity.addItem().addCheckBox("can_log_in");
canLogIn.setLabel(T_can_log_in);
canLogIn.addOption(canLogInValue, "yes");
CheckBox certificate = identity.addItem().addCheckBox("certificate");
certificate.setLabel(T_req_certs);
certificate.addOption(certificateValue,"yes");
Item buttons = identity.addItem();
buttons.addButton("submit_save").setValue(T_submit_create);
buttons.addButton("submit_cancel").setValue(T_submit_cancel);
add.addHidden("administrative-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.administrative.eperson;
import java.sql.SQLException;
import java.util.ArrayList;
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.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.eperson.EPerson;
/**
* Present the user with a list of not-yet-but-soon-to-be-deleted-epeople.
*
* @author Alexey Maslov
*/
public class DeleteEPeopleConfirm extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_eperson_trail =
message("xmlui.administrative.eperson.general.epeople_trail");
private static final Message T_title =
message("xmlui.administrative.eperson.DeleteEPeopleConfirm.title");
private static final Message T_trail =
message("xmlui.administrative.eperson.DeleteEPeopleConfirm.trail");
private static final Message T_confirm_head =
message("xmlui.administrative.eperson.DeleteEPeopleConfirm.confirm_head");
private static final Message T_confirm_para =
message("xmlui.administrative.eperson.DeleteEPeopleConfirm.confirm_para");
private static final Message T_head_id =
message("xmlui.administrative.eperson.DeleteEPeopleConfirm.head_id");
private static final Message T_head_name =
message("xmlui.administrative.eperson.DeleteEPeopleConfirm.head_name");
private static final Message T_head_email =
message("xmlui.administrative.eperson.DeleteEPeopleConfirm.head_email");
private static final Message T_submit_confirm =
message("xmlui.administrative.eperson.DeleteEPeopleConfirm.submit_confirm");
private static final Message T_submit_cancel =
message("xmlui.general.cancel");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/epeople",T_eperson_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
// Get all our parameters
String idsString = parameters.getParameter("epeopleIDs", null);
ArrayList<EPerson> epeople = new ArrayList<EPerson>();
for (String id : idsString.split(","))
{
EPerson person = EPerson.find(context,Integer.valueOf(id));
epeople.add(person);
}
// DIVISION: epeople-confirm-delete
Division deleted = body.addInteractiveDivision("epeople-confirm-delete",contextPath+"/admin/epeople",Division.METHOD_POST,"primary administrative eperson");
deleted.setHead(T_confirm_head);
deleted.addPara(T_confirm_para);
Table table = deleted.addTable("epeople-confirm-delete",epeople.size() + 1, 1);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell().addContent(T_head_id);
header.addCell().addContent(T_head_name);
header.addCell().addContent(T_head_email);
for (EPerson eperson : epeople)
{
Row row = table.addRow();
row.addCell().addContent(eperson.getID());
row.addCell().addContent(eperson.getFullName());
row.addCell().addContent(eperson.getEmail());
}
Para buttons = deleted.addPara();
buttons.addButton("submit_confirm").setValue(T_submit_confirm);
buttons.addButton("submit_cancel").setValue(T_submit_cancel);
deleted.addHidden("administrative-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.administrative;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
/**
* Utility methods to processes actions on Groups. These methods are used
* exclusivly from the administrative flow scripts.
*
* @author scott phillips
*/
public class FlowGroupUtils {
/** Language Strings */
private static final Message T_edit_group_success_notice =
new Message("default","xmlui.administrative.FlowGroupUtils.edit_group_success_notice");
private static final Message T_delete_group_success_notice =
new Message("default","xmlui.administrative.FlowGroupUtils.delete_group_success_notice");
/**
* Return the current name for the given group ID.
* @param context The current DSpace context.
* @param groupID The group id.
* @return The group's name.
*/
public static String getName(Context context, int groupID) throws SQLException
{
if (groupID < 0)
{
return "New Group";
}
Group group = Group.find(context,groupID);
if (group == null)
{
return "New Group";
}
return group.getName();
}
/**
* Return the list of current epeople ID's that are a member of this group.
*
* @param context The current DSpace context
* @param groupID The group's id.
* @return An array of ids.
*/
public static String[] getEPeopleMembers(Context context, int groupID) throws SQLException
{
// New group, just return an empty list
if (groupID < 0)
{
return new String[0];
}
Group group = Group.find(context,groupID);
if (group == null)
{
return new String[0];
}
EPerson[] epeople = group.getMembers();
String[] epeopleIDs = new String[epeople.length];
for (int i=0; i < epeople.length; i++)
{
epeopleIDs[i] = String.valueOf(epeople[i].getID());
}
return epeopleIDs;
}
/**
* Return the list of current group id's that are a member of this group.
*
* @param context The current DSpace context
* @param groupID The group's id.
* @return An array of ids.
*/
public static String[] getGroupMembers(Context context, int groupID) throws SQLException
{
if (groupID < 0)
{
return new String[0];
}
Group group = Group.find(context,groupID);
if (group == null)
{
return new String[0];
}
Group[] groups = group.getMemberGroups();
String[] groupIDs = new String[groups.length];
for (int i=0; i < groups.length; i++)
{
groupIDs[i] = String.valueOf(groups[i].getID());
}
return groupIDs;
}
/**
* Add the given id to the list and return a new list.
*
* @param list The current array
* @param id The new element
* @return A new combined array.
*/
public static String[] addMember(String[] list, String id)
{
// FIXME: this is terribly ineffecient.
List<String> newList = new ArrayList<String>(Arrays.asList(list));
newList.add(id);
return newList.toArray(new String[newList.size()]);
}
/**
* Remove all instances of the given id from the member list.
*
* @param list The current array
* @param id The id to remove
* @return A new combined array.
*/
public static String[] removeMember(String[] list, String id)
{
// FIXME: this is terribly ineffecient.
List<String> newList = new ArrayList<String>(Arrays.asList(list));
newList.remove(id);
return newList.toArray(new String[newList.size()]);
}
/**
* Save the group. If the name has been changed then it will be updated, if any
* members have been added or removed then they are updated.
*
* If the groupID is -1 then a new group is created.
*
* @param context The current dspace context
* @param groupID The group id, or -1 for a new group.
* @param newName The group's new name.
* @param newEPeopleIDsArray All epeople members
* @param newGroupIDsArray All group members.
* @return A result
*/
public static FlowResult processSaveGroup(Context context, int groupID, String newName, String[] newEPeopleIDsArray, String[] newGroupIDsArray) throws SQLException, AuthorizeException, UIException
{
FlowResult result = new FlowResult();
// Decode the name incase it uses non-ascii characters.
try
{
newName = URLDecoder.decode(newName, Constants.DEFAULT_ENCODING);
}
catch (UnsupportedEncodingException uee)
{
throw new UIException(uee);
}
Group group = null;
if (groupID == -1)
{
// First check if the name is blank.
if (newName == null || newName.length() == 0)
{
// Group's can not have blank names.
result.setContinue(false);
result.addError("group_name");
result.setOutcome(false);
result.setMessage(new Message("default","The group name may not be blank."));
return result;
}
// Create a new group, check if the newName is allready in use.
Group potentialDuplicate = Group.findByName(context,newName);
if (potentialDuplicate == null)
{
// All good, create the new group.
group = Group.create(context);
group.setName(newName);
}
else
{
// The name is allready in use, return in error.
result.setContinue(false);
result.addError("group_name");
result.addError("group_name_duplicate");
result.setOutcome(false);
result.setMessage(new Message("default","The group name is allready in use"));
return result;
}
}
else
{
group = Group.find(context,groupID);
String name = group.getName();
// Only update the name if there has been a change.
if (newName != null && newName.length() > 0 && !name.equals(newName))
{
// The group name is to be updated, check if the newName is allready in use.
Group potentialDuplicate = Group.findByName(context,newName);
if (potentialDuplicate == null)
{
// All good, update the name
group.setName(newName);
}
else
{
// The name is allready in use, return in error.
result.setContinue(false);
result.addError("group_name");
result.addError("group_name_duplicate");
result.setOutcome(false);
result.setMessage(new Message("default","The group name is allready in use"));
return result;
}
}
}
// Second, Prepare to check members by turning arrays into lists
List<Integer> newEPeopleIDs = new ArrayList<Integer>();
for (String epeopleID : newEPeopleIDsArray)
{
newEPeopleIDs.add(Integer.valueOf(epeopleID));
}
List<Integer> newGroupIDs = new ArrayList<Integer>();
for (String _groupID : newGroupIDsArray)
{
newGroupIDs.add(Integer.valueOf(_groupID));
}
// Third, check if there are any members to remove
// i.e. scan the list on the group against the ids.
for (EPerson epersonMember : group.getMembers())
{
if (!newEPeopleIDs.contains(epersonMember.getID()))
{
// The current eperson is not contained in the new list.
group.removeMember(epersonMember);
}
else
{
// If they are still in the list then remove them
// from the list of people to add.
newEPeopleIDs.remove((Object)epersonMember.getID());
}
}
for (Group groupMember : group.getMemberGroups())
{
if (!newGroupIDs.contains(groupMember.getID()))
{
// The current group is not contained in the new list.
group.removeMember(groupMember);
}
else
{
// If they are still in the list then remove them
// from the list of groups to add.
newGroupIDs.remove((Object)group.getID());
}
}
// Third, check if there are any members to add
// i.e. scan the list of ids against the group.
for (Integer epersonID : newEPeopleIDs)
{
EPerson eperson = EPerson.find(context, epersonID);
group.addMember(eperson);
}
for (Integer _groupID : newGroupIDs)
{
Group _group = Group.find(context, _groupID);
group.addMember(_group);
}
// Last, create the result flow
group.update();
context.commit();
// Let's record our group id incase we created a new one.
result.setParameter("groupID", group.getID());
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_edit_group_success_notice);
return result;
}
/**
* Remove the specified groups. It is assumed that the user has allready confirm this selection.
*
* @param context The current DSpace context
* @param groupIDs A list of groups to be removed.
* @return A results object.
*/
public static FlowResult processDeleteGroups(Context context, String[] groupIDs) throws SQLException, AuthorizeException, IOException
{
FlowResult result = new FlowResult();
result.setContinue(true);
for (String id : groupIDs)
{
Group groupDeleted = Group.find(context, Integer.valueOf(id));
// If this group is related to a collection, then un-link it.
int collectionId = getCollectionId(groupDeleted.getName());
Role role = getCollectionRole(groupDeleted.getName());
if (collectionId != -1 && role != Role.none)
{
Collection collection = Collection.find(context, collectionId);
if (collection != null)
{
if (role == Role.Administrators)
{
collection.removeAdministrators();
collection.update();
}
else if (role == Role.Submitters)
{
collection.removeSubmitters();
collection.update();
}
else if (role == Role.WorkflowStep1)
{
collection.setWorkflowGroup(1, null);
collection.update();
}
else if (role == Role.WorkflowStep2)
{
collection.setWorkflowGroup(2, null);
collection.update();
}
else if (role == Role.WorkflowStep3)
{
collection.setWorkflowGroup(3, null);
collection.update();
}
else if (role == Role.DefaultRead)
{
// Nothing special needs to happen.
}
}
}
groupDeleted.delete();
}
result.setOutcome(true);
result.setMessage(T_delete_group_success_notice);
return result;
}
/**
* The collection prefix, all groups which are specific to
* a collection start with this.
*/
private static final String COLLECTION_PREFIX = "COLLECTION_";
/**
* These are the possible collection suffixes, all groups which are
* specific to a collection will end with one of these. The collection
* id should be inbetween the prefix and the suffix.
*
* Note: the order of these suffixes are important, see getCollectionRole()
*/
private static final String[] COLLECTION_SUFFIXES = {"_SUBMIT","_ADMIN","_WFSTEP_1","_WORKFLOW_STEP_1","_WFSTEP_2","_WORKFLOW_STEP_2","_WFSTEP_3","_WORKFLOW_STEP_3","_DEFAULT_ITEM_READ"};
/**
* Extracts the collection id that may be immbedded in the given group name.
*
* @param groupName - the name of a group (ie group.getName())
* @return the integer collection id or -1 if the group is not that of a collection
*/
public static int getCollectionId(String groupName)
{
if (groupName != null && groupName.startsWith(COLLECTION_PREFIX))
{
for (String suffix : COLLECTION_SUFFIXES)
{
if (groupName.endsWith(suffix))
{
String idString = groupName.substring(COLLECTION_PREFIX.length());
idString = idString.substring(0, idString.length() - suffix.length());
int collectionID = -1;
try {
collectionID = Integer.valueOf(idString);
return collectionID;
// All good, we were able to ah
}
catch (NumberFormatException nfe)
{
// Somethnig went wrong, just ignore the exception and
// continue searching for a collection id
} // try & catch
} // if it ends with a proper suffix.
} // for each possible suffix
} // if it starts with COLLECTION_
return -1;
}
public enum Role {Administrators, Submitters, WorkflowStep1, WorkflowStep2, WorkflowStep3, DefaultRead, none};
public static Role getCollectionRole(String groupName)
{
if (groupName != null && groupName.startsWith(COLLECTION_PREFIX))
{
for (String suffix : COLLECTION_SUFFIXES)
{
if (groupName.endsWith(suffix))
{
if (COLLECTION_SUFFIXES[0].equals(suffix))
{
return Role.Submitters;
}
else if (COLLECTION_SUFFIXES[1].equals(suffix))
{
return Role.Administrators;
}
else if (COLLECTION_SUFFIXES[2].equals(suffix))
{
return Role.WorkflowStep1;
}
else if (COLLECTION_SUFFIXES[3].equals(suffix))
{
return Role.WorkflowStep1;
}
else if (COLLECTION_SUFFIXES[4].equals(suffix))
{
return Role.WorkflowStep2;
}
else if (COLLECTION_SUFFIXES[5].equals(suffix))
{
return Role.WorkflowStep2;
}
else if (COLLECTION_SUFFIXES[6].equals(suffix))
{
return Role.WorkflowStep3;
}
else if (COLLECTION_SUFFIXES[7].equals(suffix))
{
return Role.WorkflowStep3;
}
else if (COLLECTION_SUFFIXES[8].equals(suffix))
{
return Role.DefaultRead;
}
} // if it ends with a proper suffix.
} // for each possible suffix
} // if it starts with COLLECTION_
return Role.none;
}
/**
* The community prefix: all groups which are specific to
* a community start with this.
*/
private static final String COMMUNITY_PREFIX = "COMMUNITY_";
/**
* These are the possible community suffixes. All groups which are
* specific to a collection will end with one of these. The collection
* id should be between the prefix and the suffix.
*
* Note: the order of these suffixes are important, see getCollectionRole()
*/
private static final String[] COMMUNITY_SUFFIXES = {"_ADMIN"};
/**
* Extracts the community id that may be embedded in the given group name.
*
* @param groupName - the name of a group (ie group.getName())
* @return the integer community id or -1 if the group is not that of a community
*/
public static int getCommunityId(String groupName)
{
if (groupName != null && groupName.startsWith(COMMUNITY_PREFIX))
{
for (String suffix : COMMUNITY_SUFFIXES)
{
if (groupName.endsWith(suffix))
{
String idString = groupName.substring(COMMUNITY_PREFIX.length());
idString = idString.substring(0, idString.length() - suffix.length());
int communityID = -1;
try {
communityID = Integer.valueOf(idString);
return communityID;
}
catch (NumberFormatException nfe)
{}
} // if it ends with a proper suffix.
} // for each possible suffix
} // if it starts with COLLECTION_
return -1;
}
public static Role getCommunityRole(String groupName)
{
if (groupName != null && groupName.startsWith(COMMUNITY_PREFIX))
{
for (String suffix : COMMUNITY_SUFFIXES)
{
if (groupName.endsWith(suffix))
{
if (COLLECTION_SUFFIXES[0].equals(suffix))
{
return Role.Submitters;
}
else if (COLLECTION_SUFFIXES[1].equals(suffix))
{
return Role.Administrators;
}
else if (COLLECTION_SUFFIXES[2].equals(suffix))
{
return Role.WorkflowStep1;
}
else if (COLLECTION_SUFFIXES[3].equals(suffix))
{
return Role.WorkflowStep1;
}
else if (COLLECTION_SUFFIXES[4].equals(suffix))
{
return Role.WorkflowStep2;
}
else if (COLLECTION_SUFFIXES[5].equals(suffix))
{
return Role.WorkflowStep2;
}
else if (COLLECTION_SUFFIXES[6].equals(suffix))
{
return Role.WorkflowStep3;
}
else if (COLLECTION_SUFFIXES[7].equals(suffix))
{
return Role.WorkflowStep3;
}
else if (COLLECTION_SUFFIXES[8].equals(suffix))
{
return Role.DefaultRead;
}
} // if it ends with a proper suffix.
} // for each possible suffix
} // if it starts with COMMUNITY_
return Role.none;
}
}
| 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.administrative.group;
import java.sql.SQLException;
import org.dspace.app.xmlui.aspect.administrative.FlowGroupUtils;
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.Cell;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Highlight;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.eperson.Group;
/**
* Manage groups page is the entry point for group management. From here the user
* may browse/search a the list of groups, they may also add new groups or select
* exiting groups to edit or delete.
*
* @author Alexey Maslov
* @author Scott Phillips
*/
public class ManageGroupsMain extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_group_trail =
message("xmlui.administrative.group.general.group_trail");
private static final Message T_title =
message("xmlui.administrative.group.ManageGroupsMain.title");
private static final Message T_main_head =
message("xmlui.administrative.group.ManageGroupsMain.main_head");
private static final Message T_actions_head =
message("xmlui.administrative.group.ManageGroupsMain.actions_head");
private static final Message T_actions_create=
message("xmlui.administrative.group.ManageGroupsMain.actions_create");
private static final Message T_actions_create_link =
message("xmlui.administrative.group.ManageGroupsMain.actions_create_link");
private static final Message T_actions_browse =
message("xmlui.administrative.group.ManageGroupsMain.actions_browse");
private static final Message T_actions_browse_link =
message("xmlui.administrative.group.ManageGroupsMain.actions_browse_link");
private static final Message T_actions_search =
message("xmlui.administrative.group.ManageGroupsMain.actions_search");
private static final Message T_search_help =
message("xmlui.administrative.group.ManageGroupsMain.search_help");
private static final Message T_go =
message("xmlui.general.go");
private static final Message T_search_head =
message("xmlui.administrative.group.ManageGroupsMain.search_head");
private static final Message T_search_column1 =
message("xmlui.administrative.group.ManageGroupsMain.search_column1");
private static final Message T_search_column2 =
message("xmlui.administrative.group.ManageGroupsMain.search_column2");
private static final Message T_search_column3 =
message("xmlui.administrative.group.ManageGroupsMain.search_column3");
private static final Message T_search_column4 =
message("xmlui.administrative.group.ManageGroupsMain.search_column4");
private static final Message T_search_column5 =
message("xmlui.administrative.group.ManageGroupsMain.search_column5");
private static final Message T_collection_link =
message("xmlui.administrative.group.ManageGroupsMain.collection_link");
private static final Message T_submit_delete =
message("xmlui.administrative.group.ManageGroupsMain.submit_delete");
private static final Message T_no_results =
message("xmlui.administrative.group.ManageGroupsMain.no_results");
/** The number of results to show on one page. */
private static final int PAGE_SIZE = 15;
/** The maximum size of a collection or community name allowed */
private static final int MAX_COLLECTION_OR_COMMUNITY_NAME = 30;
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/groups",T_group_trail);
}
public void addBody(Body body) throws WingException, SQLException
{
// Get all our parameters
String baseURL = contextPath +"/admin/groups?administrative-continue="+knot.getId();
String query = decodeFromURL(parameters.getParameter("query",""));
int page = parameters.getParameterAsInteger("page",0);
int highlightID = parameters.getParameterAsInteger("highlightID",-1);
int resultCount = Group.searchResultCount(context, query);
Group[] groups = Group.search(context, query, page*PAGE_SIZE, PAGE_SIZE);
// DIVISION: groups-main
Division main = body.addInteractiveDivision("groups-main",contextPath +"/admin/groups",Division.METHOD_POST,"primary administrative groups");
main.setHead(T_main_head);
// DIVISION: group-actions
Division actions = main.addDivision("group-actions");
actions.setHead(T_actions_head);
// Browse Epeople
List actionsList = actions.addList("actions");
actionsList.addLabel(T_actions_create);
actionsList.addItemXref(baseURL+"&submit_add", T_actions_create_link);
actionsList.addLabel(T_actions_browse);
actionsList.addItemXref(baseURL+"&query&submit_search",T_actions_browse_link);
actionsList.addLabel(T_actions_search);
org.dspace.app.xmlui.wing.element.Item actionItem = actionsList.addItem();
Text queryField = actionItem.addText("query");
if (query != null)
{
queryField.setValue(query);
}
queryField.setHelp(T_search_help);
actionItem.addButton("submit_search").setValue(T_go);
// DIVISION: group-search
Division search = main.addDivision("group-search");
search.setHead(T_search_head);
if (resultCount > PAGE_SIZE)
{
// If there are enough results then paginate the results
int firstIndex = page*PAGE_SIZE+1;
int lastIndex = page*PAGE_SIZE + groups.length;
String nextURL = null, prevURL = null;
if (page < (resultCount / PAGE_SIZE))
{
nextURL = baseURL + "&page=" + (page + 1);
}
if (page > 0)
{
prevURL = baseURL + "&page=" + (page - 1);
}
search.setSimplePagination(resultCount,firstIndex,lastIndex,prevURL, nextURL);
}
Table table = search.addTable("groups-search-table",groups.length + 1, 1);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell().addContent(T_search_column1);
header.addCell().addContent(T_search_column2);
header.addCell().addContent(T_search_column3);
header.addCell().addContent(T_search_column4);
header.addCell().addContent(T_search_column5);
for (Group group : groups)
{
Row row;
if (group.getID() == highlightID)
{
row = table.addRow(null, null, "highlight");
}
else
{
row = table.addRow();
}
if (group.getID() > 1)
{
CheckBox select = row.addCell().addCheckBox("select_group");
select.setLabel(Integer.valueOf(group.getID()).toString());
select.addOption(Integer.valueOf(group.getID()).toString());
}
else
{
// Don't allow the user to remove the administrative (id:1) or
// anonymous group (id:0)
row.addCell();
}
row.addCell().addContent(group.getID());
row.addCell().addXref(baseURL+"&submit_edit&groupID="+group.getID(), group.getName());
int memberCount = group.getMembers().length + group.getMemberGroups().length;
row.addCell().addContent(memberCount == 0 ? "-" : String.valueOf(memberCount));
Cell cell = row.addCell();
String groupName = group.getName();
DSpaceObject collectionOrCommunity = null;
String collectionOrCommunityName = null;
int id;
id = FlowGroupUtils.getCollectionId(groupName);
if (id > -1)
{
Collection collection = Collection.find(context, id);
if (collection != null)
{
collectionOrCommunityName = collection.getMetadata("name");
collectionOrCommunity = collection;
}
}
else
{
id = FlowGroupUtils.getCommunityId(groupName);
if (id > -1)
{
Community community = Community.find(context, id);
if (community != null)
{
collectionOrCommunityName = community.getMetadata("name");
collectionOrCommunity = community;
}
}
}
if (collectionOrCommunity != null)
{
if (collectionOrCommunityName == null)
{
collectionOrCommunityName = "";
}
else if (collectionOrCommunityName.length() > MAX_COLLECTION_OR_COMMUNITY_NAME)
{
collectionOrCommunityName = collectionOrCommunityName.substring(0, MAX_COLLECTION_OR_COMMUNITY_NAME - 3) + "...";
}
cell.addContent(collectionOrCommunityName + " ");
Highlight highlight = cell.addHighlight("fade");
highlight.addContent("[");
highlight.addXref(contextPath+"/handle/"+collectionOrCommunity.getHandle(), T_collection_link);
highlight.addContent("]");
}
}
if (groups.length <= 0)
{
Cell cell = table.addRow().addCell(1,5);
cell.addHighlight("italic").addContent(T_no_results);
}
else
{
search.addPara().addButton("submit_delete").setValue(T_submit_delete);
}
search.addHidden("administrative-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.administrative.group;
import java.sql.SQLException;
import java.util.ArrayList;
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.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.eperson.Group;
/**
* Present the user with a list of soon-to-be-deleted Groups.
* If the user clicks confirm deletition then they will be
* deleted otherwise they will be spared the wrath of deletion.
* @author Scott Phillips
*/
public class DeleteGroupsConfirm extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_group_trail =
message("xmlui.administrative.group.general.group_trail");
private static final Message T_title =
message("xmlui.administrative.group.DeleteGroupsConfirm.title");
private static final Message T_trail =
message("xmlui.administrative.group.DeleteGroupsConfirm.trail");
private static final Message T_head =
message("xmlui.administrative.group.DeleteGroupsConfirm.head");
private static final Message T_para =
message("xmlui.administrative.group.DeleteGroupsConfirm.para");
private static final Message T_column1 =
message("xmlui.administrative.group.DeleteGroupsConfirm.column1");
private static final Message T_column2 =
message("xmlui.administrative.group.DeleteGroupsConfirm.column2");
private static final Message T_column3 =
message("xmlui.administrative.group.DeleteGroupsConfirm.column3");
private static final Message T_column4 =
message("xmlui.administrative.group.DeleteGroupsConfirm.column4");
private static final Message T_submit_confirm =
message("xmlui.general.delete");
private static final Message T_submit_cancel =
message("xmlui.general.cancel");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/groups",T_group_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
String idsString = parameters.getParameter("groupIDs", null);
ArrayList<Group> groups = new ArrayList<Group>();
for (String id : idsString.split(","))
{
Group group = Group.find(context,Integer.valueOf(id));
groups.add(group);
}
Division deleted = body.addInteractiveDivision("group-confirm-delete",
contextPath+"/admin/epeople",Division.METHOD_POST,"primary administrative groups");
deleted.setHead(T_head);
deleted.addPara(T_para);
Table table = deleted.addTable("groups-list",groups.size() + 1, 3);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell().addContent(T_column1);
header.addCell().addContent(T_column2);
header.addCell().addContent(T_column3);
header.addCell().addContent(T_column4);
for (Group group : groups)
{
Row row = table.addRow();
row.addCell().addContent(group.getID());
row.addCell().addContent(group.getName());
row.addCell().addContent(group.getMembers().length);
row.addCell().addContent(group.getMemberGroups().length);
}
Para buttons = deleted.addPara();
buttons.addButton("submit_confirm").setValue(T_submit_confirm);
buttons.addButton("submit_cancel").setValue(T_submit_cancel);
deleted.addHidden("administrative-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.administrative.group;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import org.dspace.app.xmlui.aspect.administrative.FlowGroupUtils;
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.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Highlight;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
/**
* Present the user with the group's current state. The user may select to
* change the group's name, OR search for new epeople / groups to add, OR select
* current group members for removal.
*
* @author Alexey Maslov
* @author Scott Phillips
*/
public class EditGroupForm extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_group_trail =
message("xmlui.administrative.group.general.group_trail");
private static final Message T_title =
message("xmlui.administrative.group.EditGroupForm.title");
private static final Message T_trail =
message("xmlui.administrative.group.EditGroupForm.trail");
private static final Message T_main_head =
message("xmlui.administrative.group.EditGroupForm.main_head");
private static final Message T_collection_para =
message("xmlui.administrative.group.EditGroupForm.collection_para");
private static final Message T_community_para =
message("xmlui.administrative.group.EditGroupForm.community_para");
private static final Message T_label_name =
message("xmlui.administrative.group.EditGroupForm.label_name");
private static final Message T_label_instructions =
message("xmlui.administrative.group.EditGroupForm.label_instructions");
private static final Message T_label_search =
message("xmlui.administrative.group.EditGroupForm.label_search");
private static final Message T_submit_search_people =
message("xmlui.administrative.group.EditGroupForm.submit_search_people");
private static final Message T_submit_search_groups =
message("xmlui.administrative.group.EditGroupForm.submit_search_groups");
private static final Message T_no_results =
message("xmlui.administrative.group.EditGroupForm.no_results");
private static final Message T_main_head_new =
message("xmlui.administrative.group.EditGroupForm.main_head_new");
private static final Message T_submit_clear =
message("xmlui.administrative.group.EditGroupForm.submit_clear");
private static final Message T_submit_save =
message("xmlui.general.save");
private static final Message T_submit_cancel =
message("xmlui.general.cancel");
private static final Message T_member =
message("xmlui.administrative.group.EditGroupForm.member");
private static final Message T_cycle =
message("xmlui.administrative.group.EditGroupForm.cycle");
private static final Message T_pending =
message("xmlui.administrative.group.EditGroupForm.pending");
private static final Message T_pending_warn =
message("xmlui.administrative.group.EditGroupForm.pending_warn");
private static final Message T_submit_add =
message("xmlui.administrative.group.EditGroupForm.submit_add");
private static final Message T_submit_remove =
message("xmlui.administrative.group.EditGroupForm.submit_remove");
// EPeople Search
private static final Message T_epeople_column1 =
message("xmlui.administrative.group.EditGroupForm.epeople_column1");
private static final Message T_epeople_column2 =
message("xmlui.administrative.group.EditGroupForm.epeople_column2");
private static final Message T_epeople_column3 =
message("xmlui.administrative.group.EditGroupForm.epeople_column3");
private static final Message T_epeople_column4 =
message("xmlui.administrative.group.EditGroupForm.epeople_column4");
// Group Search
private static final Message T_groups_column1 =
message("xmlui.administrative.group.EditGroupForm.groups_column1");
private static final Message T_groups_column2 =
message("xmlui.administrative.group.EditGroupForm.groups_column2");
private static final Message T_groups_column3 =
message("xmlui.administrative.group.EditGroupForm.groups_column3");
private static final Message T_groups_column4 =
message("xmlui.administrative.group.EditGroupForm.groups_column4");
private static final Message T_groups_column5 =
message("xmlui.administrative.group.EditGroupForm.groups_column5");
private static final Message T_groups_collection_link =
message("xmlui.administrative.group.ManageGroupsMain.groups_collection_link");
// Members
private static final Message T_members_head =
message("xmlui.administrative.group.EditGroupForm.members_head");
private static final Message T_members_column1 =
message("xmlui.administrative.group.EditGroupForm.members_column1");
private static final Message T_members_column2 =
message("xmlui.administrative.group.EditGroupForm.members_column2");
private static final Message T_members_column3 =
message("xmlui.administrative.group.EditGroupForm.members_column3");
private static final Message T_members_column4 =
message("xmlui.administrative.group.EditGroupForm.members_column4");
private static final Message T_members_group_name =
message("xmlui.administrative.group.EditGroupForm.members_group_name");
private static final Message T_members_pending =
message("xmlui.administrative.group.EditGroupForm.members_pending");
private static final Message T_members_none =
message("xmlui.administrative.group.EditGroupForm.members_none");
// How many results to show on a page.
private static final int RESULTS_PER_PAGE = 5;
/** The maximum size of a collection name allowed */
private static final int MAX_COLLECTION_NAME = 25;
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/groups",T_group_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException
{
// Find the group in question
int groupID = parameters.getParameterAsInteger("groupID",-1);
String currentName = decodeFromURL(parameters.getParameter("groupName",null));
if (currentName == null || currentName.length() == 0)
{
currentName = FlowGroupUtils.getName(context, groupID);
}
Group group = null;
if (groupID >= 0)
{
group = Group.find(context, groupID);
}
// Find the collection or community if applicable
Collection collection = null;
Community community = null;
if (group != null)
{
int collectionID = FlowGroupUtils.getCollectionId(group.getName());
if (collectionID > -1)
{
collection = Collection.find(context, collectionID);
}
else
{
int communityID = FlowGroupUtils.getCommunityId(group.getName());
if (communityID > -1)
{
community = Community.find(context, communityID);
}
}
}
// Get list of member groups
String memberGroupIDsString = parameters.getParameter("memberGroupIDs",null);
List<Integer> memberGroupIDs = new ArrayList<Integer>();
if (memberGroupIDsString != null)
{
for (String id : memberGroupIDsString.split(","))
{
if (id.length() > 0)
{
memberGroupIDs.add(Integer.valueOf(id));
}
}
}
// Get list of member epeople
String memberEPeopleIDsString = parameters.getParameter("memberEPeopleIDs",null);
List<Integer> memberEPeopleIDs = new ArrayList<Integer>();
if (memberEPeopleIDsString != null)
{
for (String id : memberEPeopleIDsString.split(","))
{
if (id.length() > 0)
{
memberEPeopleIDs.add(Integer.valueOf(id));
}
}
}
// Get highlight parameters
int highlightEPersonID = parameters.getParameterAsInteger("highlightEPersonID",-1);
int highlightGroupID = parameters.getParameterAsInteger("highlightGroupID",-1);
// Get search parameters
String query = decodeFromURL(parameters.getParameter("query",null));
int page = parameters.getParameterAsInteger("page",0);
String type = parameters.getParameter("type",null);
// Get any errors
String errorString = parameters.getParameter("errors",null);
List<String> errors = new ArrayList<String>();
if (errorString != null)
{
for (String error : errorString.split(","))
{
errors.add(error);
}
}
//DIVISION: group-edit
Division main = body.addInteractiveDivision("group-edit",contextPath+"/admin/groups",Division.METHOD_POST,"primary administrative groups");
if (group == null)
{
main.setHead(T_main_head_new);
}
else
{
main.setHead(T_main_head.parameterize(group.getName(), groupID));
}
if(collection != null)
{
Para para = main.addPara();
para.addContent(T_collection_para);
para.addXref(contextPath+"/handle/"+collection.getHandle(), collection.getMetadata("name"));
}
else if(community != null)
{
Para para = main.addPara();
para.addContent(T_community_para);
para.addXref(contextPath+"/handle/"+community.getHandle(), community.getMetadata("name"));
}
// DIVISION: group-actions
Division actions = main.addDivision("group-edit-actions");
Para groupName = actions.addPara();
groupName.addContent(T_label_name);
Text groupText = groupName.addText("group_name");
groupText.setValue(currentName);
if(collection != null || community != null)
{
// If this group is associated with a collection or community then it is special,
// thus they shouldn't be able to update it.
groupText.setDisabled();
groupText.setHelp(T_label_instructions);
}
else if (errors.contains("group_name") || errors.contains("group_name_duplicate"))
{
groupText.addError("");
}
Para searchBoxes = actions.addPara();
searchBoxes.addContent(T_label_search);
Text queryField = searchBoxes.addText("query");
queryField.setValue(query);
queryField.setSize(15);
searchBoxes.addButton("submit_search_epeople").setValue(T_submit_search_people);
searchBoxes.addButton("submit_search_groups").setValue(T_submit_search_groups);
if (query != null)
{
if ("eperson".equals(type))
{
searchBoxes.addButton("submit_clear").setValue(T_submit_clear);
addEPeopleSearch(main,query,page,group,memberEPeopleIDs);
}
else if ("group".equals(type))
{
searchBoxes.addButton("submit_clear").setValue(T_submit_clear);
addGroupSearch(main,group,query,page,group,memberGroupIDs);
}
}
boolean changes = false;
if (group != null)
{
changes = addMemberList(main, group, memberGroupIDs, memberEPeopleIDs, highlightEPersonID, highlightGroupID);
}
Para buttons = main.addPara();
buttons.addButton("submit_save").setValue(T_submit_save);
buttons.addButton("submit_cancel").setValue(T_submit_cancel);
if (changes)
{
main.addPara().addHighlight("warn").addContent(T_pending_warn);
}
main.addHidden("administrative-continue").setValue(knot.getId());
}
/**
* Search for epeople to add to this group.
*/
private void addEPeopleSearch(Division div, String query, int page, Group group, List<Integer> memberEPeopleIDs) throws SQLException, WingException
{
int resultCount = EPerson.searchResultCount(context, query);
EPerson[] epeople = EPerson.search(context, query, page*RESULTS_PER_PAGE, RESULTS_PER_PAGE);
Division results = div.addDivision("results");
if (resultCount > RESULTS_PER_PAGE)
{
// If there are enough results then paginate the results
String baseURL = contextPath +"/admin/groups?administrative-continue="+knot.getId();
int firstIndex = page*RESULTS_PER_PAGE+1;
int lastIndex = page*RESULTS_PER_PAGE + epeople.length;
String nextURL = null, prevURL = null;
if (page < (resultCount / RESULTS_PER_PAGE))
{
nextURL = baseURL + "&page=" + (page + 1);
}
if (page > 0)
{
prevURL = baseURL + "&page=" + (page - 1);
}
results.setSimplePagination(resultCount,firstIndex,lastIndex,prevURL, nextURL);
}
/* Set up a table with search results (if there are any). */
Table table = results.addTable("group-edit-search-eperson",epeople.length + 1, 1);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell().addContent(T_epeople_column1);
header.addCell().addContent(T_epeople_column2);
header.addCell().addContent(T_epeople_column3);
header.addCell().addContent(T_epeople_column4);
for (EPerson person : epeople)
{
String epersonID = String.valueOf(person.getID());
String fullName = person.getFullName();
String email = person.getEmail();
String url = contextPath+"/admin/epeople?administrative-continue="+knot.getId()+"&submit_edit_eperson&epersonID="+epersonID;
Row personData = table.addRow();
personData.addCell().addContent(person.getID());
personData.addCell().addXref(url, fullName);
personData.addCell().addXref(url, email);
// check if they are allready a member of the group
if (memberEPeopleIDs.contains(person.getID()))
{
// Check if they really members or just pending members
if (group != null && group.isMember(person))
{
personData.addCellContent(T_member);
}
else
{
personData.addCell().addHighlight("warn").addContent(T_pending);
}
}
else
{
personData.addCell().addButton("submit_add_eperson_"+epersonID).setValue(T_submit_add);
}
}
if (epeople.length <= 0) {
table.addRow().addCell(1, 4).addContent(T_no_results);
}
}
/**
* Search for groups to add to this group.
*/
private void addGroupSearch(Division div, Group sourceGroup, String query, int page, Group parent, List<Integer> memberGroupIDs) throws WingException, SQLException
{
int resultCount = Group.searchResultCount(context, query);
Group[] groups = Group.search(context, query, page*RESULTS_PER_PAGE, RESULTS_PER_PAGE);
Division results = div.addDivision("results");
if (resultCount > RESULTS_PER_PAGE)
{
// If there are enough results then paginate the results
String baseURL = contextPath +"/admin/groups?administrative-continue="+knot.getId();
int firstIndex = page*RESULTS_PER_PAGE+1;
int lastIndex = page*RESULTS_PER_PAGE + groups.length;
String nextURL = null, prevURL = null;
if (page < (resultCount / RESULTS_PER_PAGE))
{
nextURL = baseURL + "&page=" + (page + 1);
}
if (page > 0)
{
prevURL = baseURL + "&page=" + (page - 1);
}
results.setSimplePagination(resultCount,firstIndex,lastIndex,prevURL, nextURL);
}
Table table = results.addTable("roup-edit-search-group",groups.length + 1, 1);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell().addContent(T_groups_column1);
header.addCell().addContent(T_groups_column2);
header.addCell().addContent(T_groups_column3);
header.addCell().addContent(T_groups_column4);
header.addCell().addContent(T_groups_column5);
for (Group group : groups)
{
String groupID = String.valueOf(group.getID());
String name = group.getName();
String url = contextPath+"/admin/groups?administrative-continue="+knot.getId()+"&submit_edit_group&groupID="+groupID;
int memberCount = group.getMembers().length + group.getMemberGroups().length;
Row row = table.addRow();
row.addCell().addContent(groupID);
if (AuthorizeManager.isAdmin(context))
// Only administrators can edit other groups.
{
row.addCell().addXref(url, name);
}
else
{
row.addCell().addContent(name);
}
row.addCell().addContent(memberCount == 0 ? "-" : String.valueOf(memberCount));
Cell cell = row.addCell();
if (FlowGroupUtils.getCollectionId(group.getName()) > -1)
{
Collection collection = Collection.find(context, FlowGroupUtils.getCollectionId(group.getName()) );
if (collection != null)
{
String collectionName = collection.getMetadata("name");
if (collectionName == null)
{
collectionName = "";
}
else if (collectionName.length() > MAX_COLLECTION_NAME)
{
collectionName = collectionName.substring(0, MAX_COLLECTION_NAME - 3) + "...";
}
cell.addContent(collectionName+" ");
Highlight highlight = cell.addHighlight("fade");
highlight.addContent("[");
highlight.addXref(contextPath+"/handle/"+collection.getHandle(), T_groups_collection_link);
highlight.addContent("]");
}
}
// Check if the group is allready a member or would create a cycle.
if (memberGroupIDs.contains(group.getID()))
{
// Check if they really members or just pending members
if (parent != null && parent.isMember(group))
{
row.addCellContent(T_member);
}
else
{
row.addCell().addHighlight("warn").addContent(T_pending);
}
}
else if (isDescendant(sourceGroup, group, memberGroupIDs))
{
row.addCellContent(T_cycle);
}
else
{
row.addCell().addButton("submit_add_group_"+groupID).setValue(T_submit_add);
}
}
if (groups.length <= 0) {
table.addRow().addCell(1, 4).addContent(T_no_results);
}
}
/**
* Method to extensively check whether the first group has the second group as a distant
* parent. This is used to avoid creating cycles like A->B, B->C, C->D, D->A which leads
* all the groups involved to essentially include themselves.
*/
private boolean isDescendant(Group descendant, Group ancestor, List<Integer> memberGroupIDs) throws SQLException
{
Queue<Group> toVisit = new LinkedList<Group>();
Group currentGroup;
toVisit.offer(ancestor);
// Initialize by adding a list of our current list of group members.
for (Integer groupid : memberGroupIDs)
{
Group member = Group.find(context,groupid);
toVisit.offer(member);
}
while (!toVisit.isEmpty()) {
// 1. Grab a group from the queue
currentGroup = toVisit.poll();
// 2. See if it's the descendant we're looking for
if (currentGroup.equals(descendant)) {
return true;
}
// 3. If not, add that group's children to the queue
for (Group nextBatch : currentGroup.getMemberGroups()) {
toVisit.offer(nextBatch);
}
}
return false;
}
/**
* Add a table with all the current group's members to the specified division.
* @throws SQLException
*/
private boolean addMemberList(Division div, Group parent, List<Integer> memberGroupIDs, List<Integer> memberEPeopleIDs, int highlightEPersonID, int highlightGroupID) throws WingException, SQLException
{
// Flag to remember if there are any pending changes.
boolean changes = false;
Division members = div.addDivision("group-edit-members");
members.setHead(T_members_head);
Table table = members.addTable("group-edit-members-table",memberGroupIDs.size() + memberEPeopleIDs.size() + 1, 4);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell().addContent(T_members_column1);
header.addCell().addContent(T_members_column2);
header.addCell().addContent(T_members_column3);
header.addCell().addContent(T_members_column4);
// get all group members, pend or actual
@SuppressWarnings("unchecked") // the cast is correct
List<Integer> allMemberGroupIDs = new ArrayList<Integer>(memberGroupIDs);
for (Group group : parent.getMemberGroups())
{
if (!allMemberGroupIDs.contains(group.getID()))
{
allMemberGroupIDs.add(group.getID());
}
}
// Sort them to a consistent ordering
Collections.sort(allMemberGroupIDs);
// Loop through all group ids and display them.
for (Integer groupID : allMemberGroupIDs)
{
Group group = Group.find(context,groupID);
boolean highlight = (group.getID() == highlightGroupID);
boolean pendingAddition = !parent.isMember(group);
boolean pendingRemoval = !memberGroupIDs.contains(groupID);
addMemberRow(table, group, highlight,pendingAddition,pendingRemoval);
if (pendingAddition || pendingRemoval)
{
changes = true;
}
}
// get all members, pend or actual
@SuppressWarnings("unchecked") // the cast is correct
List<Integer> allMemberEPeopleIDs = new ArrayList<Integer>(memberEPeopleIDs);
for (EPerson eperson : parent.getMembers())
{
if (!allMemberEPeopleIDs.contains(eperson.getID()))
{
allMemberEPeopleIDs.add(eperson.getID());
}
}
// Sort them to a consistent ordering
Collections.sort(allMemberEPeopleIDs);
for (Integer epersonID : allMemberEPeopleIDs)
{
EPerson eperson = EPerson.find(context, epersonID);
boolean highlight = (eperson.getID() == highlightEPersonID);
boolean pendingAddition = !parent.isMember(eperson);
boolean pendingRemoval = !memberEPeopleIDs.contains(epersonID);
addMemberRow(table,eperson,highlight,pendingAddition,pendingRemoval);
if (pendingAddition || pendingRemoval)
{
changes = true;
}
}
if (allMemberGroupIDs.size() <= 0 && allMemberEPeopleIDs.size() <= 0)
{
table.addRow().addCell(1, 4).addContent(T_members_none);
}
return changes;
}
/**
* Add a singe member row for groups.
*
* @param table The table to add the row too.
* @param group The group being displayed in this row.
* @param highlight Should the row be highlighted.
* @param pendingAddition Is this group pending additition
* @param pendingRemoval Is this group pending removal
*/
private void addMemberRow(Table table,Group group, boolean highlight, boolean pendingAddition, boolean pendingRemoval) throws WingException, SQLException
{
String name = group.getName();
String url = contextPath+"/admin/groups?administrative-continue="+knot.getId()+"&submit_edit_group&groupID="+group.getID();
Row groupData = table.addRow(null,null,highlight ? "highlight" : null);
groupData.addCell().addHighlight("bold").addContent(group.getID());
// Mark if this member is pending or not.
Cell nameCell = groupData.addCell();
if (AuthorizeManager.isAdmin(context))
{
nameCell.addHighlight("bold").addXref(url, T_members_group_name.parameterize(name));
}
else
{
nameCell.addHighlight("bold").addContent(T_members_group_name.parameterize(name));
}
if (pendingAddition)
{
nameCell.addContent(" ");
nameCell.addHighlight("warn").addContent(T_members_pending);
}
groupData.addCell().addContent("-");
if (pendingRemoval)
{
groupData.addCell().addHighlight("warn").addContent(T_pending);
}
else
{
groupData.addCell().addButton("submit_remove_group_" + group.getID()).setValue(T_submit_remove);
}
}
/**
* Add a single member row for epeople.
*
* @param table The table to add a row too.
* @param eperson The eperson being displayed
* @param highlight Should this eperson be highlighted?
* @param pendingAddition Is this eperson pending addition?
* @param pendingRemoval Is this eperson pending removal?
*/
private void addMemberRow(Table table, EPerson eperson, boolean highlight, boolean pendingAddition, boolean pendingRemoval) throws WingException, SQLException
{
String fullName = eperson.getFullName();
String email = eperson.getEmail();
String url = contextPath+"/admin/epeople?administrative-continue="+knot.getId()+"&submit_edit_eperson&epersonID="+eperson.getID();
Row personData = table.addRow(null,null,highlight ? "highlight" : null);
personData.addCell().addContent(eperson.getID());
Cell nameCell = personData.addCell();
nameCell.addXref(url, fullName);
if (pendingAddition)
{
nameCell.addContent(" ");
nameCell.addHighlight("warn").addContent(T_members_pending);
}
personData.addCell().addXref(url, email);
if (pendingRemoval)
{
personData.addCell().addHighlight("warn").addContent(T_pending);
}
else
{
personData.addCell().addButton("submit_remove_eperson_" + eperson.getID()).setValue(T_submit_remove);
}
}
}
| 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.administrative.item;
import java.io.IOException;
import java.sql.SQLException;
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.Button;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.File;
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.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Bundle;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.xml.sax.SAXException;
/**
*
* Show a form that allows the user to upload a new bitstream. The
* user can select the new bitstream's bundle (which is unchangable
* after upload) and a description for the file.
*
* @author Scott Phillips
*/
public class AddBitstreamForm extends AbstractDSpaceTransformer
{
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_title = message("xmlui.administrative.item.AddBitstreamForm.title");
private static final Message T_trail = message("xmlui.administrative.item.AddBitstreamForm.trail");
private static final Message T_head1 = message("xmlui.administrative.item.AddBitstreamForm.head1");
private static final Message T_bundle_label = message("xmlui.administrative.item.AddBitstreamForm.bundle_label");
private static final Message T_file_label = message("xmlui.administrative.item.AddBitstreamForm.file_label");
private static final Message T_file_help = message("xmlui.administrative.item.AddBitstreamForm.file_help");
private static final Message T_description_label = message("xmlui.administrative.item.AddBitstreamForm.description_label");
private static final Message T_description_help = message("xmlui.administrative.item.AddBitstreamForm.description_help");
private static final Message T_submit_upload = message("xmlui.administrative.item.AddBitstreamForm.submit_upload");
private static final Message T_no_bundles = message("xmlui.administrative.item.AddBitstreamForm.no_bundles");
private static final String DEFAULT_BUNDLE_LIST = "ORIGINAL, METADATA, THUMBNAIL, LICENSE, CC_LICENSE";
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException
{
int itemID = parameters.getParameterAsInteger("itemID", -1);
org.dspace.content.Item item = org.dspace.content.Item.find(context, itemID);
// DIVISION: main div
Division div = body.addInteractiveDivision("add-bitstream", contextPath + "/admin/item", Division.METHOD_MULTIPART, "primary administrative item");
// LIST: upload form
List upload = div.addList("submit-upload-new", List.TYPE_FORM);
upload.setHead(T_head1);
int bundleCount = 0; // record how many bundles we are able to upload too.
Select select = upload.addItem().addSelect("bundle");
select.setLabel(T_bundle_label);
// Get the list of bundles to allow the user to upload too. Either use the default
// or one supplied from the dspace.cfg.
String bundleString = ConfigurationManager.getProperty("xmlui.bundle.upload");
if (bundleString == null || bundleString.length() == 0)
{
bundleString = DEFAULT_BUNDLE_LIST;
}
String[] parts = bundleString.split(",");
for (String part : parts)
{
if (addBundleOption(item, select, part.trim()))
{
bundleCount++;
}
}
select.setOptionSelected("ORIGINAL");
if (bundleCount == 0) {
select.setDisabled();
}
File file = upload.addItem().addFile("file");
file.setLabel(T_file_label);
file.setHelp(T_file_help);
file.setRequired();
if (bundleCount == 0) {
file.setDisabled();
}
Text description = upload.addItem().addText("description");
description.setLabel(T_description_label);
description.setHelp(T_description_help);
if (bundleCount == 0) {
description.setDisabled();
}
if (bundleCount == 0) {
upload.addItem().addContent(T_no_bundles);
}
// ITEM: actions
Item actions = upload.addItem();
Button button = actions.addButton("submit_upload");
button.setValue(T_submit_upload);
if (bundleCount == 0) {
button.setDisabled();
}
actions.addButton("submit_cancel").setValue(T_submit_cancel);
div.addHidden("administrative-continue").setValue(knot.getId());
}
/**
* Add the bundleName to the list of bundles available to submit to.
* Performs an authorization check that the current user has privileges
* @param item DSO item being evaluated
* @param select DRI wing select box that is being added to
* @param bundleName
* @return boolean indicating whether user can upload to bundle
* @throws SQLException
* @throws WingException
*/
public boolean addBundleOption(org.dspace.content.Item item, Select select, String bundleName) throws SQLException, WingException
{
Bundle[] bundles = item.getBundles(bundleName);
if (bundles == null || bundles.length == 0)
{
// No bundle, so the user has to be authorized to add to item.
if(!AuthorizeManager.authorizeActionBoolean(context, item, Constants.ADD))
{
return false;
}
} else
{
// At least one bundle exists, does the user have privleges to upload to it?
Bundle bundle = bundles[0];
if (!AuthorizeManager.authorizeActionBoolean(context, bundle, Constants.ADD))
{
return false; // you can't upload to this bundle.
}
// You also need the write privlege on the bundle.
if (!AuthorizeManager.authorizeActionBoolean(context, bundle, Constants.WRITE))
{
return false; // you can't upload
}
}
// It's okay to upload.
select.addOption(bundleName, message("xmlui.administrative.item.AddBitstreamForm.bundle." + bundleName));
return true;
}
}
| 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.administrative.item;
import java.sql.SQLException;
import org.dspace.app.util.AuthorizeUtil;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
/**
* Display basic meta-meta information about the item and allow the user to change
* it's state such as withdraw or reinstate, possibily even completely deleting the item!
*
* @author Jay Paz
* @author Scott Phillips
*/
public class EditItemStatusForm extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_submit_return = message("xmlui.general.return");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_option_head = message("xmlui.administrative.item.general.option_head");
private static final Message T_option_status = message("xmlui.administrative.item.general.option_status");
private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams");
private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata");
private static final Message T_option_view = message("xmlui.administrative.item.general.option_view");
private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate");
private static final Message T_title = message("xmlui.administrative.item.EditItemStatusForm.title");
private static final Message T_trail = message("xmlui.administrative.item.EditItemStatusForm.trail");
private static final Message T_para1 = message("xmlui.administrative.item.EditItemStatusForm.para1");
private static final Message T_label_id = message("xmlui.administrative.item.EditItemStatusForm.label_id");
private static final Message T_label_handle = message("xmlui.administrative.item.EditItemStatusForm.label_handle");
private static final Message T_label_modified = message("xmlui.administrative.item.EditItemStatusForm.label_modified");
private static final Message T_label_in = message("xmlui.administrative.item.EditItemStatusForm.label_in");
private static final Message T_label_page = message("xmlui.administrative.item.EditItemStatusForm.label_page");
private static final Message T_label_auth = message("xmlui.administrative.item.EditItemStatusForm.label_auth");
private static final Message T_label_withdraw = message("xmlui.administrative.item.EditItemStatusForm.label_withdraw");
private static final Message T_label_reinstate = message("xmlui.administrative.item.EditItemStatusForm.label_reinstate");
private static final Message T_label_move = message("xmlui.administrative.item.EditItemStatusForm.label_move");
private static final Message T_label_delete = message("xmlui.administrative.item.EditItemStatusForm.label_delete");
private static final Message T_submit_authorizations = message("xmlui.administrative.item.EditItemStatusForm.submit_authorizations");
private static final Message T_submit_withdraw = message("xmlui.administrative.item.EditItemStatusForm.submit_withdraw");
private static final Message T_submit_reinstate = message("xmlui.administrative.item.EditItemStatusForm.submit_reinstate");
private static final Message T_submit_move = message("xmlui.administrative.item.EditItemStatusForm.submit_move");
private static final Message T_submit_delete = message("xmlui.administrative.item.EditItemStatusForm.submit_delete");
private static final Message T_na = message("xmlui.administrative.item.EditItemStatusForm.na");
private static final Message T_not_allowed = message("xmlui.administrative.item.EditItemStatusForm.not_allowed");
private static final Message T_collectionadmins_only = message("xmlui.administrative.item.EditItemStatusForm.collection_admins_only");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws SQLException, WingException
{
// Get our parameters and state
int itemID = parameters.getParameterAsInteger("itemID",-1);
Item item = Item.find(context, itemID);
String baseURL = contextPath+"/admin/item?administrative-continue="+knot.getId();
// DIVISION: main
Division main = body.addInteractiveDivision("edit-item-status", contextPath+"/admin/item", Division.METHOD_POST,"primary administrative edit-item-status");
main.setHead(T_option_head);
// LIST: options
List options = main.addList("options",List.TYPE_SIMPLE,"horizontal");
options.addItem().addHighlight("bold").addXref(baseURL+"&submit_status",T_option_status);
options.addItem().addXref(baseURL+"&submit_bitstreams",T_option_bitstreams);
options.addItem().addXref(baseURL+"&submit_metadata",T_option_metadata);
options.addItem().addXref(baseURL + "&view_item", T_option_view);
options.addItem().addXref(baseURL + "&submit_curate", T_option_curate);
// PARA: Helpfull instructions
main.addPara(T_para1);
// LIST: Item meta-meta information
List itemInfo = main.addList("item-info");
itemInfo.addLabel(T_label_id);
itemInfo.addItem(String.valueOf(item.getID()));
itemInfo.addLabel(T_label_handle);
itemInfo.addItem(item.getHandle()==null?"None":item.getHandle());
itemInfo.addLabel(T_label_modified);
itemInfo.addItem(item.getLastModified().toString());
itemInfo.addLabel(T_label_in);
List subList = itemInfo.addList("collections", List.TYPE_SIMPLE);
Collection[] collections = item.getCollections();
for(Collection collection : collections) {
subList.addItem(collection.getMetadata("name"));
}
itemInfo.addLabel(T_label_page);
if(item.getHandle()==null){
itemInfo.addItem(T_na);
}
else{
itemInfo.addItem().addXref(ConfigurationManager.getProperty("dspace.url") + "/handle/" + item.getHandle(),ConfigurationManager.getProperty("dspace.url") + "/handle/" + item.getHandle());
}
itemInfo.addLabel(T_label_auth);
try
{
AuthorizeUtil.authorizeManageItemPolicy(context, item);
itemInfo.addItem().addButton("submit_authorization").setValue(T_submit_authorizations);
}
catch (AuthorizeException authex)
{
addNotAllowedButton(itemInfo.addItem(), "submit_authorization", T_submit_authorizations);
}
if(!item.isWithdrawn())
{
itemInfo.addLabel(T_label_withdraw);
try
{
AuthorizeUtil.authorizeWithdrawItem(context, item);
itemInfo.addItem().addButton("submit_withdraw").setValue(T_submit_withdraw);
}
catch (AuthorizeException authex)
{
addNotAllowedButton(itemInfo.addItem(), "submit_withdraw", T_submit_withdraw);
}
}
else
{
itemInfo.addLabel(T_label_reinstate);
try
{
AuthorizeUtil.authorizeReinstateItem(context, item);
itemInfo.addItem().addButton("submit_reinstate").setValue(T_submit_reinstate);
}
catch (AuthorizeException authex)
{
addNotAllowedButton(itemInfo.addItem(), "submit_reinstate", T_submit_reinstate);
}
}
itemInfo.addLabel(T_label_move);
addCollectionAdminOnlyButton(itemInfo.addItem(), item.getOwningCollection(), "submit_move", T_submit_move);
itemInfo.addLabel(T_label_delete);
if (AuthorizeManager.authorizeActionBoolean(context, item, Constants.DELETE))
{
itemInfo.addItem().addButton("submit_delete").setValue(T_submit_delete);
}
else
{
addNotAllowedButton(itemInfo.addItem(), "submit_delete", T_submit_delete);
}
// PARA: main actions
main.addPara().addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-continue").setValue(knot.getId());
}
/**
* Add a disabled button with a "not allowed" notice
* @param item
* @param buttonName
* @param buttonLabel
* @throws WingException
* @throws SQLException
*/
private void addNotAllowedButton(org.dspace.app.xmlui.wing.element.Item item, String buttonName, Message buttonLabel) throws WingException, SQLException
{
Button button = item.addButton(buttonName);
button.setValue(buttonLabel);
button.setDisabled();
item.addHighlight("fade").addContent(T_not_allowed);
}
private void addCollectionAdminOnlyButton(org.dspace.app.xmlui.wing.element.Item item, Collection collection, String buttonName, Message buttonLabel) throws WingException, SQLException
{
Button button = item.addButton(buttonName);
button.setValue(buttonLabel);
if (!AuthorizeManager.isAdmin(context, collection))
{
// Only admins can create or delete
button.setDisabled();
item.addHighlight("fade").addContent(T_collectionadmins_only);
}
}
}
| 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.administrative.item;
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.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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.content.Collection;
import org.dspace.content.Item;
/**
* Display basic meta-meta information about the item and allow the user to
* change it's state such as withdraw or reinstate, possibily even completely
* deleting the item!
*
* @author Jay Paz
* @author Scott Phillips
*/
public class ViewItem extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_option_head = message("xmlui.administrative.item.general.option_head");
private static final Message T_option_status = message("xmlui.administrative.item.general.option_status");
private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams");
private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata");
private static final Message T_option_view = message("xmlui.administrative.item.general.option_view");
private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate");
private static final Message T_title = message("xmlui.administrative.item.ViewItem.title");
private static final Message T_trail = message("xmlui.administrative.item.ViewItem.trail");
private static final Message T_head_parent_collections = message("xmlui.ArtifactBrowser.ItemViewer.head_parent_collections");
private static final Message T_show_simple =
message("xmlui.ArtifactBrowser.ItemViewer.show_simple");
private static final Message T_show_full =
message("xmlui.ArtifactBrowser.ItemViewer.show_full");
public void addPageMeta(PageMeta pageMeta) throws WingException {
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws SQLException, WingException {
// Get our parameters and state
Request request = ObjectModelHelper.getRequest(objectModel);
String show = request.getParameter("show");
boolean showFullItem = false;
if (show != null && show.length() > 0)
{
showFullItem = true;
}
int itemID = parameters.getParameterAsInteger("itemID", -1);
Item item = Item.find(context, itemID);
String baseURL = contextPath + "/admin/item?administrative-continue="
+ knot.getId() ;
String link = baseURL + "&view_item" + (showFullItem?"":"&show=full");
String tabLink = baseURL + "&view_item" + (!showFullItem?"":"&show=full");
// DIVISION: main
Division main = body.addInteractiveDivision("edit-item-status",
contextPath + "/admin/item", Division.METHOD_POST,
"primary administrative edit-item-status");
main.setHead(T_option_head);
// LIST: options
List options = main.addList("options", List.TYPE_SIMPLE, "horizontal");
options.addItem().addXref(
baseURL + "&submit_status", T_option_status);
options.addItem().addXref(baseURL + "&submit_bitstreams",
T_option_bitstreams);
options.addItem().addXref(baseURL + "&submit_metadata",
T_option_metadata);
options.addItem().addHighlight("bold").addXref(tabLink, T_option_view);
options.addItem().addXref(baseURL + "&submit_curate", T_option_curate);
// item
Para showfullPara = main.addPara(null, "item-view-toggle item-view-toggle-top");
if (showFullItem)
{
link = baseURL + "&view_item";
showfullPara.addXref(link).addContent(T_show_simple);
}
else
{
link = baseURL + "&view_item&show=full";
showfullPara.addXref(link).addContent(T_show_full);
}
ReferenceSet referenceSet;
referenceSet = main.addReferenceSet("collection-viewer",
showFullItem?ReferenceSet.TYPE_DETAIL_VIEW:ReferenceSet.TYPE_SUMMARY_VIEW);
// Refrence the actual Item
ReferenceSet appearsInclude = referenceSet.addReference(item)
.addReferenceSet(ReferenceSet.TYPE_DETAIL_LIST, null, "hierarchy");
appearsInclude.setHead(T_head_parent_collections);
// Reference all collections the item appears in.
for (Collection collection : item.getCollections()) {
appearsInclude.addReference(collection);
}
showfullPara = main.addPara(null, "item-view-toggle item-view-toggle-bottom");
if (showFullItem)
{
showfullPara.addXref(link).addContent(T_show_simple);
}
else
{
showfullPara.addXref(link).addContent(T_show_full);
}
}
}
| 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.administrative.item;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Comparator;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
/**
* This page is used as a general confirmation page for any
* actions on items. It will display the item and ask if the
* user is sure they want to preform the action.
*
* The "confirm" parameter determines what action is confirmed.
* There are three possible values, "delete", "withdraw", or
* "reinstate"
*
* @author Jay Paz
* @author Scott Phillips
*/
public class ConfirmItemForm extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
private static final Message T_title = message("xmlui.administrative.item.ConfirmItemForm.title");
private static final Message T_trail = message("xmlui.administrative.item.ConfirmItemForm.trail");
private static final Message T_head1 = message("xmlui.administrative.item.ConfirmItemForm.head1");
private static final Message T_para_delete = message("xmlui.administrative.item.ConfirmItemForm.para_delete");
private static final Message T_para_withdraw = message("xmlui.administrative.item.ConfirmItemForm.para_withdraw");
private static final Message T_para_reinstate = message("xmlui.administrative.item.ConfirmItemForm.para_reinstate");
private static final Message T_column1 = message("xmlui.administrative.item.ConfirmItemForm.column1");
private static final Message T_column2 = message("xmlui.administrative.item.ConfirmItemForm.column2");
private static final Message T_column3 = message("xmlui.administrative.item.ConfirmItemForm.column3");
private static final Message T_submit_delete = message("xmlui.general.delete");
private static final Message T_submit_withdraw = message("xmlui.administrative.item.ConfirmItemForm.submit_withdraw");
private static final Message T_submit_reinstate = message("xmlui.administrative.item.ConfirmItemForm.submit_reinstate");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath+"/admin/item", T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
@SuppressWarnings("unchecked") // the cast is correct
public void addBody(Body body) throws WingException, SQLException
{
// Get our parameters and state
int itemID = parameters.getParameterAsInteger("itemID",-1);
Item item = Item.find(context, itemID);
final DCValue[] values = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
Arrays.sort(values, new DCValueComparator());
String confirm = parameters.getParameter("confirm",null);
// DIVISION: Main
Division main = body.addInteractiveDivision("confirm-item", contextPath+"/admin/item", Division.METHOD_POST,"primary administrative item");
main.setHead(T_head1.parameterize(item.getHandle()));
// PARA: descriptive instructions
if("delete".equals(confirm))
{
main.addPara(T_para_delete);
}
else if ("reinstate".equals(confirm))
{
main.addPara(T_para_reinstate);
}
else if ("withdraw".equals(confirm))
{
main.addPara(T_para_withdraw);
}
// TABLE: metadata table
Table table = main.addTable("withdrawValues", values.length+1, 3);
final Row header = table.addRow(Row.ROLE_HEADER);
header.addCell().addContent(T_column1);
header.addCell().addContent(T_column2);
header.addCell().addContent(T_column3);
for(final DCValue value:values){
final String dcValue = value.schema + ". " + value.element + (value.qualifier==null?"":(". " + value.qualifier));
final Row row = table.addRow();
row.addCell().addContent(dcValue);
row.addCell().addContent(value.value);
row.addCell().addContent(value.language);
}
// LIST: actions, confirm or return
org.dspace.app.xmlui.wing.element.Item actions = main.addList("actions", List.TYPE_FORM).addItem();
Button confirmButton = actions.addButton("submit_confirm");
if("delete".equals(confirm))
{
confirmButton.setValue(T_submit_delete);
}
else if ("reinstate".equals(confirm))
{
confirmButton.setValue(T_submit_reinstate);
}
else if ("withdraw".equals(confirm))
{
confirmButton.setValue(T_submit_withdraw);
}
actions.addButton("submit_cancel").setValue(T_submit_cancel);
main.addHidden("administrative-continue").setValue(knot.getId());
}
/**
* Compare two metadata element's name so that they may be sorted.
*/
static class DCValueComparator implements Comparator, Serializable {
public int compare(Object arg0, Object arg1) {
final DCValue o1 = (DCValue)arg0;
final DCValue o2 = (DCValue)arg1;
final String s1 = o1.schema + o1.element + (o1.qualifier==null?"":("." + o1.qualifier));
final String s2 = o2.schema + o2.element + (o2.qualifier==null?"":("." + o2.qualifier));
return s1.compareTo(s2);
}
}
}
| 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.administrative.item;
import java.io.IOException;
import java.sql.SQLException;
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.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.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.xml.sax.SAXException;
/**
*
* Show a form allowing the user to edit a bitstream's metadata, the description & format.
*
* @author Scott Phillips
*/
public class EditBitstreamForm extends AbstractDSpaceTransformer
{
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_submit_save = message("xmlui.general.save");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_title = message("xmlui.administrative.item.EditBitstreamForm.title");
private static final Message T_trail = message("xmlui.administrative.item.EditBitstreamForm.trail");
private static final Message T_head1 = message("xmlui.administrative.item.EditBitstreamForm.head1");
private static final Message T_file_label = message("xmlui.administrative.item.EditBitstreamForm.file_label");
private static final Message T_primary_label = message("xmlui.administrative.item.EditBitstreamForm.primary_label");
private static final Message T_primary_option_yes = message("xmlui.administrative.item.EditBitstreamForm.primary_option_yes");
private static final Message T_primary_option_no = message("xmlui.administrative.item.EditBitstreamForm.primary_option_no");
private static final Message T_description_label = message("xmlui.administrative.item.EditBitstreamForm.description_label");
private static final Message T_description_help = message("xmlui.administrative.item.EditBitstreamForm.description_help");
private static final Message T_para1 = message("xmlui.administrative.item.EditBitstreamForm.para1");
private static final Message T_format_label = message("xmlui.administrative.item.EditBitstreamForm.format_label");
private static final Message T_format_default = message("xmlui.administrative.item.EditBitstreamForm.format_default");
private static final Message T_para2 = message("xmlui.administrative.item.EditBitstreamForm.para2");
private static final Message T_user_label = message("xmlui.administrative.item.EditBitstreamForm.user_label");
private static final Message T_user_help = message("xmlui.administrative.item.EditBitstreamForm.user_help");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Get our parameters
int bitstreamID = parameters.getParameterAsInteger("bitstreamID",-1);
// Get the bitstream and all the various formats
// Administrator is allowed to see internal formats too.
Bitstream bitstream = Bitstream.find(context, bitstreamID);
BitstreamFormat currentFormat = bitstream.getFormat();
BitstreamFormat[] bitstreamFormats = AuthorizeManager.isAdmin(context) ?
BitstreamFormat.findAll(context) :
BitstreamFormat.findNonInternal(context);
boolean primaryBitstream = false;
Bundle[] bundles = bitstream.getBundles();
if (bundles != null && bundles.length > 0)
{
if (bitstreamID == bundles[0].getPrimaryBitstreamID())
{
primaryBitstream = true;
}
}
// File name & url
String fileUrl = contextPath + "/bitstream/id/" +bitstream.getID() + "/" + bitstream.getName();
String fileName = bitstream.getName();
// DIVISION: main
Division div = body.addInteractiveDivision("edit-bitstream", contextPath+"/admin/item", Division.METHOD_MULTIPART, "primary administrative item");
div.setHead(T_head1);
// LIST: edit form
List edit = div.addList("edit-bitstream-list", List.TYPE_FORM);
edit.addLabel(T_file_label);
edit.addItem().addXref(fileUrl, fileName);
Select primarySelect = edit.addItem().addSelect("primary");
primarySelect.setLabel(T_primary_label);
primarySelect.addOption(primaryBitstream,"yes",T_primary_option_yes);
primarySelect.addOption(!primaryBitstream,"no",T_primary_option_no);
Text description = edit.addItem().addText("description");
description.setLabel(T_description_label);
description.setHelp(T_description_help);
description.setValue(bitstream.getDescription());
edit.addItem(T_para1);
// System supported formats
Select format = edit.addItem().addSelect("formatID");
format.setLabel(T_format_label);
// load the options menu, skipping the "Unknown" format since "Not on list" takes its place
int unknownFormatID = BitstreamFormat.findUnknown(context).getID();
format.addOption(-1,T_format_default);
for (BitstreamFormat bitstreamFormat : bitstreamFormats)
{
if (bitstreamFormat.getID() == unknownFormatID)
{
continue;
}
String supportLevel = "Unknown";
if (bitstreamFormat.getSupportLevel() == BitstreamFormat.KNOWN)
{
supportLevel = "known";
}
else if (bitstreamFormat.getSupportLevel() == BitstreamFormat.SUPPORTED)
{
supportLevel = "Supported";
}
String name = bitstreamFormat.getShortDescription()+" ("+supportLevel+")";
if (bitstreamFormat.isInternal())
{
name += " (Internal)";
}
int id = bitstreamFormat.getID();
format.addOption(id,name);
}
if (currentFormat != null)
{
format.setOptionSelected(currentFormat.getID());
}
else
{
format.setOptionSelected(-1);
}
edit.addItem(T_para2);
// User supplied format
Text userFormat = edit.addItem().addText("user_format");
userFormat.setLabel(T_user_label);
userFormat.setHelp(T_user_help);
userFormat.setValue(bitstream.getUserFormatDescription());
// ITEM: form actions
org.dspace.app.xmlui.wing.element.Item actions = edit.addItem();
actions.addButton("submit_save").setValue(T_submit_save);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
div.addHidden("administrative-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.administrative.item;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
/**
*
* @author wbossons
*/
public class CurateItemForm extends AbstractDSpaceTransformer {
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_submit_perform = message("xmlui.general.perform");
private static final Message T_submit_queue = message("xmlui.general.queue");
private static final Message T_submit_return = message("xmlui.general.return");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_option_head = message("xmlui.administrative.item.general.option_head");
private static final Message T_option_status = message("xmlui.administrative.item.general.option_status");
private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams");
private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata");
private static final Message T_option_view = message("xmlui.administrative.item.general.option_view");
private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate");
private static final Message T_title = message("xmlui.administrative.item.CurateItemForm.title");
private static final Message T_trail = message("xmlui.administrative.item.CurateItemForm.trail");
private static final Message T_label_name = message("xmlui.administrative.item.CurateItemForm.label_name");
/**
* common package method for initializing form gui elements
* Could be refactored.
*
* @param pageMeta
* @throws WingException
*/
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
/** addBody
*
* @param body
* @throws WingException
* @throws SQLException
* @throws AuthorizeException
*/
public void addBody(Body body)
throws WingException, SQLException,
AuthorizeException, UnsupportedEncodingException
{
int itemID = parameters.getParameterAsInteger("itemID", -1);
Item item = Item.find(context, itemID);
String baseURL = contextPath + "/admin/item?administrative-continue="
+ knot.getId() ;
// DIVISION: main
Division main = body.addInteractiveDivision("edit-item-status", contextPath + "/admin/item", Division.METHOD_POST,"primary administrative edit-item-status");
main.setHead(T_option_head);
// LIST: options
List options = main.addList("options", List.TYPE_SIMPLE, "horizontal");
options.addItem().addXref(baseURL + "&submit_status", T_option_status);
options.addItem().addXref(baseURL + "&submit_bitstreams", T_option_bitstreams);
options.addItem().addXref(baseURL + "&submit_metadata", T_option_metadata);
options.addItem().addXref(baseURL + "&view_item", T_option_view);
options.addItem().addHighlight("bold").addXref(baseURL + "&submit_curate", T_option_curate);
List curationTaskList = main.addList("curationTaskList", "form");
curationTaskList.addLabel(T_label_name);
Select select = curationTaskList.addItem().addSelect("curate_task");
select = getCurationOptions(select);
select.setSize(1);
select.setRequired();
// need submit_curate_task and submit_return
Para buttonList = main.addPara();
buttonList.addButton("submit_curate_task").setValue(T_submit_perform);
buttonList.addButton("submit_queue_task").setValue(T_submit_queue);
buttonList.addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-continue").setValue(knot.getId());
}
private Select getCurationOptions(Select select)
throws WingException, UnsupportedEncodingException {
String tasksString = ConfigurationManager.getProperty("curate", "ui.tasknames");
String[] tasks = tasksString.split(",");
for (String task : tasks)
{
String[] keyValuePair = task.split("=");
select.addOption(URLDecoder.decode(keyValuePair[0].trim(), "UTF-8"),
URLDecoder.decode(keyValuePair[1].trim(), "UTF-8"));
}
return select;
}
// Add a method here to build it into the dspace.cfg ... ui.curation_tasks = estimate = "Estate"
// Mapping the task name to either the description or the mapping key
}
| 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.administrative.item;
import java.sql.SQLException;
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.Cell;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Highlight;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.Item;
import org.dspace.core.Constants;
/**
* Show a list of the item's bitstreams allowing the user to delete them,
* edit them, or upload new bitstreams.
*
* @author Jay Paz
* @author Scott phillips
*/
public class EditItemBitstreamsForm extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_submit_return = message("xmlui.general.return");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_option_head = message("xmlui.administrative.item.general.option_head");
private static final Message T_option_status = message("xmlui.administrative.item.general.option_status");
private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams");
private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata");
private static final Message T_option_view = message("xmlui.administrative.item.general.option_view");
private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate");
private static final Message T_title = message("xmlui.administrative.item.EditItemBitstreamsForm.title");
private static final Message T_trail = message("xmlui.administrative.item.EditItemBitstreamsForm.trail");
private static final Message T_head1 = message("xmlui.administrative.item.EditItemBitstreamsForm.head1");
private static final Message T_column1 = message("xmlui.administrative.item.EditItemBitstreamsForm.column1");
private static final Message T_column2 = message("xmlui.administrative.item.EditItemBitstreamsForm.column2");
private static final Message T_column3 = message("xmlui.administrative.item.EditItemBitstreamsForm.column3");
private static final Message T_column4 = message("xmlui.administrative.item.EditItemBitstreamsForm.column4");
private static final Message T_column5 = message("xmlui.administrative.item.EditItemBitstreamsForm.column5");
private static final Message T_bundle_label = message("xmlui.administrative.item.EditItemBitstreamsForm.bundle_label");
private static final Message T_primary_label = message("xmlui.administrative.item.EditItemBitstreamsForm.primary_label");
private static final Message T_view_link = message("xmlui.administrative.item.EditItemBitstreamsForm.view_link");
private static final Message T_submit_add = message("xmlui.administrative.item.EditItemBitstreamsForm.submit_add");
private static final Message T_submit_delete = message("xmlui.administrative.item.EditItemBitstreamsForm.submit_delete");
private static final Message T_no_upload = message("xmlui.administrative.item.EditItemBitstreamsForm.no_upload");
private static final Message T_no_remove = message("xmlui.administrative.item.EditItemBitstreamsForm.no_remove");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws SQLException, WingException
{
// Get our parameters and state
int itemID = parameters.getParameterAsInteger("itemID",-1);
Item item = Item.find(context, itemID);
String baseURL = contextPath+"/admin/item?administrative-continue="+knot.getId();
// DIVISION: main div
Division main = body.addInteractiveDivision("edit-item-status", contextPath+"/admin/item", Division.METHOD_POST,"primary administrative item");
main.setHead(T_option_head);
// LIST: options
List options = main.addList("options",List.TYPE_SIMPLE,"horizontal");
options.addItem().addXref(baseURL+"&submit_status",T_option_status);
options.addItem().addHighlight("bold").addXref(baseURL+"&submit_bitstreams",T_option_bitstreams);
options.addItem().addXref(baseURL+"&submit_metadata",T_option_metadata);
options.addItem().addXref(baseURL + "&view_item", T_option_view);
options.addItem().addXref(baseURL + "&submit_curate", T_option_curate);
// TABLE: Bitstream summary
Table files = main.addTable("editItemBitstreams", 1, 1);
files.setHead(T_head1);
Row header = files.addRow(Row.ROLE_HEADER);
header.addCellContent(T_column1);
header.addCellContent(T_column2);
header.addCellContent(T_column3);
header.addCellContent(T_column4);
header.addCellContent(T_column5);
Bundle[] bundles = item.getBundles();
for (Bundle bundle : bundles)
{
Cell bundleCell = files.addRow().addCell(1, 5);
bundleCell.addContent(T_bundle_label.parameterize(bundle.getName()));
Bitstream[] bitstreams = bundle.getBitstreams();
for (Bitstream bitstream : bitstreams)
{
boolean primary = (bundle.getPrimaryBitstreamID() == bitstream.getID());
String name = bitstream.getName();
if (name != null && name.length() > 50)
{
// If the fiel name is too long the shorten it so that it will display nicely.
String shortName = name.substring(0,15);
shortName += " ... ";
shortName += name.substring(name.length()-25,name.length());
name = shortName;
}
String description = bitstream.getDescription();
String format = null;
BitstreamFormat bitstreamFormat = bitstream.getFormat();
if (bitstreamFormat != null)
{
format = bitstreamFormat.getShortDescription();
}
String editURL = contextPath + "/admin/item?administrative-continue="+knot.getId()+"&bitstreamID="+bitstream.getID()+"&submit_edit";
String viewURL = contextPath + "/bitstream/id/"+bitstream.getID()+"/"+bitstream.getName();
Row row = files.addRow();
CheckBox remove = row.addCell().addCheckBox("remove");
remove.setLabel("remove");
remove.addOption(bundle.getID() + "/" +bitstream.getID() );
if (!AuthorizeManager.authorizeActionBoolean(context, item, Constants.REMOVE))
{
remove.setDisabled();
}
if (AuthorizeManager.authorizeActionBoolean(context, bitstream, Constants.WRITE))
{
// The user can edit the bitstream give them a link.
Cell cell = row.addCell();
cell.addXref(editURL,name);
if (primary)
{
cell.addXref(editURL, T_primary_label);
}
row.addCell().addXref(editURL,description);
row.addCell().addXref(editURL,format);
}
else
{
// The user can't edit the bitstream just show them it.
Cell cell = row.addCell();
cell.addContent(name);
if (primary)
{
cell.addContent(T_primary_label);
}
row.addCell().addContent(description);
row.addCell().addContent(format);
}
Highlight highlight = row.addCell().addHighlight("fade");
highlight.addContent("[");
highlight.addXref(viewURL,T_view_link);
highlight.addContent("]");
}
}
if (AuthorizeManager.authorizeActionBoolean(context, item, Constants.ADD))
{
Cell cell = files.addRow().addCell(1, 5);
cell.addXref(contextPath+"/admin/item?administrative-continue="+knot.getId()+"&submit_add",T_submit_add);
}
else
{
Cell cell = files.addRow().addCell(1, 5);
cell.addHighlight("fade").addContent(T_no_upload);
}
// PARA: actions
Para actions = main.addPara("editItemActionsP","editItemActionsP" );
// Only System Administrators can delete bitstreams
if (AuthorizeManager.authorizeActionBoolean(context, item, Constants.REMOVE))
{
actions.addButton("submit_delete").setValue(T_submit_delete);
}
else
{
Button button = actions.addButton("submit_delete");
button.setValue(T_submit_delete);
button.setDisabled();
main.addPara().addHighlight("fade").addContent(T_no_remove);
}
actions.addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-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.administrative.item;
import java.util.ArrayList;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Text;
import org.xml.sax.SAXException;
/**
* Query the user for an item's identifier.
*
* @author Jay Paz
*/
public class FindItemForm extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_title = message("xmlui.administrative.item.FindItemForm.title");
private static final Message T_head1 = message("xmlui.administrative.item.FindItemForm.head1");
private static final Message T_identifier_label = message("xmlui.administrative.item.FindItemForm.identifier_label");
private static final Message T_identifier_error = message("xmlui.administrative.item.FindItemForm.identifier_error");
private static final Message T_find = message("xmlui.administrative.item.FindItemForm.find");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_item_trail);
pageMeta.addMetadata("title").addContent(T_title);
}
public void addBody(Body body) throws SAXException, WingException
{
// Get our parameters and state;
String identifier = parameters.getParameter("identifier",null);
String errorString = parameters.getParameter("errors",null);
ArrayList<String> errors = new ArrayList<String>();
if (errorString != null)
{
for (String error : errorString.split(","))
{
errors.add(error);
}
}
// DIVISION: find-item
Division findItem = body.addInteractiveDivision("find-item",contextPath + "/admin/item", Division.METHOD_GET,"primary administrative item");
findItem.setHead(T_head1);
List form = findItem.addList("find-item-form", List.TYPE_FORM);
Text id = form.addItem().addText("identifier");
id.setLabel(T_identifier_label);
if (identifier != null)
{
id.setValue(identifier);
}
if (errors.contains("identifier"))
{
id.addError(T_identifier_error);
}
form.addItem().addButton("submit_find").setValue(T_find);
findItem.addHidden("administrative-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.administrative.item;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Comparator;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
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.Cell;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Params;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.xmlui.wing.element.TextArea;
import org.dspace.app.xmlui.wing.element.Value;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.MetadataField;
import org.dspace.content.MetadataSchema;
import org.dspace.content.authority.MetadataAuthorityManager;
import org.dspace.content.authority.ChoiceAuthorityManager;
import org.dspace.content.authority.Choices;
/**
* Display a list of all metadata available for this item and allow the user to
* add, remove, or update it.
*
* @author Jay Paz
* @author Scott Phillips
*/
public class EditItemMetadataForm extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_submit_update = message("xmlui.general.update");
private static final Message T_submit_return = message("xmlui.general.return");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_template_head = message("xmlui.administrative.item.general.template_head");
private static final Message T_option_head = message("xmlui.administrative.item.general.option_head");
private static final Message T_option_status = message("xmlui.administrative.item.general.option_status");
private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams");
private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata");
private static final Message T_option_view = message("xmlui.administrative.item.general.option_view");
private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate");
private static final Message T_title = message("xmlui.administrative.item.EditItemMetadataForm.title");
private static final Message T_trail = message("xmlui.administrative.item.EditItemMetadataForm.trail");
private static final Message T_head1 = message("xmlui.administrative.item.EditItemMetadataForm.head1");
private static final Message T_name_label = message("xmlui.administrative.item.EditItemMetadataForm.name_label");
private static final Message T_value_label = message("xmlui.administrative.item.EditItemMetadataForm.value_label");
private static final Message T_lang_label = message("xmlui.administrative.item.EditItemMetadataForm.lang_label");
private static final Message T_submit_add = message("xmlui.administrative.item.EditItemMetadataForm.submit_add");
private static final Message T_para1 = message("xmlui.administrative.item.EditItemMetadataForm.para1");
private static final Message T_head2 = message("xmlui.administrative.item.EditItemMetadataForm.head2");
private static final Message T_column1 = message("xmlui.administrative.item.EditItemMetadataForm.column1");
private static final Message T_column2 = message("xmlui.administrative.item.EditItemMetadataForm.column2");
private static final Message T_column3 = message("xmlui.administrative.item.EditItemMetadataForm.column3");
private static final Message T_column4 = message("xmlui.administrative.item.EditItemMetadataForm.column4");
private static final Message T_unlock = message("xmlui.authority.confidence.unlock.help");
public void addPageMeta(PageMeta pageMeta) throws WingException, SQLException
{
Item item = Item.find(context, parameters.getParameterAsInteger("itemID",-1));
Collection owner = item.getOwningCollection();
int collectionID = (owner == null) ? -1 : owner.getID();
pageMeta.addMetadata("choice", "collection").addContent(String.valueOf(collectionID));
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Add either the simple Ajax response document or the full
* document with header and full edit item form based on the
* mode parameter. Mode parameter values are set in the Flowscipt
* and can be either 'ajax' or 'normal'.
*/
@SuppressWarnings("unchecked") // the cast is correct
public void addBody(Body body) throws SQLException, WingException
{
// Get our parameters and state
int itemID = parameters.getParameterAsInteger("itemID",-1);
Item item = Item.find(context, itemID);
DCValue[] values = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
Arrays.sort(values, new DCValueComparator());
String baseURL = contextPath+"/admin/item?administrative-continue="+knot.getId();
Request request = ObjectModelHelper.getRequest(objectModel);
String previousFieldID = request.getParameter("field");
// Metadata editing is the only type of editing available for a template item.
boolean editingTemplateItem = false;
int templateCollectionID = parameters.getParameterAsInteger("templateCollectionID",-1);
Collection templateCollection = templateCollectionID == -1 ? null : Collection.find(context, templateCollectionID);
if (templateCollection != null)
{
Item templateItem = templateCollection.getTemplateItem();
if (templateItem != null && templateItem.getID() == itemID)
{
editingTemplateItem = true;
}
}
// DIVISION: main
Division main = body.addInteractiveDivision("edit-item-status", contextPath+"/admin/item", Division.METHOD_POST,"primary administrative item");
if (editingTemplateItem)
{
main.setHead(T_template_head.parameterize(templateCollection.getName()));
}
else
{
main.setHead(T_option_head);
}
Collection owner = item.getOwningCollection();
int collectionID = (owner == null) ? -1 : owner.getID();
// LIST: options
if (!editingTemplateItem)
{
List options = main.addList("options",List.TYPE_SIMPLE,"horizontal");
options.addItem().addXref(baseURL+"&submit_status",T_option_status);
options.addItem().addXref(baseURL+"&submit_bitstreams",T_option_bitstreams);
options.addItem().addHighlight("bold").addXref(baseURL+"&submit_metadata",T_option_metadata);
options.addItem().addXref(baseURL + "&view_item", T_option_view);
options.addItem().addXref(baseURL + "&submit_curate", T_option_curate);
}
// LIST: add new metadata
List addForm = main.addList("addItemMetadata",List.TYPE_FORM);
addForm.setHead(T_head1);
Select addName = addForm.addItem().addSelect("field");
addName.setLabel(T_name_label);
MetadataField[] fields = MetadataField.findAll(context);
for (MetadataField field : fields)
{
int fieldID = field.getFieldID();
MetadataSchema schema = MetadataSchema.find(context, field.getSchemaID());
String name = schema.getName() +"."+field.getElement();
if (field.getQualifier() != null)
{
name += "." + field.getQualifier();
}
addName.addOption(fieldID, name);
}
if (previousFieldID != null)
{
addName.setOptionSelected(previousFieldID);
}
Composite addComposite = addForm.addItem().addComposite("value");
addComposite.setLabel(T_value_label);
TextArea addValue = addComposite.addTextArea("value");
Text addLang = addComposite.addText("language");
addValue.setSize(4, 35);
addLang.setLabel(T_lang_label);
addLang.setSize(6);
addForm.addItem().addButton("submit_add").setValue(T_submit_add);
// PARA: Disclaimer
main.addPara(T_para1);
Para actions = main.addPara(null,"edit-metadata-actions top" );
actions.addButton("submit_update").setValue(T_submit_update);
actions.addButton("submit_return").setValue(T_submit_return);
// TABLE: Metadata
main.addHidden("scope").setValue("*");
int index = 1;
Table table = main.addTable("editItemMetadata",1,1);
table.setHead(T_head2);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCell().addContent(T_column1);
header.addCell().addContent(T_column2);
header.addCell().addContent(T_column3);
header.addCell().addContent(T_column4);
ChoiceAuthorityManager cmgr = ChoiceAuthorityManager.getManager();
for(DCValue value : values)
{
String name = value.schema + "_" + value.element;
if (value.qualifier != null)
{
name += "_" + value.qualifier;
}
Row row = table.addRow(name,Row.ROLE_DATA,"metadata-value");
CheckBox remove = row.addCell().addCheckBox("remove_"+index);
remove.setLabel("remove");
remove.addOption(index);
Cell cell = row.addCell();
cell.addContent(name.replaceAll("_", ". "));
cell.addHidden("name_"+index).setValue(name);
// value entry cell:
Cell mdCell = row.addCell();
String fieldKey = MetadataAuthorityManager.makeFieldKey(value.schema, value.element, value.qualifier);
// put up just a selector when preferred choice presentation is select:
if (cmgr.isChoicesConfigured(fieldKey) &&
Params.PRESENTATION_SELECT.equals(cmgr.getPresentation(fieldKey)))
{
Select mdSelect = mdCell.addSelect("value_"+index);
mdSelect.setSize(1);
Choices cs = cmgr.getMatches(fieldKey, value.value, collectionID, 0, 0, null);
if (cs.defaultSelected < 0)
{
mdSelect.addOption(true, value.value, value.value);
}
for (int i = 0; i < cs.values.length; ++i)
{
mdSelect.addOption(i == cs.defaultSelected, cs.values[i].value, cs.values[i].label);
}
}
else
{
TextArea mdValue = mdCell.addTextArea("value_"+index);
mdValue.setSize(4,35);
mdValue.setValue(value.value);
boolean isAuth = MetadataAuthorityManager.getManager().isAuthorityControlled(fieldKey);
if (isAuth)
{
mdValue.setAuthorityControlled();
mdValue.setAuthorityRequired(MetadataAuthorityManager.getManager().isAuthorityRequired(fieldKey));
Value authValue = mdValue.setAuthorityValue((value.authority == null)?"":value.authority, Choices.getConfidenceText(value.confidence));
// add the "unlock" button to auth field
Button unlock = authValue.addButton("authority_unlock_"+index,"ds-authority-lock");
unlock.setHelp(T_unlock);
}
if (ChoiceAuthorityManager.getManager().isChoicesConfigured(fieldKey))
{
mdValue.setChoices(fieldKey);
mdValue.setChoicesPresentation(Params.PRESENTATION_LOOKUP);
mdValue.setChoicesClosed(ChoiceAuthorityManager.getManager().isClosed(fieldKey));
}
}
Text mdLang = row.addCell().addText("language_"+index);
mdLang.setSize(6);
mdLang.setValue(value.language);
// Tick the index counter;
index++;
}
// PARA: actions
actions = main.addPara(null,"edit-metadata-actions bottom" );
actions.addButton("submit_update").setValue(T_submit_update);
actions.addButton("submit_return").setValue(T_submit_return);
main.addHidden("administrative-continue").setValue(knot.getId());
}
/**
* Compare two metadata element's name so that they may be sorted.
*/
static class DCValueComparator implements Comparator, Serializable {
public int compare(Object arg0, Object arg1) {
final DCValue o1 = (DCValue)arg0;
final DCValue o2 = (DCValue)arg1;
final String s1 = o1.schema + o1.element + (o1.qualifier==null?"":("." + o1.qualifier));
final String s2 = o2.schema + o2.element + (o2.qualifier==null?"":("." + o2.qualifier));
return s1.compareTo(s2);
}
}
}
| 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.administrative.item;
import java.sql.SQLException;
import java.util.ArrayList;
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.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
/**
* Present the user with a list of not-yet-but-soon-to-be-deleted-bitstreams.
*
* @author Scott Phillips
*/
public class DeleteBitstreamsConfirm extends AbstractDSpaceTransformer
{
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_title = message("xmlui.administrative.item.DeleteBitstreamConfirm.title");
private static final Message T_trail = message("xmlui.administrative.item.DeleteBitstreamConfirm.trail");
private static final Message T_head1 = message("xmlui.administrative.item.DeleteBitstreamConfirm.head1");
private static final Message T_para1 = message("xmlui.administrative.item.DeleteBitstreamConfirm.para1");
private static final Message T_column1 = message("xmlui.administrative.item.DeleteBitstreamConfirm.column1");
private static final Message T_column2 = message("xmlui.administrative.item.DeleteBitstreamConfirm.column2");
private static final Message T_column3 = message("xmlui.administrative.item.DeleteBitstreamConfirm.column3");
private static final Message T_submit_delete = message("xmlui.general.delete");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
// Get all our parameters
String idsString = parameters.getParameter("bitstreamIDs", null);
ArrayList<Bitstream> bitstreams = new ArrayList<Bitstream>();
for (String id : idsString.split(","))
{
String[] parts = id.split("/");
if (parts.length != 2)
{
throw new UIException("Unable to parse id into bundle and bitstream id: " + id);
}
int bitstreamID = Integer.valueOf(parts[1]);
Bitstream bitstream = Bitstream.find(context,bitstreamID);
bitstreams.add(bitstream);
}
// DIVISION: bitstream-confirm-delete
Division deleted = body.addInteractiveDivision("bitstreams-confirm-delete",contextPath+"/admin/item",Division.METHOD_POST,"primary administrative item");
deleted.setHead(T_head1);
deleted.addPara(T_para1);
Table table = deleted.addTable("bitstreams-confirm-delete",bitstreams.size() + 1, 1);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_column1);
header.addCellContent(T_column2);
header.addCellContent(T_column3);
for (Bitstream bitstream : bitstreams)
{
String format = null;
BitstreamFormat bitstreamFormat = bitstream.getFormat();
if (bitstreamFormat != null)
{
format = bitstreamFormat.getShortDescription();
}
Row row = table.addRow();
row.addCell().addContent(bitstream.getName());
row.addCell().addContent(bitstream.getDescription());
row.addCell().addContent(format);
}
Para buttons = deleted.addPara();
buttons.addButton("submit_confirm").setValue(T_submit_delete);
buttons.addButton("submit_cancel").setValue(T_submit_cancel);
deleted.addHidden("administrative-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.administrative.item;
import java.sql.SQLException;
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.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
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.content.Collection;
import org.dspace.content.Item;
import org.dspace.core.Constants;
/**
* This page displays collections to which the user can move an item.
*
* @author Nicholas Riley
*/
public class MoveItemForm extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
private static final Message T_title = message("xmlui.administrative.item.MoveItemForm.title");
private static final Message T_trail = message("xmlui.administrative.item.MoveItemForm.trail");
private static final Message T_head1 = message("xmlui.administrative.item.MoveItemForm.head1");
private static final Message T_collection = message("xmlui.administrative.item.MoveItemForm.collection");
private static final Message T_collection_help = message("xmlui.administrative.item.MoveItemForm.collection_help");
private static final Message T_collection_default = message("xmlui.administrative.item.MoveItemForm.collection_default");
private static final Message T_submit_move = message("xmlui.administrative.item.MoveItemForm.submit_move");
private static final Message T_submit_inherit = message("xmlui.administrative.item.MoveItemForm.inherit_policies");
private static final Message T_submit_inherit_help = message("xmlui.administrative.item.MoveItemForm.inherit_policies_help");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrailLink(contextPath+"/admin/item", T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException
{
// Get our parameters and state
int itemID = parameters.getParameterAsInteger("itemID",-1);
Item item = Item.find(context, itemID);
// DIVISION: Main
Division main = body.addInteractiveDivision("move-item", contextPath+"/admin/item", Division.METHOD_POST, "primary administrative item");
main.setHead(T_head1.parameterize(item.getHandle()));
Collection[] collections = Collection.findAuthorized(context, null, Constants.ADD);
List list = main.addList("select-collection", List.TYPE_FORM);
Select select = list.addItem().addSelect("collectionID");
select.setLabel(T_collection);
select.setHelp(T_collection_help);
Collection owningCollection = item.getOwningCollection();
if (owningCollection == null) {
select.addOption("",T_collection_default);
}
for (Collection collection : collections)
{
String name = collection.getMetadata("name");
if (name.length() > 50)
{
name = name.substring(0, 47) + "...";
}
// Only add the item if it isn't already the owner
if (!item.isOwningCollection(collection))
{
select.addOption(collection.equals(owningCollection), collection.getID(), name);
}
}
org.dspace.app.xmlui.wing.element.Item actions = list.addItem();
CheckBox inheritPolicies = actions.addCheckBox("inheritPolicies");
inheritPolicies.setLabel(T_submit_inherit);
inheritPolicies.setHelp(T_submit_inherit_help);
inheritPolicies.addOption("inheritPolicies");
actions.addButton("submit_move").setValue(T_submit_move);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
main.addHidden("administrative-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.statistics;
import org.apache.cocoon.matching.Matcher;
import org.apache.cocoon.sitemap.PatternException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.dspace.core.Context;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.content.DSpaceObject;
import org.dspace.authorize.AuthorizeManager;
import java.util.Map;
import java.util.HashMap;
import java.sql.SQLException;
/**
* User: @author kevinvandevelde (kevin at atmire.com)
* Date: 19-nov-2009
* Time: 17:19:56
*/
public class StatisticsAuthorizedMatcher extends AbstractLogEnabled implements Matcher{
public Map match(String pattern, Map objectModel, Parameters parameters) throws PatternException {
// Are we checking for *NOT* the action or the action.
boolean not = false;
int action = Constants.READ; // the action to check
if (pattern.startsWith("!"))
{
not = true;
pattern = pattern.substring(1);
}
if(!pattern.equals("READ"))
{
getLogger().warn("Invalid action: '"+pattern+"'");
return null;
}
try
{
Context context = ContextUtil.obtainContext(objectModel);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
//We have always got rights to view stats on the home page (admin rights will be checked later)
boolean authorized = dso == null || AuthorizeManager.authorizeActionBoolean(context, dso, action, false);
//If we are authorized check for any other authorization actions present
if(authorized && ConfigurationManager.getBooleanProperty("statistics.item.authorization.admin"))
{
//If we have no user, we cannot be admin
if(context.getCurrentUser() == null)
{
authorized = false;
}
if(authorized){
//Check for admin
authorized = AuthorizeManager.isAdmin(context);
if(!authorized)
{
//Check if we have authorization for the owning colls, comms, ...
authorized = AuthorizeManager.isAdmin(context, dso);
}
}
}
// XOR
if (not ^ authorized)
{
return new HashMap();
}
else
{
return null;
}
}
catch (SQLException sqle)
{
throw new PatternException("Unable to obtain DSpace Context", sqle);
}
}
}
| 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.statistics;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrServerException;
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.Message;
import org.dspace.app.xmlui.wing.element.*;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Constants;
import org.dspace.statistics.Dataset;
import org.dspace.statistics.content.*;
import org.xml.sax.SAXException;
public class StatisticsTransformer extends AbstractDSpaceTransformer {
private static Logger log = Logger.getLogger(StatisticsTransformer.class);
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_head_title = message("xmlui.statistics.title");
private static final Message T_statistics_trail = message("xmlui.statistics.trail");
private static final String T_head_visits_total = "xmlui.statistics.visits.total";
private static final String T_head_visits_month = "xmlui.statistics.visits.month";
private static final String T_head_visits_views = "xmlui.statistics.visits.views";
private static final String T_head_visits_countries = "xmlui.statistics.visits.countries";
private static final String T_head_visits_cities = "xmlui.statistics.visits.cities";
private static final String T_head_visits_bitstream = "xmlui.statistics.visits.bitstreams";
/**
* Add a page title and trail links
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException {
//Try to find our dspace object
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
if(dso != null)
{
HandleUtil.buildHandleTrail(dso, pageMeta, contextPath);
}
pageMeta.addTrailLink(contextPath + "/handle" + (dso != null && dso.getHandle() != null ? "/" + dso.getHandle() : "/statistics"), T_statistics_trail);
// Add the page title
pageMeta.addMetadata("title").addContent(T_head_title);
}
/**
* What to add at the end of the body
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException {
//Try to find our dspace object
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
try
{
if(dso != null)
{
renderViewer(body, dso);
}
else
{
renderHome(body);
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public void renderHome(Body body) throws WingException {
Division home = body.addDivision("home", "primary repository");
Division division = home.addDivision("stats", "secondary stats");
division.setHead(T_head_title);
/*
try {
StatisticsTable statisticsTable = new StatisticsTable(
new StatisticsDataVisits());
statisticsTable.setTitle(T_head_visits_month);
statisticsTable.setId("tab1");
DatasetTimeGenerator timeAxis = new DatasetTimeGenerator();
timeAxis.setDateInterval("month", "-6", "+1");
statisticsTable.addDatasetGenerator(timeAxis);
addDisplayTable(division, statisticsTable);
} catch (Exception e) {
log.error("Error occurred while creating statistics for home page",
e);
}
*/
try {
/** List of the top 10 items for the entire repository **/
StatisticsListing statListing = new StatisticsListing(
new StatisticsDataVisits());
statListing.setTitle(T_head_visits_total);
statListing.setId("list1");
//Adding a new generator for our top 10 items without a name length delimiter
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(Constants.ITEM, 10, false, -1);
statListing.addDatasetGenerator(dsoAxis);
//Render the list as a table
addDisplayListing(division, statListing);
} catch (Exception e) {
log.error("Error occurred while creating statistics for home page", e);
}
}
public void renderViewer(Body body, DSpaceObject dso) throws WingException {
Division home = body.addDivision(
Constants.typeText[dso.getType()].toLowerCase() + "-home",
"primary repository " + Constants.typeText[dso.getType()].toLowerCase());
// Build the collection viewer division.
Division division = home.addDivision("stats", "secondary stats");
division.setHead(T_head_title);
try {
StatisticsListing statListing = new StatisticsListing(
new StatisticsDataVisits(dso));
statListing.setTitle(T_head_visits_total);
statListing.setId("list1");
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
statListing.addDatasetGenerator(dsoAxis);
addDisplayListing(division, statListing);
} catch (Exception e) {
log.error(
"Error occurred while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
try {
StatisticsTable statisticsTable = new StatisticsTable(new StatisticsDataVisits(dso));
statisticsTable.setTitle(T_head_visits_month);
statisticsTable.setId("tab1");
DatasetTimeGenerator timeAxis = new DatasetTimeGenerator();
timeAxis.setDateInterval("month", "-6", "+1");
statisticsTable.addDatasetGenerator(timeAxis);
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
statisticsTable.addDatasetGenerator(dsoAxis);
addDisplayTable(division, statisticsTable);
} catch (Exception e) {
log.error(
"Error occurred while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
if(dso instanceof org.dspace.content.Item){
//Make sure our item has at least one bitstream
org.dspace.content.Item item = (org.dspace.content.Item) dso;
try {
if(item.hasUploadedFiles()){
StatisticsListing statsList = new StatisticsListing(new StatisticsDataVisits(dso));
statsList.setTitle(T_head_visits_bitstream);
statsList.setId("list-bit");
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(Constants.BITSTREAM, 10, false, -1);
statsList.addDatasetGenerator(dsoAxis);
addDisplayListing(division, statsList);
}
} catch (Exception e) {
log.error(
"Error occurred while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
}
try {
StatisticsListing statListing = new StatisticsListing(
new StatisticsDataVisits(dso));
statListing.setTitle(T_head_visits_countries);
statListing.setId("list2");
// DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
// dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
DatasetTypeGenerator typeAxis = new DatasetTypeGenerator();
typeAxis.setType("countryCode");
typeAxis.setMax(10);
statListing.addDatasetGenerator(typeAxis);
addDisplayListing(division, statListing);
} catch (Exception e) {
log.error(
"Error occurred while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
try {
StatisticsListing statListing = new StatisticsListing(
new StatisticsDataVisits(dso));
statListing.setTitle(T_head_visits_cities);
statListing.setId("list3");
// DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
// dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
DatasetTypeGenerator typeAxis = new DatasetTypeGenerator();
typeAxis.setType("city");
typeAxis.setMax(10);
statListing.addDatasetGenerator(typeAxis);
addDisplayListing(division, statListing);
} catch (Exception e) {
log.error(
"Error occurred while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
}
/**
* Adds a table layout to the page
*
* @param mainDiv
* the div to add the table to
* @param display
* @throws SAXException
* @throws WingException
* @throws ParseException
* @throws IOException
* @throws SolrServerException
* @throws SQLException
*/
private void addDisplayTable(Division mainDiv, StatisticsTable display)
throws SAXException, WingException, SQLException,
SolrServerException, IOException, ParseException {
String title = display.getTitle();
Dataset dataset = display.getDataset();
if (dataset == null) {
/** activate dataset query */
dataset = display.getDataset(context);
}
if (dataset != null) {
String[][] matrix = dataset.getMatrixFormatted();
/** Generate Table */
Division wrapper = mainDiv.addDivision("tablewrapper");
Table table = wrapper.addTable("list-table", 1, 1,
title == null ? "" : "tableWithTitle");
if (title != null)
{
table.setHead(message(title));
}
/** Generate Header Row */
Row headerRow = table.addRow();
headerRow.addCell("spacer", Cell.ROLE_DATA, "labelcell");
String[] cLabels = dataset.getColLabels().toArray(new String[0]);
for (int row = 0; row < cLabels.length; row++) {
Cell cell = headerRow.addCell(0 + "-" + row + "-h",
Cell.ROLE_DATA, "labelcell");
cell.addContent(cLabels[row]);
}
/** Generate Table Body */
for (int row = 0; row < matrix.length; row++) {
Row valListRow = table.addRow();
/** Add Row Title */
valListRow.addCell("" + row, Cell.ROLE_DATA, "labelcell")
.addContent(dataset.getRowLabels().get(row));
/** Add Rest of Row */
for (int col = 0; col < matrix[row].length; col++) {
Cell cell = valListRow.addCell(row + "-" + col,
Cell.ROLE_DATA, "datacell");
cell.addContent(matrix[row][col]);
}
}
}
}
private void addDisplayListing(Division mainDiv, StatisticsListing display)
throws SAXException, WingException, SQLException,
SolrServerException, IOException, ParseException {
String title = display.getTitle();
Dataset dataset = display.getDataset();
if (dataset == null) {
/** activate dataset query */
dataset = display.getDataset(context);
}
if (dataset != null) {
String[][] matrix = dataset.getMatrixFormatted();
// String[] rLabels = dataset.getRowLabels().toArray(new String[0]);
Table table = mainDiv.addTable("list-table", matrix.length, 2,
title == null ? "" : "tableWithTitle");
if (title != null)
{
table.setHead(message(title));
}
Row headerRow = table.addRow();
headerRow.addCell("", Cell.ROLE_DATA, "labelcell");
headerRow.addCell("", Cell.ROLE_DATA, "labelcell").addContent(message(T_head_visits_views));
/** Generate Table Body */
for (int col = 0; col < matrix[0].length; col++) {
Row valListRow = table.addRow();
Cell catCell = valListRow.addCell(col + "1", Cell.ROLE_DATA,
"labelcell");
catCell.addContent(dataset.getColLabels().get(col));
Cell valCell = valListRow.addCell(col + "2", Cell.ROLE_DATA,
"datacell");
valCell.addContent(matrix[0][col]);
}
if (!"".equals(display.getCss())) {
List attrlist = mainDiv.addList("divattrs");
attrlist.addItem("style", display.getCss());
}
}
}
}
| 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.statistics;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.xml.sax.SAXException;
import java.io.Serializable;
import java.io.IOException;
import java.sql.SQLException;
/**
* Navigation Elements for viewing statistics related to Items.
*
* @author kevinvandevelde (kevin at atmire.com)
* Date: 2-nov-2009
* Time: 14:24:21
*/
public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent {
private static final Message T_statistics_head = message("xmlui.statistics.Navigation.title");
private static final Message T_statistics_view = message("xmlui.statistics.Navigation.view");
public Serializable getKey() {
//TODO: DO THIS
return null;
}
/**
* Generate the cache validity object.
*
* The cache is always valid.
*/
public SourceValidity getValidity() {
return NOPValidity.SHARED_INSTANCE;
}
/**
* Add the statistics 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");
options.addList("account");
options.addList("context");
options.addList("administrative");
List statistics = options.addList("statistics");
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if(dso != null && dso.getHandle() != null){
statistics.setHead(T_statistics_head);
statistics.addItemXref(contextPath + "/handle/" + dso.getHandle() + "/statistics", T_statistics_view);
}else{
// This Navigation is only called either on a DSO related page, or the homepage
// If on the home page: add statistics link for the home page
statistics.setHead(T_statistics_head);
statistics.addItemXref(contextPath + "/statistics-home", T_statistics_view);
}
}
}
| 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.submission.workflow;
import java.util.Map;
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.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.core.Context;
import org.dspace.workflow.WorkflowItem;
import org.dspace.workflow.WorkflowManager;
/**
* Claim all the selected workflows. This action is used by the
* submission page, when the user clicks the claim tasks button.
*
* @author Scott Phillips
*/
public class ClaimTasksAction extends AbstractAction
{
/**
* @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
{
Request request = ObjectModelHelper.getRequest(objectModel);
Context context = ContextUtil.obtainContext(objectModel);
// Or the user selected a checkbox full of workflow IDs
String[] workflowIDs = request.getParameterValues("workflowID");
if (workflowIDs != null)
{
for (String workflowID : workflowIDs)
{
WorkflowItem workflowItem = WorkflowItem.find(context, Integer.valueOf(workflowID));
int state = workflowItem.getState();
// Only unclaim tasks that are already claimed.
if ( state == WorkflowManager.WFSTATE_STEP1POOL ||
state == WorkflowManager.WFSTATE_STEP2POOL ||
state == WorkflowManager.WFSTATE_STEP3POOL)
{
WorkflowManager.claim(context, workflowItem, context.getCurrentUser());
}
}
context.commit();
}
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.submission.workflow;
import java.util.Map;
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.log4j.Logger;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.workflow.WorkflowItem;
import org.dspace.workflow.WorkflowManager;
/**
* Unclaim all the selected workflows. This action returns these
* tasks to the general pool for other users to select from.
*
*
* @author Scott Phillips
*/
public class UnclaimTasksAction extends AbstractAction
{
private static final Logger log = Logger.getLogger(UnclaimTasksAction.class);
/**
* @param redirector
* un-used.
* @param resolver
* @param objectModel
* Cocoon's object model
*/
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel,
String source, Parameters parameters) throws Exception
{
Request request = ObjectModelHelper.getRequest(objectModel);
Context context = ContextUtil.obtainContext(objectModel);
// Or the user selected a checkbox full of workflow IDs
String[] workflowIDs = request.getParameterValues("workflowID");
if (workflowIDs != null)
{
for (String workflowID : workflowIDs)
{
WorkflowItem workflowItem = WorkflowItem.find(context, Integer.valueOf(workflowID));
//workflowItem.get
int state = workflowItem.getState();
// only claim tasks that are in the pool.
if ( state == WorkflowManager.WFSTATE_STEP1 ||
state == WorkflowManager.WFSTATE_STEP2 ||
state == WorkflowManager.WFSTATE_STEP3 )
{
log.info(LogManager.getHeader(context, "unclaim_workflow", "workflow_id=" + workflowItem.getID()));
WorkflowManager.unclaim(context, workflowItem, context.getCurrentUser());
}
}
context.commit();
}
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.submission.workflow;
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.aspect.submission.AbstractStep;
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.ReferenceSet;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.workflow.WorkflowItem;
import org.dspace.workflow.WorkflowManager;
import org.xml.sax.SAXException;
/**
*
* This step displays a workfrow item to the user and and presents several
* possible actions that they may preform on the task.
*
* General the user may, accept the item, reject the item, or edit the item's
* metadata before accepting or rejecting. The user is also given the option
* of taking the task or returning it to the pool.
*
* @author Scott Phillips
*/
public class PerformTaskStep extends AbstractStep
{
/** Language Strings **/
protected static final Message T_info1=
message("xmlui.Submission.workflow.PerformTaskStep.info1");
protected static final Message T_take_help =
message("xmlui.Submission.workflow.PerformTaskStep.take_help");
protected static final Message T_take_submit =
message("xmlui.Submission.workflow.PerformTaskStep.take_submit");
protected static final Message T_leave_help =
message("xmlui.Submission.workflow.PerformTaskStep.leave_help");
protected static final Message T_leave_submit =
message("xmlui.Submission.workflow.PerformTaskStep.leave_submit");
protected static final Message T_approve_help =
message("xmlui.Submission.workflow.PerformTaskStep.approve_help");
protected static final Message T_approve_submit =
message("xmlui.Submission.workflow.PerformTaskStep.approve_submit");
protected static final Message T_commit_help =
message("xmlui.Submission.workflow.PerformTaskStep.commit_help");
protected static final Message T_commit_submit =
message("xmlui.Submission.workflow.PerformTaskStep.commit_submit");
protected static final Message T_reject_help =
message("xmlui.Submission.workflow.PerformTaskStep.reject_help");
protected static final Message T_reject_submit =
message("xmlui.Submission.workflow.PerformTaskStep.reject_submit");
protected static final Message T_edit_help =
message("xmlui.Submission.workflow.PerformTaskStep.edit_help");
protected static final Message T_edit_submit =
message("xmlui.Submission.workflow.PerformTaskStep.edit_submit");
protected static final Message T_return_help =
message("xmlui.Submission.workflow.PerformTaskStep.return_help");
protected static final Message T_return_submit =
message("xmlui.Submission.workflow.PerformTaskStep.return_submit");
protected static final Message T_cancel_submit =
message("xmlui.general.cancel");
/** Copy the workflow manager's state values so that we can refrence them easier. */
private static final int WFSTATE_STEP1POOL = WorkflowManager.WFSTATE_STEP1POOL;
private static final int WFSTATE_STEP1 = WorkflowManager.WFSTATE_STEP1;
private static final int WFSTATE_STEP2POOL = WorkflowManager.WFSTATE_STEP2POOL;
private static final int WFSTATE_STEP2 = WorkflowManager.WFSTATE_STEP2;
private static final int WFSTATE_STEP3POOL = WorkflowManager.WFSTATE_STEP3POOL;
private static final int WFSTATE_STEP3 = WorkflowManager.WFSTATE_STEP3;
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public PerformTaskStep()
{
this.requireWorkflow = true;
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Get any metadata that may be removed by unselecting one of these options.
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/workflow";
int state = ((WorkflowItem) submission).getState();
Request request = ObjectModelHelper.getRequest(objectModel);
String showfull = request.getParameter("showfull");
// if the user selected showsimple, remove showfull.
if (showfull != null && request.getParameter("showsimple") != null)
{
showfull = null;
}
// Generate a from asking the user two questions: multiple
// titles & published before.
Division div = body.addInteractiveDivision("perform-task", actionURL, Division.METHOD_POST, "primary workflow");
div.setHead(T_workflow_head);
if (showfull == null)
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_SUMMARY_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showfull").setValue(T_showfull);
}
else
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_DETAIL_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showsimple").setValue(T_showsimple);
div.addHidden("showfull").setValue("true");
}
//FIXME: set the correct table size.
Table table = div.addTable("workflow-actions", 1, 1);
table.setHead(T_info1);
// Header
Row row;
if (state == WFSTATE_STEP1POOL ||
state == WFSTATE_STEP2POOL ||
state == WFSTATE_STEP3POOL)
{
// Take task
row = table.addRow();
row.addCellContent(T_take_help);
row.addCell().addButton("submit_take_task").setValue(T_take_submit);
// Leave task
row = table.addRow();
row.addCellContent(T_leave_help);
row.addCell().addButton("submit_leave").setValue(T_leave_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2)
{
// Approve task
row = table.addRow();
row.addCellContent(T_approve_help);
row.addCell().addButton("submit_approve").setValue(T_approve_submit);
}
if (state == WFSTATE_STEP3)
{
// Commit to archive
row = table.addRow();
row.addCellContent(T_commit_help);
row.addCell().addButton("submit_approve").setValue(T_commit_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2)
{
// Reject item
row = table.addRow();
row.addCellContent(T_reject_help);
row.addCell().addButton("submit_reject").setValue(T_reject_submit);
}
if (state == WFSTATE_STEP2 ||
state == WFSTATE_STEP3 )
{
// Edit metadata
row = table.addRow();
row.addCellContent(T_edit_help);
row.addCell().addButton("submit_edit").setValue(T_edit_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2 ||
state == WFSTATE_STEP3 )
{
// Return to pool
row = table.addRow();
row.addCellContent(T_return_help);
row.addCell().addButton("submit_return").setValue(T_return_submit);
}
// Everyone can just cancel
row = table.addRow();
row.addCell(0, 2).addButton("submit_leave").setValue(T_cancel_submit);
div.addHidden("submission-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.submission.workflow;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractStep;
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.ReferenceSet;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.TextArea;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.core.LogManager;
import org.xml.sax.SAXException;
/**
* This step is used when the user has selected to
* reject the item. Here they are asked to enter
* a reason why the item should be rejected.
*
* @author Scott Phillips
*/
public class RejectTaskStep extends AbstractStep
{
private static final Logger log = Logger.getLogger(RejectTaskStep.class);
/** Language Strings **/
protected static final Message T_info1 =
message("xmlui.Submission.workflow.RejectTaskStep.info1");
protected static final Message T_reason =
message("xmlui.Submission.workflow.RejectTaskStep.reason");
protected static final Message T_reason_required =
message("xmlui.Submission.workflow.RejectTaskStep.reason_required");
protected static final Message T_submit_reject =
message("xmlui.Submission.workflow.RejectTaskStep.submit_reject");
protected static final Message T_submit_cancel =
message("xmlui.general.cancel");
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public RejectTaskStep()
{
this.requireWorkflow = true;
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/workflow";
Request request = ObjectModelHelper.getRequest(objectModel);
String showfull = request.getParameter("showfull");
// if the user selected showsimple, remove showfull.
if (showfull != null && request.getParameter("showsimple") != null)
{
showfull = null;
}
Division div = body.addInteractiveDivision("reject-task", actionURL, Division.METHOD_POST, "primary workflow");
div.setHead(T_workflow_head);
if (showfull == null)
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_SUMMARY_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showfull").setValue(T_showfull);
}
else
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_DETAIL_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showsimple").setValue(T_showsimple);
div.addHidden("showfull").setValue("true");
}
List form = div.addList("reject-workflow",List.TYPE_FORM);
form.addItem(T_info1);
TextArea reason = form.addItem().addTextArea("reason");
reason.setLabel(T_reason);
reason.setRequired();
reason.setSize(15, 50);
if (this.errorFields.contains("reason"))
{
reason.addError(T_reason_required);
}
org.dspace.app.xmlui.wing.element.Item actions = form.addItem();
actions.addButton("submit_reject").setValue(T_submit_reject);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
div.addHidden("submission-continue").setValue(knot.getId());
log.info(LogManager.getHeader(context, "get_reject_reason",
"workflow_id=" + submission.getID() + ",item_id="
+ item.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.submission;
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.element.List;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* This abstract class represents an abstract submission page.
* <P>
* This class only adds the required "addReviewSection()"
* method for a submission step. This method is used by the
* ReviewStep to generate a single review/verify screen for the user.
*
* @author Tim Donohue
*/
public abstract class AbstractSubmissionStep extends AbstractStep
{
/**
* Each submission step must define its own information to be reviewed
* during the final Review/Verify Step in the submission process.
* <P>
* The information to review should be tacked onto the passed in
* List object.
* <P>
* NOTE: To remain consistent across all Steps, you should first
* add a sub-List object (with this step's name as the heading),
* by using a call to reviewList.addList(). This sublist is
* the list you return from this method!
*
* @param reviewList
* The List to which all reviewable information should be added
* @return
* The new sub-List object created by this step, which contains
* all the reviewable information. If this step has nothing to
* review, then return null!
*/
public abstract List addReviewSection(List reviewList) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException;
}
| 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.submission;
import java.io.IOException;
import java.sql.SQLException;
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.Cell;
import org.dspace.app.xmlui.wing.element.CheckBox;
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.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.SupervisedItem;
import org.dspace.content.WorkspaceItem;
import org.dspace.core.Constants;
import org.dspace.eperson.EPerson;
import org.dspace.workflow.WorkflowItem;
import org.dspace.workflow.WorkflowManager;
import org.xml.sax.SAXException;
/**
* @author Scott Phillips
*/
public class Submissions extends AbstractDSpaceTransformer
{
/** General Language Strings */
protected static final Message T_title =
message("xmlui.Submission.Submissions.title");
protected static final Message T_dspace_home =
message("xmlui.general.dspace_home");
protected static final Message T_trail =
message("xmlui.Submission.Submissions.trail");
protected static final Message T_head =
message("xmlui.Submission.Submissions.head");
protected static final Message T_untitled =
message("xmlui.Submission.Submissions.untitled");
protected static final Message T_email =
message("xmlui.Submission.Submissions.email");
// used by the workflow section
protected static final Message T_w_head1 =
message("xmlui.Submission.Submissions.workflow_head1");
protected static final Message T_w_info1 =
message("xmlui.Submission.Submissions.workflow_info1");
protected static final Message T_w_head2 =
message("xmlui.Submission.Submissions.workflow_head2");
protected static final Message T_w_column1 =
message("xmlui.Submission.Submissions.workflow_column1");
protected static final Message T_w_column2 =
message("xmlui.Submission.Submissions.workflow_column2");
protected static final Message T_w_column3 =
message("xmlui.Submission.Submissions.workflow_column3");
protected static final Message T_w_column4 =
message("xmlui.Submission.Submissions.workflow_column4");
protected static final Message T_w_column5 =
message("xmlui.Submission.Submissions.workflow_column5");
protected static final Message T_w_submit_return =
message("xmlui.Submission.Submissions.workflow_submit_return");
protected static final Message T_w_info2 =
message("xmlui.Submission.Submissions.workflow_info2");
protected static final Message T_w_head3 =
message("xmlui.Submission.Submissions.workflow_head3");
protected static final Message T_w_submit_take =
message("xmlui.Submission.Submissions.workflow_submit_take");
protected static final Message T_w_info3 =
message("xmlui.Submission.Submissions.workflow_info3");
// used by the unfinished submissions section
protected static final Message T_s_head1 =
message("xmlui.Submission.Submissions.submit_head1");
protected static final Message T_s_info1a =
message("xmlui.Submission.Submissions.submit_info1a");
protected static final Message T_s_info1b =
message("xmlui.Submission.Submissions.submit_info1b");
protected static final Message T_s_info1c =
message("xmlui.Submission.Submissions.submit_info1c");
protected static final Message T_s_head2 =
message("xmlui.Submission.Submissions.submit_head2");
protected static final Message T_s_info2a =
message("xmlui.Submission.Submissions.submit_info2a");
protected static final Message T_s_info2b =
message("xmlui.Submission.Submissions.submit_info2b");
protected static final Message T_s_info2c =
message("xmlui.Submission.Submissions.submit_info2c");
protected static final Message T_s_column1 =
message("xmlui.Submission.Submissions.submit_column1");
protected static final Message T_s_column2 =
message("xmlui.Submission.Submissions.submit_column2");
protected static final Message T_s_column3 =
message("xmlui.Submission.Submissions.submit_column3");
protected static final Message T_s_column4 =
message("xmlui.Submission.Submissions.submit_column4");
protected static final Message T_s_head3 =
message("xmlui.Submission.Submissions.submit_head3");
protected static final Message T_s_info3 =
message("xmlui.Submission.Submissions.submit_info3");
protected static final Message T_s_head4 =
message("xmlui.Submission.Submissions.submit_head4");
protected static final Message T_s_submit_remove =
message("xmlui.Submission.Submissions.submit_submit_remove");
// Used in the in progress section
protected static final Message T_p_head1 =
message("xmlui.Submission.Submissions.progress_head1");
protected static final Message T_p_info1 =
message("xmlui.Submission.Submissions.progress_info1");
protected static final Message T_p_column1 =
message("xmlui.Submission.Submissions.progress_column1");
protected static final Message T_p_column2 =
message("xmlui.Submission.Submissions.progress_column2");
protected static final Message T_p_column3 =
message("xmlui.Submission.Submissions.progress_column3");
// The workflow status messages
protected static final Message T_status_0 =
message("xmlui.Submission.Submissions.status_0");
protected static final Message T_status_1 =
message("xmlui.Submission.Submissions.status_1");
protected static final Message T_status_2 =
message("xmlui.Submission.Submissions.status_2");
protected static final Message T_status_3 =
message("xmlui.Submission.Submissions.status_3");
protected static final Message T_status_4 =
message("xmlui.Submission.Submissions.status_4");
protected static final Message T_status_5 =
message("xmlui.Submission.Submissions.status_5");
protected static final Message T_status_6 =
message("xmlui.Submission.Submissions.status_6");
protected static final Message T_status_7 =
message("xmlui.Submission.Submissions.status_7");
protected static final Message T_status_unknown =
message("xmlui.Submission.Submissions.status_unknown");
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.addTrailLink(contextPath + "/submissions",T_trail);
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Division div = body.addInteractiveDivision("submissions", contextPath+"/submissions", Division.METHOD_POST,"primary");
div.setHead(T_head);
this.addWorkflowTasks(div);
this.addUnfinishedSubmissions(div);
this.addSubmissionsInWorkflow(div);
}
/**
* If the user has any workflow tasks, either assigned to them or in an
* available pool of tasks, then build two tables listing each of these queues.
*
* If the user dosn't have any workflows then don't do anything.
*
* @param division The division to add the two queues too.
*/
private void addWorkflowTasks(Division division) throws SQLException, WingException
{
@SuppressWarnings("unchecked") // This cast is correct
java.util.List<WorkflowItem> ownedItems = WorkflowManager.getOwnedTasks(context, context
.getCurrentUser());
@SuppressWarnings("unchecked") // This cast is correct.
java.util.List<WorkflowItem> pooledItems = WorkflowManager.getPooledTasks(context, context
.getCurrentUser());
if (!(ownedItems.size() > 0 || pooledItems.size() > 0))
// No tasks, so don't show the table.
{
return;
}
Division workflow = division.addDivision("workflow-tasks");
workflow.setHead(T_w_head1);
workflow.addPara(T_w_info1);
// Tasks you own
Table table = workflow.addTable("workflow-tasks",ownedItems.size() + 2,5);
table.setHead(T_w_head2);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_w_column1);
header.addCellContent(T_w_column2);
header.addCellContent(T_w_column3);
header.addCellContent(T_w_column4);
header.addCellContent(T_w_column5);
if (ownedItems.size() > 0)
{
for (WorkflowItem owned : ownedItems)
{
int workflowItemID = owned.getID();
String collectionUrl = contextPath + "/handle/" + owned.getCollection().getHandle();
String ownedWorkflowItemUrl = contextPath + "/handle/" + owned.getCollection().getHandle() + "/workflow?workflowID=" + workflowItemID;
DCValue[] titles = owned.getItem().getDC("title", null, Item.ANY);
String collectionName = owned.getCollection().getMetadata("name");
EPerson submitter = owned.getSubmitter();
String submitterName = submitter.getFullName();
String submitterEmail = submitter.getEmail();
Message state = getWorkflowStateMessage(owned);
Row row = table.addRow();
CheckBox remove = row.addCell().addCheckBox("workflowID");
remove.setLabel("selected");
remove.addOption(workflowItemID);
// The task description
row.addCell().addXref(ownedWorkflowItemUrl, state);
// The item description
if (titles != null && titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
{
displayTitle = displayTitle.substring(0, 50) + " ...";
}
row.addCell().addXref(ownedWorkflowItemUrl, displayTitle);
}
else
{
row.addCell().addXref(ownedWorkflowItemUrl, T_untitled);
}
// Submitted too
row.addCell().addXref(collectionUrl, collectionName);
// Submitted by
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
Row row = table.addRow();
row.addCell(0,5).addButton("submit_return_tasks").setValue(T_w_submit_return);
}
else
{
Row row = table.addRow();
row.addCell(0,5).addHighlight("italic").addContent(T_w_info2);
}
// Tasks in the pool
table = workflow.addTable("workflow-tasks",pooledItems.size()+2,5);
table.setHead(T_w_head3);
header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_w_column1);
header.addCellContent(T_w_column2);
header.addCellContent(T_w_column3);
header.addCellContent(T_w_column4);
header.addCellContent(T_w_column5);
if (pooledItems.size() > 0)
{
for (WorkflowItem pooled : pooledItems)
{
int workflowItemID = pooled.getID();
String collectionUrl = contextPath + "/handle/" + pooled.getCollection().getHandle();
String pooledItemUrl = contextPath + "/handle/" + pooled.getCollection().getHandle() + "/workflow?workflowID=" + workflowItemID;
DCValue[] titles = pooled.getItem().getDC("title", null, Item.ANY);
String collectionName = pooled.getCollection().getMetadata("name");
EPerson submitter = pooled.getSubmitter();
String submitterName = submitter.getFullName();
String submitterEmail = submitter.getEmail();
Message state = getWorkflowStateMessage(pooled);
Row row = table.addRow();
CheckBox remove = row.addCell().addCheckBox("workflowID");
remove.setLabel("selected");
remove.addOption(workflowItemID);
// The task description
row.addCell().addXref(pooledItemUrl, state);
// The item description
if (titles != null && titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
{
displayTitle = displayTitle.substring(0, 50) + " ...";
}
row.addCell().addXref(pooledItemUrl, displayTitle);
}
else
{
row.addCell().addXref(pooledItemUrl, T_untitled);
}
// Submitted too
row.addCell().addXref(collectionUrl, collectionName);
// Submitted by
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
Row row = table.addRow();
row.addCell(0,5).addButton("submit_take_tasks").setValue(T_w_submit_take);
}
else
{
Row row = table.addRow();
row.addCell(0,5).addHighlight("italic").addContent(T_w_info3);
}
}
/**
* There are two options, the user has some unfinished submissions
* or the user does not.
*
* If the user does not, then we just display a simple paragraph
* explaining that the user may submit new items to dspace.
*
* If the user does have unfinisshed submissions then a table is
* presented listing all the unfinished submissions that this user has.
*
*/
private void addUnfinishedSubmissions(Division division) throws SQLException, WingException
{
// User's WorkflowItems
WorkspaceItem[] unfinishedItems = WorkspaceItem.findByEPerson(context,context.getCurrentUser());
SupervisedItem[] supervisedItems = SupervisedItem.findbyEPerson(context, context.getCurrentUser());
if (unfinishedItems.length <= 0 && supervisedItems.length <= 0)
{
Collection[] collections = Collection.findAuthorized(context, null, Constants.ADD);
if (collections.length > 0)
{
Division start = division.addDivision("start-submision");
start.setHead(T_s_head1);
Para p = start.addPara();
p.addContent(T_s_info1a);
p.addXref(contextPath+"/submit",T_s_info1b);
p.addContent(T_s_info1c);
return;
}
}
Division unfinished = division.addInteractiveDivision("unfinished-submisions", contextPath+"/submit", Division.METHOD_POST);
unfinished.setHead(T_s_head2);
Para p = unfinished.addPara();
p.addContent(T_s_info2a);
p.addHighlight("bold").addXref(contextPath+"/submit",T_s_info2b);
p.addContent(T_s_info2c);
// Calculate the number of rows.
// Each list pluss the top header and bottom row for the button.
int rows = unfinishedItems.length + supervisedItems.length + 2;
if (supervisedItems.length > 0 && unfinishedItems.length > 0)
{
rows++; // Authoring heading row
}
if (supervisedItems.length > 0)
{
rows++; // Supervising heading row
}
Table table = unfinished.addTable("unfinished-submissions",rows,5);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_s_column1);
header.addCellContent(T_s_column2);
header.addCellContent(T_s_column3);
header.addCellContent(T_s_column4);
if (supervisedItems.length > 0 && unfinishedItems.length > 0)
{
header = table.addRow();
header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head3);
}
if (unfinishedItems.length > 0)
{
for (WorkspaceItem workspaceItem : unfinishedItems)
{
DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY);
EPerson submitterEPerson = workspaceItem.getItem().getSubmitter();
int workspaceItemID = workspaceItem.getID();
String collectionUrl = contextPath + "/handle/" + workspaceItem.getCollection().getHandle();
String workspaceItemUrl = contextPath + "/submit?workspaceID=" + workspaceItemID;
String submitterName = submitterEPerson.getFullName();
String submitterEmail = submitterEPerson.getEmail();
String collectionName = workspaceItem.getCollection().getMetadata("name");
Row row = table.addRow(Row.ROLE_DATA);
CheckBox remove = row.addCell().addCheckBox("workspaceID");
remove.setLabel("remove");
remove.addOption(workspaceItemID);
if (titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
{
displayTitle = displayTitle.substring(0, 50) + " ...";
}
row.addCell().addXref(workspaceItemUrl, displayTitle);
}
else
{
row.addCell().addXref(workspaceItemUrl, T_untitled);
}
row.addCell().addXref(collectionUrl, collectionName);
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
}
else
{
header = table.addRow();
header.addCell(0,5).addHighlight("italic").addContent(T_s_info3);
}
if (supervisedItems.length > 0)
{
header = table.addRow();
header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head4);
}
for (WorkspaceItem workspaceItem : supervisedItems)
{
DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY);
EPerson submitterEPerson = workspaceItem.getItem().getSubmitter();
int workspaceItemID = workspaceItem.getID();
String url = contextPath+"/submit?workspaceID="+workspaceItemID;
String submitterName = submitterEPerson.getFullName();
String submitterEmail = submitterEPerson.getEmail();
String collectionName = workspaceItem.getCollection().getMetadata("name");
Row row = table.addRow(Row.ROLE_DATA);
CheckBox selected = row.addCell().addCheckBox("workspaceID");
selected.setLabel("select");
selected.addOption(workspaceItemID);
if (titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
{
displayTitle = displayTitle.substring(0, 50) + " ...";
}
row.addCell().addXref(url,displayTitle);
}
else
{
row.addCell().addXref(url, T_untitled);
}
row.addCell().addXref(url,collectionName);
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
header = table.addRow();
Cell lastCell = header.addCell(0,5);
if (unfinishedItems.length > 0 || supervisedItems.length > 0)
{
lastCell.addButton("submit_submissions_remove").setValue(T_s_submit_remove);
}
}
/**
* This section lists all the submissions that this user has submitted which are currently under review.
*
* If the user has none, this nothing is displayed.
*/
private void addSubmissionsInWorkflow(Division division) throws SQLException, WingException
{
WorkflowItem[] inprogressItems = WorkflowItem.findByEPerson(context,context.getCurrentUser());
// If there is nothing in progress then don't add anything.
if (!(inprogressItems.length > 0))
{
return;
}
Division inprogress = division.addDivision("submissions-inprogress");
inprogress.setHead(T_p_head1);
inprogress.addPara(T_p_info1);
Table table = inprogress.addTable("submissions-inprogress",inprogressItems.length+1,3);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_p_column1);
header.addCellContent(T_p_column2);
header.addCellContent(T_p_column3);
for (WorkflowItem workflowItem : inprogressItems)
{
DCValue[] titles = workflowItem.getItem().getDC("title", null, Item.ANY);
String collectionName = workflowItem.getCollection().getMetadata("name");
Message state = getWorkflowStateMessage(workflowItem);
Row row = table.addRow();
// Add the title column
if (titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
{
displayTitle = displayTitle.substring(0, 50) + " ...";
}
row.addCellContent(displayTitle);
}
else
{
row.addCellContent(T_untitled);
}
// Collection name column
row.addCellContent(collectionName);
// Status column
row.addCellContent(state);
}
}
/**
* Determine the correct message that describes this workflow item's state.
*
* FIXME: change to return type of message;
*/
private Message getWorkflowStateMessage(WorkflowItem workflowItem)
{
switch (workflowItem.getState())
{
case WorkflowManager.WFSTATE_SUBMIT:
return T_status_0;
case WorkflowManager.WFSTATE_STEP1POOL:
return T_status_1;
case WorkflowManager.WFSTATE_STEP1:
return T_status_2;
case WorkflowManager.WFSTATE_STEP2POOL:
return T_status_3;
case WorkflowManager.WFSTATE_STEP2:
return T_status_4;
case WorkflowManager.WFSTATE_STEP3POOL:
return T_status_5;
case WorkflowManager.WFSTATE_STEP3:
return T_status_6;
case WorkflowManager.WFSTATE_ARCHIVE:
return T_status_7;
default:
return T_status_unknown;
}
}
}
| 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.submission.submit;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
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.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractSubmissionStep;
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.Cell;
import org.dspace.app.xmlui.wing.element.Radio;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.File;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.util.Util;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.workflow.WorkflowItem;
import org.xml.sax.SAXException;
/**
* This is a step of the item submission processes. The upload
* stages allows the user to upload files into the submission. The
* form is optimized for one file, but allows the user to upload
* more if needed.
* <P>
* The form is brokenup into three sections:
* <P>
* Part A: Ask the user to upload a file
* Part B: List previously uploaded files
* Part C: The standard action bar
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public class UploadStep extends AbstractSubmissionStep
{
/** Language Strings for Uploading **/
protected static final Message T_head =
message("xmlui.Submission.submit.UploadStep.head");
protected static final Message T_file =
message("xmlui.Submission.submit.UploadStep.file");
protected static final Message T_file_help =
message("xmlui.Submission.submit.UploadStep.file_help");
protected static final Message T_file_error =
message("xmlui.Submission.submit.UploadStep.file_error");
protected static final Message T_upload_error =
message("xmlui.Submission.submit.UploadStep.upload_error");
protected static final Message T_description =
message("xmlui.Submission.submit.UploadStep.description");
protected static final Message T_description_help =
message("xmlui.Submission.submit.UploadStep.description_help");
protected static final Message T_submit_upload =
message("xmlui.Submission.submit.UploadStep.submit_upload");
protected static final Message T_head2 =
message("xmlui.Submission.submit.UploadStep.head2");
protected static final Message T_column0 =
message("xmlui.Submission.submit.UploadStep.column0");
protected static final Message T_column1 =
message("xmlui.Submission.submit.UploadStep.column1");
protected static final Message T_column2 =
message("xmlui.Submission.submit.UploadStep.column2");
protected static final Message T_column3 =
message("xmlui.Submission.submit.UploadStep.column3");
protected static final Message T_column4 =
message("xmlui.Submission.submit.UploadStep.column4");
protected static final Message T_column5 =
message("xmlui.Submission.submit.UploadStep.column5");
protected static final Message T_column6 =
message("xmlui.Submission.submit.UploadStep.column6");
protected static final Message T_unknown_name =
message("xmlui.Submission.submit.UploadStep.unknown_name");
protected static final Message T_unknown_format =
message("xmlui.Submission.submit.UploadStep.unknown_format");
protected static final Message T_supported =
message("xmlui.Submission.submit.UploadStep.supported");
protected static final Message T_known =
message("xmlui.Submission.submit.UploadStep.known");
protected static final Message T_unsupported =
message("xmlui.Submission.submit.UploadStep.unsupported");
protected static final Message T_submit_edit =
message("xmlui.Submission.submit.UploadStep.submit_edit");
protected static final Message T_checksum =
message("xmlui.Submission.submit.UploadStep.checksum");
protected static final Message T_submit_remove =
message("xmlui.Submission.submit.UploadStep.submit_remove");
/**
* Global reference to edit file page
* (this is used when a user requests to edit a bitstream)
**/
private EditFileStep editFile = null;
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public UploadStep()
{
this.requireSubmission = true;
this.requireStep = true;
}
/**
* Check if user has requested to edit information about an
* uploaded file
*/
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters)
throws ProcessingException, SAXException, IOException
{
super.setup(resolver,objectModel,src,parameters);
//If this page for editing an uploaded file's information
//was requested, then we need to load EditFileStep instead!
if(this.errorFlag==org.dspace.submit.step.UploadStep.STATUS_EDIT_BITSTREAM)
{
this.editFile = new EditFileStep();
this.editFile.setup(resolver, objectModel, src, parameters);
}
else
{
this.editFile = null;
}
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
//If we are actually editing an uploaded file's information,
//then display that body instead!
if(this.editFile!=null)
{
editFile.addBody(body);
return;
}
// Get a list of all files in the original bundle
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue";
boolean workflow = submission instanceof WorkflowItem;
Bundle[] bundles = item.getBundles("ORIGINAL");
Bitstream[] bitstreams = new Bitstream[0];
if (bundles.length > 0)
{
bitstreams = bundles[0].getBitstreams();
}
// Part A:
// First ask the user if they would like to upload a new file (may be the first one)
Division div = body.addInteractiveDivision("submit-upload", actionURL, Division.METHOD_MULTIPART, "primary submission");
div.setHead(T_submission_head);
addSubmissionProgressList(div);
List upload = null;
if (!workflow)
{
// Only add the upload capabilities for new item submissions
upload = div.addList("submit-upload-new", List.TYPE_FORM);
upload.setHead(T_head);
File file = upload.addItem().addFile("file");
file.setLabel(T_file);
file.setHelp(T_file_help);
file.setRequired();
//if no files found error was thrown by processing class, display it!
if (this.errorFlag==org.dspace.submit.step.UploadStep.STATUS_NO_FILES_ERROR)
{
file.addError(T_file_error);
}
// if an upload error was thrown by processing class, display it!
if (this.errorFlag == org.dspace.submit.step.UploadStep.STATUS_UPLOAD_ERROR)
{
file.addError(T_upload_error);
}
Text description = upload.addItem().addText("description");
description.setLabel(T_description);
description.setHelp(T_description_help);
Button uploadSubmit = upload.addItem().addButton("submit_upload");
uploadSubmit.setValue(T_submit_upload);
}
// Part B:
// If the user has allready uploaded files provide a list for the user.
if (bitstreams.length > 0 || workflow)
{
Table summary = div.addTable("submit-upload-summary",(bitstreams.length * 2) + 2,7);
summary.setHead(T_head2);
Row header = summary.addRow(Row.ROLE_HEADER);
header.addCellContent(T_column0); // primary bitstream
header.addCellContent(T_column1); // select checkbox
header.addCellContent(T_column2); // file name
header.addCellContent(T_column3); // size
header.addCellContent(T_column4); // description
header.addCellContent(T_column5); // format
header.addCellContent(T_column6); // edit button
for (Bitstream bitstream : bitstreams)
{
int id = bitstream.getID();
String name = bitstream.getName();
String url = makeBitstreamLink(item, bitstream);
long bytes = bitstream.getSize();
String desc = bitstream.getDescription();
String algorithm = bitstream.getChecksumAlgorithm();
String checksum = bitstream.getChecksum();
Row row = summary.addRow();
// Add radio-button to select this as the primary bitstream
Radio primary = row.addCell().addRadio("primary_bitstream_id");
primary.addOption(String.valueOf(id));
// If this bitstream is already marked as the primary bitstream
// mark it as such.
if(bundles[0].getPrimaryBitstreamID() == id) {
primary.setOptionSelected(String.valueOf(id));
}
if (!workflow)
{
// Workflow users can not remove files.
CheckBox remove = row.addCell().addCheckBox("remove");
remove.setLabel("remove");
remove.addOption(id);
}
else
{
row.addCell();
}
row.addCell().addXref(url,name);
row.addCellContent(bytes + " bytes");
if (desc == null || desc.length() == 0)
{
row.addCellContent(T_unknown_name);
}
else
{
row.addCellContent(desc);
}
BitstreamFormat format = bitstream.getFormat();
if (format == null)
{
row.addCellContent(T_unknown_format);
}
else
{
int support = format.getSupportLevel();
Cell cell = row.addCell();
cell.addContent(format.getMIMEType());
cell.addContent(" ");
switch (support)
{
case 1:
cell.addContent(T_supported);
break;
case 2:
cell.addContent(T_known);
break;
case 3:
cell.addContent(T_unsupported);
break;
}
}
Button edit = row.addCell().addButton("submit_edit_"+id);
edit.setValue(T_submit_edit);
Row checksumRow = summary.addRow();
checksumRow.addCell();
Cell checksumCell = checksumRow.addCell(null, null, 0, 6, null);
checksumCell.addHighlight("bold").addContent(T_checksum);
checksumCell.addContent(" ");
checksumCell.addContent(algorithm + ":" + checksum);
}
if (!workflow)
{
// Workflow user's can not remove files.
Row actionRow = summary.addRow();
actionRow.addCell();
Button removeSeleceted = actionRow.addCell(null, null, 0, 6, null).addButton("submit_remove_selected");
removeSeleceted.setValue(T_submit_remove);
}
upload = div.addList("submit-upload-new-part2", List.TYPE_FORM);
}
// Part C:
// add standard control/paging buttons
addControlButtons(upload);
}
/**
* Each submission step must define its own information to be reviewed
* during the final Review/Verify Step in the submission process.
* <P>
* The information to review should be tacked onto the passed in
* List object.
* <P>
* NOTE: To remain consistent across all Steps, you should first
* add a sub-List object (with this step's name as the heading),
* by using a call to reviewList.addList(). This sublist is
* the list you return from this method!
*
* @param reviewList
* The List to which all reviewable information should be added
* @return
* The new sub-List object created by this step, which contains
* all the reviewable information. If this step has nothing to
* review, then return null!
*/
public List addReviewSection(List reviewList) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
// Create a new list section for this step (and set its heading)
List uploadSection = reviewList.addList("submit-review-" + this.stepAndPage, List.TYPE_FORM);
uploadSection.setHead(T_head);
//Review all uploaded files
Item item = submission.getItem();
Bundle[] bundles = item.getBundles("ORIGINAL");
Bitstream[] bitstreams = new Bitstream[0];
if (bundles.length > 0)
{
bitstreams = bundles[0].getBitstreams();
}
for (Bitstream bitstream : bitstreams)
{
BitstreamFormat bitstreamFormat = bitstream.getFormat();
String name = bitstream.getName();
String url = makeBitstreamLink(item, bitstream);
String format = bitstreamFormat.getShortDescription();
Message support = ReviewStep.T_unknown;
if (bitstreamFormat.getSupportLevel() == BitstreamFormat.KNOWN)
{
support = T_known;
}
else if (bitstreamFormat.getSupportLevel() == BitstreamFormat.SUPPORTED)
{
support = T_supported;
}
org.dspace.app.xmlui.wing.element.Item file = uploadSection.addItem();
file.addXref(url,name);
file.addContent(" - "+ format + " ");
file.addContent(support);
}
//return this new "upload" section
return uploadSection;
}
/**
* Returns canonical link to a bitstream in the item.
*
* @param item The DSpace Item that the bitstream is part of
* @param bitstream The bitstream to link to
* @returns a String link to the bistream
*/
private String makeBitstreamLink(Item item, Bitstream bitstream)
{
String name = bitstream.getName();
StringBuilder result = new StringBuilder(contextPath);
result.append("/bitstream/item/").append(String.valueOf(item.getID()));
// append name although it isn't strictly necessary
try
{
if (name != null)
{
result.append("/").append(Util.encodeBitstreamName(name, "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....
}
result.append("?sequence=").append(String.valueOf(bitstream.getSequenceID()));
return result.toString();
}
}
| 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.submission.submit;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractSubmissionStep;
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.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.LicenseUtils;
import org.dspace.license.CreativeCommons;
import org.dspace.core.LogManager;
import org.xml.sax.SAXException;
/**
* This is the last step of the item submission processes. During this
* step the user must agree to the collection's standard distribution
* license. If the user can not agree to the license they they may either
* save the submission untill a later time or remove the submission completely.
*
* This step will include the full license text inside the page using the
* HTML fragment method.
*
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public class LicenseStep extends AbstractSubmissionStep
{
private static final Logger log = Logger.getLogger(LicenseStep.class);
/** Language Strings **/
protected static final Message T_head =
message("xmlui.Submission.submit.LicenseStep.head");
protected static final Message T_info1 =
message("xmlui.Submission.submit.LicenseStep.info1");
protected static final Message T_info2 =
message("xmlui.Submission.submit.LicenseStep.info2");
protected static final Message T_info3 =
message("xmlui.Submission.submit.LicenseStep.info3");
protected static final Message T_decision_label =
message("xmlui.Submission.submit.LicenseStep.decision_label");
protected static final Message T_decision_checkbox =
message("xmlui.Submission.submit.LicenseStep.decision_checkbox");
protected static final Message T_decision_error =
message("xmlui.Submission.submit.LicenseStep.decision_error");
protected static final Message T_submit_remove =
message("xmlui.Submission.submit.LicenseStep.submit_remove");
protected static final Message T_submit_complete =
message("xmlui.Submission.submit.LicenseStep.submit_complete");
/**
* Global reference to Creative Commons license page
* (this is used when CC Licensing is enabled in dspace.cfg)
**/
private CCLicenseStep ccLicenseStep = null;
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public LicenseStep()
{
this.requireSubmission = true;
this.requireStep = true;
}
/**
* Check if this is actually the creative commons license step
*/
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters)
throws ProcessingException, SAXException, IOException
{
super.setup(resolver,objectModel,src,parameters);
//if Creative Commons licensing is enabled, and
//we are on the 1st page of Licensing,
//then this is the CC License page
if (CreativeCommons.isEnabled() && this.getPage()==1)
{
ccLicenseStep = new CCLicenseStep();
ccLicenseStep.setup(resolver, objectModel, src, parameters);
}
else
{
ccLicenseStep = null;
}
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// If Creative Commons licensing is enabled,
// and we've initialized the CC license Page
// then load the CreativeCommons page!
if (CreativeCommons.isEnabled() && ccLicenseStep!=null)
{
//add body for CC License page
ccLicenseStep.addBody(body);
return;
}
// Get the full text for the actuial licese
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue";
String licenseText = LicenseUtils.getLicenseText(context
.getCurrentLocale(), collection, submission.getItem(),
submission.getSubmitter());
Division div = body.addInteractiveDivision("submit-license",actionURL, Division.METHOD_POST,"primary submission");
div.setHead(T_submission_head);
addSubmissionProgressList(div);
Division inner = div.addDivision("submit-license-inner");
inner.setHead(T_head);
inner.addPara(T_info1);
inner.addPara(T_info2);
// Add the actual text of the license:
Division displayLicense = inner.addDivision("submit-license-standard-text","license-text");
displayLicense.addSimpleHTMLFragment(true, licenseText);
inner.addPara(T_info3);
List controls = inner.addList("submit-review", List.TYPE_FORM);
CheckBox decision = controls.addItem().addCheckBox("decision");
decision.setLabel(T_decision_label);
decision.addOption("accept",T_decision_checkbox);
// If user did not check "I accept" checkbox
if(this.errorFlag==org.dspace.submit.step.LicenseStep.STATUS_LICENSE_REJECTED)
{
log.info(LogManager.getHeader(context, "reject_license", submissionInfo.getSubmissionLogInfo()));
decision.addError(T_decision_error);
}
//add standard control/paging buttons
addControlButtons(controls);
}
/**
* Each submission step must define its own information to be reviewed
* during the final Review/Verify Step in the submission process.
* <P>
* The information to review should be tacked onto the passed in
* List object.
* <P>
* NOTE: To remain consistent across all Steps, you should first
* add a sub-List object (with this step's name as the heading),
* by using a call to reviewList.addList(). This sublist is
* the list you return from this method!
*
* @param reviewList
* The List to which all reviewable information should be added
* @return
* The new sub-List object created by this step, which contains
* all the reviewable information. If this step has nothing to
* review, then return null!
*/
public List addReviewSection(List reviewList) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
//License step doesn't require reviewing
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.submission.submit;
import java.util.Map;
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.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.content.WorkspaceItem;
import org.dspace.core.Context;
/**
* Remove all selected submissions. This action is used by the
* submission page, the user may check each unfinished submission
* and when he clicks the remove submissions button this action
* will remove them all.
*
* @author Scott Phillips
*/
public class RemoveSubmissionsAction extends AbstractAction
{
/**
* Remove all selected submissions
*
* @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);
Request request = ObjectModelHelper.getRequest(objectModel);
String[] workspaceIDs = request.getParameterValues("workspaceID");
if (workspaceIDs != null)
{
for (String workspaceID : workspaceIDs)
{
// If they selected to remove the item then delete everything.
WorkspaceItem workspaceItem = WorkspaceItem.find(context, Integer.valueOf(workspaceID));
workspaceItem.deleteAll();
}
context.commit();
}
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.submission.submit;
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.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractStep;
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.ReferenceSet;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.xml.sax.SAXException;
/**
* This step is used when the a user clicks an unfinished submission
* from the submissions page. Here we present the full item and then
* give the user the option to resume the item's submission.
* <P>
* This is not a true "step" in the submission process, it just
* kicks off editing an unfinished submission.
*
* FIXME: We should probably give the user the option to remove the
* submission as well.
*
* @author Scott Phillips
* @author Tim Donohue (small updates for Configurable Submission)
*/
public class ResumeStep extends AbstractStep
{
/** Language Strings **/
protected static final Message T_submit_resume =
message("xmlui.Submission.submit.ResumeStep.submit_resume");
protected static final Message T_submit_cancel =
message("xmlui.general.cancel");
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public ResumeStep()
{
this.requireWorkspace = true;
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Get any metadata that may be removed by unselecting one of these options.
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue";
Request request = ObjectModelHelper.getRequest(objectModel);
String showfull = request.getParameter("showfull");
// if the user selected showsimple, remove showfull.
if (showfull != null && request.getParameter("showsimple") != null)
{
showfull = null;
}
Division div = body.addInteractiveDivision("resume-submission", actionURL, Division.METHOD_POST, "primary submission");
div.setHead(T_submission_head);
if (showfull == null)
{
ReferenceSet referenceSet = div.addReferenceSet("submission",ReferenceSet.TYPE_SUMMARY_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showfull").setValue(T_showfull);
}
else
{
ReferenceSet referenceSet = div.addReferenceSet("submission",ReferenceSet.TYPE_DETAIL_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showsimple").setValue(T_showsimple);
div.addHidden("showfull").setValue("true");
}
List form = div.addList("resume-submission",List.TYPE_FORM);
org.dspace.app.xmlui.wing.element.Item actions = form.addItem();
actions.addButton("submit_resume").setValue(T_submit_resume);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
}
}
| 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.submission.submit;
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.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractSubmissionStep;
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.List;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.license.CreativeCommons;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
/**
* This is an optional page of the item submission processes. The Creative
* Commons license may be added to an item in addition to the standard distribution
* license. This step will allow the user to go off to the creative commons website
* select a license and then when returned view what license was added to the item.
* <P>
* This class is called by org.dspace.app.xmlui.submission.step.LicenseStep
* when the Creative Commons license is enabled
* <P>
* The form is divided into three major divisions: 1) A global div surrounds the
* whole page, 2) a specific interactive div displays the button that goes off to the
* creative commons website to select a license, and 3) a local division that displays
* the selected license and standard action bar.
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public class CCLicenseStep extends AbstractSubmissionStep
{
/** Language Strings **/
protected static final Message T_head =
message("xmlui.Submission.submit.CCLicenseStep.head");
protected static final Message T_info1 =
message("xmlui.Submission.submit.CCLicenseStep.info1");
protected static final Message T_submit_to_creative_commons =
message("xmlui.Submission.submit.CCLicenseStep.submit_to_creative_commons");
protected static final Message T_license =
message("xmlui.Submission.submit.CCLicenseStep.license");
protected static final Message T_submit_remove =
message("xmlui.Submission.submit.CCLicenseStep.submit_remove");
protected static final Message T_no_license =
message("xmlui.Submission.submit.CCLicenseStep.no_license");
/**
* The creative commons URL, where to send the user off to so that they can select a license.
*/
public static final String CREATIVE_COMMONS_URL = "http://creativecommons.org/license/";
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public CCLicenseStep()
{
this.requireSubmission = true;
this.requireStep = true;
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Build the url to and from creative commons
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue";
Request request = ObjectModelHelper.getRequest(objectModel);
boolean https = request.isSecure();
String server = request.getServerName();
int port = request.getServerPort();
String exitURL = (https) ? "https://" : "http://";
exitURL += server;
if (! (port == 80 || port == 443))
{
exitURL += ":" + port;
}
exitURL += actionURL + "?submission-continue="+knot.getId()+"&cc_license_url=[license_url]";
// Division 1:
// Global division
Division div = body.addDivision("submit-cclicense", "primary submission");
div.setHead(T_submission_head);
// Division 2:
//Progress bar division
Division progressDiv = div.addInteractiveDivision("submit-cclicense-progress", actionURL, Division.METHOD_POST);
addSubmissionProgressList(progressDiv);
//need 'submission-continue' in order to keep current state
progressDiv.addHidden("submission-continue").setValue(knot.getId());
// Division 3:
// Creative commons offsite division
Division offsiteDiv = div.addInteractiveDivision("submit-cclicense-offsite", CREATIVE_COMMONS_URL, Division.METHOD_POST);
offsiteDiv.setHead(T_head);
offsiteDiv.addPara(T_info1);
offsiteDiv.addHidden("submission-continue").setValue(knot.getId());
offsiteDiv.addHidden("partner").setValue("dspace");
offsiteDiv.addHidden("exit_url").setValue(exitURL);
String jurisdiction = ConfigurationManager.getProperty("webui.submit.cc-jurisdiction");
if ((jurisdiction != null) && (!"".equals(jurisdiction)))
{
offsiteDiv.addHidden("jurisdiction").setValue(jurisdiction.trim());
}
Para ccPara = offsiteDiv.addPara("creative-commons-button","creative-commons-button");
ccPara.addButton("submit_to_creative_commons").setValue(T_submit_to_creative_commons);
// Division 4:
// Local onsite division
Division onsiteDiv = div.addInteractiveDivision("submit-cclicense-offsite", actionURL, Division.METHOD_POST);
List form = onsiteDiv.addList("submit-review", List.TYPE_FORM);
form.addLabel(T_license);
if (CreativeCommons.hasLicense(context, item))
{
String url = CreativeCommons.getLicenseURL(item);
form.addItem().addXref(url,url);
form.addItem().addButton("submit_no_cc").setValue(T_submit_remove);
form.addItem().addHidden("cc_license_url").setValue(url);
}
else
{
form.addItem().addHighlight("italic").addContent(T_no_license);
}
// add standard control/paging buttons
addControlButtons(form);
}
/**
* Each submission step must define its own information to be reviewed
* during the final Review/Verify Step in the submission process.
* <P>
* The information to review should be tacked onto the passed in
* List object.
* <P>
* NOTE: To remain consistent across all Steps, you should first
* add a sub-List object (with this step's name as the heading),
* by using a call to reviewList.addList(). This sublist is
* the list you return from this method!
*
* @param reviewList
* The List to which all reviewable information should be added
* @return
* The new sub-List object created by this step, which contains
* all the reviewable information. If this step has nothing to
* review, then return null!
*/
public List addReviewSection(List reviewList) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
//nothing to review for CC License step
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.submission.submit;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractSubmissionStep;
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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Constants;
import org.dspace.handle.HandleManager;
import org.xml.sax.SAXException;
/**
* Allow the user to select a collection they wish to submit an item to,
* this step is sort-of but not officialy part of the item submission
* processes. Normaly a user will have selected a collection to submit
* too by going to the collection's page, but if that was invalid or the
* user came directly from the mydspace page then this step is given.
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public class SelectCollectionStep extends AbstractSubmissionStep
{
/** Language Strings */
protected static final Message T_head =
message("xmlui.Submission.submit.SelectCollection.head");
protected static final Message T_collection =
message("xmlui.Submission.submit.SelectCollection.collection");
protected static final Message T_collection_help =
message("xmlui.Submission.submit.SelectCollection.collection_help");
protected static final Message T_collection_default =
message("xmlui.Submission.submit.SelectCollection.collection_default");
protected static final Message T_submit_next =
message("xmlui.general.next");
public SelectCollectionStep()
{
this.requireHandle = true;
}
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException
{
pageMeta.addMetadata("title").addContent(T_submission_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_submission_trail);
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Collection[] collections; // List of possible collections.
String actionURL = contextPath + "/submit/" + knot.getId() + ".continue";
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
if (dso instanceof Community)
{
collections = Collection.findAuthorized(context, ((Community) dso), Constants.ADD);
}
else
{
collections = Collection.findAuthorized(context, null, Constants.ADD);
}
// Basic form with a drop down list of all the collections
// you can submit too.
Division div = body.addInteractiveDivision("select-collection",actionURL,Division.METHOD_POST,"primary submission");
div.setHead(T_submission_head);
List list = div.addList("select-collection", List.TYPE_FORM);
list.setHead(T_head);
Select select = list.addItem().addSelect("handle");
select.setLabel(T_collection);
select.setHelp(T_collection_help);
select.addOption("",T_collection_default);
for (Collection collection : collections)
{
String name = collection.getMetadata("name");
if (name.length() > 50)
{
name = name.substring(0, 47) + "...";
}
select.addOption(collection.getHandle(),name);
}
Button submit = list.addItem().addButton("submit");
submit.setValue(T_submit_next);
}
/**
* Each submission step must define its own information to be reviewed
* during the final Review/Verify Step in the submission process.
* <P>
* The information to review should be tacked onto the passed in
* List object.
* <P>
* NOTE: To remain consistent across all Steps, you should first
* add a sub-List object (with this step's name as the heading),
* by using a call to reviewList.addList(). This sublist is
* the list you return from this method!
*
* @param reviewList
* The List to which all reviewable information should be added
* @return
* The new sub-List object created by this step, which contains
* all the reviewable information. If this step has nothing to
* review, then return null!
*/
public List addReviewSection(List reviewList) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
//Currently, the selecting a Collection is not reviewable in DSpace,
//since it cannot be changed easily after creating the item
return null;
}
/**
* Recycle
*/
public void recycle()
{
this.handle = 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.submission.submit;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractSubmissionStep;
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.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.xml.sax.SAXException;
/**
* This is the first official step of the item submission processes. This
* step will ask the user two questions which will direct whether future
* questions will be asked of the user. Since they user may move next or
* previous or even jump around between the stages some metadata values
* may all ready be filled for selected values. i.e. if the user selected
* that there may be multiple titles and then later comes back and unchecks
* then multiple titles box. In this case these metadata entries are removed
* from the item, a note is displayed informing the user of this discrepency.
*
* Questions:
* - Multiple titles
* - Published Before
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public class InitialQuestionsStep extends AbstractSubmissionStep
{
/** Language Strings **/
protected static final Message T_head=
message("xmlui.Submission.submit.InitialQuestionsStep.head");
protected static final Message T_important_note=
message("xmlui.Submission.submit.InitialQuestionsStep.important_note");
protected static final Message T_and=
message("xmlui.Submission.submit.InitialQuestionsStep.and");
protected static final Message T_separator =
message("xmlui.Submission.submit.InitialQuestionsStep.separator");
protected static final Message T_open=
message("xmlui.Submission.submit.InitialQuestionsStep.open_set");
protected static final Message T_close=
message("xmlui.Submission.submit.InitialQuestionsStep.close_set");
protected static final Message T_multiple_titles=
message("xmlui.Submission.submit.InitialQuestionsStep.multiple_titles");
protected static final Message T_multiple_titles_help=
message("xmlui.Submission.submit.InitialQuestionsStep.multiple_titles_help");
protected static final Message T_multiple_titles_note=
message("xmlui.Submission.submit.InitialQuestionsStep.multiple_titles_note");
protected static final Message T_published_before=
message("xmlui.Submission.submit.InitialQuestionsStep.published_before");
protected static final Message T_published_before_help=
message("xmlui.Submission.submit.InitialQuestionsStep.published_before_help");
protected static final Message T_published_before_note=
message("xmlui.Submission.submit.InitialQuestionsStep.published_before_note");
protected static final Message T_date_issued=
message("xmlui.Submission.submit.InitialQuestionsStep.date_issued");
protected static final Message T_citation=
message("xmlui.Submission.submit.InitialQuestionsStep.citation");
protected static final Message T_publisher=
message("xmlui.Submission.submit.InitialQuestionsStep.publisher");
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public InitialQuestionsStep()
{
this.requireSubmission = true;
this.requireStep = true;
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Get any metadata that may be removed by unselecting one of these options.
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue";
DCValue[] titles = item.getDC("title", "alternative", Item.ANY);
DCValue[] dateIssued = item.getDC("date", "issued", Item.ANY);
DCValue[] citation = item.getDC("identifier", "citation", Item.ANY);
DCValue[] publisher = item.getDC("publisher", null, Item.ANY);
// Generate a from asking the user two questions: multiple
// titles & published before.
Division div = body.addInteractiveDivision("submit-initial-questions", actionURL, Division.METHOD_POST, "primary submission");
div.setHead(T_submission_head);
addSubmissionProgressList(div);
List form = div.addList("submit-initial-questions", List.TYPE_FORM);
form.setHead(T_head);
CheckBox multipleTitles = form.addItem().addCheckBox("multiple_titles");
multipleTitles.setLabel(T_multiple_titles);
multipleTitles.setHelp(T_multiple_titles_help);
multipleTitles.addOption("true");
if (submission.hasMultipleTitles())
{
multipleTitles.setOptionSelected("true");
}
// If any titles would be removed if the user unselected this box then
// warn the user!
if (titles.length > 0)
{
org.dspace.app.xmlui.wing.element.Item note = form.addItem();
note.addHighlight("bold").addContent(T_important_note);
note.addContent(T_multiple_titles_note);
for (int i=0; i< titles.length; i++)
{
if (i > 0)
{
note.addContent(T_separator);
}
note.addContent("\"");
note.addHighlight("bold").addContent(titles[i].value);
note.addContent("\"");
}
}
CheckBox publishedBefore = form.addItem().addCheckBox("published_before");
publishedBefore.setLabel(T_published_before);
publishedBefore.setHelp(T_published_before_help);
publishedBefore.addOption("true");
if (submission.isPublishedBefore())
{
publishedBefore.setOptionSelected("true");
}
// If any metadata would be removed if the user unselected the box then warn
// the user about what will be removed.
if (dateIssued.length > 0 || citation.length > 0 || publisher.length > 0)
{
org.dspace.app.xmlui.wing.element.Item note = form.addItem();
note.addHighlight("bold").addContent(T_important_note);
note.addContent(T_published_before_note);
// Start a convoluted processes to build an english list of values.
// Format: Date Issued (value, value, value), Citation (value, value, value), Publisher (value, value, value)
if (dateIssued.length > 0)
{
note.addHighlight("bold").addContent(T_date_issued);
note.addContent(T_open);
for (int i=0; i< dateIssued.length; i++)
{
if (i > 0)
{
note.addContent(T_separator);
}
note.addContent(dateIssued[i].value);
}
note.addContent(T_close);
}
// Conjunction
if (dateIssued.length > 0 && (citation.length > 0 || publisher.length > 0))
{
note.addContent(T_separator);
}
if (dateIssued.length > 0 && citation.length > 0 && publisher.length == 0)
{
note.addContent(T_and);
}
// Citation
if (citation.length > 0)
{
note.addHighlight("bold").addContent(T_citation);
note.addContent(T_open);
for (int i=0; i< citation.length; i++)
{
if (i > 0)
{
note.addContent(T_separator);
}
note.addContent(citation[i].value);
}
note.addContent(T_close);
}
// Conjunction
if (citation.length > 0 && publisher.length > 0)
{
note.addContent(T_separator);
}
if ((dateIssued.length > 0 || citation.length > 0) && publisher.length > 0)
{
note.addContent(T_and);
}
// Publisher
if (publisher.length > 0)
{
note.addHighlight("bold").addContent(T_publisher);
note.addContent(T_open);
for (int i=0; i< publisher.length; i++)
{
if (i > 0)
{
note.addContent(T_separator);
}
note.addContent(publisher[i].value);
}
note.addContent(T_close);
}
}
//add standard control/paging buttons
addControlButtons(form);
//Since we already warn users about the metadata pruning to happen
//if they uncheck an already checked box, then
//we can let the prune process occur immediately!
div.addHidden("prune").setValue("true");
}
/**
* Each submission step must define its own information to be reviewed
* during the final Review/Verify Step in the submission process.
* <P>
* The information to review should be tacked onto the passed in
* List object.
* <P>
* NOTE: To remain consistent across all Steps, you should first
* add a sub-List object (with this step's name as the heading),
* by using a call to reviewList.addList(). This sublist is
* the list you return from this method!
*
* @param reviewList
* The List to which all reviewable information should be added
* @return
* The new sub-List object created by this step, which contains
* all the reviewable information. If this step has nothing to
* review, then return null!
*/
public List addReviewSection(List reviewList) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
//Create a new section for this Initial Questions information
List initSection = reviewList.addList("submit-review-" + this.stepAndPage, List.TYPE_FORM);
initSection.setHead(T_head);
//add information to review
Message multipleTitles = ReviewStep.T_no;
if (submission.hasMultipleTitles())
{
multipleTitles = ReviewStep.T_yes;
}
Message publishedBefore = ReviewStep.T_no;
if (submission.isPublishedBefore())
{
publishedBefore = ReviewStep.T_yes;
}
initSection.addLabel(T_multiple_titles);
initSection.addItem(multipleTitles);
initSection.addLabel(T_published_before);
initSection.addItem(publishedBefore);
//return this new review section
return initSection;
}
}
| 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.submission.submit;
import java.io.IOException;
import java.sql.SQLException;
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.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractStep;
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.List;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Collection;
import org.dspace.content.FormatIdentifier;
import org.xml.sax.SAXException;
/**
* This is a sub step of the Upload step during item submission. This
* page allows the user to edit metadata about a bitstream (aka file)
* that has been uploaded. The user can change the format or change
* the file's description.
* <P>
* Since this page is a sub step, the normal control actions are not
* present, the user only has the option of returning back to the
* upload step.
* <P>
* NOTE: As a sub step, it is called directly from the UploadStep class.
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public class EditFileStep extends AbstractStep
{
/** Language Strings **/
protected static final Message T_head =
message("xmlui.Submission.submit.EditFileStep.head");
protected static final Message T_file =
message("xmlui.Submission.submit.EditFileStep.file");
protected static final Message T_description =
message("xmlui.Submission.submit.EditFileStep.description");
protected static final Message T_description_help =
message("xmlui.Submission.submit.EditFileStep.description_help");
protected static final Message T_info1 =
message("xmlui.Submission.submit.EditFileStep.info1");
protected static final Message T_format_detected =
message("xmlui.Submission.submit.EditFileStep.format_detected");
protected static final Message T_format_selected =
message("xmlui.Submission.submit.EditFileStep.format_selected");
protected static final Message T_format_default =
message("xmlui.Submission.submit.EditFileStep.format_default");
protected static final Message T_info2 =
message("xmlui.Submission.submit.EditFileStep.info2");
protected static final Message T_format_user =
message("xmlui.Submission.submit.EditFileStep.format_user");
protected static final Message T_format_user_help =
message("xmlui.Submission.submit.EditFileStep.format_user_help");
protected static final Message T_submit_save =
message("xmlui.general.save");
protected static final Message T_submit_cancel =
message("xmlui.general.cancel");
/** The bitstream we are editing */
private Bitstream bitstream;
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public EditFileStep()
{
this.requireSubmission = true;
this.requireStep = true;
}
/**
* Get the bitstream we are editing
*/
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters)
throws ProcessingException, SAXException, IOException
{
super.setup(resolver,objectModel,src,parameters);
//the bitstream should be stored in our Submission Info object
this.bitstream = submissionInfo.getBitstream();
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue";
// Get the bitstream and all the various formats
BitstreamFormat currentFormat = bitstream.getFormat();
BitstreamFormat guessedFormat = FormatIdentifier.guessFormat(context, bitstream);
BitstreamFormat[] bitstreamFormats = BitstreamFormat.findNonInternal(context);
int itemID = submissionInfo.getSubmissionItem().getItem().getID();
String fileUrl = contextPath + "/bitstream/item/" + itemID + "/" + bitstream.getName();
String fileName = bitstream.getName();
// Build the form that describes an item.
Division div = body.addInteractiveDivision("submit-edit-file", actionURL, Division.METHOD_POST, "primary submission");
div.setHead(T_submission_head);
addSubmissionProgressList(div);
List edit = div.addList("submit-edit-file", List.TYPE_FORM);
edit.setHead(T_head);
edit.addLabel(T_file);
edit.addItem().addXref(fileUrl, fileName);
Text description = edit.addItem().addText("description");
description.setLabel(T_description);
description.setHelp(T_description_help);
description.setValue(bitstream.getDescription());
edit.addItem(T_info1);
if (guessedFormat != null)
{
edit.addLabel(T_format_detected);
edit.addItem(guessedFormat.getShortDescription());
}
// System supported formats
Select format = edit.addItem().addSelect("format");
format.setLabel(T_format_selected);
format.addOption(-1,T_format_default);
for (BitstreamFormat bitstreamFormat : bitstreamFormats)
{
String supportLevel = "Unknown";
if (bitstreamFormat.getSupportLevel() == BitstreamFormat.KNOWN)
{
supportLevel = "known";
}
else if (bitstreamFormat.getSupportLevel() == BitstreamFormat.SUPPORTED)
{
supportLevel = "Supported";
}
String name = bitstreamFormat.getShortDescription()+" ("+supportLevel+")";
int id = bitstreamFormat.getID();
format.addOption(id,name);
}
if (currentFormat != null)
{
format.setOptionSelected(currentFormat.getID());
}
else if (guessedFormat != null)
{
format.setOptionSelected(guessedFormat.getID());
}
else
{
format.setOptionSelected(-1);
}
edit.addItem(T_info2);
// User supplied format
Text userFormat = edit.addItem().addText("format_description");
userFormat.setLabel(T_format_user);
userFormat.setHelp(T_format_user_help);
userFormat.setValue(bitstream.getUserFormatDescription());
// add ID of bitstream we're editing
div.addHidden("bitstream_id").setValue(bitstream.getID());
// Note, not standard control actions, this page just goes back to the upload step.
org.dspace.app.xmlui.wing.element.Item actions = edit.addItem();
actions.addButton("submit_save").setValue(T_submit_save);
actions.addButton("submit_edit_cancel").setValue(T_submit_cancel);
}
}
| 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.submission.submit;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Locale;
import javax.servlet.ServletException;
import org.dspace.app.util.DCInput;
import org.dspace.app.util.DCInputSet;
import org.dspace.app.util.DCInputsReader;
import org.dspace.app.util.DCInputsReaderException;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractSubmissionStep;
import org.dspace.app.xmlui.aspect.submission.FlowUtils;
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.CheckBox;
import org.dspace.app.xmlui.wing.element.Composite;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Field;
import org.dspace.app.xmlui.wing.element.Instance;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Params;
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.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCPersonName;
import org.dspace.content.DCSeriesNumber;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.authority.MetadataAuthorityManager;
import org.dspace.content.authority.ChoiceAuthorityManager;
import org.dspace.content.authority.Choice;
import org.dspace.content.authority.Choices;
import org.xml.sax.SAXException;
/**
* This is a step of the item submission processes. The describe step queries
* the user for various metadata items about the item. For the most part all the
* questions queried are completely configurable via the input-sets.xml file.
* This system allows for multiple pages to be defined so this step is different
* from all other stages in that it may represent multiple stages within the
* submission processes.
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public class DescribeStep extends AbstractSubmissionStep
{
/** Language Strings **/
protected static final Message T_head =
message("xmlui.Submission.submit.DescribeStep.head");
protected static final Message T_unknown_field=
message("xmlui.Submission.submit.DescribeStep.unknown_field");
protected static final Message T_required_field=
message("xmlui.Submission.submit.DescribeStep.required_field");
protected static final Message T_last_name_help=
message("xmlui.Submission.submit.DescribeStep.last_name_help");
protected static final Message T_first_name_help=
message("xmlui.Submission.submit.DescribeStep.first_name_help");
protected static final Message T_year=
message("xmlui.Submission.submit.DescribeStep.year");
protected static final Message T_month=
message("xmlui.Submission.submit.DescribeStep.month");
protected static final Message T_day=
message("xmlui.Submission.submit.DescribeStep.day");
protected static final Message T_series_name=
message("xmlui.Submission.submit.DescribeStep.series_name");
protected static final Message T_report_no=
message("xmlui.Submission.submit.DescribeStep.report_no");
/**
* A shared resource of the inputs reader. The 'inputs' are the
* questions we ask the user to describe an item during the
* submission process. The reader is a utility class to read
* that configuration file.
*/
private static DCInputsReader INPUTS_READER = null;
/**
* Ensure that the inputs reader has been initialized, this method may be
* called multiple times with no ill-effect.
*/
private static void initializeInputsReader() throws DCInputsReaderException
{
if (INPUTS_READER == null)
{
INPUTS_READER = new DCInputsReader();
}
}
/**
* Return the inputs reader. Note, the reader must have been
* initialized before the reader can be accessed.
*
* @return The input reader.
*/
private static DCInputsReader getInputsReader()
{
return INPUTS_READER;
}
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public DescribeStep() throws ServletException
{
this.requireSubmission = true;
this.requireStep = true;
//Ensure that the InputsReader is initialized.
try
{
initializeInputsReader();
}
catch (DCInputsReaderException e)
{
throw new ServletException(e);
}
}
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
super.addPageMeta(pageMeta);
int collectionID = submission.getCollection().getID();
pageMeta.addMetadata("choice", "collection").addContent(String.valueOf(collectionID));
String jumpTo = submissionInfo.getJumpToField();
if (jumpTo != null)
{
pageMeta.addMetadata("page", "jumpTo").addContent(jumpTo);
}
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Obtain the inputs (i.e. metadata fields we are going to display)
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue";
DCInputSet inputSet;
DCInput[] inputs;
try
{
inputSet = getInputsReader().getInputs(submission.getCollection().getHandle());
inputs = inputSet.getPageRows(getPage()-1, submission.hasMultipleTitles(), submission.isPublishedBefore());
}
catch (DCInputsReaderException se)
{
throw new UIException(se);
}
Division div = body.addInteractiveDivision("submit-describe",actionURL,Division.METHOD_POST,"primary submission");
div.setHead(T_submission_head);
addSubmissionProgressList(div);
List form = div.addList("submit-describe",List.TYPE_FORM);
form.setHead(T_head);
// Iterate over all inputs and add it to the form.
for(DCInput dcInput : inputs)
{
String scope = submissionInfo.isInWorkflow() ? DCInput.WORKFLOW_SCOPE : DCInput.SUBMISSION_SCOPE;
boolean readonly = dcInput.isReadOnly(scope);
// If the input is invisible in this scope, then skip it.
if (!dcInput.isVisible(scope) && !readonly)
{
continue;
}
String schema = dcInput.getSchema();
String element = dcInput.getElement();
String qualifier = dcInput.getQualifier();
DCValue[] dcValues = item.getMetadata(schema, element, qualifier, Item.ANY);
String fieldName = FlowUtils.getFieldName(dcInput);
String inputType = dcInput.getInputType();
// if this field is configured as choice control and its
// presentation format is SELECT, render it as select field:
String fieldKey = MetadataAuthorityManager.makeFieldKey(schema, element, qualifier);
ChoiceAuthorityManager cmgr = ChoiceAuthorityManager.getManager();
if (cmgr.isChoicesConfigured(fieldKey) &&
Params.PRESENTATION_SELECT.equals(cmgr.getPresentation(fieldKey)))
{
renderChoiceSelectField(form, fieldName, collection, dcInput, dcValues, readonly);
}
else if (inputType.equals("name"))
{
renderNameField(form, fieldName, dcInput, dcValues, readonly);
}
else if (inputType.equals("date"))
{
renderDateField(form, fieldName, dcInput, dcValues, readonly);
}
else if (inputType.equals("series"))
{
renderSeriesField(form, fieldName, dcInput, dcValues, readonly);
}
else if (inputType.equals("twobox"))
{
// We don't have a twobox field, instead it's just a
// one box field that the theme can render in two columns.
renderOneboxField(form, fieldName, dcInput, dcValues, readonly);
}
else if (inputType.equals("qualdrop_value"))
{
// Determine the real field's values. Since the qualifier is
// selected we need to search through all the metadata and see
// if any match for another field, if not we assume that this field
// should handle it.
DCValue[] unfiltered = item.getMetadata(dcInput.getSchema(), dcInput.getElement(), Item.ANY, Item.ANY);
ArrayList<DCValue> filtered = new ArrayList<DCValue>();
for (DCValue dcValue : unfiltered)
{
String unfilteredFieldName = dcValue.element + "." + dcValue.qualifier;
if ( ! inputSet.isFieldPresent(unfilteredFieldName) )
{
filtered.add( dcValue );
}
}
renderQualdropField(form, fieldName, dcInput, filtered.toArray(new DCValue[filtered.size()]), readonly);
}
else if (inputType.equals("textarea"))
{
renderTextArea(form, fieldName, dcInput, dcValues, readonly);
}
else if (inputType.equals("dropdown"))
{
renderDropdownField(form, fieldName, dcInput, dcValues, readonly);
}
else if (inputType.equals("list"))
{
renderSelectFromListField(form, fieldName, dcInput, dcValues, readonly);
}
else if (inputType.equals("onebox"))
{
renderOneboxField(form, fieldName, dcInput, dcValues, readonly);
}
else
{
form.addItem(T_unknown_field);
}
}
// add standard control/paging buttons
addControlButtons(form);
}
/**
* Each submission step must define its own information to be reviewed
* during the final Review/Verify Step in the submission process.
* <P>
* The information to review should be tacked onto the passed in
* List object.
* <P>
* NOTE: To remain consistent across all Steps, you should first
* add a sub-List object (with this step's name as the heading),
* by using a call to reviewList.addList(). This sublist is
* the list you return from this method!
*
* @param reviewList
* The List to which all reviewable information should be added
* @return
* The new sub-List object created by this step, which contains
* all the reviewable information. If this step has nothing to
* review, then return null!
*/
public List addReviewSection(List reviewList) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
//Create a new list section for this step (and set its heading)
List describeSection = reviewList.addList("submit-review-" + this.stepAndPage, List.TYPE_FORM);
describeSection.setHead(T_head);
//Review the values assigned to all inputs
//on this page of the Describe step.
DCInputSet inputSet = null;
try
{
inputSet = getInputsReader().getInputs(submission.getCollection().getHandle());
}
catch (DCInputsReaderException se)
{
throw new UIException(se);
}
MetadataAuthorityManager mam = MetadataAuthorityManager.getManager();
DCInput[] inputs = inputSet.getPageRows(getPage()-1, submission.hasMultipleTitles(), submission.isPublishedBefore());
for (DCInput input : inputs)
{
// If the input is invisible in this scope, then skip it.
String scope = submissionInfo.isInWorkflow() ? DCInput.WORKFLOW_SCOPE : DCInput.SUBMISSION_SCOPE;
if (!input.isVisible(scope) && !input.isReadOnly(scope))
{
continue;
}
String inputType = input.getInputType();
String pairsName = input.getPairsType();
DCValue[] values;
if (inputType.equals("qualdrop_value"))
{
values = submission.getItem().getMetadata(input.getSchema(), input.getElement(), Item.ANY, Item.ANY);
}
else
{
values = submission.getItem().getMetadata(input.getSchema(), input.getElement(), input.getQualifier(), Item.ANY);
}
if (values != null && values.length > 0)
{
for (DCValue value : values)
{
String displayValue = null;
if (inputType.equals("date"))
{
DCDate date = new DCDate(value.value);
displayValue = date.toString();
}
else if (inputType.equals("dropdown"))
{
displayValue = input.getDisplayString(pairsName,value.value);
}
else if (inputType.equals("qualdrop_value"))
{
String qualifier = value.qualifier;
String displayQual = input.getDisplayString(pairsName,qualifier);
if (displayQual!=null && displayQual.length()>0)
{
displayValue = displayQual + ":" + value.value;
}
}
else
{
displayValue = value.value;
}
//Only display this field if we have a value to display
if (displayValue!=null && displayValue.length()>0)
{
describeSection.addLabel(input.getLabel());
if (mam.isAuthorityControlled(value.schema, value.element, value.qualifier))
{
String confidence = (value.authority != null && value.authority.length() > 0) ?
Choices.getConfidenceText(value.confidence).toLowerCase() :
"blank";
org.dspace.app.xmlui.wing.element.Item authItem =
describeSection.addItem("submit-review-field-with-authority", "ds-authority-confidence cf-"+confidence);
authItem.addContent(displayValue);
}
else
{
describeSection.addItem(displayValue);
}
}
} // For each DCValue
} // If values exist
}// For each input
//return this new "describe" section
return describeSection;
}
/**
* Render a Name field to the DRI document. The name field consists of two
* text fields, one for the last name and the other for a first name (plus
* all other names).
*
* @param form
* The form list to add the field too
* @param fieldName
* The field's name.
* @param dcInput
* The field's input deffinition
* @param dcValues
* The field's pre-existing values.
*/
private void renderNameField(List form, String fieldName, DCInput dcInput, DCValue[] dcValues, boolean readonly) throws WingException
{
// The name field is a composite field containing two text fields, one
// for first name the other for last name.
Composite fullName = form.addItem().addComposite(fieldName, "submit-name");
Text lastName = fullName.addText(fieldName+"_last");
Text firstName = fullName.addText(fieldName+"_first");
// Setup the full name
fullName.setLabel(dcInput.getLabel());
fullName.setHelp(cleanHints(dcInput.getHints()));
if (dcInput.isRequired())
{
fullName.setRequired();
}
if (isFieldInError(fieldName))
{
if (dcInput.getWarning() != null && dcInput.getWarning().length() > 0)
{
fullName.addError(dcInput.getWarning());
}
else
{
fullName.addError(T_required_field);
}
}
if (dcInput.isRepeatable() && !readonly)
{
fullName.enableAddOperation();
}
if ((dcInput.isRepeatable() || dcValues.length > 1) && !readonly)
{
fullName.enableDeleteOperation();
}
String fieldKey = MetadataAuthorityManager.makeFieldKey(dcInput.getSchema(), dcInput.getElement(), dcInput.getQualifier());
boolean isAuthorityControlled = MetadataAuthorityManager.getManager().isAuthorityControlled(fieldKey);
if (isAuthorityControlled)
{
fullName.setAuthorityControlled();
fullName.setAuthorityRequired(MetadataAuthorityManager.getManager().isAuthorityRequired(fieldKey));
}
if (ChoiceAuthorityManager.getManager().isChoicesConfigured(fieldKey))
{
fullName.setChoices(fieldKey);
fullName.setChoicesPresentation(ChoiceAuthorityManager.getManager().getPresentation(fieldKey));
fullName.setChoicesClosed(ChoiceAuthorityManager.getManager().isClosed(fieldKey));
}
// Setup the first and last name
lastName.setLabel(T_last_name_help);
firstName.setLabel(T_first_name_help);
if (readonly)
{
lastName.setDisabled();
firstName.setDisabled();
fullName.setDisabled();
}
// Setup the field's values
if (dcInput.isRepeatable() || dcValues.length > 1)
{
for (DCValue dcValue : dcValues)
{
DCPersonName dpn = new DCPersonName(dcValue.value);
lastName.addInstance().setValue(dpn.getLastName());
firstName.addInstance().setValue(dpn.getFirstNames());
Instance fi = fullName.addInstance();
fi.setValue(dcValue.value);
if (isAuthorityControlled)
{
if (dcValue.authority == null || dcValue.authority.equals(""))
{
fi.setAuthorityValue("", "blank");
}
else
{
fi.setAuthorityValue(dcValue.authority, Choices.getConfidenceText(dcValue.confidence));
}
}
}
}
else if (dcValues.length == 1)
{
DCPersonName dpn = new DCPersonName(dcValues[0].value);
lastName.setValue(dpn.getLastName());
firstName.setValue(dpn.getFirstNames());
if (isAuthorityControlled)
{
if (dcValues[0].authority == null || dcValues[0].authority.equals(""))
{
lastName.setAuthorityValue("", "blank");
}
else
{
lastName.setAuthorityValue(dcValues[0].authority, Choices.getConfidenceText(dcValues[0].confidence));
}
}
}
}
/**
* Render a date field to the DRI document. The date field consists of
* three component fields, a 4 character text field for the year, a select
* box for the month, and a 2 character text field for the day.
*
* @param form
* The form list to add the field too
* @param fieldName
* The field's name.
* @param dcInput
* The field's input deffinition
* @param dcValues
* The field's pre-existing values.
*/
private void renderDateField(List form, String fieldName, DCInput dcInput, DCValue[] dcValues, boolean readonly) throws WingException
{
// The date field consists of three primitive fields: a text field
// for the year, followed by a select box of the months, follewed
// by a text box for the day.
Composite fullDate = form.addItem().addComposite(fieldName, "submit-date");
Text year = fullDate.addText(fieldName+"_year");
Select month = fullDate.addSelect(fieldName+"_month");
Text day = fullDate.addText(fieldName+"_day");
// Set up the full field
fullDate.setLabel(dcInput.getLabel());
fullDate.setHelp(cleanHints(dcInput.getHints()));
if (dcInput.isRequired())
{
fullDate.setRequired();
}
if (isFieldInError(fieldName))
{
if (dcInput.getWarning() != null && dcInput.getWarning().length() > 0)
{
fullDate.addError(dcInput.getWarning());
}
else
{
fullDate.addError(T_required_field);
}
}
if (dcInput.isRepeatable() && !readonly)
{
fullDate.enableAddOperation();
}
if ((dcInput.isRepeatable() || dcValues.length > 1) && !readonly)
{
fullDate.enableDeleteOperation();
}
if (readonly)
{
year.setDisabled();
month.setDisabled();
day.setDisabled();
}
// Setup the year field
year.setLabel(T_year);
year.setSize(4,4);
// Setup the month field
month.setLabel(T_month);
month.addOption(0,"");
for (int i = 1; i < 13; i++)
{
month.addOption(i,org.dspace.content.DCDate.getMonthName(i,Locale.getDefault()));
}
// Setup the day field
day.setLabel(T_day);
day.setSize(2,2);
// Setup the field's values
if (dcInput.isRepeatable() || dcValues.length > 1)
{
for (DCValue dcValue : dcValues)
{
DCDate dcDate = new DCDate(dcValue.value);
year.addInstance().setValue(String.valueOf(dcDate.getYear()));
month.addInstance().setOptionSelected(dcDate.getMonth());
day.addInstance().setValue(String.valueOf(dcDate.getDay()));
fullDate.addInstance().setValue(dcDate.toString());
}
}
else if (dcValues.length == 1)
{
DCDate dcDate = new DCDate(dcValues[0].value);
year.setValue(String.valueOf(dcDate.getYear()));
month.setOptionSelected(dcDate.getMonth());
// Check if the day field is not specified, if so then just
// put a blank value in instead of the wiered looking -1.
if (dcDate.getDay() == -1)
{
day.setValue("");
}
else
{
day.setValue(String.valueOf(dcDate.getDay()));
}
}
}
/**
* Render a series field to the DRI document. The series field conist of
* two component text fields. When interpreted each of these fields are
* combined back together to be a single value joined together by a
* semicolen. The primary use case is for the journal or report number
* the left hand side is the journal and the right hand side in a
* unique number within the journal.
*
* @param form
* The form list to add the field too
* @param fieldName
* The field's name.
* @param dcInput
* The field's input deffinition
* @param dcValues
* The field's pre-existing values.
*/
private void renderSeriesField(List form, String fieldName, DCInput dcInput, DCValue[] dcValues, boolean readonly) throws WingException
{
// The seiries field consists of two parts, a series name (text field)
// and report or paper number (also a text field).
Composite fullSeries = form.addItem().addComposite(fieldName,"submit-"+dcInput.getInputType());
Text series = fullSeries.addText(fieldName+"_series");
Text number = fullSeries.addText(fieldName+"_number");
// Setup the full field.
fullSeries.setLabel(dcInput.getLabel());
fullSeries.setHelp(cleanHints(dcInput.getHints()));
if (dcInput.isRequired())
{
fullSeries.setRequired();
}
if (isFieldInError(fieldName))
{
if (dcInput.getWarning() != null && dcInput.getWarning().length() > 0)
{
fullSeries.addError(dcInput.getWarning());
}
else
{
fullSeries.addError(T_required_field);
}
}
if (dcInput.isRepeatable() && !readonly)
{
fullSeries.enableAddOperation();
}
if ((dcInput.isRepeatable() || dcValues.length > 1) && !readonly)
{
fullSeries.enableDeleteOperation();
}
series.setLabel(T_series_name);
number.setLabel(T_report_no);
if (readonly)
{
fullSeries.setDisabled();
series.setDisabled();
number.setDisabled();
}
// Setup the field's values
if (dcInput.isRepeatable() || dcValues.length > 1)
{
for (DCValue dcValue : dcValues)
{
DCSeriesNumber dcSeriesNumber = new DCSeriesNumber(dcValue.value);
series.addInstance().setValue(dcSeriesNumber.getSeries());
number.addInstance().setValue(dcSeriesNumber.getNumber());
fullSeries.addInstance().setValue(dcSeriesNumber.toString());
}
}
else if (dcValues.length == 1)
{
DCSeriesNumber dcSeriesNumber = new DCSeriesNumber(dcValues[0].value);
series.setValue(dcSeriesNumber.getSeries());
number.setValue(dcSeriesNumber.getNumber());
}
}
/**
* Render a qualdrop field to the DRI document. Qualdrop fields are complicated,
* widget wise they are composed of two fields, a select and text box field.
* The select field selects the metedata's qualifier and the text box is the
* value. This means that that there is not just one metadata element that is
* represented so the confusing part is that the name can change.
*
* @param form
* The form list to add the field too
* @param fieldName
* The field's name.
* @param dcInput
* The field's input deffinition
* @param dcValues
* The field's pre-existing values.
*/
private void renderQualdropField(List form, String fieldName, DCInput dcInput, DCValue[] dcValues, boolean readonly) throws WingException
{
Composite qualdrop = form.addItem().addComposite(fieldName,"submit-qualdrop");
Select qual = qualdrop.addSelect(fieldName+"_qualifier");
Text value = qualdrop.addText(fieldName+"_value");
// Setup the full field.
qualdrop.setLabel(dcInput.getLabel());
qualdrop.setHelp(cleanHints(dcInput.getHints()));
if (dcInput.isRequired())
{
qualdrop.setRequired();
}
if (isFieldInError(fieldName))
{
if (dcInput.getWarning() != null && dcInput.getWarning().length() > 0)
{
qualdrop.addError(dcInput.getWarning());
}
else
{
qualdrop.addError(T_required_field);
}
}
if (dcInput.isRepeatable() && !readonly)
{
qualdrop.enableAddOperation();
}
// Update delete based upon the filtered values.
if ((dcInput.isRepeatable() || dcValues.length > 1) && !readonly)
{
qualdrop.enableDeleteOperation();
}
if (readonly)
{
qualdrop.setDisabled();
qual.setDisabled();
value.setDisabled();
}
// Setup the possible options
@SuppressWarnings("unchecked") // This cast is correct
java.util.List<String> pairs = dcInput.getPairs();
for (int i = 0; i < pairs.size(); i += 2)
{
String display = pairs.get(i);
String returnValue = pairs.get(i+1);
qual.addOption(returnValue,display);
}
// Setup the field's values
if (dcInput.isRepeatable() || dcValues.length > 1)
{
for (DCValue dcValue : dcValues)
{
qual.addInstance().setOptionSelected(dcValue.qualifier);
value.addInstance().setValue(dcValue.value);
qualdrop.addInstance().setValue(dcValue.qualifier + ":" + dcValue.value);
}
}
else if (dcValues.length == 1)
{
qual.setOptionSelected(dcValues[0].qualifier);
value.setValue(dcValues[0].value);
}
}
/**
* Render a Text Area field to the DRI document. The text area is a simple
* multi row and column text field.
*
* @param form
* The form list to add the field too
* @param fieldName
* The field's name.
* @param dcInput
* The field's input deffinition
* @param dcValues
* The field's pre-existing values.
*/
private void renderTextArea(List form, String fieldName, DCInput dcInput, DCValue[] dcValues, boolean readonly) throws WingException
{
// Plain old Textarea
TextArea textArea = form.addItem().addTextArea(fieldName,"submit-textarea");
// Setup the text area
textArea.setLabel(dcInput.getLabel());
textArea.setHelp(cleanHints(dcInput.getHints()));
String fieldKey = MetadataAuthorityManager.makeFieldKey(dcInput.getSchema(), dcInput.getElement(), dcInput.getQualifier());
boolean isAuth = MetadataAuthorityManager.getManager().isAuthorityControlled(fieldKey);
if (isAuth)
{
textArea.setAuthorityControlled();
textArea.setAuthorityRequired(MetadataAuthorityManager.getManager().isAuthorityRequired(fieldKey));
}
if (ChoiceAuthorityManager.getManager().isChoicesConfigured(fieldKey))
{
textArea.setChoices(fieldKey);
textArea.setChoicesPresentation(ChoiceAuthorityManager.getManager().getPresentation(fieldKey));
textArea.setChoicesClosed(ChoiceAuthorityManager.getManager().isClosed(fieldKey));
}
if (dcInput.isRequired())
{
textArea.setRequired();
}
if (isFieldInError(fieldName))
{
if (dcInput.getWarning() != null && dcInput.getWarning().length() > 0)
{
textArea.addError(dcInput.getWarning());
}
else
{
textArea.addError(T_required_field);
}
}
if (dcInput.isRepeatable() && !readonly)
{
textArea.enableAddOperation();
}
if ((dcInput.isRepeatable() || dcValues.length > 1) && !readonly)
{
textArea.enableDeleteOperation();
}
if (readonly)
{
textArea.setDisabled();
}
// Setup the field's values
if (dcInput.isRepeatable() || dcValues.length > 1)
{
for (DCValue dcValue : dcValues)
{
Instance ti = textArea.addInstance();
ti.setValue(dcValue.value);
if (isAuth)
{
if (dcValue.authority == null || dcValue.authority.equals(""))
{
ti.setAuthorityValue("", "blank");
}
else
{
ti.setAuthorityValue(dcValue.authority, Choices.getConfidenceText(dcValue.confidence));
}
}
}
}
else if (dcValues.length == 1)
{
textArea.setValue(dcValues[0].value);
if (isAuth)
{
if (dcValues[0].authority == null || dcValues[0].authority.equals(""))
{
textArea.setAuthorityValue("", "blank");
}
else
{
textArea.setAuthorityValue(dcValues[0].authority, Choices.getConfidenceText(dcValues[0].confidence));
}
}
}
}
/**
* Render a dropdown field for a choice-controlled input of the
* 'select' presentation to the DRI document. The dropdown field
* consists of an HTML select box.
*
* @param form
* The form list to add the field too
* @param fieldName
* The field's name.
* @param dcInput
* The field's input deffinition
* @param dcValues
* The field's pre-existing values.
*/
private void renderChoiceSelectField(List form, String fieldName, Collection coll, DCInput dcInput, DCValue[] dcValues, boolean readonly) throws WingException
{
String fieldKey = MetadataAuthorityManager.makeFieldKey(dcInput.getSchema(), dcInput.getElement(), dcInput.getQualifier());
if (MetadataAuthorityManager.getManager().isAuthorityControlled(fieldKey))
{
throw new WingException("Field " + fieldKey + " has choice presentation of type \"" + Params.PRESENTATION_SELECT + "\", it may NOT be authority-controlled.");
}
// Plain old select list.
Select select = form.addItem().addSelect(fieldName,"submit-select");
//Setup the select field
select.setLabel(dcInput.getLabel());
select.setHelp(cleanHints(dcInput.getHints()));
if (dcInput.isRequired())
{
select.setRequired();
}
if (isFieldInError(fieldName))
{
if (dcInput.getWarning() != null && dcInput.getWarning().length() > 0)
{
select.addError(dcInput.getWarning());
}
else
{
select.addError(T_required_field);
}
}
if (dcInput.isRepeatable() || dcValues.length > 1)
{
// Use the multiple functionality from the HTML
// widget instead of DRI's version.
select.setMultiple();
select.setSize(6);
}
else
{
select.setSize(1);
}
if (readonly)
{
select.setDisabled();
}
Choices cs = ChoiceAuthorityManager.getManager().getMatches(fieldKey, "", coll.getID(), 0, 0, null);
if (dcValues.length == 0)
{
select.addOption(true, "", "");
}
for (Choice c : cs.values)
{
select.addOption(c.value, c.label);
}
// Setup the field's pre-selected values
for (DCValue dcValue : dcValues)
{
select.setOptionSelected(dcValue.value);
}
}
/**
* Render a dropdown field to the DRI document. The dropdown field consists
* of an HTML select box.
*
* @param form
* The form list to add the field too
* @param fieldName
* The field's name.
* @param dcInput
* The field's input deffinition
* @param dcValues
* The field's pre-existing values.
*/
private void renderDropdownField(List form, String fieldName, DCInput dcInput, DCValue[] dcValues, boolean readonly) throws WingException
{
// Plain old select list.
Select select = form.addItem().addSelect(fieldName,"submit-select");
//Setup the select field
select.setLabel(dcInput.getLabel());
select.setHelp(cleanHints(dcInput.getHints()));
if (dcInput.isRequired())
{
select.setRequired();
}
if (isFieldInError(fieldName))
{
if (dcInput.getWarning() != null && dcInput.getWarning().length() > 0)
{
select.addError(dcInput.getWarning());
}
else
{
select.addError(T_required_field);
}
}
if (dcInput.isRepeatable() || dcValues.length > 1)
{
// Use the multiple functionality from the HTML
// widget instead of DRI's version.
select.setMultiple();
select.setSize(6);
}
if (readonly)
{
select.setDisabled();
}
// Setup the possible options
@SuppressWarnings("unchecked") // This cast is correct
java.util.List<String> pairs = dcInput.getPairs();
for (int i = 0; i < pairs.size(); i += 2)
{
String display = pairs.get(i);
String value = pairs.get(i+1);
select.addOption(value,display);
}
// Setup the field's pre-selected values
for (DCValue dcValue : dcValues)
{
select.setOptionSelected(dcValue.value);
}
}
/**
* Render a select-from-list field to the DRI document.
* This field consists of either a series of checkboxes
* (if repeatable) or a series of radio buttons (if not repeatable).
* <P>
* Note: This is NOT the same as a List element
* (org.dspace.app.xmlui.wing.element.List). It's just unfortunately
* similarly named.
*
* @param form
* The form list to add the field too
* @param fieldName
* The field's name.
* @param dcInput
* The field's input deffinition
* @param dcValues
* The field's pre-existing values.
*/
private void renderSelectFromListField(List form, String fieldName, DCInput dcInput, DCValue[] dcValues, boolean readonly) throws WingException
{
Field listField = null;
//if repeatable, this list of fields should be checkboxes
if (dcInput.isRepeatable())
{
listField = form.addItem().addCheckBox(fieldName);
}
else //otherwise this is a list of radio buttons
{
listField = form.addItem().addRadio(fieldName);
}
if (readonly)
{
listField.setDisabled();
}
// Setup the field
listField.setLabel(dcInput.getLabel());
listField.setHelp(cleanHints(dcInput.getHints()));
if (dcInput.isRequired())
{
listField.setRequired();
}
if (isFieldInError(fieldName))
{
if (dcInput.getWarning() != null && dcInput.getWarning().length() > 0)
{
listField.addError(dcInput.getWarning());
}
else
{
listField.addError(T_required_field);
}
}
//Setup each of the possible options
java.util.List<String> pairs = dcInput.getPairs();
for (int i = 0; i < pairs.size(); i += 2)
{
String display = pairs.get(i);
String value = pairs.get(i+1);
if(listField instanceof CheckBox)
{
((CheckBox)listField).addOption(value, display);
}
else if(listField instanceof Radio)
{
((Radio)listField).addOption(value, display);
}
}
// Setup the field's pre-selected values
for (DCValue dcValue : dcValues)
{
if(listField instanceof CheckBox)
{
((CheckBox)listField).setOptionSelected(dcValue.value);
}
else if(listField instanceof Radio)
{
((Radio)listField).setOptionSelected(dcValue.value);
}
}
}
/**
* Render a simple text field to the DRI document
*
* @param form
* The form list to add the field too
* @param fieldName
* The field's name.
* @param dcInput
* The field's input deffinition
* @param dcValues
* The field's pre-existing values.
*/
private void renderOneboxField(List form, String fieldName, DCInput dcInput, DCValue[] dcValues, boolean readonly) throws WingException
{
// Both onebox and twobox consist a free form text field
// that the user may enter any value. The difference between
// the two is that a onebox should be rendered in one column
// as twobox should be listed in a two column format. Since this
// decision is not something the Aspect can effect we merely place
// as a render hint.
Text text = form.addItem().addText(fieldName,"submit-text");
// Setup the select field
text.setLabel(dcInput.getLabel());
text.setHelp(cleanHints(dcInput.getHints()));
String fieldKey = MetadataAuthorityManager.makeFieldKey(dcInput.getSchema(), dcInput.getElement(), dcInput.getQualifier());
boolean isAuth = MetadataAuthorityManager.getManager().isAuthorityControlled(fieldKey);
if (isAuth)
{
text.setAuthorityControlled();
text.setAuthorityRequired(MetadataAuthorityManager.getManager().isAuthorityRequired(fieldKey));
}
if (ChoiceAuthorityManager.getManager().isChoicesConfigured(fieldKey))
{
text.setChoices(fieldKey);
text.setChoicesPresentation(ChoiceAuthorityManager.getManager().getPresentation(fieldKey));
text.setChoicesClosed(ChoiceAuthorityManager.getManager().isClosed(fieldKey));
}
if (dcInput.isRequired())
{
text.setRequired();
}
if (isFieldInError(fieldName))
{
if (dcInput.getWarning() != null && dcInput.getWarning().length() > 0)
{
text.addError(dcInput.getWarning());
}
else
{
text.addError(T_required_field);
}
}
if (dcInput.isRepeatable() && !readonly)
{
text.enableAddOperation();
}
if ((dcInput.isRepeatable() || dcValues.length > 1) && !readonly)
{
text.enableDeleteOperation();
}
if (readonly)
{
text.setDisabled();
}
// Setup the field's values
if (dcInput.isRepeatable() || dcValues.length > 1)
{
for (DCValue dcValue : dcValues)
{
Instance ti = text.addInstance();
ti.setValue(dcValue.value);
if (isAuth)
{
if (dcValue.authority == null || dcValue.authority.equals(""))
{
ti.setAuthorityValue("", "blank");
}
else
{
ti.setAuthorityValue(dcValue.authority, Choices.getConfidenceText(dcValue.confidence));
}
}
}
}
else if (dcValues.length == 1)
{
text.setValue(dcValues[0].value);
if (isAuth)
{
if (dcValues[0].authority == null || dcValues[0].authority.equals(""))
{
text.setAuthorityValue("", "blank");
}
else
{
text.setAuthorityValue(dcValues[0].authority, Choices.getConfidenceText(dcValues[0].confidence));
}
}
}
}
/**
* Check if the given fieldname is listed as being in error.
*
* @param fieldName
* @return
*/
private boolean isFieldInError(String fieldName)
{
return (this.errorFields.contains(fieldName));
}
/**
* There is a problem with the way hints are handled. The class that we use to
* read the input-forms.xml configuration will append and prepend HTML to hints.
* This causes all sorts of confusion when inserting into the DRI page, so this
* method will strip that extra HTML and just leave the cleaned comments.
*
*
* However this method will not remove naughty or sexual innuendoes from the
* field's hints.
*
*
* @param dirtyHints HTML-ized hints
* @return Hints without HTML.
*/
private static final String HINT_HTML_PREFIX = "<tr><td colspan=\"4\" class=\"submitFormHelp\">";
private static final String HINT_HTML_POSTFIX = "</td></tr>";
private String cleanHints(String dirtyHints)
{
String clean = (dirtyHints!=null ? dirtyHints : "");
if (clean.startsWith(HINT_HTML_PREFIX))
{
clean = clean.substring(HINT_HTML_PREFIX.length());
}
if (clean.endsWith(HINT_HTML_POSTFIX))
{
clean = clean.substring(0,clean.length() - HINT_HTML_POSTFIX.length());
}
return clean;
}
}
| 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.submission.submit;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractSubmissionStep;
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.List;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* This is a conformation page informing the user that they have
* completed the submission of the item. It tells them what to
* expect next, i.e. the workflow, and gives the option to go home
* or start another submission.
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public class CompletedStep extends AbstractSubmissionStep
{
/** Language Strings **/
protected static final Message T_head =
message("xmlui.Submission.submit.CompletedStep.head");
protected static final Message T_info1 =
message("xmlui.Submission.submit.CompletedStep.info1");
protected static final Message T_go_submission =
message("xmlui.Submission.submit.CompletedStep.go_submission");
protected static final Message T_submit_again =
message("xmlui.Submission.submit.CompletedStep.submit_again");
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public CompletedStep()
{
this.requireHandle = true;
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Division div = body.addInteractiveDivision("submit-complete",contextPath+"/handle/"+handle+"/submit", Division.METHOD_POST,"primary submission");
div.setHead(T_head);
div.addPara(T_info1);
div.addPara().addXref(contextPath+"/submissions",T_go_submission);
div.addPara().addButton("submit_again").setValue(T_submit_again);
div.addHidden("handle").setValue(handle);
}
/**
* Each submission step must define its own information to be reviewed
* during the final Review/Verify Step in the submission process.
* <P>
* The information to review should be tacked onto the passed in
* List object.
* <P>
* NOTE: To remain consistent across all Steps, you should first
* add a sub-List object (with this step's name as the heading),
* by using a call to reviewList.addList(). This sublist is
* the list you return from this method!
*
* @param reviewList
* The List to which all reviewable information should be added
* @return
* The new sub-List object created by this step, which contains
* all the reviewable information. If this step has nothing to
* review, then return null!
*/
public List addReviewSection(List reviewList) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
//nothing to review, since submission is now Completed!
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.submission.submit;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractStep;
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.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* This is a confirmation page informing the user that they have
* successfully removed their submission.
* <P>
* As such, it's not a true "step" in the submission process
*
* @author Scott Phillips
*/
public class RemovedStep extends AbstractStep
{
/** Language Strings **/
protected static final Message T_head =
message("xmlui.Submission.submit.RemovedStep.head");
protected static final Message T_info1 =
message("xmlui.Submission.submit.RemovedStep.info1");
protected static final Message T_go_submissions =
message("xmlui.Submission.submit.RemovedStep.go_submission");
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Division div = body.addInteractiveDivision("submit-removed",contextPath+"/submit", Division.METHOD_POST,"primary submission");
div.setHead(T_head);
div.addPara(T_info1);
div.addPara().addXref(contextPath+"/submissions",T_go_submissions);
}
}
| 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.submission.submit;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.log4j.Logger;
import org.dspace.app.util.SubmissionConfig;
import org.dspace.app.util.SubmissionStepConfig;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractStep;
import org.dspace.app.xmlui.aspect.submission.AbstractSubmissionStep;
import org.dspace.app.xmlui.aspect.submission.StepAndPage;
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.List;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.submit.step.UploadStep;
import org.xml.sax.SAXException;
/**
* This is a step of the item submission processes. This is where the user
* reviews everything they have entered about the item up to this point.
* <P>
* This step is dynamic, since when using the Configurable Submission
* it is unknown what steps are available and in what order.
* <P>
* This step builds a form with which consists of a separate section
* for each step which implements the "addReviewSection()" method
* of AbstractSubmissionStep class.
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public class ReviewStep extends AbstractSubmissionStep
{
/** Language Strings **/
protected static final Message T_head =
message("xmlui.Submission.submit.ReviewStep.head");
protected static final Message T_yes =
message("xmlui.Submission.submit.ReviewStep.yes");
protected static final Message T_no =
message("xmlui.Submission.submit.ReviewStep.no");
protected static final Message T_submit_jump =
message("xmlui.Submission.submit.ReviewStep.submit_jump");
protected static final Message T_no_metadata =
message("xmlui.Submission.submit.ReviewStep.no_metadata");
protected static final Message T_unknown =
message("xmlui.Submission.submit.ReviewStep.unknown");
protected static final Message T_known =
message("xmlui.Submission.submit.ReviewStep.known");
protected static final Message T_supported =
message("xmlui.Submission.submit.ReviewStep.supported");
/* The SourceResolver used to setup this class */
private SourceResolver resolver;
/* The source string used to setup this class */
private String src;
/** log4j logger */
private static Logger log = Logger.getLogger(UploadStep.class);
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public ReviewStep()
{
this.requireSubmission = true;
this.requireStep = true;
}
/**
* Save these setup parameters, to use for loading up
* the previous step's review information
*/
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters)
throws ProcessingException, SAXException, IOException
{
super.setup(resolver,objectModel,src,parameters);
this.resolver = resolver;
this.src = src;
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Get actionable URL
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue";
SubmissionConfig subConfig = submissionInfo.getSubmissionConfig();
//Part A:
// Build the main Review Form!
Division div = body.addInteractiveDivision("submit-upload", actionURL, Division.METHOD_POST, "primary submission");
div.setHead(T_submission_head);
addSubmissionProgressList(div);
List review = div.addList("submit-review", List.TYPE_FORM);
review.setHead(T_head);
// Part B:
// Add review section for each step
//get a list of all pages in progress bar
//(this is to ensure we are no looping through non-interactive steps)
Set submissionPagesSet = submissionInfo.getProgressBarInfo().keySet();
String[] submissionPages = (String[]) submissionPagesSet.toArray(new String[submissionPagesSet.size()]);
//loop through each page in progress bar,
//adding each as a separate section to the review form
for(int i=0; i<submissionPages.length; i++)
{
StepAndPage currentStepAndPage = new StepAndPage(submissionPages[i]);
//If the step we are looking at is this current
// Review/Verify step, exit the for loop,
// since we have completed all steps up to this one!
if(currentStepAndPage.equals(this.stepAndPage))
{
break;
}
//load up step configuration
SubmissionStepConfig stepConfig = subConfig.getStep(currentStepAndPage.getStep());
//load the step's XML-UI Class
AbstractStep stepUIClass = loadXMLUIClass(stepConfig.getXMLUIClassName());
try
{
//initialize this class (with proper step parameter)
parameters.setParameter("step", currentStepAndPage.toString());
stepUIClass.setup(resolver, objectModel, src, parameters);
}
catch(Exception e)
{
throw new UIException("Unable to initialize AbstractStep identified by "
+ stepConfig.getXMLUIClassName() + ":", e);
}
//If this stepUIClass is not a value AbstractSubmissionStep,
//we will be unable to display its review information!
if(stepUIClass instanceof AbstractSubmissionStep)
{
//add the Review section for this step,
//and return a reference to that newly created step section
List stepSection = ((AbstractSubmissionStep) stepUIClass).addReviewSection(review);
//as long as this step has something to review
if(stepSection!=null)
{
//add a Jump To button for this section
addJumpButton(stepSection, T_submit_jump, currentStepAndPage);
}
}
else
{
//Log a warning that this step cannot be reviewed!
log.warn("The Step represented by " + stepConfig.getXMLUIClassName() + " is not a valid AbstractSubmissionStep, so it cannot be reviewed during the ReviewStep!");
}
}
// Part C:
// add standard control/paging buttons
addControlButtons(review);
}
/**
* Each submission step must define its own information to be reviewed
* during the final Review/Verify Step in the submission process.
* <P>
* The information to review should be tacked onto the passed in
* List object.
* <P>
* NOTE: To remain consistent across all Steps, you should first
* add a sub-List object (with this step's name as the heading),
* by using a call to reviewList.addList(). This sublist is
* the list you return from this method!
*
* @param reviewList
* The List to which all reviewable information should be added
* @return
* The new sub-List object created by this step, which contains
* all the reviewable information. If this step has nothing to
* review, then return null!
*/
public List addReviewSection(List reviewList) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
//Review step cannot review itself :)
return null;
}
/**
* Loads the specified XML-UI class
* which will generate the review information
* for a given step
*
* @return AbstractStep which references
* the XML-UI Class
*/
private AbstractStep loadXMLUIClass(String transformerClassName)
throws UIException
{
try
{
//retrieve an instance of the transformer class
ClassLoader loader = this.getClass().getClassLoader();
Class stepClass = loader
.loadClass(transformerClassName);
// this XML-UI class *must* be a valid AbstractStep,
// or else we'll have problems here
return (AbstractStep) stepClass
.newInstance();
}
catch(ClassNotFoundException cnfe)
{
//means that we couldn't find a class by the given name
throw new UIException("Class Not Found: " + transformerClassName, cnfe);
}
catch(Exception e)
{
//means we couldn't instantiate the class as an AbstractStep
throw new UIException("Unable to instantiate class " + transformerClassName + ". " +
"Please make sure it extends org.dspace.app.xmlui.submission.AbstractSubmissionStep!", e);
}
}
}
| 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.submission.submit;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.aspect.submission.AbstractStep;
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.List;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.xml.sax.SAXException;
/**
* This is sort-of a step of the submission processes (not
* an official "step", since it does not extend AbstractSubmissionStep).
* <P>
* At any time during submission the user may leave the processe and either
* leave it for later or remove the submission.
* <P>
* This form presents three options, 1) Go back, 2) save the work,
* or 3) remove it.
*
* @author Scott Phillips
* @author Tim Donohue (small updates for Configurable Submission)
*/
public class SaveOrRemoveStep extends AbstractStep
{
/** Language Strings **/
protected static final Message T_head =
message("xmlui.Submission.submit.SaveOrRemoveStep.head");
protected static final Message T_info1 =
message("xmlui.Submission.submit.SaveOrRemoveStep.info1");
protected static final Message T_submit_back =
message("xmlui.Submission.submit.SaveOrRemoveStep.submit_back");
protected static final Message T_submit_save =
message("xmlui.Submission.submit.SaveOrRemoveStep.submit_save");
protected static final Message T_submit_remove =
message("xmlui.Submission.submit.SaveOrRemoveStep.submit_remove");
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public SaveOrRemoveStep()
{
this.requireSubmission = true;
this.requireStep = true;
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Collection collection = submission.getCollection();
String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue";
Division div = body.addInteractiveDivision("submit-save-or-cancel",actionURL, Division.METHOD_POST,"primary submission");
div.setHead(T_submission_head);
addSubmissionProgressList(div);
List saveOrCancel = div.addList("submit-review", List.TYPE_FORM);
saveOrCancel.setHead(T_head);
saveOrCancel.addItem(T_info1);
org.dspace.app.xmlui.wing.element.Item actions = saveOrCancel.addItem();
actions.addButton("submit_back").setValue(T_submit_back);
actions.addButton("submit_save").setValue(T_submit_save);
actions.addButton("submit_remove").setValue(T_submit_remove);
}
}
| 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.submission;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
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.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Constants;
import org.dspace.eperson.Group;
import org.xml.sax.SAXException;
/**
* Add a single link to the display item page that allows
* the user to submit a new item to this collection.
*
* @author Scott Phillips
*/
public class CollectionViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
protected static final Message T_title =
message("xmlui.Submission.SelectCollection.title");
protected static final Message T_submit =
message("xmlui.Submission.CollectionViewer.link1");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return "0";
}
return HashUtil.hash(dso.getHandle());
}
catch (SQLException sqle)
{
// Ignore all errors and just return that the component is not
// cachable.
return "0";
}
}
/**
* 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
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return null;
}
if (!(dso instanceof Collection))
{
return null;
}
Collection collection = (Collection) dso;
DSpaceValidity validity = new DSpaceValidity();
// Add the actual collection;
validity.add(collection);
// Add the eperson viewing the collection
validity.add(eperson);
// Include any groups they are a member of
Group[] groups = Group.allMemberGroups(context, eperson);
for (Group group : groups)
{
validity.add(group);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add a single link to the view item page that allows the user
* to submit to the collection.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Collection))
{
return;
}
// Set up the major variables
Collection collection = (Collection) dso;
// Only add the submit link if the user has the ability to add items.
if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.ADD))
{
Division home = body.addDivision("collection-home","primary repository collection");
Division viewer = home.addDivision("collection-view","secondary");
String submitURL = contextPath + "/handle/" + collection.getHandle() + "/submit";
viewer.addPara().addXref(submitURL,T_submit);
}
}
/**
* 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.submission;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
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.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.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* Simple navigation class to add the top level link to
* the main submissions page.
*
* @author Scott Phillips
*/
public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings **/
protected static final Message T_submissions =
message("xmlui.Submission.Navigation.submissions");
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey() {
return 1;
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity()
{
return NOPValidity.SHARED_INSTANCE;
}
public void addOptions(Options options) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Basic navigation skeleton
options.addList("browse");
List account = options.addList("account");
options.addList("context");
options.addList("administrative");
// This dosn't flow very well, lets remove it and see if anyone misses it.
// DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
// if (dso != null && dso instanceof Collection)
// {
// Collection collection = (Collection) dso;
// if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.ADD))
// {
// String submitURL = contextPath + "/handle/" + collection.getHandle() + "/submit";
// account.addItemXref(submitURL,"Submit to this collection");
// }
// }
account.addItemXref(contextPath+"/submissions",T_submissions);
}
}
| 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.submission;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.log4j.Logger;
import org.dspace.app.util.DCInput;
import org.dspace.app.util.SubmissionConfig;
import org.dspace.app.util.SubmissionConfigReader;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.util.SubmissionStepConfig;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.InProgressSubmission;
import org.dspace.content.Item;
import org.dspace.content.WorkspaceItem;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.handle.HandleManager;
import org.dspace.submit.AbstractProcessingStep;
import org.dspace.workflow.WorkflowItem;
import org.dspace.workflow.WorkflowManager;
/**
* This is a utility class to aid in the submission flow scripts.
* Since data validation is cumbersome inside a flow script this
* is a collection of methods to perform processing at each step
* of the flow, the flow script will ties these operations
* together in a meaningful order but all actually processing
* is done through these various processes.
*
* @author Scott Phillips
* @author Tim Donohue (modified for Configurable Submission)
*/
public class FlowUtils {
private static final Logger log = Logger.getLogger(FlowUtils.class);
/** Where the submissionInfo is stored on an HTTP Request object */
private static final String DSPACE_SUBMISSION_INFO = "dspace.submission.info";
/**
* Return the InProgressSubmission, either workspaceItem or workflowItem,
* depending on the id provided. If the id begins with an S then it is a
* considered a workspaceItem. If the id begins with a W then it is
* considered a workflowItem.
*
* @param context
* @param inProgressSubmissionID
* @return The InprogressSubmission or null if non found
*/
public static InProgressSubmission findSubmission(Context context, String inProgressSubmissionID) throws SQLException
{
char type = inProgressSubmissionID.charAt(0);
int id = Integer.valueOf(inProgressSubmissionID.substring(1));
if (type == 'S')
{
return WorkspaceItem.find(context, id);
}
else if (type == 'W')
{
return WorkflowItem.find(context, id);
}
return null;
}
/**
* Return the workspace identified by the given id, the id should be
* prepended with the character S to signify that it is a workspace
* instead of a workflow.
*
* @param context
* @param inProgressSubmissionID
* @return The found workspaceitem or null if none found.
*/
public static WorkspaceItem findWorkspace(Context context, String inProgressSubmissionID) throws SQLException
{
InProgressSubmission submission = findSubmission(context, inProgressSubmissionID);
if (submission instanceof WorkspaceItem)
{
return (WorkspaceItem) submission;
}
return null;
}
/**
* Return the workflow identified by the given id, the id should be
* prepended with the character S to signify that it is a workflow
* instead of a workspace.
*
* @param context
* @param inProgressSubmissionID
* @return The found workflowitem or null if none found.
*/
public static WorkflowItem findWorkflow(Context context, String inProgressSubmissionID) throws SQLException
{
InProgressSubmission submission = findSubmission(context, inProgressSubmissionID);
if (submission instanceof WorkflowItem)
{
return (WorkflowItem) submission;
}
return null;
}
/**
* Obtains the submission info for the current submission process.
* If a submissionInfo object has already been created
* for this HTTP request, it is re-used, otherwise it is created.
*
* @param objectModel
* the cocoon Objectmodel
* @param workspaceID
* the workspaceID of the submission info to obtain
*
* @return a SubmissionInfo object
*/
public static SubmissionInfo obtainSubmissionInfo(Map objectModel, String workspaceID) throws SQLException
{
Request request = ObjectModelHelper.getRequest(objectModel);
Context context = ContextUtil.obtainContext(objectModel);
//try loading subInfo from HTTP request
SubmissionInfo subInfo = (SubmissionInfo) request.getAttribute(DSPACE_SUBMISSION_INFO);
//get the submission represented by the WorkspaceID
InProgressSubmission submission = findSubmission(context, workspaceID);
//if no submission info, or wrong submission info, reload it!
if ((subInfo == null && submission!=null) ||
(subInfo!=null && submission!=null && subInfo.getSubmissionItem().getID()!=submission.getID()))
{
try
{
final HttpServletRequest httpRequest = (HttpServletRequest) objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
// load submission info
subInfo = SubmissionInfo.load(httpRequest, submission);
// Set the session ID
context.setExtraLogInfo("session_id="
+ request.getSession().getId());
// Store the submissionInfo in the request
request.setAttribute(DSPACE_SUBMISSION_INFO, subInfo);
}
catch(Exception e)
{
throw new SQLException("Error loading Submission Info: " + e.getMessage(), e);
}
}
else if(subInfo==null && submission==null)
{
throw new SQLException("Unable to load Submission Information, since WorkspaceID (ID:" + workspaceID + ") is not a valid in-process submission.");
}
return subInfo;
}
/**
* Indicate the user has advanced to the given page within a given step.
* This will only actually do anything when it's a user initially entering
* a submission. It will increase the "stage reached" and "page reached"
* columns - it will not "set back" where a user has reached.
*
* @param context The current DSpace content
* @param id The unique ID of the current workflow/workspace
* @param step the step the user has just reached
* @param page the page (within the step) the user has just reached
*/
public static void setPageReached(Context context, String id, int step, int page)
throws SQLException, AuthorizeException, IOException
{
InProgressSubmission submission = findSubmission(context, id);
if (submission instanceof WorkspaceItem)
{
WorkspaceItem workspaceItem = (WorkspaceItem) submission;
if (step > workspaceItem.getStageReached())
{
workspaceItem.setStageReached(step);
workspaceItem.setPageReached(1); //reset page to first page in new step
workspaceItem.update();
context.commit();
}
else if ((step == workspaceItem.getStageReached()) &&
(page > workspaceItem.getPageReached()))
{
workspaceItem.setPageReached(page);
workspaceItem.update();
context.commit();
}
}
}
/**
* Set a specific step and page as reached.
* It will also "set back" where a user has reached.
*
* @param context The current DSpace content
* @param id The unique ID of the current workflow/workspace
* @param step the step to set as reached, can be also a previous reached step
* @param page the page (within the step) to set as reached, can be also a previous reached page
*/
public static void setBackPageReached(Context context, String id, int step,
int page) throws SQLException, AuthorizeException, IOException
{
InProgressSubmission submission = findSubmission(context, id);
if (submission instanceof WorkspaceItem)
{
WorkspaceItem workspaceItem = (WorkspaceItem) submission;
workspaceItem.setStageReached(step);
workspaceItem.setPageReached(page > 0 ? page : 1);
workspaceItem.update();
context.commit();
}
}
/**
* Find the maximum step the user has reached in the submission processes.
* If this submission is a workflow then return max-int.
*
* @param context The current DSpace content
* @param id The unique ID of the current workflow/workspace
*/
public static int getMaximumStepReached(Context context, String id) throws SQLException {
InProgressSubmission submission = findSubmission(context, id);
if (submission instanceof WorkspaceItem)
{
WorkspaceItem workspaceItem = (WorkspaceItem) submission;
int stage = workspaceItem.getStageReached();
if (stage < 0)
{
stage = 0;
}
return stage;
}
// This is a workflow, return infinity.
return Integer.MAX_VALUE;
}
/**
* Find the maximum page (within the maximum step) that the user has
* reached in the submission processes.
* If this submission is a workflow then return max-int.
*
* @param context The current DSpace content
* @param id The unique ID of the current workflow/workspace
*/
public static int getMaximumPageReached(Context context, String id) throws SQLException {
InProgressSubmission submission = findSubmission(context, id);
if (submission instanceof WorkspaceItem)
{
WorkspaceItem workspaceItem = (WorkspaceItem) submission;
int page = workspaceItem.getPageReached();
if (page < 0)
{
page = 0;
}
return page;
}
// This is a workflow, return infinity.
return Integer.MAX_VALUE;
}
/**
* Get current step number
*
* @param stepAndPage
* a double representing the current step and page
* (e.g. 1.2 is page 2 of step 1)
* @return step number
*/
public static int getStep(double stepAndPage)
{
//split step and page (e.g. 1.2 is page 2 of step 1)
String[] fields = Double.toString(stepAndPage).split("\\."); // split on period
return Integer.parseInt(fields[0]);
}
/**
* Get number of the current page within the current step
*
*@param stepAndPage
* a double representing the current step and page
* (e.g. 1.2 is page 2 of step 1)
* @return page number (within current step)
*/
public static int getPage(double stepAndPage)
{
//split step and page (e.g. 1.2 is page 2 of step 1)
String[] fields = Double.toString(stepAndPage).split("\\."); // split on period
return Integer.parseInt(fields[1]);
}
/**
* Process the save or remove step. If the user has selected to
* remove their submission then remove it.
*
* @param context The current DSpace content
* @param id The unique ID of the current workspace/workflow
* @param request The cocoon request object.
*/
public static void processSaveOrRemove(Context context, String id, Request request) throws SQLException, AuthorizeException, IOException
{
if (request.getParameter("submit_remove") != null)
{
// If they selected to remove the item then delete everything.
WorkspaceItem workspace = findWorkspace(context,id);
workspace.deleteAll();
context.commit();
}
}
/**
* Update the provided workflowItem to advance to the next workflow
* step. If this was the last thing needed before the item is
* committed to the repository then return true, otherwise false.
*
* @param context The current DSpace content
* @param id The unique ID of the current workflow
*/
public static boolean processApproveTask(Context context, String id) throws SQLException, UIException, ServletException, AuthorizeException, IOException
{
WorkflowItem workflowItem = findWorkflow(context, id);
Item item = workflowItem.getItem();
// Advance the item along the workflow
WorkflowManager.advance(context, workflowItem, context.getCurrentUser());
// FIXME: This should be a return value from advance()
// See if that gave the item a Handle. If it did,
// the item made it into the archive, so we
// should display a suitable page.
String handle = HandleManager.findHandle(context, item);
context.commit();
return (handle != null);
}
/**
* Return the given task back to the pool of unclaimed tasks for another user
* to select and perform.
*
* @param context The current DSpace content
* @param id The unique ID of the current workflow
*/
public static void processUnclaimTask(Context context, String id) throws SQLException, UIException, ServletException, AuthorizeException, IOException
{
WorkflowItem workflowItem = findWorkflow(context, id);
// Return task to pool
WorkflowManager.unclaim(context, workflowItem, context.getCurrentUser());
context.commit();
//Log this unclaim action
log.info(LogManager.getHeader(context, "unclaim_workflow",
"workflow_item_id=" + workflowItem.getID() + ",item_id="
+ workflowItem.getItem().getID() + ",collection_id="
+ workflowItem.getCollection().getID()
+ ",new_state=" + workflowItem.getState()));
}
/**
* Claim this task from the pool of unclaimed task so that this user may
* perform the task by either approving or rejecting it.
*
* @param context The current DSpace content
* @param id The unique ID of the current workflow
*/
public static void processClaimTask(Context context, String id) throws SQLException, UIException, ServletException, AuthorizeException, IOException
{
WorkflowItem workflowItem = findWorkflow(context, id);
// Claim the task
WorkflowManager.claim(context, workflowItem, context.getCurrentUser());
context.commit();
//log this claim information
log.info(LogManager.getHeader(context, "claim_task", "workflow_item_id="
+ workflowItem.getID() + "item_id=" + workflowItem.getItem().getID()
+ "collection_id=" + workflowItem.getCollection().getID()
+ "newowner_id=" + workflowItem.getOwner().getID()
+ "new_state=" + workflowItem.getState()));
}
/**
* Reject the given task for the given reason. If the user did not provide
* a reason then an error is generated placing that field in error.
*
* @param context The current DSpace content
* @param id The unique ID of the current workflow
* @param request The current request object
*/
public static String processRejectTask(Context context, String id,Request request) throws SQLException, UIException, ServletException, AuthorizeException, IOException
{
WorkflowItem workflowItem = findWorkflow(context, id);
String reason = request.getParameter("reason");
if (reason != null && reason.length() > 1)
{
WorkspaceItem wsi = WorkflowManager.reject(context, workflowItem,context.getCurrentUser(), reason);
//Load the Submission Process for the collection this WSI is associated with
Collection c = wsi.getCollection();
SubmissionConfigReader subConfigReader = new SubmissionConfigReader();
SubmissionConfig subConfig = subConfigReader.getSubmissionConfig(c.getHandle(), false);
// Set the "stage_reached" column on the workspace item
// to the LAST page of the LAST step in the submission process
// (i.e. the page just before "Complete", which is at NumSteps-1)
int lastStep = subConfig.getNumberOfSteps()-2;
wsi.setStageReached(lastStep);
wsi.setPageReached(AbstractProcessingStep.LAST_PAGE_REACHED);
wsi.update();
context.commit();
//Submission rejected. Log this information
log.info(LogManager.getHeader(context, "reject_workflow", "workflow_item_id="
+ wsi.getID() + "item_id=" + wsi.getItem().getID()
+ "collection_id=" + wsi.getCollection().getID()
+ "eperson_id=" + context.getCurrentUser().getID()));
// Return no errors.
return null;
}
else
{
// If the user did not supply a reason then
// place the reason field in error.
return "reason";
}
}
/**
* Return the HTML / DRI field name for the given input.
*
* @param input
* @return field name as a String (e.g. dc_contributor_editor)
*/
public static String getFieldName(DCInput input)
{
String dcSchema = input.getSchema();
String dcElement = input.getElement();
String dcQualifier = input.getQualifier();
if (dcQualifier != null && ! dcQualifier.equals(Item.ANY))
{
return dcSchema + "_" + dcElement + '_' + dcQualifier;
}
else
{
return dcSchema + "_" + dcElement;
}
}
/**
* Retrieves a list of all steps and pages within the
* current submission process.
* <P>
* This list may differ from the list of steps in the
* progress bar if the current submission process includes
* non-interactive steps which do not appear in the progress bar!
* <P>
* This method is used by the Manakin submission flowscript
* (submission.js) to step forward/backward between steps.
*
* @param request
* The HTTP Servlet Request object
* @param subInfo
* the current SubmissionInfo object
*
*/
public static StepAndPage[] getListOfAllSteps(HttpServletRequest request, SubmissionInfo subInfo)
{
ArrayList<StepAndPage> listStepNumbers = new ArrayList<StepAndPage>();
// loop through all steps
for (int i = 0; i < subInfo.getSubmissionConfig().getNumberOfSteps(); i++)
{
// get the current step info
SubmissionStepConfig currentStep = subInfo.getSubmissionConfig()
.getStep(i);
int stepNumber = currentStep.getStepNumber();
//Skip over the "Select Collection" step, since
// a user is never allowed to return to that step or jump from that step
if(currentStep.getId()!=null && currentStep.getId().equals(SubmissionStepConfig.SELECT_COLLECTION_STEP))
{
continue;
}
// default to just one page in this step
int numPages = 1;
try
{
// load the processing class for this step
ClassLoader loader = subInfo.getClass().getClassLoader();
Class<?> stepClass = loader.loadClass(currentStep.getProcessingClassName());
// call the "getNumberOfPages()" method of the class
// to get it's number of pages
AbstractProcessingStep step = (AbstractProcessingStep) stepClass
.newInstance();
// get number of pages from servlet
numPages = step.getNumberOfPages(request, subInfo);
}
catch (Exception e)
{
log.error("Error loading step information from Step Class '"
+ currentStep.getProcessingClassName()
+ "' Error:", e);
}
// save each of the step's pages to the progress bar
for (int j = 1; j <= numPages; j++)
{
StepAndPage stepAndPageNum = new StepAndPage(stepNumber,j);
listStepNumbers.add(stepAndPageNum);
}// end for each page
}// end for each step
//convert into an array and return that
return listStepNumbers.toArray(new StepAndPage[listStepNumbers.size()]);
}
}
| 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.submission;
import java.io.IOException;
import java.sql.SQLException;
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.utils.UIException;
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.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* This generic transformer is used to generate the DRI
* for any Submission Step which extends the class
* org.dspace.app.xmlui.submission.AbstractStep
* <p>
* This transformer just initializes the current step class
* and calls the appropriate method(s) for the step.
*
* @author Tim Donohue
* @see AbstractStep
*/
public class StepTransformer extends AbstractDSpaceTransformer
{
/**
* The id of the currently active workspace or workflow, this contains
* the incomplete DSpace item
*/
protected String id;
/**
* The current step and page's numeric value that it is at currently. This
* number is dynamic between submissions and is a double where the integer
* value is the step #, and the decimal value is the page #
* (e.g. 1.2 is page 2 of step 1)
*/
private double stepAndPage;
/**
* Full name of the step's transformer class (which must extend
* org.dspace.app.xmlui.submission.AbstractStep).
*/
private String transformerClassName;
/**
* The handle of the collection into which this DSpace
* item is being submitted
*/
protected String collectionHandle;
/**
* An instance of the current step's transformer class (which must extend
* org.dspace.app.xmlui.submission.AbstractStep). This class is
* used to generate the actual DRI for this step.
*/
private AbstractSubmissionStep step;
/**
* Grab all the step's parameters from the sitemap. This includes
* workspaceID, step, and a list of errored fields.
*
* If the implementer set any required parameters then insure that
* they are all present.
*/
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters)
throws ProcessingException, SAXException, IOException
{
super.setup(resolver,objectModel,src,parameters);
//retrieve id and transformer information
//(This ID should always exist by this point, since the
// selection of the collection should have already happened!)
this.id = parameters.getParameter("id",null);
this.transformerClassName = parameters.getParameter("transformer",null);
//even though its not used in this class, this "step" parameter
//is heavily used by the Transformers which extend the
//org.dspace.app.xmlui.submission.AbstractStep
this.stepAndPage = Double.valueOf(parameters.getParameter("step","-1"));
//retrieve collection handle if it's there
this.collectionHandle = parameters.getParameter("handle",null);
try
{
//retrieve an instance of the transformer class
ClassLoader loader = this.getClass().getClassLoader();
Class stepClass = loader
.loadClass(this.transformerClassName);
// this XML-UI class *must* be a valid AbstractSubmissionStep,
// or else we'll have problems here
step = (AbstractSubmissionStep) stepClass
.newInstance();
}
catch(ClassNotFoundException cnfe)
{
//means that we couldn't find a class by the given name
throw new ProcessingException("Class Not Found: " + this.transformerClassName, cnfe);
}
catch(Exception e)
{
//means we couldn't instantiate the class as an AbstractStep
throw new ProcessingException("Unable to instantiate class " + this.transformerClassName + ". " +
"Please make sure it extends org.dspace.app.xmlui.submission.AbstractSubmissionStep!", e);
}
//call the setup for this step
if(step!=null)
{
step.setup(resolver, objectModel, src, parameters);
}
else
{
throw new ProcessingException("Step class is null! We do not have a valid AbstractStep in " + this.transformerClassName + ". ");
}
}
/** What to add at the end of the body */
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
//call addBody for this step
step.addBody(body);
}
/** What to add to the options list */
public void addOptions(Options options) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
//call addOptions for this step
step.addOptions(options);
}
/** What user metadata to add to the document */
public void addUserMeta(UserMeta userMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
//call addUserMeta for this step
step.addUserMeta(userMeta);
}
/** What page metadata to add to the document */
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
//call addPageMeta for this step
step.addPageMeta(pageMeta);
}
/**
* Recycle
*/
public void recycle()
{
this.id = null;
this.transformerClassName = null;
this.collectionHandle = null;
this.stepAndPage = -1;
if(step!=null)
{
this.step.recycle();
this.step = 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.submission;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.log4j.Logger;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Button;
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.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.InProgressSubmission;
import org.dspace.content.WorkspaceItem;
import org.dspace.submit.AbstractProcessingStep;
import org.dspace.workflow.WorkflowItem;
import org.xml.sax.SAXException;
/**
* This abstract class represents an abstract page in the
* submission or workflow processes. This class provides a place
* for common resources to be shared such as i18n tags, progress bars,
* and a common setup.
*
*
* @author Scott Phillips
* @author Tim Donohue (updated for Configurable Submission)
*/
public abstract class AbstractStep extends AbstractDSpaceTransformer
{
private static Logger log = Logger.getLogger(AbstractStep.class);
/** General Language Strings */
protected static final Message T_submission_title =
message("xmlui.Submission.general.submission.title");
protected static final Message T_submission_trail =
message("xmlui.Submission.general.submission.trail");
protected static final Message T_submission_head =
message("xmlui.Submission.general.submission.head");
protected static final Message T_previous =
message("xmlui.Submission.general.submission.previous");
protected static final Message T_save =
message("xmlui.Submission.general.submission.save");
protected static final Message T_next =
message("xmlui.Submission.general.submission.next");
protected static final Message T_complete =
message("xmlui.Submission.general.submission.complete");
protected static final Message T_dspace_home =
message("xmlui.general.dspace_home");
protected static final Message T_workflow_title =
message("xmlui.Submission.general.workflow.title");
protected static final Message T_workflow_trail =
message("xmlui.Submission.general.workflow.trail");
protected static final Message T_workflow_head =
message("xmlui.Submission.general.workflow.head");
protected static final Message T_showfull =
message("xmlui.Submission.general.showfull");
protected static final Message T_showsimple =
message("xmlui.Submission.general.showsimple");
protected static final Message T_default_title =
message("xmlui.Submission.general.default.title");
protected static final Message T_default_trail =
message("xmlui.Submission.general.default.trail");
/** Progress Bar Language Strings */
protected static final Message T_initial_questions =
message("xmlui.Submission.general.progress.initial_questions");
protected static final Message T_describe =
message("xmlui.Submission.general.progress.describe");
protected static final Message T_upload =
message("xmlui.Submission.general.progress.upload");
protected static final Message T_review =
message("xmlui.Submission.general.progress.review");
protected static final Message T_creative_commons =
message("xmlui.Submission.general.progress.creative_commons");
protected static final Message T_license =
message("xmlui.Submission.general.progress.license");
/**
* The id of the currently active workspace or workflow, this contains
* the incomplete DSpace item
*/
protected String id;
/**
* The current DSpace SubmissionInfo
*/
protected SubmissionInfo submissionInfo;
/**
* The in progress submission, if one is available, this may be either
* a workflowItem or a workspaceItem.
*/
protected InProgressSubmission submission;
/**
* The current step and page's numeric values that it is at currently. This
* number is dynamic between submissions.
*/
protected StepAndPage stepAndPage;
/**
* The handle being processed by the current step.
*/
protected String handle;
/**
* The error flag which was returned by the processing of this step
*/
protected int errorFlag;
/**
* A list of fields that may be in error, not all stages support
* errored fields but if they do then this is where a list of all
* fields in error may be found.
*/
protected java.util.List<String> errorFields;
/** The parameters that are required by this submissions / workflow step */
protected boolean requireSubmission = false;
protected boolean requireWorkflow = false;
protected boolean requireWorkspace = false;
protected boolean requireStep = false;
protected boolean requireHandle = false;
/**
* Grab all the page's parameters from the sitemap. This includes
* workspaceID, step, and a list of errored fields.
*
* If the implementer set any required parameters then insure that
* they are all present.
*/
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters)
throws ProcessingException, SAXException, IOException
{
super.setup(resolver,objectModel,src,parameters);
try {
this.id = parameters.getParameter("id",null);
this.stepAndPage = new StepAndPage(parameters.getParameter("step","-1.-1"));
log.debug("AbstractStep.setup: step is " + parameters.getParameter("step","]defaulted[")); // FIXME mhw
this.handle = parameters.getParameter("handle",null);
this.errorFlag = Integer.valueOf(parameters.getParameter("error", String.valueOf(AbstractProcessingStep.STATUS_COMPLETE)));
this.errorFields = getErrorFields(parameters);
//load in-progress submission
if (this.id != null)
{
this.submissionInfo = FlowUtils.obtainSubmissionInfo(objectModel, this.id);
this.submission = submissionInfo.getSubmissionItem();
}
// Check required error conditions
if (this.requireSubmission && this.submission == null)
{
throw new ProcessingException("Unable to find submission for id: " + this.id);
}
if (this.requireWorkflow && !(submission instanceof WorkflowItem))
{
throw new ProcessingException("The submission is not a workflow, " + this.id);
}
if (this.requireWorkspace && !(submission instanceof WorkspaceItem))
{
throw new ProcessingException("The submission is not a workspace, " + this.id);
}
if (this.requireStep && stepAndPage.getStep() < 0)
{
throw new ProcessingException("Step is a required parameter.");
}
if (this.requireHandle && handle == null)
{
throw new ProcessingException("Handle is a required parameter.");
}
}
catch (SQLException sqle)
{
throw new ProcessingException("Unable to find submission.",sqle);
}
}
/**
* Base pageMeta that is added to ALL submission stages
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
if (submission instanceof WorkspaceItem)
{
pageMeta.addMetadata("title").addContent(T_submission_title);
Collection collection = submission.getCollection();
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
HandleUtil.buildHandleTrail(collection,pageMeta,contextPath);
pageMeta.addTrail().addContent(T_submission_trail);
}
else if (submission instanceof WorkflowItem)
{
pageMeta.addMetadata("title").addContent(T_workflow_title);
Collection collection = submission.getCollection();
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
HandleUtil.buildHandleTrail(collection,pageMeta,contextPath);
pageMeta.addTrail().addContent(T_workflow_trail);
}
else
{
// defaults for pages that don't have a workspace item or workflow
// item such as the submission complete page where the object is in transition.
pageMeta.addMetadata("title").addContent(T_default_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_default_trail);
}
}
/**
* Add a submission progress list to the current div for this step.
*
* @param div The division to add the list to.
*/
public void addSubmissionProgressList(Division div) throws WingException
{
//each entry in progress bar is placed under this "submit-progress" div
List progress = div.addList("submit-progress",List.TYPE_PROGRESS);
//get Map of progress bar information
//key: entry # (i.e. step & page),
//value: entry name key (i.e. display name)
Map<String, String> progBarInfo = this.submissionInfo.getProgressBarInfo();
//add each entry to progress bar
for (Map.Entry<String, String> progBarEntry : progBarInfo.entrySet())
{
//Since we are using XML-UI, we need to prepend the heading key with "xmlui.Submission."
String entryNameKey = "xmlui.Submission." + progBarEntry.getValue();
//the value of entryNum is current step & page
//(e.g. 1.2 is page 2 of step 1)
StepAndPage currentStepAndPage = new StepAndPage(progBarEntry.getKey());
//add a button to progress bar for this step & page
addJumpButton(progress, message(entryNameKey), currentStepAndPage);
}
}
/**
* Adds a single "jump-to" button, which when clicked will
* jump the user directly to a particular step within the
* submission process.
* <P>
* This method is used by the addSubmissionProgressList() method
* to create the progress bar at the top of the submission process.
* <P>
* This method is also used by the ReviewStep to add buttons to
* jump back to a particular step in the submission process
*
* @param list
* The List which the button will be added to
* @param buttonText
* The text to be displayed on the button
* @param stepAndPage
* The step and page (a double of the form 'step.page', e.g. 1.2)
* which this button will jump back to
*/
public void addJumpButton(List list, Message buttonText, StepAndPage stepAndPage)
throws WingException
{
//Only add the button if we have button text and a valid step & page!
if(buttonText!=null && stepAndPage.isSet())
{
//add a Jump To button for this section
Button jumpButton = list.addItem("step_" + stepAndPage, renderJumpButton(stepAndPage))
.addButton(AbstractProcessingStep.PROGRESS_BAR_PREFIX + stepAndPage);
jumpButton.setValue(buttonText);
}
}
/**
* Adds the "<-Previous", "Save/Cancel" and "Next->" buttons
* to a given form. This method ensures that the same
* default control/paging buttons appear on each submission page.
* <P>
* Note: A given step may define its own buttons as necessary,
* and not call this method (since it must be explicitly invoked by
* the step's addBody() method)
*
* @param controls
* The List which will contain all control buttons
*/
public void addControlButtons(List controls)
throws WingException
{
Item actions = controls.addItem();
//only have "<-Previous" button if not first step
if(!isFirstStep())
{
actions.addButton(AbstractProcessingStep.PREVIOUS_BUTTON).setValue(T_previous);
}
//always show "Save/Cancel"
actions.addButton(AbstractProcessingStep.CANCEL_BUTTON).setValue(T_save);
//If last step, show "Complete Submission"
if(isLastStep())
{
actions.addButton(AbstractProcessingStep.NEXT_BUTTON).setValue(T_complete);
}
else //otherwise, show "Next->"
{
actions.addButton(AbstractProcessingStep.NEXT_BUTTON).setValue(T_next);
}
}
/**
* Get current step number
*
* @return step number
*/
public int getStep()
{
return this.stepAndPage.getStep();
}
/**
* Get number of the current page within the current step
*
* @return page number (within current step)
*/
public int getPage()
{
return this.stepAndPage.getPage();
}
/**
* Return whether this is the first step in
* the submission process (the first step is
* currently considered the first that appears
* in the progress bar)
*
* @return true if first step
*/
public boolean isFirstStep()
{
Set submissionPagesSet = submissionInfo.getProgressBarInfo().keySet();
String[] submissionPages = (String[]) submissionPagesSet.toArray(new String[submissionPagesSet.size()]);
StepAndPage firstStepAndPage = new StepAndPage(submissionPages[0]);
return firstStepAndPage.equals(stepAndPage);
}
/**
* Return whether this is the last step in
* the submission process (the last step is
* currently considered the one directly *before*
* the Complete step in the progress bar)
*
* @return true if last step
*/
public boolean isLastStep()
{
boolean inWorkflow = this.submissionInfo.isInWorkflow();
Set submissionPagesSet = submissionInfo.getProgressBarInfo().keySet();
String[] submissionPages = (String[]) submissionPagesSet.toArray(new String[submissionPagesSet.size()]);
StepAndPage lastStepAndPage;
if(!inWorkflow)
{
// If not in Workflow,
// Last step is considered the one *before* the Complete Step
lastStepAndPage = new StepAndPage(submissionPages[submissionPages.length-2]);
}
else
{
lastStepAndPage = new StepAndPage(submissionPages[submissionPages.length-1]);
}
return lastStepAndPage.equals(stepAndPage);
}
/**
* Find the maximum step and page that the user has
* reached in the submission processes.
* If this submission is a workflow then return max-int.
*/
public StepAndPage getMaxStepAndPageReached() throws SQLException {
if (this.submission instanceof WorkspaceItem)
{
WorkspaceItem workspaceItem = (WorkspaceItem) submission;
int step = workspaceItem.getStageReached();
if(step<0)
{
step = 0;
}
int page = workspaceItem.getPageReached();
if (page < 0)
{
page = 0;
}
return new StepAndPage(step, page);
}
// This is a workflow, return infinity.
return new StepAndPage(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* Retrieve error fields from the list of parameters
* and return a List of all fields which had errors
*
* @return java.util.List of field names with errors
*/
public java.util.List<String> getErrorFields(Parameters parameters)
{
java.util.List<String> fields = new ArrayList<String>();
String errors = parameters.getParameter("error_fields","");
if (errors!=null && errors.length() > 0)
{
if(errors.indexOf(',') > 0)
{
fields = Arrays.asList(errors.split(","));
}
else//only one error field
{
fields.add(errors);
}
}
return fields;
}
/**
* A simple method to determine how the Jump to button
* for a given step and page should be rendered.
* <P>
* If the given step and page corresponds to the current
* step and page, render it with "current" style.
* <P>
* If the given step and page is greater than the max,
* render it with "disabled" style.
*
* @param givenStepAndPage
* This given step & page (e.g. (1,2))
* @return
* render style for this button
*/
private String renderJumpButton(StepAndPage givenStepAndPage)
{
try
{
if (givenStepAndPage.equals(this.stepAndPage))
{
return "current";
}
else if (givenStepAndPage.compareTo(getMaxStepAndPageReached())>0)
{
return "disabled";
}
else
{
return null;
}
}
catch(Exception e)
{
return null;
}
}
/**
* Recycle
*/
public void recycle()
{
this.id = null;
this.submission = null;
this.stepAndPage = new StepAndPage();
this.handle = null;
this.errorFlag = 0;
this.errorFields = 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.submission;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Holds a step number and a page number within that step.
*
* @author Mark Wood
*/
public class StepAndPage implements Comparable<StepAndPage>
{
/** Magic value meaning "no value" */
private static final int UNSET = -1;
/** Step number */
private int step;
/** Page number within step */
private int page;
/** Default constructor returns an unset instance */
public StepAndPage()
{
step = UNSET;
page = UNSET;
}
/**
* Initialize a new StepAndPage from given step and page numbers
*
* @param step
* @param page
*/
public StepAndPage(int step, int page)
{
this.step = step;
this.page = page;
}
/**
* Initialize a new StepAndPage by parsing a string of the form "step.page".
*
* @param asString
* decimal step and page numbers separated by a period.
*/
public StepAndPage(String asString)
{
String[] components = asString.split("\\.");
if (components.length > 0)
{
step = Integer.parseInt(components[0]);
if (components.length > 1)
{
page = Integer.parseInt(components[1]);
}
else
{
page = UNSET;
}
}
else
{
step = UNSET;
}
}
public int getStep()
{
return step;
}
public int getPage()
{
return page;
}
/**
* Does this instance have a value?
*
* @return true if step and page have been set
*/
public boolean isSet()
{
return (step != UNSET) && (page != UNSET);
}
/**
* Compare this StepAndPage with another
*
* @param other
* @return true if both objects have same step value and same page value.
*/
public boolean equals(Object other)
{
if (other instanceof StepAndPage)
{
StepAndPage sapOther = (StepAndPage)other;
return (this.step == sapOther.step) && (this.page == sapOther.page);
}
return false;
}
@Override
public int hashCode()
{
return new HashCodeBuilder().append(step).append(page).hashCode();
}
@Override
public String toString()
{
return Integer.toString(step) + "." + Integer.toString(page);
}
@Override
public int compareTo(StepAndPage o)
{
if (this.step == o.step)
{
return this.page - o.page;
}
else
{
return this.step - o.step;
}
}
} | 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.browseArtifacts;
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.HandleUtil;
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.authorize.AuthorizeException;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* Navigation that adds code needed for the browse features from dspace
*
* @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 {
/** Language Strings */
private static final Message T_head_all_of_dspace =
message("xmlui.ArtifactBrowser.Navigation.head_all_of_dspace");
private static final Message T_head_browse =
message("xmlui.ArtifactBrowser.Navigation.head_browse");
private static final Message T_communities_and_collections =
message("xmlui.ArtifactBrowser.Navigation.communities_and_collections");
private static final Message T_head_this_collection =
message("xmlui.ArtifactBrowser.Navigation.head_this_collection");
private static final Message T_head_this_community =
message("xmlui.ArtifactBrowser.Navigation.head_this_community");
/**
* 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;
}
/**
* Add the basic navigational options:
*
* browse - browse by Titles - browse by Authors - browse by Dates
*
* language FIXME: add languages
*
* context no context options are added.
*
* action no action options are added.
*/
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
*/
List browse = options.addList("browse");
options.addList("account");
options.addList("context");
options.addList("administrative");
browse.setHead(T_head_browse);
List browseGlobal = browse.addList("global");
List browseContext = browse.addList("context");
browseGlobal.setHead(T_head_all_of_dspace);
browseGlobal.addItemXref(contextPath + "/community-list",T_communities_and_collections);
// Add the configured browse lists for 'top level' browsing
addBrowseOptions(browseGlobal, contextPath + "/browse");
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
{
if (dso instanceof Item)
{
// If we are an item change the browse scope to the parent
// collection.
dso = ((Item) dso).getOwningCollection();
}
if (dso instanceof Collection)
{
browseContext.setHead(T_head_this_collection);
}
if (dso instanceof Community)
{
browseContext.setHead(T_head_this_community);
}
// Add the configured browse lists for scoped browsing
String handle = dso.getHandle();
addBrowseOptions(browseContext, contextPath + "/handle/" + handle + "/browse");
}
}
/**
* Add navigation for the configured browse tables to the supplied list.
*
* @param browseList
* @param browseURL
* @throws WingException
*/
private void addBrowseOptions(List browseList, String browseURL) throws WingException
{
// FIXME Exception handling
try
{
// Get a Map of all the browse tables
BrowseIndex[] bis = BrowseIndex.getBrowseIndices();
for (BrowseIndex bix : bis)
{
// Create a Map of the query parameters for this link
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("type", bix.getName());
// Add a link to this browse
browseList.addItemXref(super.generateURL(browseURL, queryParams),
message("xmlui.ArtifactBrowser.Navigation.browse_" + bix.getName()));
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to get browse indicies", bex);
}
}
}
| 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.general;
import java.sql.SQLException;
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.authorize.AuthorizeException;
/**
* This class will add a simple notification div the DRI document. Typicaly
* this transformer is used after an action has been preformed to let the
* user know if an operation succeded or failed.
*
* The possible paramaters are:
*
* outcome: The outcome determines whether the notice is positive or negative.
* Possible values are: "success", "failure", or "netural". If no values are
* supplied then netural is assumed.
*
* header: An i18n dictionary key referencing the text that should be used
* as a header for this notice.
*
* message: An i18n dictionary key refrencing the text that should be used as
* the content for this notice.
*
* characters: Plain text string that should be used as the content for this
* notice. Normaly all messages should be i18n dictionary keys however this
* parameter is usefull for error messages that are not nessasarly translated.
*
* All parameters are optional but you must supply at least the message or the
* characters
*
*
*
* Examlpe:
* <map:transformer type="notice">
* <map:parameter name="outcome" value="success"/>
* <map:parameter name="message" value="xmlui.<aspect>.<class>.<type>"/>
* </map:transformer>
*
* @author Scott Phillips
* @author Alexey Maslov
*/
public class NoticeTransformer extends AbstractDSpaceTransformer
{
/** Language Strings */
private static final Message T_head =
message("xmlui.general.notice.default_head");
/**
* Add the notice div to the body.
*/
public void addBody(Body body) throws WingException, SQLException, AuthorizeException
{
String outcome = parameters.getParameter("outcome",null);
String header = parameters.getParameter("header",null);
String message = parameters.getParameter("message",null);
String characters = parameters.getParameter("characters",null);
if ((message == null || message.length() <= 0) &&
(characters == null || characters.length() <= 0))
{
throw new WingException("No message found.");
}
String rend = "notice";
if ("netural".equals(outcome))
{
rend += " netural";
}
else if ("success".equals(outcome))
{
rend += " success";
}
else if ("failure".equals(outcome))
{
rend += " failure";
}
Division div = body.addDivision("general-message",rend);
if ((header != null) && (!"".equals(header)))
{
div.setHead(message(header));
}
else
{
div.setHead(T_head);
}
if (message != null && message.length() > 0)
{
div.addPara(message(message));
}
if (characters != null && characters.length() > 0)
{
div.addPara(characters);
}
}
}
| 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.general;
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.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
/**
* Simple action to return a 304 (Not Modified) status, for when request
* had the If-modified-since header and resource has not been modified.
* Used in conjunction with IfModifiedSinceSelector
*
* @author Larry Stone
*/
public class NotModifiedAction extends AbstractAction
{
/**
* Return a 304 (Not Modified) status in the response.
*/
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);
httpResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED);
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.general;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import javax.servlet.http.HttpServletResponse;
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.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.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingConstants;
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.Attributes;
import org.xml.sax.SAXException;
/**
* This special comonent checks to see if the body element is empty (has no sub elements) and if
* it is then displays some page not found text.
*
* @author Scott Phillips
*/
public class PageNotFoundTransformer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_title =
message("xmlui.PageNotFound.title");
private static final Message T_head =
message("xmlui.PageNotFound.head");
private static final Message T_para1 =
message("xmlui.PageNotFound.para1");
private static final Message T_go_home =
message("xmlui.general.go_home");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
/** Where the body element is stored while we wait to see if it is empty */
private SAXEvent bodyEvent;
/** Have we determined that the body is empty, and hence a we should generate a page not found. */
private boolean bodyEmpty;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
Request request = ObjectModelHelper.getRequest(objectModel);
return HashUtil.hash(request.getSitemapURI());
}
/**
* Generate the cache validity object.
*
* The cache is always valid.
*/
public SourceValidity getValidity() {
return NOPValidity.SHARED_INSTANCE;
}
/**
* Receive notification of the beginning of a document.
*/
public void startDocument() throws SAXException
{
// Reset our parameters before starting a new document.
this.bodyEvent = null;
this.bodyEmpty = false;
super.startDocument();
}
/**
* Process the SAX event.
* @see org.xml.sax.ContentHandler#startElement
*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes attributes) throws SAXException
{
if (this.bodyEvent != null)
{
// If we have recorded the startElement for body and we are
// recieving another start event, then there must be something
// inside the body element, so we send the held body and carry
// on as normal.
sendEvent(this.bodyEvent);
this.bodyEvent = null;
}
if (WingConstants.DRI.URI.equals(namespaceURI) && Body.E_BODY.equals(localName))
{
// Save the element and see if there is anything inside the body.
this.bodyEvent = SAXEvent.startElement(namespaceURI,localName,qName,attributes);
return;
}
super.startElement(namespaceURI, localName, qName, attributes);
}
/**
* Process the SAX event.
* @see org.xml.sax.ContentHandler#endElement
*/
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException
{
if (this.bodyEvent != null && WingConstants.DRI.URI.equals(namespaceURI) && Body.E_BODY.equals(localName))
{
// If we are recieving an endElement event for body while we
// still have a startElement body event recorded then
// the body element must have been empty. In this case, record
// that the body is empty, and send both the start and end body events.
this.bodyEmpty = true;
// Sending the body will trigger the Wing framework to ask
// us if we want to add a body to the page.
sendEvent(this.bodyEvent);
this.bodyEvent = null;
}
super.endElement(namespaceURI, localName, qName);
}
/** What to add at the end of the body */
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
if (this.bodyEmpty)
{
Division notFound = body.addDivision("page-not-found","primary");
notFound.setHead(T_head);
notFound.addPara(T_para1);
notFound.addPara().addXref(contextPath + "/",T_go_home);
HttpServletResponse response = (HttpServletResponse)objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
/** What page metadata to add to the document */
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
if (this.bodyEmpty)
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
// Give theme a base trail
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
}
}
/**
* Send the given recorded sax event.
*/
public void sendEvent(SAXEvent event) throws SAXException
{
if (event.type == SAXEvent.EventType.START)
{
super.startElement(event.namespaceURI,event.localName,event.qName,event.attributes);
}
else if (event.type == SAXEvent.EventType.END)
{
super.endElement(event.namespaceURI,event.localName,event.qName);
}
}
/**
* This private class remembers start and end element SAX events.
*/
private static class SAXEvent {
public enum EventType { START, END };
protected EventType type = null;
protected String namespaceURI = null;
protected String localName = null;
protected String qName = null;
protected Attributes attributes = null;
/**
* Create a new StartElement recorded sax event.
*/
public static SAXEvent startElement(String namespaceURI, String localName, String qName, Attributes attributes)
{
SAXEvent event = new SAXEvent();
event.type = EventType.START;
event.namespaceURI = namespaceURI;
event.localName = localName;
event.qName = qName;
event.attributes = attributes;
return event;
}
/**
* Create a new EndElement recorded sax event.
*/
public static SAXEvent endElement(String namespaceURI, String localName, String qName)
{
SAXEvent event = new SAXEvent();
event.type = EventType.END;
event.namespaceURI = namespaceURI;
event.localName = localName;
event.qName = qName;
return event;
}
}
}
| 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.general;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.content.authority.ChoiceAuthorityManager;
import org.dspace.content.DCPersonName;
import org.dspace.core.ConfigurationManager;
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.Composite;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Hidden;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.Item;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.xmlui.wing.element.Button;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* Create the "lookup" popup window for Choice Control. It loads a selector
* via AJAX request, and transfers values (both text and authority/confidence)
* back to the indicated form fields in the window that launched it.
* Some necessary logic is in JavaScript, see choice-control.js.
*
* Expected Parameters:
* field - name of metadata field in "_" notation, eg: dc_contributor_author
* value - maybe-partial value of field
* formID - the @id of <form> tag in calling window containing the inputs we are to set.
* valueInput - @name of input field in DOM for value.
* authorityInput - @name of input field in DOM for authority value
* isRepeating - true if metadata value can be repeated
* isName - true if this is a name value (i.e. last/first boxes)
* start - starting index, default 0
* limit - maximum values to return, default 0 (none)
*
* Configuration Properties:
* xmlui.lookup.select.size = 12 (default, entries to show in SELECT widget.)
*
* For each FIELD, e.g. dc.contributor.author, these message properties
* will OVERRIDE the corresponding i18n message catalog entries:
* xmlui.lookup.field.FIELD.title = title of lookup page
* (e.g. xmlui.lookup.field.dc_contributor_author.title = Author..)
* xmlui.lookup.field.FIELD.nonauthority = template for "non-authority" label in options
* xmlui.lookup.field.FIELD.help = help message for single input
* (NOTE this is still required even for name inputs)
* xmlui.lookup.field.FIELD.help.last = help message for last name of Name-oriented input
* xmlui.lookup.field.FIELD.help.first = help message for first name of Name-oriented input
*
* @author Larry Stone
*/
public class ChoiceLookupTransformer extends AbstractDSpaceTransformer
{
private static final String CONFIG_PREFIX = "xmlui.lookup.field.";
/** Language Strings */
private static final String MESSAGE_PREFIX = "xmlui.ChoiceLookupTransformer.";
private static final Message T_title = message(MESSAGE_PREFIX+"title");
private static final Message T_add = message(MESSAGE_PREFIX+"add");
private static final Message T_accept = message(MESSAGE_PREFIX+"accept");
private static final Message T_more = message(MESSAGE_PREFIX+"more");
private static final Message T_cancel = message(MESSAGE_PREFIX+"cancel");
private static final Message T_results = message(MESSAGE_PREFIX+"results");
private static final Message T_fail = message(MESSAGE_PREFIX+"fail");
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
String field = null;
String value = null;
String formID = null;
String confIndicatorID = null;
boolean isName = false;
boolean isRepeating = false;
String valueInput = null;
String authorityInput = null;
int start = 0;
int limit = 0;
String collection = null;
// HTTP parameters:
try
{
field = parameters.getParameter("field");
value = parameters.getParameter("value");
formID = parameters.getParameter("formID");
confIndicatorID = parameters.getParameter("confIndicatorID");
isName = parameters.getParameterAsBoolean("isName", false);
isRepeating = parameters.getParameterAsBoolean("isRepeating", false);
valueInput = parameters.getParameter("valueInput");
authorityInput = parameters.getParameter("authorityInput");
String sStart = parameters.getParameter("start");
if (sStart != null)
{
start = atoi(sStart);
}
String sLimit = parameters.getParameter("limit");
if (sLimit != null)
{
limit = atoi(sLimit);
}
collection = parameters.getParameter("collection");
if (collection == null)
{
collection = "-1";
}
}
catch (org.apache.avalon.framework.parameters.ParameterException e)
{
throw new UIException("Missing a required parameter",e);
}
Division idiv = body.addInteractiveDivision("lookup", "", "get", "popup");
if (isFieldMessage(field, "title"))
{
idiv.setHead(getFieldMessage(field, "title"));
}
else
{
idiv.setHead(getFieldLabel(field, "title"));
}
List fl = idiv.addList("choicesList", "form", "choices-lookup");
fl.setHead(T_results);
// the <select> tag, and param values
Item selectItem = fl.addItem("select", "choices-lookup");
Select s = selectItem.addSelect("chooser", "choices-lookup");
s.setSize(ConfigurationManager.getIntProperty("xmlui.lookup.select.size", 12));
// parameters for javascript
Hidden h = selectItem.addHidden("paramField");
h.setValue(field);
h = selectItem.addHidden("paramValue");
h.setValue(value);
h = selectItem.addHidden("paramIsName");
h.setValue(String.valueOf(isName));
h = selectItem.addHidden("paramIsRepeating");
h.setValue(String.valueOf(isRepeating));
h = selectItem.addHidden("paramValueInput");
h.setValue(valueInput);
h = selectItem.addHidden("paramAuthorityInput");
h.setValue(authorityInput);
h = selectItem.addHidden("paramStart");
h.setValue(String.valueOf(start));
h = selectItem.addHidden("paramLimit");
h.setValue(String.valueOf(limit));
h = selectItem.addHidden("paramFormID");
h.setValue(formID);
h = selectItem.addHidden("paramConfIndicatorID");
h.setValue(confIndicatorID);
h = selectItem.addHidden("paramFail");
h.setValue(T_fail);
boolean isClosed = ChoiceAuthorityManager.getManager().isClosed(field);
h = selectItem.addHidden("paramIsClosed");
h.setValue(String.valueOf(isClosed));
h = selectItem.addHidden("paramCollection");
h.setValue(String.valueOf(collection));
if (!isClosed)
{
h = selectItem.addHidden("paramNonAuthority");
if (isFieldMessage(field, "nonauthority"))
{
h.setValue(getFieldMessage(field, "nonauthority"));
}
else
{
h.setValue(getFieldLabel(field, "nonauthority"));
}
}
h = selectItem.addHidden("contextPath");
h.setValue(contextPath);
// NOTE: the "spinner" indicator image gets added in the XSLT.
// the text input(s)
Item ti = fl.addItem("textFields", "choices-lookup");
Composite textItem = ti.addComposite("textFieldsComp", "choices-lookup");
Text t1 = textItem.addText("text1", "choices-lookup");
if (isName)
{
Text t2 = textItem.addText("text2", "choices-lookup");
DCPersonName dp = new DCPersonName(value);
t1.setValue(dp.getLastName());
t2.setValue(dp.getFirstNames());
if (isFieldMessage(field, "help.last"))
{
Message m = getFieldMessage(field, "help.last");
t1.setLabel(m);
t1.setHelp(m);
}
else
{
String m = getFieldLabel(field, "help.last");
t1.setLabel(m);
t1.setHelp(m);
}
if (isFieldMessage(field, "help.first"))
{
Message m = getFieldMessage(field, "help.first");
t2.setLabel(m);
t2.setHelp(m);
}
else
{
String m = getFieldLabel(field, "help.first");
t2.setLabel(m);
t2.setHelp(m);
}
}
else
{
t1.setValue(value);
if (isFieldMessage(field, "help"))
{
Message m = getFieldMessage(field, "help");
t1.setLabel(m);
t1.setHelp(m);
}
else
{
String m = getFieldLabel(field, "help");
t1.setLabel(m);
t1.setHelp(m);
}
}
// confirmation buttons
Item buttItem = fl.addItem("confirmation", "choices-lookup");
Button accept = buttItem.addButton("accept", "choices-lookup");
accept.setValue(isRepeating ? T_add : T_accept);
Button more = buttItem.addButton("more", "choices-lookup");
more.setDisabled();
more.setValue(T_more);
Button cancel = buttItem.addButton("cancel", "choices-lookup");
cancel.setValue(T_cancel);
}
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
// This invokes magic popup transformation in XSL - "framing.popup"
pageMeta.addMetadata("framing","popup").addContent("true");
}
/**
* Protocol to get custom and/or i18n strings:
* For label NAME,
* .. if config key xmlui.choices.FIELD.NAME is defined, and starts
* with "xmlui.", then it's a message key.
* .. if NO config key is defined, look for message
* xmlui.ChoiceLookupTransformer.field.FIELD.NAME
* .. otherwise take literal value from configuration
*/
// return true if configured (or lack thereof) value points to Message
private boolean isFieldMessage(String field, String name)
{
String cv = getFieldLabel(field, name);
return (cv == null || cv.startsWith("xmlui."));
}
// get field-specific label value
private String getFieldLabel(String field, String name)
{
return ConfigurationManager.getProperty(CONFIG_PREFIX+field+"."+name);
}
// get field-specific label value
private Message getFieldMessage(String field, String name)
{
String cv = getFieldLabel(field, name);
if (cv == null)
{
return message(MESSAGE_PREFIX + "field." + field + "." + name);
}
else
{
return message(cv);
}
}
private int atoi(String s)
{
try
{
return Integer.parseInt(s);
}
catch (Exception e) {}
return 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.aspect.general;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.matching.Matcher;
import org.apache.cocoon.sitemap.PatternException;
import org.dspace.app.xmlui.utils.HandleUtil;
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;
/**
* Test the current URL to see if it or any of it's parants match against the
* given handle.
*
* @author Scott Phillips
*/
public class HandleMatcher extends AbstractLogEnabled implements Matcher
{
/**
* Match method to see if the sitemap parameter exists. If it does have a
* value the parameter added to the array list for later sitemap
* substitution.
*
* @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
{
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return null;
}
DSpaceObject parent = dspaceObjectWalk(dso, pattern);
if (parent != null)
{
return new HashMap();
}
else
{
return null;
}
}
catch (SQLException sqle)
{
throw new PatternException("Unable to obtain DSpace Context", sqle);
}
}
/**
* Private method to determine if the parent hirearchy matches the given
* handle.
*
* @param dso
* The child DSO object.
* @param handle
* The Handle to test against.
* @return The matched DSO object or null if none found.
*/
private DSpaceObject dspaceObjectWalk(DSpaceObject dso, String handle)
throws SQLException
{
DSpaceObject current = dso;
while (current != null)
{
// Check if the current object has the handle we are looking for.
if (current.getHandle().equals(handle))
{
return current;
}
if (dso.getType() == Constants.ITEM)
{
current = ((Item) current).getOwningCollection();
}
else if (dso.getType() == Constants.COLLECTION)
{
current = ((Collection) current).getCommunities()[0];
}
else if (dso.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 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.general;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.matching.Matcher;
import org.apache.cocoon.sitemap.PatternException;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Constants;
import org.dspace.core.Context;
/**
* Test the current URL to see if the user has access to the described
* resources. The privelege tested against uses the pattern attribute, the
* possible values are listed in the DSpace Constant class.
*
* @author Scott Phillips
*/
public class HandleAuthorizedMatcher extends AbstractLogEnabled implements Matcher
{
/**
* Match method to see if the sitemap parameter exists. If it does have a
* value the parameter added to the array list for later sitemap
* substitution.
*
* @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
{
// Are we checking for *NOT* the action or the action.
boolean not = false;
int action = -1; // the action to check
if (pattern.startsWith("!"))
{
not = true;
pattern = pattern.substring(1);
}
for (int i=0; i< Constants.actionText.length; i++)
{
if (Constants.actionText[i].equals(pattern))
{
action = i;
}
}
// Is it a valid action?
if (action > 0 || action >= Constants.actionText.length)
{
getLogger().warn("Invalid action: '"+pattern+"'");
return null;
}
try
{
Context context = ContextUtil.obtainContext(objectModel);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return null;
}
boolean authorized = AuthorizeManager.authorizeActionBoolean(context, dso, action);
// XOR
if (not ^ authorized)
{
return new HashMap();
}
else
{
return null;
}
}
catch (SQLException sqle)
{
throw new PatternException("Unable to obtain DSpace Context", sqle);
}
}
}
| 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.general;
import java.util.Map;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.selection.Selector;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
/**
* This simple selector operates on the authenticated DSpace user and selects
* between two levels of access.
*
* <map:selector name="AuthenticatedSelector" src="org.dspace.app.xmlui.AuthenticatedSelector"/>
*
*
*
* <map:select type="AuthenticatedSelector">
* <map:when test="administrator">
* ...
* </map:when>
* <map:when test="eperson">
* ...
* </map:when>
* <map:otherwise>
* ...
* </map:otherwise>
* </map:select>
*
* There are only two defined test expressions: "administrator" and "eperson".
* Remember an administrator is also an eperson so if you need to check for
* administrators distinct from epersons that select must come first.
*
* @author Scott Phillips
*/
public class AuthenticatedSelector extends AbstractLogEnabled implements
Selector
{
private static Logger log = Logger.getLogger(AuthenticatedSelector.class);
/** Test expressiots */
public static final String EPERSON = "eperson";
public static final String ADMINISTRATOR = "administrator";
/**
* Determine if the authenticated eperson matches the given expression.
*/
public boolean select(String expression, Map objectModel,
Parameters parameters)
{
try
{
Context context = ContextUtil.obtainContext(objectModel);
EPerson eperson = context.getCurrentUser();
if (eperson == null)
{
// No one is authenticated.
return false;
}
if (EPERSON.equals(expression))
{
// At least someone is authenticated.
return true;
}
else if (ADMINISTRATOR.equals(expression))
{
// Is this eperson an administrator?
return AuthorizeManager.isAdmin(context);
}
// Otherwise return false;
return false;
}
catch (Exception e)
{
// Log it and returned no match.
log.error("Error selecting based on authentication status: "
+ e.getMessage());
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.aspect.general;
import java.util.Map;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.selection.Selector;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.Constants;
/**
* This simple selector looks for the If-Modified-Since header, and
* returns true if the Item in the request has not been modified since that
* date. The expression is ignored since the test is inherent in the request.
*
* Typical sitemap usage:
*
* <map:match type="HandleTypeMatcher" pattern="item">
* <map:select type="IfModifiedSinceSelector">
* <map:when test="true">
* <map:act type="NotModifiedAction"/>
* <map:serialize/>
* </map:when>
* <map:otherwise>
* <map:transform type="ItemViewer"/>
* <map:serialize type="xml"/>
* </map:otherwise>
* </map:select>
* </map:match>
*
* @author Larry Stone
*/
public class IfModifiedSinceSelector implements Selector
{
private static Logger log = Logger.getLogger(IfModifiedSinceSelector.class);
/**
* Check for If-Modified-Since header on request,
* and returns true if the Item should *not* be sent, i.e.
* if the response status should be 304 (HttpServletResponse.SC_NOT_MODIFIED).
*
* @param expression is ignored
* @param objectModel
* environment passed through via cocoon
* @return null or map containing value of sitemap parameter 'pattern'
*/
public boolean select(String expression, Map objectModel,
Parameters parameters)
{
try
{
Request request = ObjectModelHelper.getRequest(objectModel);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso.getType() == Constants.ITEM)
{
Item item = (Item) dso;
long modSince = request.getDateHeader("If-Modified-Since");
if (modSince != -1 && item.getLastModified().getTime() < modSince)
{
return true;
}
}
return false;
}
catch (Exception e)
{
log.error("Error selecting based on If-Modified-Since: "+e.toString());
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.aspect.general;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.matching.Matcher;
import org.apache.cocoon.sitemap.PatternException;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Constants;
/**
* Test the current URL to see if it contains a reference to a DSpaceObject, if
* it dose then the object type is compared against the given pattern. The
* matcher succeeds only if the object type matches. Valid expressions may be
* combined with a comma to produce a set of "OR" expressions.
*
* Thus if you want to match all handles that are communities or collections
* then use the pattern value of "community,collection".
*
* @author Scott Phillips
*/
public class HandleTypeMatcher extends AbstractLogEnabled implements Matcher
{
/** The community expression */
public static final String COMMUNITY_EXPRESSION = "community";
/** The collection expression */
public static final String COLLECITON_EXPRESSION = "collection";
/** The item expression */
public static final String ITEM_EXPRESSION = "item";
/**
* Match the encoded DSpaceObject against a specified type.
*
* @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
{
String[] expressions = pattern.split(",");
for (String expression : expressions)
{
if (!(COMMUNITY_EXPRESSION.equals(expression)
|| COLLECITON_EXPRESSION.equals(expression) || ITEM_EXPRESSION
.equals(expression)))
{
getLogger().warn("Invalid test pattern, '" + pattern + "', encountered.");
return null;
}
}
DSpaceObject dso = null;
try
{
// HandleUtil handles caching if needed.
dso = HandleUtil.obtainHandle(objectModel);
}
catch (SQLException sqle)
{
throw new PatternException("Unable to obtain DSpace Object", sqle);
}
if (dso == null)
{
return null;
}
Map<String, String> result = new HashMap<String, String>();
for (String expression : expressions)
{
if (ITEM_EXPRESSION.equals(expression)
&& dso.getType() == Constants.ITEM)
{
result.put("type", ITEM_EXPRESSION);
return result;
}
else if (COLLECITON_EXPRESSION.equals(expression)
&& dso.getType() == Constants.COLLECTION)
{
result.put("type", COLLECITON_EXPRESSION);
return result;
}
else if (COMMUNITY_EXPRESSION.equals(expression)
&& dso.getType() == Constants.COMMUNITY)
{
result.put("type", COMMUNITY_EXPRESSION);
return result;
}
}
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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
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.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.app.xmlui.wing.element.Para;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
/**
* This simple component will add a Search Box. It is intended for use on the front page.
*
* @author Scott Phillips
*/
public class FrontPageSearch extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
public static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_head =
message("xmlui.ArtifactBrowser.FrontPageSearch.head");
private static final Message T_para1 =
message("xmlui.ArtifactBrowser.FrontPageSearch.para1");
private static final Message T_go =
message("xmlui.general.go");
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
return "1";
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity()
{
return NOPValidity.SHARED_INSTANCE;
}
/**
* Add a page title and trail links.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent(T_dspace_home);
pageMeta.addTrailLink(contextPath, T_dspace_home);
// Add RSS links if available
String formats = ConfigurationManager.getProperty("webui.feed.formats");
if ( formats != null )
{
for (String format : formats.split(","))
{
// Remove the protocol number, i.e. just list 'rss' or' atom'
String[] parts = format.split("_");
if (parts.length < 1)
{
continue;
}
String feedFormat = parts[0].trim()+"+xml";
String feedURL = contextPath+"/feed/"+format.trim()+"/site";
pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
}
}
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Division search =
body.addInteractiveDivision("front-page-search",contextPath+"/search",Division.METHOD_GET,"primary");
search.setHead(T_head);
search.addPara(T_para1);
Para fields = search.addPara();
fields.addText("query");
fields.addButton("submit").setValue(T_go);
}
}
| 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.artifactbrowser;
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.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.Para;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.sql.SQLException;
/**
* Renders the search box for a community
*
* @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 CommunitySearch extends AbstractDSpaceTransformer {
private static final Message T_advanced_search_link=
message("xmlui.ArtifactBrowser.CommunityViewer.advanced_search_link");
private static final Message T_full_text_search =
message("xmlui.ArtifactBrowser.CommunityViewer.full_text_search");
private static final Message T_go =
message("xmlui.general.go");
/**
* Display a single community (and refrence any sub communites or
* collections)
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Community))
{
return;
}
// Set up the major variables
Community community = (Community) dso;
Division home = body.addDivision("community-home", "primary repository community");
Division search = home.addDivision("community-search-browse", "secondary search-browse");
// Search query
Division query = search.addInteractiveDivision("community-search",
contextPath + "/handle/" + community.getHandle() + "/search",
Division.METHOD_POST, "secondary search");
Para para = query.addPara("search-query", null);
para.addContent(T_full_text_search);
para.addContent(" ");
para.addText("query");
para.addContent(" ");
para.addButton("submit").setValue(T_go);
query.addPara().addXref(contextPath + "/handle/" + community.getHandle() + "/advanced-search", T_advanced_search_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.artifactbrowser;
import java.net.InetAddress;
import java.util.Date;
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.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.Email;
import org.dspace.core.I18nUtil;
import org.dspace.eperson.EPerson;
/**
* @author Scott Phillips
*/
public class SendFeedbackAction extends AbstractAction
{
/**
*
*/
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel,
String source, Parameters parameters) throws Exception
{
Request request = ObjectModelHelper.getRequest(objectModel);
String page = request.getParameter("page");
String address = request.getParameter("email");
String agent = request.getHeader("User-Agent");
String session = request.getSession().getId();
String comments = request.getParameter("comments");
// Obtain information from request
// The page where the user came from
String fromPage = request.getHeader("Referer");
// Prevent spammers and splogbots from poisoning the feedback page
String host = ConfigurationManager.getProperty("dspace.hostname");
String allowedReferrersString = ConfigurationManager.getProperty("mail.allowed.referrers");
String[] allowedReferrersSplit = null;
boolean validReferral = false;
if((allowedReferrersString != null) && (allowedReferrersString.length() > 0))
{
allowedReferrersSplit = allowedReferrersString.trim().split("\\s*,\\s*");
for(int i = 0; i < allowedReferrersSplit.length; i++)
{
if(fromPage.indexOf(allowedReferrersSplit[i]) != -1)
{
validReferral = true;
break;
}
}
}
String basicHost = "";
if ("localhost".equals(host) || "127.0.0.1".equals(host)
|| host.equals(InetAddress.getLocalHost().getHostAddress()))
{
basicHost = host;
}
else
{
// cut off all but the hostname, to cover cases where more than one URL
// arrives at the installation; e.g. presence or absence of "www"
int lastDot = host.lastIndexOf('.');
basicHost = host.substring(host.substring(0, lastDot).lastIndexOf('.'));
}
if ((fromPage == null) || ((fromPage.indexOf(basicHost) == -1) && (!validReferral)))
{
// N.B. must use old message catalog because Cocoon i18n is only available to transformed pages.
throw new AuthorizeException(I18nUtil.getMessage("feedback.error.forbidden"));
}
// User email from context
Context context = ContextUtil.obtainContext(objectModel);
EPerson loggedin = context.getCurrentUser();
String eperson = null;
if (loggedin != null)
{
eperson = loggedin.getEmail();
}
if (page == null || page.equals(""))
{
page = fromPage;
}
// Check all data is there
if ((address == null) || address.equals("")
|| (comments == null) || comments.equals(""))
{
// Either the user did not fill out the form or this is the
// first time they are visiting the page.
Map<String,String> map = new HashMap<String,String>();
map.put("page",page);
if (address == null || address.equals(""))
{
map.put("email", eperson);
}
else
{
map.put("email", address);
}
map.put("comments",comments);
return map;
}
// All data is there, send the email
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback"));
email.addRecipient(ConfigurationManager
.getProperty("feedback.recipient"));
email.addArgument(new Date()); // Date
email.addArgument(address); // Email
email.addArgument(eperson); // Logged in as
email.addArgument(page); // Referring page
email.addArgument(agent); // User agent
email.addArgument(session); // Session ID
email.addArgument(comments); // The feedback itself
// Replying to feedback will reply to email on form
email.setReplyTo(address);
// May generate MessageExceptions.
email.send();
// Finished, allow to pass.
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.artifactbrowser;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
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.ReferenceSet;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.*;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.sort.SortException;
import org.dspace.sort.SortOption;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Renders a list of recently submitted items for the community by using the dspace browse
*
* @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 CommunityRecentSubmissions extends AbstractDSpaceTransformer implements CacheableProcessingComponent {
private static final Logger log = Logger.getLogger(CommunityRecentSubmissions.class);
private static final Message T_head_recent_submissions =
message("xmlui.ArtifactBrowser.CommunityViewer.head_recent_submissions");
/** How many recent submissions to list */
private static final int RECENT_SUBMISSIONS = 5;
/** The cache of recently submitted items */
private java.util.List<BrowseItem> recentSubmittedItems;
/** Cached validity object */
private SourceValidity validity;
@Override
public Serializable getKey() {
try {
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return "0";
} // no item, something is wrong
return HashUtil.hash(dso.getHandle());
}
catch (SQLException sqle)
{
// Ignore all errors and just return that the component is not cachable.
return "0";
}
}
@Override
public SourceValidity getValidity() {
if (this.validity == null)
{
Community community = null;
try {
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return null;
}
if (!(dso instanceof Community))
{
return null;
}
community = (Community) dso;
DSpaceValidity validity = new DSpaceValidity();
validity.add(community);
// Recently submitted items
for (BrowseItem item : getRecentlySubmittedItems(community))
{
validity.add(item);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Ignore all errors and invalidate the cache.
}
}
return this.validity;
}
@Override
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException {
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Community))
{
return;
}
Community community = (Community) dso;
Division home = body.addDivision("community-home", "primary repository community");
java.util.List<BrowseItem> items = getRecentlySubmittedItems(community);
if(items.size() == 0)
{
return;
}
Division lastSubmittedDiv = home
.addDivision("community-recent-submission","secondary recent-submission");
lastSubmittedDiv.setHead(T_head_recent_submissions);
ReferenceSet lastSubmitted = lastSubmittedDiv.addReferenceSet(
"collection-last-submitted", ReferenceSet.TYPE_SUMMARY_LIST,
null, "recent-submissions");
for (BrowseItem item : items)
{
lastSubmitted.addReference(item);
}
}
/**
* Get the recently submitted items for the given community.
*
* @param community The community.
* @return List of recently submitted items
*/
@SuppressWarnings("unchecked")
private java.util.List<BrowseItem> getRecentlySubmittedItems(Community community)
throws SQLException
{
if (recentSubmittedItems != null)
{
return recentSubmittedItems;
}
String source = ConfigurationManager.getProperty("recent.submissions.sort-option");
int numRecentSubmissions = ConfigurationManager.getIntProperty("recent.submissions.count", RECENT_SUBMISSIONS);
if(numRecentSubmissions == 0)
{
return new ArrayList<BrowseItem>();
}
BrowserScope scope = new BrowserScope(context);
scope.setCommunity(community);
scope.setResultsPerPage(numRecentSubmissions);
// 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.recentSubmittedItems = be.browse(scope).getResults();
}
catch (SortException se)
{
log.error("Caught SortException", se);
}
catch (BrowseException bex)
{
log.error("Caught BrowseException", bex);
}
return this.recentSubmittedItems;
}
@Override
public void recycle() {
this.recentSubmittedItems = 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.artifactbrowser;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.element.*;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.statistics.*;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.ConfigurationManager;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import java.io.*;
import java.io.File;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/**
* Transformer to display statistics data in XML UI.
*
* Unlike the JSP interface that pre-generates HTML and stores in the reports folder,
* this class transforms the raw analysis data into a Wing representation
*/
public class StatisticsViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
private static final Logger log = Logger.getLogger(StatisticsViewer.class);
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_choose_report = message("xmlui.ArtifactBrowser.StatisticsViewer.choose_month");
private static final Message T_page_title = message("xmlui.ArtifactBrowser.StatisticsViewer.report.title");
private static final Message T_empty_title = message("xmlui.ArtifactBrowser.StatisticsViewer.no_report.title");
private static final Message T_empty_text = message("xmlui.ArtifactBrowser.StatisticsViewer.no_report.text");
private static final SimpleDateFormat sdfDisplay = new SimpleDateFormat("MM'/'yyyy");
private static final SimpleDateFormat sdfLink = new SimpleDateFormat("yyyy'-'M");
private boolean initialised = false;
private String reportDate = null;
private SourceValidity validity;
/**
* Get the caching key for this report
* @return
*/
public Serializable getKey()
{
initialise();
if (reportDate != null)
{
return reportDate;
}
return "general";
}
/**
* Generate the validity for this cached entry
* @return
*/
public SourceValidity getValidity()
{
if (validity == null)
{
try
{
initialise();
boolean showReport = ConfigurationManager.getBooleanProperty("report.public");
// If the report isn't public
if (!showReport)
{
try
{
// Administrators can always view reports
showReport = AuthorizeManager.isAdmin(context);
}
catch (SQLException sqle)
{
log.error("Unable to check for administrator", sqle);
}
}
// Only generate a validity if the report is visible
if (showReport)
{
File analysisFile = null;
// Get a file for the report data
if (reportDate != null)
{
analysisFile = StatisticsLoader.getAnalysisFor(reportDate);
}
else
{
analysisFile = StatisticsLoader.getGeneralAnalysis();
}
if (analysisFile != null)
{
// Generate the validity based on the properties of the report data file
DSpaceValidity newValidity = new DSpaceValidity();
newValidity.add(Long.toString(analysisFile.lastModified()));
newValidity.add("-");
newValidity.add(Long.toString(analysisFile.length()));
validity = newValidity.complete();
}
}
}
catch (Exception e)
{
}
}
return validity;
}
/**
* Add additional navigation options. This is to allow selection of a monthly report
*
* @param options
* @throws SAXException
* @throws WingException
* @throws UIException
* @throws SQLException
* @throws IOException
* @throws AuthorizeException
*/
public void addOptions(Options options) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Date[] monthlyDates = StatisticsLoader.getMonthlyAnalysisDates();
if (monthlyDates != null && monthlyDates.length > 0)
{
List statList = options.addList("statsreports");
statList.setHead(T_choose_report);
HashMap<String, String> params = new HashMap<String, String>();
for (Date date : monthlyDates)
{
params.put("date", sdfLink.format(date));
statList.addItemXref(super.generateURL("statistics", params), sdfDisplay.format(date));
}
}
}
/**
* Add title, etc. metadata
*
* @param pageMeta
* @throws SAXException
* @throws WingException
* @throws UIException
* @throws SQLException
* @throws IOException
* @throws AuthorizeException
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException,
SQLException, IOException, AuthorizeException
{
initialise();
pageMeta.addMetadata("title").addContent(T_page_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_page_title);
}
/**
* Output the body of the report
*
* @param body
* @throws SAXException
* @throws WingException
* @throws UIException
* @throws SQLException
* @throws IOException
* @throws AuthorizeException
*/
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException,
IOException, AuthorizeException
{
initialise();
boolean publicise = ConfigurationManager.getBooleanProperty("report.public");
// Check that the reports are either public, or user is an administrator
if (!publicise && !AuthorizeManager.isAdmin(context))
{
throw new AuthorizeException();
}
// Retrieve the report data to display
File analysisFile;
if (reportDate != null)
{
analysisFile = StatisticsLoader.getAnalysisFor(reportDate);
}
else
{
analysisFile = StatisticsLoader.getGeneralAnalysis();
}
// Create the renderer for the results
Division div = body.addDivision("statistics", "primary");
if (analysisFile != null)
{
try
{
// Generate the XML stream
Report myRep = new XMLUIReport(div);
ReportGenerator.processReport(context, myRep, analysisFile.getCanonicalPath());
}
catch (Exception e)
{
throw new UIException(e);
}
}
else
{
div.setHead(T_empty_title);
div.addPara(T_empty_text);
}
}
/**
* Initialise the member variables from the request
*/
private void initialise()
{
if (!initialised)
{
Request request = ObjectModelHelper.getRequest(objectModel);
reportDate = (String) request.getParameter("date");
initialised = true;
}
}
/**
* Clear the member variables so that the instance can be reused
*/
public void recycle()
{
initialised = false;
reportDate = null;
validity = null;
super.recycle();
}
/**
* Implementation of the Report interface, to output the statistics data for xmlui
* Note that all methods that return Strings return 'null' in this implementation, as
* all the outputting is done directly using the Wing framework.
*/
static class XMLUIReport implements Report
{
private java.util.List<Statistics> blocks = new ArrayList<Statistics>();
private String mainTitle = null;
private String pageTitle = null;
/** start date for report */
private Date start = null;
/** end date for report */
private Date end = null;
private Division rootDiv;
private Division currDiv;
/**
* Hide the default constructor, so that you have to pass in a Division
*/
private XMLUIReport() {}
/**
* Create instance, providing the Wing element that we will be adding to
*
* @param myDiv
*/
public XMLUIReport(Division myDiv)
{
rootDiv = myDiv;
currDiv = myDiv;
}
/**
* Get the header for the report - currently not supported
*
* @return
*/
public String header()
{
return header("");
}
// Currently not supported
public String header(String title)
{
return "";
}
/**
* Add the main title to the report
* @return
*/
public String mainTitle()
{
try
{
rootDiv.setHead(mainTitle);
}
catch (WingException we)
{
log.error("Error creating XML for report", we);
}
return null;
}
/**
* Output the date range for this report
* @return
*/
public String dateRange()
{
StringBuilder content = new StringBuilder();
DateFormat df = DateFormat.getDateInstance();
if (start != null)
{
content.append(df.format(start));
}
else
{
content.append("from start of records ");
}
content.append(" to ");
if (end != null)
{
content.append(df.format(end));
}
else
{
content.append(" end of records");
}
try
{
rootDiv.addDivision("reportDate").addPara(content.toString());
}
catch (WingException we)
{
log.error("Error creating XML for report", we);
}
return null;
}
/**
* Output the section header
* @param title
* @return
*/
public String sectionHeader(String title)
{
try
{
currDiv.setHead(title);
}
catch (WingException we)
{
log.error("Error creating XML for report", we);
}
return null;
}
/**
* Output the current statistics block
* @param content
* @return
*/
public String statBlock(Statistics content)
{
Stat[] stats = content.getStats();
try
{
int rows = stats.length;
if (content.getStatName() != null || content.getResultName() != null)
{
rows++;
}
Table block = currDiv.addTable("reportBlock", rows, 2);
// prepare the table headers
if (content.getStatName() != null || content.getResultName() != null)
{
Row row = block.addRow();
if (content.getStatName() != null)
{
row.addCellContent(content.getStatName());
}
else
{
row.addCellContent(" ");
}
if (content.getResultName() != null)
{
row.addCellContent(content.getResultName());
}
else
{
row.addCellContent(" ");
}
}
// output the statistics in the table
for (int i = 0; i < stats.length; i++)
{
Row row = block.addRow();
if (stats[i].getReference() != null)
{
row.addCell().addXref(stats[i].getReference()).addContent(label(stats[i].getKey()));
}
else
{
row.addCell().addContent(label(stats[i].getKey()));
}
if (stats[i].getUnits() != null)
{
row.addCell(null, null, "right").addContent(entry(stats[i].getValue() + " " + stats[i].getUnits()));
}
else
{
row.addCell(null, null, "right").addContent(entry(ReportTools.numberFormat(stats[i].getValue())));
}
}
}
catch (WingException we)
{
log.error("Error creating XML for report", we);
}
return null;
}
/**
* Output any information about the lower boundary restriction for this section
* @param floor
* @return
*/
public String floorInfo(int floor)
{
try
{
if (floor > 0)
{
currDiv.addDivision("reportFloor").addPara("(more than " + ReportTools.numberFormat(floor) + " times)");
}
}
catch (WingException we)
{
log.error("Error creating XML for report", we);
}
return null;
}
/**
* Output an explanation for this section
*
* @param explanation
* @return
*/
public String blockExplanation(String explanation)
{
try
{
if (explanation != null)
{
currDiv.addDivision("reportExplanation").addPara(explanation);
}
}
catch (WingException we)
{
log.error("Error creating XML for report", we);
}
return null;
}
/**
* Output the footer
*
* @return
*/
public String footer()
{
return "";
}
/**
* Set the main title for this report
*
* @param name
* @param serverName
*/
public void setMainTitle(String name, String serverName)
{
mainTitle = "Statistics for " + name;
if (ConfigurationManager.getBooleanProperty("report.show.server", true))
{
mainTitle += " on " + serverName;
}
if (pageTitle == null)
{
pageTitle = mainTitle;
}
return;
}
/**
* Add a block to report on
*
* @param stat
*/
public void addBlock(Statistics stat)
{
blocks.add(stat);
return;
}
/**
* Render the statistics into an XML stream
* @return
*/
public String render()
{
Pattern space = Pattern.compile(" ");
// Output the heading information
header(pageTitle);
mainTitle();
dateRange();
// Loop through all the sections
for (Statistics stats : blocks)
{
// navigation();
try
{
String title = stats.getSectionHeader();
String aName = title.toLowerCase();
Matcher matchSpace = space.matcher(aName);
aName = matchSpace.replaceAll("_");
// Create a new division for each section
currDiv = rootDiv.addDivision(aName);
sectionHeader(title);
// topLink();
blockExplanation(stats.getExplanation());
floorInfo(stats.getFloor());
statBlock(stats);
currDiv = rootDiv;
}
catch (WingException we)
{
log.error("Error creating XML for report", we);
}
}
return null;
}
/**
* Set the start date for this report
* @param start
*/
public void setStartDate(Date start)
{
this.start = start;
}
/**
* Set the end date for this report
* @param end
*/
public void setEndDate(Date end)
{
this.end = end;
}
}
/**
* Protect the display from excessively wrong data, typically this occures if a long word finds it's way
* into the data that is not breakable by the browser because there is no space, dash, period, or other
* delimiter character. This just prevents the page from blowing up when bad data is being presented.
*/
private static final int MAX_ENTRY_LENGTH = 50;
private static String entry(String entry)
{
if (entry != null && entry.length() > MAX_ENTRY_LENGTH)
{
entry = entry.substring(0, MAX_ENTRY_LENGTH - 3) + "...";
}
return entry;
}
private static final int MAX_LABEL_LENGTH = 100;
private static String label(String label)
{
if (label != null && label.length() > MAX_LABEL_LENGTH)
{
label = label.substring(0, MAX_LABEL_LENGTH - 3) + "...";
}
return label;
}
}
| 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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
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.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
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.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.Reference;
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.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.LogManager;
import org.xml.sax.SAXException;
/**
* Display a list of Communities and collections.
*
* This item may be configured so that it will only display to a specific depth,
* and may include or exclude collections from the tree.
*
* The configuration option available: <depth exclude-collections="true">999</depth>
*
* @author Scott Phillips
*/
public class CommunityBrowser extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
private static Logger log = Logger.getLogger(CommunityBrowser.class);
/** Language Strings */
public static final Message T_dspace_home =
message("xmlui.general.dspace_home");
public static final Message T_title =
message("xmlui.ArtifactBrowser.CommunityBrowser.title");
public static final Message T_trail =
message("xmlui.ArtifactBrowser.CommunityBrowser.trail");
public static final Message T_head =
message("xmlui.ArtifactBrowser.CommunityBrowser.head");
public static final Message T_select =
message("xmlui.ArtifactBrowser.CommunityBrowser.select");
/** Should collections be excluded from the list */
protected boolean excludeCollections = false;
/** The default depth if one is not provided by the sitemap */
private static final int DEFAULT_DEPTH = 999;
/** What depth is the maximum depth of the tree */
protected int depth = DEFAULT_DEPTH;
/** Cached version the community / collection hierarchy */
protected TreeNode root;
/** cached validity object */
private SourceValidity validity;
/**
* Set the component up, pulling any configuration values from the sitemap
* parameters.
*/
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
super.setup(resolver, objectModel, src, parameters);
depth = parameters.getParameterAsInteger("depth", DEFAULT_DEPTH);
excludeCollections = parameters.getParameterAsBoolean(
"exclude-collections", false);
}
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
boolean full = ConfigurationManager.getBooleanProperty("xmlui.community-list.render.full", true);
return HashUtil.hash(depth + "-" + excludeCollections + "-" + (full ? "true" : "false"));
}
/**
* Generate the cache validity object.
*
* The validity object will include a list of all communities
* & collection being browsed along with there logo bitstreams.
*/
public SourceValidity getValidity()
{
if (validity == null)
{
try {
DSpaceValidity validity = new DSpaceValidity();
TreeNode root = buildTree(Community.findAllTop(context));
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.empty())
{
TreeNode node = stack.pop();
validity.add(node.getDSO());
for (TreeNode child : node.getChildren())
{
stack.push(child);
}
}
// Check if we are configured to assume validity.
String assumeCacheValidity = ConfigurationManager.getProperty("xmlui.community-list.cache");
if (assumeCacheValidity != null)
{
validity.setAssumedValidityDelay(assumeCacheValidity);
}
this.validity = validity.complete();
}
catch (SQLException sqle)
{
// ignore all errors and return an invalid cache.
}
log.info(LogManager.getHeader(context, "view_community_list", ""));
}
return this.validity;
}
/**
* Add a page title and trail links.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
// Set the page title
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Add a community-browser division that includes references to community and
* collection metadata.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Division division = body.addDivision("comunity-browser", "primary");
division.setHead(T_head);
division.addPara(T_select);
TreeNode root = buildTree(Community.findAllTop(context));
boolean full = ConfigurationManager.getBooleanProperty("xmlui.community-list.render.full", true);
if (full)
{
ReferenceSet referenceSet = division.addReferenceSet("community-browser",
ReferenceSet.TYPE_SUMMARY_LIST,null,"hierarchy");
java.util.List<TreeNode> rootNodes = root.getChildrenOfType(Constants.COMMUNITY);
for (TreeNode node : rootNodes)
{
buildReferenceSet(referenceSet,node);
}
}
else
{
List list = division.addList("comunity-browser");
java.util.List<TreeNode> rootNodes = root.getChildrenOfType(Constants.COMMUNITY);
for (TreeNode node : rootNodes)
{
buildList(list,node);
}
}
}
/**
* Recursively build an includeset of the community / collection hierarchy based upon
* the given NodeTree.
*
* @param referenceSet The include set
* @param node The current node of the hierarchy.
*/
public void buildReferenceSet(ReferenceSet referenceSet, TreeNode node) throws WingException
{
DSpaceObject dso = node.getDSO();
Reference objectInclude = referenceSet.addReference(dso);
// Add all the sub-collections;
java.util.List<TreeNode> collectionNodes = node.getChildrenOfType(Constants.COLLECTION);
if (collectionNodes != null && collectionNodes.size() > 0)
{
ReferenceSet collectionSet = objectInclude.addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST);
for (TreeNode collectionNode : collectionNodes)
{
collectionSet.addReference(collectionNode.getDSO());
}
}
// Add all the sub-communities
java.util.List<TreeNode> communityNodes = node.getChildrenOfType(Constants.COMMUNITY);
if (communityNodes != null && communityNodes.size() > 0)
{
ReferenceSet communitySet = objectInclude.addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST);
for (TreeNode communityNode : communityNodes)
{
buildReferenceSet(communitySet,communityNode);
}
}
}
/**
* Recursively build a list of the community / collection hierarchy based upon
* the given NodeTree.
*
* @param list The parent list
* @param node The current node of the hierarchy.
*/
public void buildList(List list, TreeNode node) throws WingException
{
DSpaceObject dso = node.getDSO();
String name = null;
if (dso instanceof Community)
{
name = ((Community) dso).getMetadata("name");
}
else if (dso instanceof Collection)
{
name = ((Collection) dso).getMetadata("name");
}
String url = contextPath + "/handle/"+dso.getHandle();
list.addItem().addHighlight("bold").addXref(url, name);
List subList = null;
// Add all the sub-collections;
java.util.List<TreeNode> collectionNodes = node.getChildrenOfType(Constants.COLLECTION);
if (collectionNodes != null && collectionNodes.size() > 0)
{
subList = list.addList("sub-list-"+dso.getID());
for (TreeNode collectionNode : collectionNodes)
{
String collectionName = ((Collection) collectionNode.getDSO()).getMetadata("name");
String collectionUrl = contextPath + "/handle/"+collectionNode.getDSO().getHandle();
subList.addItemXref(collectionUrl, collectionName);
}
}
// Add all the sub-communities
java.util.List<TreeNode> communityNodes = node.getChildrenOfType(Constants.COMMUNITY);
if (communityNodes != null && communityNodes.size() > 0)
{
if (subList == null)
{
subList = list.addList("sub-list-" + dso.getID());
}
for (TreeNode communityNode : communityNodes)
{
buildList(subList,communityNode);
}
}
}
/**
* recycle
*/
public void recycle()
{
this.root = null;
this.validity = null;
super.recycle();
}
/**
* construct a tree structure of communities and collections. The results
* of this hierarchy are cached so calling it multiple times is acceptable.
*
* @param communities The root level communities
* @return A root level node.
*/
private TreeNode buildTree(Community[] communities) throws SQLException
{
if (root != null)
{
return root;
}
TreeNode newRoot = new TreeNode();
// Setup for breath-first traversal
Stack<TreeNode> stack = new Stack<TreeNode>();
for (Community community : communities)
{
stack.push(newRoot.addChild(community));
}
while (!stack.empty())
{
TreeNode node = stack.pop();
// Short circuit if we have reached our max depth.
if (node.getLevel() >= this.depth)
{
continue;
}
// Only communities nodes are pushed on the stack.
Community community = (Community) node.getDSO();
for (Community subcommunity : community.getSubcommunities())
{
stack.push(node.addChild(subcommunity));
}
// Add any collections to the document.
if (!excludeCollections)
{
for (Collection collection : community.getCollections())
{
node.addChild(collection);
}
}
}
this.root = newRoot;
return root;
}
/**
* Private class to represent the tree structure of communities & collections.
*/
protected static class TreeNode
{
/** The object this node represents */
private DSpaceObject dso;
/** The level in the hierarchy that this node is at. */
private int level;
/** All children of this node */
private java.util.List<TreeNode> children = new ArrayList<TreeNode>();
/**
* Construct a new root level node
*/
public TreeNode()
{
// Root level node is add the zero level.
this.level = 0;
}
/**
* @return The DSpaceObject this node represents
*/
public DSpaceObject getDSO()
{
return this.dso;
}
/**
* Add a child DSpaceObject
*
* @param dso The child
* @return A new TreeNode object attached to the tree structure.
*/
public TreeNode addChild(DSpaceObject dso)
{
TreeNode child = new TreeNode();
child.dso = dso;
child.level = this.level + 1;
children.add(child);
return child;
}
/**
* @return The current level in the hierarchy of this node.
*/
public int getLevel()
{
return this.level;
}
/**
* @return All children
*/
public java.util.List<TreeNode> getChildren()
{
return children;
}
/**
* @return All children of the given @type.
*/
public java.util.List<TreeNode> getChildrenOfType(int type)
{
java.util.List<TreeNode> results = new ArrayList<TreeNode>();
for (TreeNode node : children)
{
if (node.dso.getType() == type)
{
results.add(node);
}
}
return results;
}
}
}
| 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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
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.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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
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;
/**
* Display to the user a simple form letting the user give feedback.
*
* @author Scott Phillips
*/
public class FeedbackForm extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_title =
message("xmlui.ArtifactBrowser.FeedbackForm.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.FeedbackForm.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.FeedbackForm.head");
private static final Message T_para1 =
message("xmlui.ArtifactBrowser.FeedbackForm.para1");
private static final Message T_email =
message("xmlui.ArtifactBrowser.FeedbackForm.email");
private static final Message T_email_help =
message("xmlui.ArtifactBrowser.FeedbackForm.email_help");
private static final Message T_comments =
message("xmlui.ArtifactBrowser.FeedbackForm.comments");
private static final Message T_submit =
message("xmlui.ArtifactBrowser.FeedbackForm.submit");
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey() {
String email = parameters.getParameter("email","");
String comments = parameters.getParameter("comments","");
String page = parameters.getParameter("page","unknown");
return HashUtil.hash(email + "-" + comments + "-" + page);
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity()
{
return NOPValidity.SHARED_INSTANCE;
}
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 void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Build the item viewer division.
Division feedback = body.addInteractiveDivision("feedback-form",
contextPath+"/feedback",Division.METHOD_POST,"primary");
feedback.setHead(T_head);
feedback.addPara(T_para1);
List form = feedback.addList("form",List.TYPE_FORM);
Text email = form.addItem().addText("email");
email.setLabel(T_email);
email.setHelp(T_email_help);
email.setValue(parameters.getParameter("email",""));
TextArea comments = form.addItem().addTextArea("comments");
comments.setLabel(T_comments);
comments.setValue(parameters.getParameter("comments",""));
form.addItem().addButton("submit").setValue(T_submit);
feedback.addHidden("page").setValue(parameters.getParameter("page","unknown"));
}
}
| 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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.*;
import org.apache.cocoon.ResourceNotFoundException;
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.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.RequestUtils;
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.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseItem;
import org.dspace.browse.BrowserScope;
import org.dspace.sort.SortOption;
import org.dspace.sort.SortException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCDate;
import org.dspace.content.DSpaceObject;
import org.dspace.content.authority.ChoiceAuthorityManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.xml.sax.SAXException;
import javax.servlet.http.HttpServletResponse;
/**
* Implements all the browse functionality (browse by title, subject, authors,
* etc.) The types of browse available are configurable by the implementor. See
* dspace.cfg and documentation for instructions on how to configure.
*
* @author Graham Triggs
*/
public class ConfigurableBrowse extends AbstractDSpaceTransformer implements
CacheableProcessingComponent
{
private static final Logger log = Logger.getLogger(ConfigurableBrowse.class);
/**
* Static Messages for common text
*/
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_go = message("xmlui.general.go");
private static final Message T_update = message("xmlui.general.update");
private static final Message T_choose_month = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.choose_month");
private static final Message T_choose_year = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.choose_year");
private static final Message T_jump_year = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_year");
private static final Message T_jump_year_help = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_year_help");
private static final Message T_jump_select = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_select");
private static final Message T_starts_with = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.starts_with");
private static final Message T_starts_with_help = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.starts_with_help");
private static final Message T_sort_by = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.sort_by");
private static final Message T_order = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.order");
private static final Message T_no_results= message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.no_results");
private static final Message T_rpp = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.rpp");
private static final Message T_order_asc = message("xmlui.ArtifactBrowser.ConfigurableBrowse.order.asc");
private static final Message T_order_desc = message("xmlui.ArtifactBrowser.ConfigurableBrowse.order.desc");
private static final String BROWSE_URL_BASE = "browse";
/**
* These variables dictate when the drop down list of years is to break from
* 1 year increments, to 5 year increments, to 10 year increments, and
* finally to stop.
*/
private static final int ONE_YEAR_LIMIT = 10;
private static final int FIVE_YEAR_LIMIT = 30;
private static final int TEN_YEAR_LIMIT = 100;
/** The options for results per page */
private static final int[] RESULTS_PER_PAGE_PROGRESSION = {5,10,20,40,60,80,100};
/** Cached validity object */
private SourceValidity validity;
/** Cached UI parameters, results and messages */
private BrowseParams userParams;
private BrowseInfo browseInfo;
private Message titleMessage = null;
private Message trailMessage = null;
public Serializable getKey()
{
try
{
BrowseParams params = getUserParams();
String key = params.getKey();
if (key != null)
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
{
key += "-" + dso.getHandle();
}
return HashUtil.hash(key);
}
}
catch (RuntimeException re)
{
throw re;
}
catch (Exception e)
{
return "0";
}
return "0";
}
public SourceValidity getValidity()
{
if (validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
{
validity.add(dso);
}
BrowseInfo info = getBrowseInfo();
// Are we browsing items, or unique metadata?
if (isItemBrowse(info))
{
// Add the browse items to the validity
for (BrowseItem item : (java.util.List<BrowseItem>) info.getResults())
{
validity.add(item);
}
}
else
{
// Add the metadata to the validity
for (String[] singleEntry : browseInfo.getStringResults())
{
validity.add(singleEntry[0]+"#"+singleEntry[1]);
}
}
this.validity = validity.complete();
}
catch (RuntimeException re)
{
throw re;
}
catch (Exception e)
{
return null;
}
if (this.validity != null)
{
log.info(LogManager.getHeader(context, "browse", this.validity.toString()));
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException,
SQLException, IOException, AuthorizeException
{
BrowseInfo info = getBrowseInfo();
pageMeta.addMetadata("title").addContent(getTitleMessage(info));
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
if (dso != null)
{
HandleUtil.buildHandleTrail(dso, pageMeta, contextPath);
}
pageMeta.addTrail().addContent(getTrailMessage(info));
}
/**
* Add the browse-title division.
*/
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException,
IOException, AuthorizeException
{
BrowseParams params = null;
try {
params = getUserParams();
} catch (ResourceNotFoundException e) {
HttpServletResponse response = (HttpServletResponse)objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
BrowseInfo info = getBrowseInfo();
String type = info.getBrowseIndex().getName();
// Build the DRI Body
Division div = body.addDivision("browse-by-" + type, "primary");
div.setHead(getTitleMessage(info));
// Build the internal navigation (jump lists)
addBrowseJumpNavigation(div, info, params);
// Build the sort and display controls
addBrowseControls(div, info, params);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-" + type + "-results", "primary");
// If there are items to browse, add the pagination
int itemsTotal = info.getTotal();
if (itemsTotal > 0)
{
//results.setSimplePagination(itemsTotal, firstItemIndex, lastItemIndex, previousPage, nextPage)
results.setSimplePagination(itemsTotal, browseInfo.getOverallPosition() + 1,
browseInfo.getOverallPosition() + browseInfo.getResultCount(), getPreviousPageURL(
params, info), getNextPageURL(params, info));
// Reference all the browsed items
ReferenceSet referenceSet = results.addReferenceSet("browse-by-" + type,
ReferenceSet.TYPE_SUMMARY_LIST, type, null);
// Are we browsing items, or unique metadata?
if (isItemBrowse(info))
{
// Add the items to the browse results
for (BrowseItem item : (java.util.List<BrowseItem>) info.getResults())
{
referenceSet.addReference(item);
}
}
else // browsing a list of unique metadata entries
{
// Create a table for the results
Table singleTable = results.addTable("browse-by-" + type + "-results",
browseInfo.getResultCount() + 1, 1);
// Add the column heading
singleTable.addRow(Row.ROLE_HEADER).addCell().addContent(
message("xmlui.ArtifactBrowser.ConfigurableBrowse." + type + ".column_heading"));
// Iterate each result
for (String[] singleEntry : browseInfo.getStringResults())
{
// Create a Map of the query parameters for the link
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put(BrowseParams.TYPE, encodeForURL(type));
if (singleEntry[1] != null)
{
queryParams.put(BrowseParams.FILTER_VALUE[1], encodeForURL(
singleEntry[1]));
}
else
{
queryParams.put(BrowseParams.FILTER_VALUE[0], encodeForURL(
singleEntry[0]));
}
// Create an entry in the table, and a linked entry
Cell cell = singleTable.addRow().addCell();
cell.addXref(super.generateURL(BROWSE_URL_BASE, queryParams),
singleEntry[0]);
}
}
}
else
{
results.addPara(T_no_results);
}
}
/**
* Recycle
*/
public void recycle()
{
this.validity = null;
this.userParams = null;
this.browseInfo = null;
this.titleMessage = null;
this.trailMessage = null;
super.recycle();
}
/**
* Makes the jump-list navigation for the results
*
* @param div
* @param info
* @param params
* @throws WingException
*/
private void addBrowseJumpNavigation(Division div, BrowseInfo info, BrowseParams params)
throws WingException
{
// Prepare a Map of query parameters required for all links
Map<String, String> queryParamsGET = new HashMap<String, String>();
queryParamsGET.putAll(params.getCommonParametersEncoded());
queryParamsGET.putAll(params.getControlParameters());
Map<String, String> queryParamsPOST = new HashMap<String, String>();
queryParamsPOST.putAll(params.getCommonParameters());
queryParamsPOST.putAll(params.getControlParameters());
// Navigation aid (really this is a poor version of pagination)
Division jump = div.addInteractiveDivision("browse-navigation", BROWSE_URL_BASE,
Division.METHOD_POST, "secondary navigation");
// Add all the query parameters as hidden fields on the form
for (Map.Entry<String, String> param : queryParamsPOST.entrySet())
{
jump.addHidden(param.getKey()).setValue(param.getValue());
}
// If this is a date based browse, render the date navigation
if (isSortedByDate(info))
{
Para jumpForm = jump.addPara();
// Create a select list to choose a month
jumpForm.addContent(T_jump_select);
Select month = jumpForm.addSelect(BrowseParams.MONTH);
month.addOption(false, "-1", T_choose_month);
for (int i = 1; i <= 12; i++)
{
month.addOption(false, String.valueOf(i), DCDate.getMonthName(i, Locale
.getDefault()));
}
// Create a select list to choose a year
Select year = jumpForm.addSelect(BrowseParams.YEAR);
year.addOption(false, "-1", T_choose_year);
int currentYear = DCDate.getCurrent().getYear();
int i = currentYear;
// Calculate where to move from 1, 5 to 10 year jumps
int oneYearBreak = ((currentYear - ONE_YEAR_LIMIT) / 5) * 5;
int fiveYearBreak = ((currentYear - FIVE_YEAR_LIMIT) / 10) * 10;
int tenYearBreak = (currentYear - TEN_YEAR_LIMIT);
do
{
year.addOption(false, String.valueOf(i), String.valueOf(i));
if (i <= fiveYearBreak)
{
i -= 10;
}
else if (i <= oneYearBreak)
{
i -= 5;
}
else
{
i--;
}
}
while (i > tenYearBreak);
// Create a free text entry box for the year
jumpForm = jump.addPara();
jumpForm.addContent(T_jump_year);
jumpForm.addText(BrowseParams.STARTS_WITH).setHelp(T_jump_year_help);
jumpForm.addButton("submit").setValue(T_go);
}
else
{
// Create a clickable list of the alphabet
List jumpList = jump.addList("jump-list", List.TYPE_SIMPLE, "alphabet");
// browse params for each letter are all the query params
// WITHOUT the second-stage browse value, and add STARTS_WITH.
Map<String, String> letterQuery = new HashMap<String, String>(queryParamsGET);
for (String valueKey : BrowseParams.FILTER_VALUE)
{
letterQuery.remove(valueKey);
}
letterQuery.put(BrowseParams.STARTS_WITH, "0");
jumpList.addItemXref(super.generateURL(BROWSE_URL_BASE, letterQuery), "0-9");
for (char c = 'A'; c <= 'Z'; c++)
{
letterQuery.put(BrowseParams.STARTS_WITH, Character.toString(c));
jumpList.addItemXref(super.generateURL(BROWSE_URL_BASE, letterQuery), Character
.toString(c));
}
// Create a free text field for the initial characters
Para jumpForm = jump.addPara();
jumpForm.addContent(T_starts_with);
jumpForm.addText(BrowseParams.STARTS_WITH).setHelp(T_starts_with_help);
jumpForm.addButton("submit").setValue(T_go);
}
}
/**
* Add the controls to changing sorting and display options.
*
* @param div
* @param info
* @param params
* @throws WingException
*/
private void addBrowseControls(Division div, BrowseInfo info, BrowseParams params)
throws WingException
{
// Prepare a Map of query parameters required for all links
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.putAll(params.getCommonParameters());
Division controls = div.addInteractiveDivision("browse-controls", BROWSE_URL_BASE,
Division.METHOD_POST, "browse controls");
// Add all the query parameters as hidden fields on the form
for (Map.Entry<String, String> param : queryParams.entrySet())
{
controls.addHidden(param.getKey()).setValue(param.getValue());
}
Para controlsForm = controls.addPara();
// If we are browsing a list of items
if (isItemBrowse(info)) // && info.isSecondLevel()
{
try
{
// Create a drop down of the different sort columns available
Set<SortOption> sortOptions = SortOption.getSortOptions();
// Only generate the list if we have multiple columns
if (sortOptions.size() > 1)
{
controlsForm.addContent(T_sort_by);
Select sortSelect = controlsForm.addSelect(BrowseParams.SORT_BY);
for (SortOption so : sortOptions)
{
if (so.isVisible())
{
sortSelect.addOption(so.equals(info.getSortOption()), so.getNumber(),
message("xmlui.ArtifactBrowser.ConfigurableBrowse.sort_by." + so.getName()));
}
}
}
}
catch (SortException se)
{
throw new WingException("Unable to get sort options", se);
}
}
// Create a control to changing ascending / descending order
controlsForm.addContent(T_order);
Select orderSelect = controlsForm.addSelect(BrowseParams.ORDER);
orderSelect.addOption("ASC".equals(params.scope.getOrder()), "ASC", T_order_asc);
orderSelect.addOption("DESC".equals(params.scope.getOrder()), "DESC", T_order_desc);
// Create a control for the number of records to display
controlsForm.addContent(T_rpp);
Select rppSelect = controlsForm.addSelect(BrowseParams.RESULTS_PER_PAGE);
for (int i : RESULTS_PER_PAGE_PROGRESSION)
{
rppSelect.addOption((i == info.getResultsPerPage()), i, Integer.toString(i));
}
// Create a control for the number of authors per item to display
// FIXME This is currently disabled, as the supporting functionality
// is not currently present in xmlui
//if (isItemBrowse(info))
//{
// controlsForm.addContent(T_etal);
// Select etalSelect = controlsForm.addSelect(BrowseParams.ETAL);
//
// etalSelect.addOption((info.getEtAl() < 0), 0, T_etal_all);
// etalSelect.addOption(1 == info.getEtAl(), 1, Integer.toString(1));
//
// for (int i = 5; i <= 50; i += 5)
// {
// etalSelect.addOption(i == info.getEtAl(), i, Integer.toString(i));
// }
//}
controlsForm.addButton("update").setValue(T_update);
}
/**
* The URL query string of of the previous page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as appropriate by the caller.
*/
private String getPreviousPageURL(BrowseParams params, BrowseInfo info) throws SQLException,
UIException
{
// Don't create a previous page link if this is the first page
if (info.isFirst())
{
return null;
}
Map<String, String> parameters = new HashMap<String, String>();
parameters.putAll(params.getCommonParametersEncoded());
parameters.putAll(params.getControlParameters());
if (info.hasPrevPage())
{
parameters.put(BrowseParams.OFFSET, encodeForURL(String.valueOf(info.getPrevOffset())));
}
return super.generateURL(BROWSE_URL_BASE, parameters);
}
/**
* The URL query string of of the next page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as appropriate by the caller.
*/
private String getNextPageURL(BrowseParams params, BrowseInfo info) throws SQLException,
UIException
{
// Don't create a next page link if this is the last page
if (info.isLast())
{
return null;
}
Map<String, String> parameters = new HashMap<String, String>();
parameters.putAll(params.getCommonParametersEncoded());
parameters.putAll(params.getControlParameters());
if (info.hasNextPage())
{
parameters.put(BrowseParams.OFFSET, encodeForURL(String.valueOf(info.getNextOffset())));
}
return super.generateURL(BROWSE_URL_BASE, parameters);
}
/**
* Get the query parameters supplied to the browse.
*
* @return
* @throws SQLException
* @throws UIException
*/
private BrowseParams getUserParams() throws SQLException, UIException, ResourceNotFoundException, IllegalArgumentException {
if (this.userParams != null)
{
return this.userParams;
}
Context context = ContextUtil.obtainContext(objectModel);
Request request = ObjectModelHelper.getRequest(objectModel);
BrowseParams params = new BrowseParams();
params.month = request.getParameter(BrowseParams.MONTH);
params.year = request.getParameter(BrowseParams.YEAR);
params.etAl = RequestUtils.getIntParameter(request, BrowseParams.ETAL);
params.scope = new BrowserScope(context);
// Are we in a community or collection?
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso instanceof Community)
{
params.scope.setCommunity((Community) dso);
}
if (dso instanceof Collection)
{
params.scope.setCollection((Collection) dso);
}
try
{
String type = request.getParameter(BrowseParams.TYPE);
int sortBy = RequestUtils.getIntParameter(request, BrowseParams.SORT_BY);
if(!request.getParameters().containsKey("type"))
{
// default to first browse index.
String defaultBrowseIndex = ConfigurationManager.getProperty("webui.browse.index.1");
if(defaultBrowseIndex != null)
{
type = defaultBrowseIndex.split(":")[0];
}
}
BrowseIndex bi = BrowseIndex.getBrowseIndex(type);
if (bi == null)
{
throw new ResourceNotFoundException("Browse index " + type + " not found");
}
// If we don't have a sort column
if (sortBy == -1)
{
// Get the default one
SortOption so = bi.getSortOption();
if (so != null)
{
sortBy = so.getNumber();
}
}
else if (bi.isItemIndex() && !bi.isInternalIndex())
{
try
{
// If a default sort option is specified by the index, but it isn't
// the same as sort option requested, attempt to find an index that
// is configured to use that sort by default
// This is so that we can then highlight the correct option in the navigation
SortOption bso = bi.getSortOption();
SortOption so = SortOption.getSortOption(sortBy);
if ( bso != null && bso.equals(so))
{
BrowseIndex newBi = BrowseIndex.getBrowseIndex(so);
if (newBi != null)
{
bi = newBi;
type = bi.getName();
}
}
}
catch (SortException se)
{
throw new UIException("Unable to get sort options", se);
}
}
params.scope.setBrowseIndex(bi);
params.scope.setSortBy(sortBy);
params.scope.setJumpToItem(RequestUtils.getIntParameter(request, BrowseParams.JUMPTO_ITEM));
params.scope.setOrder(request.getParameter(BrowseParams.ORDER));
int offset = RequestUtils.getIntParameter(request, BrowseParams.OFFSET);
params.scope.setOffset(offset > 0 ? offset : 0);
params.scope.setResultsPerPage(RequestUtils.getIntParameter(request, BrowseParams.RESULTS_PER_PAGE));
params.scope.setStartsWith(decodeFromURL(request.getParameter(BrowseParams.STARTS_WITH)));
String filterValue = request.getParameter(BrowseParams.FILTER_VALUE[0]);
if (filterValue == null)
{
filterValue = request.getParameter(BrowseParams.FILTER_VALUE[1]);
params.scope.setAuthorityValue(filterValue);
}
params.scope.setFilterValue(filterValue);
params.scope.setJumpToValue(decodeFromURL(request.getParameter(BrowseParams.JUMPTO_VALUE)));
params.scope.setJumpToValueLang(decodeFromURL(request.getParameter(BrowseParams.JUMPTO_VALUE_LANG)));
params.scope.setFilterValueLang(decodeFromURL(request.getParameter(BrowseParams.FILTER_VALUE_LANG)));
// Filtering to a value implies this is a second level browse
if (params.scope.getFilterValue() != null)
{
params.scope.setBrowseLevel(1);
}
// if year and perhaps month have been selected, we translate these
// into "startsWith"
// if startsWith has already been defined then it is overwritten
if (params.year != null && !"".equals(params.year) && !"-1".equals(params.year))
{
String startsWith = params.year;
if ((params.month != null) && !"-1".equals(params.month) && !"".equals(params.month))
{
// subtract 1 from the month, so the match works
// appropriately
if ("ASC".equals(params.scope.getOrder()))
{
params.month = Integer.toString((Integer.parseInt(params.month) - 1));
}
// They've selected a month as well
if (params.month.length() == 1)
{
// Ensure double-digit month number
params.month = "0" + params.month;
}
startsWith = params.year + "-" + params.month;
if ("ASC".equals(params.scope.getOrder()))
{
startsWith = startsWith + "-32";
}
}
params.scope.setStartsWith(startsWith);
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to create browse parameters", bex);
}
this.userParams = params;
return params;
}
/**
* Get the results of the browse. If the results haven't been generated yet,
* then this will perform the browse.
*
* @return
* @throws SQLException
* @throws UIException
*/
private BrowseInfo getBrowseInfo() throws SQLException, UIException
{
if (this.browseInfo != null)
{
return this.browseInfo;
}
Context context = ContextUtil.obtainContext(objectModel);
// Get the parameters we will use for the browse
// (this includes a browse scope)
BrowseParams params = null;
try {
params = getUserParams();
} catch (ResourceNotFoundException e) {
return null;
}
try
{
// Create a new browse engine, and perform the browse
BrowseEngine be = new BrowseEngine(context);
this.browseInfo = be.browse(params.scope);
// figure out the setting for author list truncation
if (params.etAl < 0)
{
// there is no limit, or the UI says to use the default
int etAl = ConfigurationManager.getIntProperty("webui.browse.author-limit");
if (etAl != 0)
{
this.browseInfo.setEtAl(etAl);
}
}
else if (params.etAl == 0) // 0 is the user setting for unlimited
{
this.browseInfo.setEtAl(-1); // but -1 is the application
// setting for unlimited
}
else
// if the user has set a limit
{
this.browseInfo.setEtAl(params.etAl);
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to process browse", bex);
}
return this.browseInfo;
}
/**
* Is this a browse on a list of items, or unique metadata values?
*
* @param info
* @return
*/
private boolean isItemBrowse(BrowseInfo info)
{
return info.getBrowseIndex().isItemIndex() || info.isSecondLevel();
}
/**
* Is this browse sorted by date?
* @param info
* @return
*/
private boolean isSortedByDate(BrowseInfo info)
{
return info.getSortOption().isDate() ||
(info.getBrowseIndex().isDate() && info.getSortOption().isDefault());
}
private Message getTitleMessage(BrowseInfo info)
{
if (titleMessage == null)
{
BrowseIndex bix = info.getBrowseIndex();
// For a second level browse (ie. items for author),
// get the value we are focussing on (ie. author).
// (empty string if none).
String value = "";
if (info.hasValue())
{
if (bix.isAuthorityIndex())
{
ChoiceAuthorityManager cm = ChoiceAuthorityManager.getManager();
String fk = cm.makeFieldKey(bix.getMetadata(0));
value = "\""+cm.getLabel(fk, info.getValue(), null)+"\"";
}
else
{
value = "\"" + info.getValue() + "\"";
}
}
// Get the name of any scoping element (collection / community)
String scopeName = "";
if (info.getBrowseContainer() != null)
{
scopeName = info.getBrowseContainer().getName();
}
else
{
scopeName = "";
}
if (bix.isMetadataIndex())
{
titleMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.title.metadata." + bix.getName())
.parameterize(scopeName, value);
}
else if (info.getSortOption() != null)
{
titleMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.title.item." + info.getSortOption().getName())
.parameterize(scopeName, value);
}
else
{
titleMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.title.item." + bix.getSortOption().getName())
.parameterize(scopeName, value);
}
}
return titleMessage;
}
private Message getTrailMessage(BrowseInfo info)
{
if (trailMessage == null)
{
BrowseIndex bix = info.getBrowseIndex();
// Get the name of any scoping element (collection / community)
String scopeName = "";
if (info.getBrowseContainer() != null)
{
scopeName = info.getBrowseContainer().getName();
}
else
{
scopeName = "";
}
if (bix.isMetadataIndex())
{
trailMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.trail.metadata." + bix.getName())
.parameterize(scopeName);
}
else if (info.getSortOption() != null)
{
trailMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.trail.item." + info.getSortOption().getName())
.parameterize(scopeName);
}
else
{
trailMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.trail.item." + bix.getSortOption().getName())
.parameterize(scopeName);
}
}
return trailMessage;
}
}
/*
* Helper class to track browse parameters
*/
class BrowseParams
{
String month;
String year;
int etAl;
BrowserScope scope;
static final String MONTH = "month";
static final String YEAR = "year";
static final String ETAL = "etal";
static final String TYPE = "type";
static final String JUMPTO_ITEM = "focus";
static final String JUMPTO_VALUE = "vfocus";
static final String JUMPTO_VALUE_LANG = "vfocus_lang";
static final String ORDER = "order";
static final String OFFSET = "offset";
static final String RESULTS_PER_PAGE = "rpp";
static final String SORT_BY = "sort_by";
static final String STARTS_WITH = "starts_with";
static final String[] FILTER_VALUE = new String[]{"value","authority"};
static final String FILTER_VALUE_LANG = "value_lang";
/*
* Creates a map of the browse options common to all pages (type / value /
* value language)
*/
Map<String, String> getCommonParameters() throws UIException
{
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put(BrowseParams.TYPE, scope.getBrowseIndex().getName());
if (scope.getFilterValue() != null)
{
paramMap.put(scope.getAuthorityValue() != null?
BrowseParams.FILTER_VALUE[1]:BrowseParams.FILTER_VALUE[0], scope.getFilterValue());
}
if (scope.getFilterValueLang() != null)
{
paramMap.put(BrowseParams.FILTER_VALUE_LANG, scope.getFilterValueLang());
}
return paramMap;
}
Map<String, String> getCommonParametersEncoded() throws UIException
{
Map<String, String> paramMap = getCommonParameters();
Map<String, String> encodedParamMap = new HashMap<String, String>();
for (Map.Entry<String, String> param : paramMap.entrySet())
{
encodedParamMap.put(param.getKey(), AbstractDSpaceTransformer.encodeForURL(param.getValue()));
}
return encodedParamMap;
}
/*
* Creates a Map of the browse control options (sort by / ordering / results
* per page / authors per item)
*/
Map<String, String> getControlParameters() throws UIException
{
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put(BrowseParams.SORT_BY, Integer.toString(this.scope.getSortBy()));
paramMap
.put(BrowseParams.ORDER, AbstractDSpaceTransformer.encodeForURL(this.scope.getOrder()));
paramMap.put(BrowseParams.RESULTS_PER_PAGE, Integer
.toString(this.scope.getResultsPerPage()));
paramMap.put(BrowseParams.ETAL, Integer.toString(this.etAl));
return paramMap;
}
String getKey()
{
try
{
String key = "";
key += "-" + scope.getBrowseIndex().getName();
key += "-" + scope.getBrowseLevel();
key += "-" + scope.getStartsWith();
key += "-" + scope.getOrder();
key += "-" + scope.getResultsPerPage();
key += "-" + scope.getSortBy();
key += "-" + scope.getSortOption().getNumber();
key += "-" + scope.getOffset();
key += "-" + scope.getJumpToItem();
key += "-" + scope.getFilterValue();
key += "-" + scope.getFilterValueLang();
key += "-" + scope.getJumpToValue();
key += "-" + scope.getJumpToValueLang();
key += "-" + etAl;
return key;
}
catch (RuntimeException re)
{
throw re;
}
catch (Exception e)
{
return null; // ignore exception and return no key
}
}
};
| 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.artifactbrowser;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.oro.text.perl.Perl5Util;
import org.dspace.app.xmlui.utils.HandleUtil;
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.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
/**
* Preform an advanced search of the repository. The user is presented with
* three search parameters, that may be ORed, ANDed, NOTed together.
*
* At the present time only three fields are displayed however if the theme
* whishes to expand this they can by setting the num_search_fields to the
* desired number of search fields. Also the theme can change the number of
* results per the page by setting results_per_page
*
* FIXME: The list of what fields are search should come from a configurable
* place. Possibily the sitemap configuration.
*
* @author Scott Phillips
*/
public class AdvancedSearch extends AbstractSearch implements CacheableProcessingComponent
{
/** Language string used: */
private static final Message T_title =
message("xmlui.ArtifactBrowser.AdvancedSearch.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.AdvancedSearch.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.AdvancedSearch.head");
private static final Message T_search_scope =
message("xmlui.ArtifactBrowser.AdvancedSearch.search_scope");
private static final Message T_search_scope_help =
message("xmlui.ArtifactBrowser.AdvancedSearch.search_scope_help");
private static final Message T_conjunction =
message("xmlui.ArtifactBrowser.AdvancedSearch.conjunction");
private static final Message T_search_type =
message("xmlui.ArtifactBrowser.AdvancedSearch.search_type");
private static final Message T_search_for =
message("xmlui.ArtifactBrowser.AdvancedSearch.search_for");
private static final Message T_go =
message("xmlui.general.go");
private static final Message T_and =
message("xmlui.ArtifactBrowser.AdvancedSearch.and");
private static final Message T_or =
message("xmlui.ArtifactBrowser.AdvancedSearch.or");
private static final Message T_not =
message("xmlui.ArtifactBrowser.AdvancedSearch.not");
/** How many conjunction fields to display */
private static final int FIELD_DISPLAY_COUNT = 3;
private static final int FIELD_MAX_COUNT = 12;
/** A cache of extracted search fields */
private java.util.List<SearchField> fields;
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws WingException, SQLException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if ((dso instanceof Collection) || (dso instanceof Community))
{
HandleUtil.buildHandleTrail(dso,pageMeta,contextPath);
}
pageMeta.addTrail().addContent(T_trail);
}
/**
* Add the body
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String numSearchField = request.getParameter("num_search_field");
if (numSearchField == null || numSearchField.length() == 0)
{
numSearchField = "3";
}
// Build the DRI Body
Division search = body.addDivision("advanced-search","primary");
search.setHead(T_head);
Division query = search.addInteractiveDivision("search-query",
"advanced-search",Division.METHOD_POST,"secondary search");
// Use these fields to change the number of search fields, or change the results per page.
query.addHidden("num_search_field").setValue(numSearchField);
query.addHidden("results_per_page").setValue(getParameterRpp());
List queryList = query.addList("search-query",List.TYPE_FORM);
if (variableScope())
{
Select scope = queryList.addItem().addSelect("scope");
scope.setLabel(T_search_scope);
scope.setHelp(T_search_scope_help);
buildScopeList(scope);
}
Table queryTable = query.addTable("search-query", 4, 3);
Row header = queryTable.addRow(Row.ROLE_HEADER);
header.addCellContent(T_conjunction);
header.addCellContent(T_search_type);
header.addCellContent(T_search_for);
for (int i = 1; i <= FIELD_DISPLAY_COUNT; i++)
{
Row row = queryTable.addRow(Row.ROLE_DATA);
buildConjunctionField(i, row.addCell());
buildTypeField(i, row.addCell());
buildQueryField(i, row.addCell());
}
for (SearchField field : fields)
{
// Skip over all the fields we've displayed.
int i = field.getIndex();
if (i <= FIELD_DISPLAY_COUNT)
{
continue;
}
query.addHidden("conjunction"+i).setValue(field.getConjunction());
query.addHidden("field"+i).setValue(field.getField());
query.addHidden("query"+i).setValue(field.getQuery());
}
buildSearchControls(query);
query.addPara(null, "button-list").addButton("submit").setValue(T_go);
// Add the result division
buildSearchResultsDivision(search);
}
/**
* Build a conjunction field in the given for the given cell. A
* conjunction consists of logical the operators AND, OR, NOT.
*
* @param row The current row
* @param cell The current cell
*/
private void buildConjunctionField(int row, Cell cell) throws WingException
{
// No conjunction for the first row.
if (row == 1)
{
return;
}
Request request = ObjectModelHelper.getRequest(objectModel);
String current = request.getParameter("conjunction" + row);
// default to AND if nothing specified.
if (current == null || current.length() == 0)
{
current = "AND";
}
Select select = cell.addSelect("conjunction" + row);
select.addOption("AND".equals(current), "AND").addContent(T_and);
select.addOption("OR".equals(current), "OR").addContent(T_or);
select.addOption("NOT".equals(current), "NOT").addContent(T_not);
}
/**
* Build a list of all the indexable fields in the given cell.
*
* FIXME: This needs to use the dspace.cfg data
*
* @param row The current row
* @param cell The current cell
*/
private void buildTypeField(int row, Cell cell) throws WingException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String current = request.getParameter("field" + row);
Select select = cell.addSelect("field" + row);
Map<String, Message> searchTypes = new HashMap<String, Message>();
int i = 1;
String sindex = ConfigurationManager.getProperty("search.index." + i);
while(sindex != null)
{
String field = sindex.split(":")[0];
searchTypes.put(field, message("xmlui.ArtifactBrowser.AdvancedSearch.type_" + field));
sindex = ConfigurationManager.getProperty("search.index." + ++i);
}
// Special case ANY
select.addOption((current == null), "ANY").addContent(
message("xmlui.ArtifactBrowser.AdvancedSearch.type_ANY"));
for (Map.Entry<String, Message> searchType : searchTypes.entrySet())
{
select.addOption(searchType.getKey().equals(current), searchType.getKey()).addContent(searchType.getValue());
}
}
/**
* Recycle
*/
public void recycle()
{
this.fields = null;
super.recycle();
}
/**
* Build the query field for the given cell.
*
* @param row The current row.
* @param cell The current cell.
*/
private void buildQueryField(int row, Cell cell) throws WingException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String current = decodeFromURL(request.getParameter("query" + row));
Text text = cell.addText("query" + row);
if (current != null)
{
text.setValue(current);
}
}
/**
* Generate a URL for this search page which includes all the
* search parameters along with the added parameters.
*
* @param parameters URL parameters to be included in the generated url.
*/
protected String generateURL(Map<String, String> parameters)
throws UIException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String numSearchField = request.getParameter("num_search_field");
if (numSearchField != null)
{
parameters.put("num_search_field", numSearchField);
}
String resultsPerPage = request.getParameter("results_per_page");
if (resultsPerPage != null)
{
parameters.put("results_per_page", resultsPerPage);
}
String scope = request.getParameter("scope");
if (scope != null)
{
parameters.put("scope", scope);
}
for (SearchField searchField : getSearchFields(request))
{
int index = searchField.getIndex();
String field = searchField.getField();
String query = searchField.getQuery();
String conjunction = searchField.getConjunction();
parameters.put("conjunction" + index, conjunction);
parameters.put("field" + index, field);
parameters.put("query" + index, query);
}
if (parameters.get("page") == null)
{
parameters.put("page", String.valueOf(getParameterPage()));
}
if (parameters.get("rpp") == null)
{
parameters.put("rpp", String.valueOf(getParameterRpp()));
}
if (parameters.get("sort_by") == null)
{
parameters.put("sort_by", String.valueOf(getParameterSortBy()));
}
if (parameters.get("order") == null)
{
parameters.put("order", getParameterOrder());
}
if (parameters.get("etal") == null)
{
parameters.put("etal", String.valueOf(getParameterEtAl()));
}
return super.generateURL("advanced-search", parameters);
}
/**
* Determine the search query for this search page.
*
* @return the query.
*/
protected String getQuery() throws UIException
{
Request request = ObjectModelHelper.getRequest(objectModel);
return buildQuery(getSearchFields(request));
}
/**
* Given a list of search fields buld a lucene search query string.
*
* @param fields The search fields
* @return A string
*/
private String buildQuery(java.util.List<SearchField> fields)
{
Perl5Util util = new Perl5Util();
StringBuilder query = new StringBuilder();
query.append("(");
// Loop through the fields building the search query as we go.
for (SearchField field : fields)
{
// if the field is empty, then skip it and try a later one.
if (field.getQuery() == null)
{
continue;
}
// Add the conjunction for everything but the first field.
if (fields.indexOf(field) > 0)
{
query.append(" ").append(field.getConjunction()).append(" ").toString();
}
// Two cases, one if a specific search field is specified or if
// ANY is given then just a general search is performed.
if ("ANY".equals(field.getField()))
{
// No field specified,
query.append("(").append(field.getQuery()).append(")").toString();
}
else
{
// Specific search field specified, add the field specific field.
// Replace singe quote's with double quotes (only if they match)
String subQuery = util.substitute("s/\'(.*)\'/\"$1\"/g", field.getQuery());
// If the field is not quoted ...
if (!util.match("/\".*\"/", subQuery))
{
// ... then seperate each word and re-specify the search field.
subQuery = util.substitute("s/[ ]+/ " + field.getField() + ":/g", subQuery);
}
// Put the subQuery into the general query
query.append("(").append(field.getField()).append(":").append(subQuery).append(")").toString();
}
}
if (query.length() == 1)
{
return "";
}
return query.append(")").toString();
}
/**
* Get a list of search fields from the request object
* and parse them into a linear array of fileds. The field's
* index is preserved, so if it comes in as index 17 it will
* be outputted as field 17.
*
* @param request The http request object
* @return Array of search fields
* @throws UIException
*/
public java.util.List<SearchField> getSearchFields(Request request) throws UIException
{
if (this.fields != null)
{
return this.fields;
}
// Get how many fields to search
int numSearchField;
try {
String numSearchFieldStr = request.getParameter("num_search_field");
numSearchField = Integer.valueOf(numSearchFieldStr);
}
catch (NumberFormatException nfe)
{
numSearchField = FIELD_MAX_COUNT;
}
// Iterate over all the possible fields and add each one to the list of fields.
ArrayList<SearchField> fields = new ArrayList<SearchField>();
for (int i = 1; i <= numSearchField; i++)
{
String field = request.getParameter("field"+i);
String query = decodeFromURL(request.getParameter("query"+i));
String conjunction = request.getParameter("conjunction"+i);
if (field != null)
{
field = field.trim();
if (field.length() == 0)
{
field = null;
}
}
if (query != null)
{
query = query.trim();
if (query.length() == 0)
{
query = null;
}
}
if (conjunction != null)
{
conjunction = conjunction.trim();
if (conjunction.length() == 0)
{
conjunction = null;
}
}
if (field == null)
{
field = "ANY";
}
if (conjunction == null)
{
conjunction = "AND";
}
if (query != null)
{
fields.add(new SearchField(i, field, query, conjunction));
}
}
this.fields = fields;
return this.fields;
}
/**
* A private record keeping class to relate the various
* components of a search field together.
*/
private static class SearchField {
/** What index the search field is, typicaly there are just three - but the theme may exand this number */
private int index;
/** The field to search, ANY if none specified */
private String field;
/** The query string to search for */
private String query;
/** the conjunction: either "AND" or "OR" */
private String conjuction;
public SearchField(int index, String field, String query, String conjunction)
{
this.index = index;
this.field = field;
this.query = query;
this.conjuction = conjunction;
}
public int getIndex() { return this.index;}
public String getField() { return this.field;}
public String getQuery() { return this.query;}
public String getConjunction() { return this.conjuction;}
}
}
| 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.artifactbrowser;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.dspace.app.xmlui.utils.HandleUtil;
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.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.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.xml.sax.SAXException;
/**
* Preform a simple search of the repository. The user provides a simple one
* field query (the url parameter is named query) and the results are processed.
*
* @author Scott Phillips
*/
public class SimpleSearch extends AbstractSearch implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_title =
message("xmlui.ArtifactBrowser.SimpleSearch.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.SimpleSearch.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.SimpleSearch.head");
private static final Message T_search_scope =
message("xmlui.ArtifactBrowser.SimpleSearch.search_scope");
private static final Message T_full_text_search =
message("xmlui.ArtifactBrowser.SimpleSearch.full_text_search");
private static final Message T_go =
message("xmlui.general.go");
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws WingException, SQLException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if ((dso instanceof Collection) || (dso instanceof Community))
{
HandleUtil.buildHandleTrail(dso,pageMeta,contextPath);
}
pageMeta.addTrail().addContent(T_trail);
}
/**
* build the DRI page representing the body of the search query. This
* provides a widget to generate a new query and list of search results if
* present.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
String queryString = getQuery();
// Build the DRI Body
Division search = body.addDivision("search","primary");
search.setHead(T_head);
Division query = search.addInteractiveDivision("general-query",
"search",Division.METHOD_GET,"secondary search");
List queryList = query.addList("search-query",List.TYPE_FORM);
if (variableScope())
{
Select scope = queryList.addItem().addSelect("scope");
scope.setLabel(T_search_scope);
buildScopeList(scope);
}
Text text = queryList.addItem().addText("query");
text.setLabel(T_full_text_search);
text.setValue(queryString);
buildSearchControls(query);
query.addPara(null, "button-list").addButton("submit").setValue(T_go);
// Add the result division
buildSearchResultsDivision(search);
}
/**
* Get the search query from the URL parameter, if none is found the empty
* string is returned.
*/
protected String getQuery() throws UIException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String query = decodeFromURL(request.getParameter("query"));
if (query == null)
{
return "";
}
return query;
}
/**
* Generate a url to the simple search url.
*/
protected String generateURL(Map<String, String> parameters)
throws UIException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String scope = request.getParameter("scope");
if (scope != null)
{
parameters.put("scope", scope);
}
String query = getQuery();
if (!"".equals(query))
{
parameters.put("query", encodeForURL(query));
}
if (parameters.get("page") == null)
{
parameters.put("page", String.valueOf(getParameterPage()));
}
if (parameters.get("rpp") == null)
{
parameters.put("rpp", String.valueOf(getParameterRpp()));
}
if (parameters.get("sort_by") == null)
{
parameters.put("sort_by", String.valueOf(getParameterSortBy()));
}
if (parameters.get("order") == null)
{
parameters.put("order", getParameterOrder());
}
if (parameters.get("etal") == null)
{
parameters.put("etal", String.valueOf(getParameterEtAl()));
}
return super.generateURL("search", parameters);
}
}
| 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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Map;
import java.util.HashMap;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
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.ReferenceSet;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
/**
* Display a single collection. This includes a full text search, browse by
* list, community display and a list of recent submissions.
*
* @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 CollectionViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
public static final Message T_untitled =
message("xmlui.general.untitled");
private static final Message T_head_browse =
message("xmlui.ArtifactBrowser.CollectionViewer.head_browse");
private static final Message T_browse_titles =
message("xmlui.ArtifactBrowser.CollectionViewer.browse_titles");
private static final Message T_browse_authors =
message("xmlui.ArtifactBrowser.CollectionViewer.browse_authors");
private static final Message T_browse_dates =
message("xmlui.ArtifactBrowser.CollectionViewer.browse_dates");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return "0";
}
return HashUtil.hash(dso.getHandle());
}
catch (SQLException sqle)
{
// Ignore all errors and just return that the component is not
// cachable.
return "0";
}
}
/**
* 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)
{
Collection collection = null;
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return null;
}
if (!(dso instanceof Collection))
{
return null;
}
collection = (Collection) dso;
DSpaceValidity validity = new DSpaceValidity();
// Add the actual collection;
validity.add(collection);
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add a page title and trail links.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Collection))
{
return;
}
Collection collection = (Collection) dso;
// Set the page title
String name = collection.getMetadata("name");
if (name == null || name.length() == 0)
{
pageMeta.addMetadata("title").addContent(T_untitled);
}
else
{
pageMeta.addMetadata("title").addContent(name);
}
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
HandleUtil.buildHandleTrail(collection,pageMeta,contextPath);
// Add RSS links if available
String formats = ConfigurationManager.getProperty("webui.feed.formats");
if ( formats != null )
{
for (String format : formats.split(","))
{
// Remove the protocol number, i.e. just list 'rss' or' atom'
String[] parts = format.split("_");
if (parts.length < 1)
{
continue;
}
String feedFormat = parts[0].trim()+"+xml";
String feedURL = contextPath+"/feed/"+format.trim()+"/"+collection.getHandle();
pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
}
}
}
/**
* Display a single collection
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Collection))
{
return;
}
// Set up the major variables
Collection collection = (Collection) dso;
// Build the collection viewer division.
Division home = body.addDivision("collection-home", "primary repository collection");
String name = collection.getMetadata("name");
if (name == null || name.length() == 0)
{
home.setHead(T_untitled);
}
else
{
home.setHead(name);
}
// The search / browse box.
{
// TODO: move browse stuff out of here
Division search = home.addDivision("collection-search-browse",
"secondary search-browse");
// Browse by list
Division browseDiv = search.addDivision("collection-browse","secondary browse");
List browse = browseDiv.addList("collection-browse", List.TYPE_SIMPLE,
"collection-browse");
browse.setHead(T_head_browse);
String url = contextPath + "/handle/" + collection.getHandle();
try
{
// Get a Map of all the browse tables
BrowseIndex[] bis = BrowseIndex.getBrowseIndices();
for (BrowseIndex bix : bis)
{
// Create a Map of the query parameters for this link
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("type", bix.getName());
// Add a link to this browse
browse.addItemXref(super.generateURL(url + "/browse", queryParams),
message("xmlui.ArtifactBrowser.Navigation.browse_" + bix.getName()));
}
}
catch (BrowseException bex)
{
browse.addItemXref(url + "/browse?type=title",T_browse_titles);
browse.addItemXref(url + "/browse?type=author",T_browse_authors);
browse.addItemXref(url + "/browse?type=dateissued",T_browse_dates);
}
}
// Add the reference
{
Division viewer = home.addDivision("collection-view","secondary");
ReferenceSet mainInclude = viewer.addReferenceSet("collection-view",
ReferenceSet.TYPE_DETAIL_VIEW);
mainInclude.addReference(collection);
}
}
/**
* Recycle
*/
public void recycle()
{
// Clear out our item's cache.
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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Map;
import java.util.HashMap;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
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.ReferenceSet;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.Reference;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
/**
* Display a single community. This includes a full text search, browse by list,
* community display and a list of recent submissions.
* private static final Logger log = Logger.getLogger(DSpaceFeedGenerator.class);
* @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 CommunityViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
public static final Message T_untitled =
message("xmlui.general.untitled");
private static final Message T_head_browse =
message("xmlui.ArtifactBrowser.CommunityViewer.head_browse");
private static final Message T_browse_titles =
message("xmlui.ArtifactBrowser.CommunityViewer.browse_titles");
private static final Message T_browse_authors =
message("xmlui.ArtifactBrowser.CommunityViewer.browse_authors");
private static final Message T_browse_dates =
message("xmlui.ArtifactBrowser.CommunityViewer.browse_dates");
private static final Message T_head_sub_communities =
message("xmlui.ArtifactBrowser.CommunityViewer.head_sub_communities");
private static final Message T_head_sub_collections =
message("xmlui.ArtifactBrowser.CommunityViewer.head_sub_collections");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey() {
try {
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return "0"; // no item, something is wrong
}
return HashUtil.hash(dso.getHandle());
}
catch (SQLException sqle)
{
// Ignore all errors and just return that the component is not cachable.
return "0";
}
}
/**
* Generate the cache validity object.
*
* This validity object includes the community being viewed, all
* sub-communites (one level deep), all sub-collections, and
* recently submitted items.
*/
public SourceValidity getValidity()
{
if (this.validity == null)
{
Community community = null;
try {
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return null;
}
if (!(dso instanceof Community))
{
return null;
}
community = (Community) dso;
DSpaceValidity validity = new DSpaceValidity();
validity.add(community);
Community[] subCommunities = community.getSubcommunities();
Collection[] collections = community.getCollections();
// Sub communities
for (Community subCommunity : subCommunities)
{
validity.add(subCommunity);
}
// Sub collections
for (Collection collection : collections)
{
validity.add(collection);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Ignore all errors and invalidate the cache.
}
}
return this.validity;
}
/**
* Add the community's title and trail links to the page's metadata
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Community))
{
return;
}
// Set up the major variables
Community community = (Community) dso;
// Set the page title
String name = community.getMetadata("name");
if (name == null || name.length() == 0)
{
pageMeta.addMetadata("title").addContent(T_untitled);
}
else
{
pageMeta.addMetadata("title").addContent(name);
}
// Add the trail back to the repository root.
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
HandleUtil.buildHandleTrail(community, pageMeta,contextPath);
// Add RSS links if available
String formats = ConfigurationManager.getProperty("webui.feed.formats");
if ( formats != null )
{
for (String format : formats.split(","))
{
// Remove the protocol number, i.e. just list 'rss' or' atom'
String[] parts = format.split("_");
if (parts.length < 1)
{
continue;
}
String feedFormat = parts[0].trim()+"+xml";
String feedURL = contextPath+"/feed/"+format.trim()+"/"+community.getHandle();
pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
}
}
}
/**
* Display a single community (and refrence any sub communites or
* collections)
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Community))
{
return;
}
// Set up the major variables
Community community = (Community) dso;
Community[] subCommunities = community.getSubcommunities();
Collection[] collections = community.getCollections();
// Build the community viewer division.
Division home = body.addDivision("community-home", "primary repository community");
String name = community.getMetadata("name");
if (name == null || name.length() == 0)
{
home.setHead(T_untitled);
}
else
{
home.setHead(name);
}
// The search / browse box.
{
Division search = home.addDivision("community-search-browse",
"secondary search-browse");
// TODO: move browse stuff out of here
// Browse by list
Division browseDiv = search.addDivision("community-browse","secondary browse");
List browse = browseDiv.addList("community-browse", List.TYPE_SIMPLE,
"community-browse");
browse.setHead(T_head_browse);
String url = contextPath + "/handle/" + community.getHandle();
try
{
// Get a Map of all the browse tables
BrowseIndex[] bis = BrowseIndex.getBrowseIndices();
for (BrowseIndex bix : bis)
{
// Create a Map of the query parameters for this link
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("type", bix.getName());
// Add a link to this browse
browse.addItemXref(super.generateURL(url + "/browse", queryParams),
message("xmlui.ArtifactBrowser.Navigation.browse_" + bix.getName()));
}
}
catch (BrowseException bex)
{
browse.addItemXref(url + "/browse?type=title",T_browse_titles);
browse.addItemXref(url + "/browse?type=author",T_browse_authors);
browse.addItemXref(url + "/browse?type=dateissued",T_browse_dates);
}
}
// Add main reference:
{
Division viewer = home.addDivision("community-view","secondary");
ReferenceSet referenceSet = viewer.addReferenceSet("community-view",
ReferenceSet.TYPE_DETAIL_VIEW);
Reference communityInclude = referenceSet.addReference(community);
// If the community has any children communities also refrence them.
if (subCommunities != null && subCommunities.length > 0)
{
ReferenceSet communityReferenceSet = communityInclude
.addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST,null,"hierarchy");
communityReferenceSet.setHead(T_head_sub_communities);
// Sub communities
for (Community subCommunity : subCommunities)
{
communityReferenceSet.addReference(subCommunity);
}
}
if (collections != null && collections.length > 0)
{
ReferenceSet communityReferenceSet = communityInclude
.addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST,null,"hierarchy");
communityReferenceSet.setHead(T_head_sub_collections);
// Sub collections
for (Collection collection : collections)
{
communityReferenceSet.addReference(collection);
}
}
}// main refrence
}
/**
* Recycle
*/
public void recycle()
{
// Clear out our item's cache.
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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
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.HandleUtil;
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.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.app.util.Util;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
/**
* This transform applys the basic navigational links that should be available
* on all pages generated by DSpace.
*
* @author Scott Phillips
*/
public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_head_all_of_dspace =
message("xmlui.ArtifactBrowser.Navigation.head_all_of_dspace");
private static final Message T_head_browse =
message("xmlui.ArtifactBrowser.Navigation.head_browse");
private static final Message T_communities_and_collections =
message("xmlui.ArtifactBrowser.Navigation.communities_and_collections");
private static final Message T_head_this_collection =
message("xmlui.ArtifactBrowser.Navigation.head_this_collection");
private static final Message T_head_this_community =
message("xmlui.ArtifactBrowser.Navigation.head_this_community");
/**
* 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;
}
/**
* Add the basic navigational options:
*
* Search - advanced search
*
* browse - browse by Titles - browse by Authors - browse by Dates
*
* language FIXME: add languages
*
* context no context options are added.
*
* action no action options are added.
*/
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
*/
List browse = options.addList("browse");
options.addList("account");
options.addList("context");
options.addList("administrative");
browse.setHead(T_head_browse);
List browseGlobal = browse.addList("global");
List browseContext = browse.addList("context");
browseGlobal.setHead(T_head_all_of_dspace);
browseGlobal.addItemXref(contextPath + "/community-list",T_communities_and_collections);
// Add the configured browse lists for 'top level' browsing
addBrowseOptions(browseGlobal, contextPath + "/browse");
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
{
if (dso instanceof Item)
{
// If we are an item change the browse scope to the parent
// collection.
dso = ((Item) dso).getOwningCollection();
}
if (dso instanceof Collection)
{
browseContext.setHead(T_head_this_collection);
}
if (dso instanceof Community)
{
browseContext.setHead(T_head_this_community);
}
// Add the configured browse lists for scoped browsing
String handle = dso.getHandle();
addBrowseOptions(browseContext, contextPath + "/handle/" + handle + "/browse");
}
}
/**
* 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"));
}
// Add metadata for quick searches:
pageMeta.addMetadata("search", "simpleURL").addContent(
contextPath + "/search");
pageMeta.addMetadata("search", "advancedURL").addContent(
contextPath + "/advanced-search");
pageMeta.addMetadata("search", "queryField").addContent("query");
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);
}
}
}
/**
* Add navigation for the configured browse tables to the supplied list.
*
* @param browseList
* @param browseURL
* @throws WingException
*/
private void addBrowseOptions(List browseList, String browseURL) throws WingException
{
// FIXME Exception handling
try
{
// Get a Map of all the browse tables
BrowseIndex[] bis = BrowseIndex.getBrowseIndices();
for (BrowseIndex bix : bis)
{
// Create a Map of the query parameters for this link
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("type", bix.getName());
// Add a link to this browse
browseList.addItemXref(super.generateURL(browseURL, queryParams),
message("xmlui.ArtifactBrowser.Navigation.browse_" + bix.getName()));
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to get browse indicies", bex);
}
}
}
| 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.artifactbrowser;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.utils.HandleUtil;
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.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.xml.sax.SAXException;
/**
* Display an item restricted message.
*
* @author Scott Phillips
*/
public class RestrictedItem extends AbstractDSpaceTransformer //implements CacheableProcessingComponent
{
private static final Logger log = Logger.getLogger(RestrictedItem.class);
/** language strings */
private static final Message T_title =
message("xmlui.ArtifactBrowser.RestrictedItem.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.RestrictedItem.trail");
private static final Message T_head_resource =
message("xmlui.ArtifactBrowser.RestrictedItem.head_resource");
private static final Message T_head_community =
message("xmlui.ArtifactBrowser.RestrictedItem.head_community");
private static final Message T_head_collection =
message("xmlui.ArtifactBrowser.RestrictedItem.head_collection");
private static final Message T_head_item =
message("xmlui.ArtifactBrowser.RestrictedItem.head_item");
private static final Message T_head_bitstream =
message("xmlui.ArtifactBrowser.RestrictedItem.head_bitstream");
private static final Message T_para_resource =
message("xmlui.ArtifactBrowser.RestrictedItem.para_resource");
private static final Message T_para_community =
message("xmlui.ArtifactBrowser.RestrictedItem.para_community");
private static final Message T_para_collection =
message("xmlui.ArtifactBrowser.RestrictedItem.para_collection");
private static final Message T_para_item =
message("xmlui.ArtifactBrowser.RestrictedItem.para_item");
private static final Message T_para_bitstream =
message("xmlui.ArtifactBrowser.RestrictedItem.para_bitstream");
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
if (dso != null)
{
HandleUtil.buildHandleTrail(dso, pageMeta, contextPath);
}
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Request request = ObjectModelHelper.getRequest(objectModel);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
Division unauthorized = body.addDivision("unauthorized-resource","primary");
if (dso == null)
{
unauthorized.setHead(T_head_resource);
unauthorized.addPara(T_para_resource);
}
else if (dso instanceof Community)
{
Community community = (Community) dso;
unauthorized.setHead(T_head_community);
unauthorized.addPara(T_para_community.parameterize(community.getMetadata("name")));
}
else if (dso instanceof Collection)
{
Collection collection = (Collection) dso;
unauthorized.setHead(T_head_collection);
unauthorized.addPara(T_para_collection.parameterize(collection.getMetadata("name")));
}
else if (dso instanceof Item)
{
// The dso may be an item but it could still be an item's bitstream. So let's check for the parameter.
if (request.getParameter("bitstreamId") != null)
{
String identifier = "unknown";
try {
Bitstream bit = Bitstream.find(context, Integer.valueOf(request.getParameter("bitstreamId")));
if (bit != null) {
identifier = bit.getName();
}
}
catch(Exception e) {
// just forget it - and display the restricted message.
log.trace("Caught exception", e);
}
unauthorized.setHead(T_head_bitstream);
unauthorized.addPara(T_para_bitstream.parameterize(identifier));
}
else
{
String identifier = "unknown";
String handle = dso.getHandle();
if (handle == null || "".equals(handle))
{
identifier = "internal ID: " + dso.getID();
}
else
{
identifier = "hdl:"+handle;
}
unauthorized.setHead(T_head_item);
unauthorized.addPara(T_para_item.parameterize(identifier));
}
}
else
{
// This case should not occure, but if it does just fall back to the resource message.
unauthorized.setHead(T_head_resource);
unauthorized.addPara(T_para_resource);
}
}
}
| 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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
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.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.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;
/**
* Create a simple contact us page. Fancier contact us pages should be handled by the theme.
*
*
* @author Scott Phillips
*/
public class Contact extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** language strings */
private static final Message T_title =
message("xmlui.ArtifactBrowser.Contact.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.Contact.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.Contact.head");
private static final Message T_para1 =
message("xmlui.ArtifactBrowser.Contact.para1");
private static final Message T_feedback_label =
message("xmlui.ArtifactBrowser.Contact.feedback_label");
private static final Message T_feedback_link =
message("xmlui.ArtifactBrowser.Contact.feedback_link");
private static final Message T_email =
message("xmlui.ArtifactBrowser.Contact.email");
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
return "1";
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity()
{
return NOPValidity.SHARED_INSTANCE;
}
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 void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Division contact = body.addDivision("contact","primary");
contact.setHead(T_head);
String name = ConfigurationManager.getProperty("dspace.name");
contact.addPara(T_para1.parameterize(name));
List list = contact.addList("contact");
list.addLabel(T_feedback_label);
list.addItem().addXref(contextPath+"/feedback",T_feedback_link);
list.addLabel(T_email);
String email = ConfigurationManager.getProperty("mail.admin");
list.addItem().addXref("mailto:"+email,email);
}
}
| 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.artifactbrowser;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
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.ReferenceSet;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.*;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.sort.SortException;
import org.dspace.sort.SortOption;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Renders a list of recently submitted items for the collection by using the dspace browse
*
* @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 CollectionRecentSubmissions extends AbstractDSpaceTransformer implements CacheableProcessingComponent {
private static final Logger log = Logger.getLogger(CollectionRecentSubmissions.class);
/** How many recent submissions to include in the page */
private static final int RECENT_SUBMISSIONS = 5;
/** The cache of recently submitted items */
private java.util.List<BrowseItem> recentSubmissionItems;
private static final Message T_head_recent_submissions =
message("xmlui.ArtifactBrowser.CollectionViewer.head_recent_submissions");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return "0";
}
return HashUtil.hash(dso.getHandle());
}
catch (SQLException sqle)
{
// Ignore all errors and just return that the component is not
// cachable.
return "0";
}
}
/**
* 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)
{
Collection collection = null;
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return null;
}
if (!(dso instanceof Collection))
{
return null;
}
collection = (Collection) dso;
DSpaceValidity validity = new DSpaceValidity();
// Add the actual collection;
validity.add(collection);
// add reciently submitted items
for(BrowseItem item : getRecientlySubmittedItems(collection))
{
validity.add(item);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
@Override
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException {
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Collection))
{
return;
}
// Set up the major variables
Collection collection = (Collection) dso;
java.util.List<BrowseItem> items = getRecientlySubmittedItems(collection);
if(items.size() == 0)
{
return;
}
Division home = body.addDivision("collection-home", "primary repository collection");
Division lastSubmittedDiv = home
.addDivision("collection-recent-submission","secondary recent-submission");
lastSubmittedDiv.setHead(T_head_recent_submissions);
ReferenceSet lastSubmitted = lastSubmittedDiv.addReferenceSet(
"collection-last-submitted", ReferenceSet.TYPE_SUMMARY_LIST,
null, "recent-submissions");
for (BrowseItem item : items)
{
lastSubmitted.addReference(item);
}
}
/**
* Get the recently submitted items for the given collection.
*
* @param collection The collection.
*/
@SuppressWarnings("unchecked") // The cast from getLastSubmitted is correct, it dose infact return a list of Items.
private java.util.List<BrowseItem> getRecientlySubmittedItems(Collection collection)
throws SQLException
{
if (recentSubmissionItems != null)
{
return recentSubmissionItems;
}
String source = ConfigurationManager.getProperty("recent.submissions.sort-option");
int numRecentSubmissions = ConfigurationManager.getIntProperty("recent.submissions.count", RECENT_SUBMISSIONS);
if(numRecentSubmissions == 0)
{
return new ArrayList<BrowseItem>();
}
BrowserScope scope = new BrowserScope(context);
scope.setCollection(collection);
scope.setResultsPerPage(numRecentSubmissions);
// 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.browse(scope).getResults();
}
catch (SortException se)
{
log.error("Caught SortException", se);
}
catch (BrowseException bex)
{
log.error("Caught BrowseException", bex);
}
return this.recentSubmissionItems;
}
/**
* Recycle
*/
public void recycle()
{
// Clear out our item's cache.
this.recentSubmissionItems = 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.artifactbrowser;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
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.ReferenceSet;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.app.util.GoogleMetadata;
import org.dspace.content.crosswalk.CrosswalkException;
import org.dspace.content.crosswalk.DisseminationCrosswalk;
import org.dspace.core.PluginManager;
import org.jdom.Element;
import org.jdom.Text;
import org.jdom.output.XMLOutputter;
import org.xml.sax.SAXException;
import org.dspace.core.ConfigurationManager;
import org.dspace.app.sfx.SFXFileReader;
/**
* Display a single item.
*
* @author Scott Phillips
*/
public class ItemViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.ItemViewer.trail");
private static final Message T_show_simple =
message("xmlui.ArtifactBrowser.ItemViewer.show_simple");
private static final Message T_show_full =
message("xmlui.ArtifactBrowser.ItemViewer.show_full");
private static final Message T_head_parent_collections =
message("xmlui.ArtifactBrowser.ItemViewer.head_parent_collections");
/** Cached validity object */
private SourceValidity validity = null;
/** XHTML crosswalk instance */
private DisseminationCrosswalk xHTMLHeadCrosswalk = null;
private String sfxFile = ConfigurationManager.getProperty("dspace.dir") + File.separator
+ "config" + File.separator + "sfx.xml";
private String sfxQuery = null;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey() {
try {
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
{
return "0"; // no item, something is wrong.
}
return HashUtil.hash(dso.getHandle() + "full:" + showFullItem(objectModel));
}
catch (SQLException sqle)
{
// Ignore all errors and just return that the component is not cachable.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The validity object will include the item being viewed,
* along with all bundles & bitstreams.
*/
public SourceValidity getValidity()
{
DSpaceObject dso = null;
if (this.validity == null)
{
try {
dso = HandleUtil.obtainHandle(objectModel);
DSpaceValidity validity = new DSpaceValidity();
validity.add(dso);
this.validity = validity.complete();
}
catch (Exception e)
{
// Ignore all errors and just invalidate the cache.
}
}
return this.validity;
}
/**
* Add the item's title and trail links to the page's metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Item))
{
return;
}
Item item = (Item) dso;
// Set the page title
String title = getItemTitle(item);
if (title != null)
{
pageMeta.addMetadata("title").addContent(title);
}
else
{
pageMeta.addMetadata("title").addContent(item.getHandle());
}
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
HandleUtil.buildHandleTrail(item,pageMeta,contextPath);
pageMeta.addTrail().addContent(T_trail);
// Add SFX link
String sfxserverUrl = ConfigurationManager.getProperty("sfx.server.url");
if (sfxserverUrl != null && sfxserverUrl.length() > 0)
{
sfxQuery = "";
// parse XML file -> XML document will be build
sfxQuery = SFXFileReader.loadSFXFile(sfxFile, item);
// Remove initial &, if any
if (sfxQuery.startsWith("&"))
{
sfxQuery = sfxQuery.substring(1);
}
sfxserverUrl = sfxserverUrl.trim() +"&" + sfxQuery.trim();
pageMeta.addMetadata("sfx","server").addContent(sfxserverUrl);
}
boolean googleEnabled = ConfigurationManager.getBooleanProperty(
"google-metadata.enable", false);
if (googleEnabled)
{
// Add Google metadata field names & values to DRI
GoogleMetadata gmd = new GoogleMetadata(context, item);
for (Entry<String, String> m : gmd.getMappings())
{
pageMeta.addMetadata(m.getKey()).addContent(m.getValue());
}
}
// Metadata for <head> element
if (xHTMLHeadCrosswalk == null)
{
xHTMLHeadCrosswalk = (DisseminationCrosswalk) PluginManager.getNamedPlugin(
DisseminationCrosswalk.class, "XHTML_HEAD_ITEM");
}
// Produce <meta> elements for header from crosswalk
try
{
List l = xHTMLHeadCrosswalk.disseminateList(item);
StringWriter sw = new StringWriter();
XMLOutputter xmlo = new XMLOutputter();
xmlo.output(new Text("\n"), sw);
for (int i = 0; i < l.size(); i++)
{
Element e = (Element) l.get(i);
// FIXME: we unset the Namespace so it's not printed.
// This is fairly yucky, but means the same crosswalk should
// work for Manakin as well as the JSP-based UI.
e.setNamespace(null);
xmlo.output(e, sw);
xmlo.output(new Text("\n"), sw);
}
pageMeta.addMetadata("xhtml_head_item").addContent(sw.toString());
}
catch (CrosswalkException ce)
{
// TODO: Is this the right exception class?
throw new WingException(ce);
}
}
/**
* Display a single item
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Item))
{
return;
}
Item item = (Item) dso;
// Build the item viewer division.
Division division = body.addDivision("item-view","primary");
String title = getItemTitle(item);
if (title != null)
{
division.setHead(title);
}
else
{
division.setHead(item.getHandle());
}
Para showfullPara = division.addPara(null, "item-view-toggle item-view-toggle-top");
if (showFullItem(objectModel))
{
String link = contextPath + "/handle/" + item.getHandle();
showfullPara.addXref(link).addContent(T_show_simple);
}
else
{
String link = contextPath + "/handle/" + item.getHandle()
+ "?show=full";
showfullPara.addXref(link).addContent(T_show_full);
}
ReferenceSet referenceSet;
if (showFullItem(objectModel))
{
referenceSet = division.addReferenceSet("collection-viewer",
ReferenceSet.TYPE_DETAIL_VIEW);
}
else
{
referenceSet = division.addReferenceSet("collection-viewer",
ReferenceSet.TYPE_SUMMARY_VIEW);
}
// Refrence the actual Item
ReferenceSet appearsInclude = referenceSet.addReference(item).addReferenceSet(ReferenceSet.TYPE_DETAIL_LIST,null,"hierarchy");
appearsInclude.setHead(T_head_parent_collections);
// Reference all collections the item appears in.
for (Collection collection : item.getCollections())
{
appearsInclude.addReference(collection);
}
showfullPara = division.addPara(null,"item-view-toggle item-view-toggle-bottom");
if (showFullItem(objectModel))
{
String link = contextPath + "/handle/" + item.getHandle();
showfullPara.addXref(link).addContent(T_show_simple);
}
else
{
String link = contextPath + "/handle/" + item.getHandle()
+ "?show=full";
showfullPara.addXref(link).addContent(T_show_full);
}
}
/**
* Determine if the full item should be referenced or just a summary.
*/
public static boolean showFullItem(Map objectModel)
{
Request request = ObjectModelHelper.getRequest(objectModel);
String show = request.getParameter("show");
if (show != null && show.length() > 0)
{
return true;
}
return false;
}
/**
* Obtain the item's title.
*/
public static String getItemTitle(Item item)
{
DCValue[] titles = item.getDC("title", Item.ANY, Item.ANY);
String title;
if (titles != null && titles.length > 0)
{
title = titles[0].value;
}
else
{
title = null;
}
return title;
}
/**
* 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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
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.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
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.ReferenceSet;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Cell;
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.Context;
import org.dspace.core.LogManager;
import org.dspace.core.Constants;
import org.dspace.handle.HandleManager;
import org.dspace.search.DSQuery;
import org.dspace.search.QueryArgs;
import org.dspace.search.QueryResults;
import org.dspace.sort.SortOption;
import org.dspace.sort.SortException;
import org.xml.sax.SAXException;
/**
* This is an abstract search page. It is a collection of search methods that
* are common between different search implementation. An implementer must
* implement at least three methods: addBody(), getQuery(), and generateURL().
*
* See the two implementors: SimpleSearch and AdvancedSearch.
*
* @author Scott Phillips
*/
public abstract class AbstractSearch extends AbstractDSpaceTransformer
{
private static final Logger log = Logger.getLogger(AbstractSearch.class);
/** Language strings */
private static final Message T_result_query =
message("xmlui.ArtifactBrowser.AbstractSearch.result_query");
private static final Message T_head1_community =
message("xmlui.ArtifactBrowser.AbstractSearch.head1_community");
private static final Message T_head1_collection =
message("xmlui.ArtifactBrowser.AbstractSearch.head1_collection");
private static final Message T_head1_none =
message("xmlui.ArtifactBrowser.AbstractSearch.head1_none");
private static final Message T_head2 =
message("xmlui.ArtifactBrowser.AbstractSearch.head2");
private static final Message T_head3 =
message("xmlui.ArtifactBrowser.AbstractSearch.head3");
private static final Message T_no_results =
message("xmlui.ArtifactBrowser.AbstractSearch.no_results");
private static final Message T_all_of_dspace =
message("xmlui.ArtifactBrowser.AbstractSearch.all_of_dspace");
private static final Message T_sort_by_relevance =
message("xmlui.ArtifactBrowser.AbstractSearch.sort_by.relevance");
private static final Message T_sort_by = message("xmlui.ArtifactBrowser.AbstractSearch.sort_by");
private static final Message T_order = message("xmlui.ArtifactBrowser.AbstractSearch.order");
private static final Message T_order_asc = message("xmlui.ArtifactBrowser.AbstractSearch.order.asc");
private static final Message T_order_desc = message("xmlui.ArtifactBrowser.AbstractSearch.order.desc");
private static final Message T_rpp = message("xmlui.ArtifactBrowser.AbstractSearch.rpp");
/** The options for results per page */
private static final int[] RESULTS_PER_PAGE_PROGRESSION = {5,10,20,40,60,80,100};
/** Cached query arguments */
private QueryArgs queryArgs;
/** Cached query results */
private QueryResults queryResults;
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
try
{
String key = "";
// Page Parameter
key += "-" + getParameterPage();
key += "-" + getParameterRpp();
key += "-" + getParameterSortBy();
key += "-" + getParameterOrder();
key += "-" + getParameterEtAl();
// What scope the search is at
DSpaceObject scope = getScope();
if (scope != null)
{
key += "-" + scope.getHandle();
}
// The actual search query.
key += "-" + getQuery();
return HashUtil.hash(key);
}
catch (RuntimeException re)
{
throw re;
}
catch (Exception e)
{
// Ignore all errors and just don't cache.
return "0";
}
}
/**
* Generate the cache validity object.
*
* This validity object should never "over cache" because it will
* perform the search, and serialize the results using the
* DSpaceValidity object.
*/
public SourceValidity getValidity()
{
if (this.validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject scope = getScope();
validity.add(scope);
performSearch();
@SuppressWarnings("unchecked") // This cast is correct
java.util.List<String> handles = queryResults.getHitHandles();
for (String handle : handles)
{
DSpaceObject resultDSO = HandleManager.resolveToObject(context, handle);
validity.add(resultDSO);
}
this.validity = validity.complete();
}
catch (RuntimeException re)
{
throw re;
}
catch (Exception e)
{
this.validity = null;
}
// add log message that we are viewing the item
// done here, as the serialization may not occur if the cache is valid
logSearch();
}
return this.validity;
}
/**
* Build the resulting search DRI document.
*/
public abstract void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException;
/**
*
* Attach a division to the given search division named "search-results"
* which contains results for this search query.
*
* @param search
* The search division to contain the search-results division.
*/
protected void buildSearchResultsDivision(Division search)
throws IOException, SQLException, WingException
{
if (getQuery().length() > 0)
{
// Perform the actual search
performSearch();
DSpaceObject searchScope = getScope();
Para para = search.addPara("result-query","result-query");
String query = getQuery();
int hitCount = queryResults.getHitCount();
para.addContent(T_result_query.parameterize(query,hitCount));
Division results = search.addDivision("search-results","primary");
if (searchScope instanceof Community)
{
Community community = (Community) searchScope;
String communityName = community.getMetadata("name");
results.setHead(T_head1_community.parameterize(communityName));
}
else if (searchScope instanceof Collection)
{
Collection collection = (Collection) searchScope;
String collectionName = collection.getMetadata("name");
results.setHead(T_head1_collection.parameterize(collectionName));
}
else
{
results.setHead(T_head1_none);
}
if (queryResults.getHitCount() > 0)
{
// Pagination variables.
int itemsTotal = queryResults.getHitCount();
int firstItemIndex = queryResults.getStart() + 1;
int lastItemIndex = queryResults.getStart()
+ queryResults.getPageSize();
if (itemsTotal < lastItemIndex)
{
lastItemIndex = itemsTotal;
}
int currentPage = (queryResults.getStart() / queryResults
.getPageSize()) + 1;
int pagesTotal = ((queryResults.getHitCount() - 1) / queryResults
.getPageSize()) + 1;
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("page", "{pageNum}");
String pageURLMask = generateURL(parameters);
results.setMaskedPagination(itemsTotal, firstItemIndex,
lastItemIndex, currentPage, pagesTotal, pageURLMask);
// Look for any communities or collections in the mix
ReferenceSet referenceSet = null;
boolean resultsContainsBothContainersAndItems = false;
@SuppressWarnings("unchecked") // This cast is correct
java.util.List<String> containerHandles = queryResults.getHitHandles();
for (String handle : containerHandles)
{
DSpaceObject resultDSO = HandleManager.resolveToObject(
context, handle);
if (resultDSO instanceof Community
|| resultDSO instanceof Collection)
{
if (referenceSet == null) {
referenceSet = results.addReferenceSet("search-results-repository",
ReferenceSet.TYPE_SUMMARY_LIST,null,"repository-search-results");
// Set a heading showing that we will be listing containers that matched:
referenceSet.setHead(T_head2);
resultsContainsBothContainersAndItems = true;
}
referenceSet.addReference(resultDSO);
}
}
// Look for any items in the result set.
referenceSet = null;
@SuppressWarnings("unchecked") // This cast is correct
java.util.List<String> itemHandles = queryResults.getHitHandles();
for (String handle : itemHandles)
{
DSpaceObject resultDSO = HandleManager.resolveToObject(
context, handle);
if (resultDSO instanceof Item)
{
if (referenceSet == null) {
referenceSet = results.addReferenceSet("search-results-repository",
ReferenceSet.TYPE_SUMMARY_LIST,null,"repository-search-results");
// Only set a heading if there are both containers and items.
if (resultsContainsBothContainersAndItems)
{
referenceSet.setHead(T_head3);
}
}
referenceSet.addReference(resultDSO);
}
}
}
else
{
results.addPara(T_no_results);
}
}// Empty query
}
/**
* Add options to the search scope field. This field determines in what
* communities or collections to search for the query.
*
* The scope list will depend upon the current search scope. There are three
* cases:
*
* No current scope: All top level communities are listed.
*
* The current scope is a community: All collections contained within the
* community are listed.
*
* The current scope is a collection: All parent communities are listed.
*
* @param scope
* The current scope field.
*/
protected void buildScopeList(Select scope) throws SQLException,
WingException
{
DSpaceObject scopeDSO = getScope();
if (scopeDSO == null)
{
// No scope, display all root level communities
scope.addOption("/",T_all_of_dspace);
scope.setOptionSelected("/");
for (Community community : Community.findAllTop(context))
{
scope.addOption(community.getHandle(),community.getMetadata("name"));
}
}
else if (scopeDSO instanceof Community)
{
// The scope is a community, display all collections contained
// within
Community community = (Community) scopeDSO;
scope.addOption("/",T_all_of_dspace);
scope.addOption(community.getHandle(),community.getMetadata("name"));
scope.setOptionSelected(community.getHandle());
for (Collection collection : community.getCollections())
{
scope.addOption(collection.getHandle(),collection.getMetadata("name"));
}
}
else if (scopeDSO instanceof Collection)
{
// The scope is a collection, display all parent collections.
Collection collection = (Collection) scopeDSO;
scope.addOption("/",T_all_of_dspace);
scope.addOption(collection.getHandle(),collection.getMetadata("name"));
scope.setOptionSelected(collection.getHandle());
Community[] communities = collection.getCommunities()[0]
.getAllParents();
for (Community community : communities)
{
scope.addOption(community.getHandle(),community.getMetadata("name"));
}
}
}
/**
* Query DSpace for a list of all items / collections / or communities that
* match the given search query.
*/
protected void performSearch() throws SQLException, IOException, UIException
{
if (queryResults != null)
{
return;
}
Context context = ContextUtil.obtainContext(objectModel);
String query = getQuery();
DSpaceObject scope = getScope();
int page = getParameterPage();
queryArgs = new QueryArgs();
queryArgs.setPageSize(getParameterRpp());
try
{
queryArgs.setSortOption(SortOption.getSortOption(getParameterSortBy()));
}
catch (SortException se)
{
}
queryArgs.setSortOrder(getParameterOrder());
queryArgs.setQuery(query);
if (page > 1)
{
queryArgs.setStart((Integer.valueOf(page) - 1) * queryArgs.getPageSize());
}
else
{
queryArgs.setStart(0);
}
QueryResults qResults = null;
if (scope instanceof Community)
{
qResults = DSQuery.doQuery(context, queryArgs, (Community) scope);
}
else if (scope instanceof Collection)
{
qResults = DSQuery.doQuery(context, queryArgs, (Collection) scope);
}
else
{
qResults = DSQuery.doQuery(context, queryArgs);
}
this.queryResults = qResults;
}
/**
* Determine the current scope. This may be derived from the current url
* handle if present or the scope parameter is given. If no scope is
* specified then null is returned.
*
* @return The current scope.
*/
protected DSpaceObject getScope() throws SQLException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String scopeString = request.getParameter("scope");
// Are we in a community or collection?
DSpaceObject dso;
if (scopeString == null || "".equals(scopeString))
{
// get the search scope from the url handle
dso = HandleUtil.obtainHandle(objectModel);
}
else
{
// Get the search scope from the location parameter
dso = HandleManager.resolveToObject(context, scopeString);
}
return dso;
}
protected int getParameterPage()
{
try
{
return Integer.parseInt(ObjectModelHelper.getRequest(objectModel).getParameter("page"));
}
catch (Exception e)
{
return 1;
}
}
protected int getParameterRpp()
{
try
{
return Integer.parseInt(ObjectModelHelper.getRequest(objectModel).getParameter("rpp"));
}
catch (Exception e)
{
return 10;
}
}
protected int getParameterSortBy()
{
try
{
return Integer.parseInt(ObjectModelHelper.getRequest(objectModel).getParameter("sort_by"));
}
catch (Exception e)
{
return 0;
}
}
protected String getParameterOrder()
{
String s = ObjectModelHelper.getRequest(objectModel).getParameter("order");
return s != null ? s : "DESC";
}
protected int getParameterEtAl()
{
try
{
return Integer.parseInt(ObjectModelHelper.getRequest(objectModel).getParameter("etal"));
}
catch (Exception e)
{
return 0;
}
}
protected QueryResults getQueryResults() {
return queryResults;
}
/**
* Determine if the scope of the search should fixed or is changeable by the
* user.
*
* The search scope when preformed by url, i.e. they are at the url handle/xxxx/xx/search
* then it is fixed. However at the global level the search is variable.
*
* @return true if the scope is variable, false otherwise.
*/
protected boolean variableScope() throws SQLException
{
return (HandleUtil.obtainHandle(objectModel) == null);
}
/**
* Extract the query string. Under most implementations this will be derived
* from the url parameters.
*
* @return The query string.
*/
protected abstract String getQuery() throws UIException;
/**
* Generate a url to the given search implementation with the associated
* parameters included.
*
* @param parameters
* @return The post URL
*/
protected abstract String generateURL(Map<String, String> parameters)
throws UIException;
/**
* Recycle
*/
public void recycle()
{
this.queryResults = null;
this.validity = null;
super.recycle();
}
protected void buildSearchControls(Division div)
throws WingException
{
Table controlsTable = div.addTable("search-controls", 1, 3);
Row controlsRow = controlsTable.addRow(Row.ROLE_DATA);
// Create a control for the number of records to display
Cell rppCell = controlsRow.addCell();
rppCell.addContent(T_rpp);
Select rppSelect = rppCell.addSelect("rpp");
for (int i : RESULTS_PER_PAGE_PROGRESSION)
{
rppSelect.addOption((i == getParameterRpp()), i, Integer.toString(i));
}
Cell sortCell = controlsRow.addCell();
try
{
// Create a drop down of the different sort columns available
sortCell.addContent(T_sort_by);
Select sortSelect = sortCell.addSelect("sort_by");
sortSelect.addOption(false, 0, T_sort_by_relevance);
for (SortOption so : SortOption.getSortOptions())
{
if (so.isVisible())
{
sortSelect.addOption((so.getNumber() == getParameterSortBy()), so.getNumber(),
message("xmlui.ArtifactBrowser.AbstractSearch.sort_by." + so.getName()));
}
}
}
catch (SortException se)
{
throw new WingException("Unable to get sort options", se);
}
// Create a control to changing ascending / descending order
Cell orderCell = controlsRow.addCell();
orderCell.addContent(T_order);
Select orderSelect = orderCell.addSelect("order");
orderSelect.addOption(SortOption.ASCENDING.equals(getParameterOrder()), SortOption.ASCENDING, T_order_asc);
orderSelect.addOption(SortOption.DESCENDING.equals(getParameterOrder()), SortOption.DESCENDING, T_order_desc);
// Create a control for the number of authors per item to display
// FIXME This is currently disabled, as the supporting functionality
// is not currently present in xmlui
//if (isItemBrowse(info))
//{
// controlsForm.addContent(T_etal);
// Select etalSelect = controlsForm.addSelect(BrowseParams.ETAL);
//
// etalSelect.addOption((info.getEtAl() < 0), 0, T_etal_all);
// etalSelect.addOption(1 == info.getEtAl(), 1, Integer.toString(1));
//
// for (int i = 5; i <= 50; i += 5)
// {
// etalSelect.addOption(i == info.getEtAl(), i, Integer.toString(i));
// }
//}
}
protected void logSearch()
{
int countCommunities = 0;
int countCollections = 0;
int countItems = 0;
for (Integer type : queryResults.getHitTypes())
{
switch (type.intValue())
{
case Constants.ITEM: countItems++; break;
case Constants.COLLECTION: countCollections++; break;
case Constants.COMMUNITY: countCommunities++; break;
}
}
String logInfo = "";
try
{
DSpaceObject dsoScope = getScope();
if (dsoScope instanceof Collection)
{
logInfo = "collection_id=" + dsoScope.getID() + ",";
}
else if (dsoScope instanceof Community)
{
logInfo = "community_id=" + dsoScope.getID() + ",";
}
}
catch (SQLException sqle)
{
// Ignore, as we are only trying to get the scope to add detail to the log message
}
log.info(LogManager.getHeader(context, "search", logInfo + "query=\""
+ queryArgs.getQuery() + "\",results=(" + countCommunities + ","
+ countCollections + "," + countItems + ")"));
}
}
| 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.artifactbrowser;
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.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.Para;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.sql.SQLException;
/**
* Renders the search box for a collection
*
* @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 CollectionSearch extends AbstractDSpaceTransformer {
private static final Message T_full_text_search =
message("xmlui.ArtifactBrowser.CollectionViewer.full_text_search");
private static final Message T_go =
message("xmlui.general.go");
private static final Message T_advanced_search_link=
message("xmlui.ArtifactBrowser.CollectionViewer.advanced_search_link");
@Override
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException {
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Collection))
{
return;
}
// Set up the major variables
Collection collection = (Collection) dso;
Division home = body.addDivision("collection-home", "primary repository collection");
Division search = home.addDivision("collection-search-browse",
"secondary search-browse");
// Search query
Division query = search.addInteractiveDivision("collection-search",
contextPath + "/handle/" + collection.getHandle() + "/search",
Division.METHOD_POST, "secondary search");
Para para = query.addPara("search-query", null);
para.addContent(T_full_text_search);
para.addContent(" ");
para.addText("query");
para.addContent(" ");
para.addButton("submit").setValue(T_go);
query.addPara().addXref(contextPath + "/handle/" + collection.getHandle()+ "/advanced-search", T_advanced_search_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.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
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.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;
/**
* Simple page to let the user know their feedback has been sent.
*
* @author Scott Phillips
*/
public class FeedbackSent extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** language strings */
public static final Message T_title =
message("xmlui.ArtifactBrowser.FeedbackSent.title");
public static final Message T_dspace_home =
message("xmlui.general.dspace_home");
public static final Message T_trail =
message("xmlui.ArtifactBrowser.FeedbackSent.trail");
public static final Message T_head =
message("xmlui.ArtifactBrowser.FeedbackSent.head");
public static final Message T_para1 =
message("xmlui.ArtifactBrowser.FeedbackSent.para1");
/**
* Generate the unique caching key.
*/
public Serializable getKey() {
return "1";
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity()
{
return NOPValidity.SHARED_INSTANCE;
}
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 void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Division feedback = body.addDivision("feedback-sent","primary");
feedback.setHead(T_head);
feedback.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.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.Hidden;
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.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 basic form capabilities of DRI. All
* the fields used here will be simple and only used inside the
* context of a form.
*
* 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 BasicFormTest extends AbstractDSpaceTransformer
{
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent("Basic Form Test");
pageMeta.addTrailLink(contextPath + "/","DSpace Home");
pageMeta.addTrail().addContent("Basic 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("Basic 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("Fields");
// Text field
Text text = list.addItem().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");
// Long help
Text longHelp = list.addItem().addText("longHelp");
longHelp.setLabel("Long Help");
if (help)
{
longHelp.setHelp("This is a really long help message. It could potentially be a paragraph of material, really really long. Actually we don't know how long it can be because there is no upper limit on it! Although if you do find your self adding a long help message consider whether your user will actually read any of this, my bet is that they won't. However we still need to support these really, really, really, long messages that may break across multiple lines!");
}
if (error)
{
longHelp.addError("This field is in error.");
}
longHelp.setValue("Current raw value");
// Long error
Text longError = list.addItem().addText("longError");
longError.setLabel("Long Error");
if (help)
{
longError.setHelp("TThis is helpfull text.");
}
if (error)
{
longError.addError("This field is very much is serious trouble, it's so horrible wrong that i now have to give you a very long stern message that may break across multiple lines! To fix this problem you should examine what you are attempting to do and consider other factors like what might have lead you to this path vs another path. Are you sure you even want this field or might another one work just as well?");
}
longError.setValue("Current raw value");
// Text Area Field
TextArea textArea = list.addItem().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");
// Blank Text Area Field
TextArea emptyTextArea = list.addItem().addTextArea("emptyTextarea");
emptyTextArea.setLabel("Empty Text Area");
if (help)
{
emptyTextArea.setHelp("This is helpfull text.");
}
if (error)
{
emptyTextArea.addError("This field is in error.");
}
// Password field
Password password = list.addItem().addPassword("password");
password.setLabel("password");
if (help)
{
password.setHelp("This is helpfull text.");
}
if (error)
{
password.addError("This field is in error.");
}
// Hidden field
Hidden hidden = list.addItem().addHidden("hidden");
hidden.setLabel("Hidden");
hidden.setValue("You can not see this.");
if (help)
{
hidden.setHelp("This is hidden help?");
}
if (error)
{
hidden.addError("This a hidden error - I have no idea what this means?");
}
// Checkbox field
CheckBox checkBox = list.addItem().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");
// Radio buttons
Radio radio = list.addItem().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");
// File
File file = list.addItem().addFile("file");
file.setLabel("File");
if (help)
{
file.setHelp("Upload a file.");
}
if (error)
{
file.addError("This field is in error.");
}
// Select (single)
Select select = list.addItem().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");
select = list.addItem().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");
// Non-Field-item
list.addLabel("Non-Field");
list.addItem().addContent("This is just text, not a field, but it has a list label.");
// Button
Button button = list.addItem().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.");
}
// Non-field-unlabeled-item
list.addItem().addContent("The following fields are all various use cases of composites. Also note that this item is an item inside a list of type form that 1) does not contain a field and 2) does not have a label.");
// Composite
Composite composite = list.addItem().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");
}
// composite select & text fields
composite = list.addItem().addComposite("compositeB");
composite.setLabel("Composite (select & text fields)");
if (help)
{
composite.setHelp("This field is composed of a select and text field, select one and type the other.");
}
select = composite.addSelect("selectB");
select.setLabel("Numbers");
if (help)
{
select.setHelp("Me, me, me..... select me!");
}
if (error)
{
select.addError("The composite components 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");
text = composite.addText("TextB");
text.setLabel("Spanish Numbers");
if (help)
{
text.setHelp("Yay, yet another text field");
}
if (error)
{
text.addError("The composite components are in error.");
}
// Composite
composite = list.addItem().addComposite("composite-date");
composite.setLabel("Composite (date)");
if (help)
{
composite.setHelp("The data the item was published.");
}
if (error)
{
composite.addError("The date is in error.");
}
text = composite.addText("year");
text.setLabel("Year");
text.setSize(4,4);
if (help)
{
text.setHelp("year");
}
if (error)
{
text.addError("The year is in error");
}
select = composite.addSelect("month");
select.setLabel("Month");
if (error)
{
select.addError("The month is in error");
}
if (help)
{
text.setHelp("month");
}
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");
text = composite.addText("day");
text.setLabel("Day");
if (help)
{
text.setHelp("day");
}
if (error)
{
text.addError("The day is in error.");
}
text.setSize(4,2);
// 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");
/////////////////////////////////////////////////
/// Multi section
////////////////////////////////////////////////
div.addPara("This next test will use form sections. Sections are logical groupings of related fields that together form the entire set.");
list = div.addList("sectionTest",List.TYPE_FORM);
list.setHead("Multi-Section form");
List identity = list.addList("identity",List.TYPE_FORM);
identity.setHead("Identity");
Text name = identity.addItem().addText("name");
name.setLabel("Username");
if (help)
{
name.setHelp("The username you wish to chooose");
}
if (error)
{
name.addError("Sorry, that username is allready used by another user.");
}
Composite ssn = identity.addItem().addComposite("ssn");
ssn.setLabel("SSN");
if (help)
{
ssn.setHelp("Your Social Security Number, really we won't use it for anything bad.... you can trust me.");
}
if (error)
{
ssn.addError("The SSN you entered is invalid.");
}
Text ssn1 = ssn.addText("ssn1");
ssn1.setSize(4,4);
Text ssn2 = ssn.addText("ssn2");
ssn2.setSize(2,2);
Text ssn3 = ssn.addText("ssn3");
ssn3.setSize(4,4);
List intrests = list.addList("intrests",List.TYPE_FORM);
intrests.setHead("Intrests");
CheckBox intrest = intrests.addItem().addCheckBox("intrests");
intrest.setLabel("Intrests");
if (help)
{
intrest.setHelp("Select all topics which are of intrests to you.");
}
if (error)
{
intrest.addError("You're intrests are in error?");
}
intrest.addOption("DL","Digital Libraries");
intrest.addOption("HT","Hypertexts");
intrest.addOption("IM","Information Managment");
intrest.addOption("ID","Information Discovery");
intrest.addOption("SI","Social Impact");
List affiliation = list.addList("affiliation",List.TYPE_FORM);
affiliation.setHead("Affiliation");
Text institution = affiliation.addItem().addText("institution");
institution.setLabel("Institution");
if (help)
{
name.setHelp("The institution you are affiliated with");
}
if (error)
{
name.addError("That institution is an invalid option.");
}
Radio geography = affiliation.addItem().addRadio("geography");
geography.setLabel("Geography");
if (help)
{
geography.setHelp("Select your institution's geographical region");
}
if (error)
{
geography.addError("Your entry is invalid.");
}
geography.addOption("na","North America");
geography.addOption("sa","South America");
geography.addOption("eu","Europe");
geography.addOption("af","Africa");
geography.addOption("ai","Asia");
geography.addOption("pi","Pacific Island");
geography.addOption("an","Antarctica");
Item buttons = list.addItem();
buttons.addButton("submit_save2").setValue("Save");
buttons.addButton("submit_cancel2").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.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.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* This is a class to test the capabilities of DRI's structural
* elements: i.e. divs, paragraphs, lists, and tables.
*
* 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 StructureTest extends AbstractDSpaceTransformer
{
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent("Structural Test");
pageMeta.addTrailLink(contextPath + "/","DSpace Home");
pageMeta.addTrail().addContent("Structural Test");
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Division test = body.addDivision("test");
test.setHead("Structural Tests");
test.addPara("This is a series of tests that show various options and uses of DRI's structural elements: divisions, paragraphs, lists, and tables.");
//////////////////////////////////////
// Paragrpah test
Division paraT = test.addDivision("para");
paraT.setHead("1) Paragraph Tests");
paraT.addPara("This is a simple paragraph");
Para para = paraT.addPara();
para.addContent("This is ");
para.addHighlight("bold").addContent("not");
para.addContent(" a ");
para.addHighlight("bold").addHighlight("italic").addContent("simple");
para.addContent(" paragraph.");
/////////////////////////////////////
// List test
Division listT = test.addDivision("list");
listT.setHead("2) List Tests");
List list = listT.addList("simple");
list.setHead("Simple list");
list.addItem("one");
list.addItem("two");
list.addItem("three");
list = listT.addList("labeled");
list.setHead("Simple list ( with labels )");
list.addLabel("uno");
list.addItem("one");
list.addLabel("dos");
list.addItem("two");
list.addLabel("threes");
list.addItem("three");
list = listT.addList("bulleted",List.TYPE_BULLETED);
list.setHead("Bulleted list");
list.addItem("one");
list.addItem("two");
list.addItem("three");
list = listT.addList("ordered",List.TYPE_ORDERED);
list.setHead("Ordered list");
list.addItem("one");
list.addItem("two");
list.addItem("three");
list = listT.addList("glossary",List.TYPE_GLOSS);
list.setHead("Glossary list");
list.addLabel("uno");
list.addItem("one");
list.addLabel("dos");
list.addItem("two");
list.addLabel("tres");
list.addItem("three");
// Nests
list = listT.addList("simple-nest");
list.setHead("Simple list ( nested )");
list.addItem("one");
list.addItem("two");
List nest = list.addList("nest1");
nest.setHead("Sub list point three");
nest.addItem("three point one");
nest.addItem("three point two");
nest.addItem("three point three");
list.addItem("four");
list = listT.addList("labeled-nest");
list.setHead("Simple list ( with labels and nested )");
list.addLabel("uno");
list.addItem("one");
list.addLabel("dos");
list.addItem("two");
nest = list.addList("nest2");
nest.addLabel("dos punto uno");
nest.addItem("two point one");
nest.addLabel("dos punto dos");
nest.addItem("two point two");
nest.addLabel("dos punto tres");
nest.addItem("two point three");
list.addLabel("threes");
list.addItem("three");
list = listT.addList("bulleted-nest",List.TYPE_BULLETED);
list.setHead("Bulleted list ( nested )");
list.addItem("one");
list.addItem("two");
nest = list.addList("nest3");
nest.addItem("three point one");
nest.addItem("three point two");
nest.addItem("three point three");
list.addItem("four");
list = listT.addList("ordered-nest",List.TYPE_ORDERED);
list.setHead("Ordered list ( nested )");
list.addItem("one");
list.addItem("two");
nest = list.addList("nest4");
nest.setHead("Sub list point three");
nest.addItem("three point one");
nest.addItem("three point two");
nest.addItem("three point three");
list.addItem("four");
list = listT.addList("glossary-nest",List.TYPE_GLOSS);
list.setHead("Glossary list ( nested )");
list.addLabel("uno");
list.addItem("one");
list.addLabel("dos");
list.addItem("two");
nest = list.addList("nest5");
nest.addLabel("dos punto uno");
nest.addItem("two point one");
nest.addLabel("dos punto dos");
nest.addItem("two point two");
nest.addLabel("dos punto tres");
nest.addItem("two point three");
list.addLabel("tres");
list.addItem("three");
///////////////////////////////////////////////////
// Table test
Division tableT = test.addDivision("table");
tableT.setHead("3) Table Tests");
// Simple table
Table table = tableT.addTable("table1",3,3);
table.setHead("Table: simple");
Row row = table.addRow();
row.addCellContent("1.1");
row.addCellContent("1.2");
row.addCellContent("1.3");
row = table.addRow();
row.addCellContent("2.1");
row.addCellContent("2.2");
row.addCellContent("2.3");
row = table.addRow();
row.addCellContent("3.1");
row.addCellContent("3.2");
row.addCellContent("3.3");
// Header vs data rows
table = tableT.addTable("table1",4,3);
table.setHead("Table: header vs data roles");
row = table.addRow(Row.ROLE_HEADER);
row.addCellContent("This whole");
row.addCellContent("row is a");
row.addCellContent("Header");
row = table.addRow();
row.addCellContent("2.1");
row.addCellContent("2.2");
row.addCellContent("2.3");
row = table.addRow();
row.addCellContent("3.1");
row.addCell(Cell.ROLE_HEADER).addContent("3.2 - single cell header");
row.addCellContent("3.3");
row = table.addRow();
row.addCellContent("4.1");
row.addCellContent("4.2");
row.addCellContent("4.3");
// column and row spans
table = tableT.addTable("table1",6,3);
table.setHead("Table: column & row spans");
row = table.addRow();
row.addCellContent("1.1");
row.addCellContent("1.2");
row.addCellContent("1.3");
row = table.addRow();
row.addCell(null,null,0,3,null).addContent("2.1 - spans three columns");
row = table.addRow();
row.addCellContent("3.1");
row.addCell(null,null,3,0,null).addContent("3.2 - spans three rows");
row.addCellContent("3.3");
row = table.addRow();
row.addCellContent("4.1");
//row.addCellContent("3.2"); // Should be missing
row.addCellContent("4.3");
row = table.addRow();
row.addCellContent("5.1");
//row.addCellContent("5.2"); // Should be missing
row.addCellContent("5.3");
row = table.addRow();
row.addCellContent("6.1");
row.addCellContent("6.2");
row.addCellContent("6.3");
}
}
| 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.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
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 capabilities of including HTML inside
* a DRI document. This can be usefull for resources out side of a
* developers control such as text files on disk or user supplied data.
*
* 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 HTMLTest extends AbstractDSpaceTransformer
{
// The default string to include in test, may be overridden by the user.
private static final String DEFAULT_HTML_STRING = "<p>This is a test of manakin's ability to render HTML fragments.</p>\n\n<p>Only a few tags are allowed such as: <b>bold</b>, <i>italic</i>, <u>underline</u>, and <a href=\"http://di.tamu.edu/\">link</a>.</p>\n\n<h2>This is a heading</h2>\n\nInvalid tags are treated as plain text: <invalid attribute=\"a\">this is invalid</invalid>\n\nAlso line breaks may be treated as a paragraphs when that action is specified.";
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent("HTML Test");
pageMeta.addTrailLink(contextPath + "/","DSpace Home");
pageMeta.addTrail().addContent("HTML Test");
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Request request = ObjectModelHelper.getRequest(objectModel);
String fragment = request.getParameter("fragment");
String[] options = request.getParameterValues("options");
// If none present set the default HTML string
if (fragment == null || fragment.length() <= 0)
{
fragment = DEFAULT_HTML_STRING;
}
boolean blankLines = false;
if (options != null && options[0].equals("blankLines"))
{
blankLines = true;
}
Division div = body.addInteractiveDivision("html-test", "", Division.METHOD_GET, "primary");
div.setHead("HTML Test");
div.addPara("This page tests Manakin's ability to handle HTML fragments, this ability is normally used to handle user-inputed text. There are two reasons for using this ability of including user supplied HTML fragments 1) it doesn't break the abstraction between themes and aspects, 2) it provides a safety mechanism preventing security vulnerabilities such as cross site scripting.");
List form = div.addList("html-test",List.TYPE_FORM);
TextArea fragmentField = form.addItem().addTextArea("fragment");
fragmentField.setLabel("Fragment");
fragmentField.setHelp("Enter free formed text, you may use <p>,<a>,<b>,<i>, or <img> tags.");
fragmentField.setSize(15, 50);
fragmentField.setValue(fragment);
CheckBox optionsField = form.addItem().addCheckBox("options");
optionsField.setLabel("Options");
optionsField.addOption("blankLines", "Treat blank lines as paragraph breaks.");
if (blankLines)
{
optionsField.setOptionSelected("blankLines");
}
Button submit = form.addItem().addButton("submit");
submit.setValue("Test HTML Rendering");
Division test = div.addDivision("html-test-sample");
test.setHead("Rendered Sample");
test.addSimpleHTMLFragment(blankLines, fragment);
}
}
| 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.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.List;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* @author Scott Phillips
*/
public class Navigation extends AbstractDSpaceTransformer
{
public void addOptions(Options options) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
List test = options.addList("XMLTest");
test.setHead("XML Test");
test.addItemXref(contextPath + "/xmltest/structural","Structural");
test.addItemXref(contextPath + "/xmltest/HTML","HTML");
List form = test.addList("FormTest");
form.setHead("Forms");
form.addItemXref(contextPath + "/xmltest/form/basic","Basic");
form.addItemXref(contextPath + "/xmltest/form/inline","In line");
form.addItemXref(contextPath + "/xmltest/form/advanced","Advanced");
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.