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.webui.submit;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
/**
* Abstract 'binding' class for DSpace Submission Steps which use the JSP-UI.
* <P>
* These methods revolve around the following: (1) pre-processing of data to
* prepare for display, (2) displaying the JSP, and (3) post-processing of any
* user input (or alternatively backend processing, for non-interactive steps).
* <P>
* For the JSP UI, the job of this class is to maintain the context of where the
* user is within the current "step" of the submission process. Each "step" can
* consist of multiple "pages" (which roughly correspond to HTML displays), so
* this class helps manage which page the user should see next.
* <P>
* The methods of the JSPStepManager are called in this order:
* <ul>
* <li>Call doPreProcessing() method</li>
* <li>If showJSP() was specified from doPreProcessing(), then the JSP
* specified will be displayed</li>
* <li>If showJSP() was not specified from doPreProcessing(), then the
* doProcessing() method is called an the step completes immediately</li>
* <li>Call doProcessing() method on appropriate AbstractProcessingStep after the user returns from the JSP, in order
* to process the user input</li>
* <li>Call doPostProcessing() method to determine if more user interaction is
* required, and if further JSPs need to be called.</li>
* <li>If there are more "pages" in this step then, the process begins again
* (for the new page).</li>
* <li>Once all pages are complete, control is forwarded back to the
* SubmissionController, and the next step is called.</li>
* </ul>
*
* @see org.dspace.submit.AbstractProcessingStep
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.util.SubmissionConfig
* @see org.dspace.app.util.SubmissionStepConfig
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public abstract class JSPStep
{
/**
* Value to return from doPreProcessing to specify not to load any JSP Page
* (equal to "") *
*/
public static final String NO_JSP = "";
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public abstract void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException;
/**
* Do any post-processing after the step's backend processing occurred (in
* the doProcessing() method).
* <P>
* It is this method's job to determine whether processing completed
* successfully, or display another JSP informing the users of any potential
* problems/errors.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
public abstract void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException;
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public abstract String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo);
}
| 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.webui.submit;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.servlet.SubmissionController;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.util.SubmissionStepConfig;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.WorkspaceItem;
import org.dspace.core.Context;
import org.dspace.submit.AbstractProcessingStep;
/**
* Manages and processes all JSP-UI classes for DSpace Submission steps.
* <P>
* This manager is utilized by the SubmissionController to appropriately
* load each JSP-UI step, and process any information returned by each step
*
* @see org.dspace.submit.AbstractProcessingStep
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPStepManager
{
/** log4j logger */
private static Logger log = Logger.getLogger(JSPStepManager.class);
/**
* Current Processing class for step that is being processed by the JSPStepManager
* This is the class that performs processing of information entered in during a step
*/
private AbstractProcessingStep stepProcessing = null;
/**
* Current JSP-UI binding class for step that is being processed by the JSPStepManager
* This is the class that manages calling all JSPs, and determines if additional processing
* of information (or confirmation) is necessary.
*/
private JSPStep stepJSPUI = null;
/**
* The SubmissionStepConfig object describing the current step
**/
private SubmissionStepConfig stepConfig = null;
/**
* Initialize the current JSPStepManager object, by loading the
* specified step class.
*
* @param stepConfig
* the SubmissionStepConfig object which describes
* this step's configuration in the item-submission.xml
*
* @throws Exception
* if the JSPStep cannot be loaded or the class
* specified doesn't implement the JSPStep interface
*/
public static JSPStepManager loadStep(SubmissionStepConfig stepConfig) throws Exception
{
JSPStepManager stepManager = new JSPStepManager();
//save step configuration
stepManager.stepConfig = stepConfig;
/*
* First, load the step processing class (using the current class loader)
*/
ClassLoader loader = stepManager.getClass().getClassLoader();
Class stepClass = loader
.loadClass(stepConfig.getProcessingClassName());
Object stepInstance = stepClass.newInstance();
if(stepInstance instanceof AbstractProcessingStep)
{
// load the JSPStep interface for this step
stepManager.stepProcessing = (AbstractProcessingStep) stepClass.newInstance();
}
else
{
throw new Exception("The submission step class specified by '" + stepConfig.getProcessingClassName() +
"' does not extend the class org.dspace.submit.AbstractProcessingStep!" +
" Therefore it cannot be used by the Configurable Submission as the <processing-class>!");
}
/*
* Next, load the step's JSPUI binding class (using the current class loader)
* (Only load JSPUI binding class if specified...otherwise this is a non-interactive step)
*/
if(stepConfig.getJSPUIClassName()!=null && stepConfig.getJSPUIClassName().length()>0)
{
stepClass = loader
.loadClass(stepConfig.getJSPUIClassName());
stepInstance = stepClass.newInstance();
if(stepInstance instanceof JSPStep)
{
// load the JSPStep interface for this step
stepManager.stepJSPUI = (JSPStep) stepClass.newInstance();
}
else
{
throw new Exception("The submission step class specified by '" + stepConfig.getJSPUIClassName() +
"' does not extend the class org.dspace.app.webui.JSPStep!" +
" Therefore it cannot be used by the Configurable Submission for the JSP user interface!");
}
}
return stepManager;
}
/**
* Initialize the current JSPStepManager object, to prepare for processing
* of this step. This method is called by the SubmissionController, and its
* job is to determine which "page" of the step the current user is on.
* <P>
* Once the page has been determined, this method also determines whether
* the user is completing this page (i.e. there is user input data that
* needs to be saved to the database) or beginning this page (i.e. the user
* needs to be sent to the JSP for this page).
*
* @param context
* a DSpace Context object
* @param request
* the HTTP request
* @param response
* the HTTP response
* @param subInfo
* submission info object
*
* @return true if step is completed (successfully), false otherwise
*
* @throws ServletException
* if a general error occurs
* @throws IOException
* if a i/o error occurs
* @throws SQLException
* if a database error occurs
* @throws AuthorizeException
* if some authorization error occurs
*/
public final boolean processStep(Context context,
HttpServletRequest request, HttpServletResponse response,
SubmissionInfo subInfo) throws ServletException, IOException,
SQLException, AuthorizeException
{
/*
* This method SHOULD NOT BE OVERRIDDEN, unless it's absolutely
* necessary. If you override this method, make sure you call the
* "doStepStart()" and "doStepEnd()" methods at the appropriate time in
* your processStep() method.
*
*/
/*
* Figure out Current Page in this Step
*/
int currentPage = -1;
// if user came to this Step by pressing "Previous" button
// from the following step, then we will have to calculate
// the correct page to go to.
if ((request.getAttribute("step.backwards") != null)
&& ((Boolean) request.getAttribute("step.backwards"))
.booleanValue())
{
// current page should be the LAST page in this step
currentPage = getNumPagesInProgressBar(subInfo, this.stepConfig
.getStepNumber());
AbstractProcessingStep.setCurrentPage(request, currentPage);
}
else
{
// retrieve current page number from request
currentPage = AbstractProcessingStep.getCurrentPage(request);
}
/*
* Update Last page reached (if necessary)
*/
int pageReached = getPageReached(subInfo);
// TD: Special Case, where an item was just rejected & returned to
// Workspace. In this case, we have an invalid "pageReached" in
// the database which needs updating
if (pageReached == AbstractProcessingStep.LAST_PAGE_REACHED)
{
// the first time this flag is encountered, we have to update
// the Database with the number of the last page in the current
// StepReached
// get the number of pages in the last step reached
int lastPageNum = getNumPagesInProgressBar(subInfo,
SubmissionController.getStepReached(subInfo));
// update database with the number of this last page
updatePageReached(subInfo, lastPageNum);
context.commit();
}
// otherwise, check if pageReached needs updating
// (it only needs updating if we're in the latest step reached,
// and we've made it to a later page in that step)
else if ((this.stepConfig.getStepNumber() == SubmissionController
.getStepReached(subInfo))
&& (currentPage > pageReached))
{
// reset page number reached & commit to database
updatePageReached(subInfo, currentPage);
context.commit();
}
/*
* Determine whether we are Starting or Finishing this Step
*/
// check if we just started this step
boolean beginningOfStep = SubmissionController
.isBeginningOfStep(request);
// if this step has just been started, do beginning processing
if (beginningOfStep)
{
return doStepStart(context, request, response, subInfo);
}
else
// We just returned from a page (i.e. JSP), so we need to do any end
// processing
{
return doStepEnd(context, request, response, subInfo);
}
}
/**
* Do the beginning of a Step. First do pre-processing, then display the JSP
* (if there is one). If there's no JSP, just End the step immediately.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*
* @return true if the step is completed (no JSP was loaded), false
* otherwise
*
*/
private boolean doStepStart(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
log.debug("Doing pre-processing for step " + this.getClass().getName());
// first, do any pre-processing and get the JSP to display
// (assuming that this step has an interface)
if(stepJSPUI!=null)
{
stepJSPUI.doPreProcessing(context, request, response, subInfo);
}
// Complete this step, if this response has not already
// been committed.
//
// Note: the response should only be "committed" if the user
// has be forwarded on to a JSP page (in which case the step
// is not finished!).
if (!response.isCommitted())
{
// Otherwise, this is a non-interactive step!
// There's no JSP to display, so only perform the processing
// and forward back to the Submission Controller servlet
log.debug("Calling processing for step "
+ this.getClass().getName());
int errorFlag = stepProcessing.doProcessing(context, request, response, subInfo);
// if it didn't complete successfully, try and log this error!
if (errorFlag != AbstractProcessingStep.STATUS_COMPLETE)
{
// see if an error message was defined!
String errorMessage = stepProcessing.getErrorMessage(errorFlag);
// if not defined, construct a dummy error
if (errorMessage == null)
{
errorMessage = "The doProcessing() method for "
+ this.getClass().getName()
+ " returned an error flag = "
+ errorFlag
+ ". "
+ "It is recommended to define a custom error message for this error flag using the addErrorMessage() method!";
}
log.error(errorMessage);
}
return completeStep(context, request, response, subInfo);
}
else
{
return false; // step not completed
}
}
/**
* This method actually displays a JSP page for this "step". This method can
* be called from "doPostProcessing()" to display an error page, etc.
*
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param pathToJSP
* context path to the JSP to display
*
*/
public static final void showJSP(HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo,
String pathToJSP) throws ServletException, IOException,
SQLException
{
// As long as user is not currently cancelling
// or saving submission, show the JSP specified
if (!response.isCommitted()
&& !SubmissionController.isCancellationInProgress(request))
{
// set beginningOfStep flag to false
// (so that we know it will be time for "post-processing"
// after loading the JSP)
SubmissionController.setBeginningOfStep(request, false);
// save our current Submission information into the Request
// object (so JSP has access to it)
SubmissionController.saveSubmissionInfo(request, subInfo);
// save our current page information to Request object
//setCurrentPage(request, currentPage);
// save the JSP we are displaying
setLastJSPDisplayed(request, pathToJSP);
// load JSP
JSPManager.showJSP(request, response, pathToJSP);
}
}
/**
* Do the end of a Step. If "cancel" or "progress bar" was pressed, we need
* to forward back to the SubmissionManagerServlet immediately. Otherwise,
* do Post-processing, and figure out if this step is truly finished or not.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @return true if the step is completed (successfully), false otherwise
*
*/
private boolean doStepEnd(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// we've returned from the JSP page
// and need to do the processing for this step
log.debug("Calling processing for step " + this.getClass().getName());
int status = stepProcessing.doProcessing(context, request, response, subInfo);
log.debug("Calling post-processing for step "
+ this.getClass().getName());
// After doing the processing, we have to do any post-processing
// of any potential error messages, in case we need to re-display
// the JSP
stepJSPUI.doPostProcessing(context, request, response, subInfo, status);
int currentPage = AbstractProcessingStep.getCurrentPage(request);
// Assuming step didn't forward back to a JSP during
// post-processing, then check to see if this is the last page!
if (!response.isCommitted())
{
// check if this step has more pages!
if (!hasMorePages(request, subInfo, currentPage))
{
// this step is complete! (return completion
// status to SubmissionController)
return completeStep(context, request, response, subInfo);
}
else
{
if (status == AbstractProcessingStep.NEW_DOC_TYPE)
//if just document type was changed we will show the same page
AbstractProcessingStep.setCurrentPage(request, currentPage);
else
// otherwise, increment to the next page
AbstractProcessingStep.setCurrentPage(request, currentPage + 1);
// reset to beginning of step (so that pre-processing is run
// again)
SubmissionController.setBeginningOfStep(request, true);
// recursively call processStep to reload this Step class for
// the next page
return processStep(context, request, response, subInfo);
}
}
else
{
// this is the case when a response was already given
// in doPostProcessing(), which means the user was
// forwarded to a JSP page.
return false;
}
}
/**
* This method completes the processing of this "step" and forwards the
* request back to the SubmissionController (so that the next step can be
* called).
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*
* @return true if step completed (successfully), false otherwise
*/
protected final boolean completeStep(Context context,
HttpServletRequest request, HttpServletResponse response,
SubmissionInfo subInfo) throws ServletException, IOException,
SQLException, AuthorizeException
{
log.debug("Completing Step " + this.getClass().getName());
// If a response has not already been sent to the web browser,
// then forward control back to the SubmissionController
// (and let the controller know this step is complete!
//
// Note: The only cases in which a response would have already
// been sent to the web browser is if an error occurred or the
// Submission Process had to immediately exit for some reason
// (e.g. user rejected license, or tried to submit a thesis while theses
// are blocked, etc.)
if (!response.isCommitted())
{
// save our current Submission information into the Request object
SubmissionController.saveSubmissionInfo(request, subInfo);
// save the current step into the Request object
SubmissionController.saveCurrentStepConfig(request, stepConfig);
// reset current page back to 1
AbstractProcessingStep.setCurrentPage(request, 1);
// return success (true) to controller!
return true;
}
else
{
return false; // couldn't return to controller since response is
// committed
}
}
/**
* Checks to see if there are more pages in the current step after the
* specified page
*
* @param request
* The HTTP Request object
* @param subInfo
* The current submission information object
* @param pageNumber
* The current page
*
* @throws ServletException
* if there are no more pages in this step
*
*/
protected final boolean hasMorePages(HttpServletRequest request,
SubmissionInfo subInfo, int pageNumber) throws ServletException
{
int numberOfPages = stepProcessing.getNumberOfPages(request, subInfo);
return (pageNumber < numberOfPages);
}
/**
* Find out which page a user has reached in this particular step.
*
* @param subInfo
* Submission information
*
* @return page reached
*/
public static final int getPageReached(SubmissionInfo subInfo)
{
if (subInfo.isInWorkflow() || subInfo.getSubmissionItem() == null)
{
return -1;
}
else
{
WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem();
int i = wi.getPageReached();
return i;
}
}
/**
* Sets the number of the page reached for the specified step
*
* @param session
* HTTP session (where page reached is stored)
* @param step
* the current Submission Process Step (which we want to
* increment the page reached)
* @param pageNumber
* new page reached
*/
private void updatePageReached(SubmissionInfo subInfo, int page)
throws SQLException, AuthorizeException, IOException
{
if (!subInfo.isInWorkflow() && subInfo.getSubmissionItem() != null)
{
WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem();
if (page > wi.getPageReached())
{
wi.setPageReached(page);
wi.update();
}
}
}
/**
* Return the number pages for the given step in the Submission Process
* according to the Progress Bar. So, if "stepNum" is 7, this will return
* the number of pages in step #7 (at least according to the progressBar)
*
* @param subInfo
* current Submission Information object
* @param stepNum
* the number of the step
*
* @return the number of pages in the step
*/
private static int getNumPagesInProgressBar(SubmissionInfo subInfo,
int stepNum)
{
// get the keys of the progressBar information (key format:
// stepNum.pageNum)
Iterator keyIterator = subInfo.getProgressBarInfo().keySet().iterator();
// default to last page being page #1
int lastPage = 1;
while (keyIterator.hasNext())
{
// find step & page info (format: stepNum.pageNum)
String stepAndPage = (String) keyIterator.next();
if (stepAndPage.startsWith(stepNum + "."))
{
// split into stepNum and pageNum
String[] fields = stepAndPage.split("\\."); // split on period
int page = Integer.parseInt(fields[1]);
if (page > lastPage)
{
// update last page found for this step
lastPage = page;
}
}
}
// return # of last page found for this step (which is also the number
// of pages)
return lastPage;
}
/**
* Retrieves the context path of the last JSP that was displayed to the
* user. This is useful in the "doPostProcessing()" method to determine
* which JSP has just submitted form information.
*
* @param request
* current servlet request object
*
* @return pathToJSP The context path to the JSP page (e.g.
* "/submit/select-collection.jsp")
*/
public static final String getLastJSPDisplayed(HttpServletRequest request)
{
String jspDisplayed = (String) request.getAttribute("jsp");
if ((jspDisplayed == null) || jspDisplayed.length() == 0)
{
// try and retrieve the JSP name as a request parameter
if (request.getParameter("jsp") == null)
{
jspDisplayed = "";
}
else
{
jspDisplayed = request.getParameter("jsp");
}
}
return jspDisplayed;
}
/**
* Saves the context path of the last JSP that was displayed to the user.
*
* @param request
* current servlet request object
* @param pathToJSP
* The context path to the JSP page (e.g.
* "/submit/select-collection.jsp")
*/
private static final void setLastJSPDisplayed(HttpServletRequest request,
String pathToJSP)
{
// save to request
request.setAttribute("jsp", pathToJSP);
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in the currently
* loaded Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return stepJSPUI.getReviewJSP(context, request, response, subInfo);
}
}
| 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.webui.submit.step;
import java.io.IOException;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.util.SubmissionConfig;
import org.dspace.app.util.SubmissionStepConfig;
import org.dspace.app.webui.servlet.SubmissionController;
import org.dspace.app.webui.submit.JSPStep;
import org.dspace.app.webui.submit.JSPStepManager;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
/**
* Verify step for DSpace. Presents the user with a verification screen for all
* information entered about the item being submitted.
* <P>
* This JSPStepManager class works with the SubmissionController servlet
* for the JSP-UI
* <P>
* The following methods are called in this order:
* <ul>
* <li>Call doPreProcessing() method</li>
* <li>If showJSP() was specified from doPreProcessing(), then the JSP
* specified will be displayed</li>
* <li>If showJSP() was not specified from doPreProcessing(), then the
* doProcessing() method is called an the step completes immediately</li>
* <li>Call doProcessing() method after the user returns from the JSP, in order
* to process the user input</li>
* <li>Call doPostProcessing() method to determine if more user interaction is
* required, and if further JSPs need to be called.</li>
* <li>If there are more "pages" in this step then, the process begins again
* (for the new page).</li>
* <li>Once all pages are complete, control is forwarded back to the
* SubmissionController, and the next step is called.</li>
* </ul>
*
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
* @see org.dspace.submit.step.VerifyStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPVerifyStep extends JSPStep
{
/** JSP which displays initial questions * */
public static final String VERIFY_JSP = "/submit/review.jsp";
/** log4j logger */
private static Logger log = Logger.getLogger(JSPVerifyStep.class);
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// load the current submission process config
// to get the list of steps the user went through
SubmissionConfig subProcessConfig = subInfo.getSubmissionConfig();
// create a HashMap of step data to review for the Verify JSP
// This HashMap will be the following format:
// key = stepNumber.pageNumber
// value = path to review JSP for this Step (which will load the users
// answers)
Map<String, String> reviewData = new LinkedHashMap<String, String>();
// this shouldn't happen...but just in case!
if (subInfo.getProgressBarInfo() == null)
{
// progress bar information is lost!
log.warn(LogManager.getHeader(context, "integrity_error", UIUtil
.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
return;
}
// loop through the steps in our Progress Bar
// (since these are steps the user visited)
Iterator<String> stepIterator = subInfo.getProgressBarInfo().keySet()
.iterator();
while (stepIterator.hasNext())
{
// remember, the keys of the progressBar hashmap is in the
// format: stepNumber.pageNumber
String stepAndPage = stepIterator.next();
// extract out the step number (which is before the period)
String[] fields = stepAndPage.split("\\."); // split on period
int stepNum = Integer.parseInt(fields[0]);
// only include this step if it is BEFORE the current "verify" step
// (We cannot review steps that we haven't gotten to!!)
if (stepNum < SubmissionController.getCurrentStepConfig(request,
subInfo).getStepNumber())
{
// load this step's information
SubmissionStepConfig s = subProcessConfig.getStep(stepNum);
try
{
JSPStepManager stepManager = JSPStepManager.loadStep(s);
// get this step's review JSP
String reviewJSP = stepManager.getReviewJSP(context, request, response, subInfo);
if ((reviewJSP != null) && (reviewJSP.length() > 0))
{
// save the path to this steps JSP to our reviewData Hashmap
// (with the key = stepNum.pageNum)
reviewData.put(stepAndPage, reviewJSP);
}
}
catch(Exception e)
{
log.error("Problem loading Review JSP for step #" + s.getStepNumber() + ". ", e);
JSPManager.showIntegrityError(request, response);
return;
}
}
}
if (reviewData.isEmpty())
{
// need review data for this page to work!
log.warn(LogManager.getHeader(context, "integrity_error", UIUtil
.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
return;
}
// save our data to review to request for the Verify JSP
request.setAttribute("submission.review", reviewData);
// forward to verify JSP
JSPStepManager.showJSP(request, response, subInfo, VERIFY_JSP);
}
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
public void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// nothing to do from the Verify Step.
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return NO_JSP; //no review JSP, since this is the verification 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.webui.submit.step;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.util.DCInputsReaderException;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.webui.submit.JSPStep;
import org.dspace.app.webui.submit.JSPStepManager;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.core.Context;
import org.dspace.core.I18nUtil;
import org.dspace.core.LogManager;
import org.dspace.submit.step.DescribeStep;
/**
* Describe step for DSpace JSP-UI submission process. Handles the pages that gather
* descriptive information (i.e. metadata) for an item being submitted into
* DSpace.
* <P>
* This JSPStep class works with the SubmissionController servlet
* for the JSP-UI.
* <P>
* The following methods are called in this order:
* <ul>
* <li>Call doPreProcessing() method</li>
* <li>If showJSP() was specified from doPreProcessing(), then the JSP
* specified will be displayed</li>
* <li>If showJSP() was not specified from doPreProcessing(), then the
* doProcessing() method is called an the step completes immediately</li>
* <li>Call doProcessing() method on appropriate AbstractProcessingStep after the user returns from the JSP, in order
* to process the user input</li>
* <li>Call doPostProcessing() method to determine if more user interaction is
* required, and if further JSPs need to be called.</li>
* <li>If there are more "pages" in this step then, the process begins again
* (for the new page).</li>
* <li>Once all pages are complete, control is forwarded back to the
* SubmissionController, and the next step is called.</li>
* </ul>
*
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
* @see org.dspace.submit.step.DescribeStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPDescribeStep extends JSPStep
{
/** JSP which displays HTML for this Class * */
private static final String DISPLAY_JSP = "/submit/edit-metadata.jsp";
/** JSP which reviews information gathered by DISPLAY_JSP * */
private static final String REVIEW_JSP = "/submit/review-metadata.jsp";
/** log4j logger */
private static Logger log = Logger.getLogger(JSPDescribeStep.class);
/** Constructor */
public JSPDescribeStep() throws ServletException
{
//just call DescribeStep's constructor
super();
}
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// display edit metadata page
showEditMetadata(context, request, response, subInfo);
}
/**
* Do any post-processing after the step's backend processing occurred (in
* the doProcessing() method).
* <P>
* It is this method's job to determine whether processing completed
* successfully, or display another JSP informing the users of any potential
* problems/errors.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
public void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// check what submit button was pressed in User Interface
String buttonPressed = UIUtil.getSubmitButton(request, DescribeStep.NEXT_BUTTON);
// this shouldn't happen...but just in case!
if (subInfo.getSubmissionItem() == null)
{
// In progress submission is lost
log.warn(LogManager.getHeader(context, "integrity_error", UIUtil
.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
return;
}
// if user added an extra input field, stay on the same page
if (status == DescribeStep.STATUS_MORE_INPUT_REQUESTED)
{
// reload this same JSP to display extra input boxes
showEditMetadata(context, request, response, subInfo);
}
// if one of the "Remove This Entry" buttons was pressed
else if (buttonPressed.indexOf("remove") > -1)
{
// reload this same JSP to display removed entries
showEditMetadata(context, request, response, subInfo);
}
else if (status == DescribeStep.STATUS_MISSING_REQUIRED_FIELDS)
{
List<String> missingFields = DescribeStep.getErrorFields(request);
// return to current edit metadata screen if any fields missing
if (missingFields.size() > 0)
{
subInfo.setJumpToField(missingFields.get(0));
subInfo.setMissingFields(missingFields);
// reload this same JSP to display missing fields info
showEditMetadata(context, request, response, subInfo);
}
}
}
/**
* Show the page which displays all the Initial Questions to the user
*
* @param context
* current DSpace context
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
*
*/
private void showEditMetadata(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws SQLException, ServletException, IOException
{
Locale sessionLocale = null;
sessionLocale = UIUtil.getSessionLocale(request);
String formFileName = I18nUtil.getInputFormsFileName(sessionLocale);
// determine collection
Collection c = subInfo.getSubmissionItem().getCollection();
// requires configurable form info per collection
try
{
request.setAttribute("submission.inputs", DescribeStep.getInputsReader(formFileName).getInputs(c
.getHandle()));
}
catch (DCInputsReaderException e)
{
throw new ServletException(e);
}
// forward to edit-metadata JSP
JSPStepManager.showJSP(request, response, subInfo, DISPLAY_JSP);
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return REVIEW_JSP;
}
}
| 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.webui.submit.step;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.util.DCInputsReaderException;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.webui.submit.JSPStep;
import org.dspace.app.webui.submit.JSPStepManager;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.Context;
import org.dspace.core.I18nUtil;
import org.dspace.core.LogManager;
import org.dspace.submit.step.DescribeStepExt;
/**
* Describe step for DSpace JSP-UI submission process. Handles the pages that gather
* descriptive information (i.e. metadata) for an item being submitted into
* DSpace.
* <P>
* This JSPStep class works with the SubmissionController servlet
* for the JSP-UI.
* <P>
* The following methods are called in this order:
* <ul>
* <li>Call doPreProcessing() method</li>
* <li>If showJSP() was specified from doPreProcessing(), then the JSP
* specified will be displayed</li>
* <li>If showJSP() was not specified from doPreProcessing(), then the
* doProcessing() method is called an the step completes immediately</li>
* <li>Call doProcessing() method on appropriate AbstractProcessingStep after the user returns from the JSP, in order
* to process the user input</li>
* <li>Call doPostProcessing() method to determine if more user interaction is
* required, and if further JSPs need to be called.</li>
* <li>If there are more "pages" in this step then, the process begins again
* (for the new page).</li>
* <li>Once all pages are complete, control is forwarded back to the
* SubmissionController, and the next step is called.</li>
* </ul>
*
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
* @see org.dspace.submit.step.DescribeStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPDescribeStepExt extends JSPStep
{
/** JSP which displays HTML for this Class * */
private static final String DISPLAY_JSP = "/submit/edit-metadata.jsp";
/** JSP which reviews information gathered by DISPLAY_JSP * */
private static final String REVIEW_JSP = "/submit/review-metadata.jsp";
/** log4j logger */
private static Logger log = Logger.getLogger(JSPDescribeStep.class);
/** Constructor */
public JSPDescribeStepExt() throws ServletException
{
//just call DescribeStep's constructor
super();
}
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
@Override
public void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// check for type of submission changed
String doctype = request.getParameter("select_doctype");
if (doctype != null)
{
request.setAttribute("submission.doctype", doctype);
}
// display edit metadata page
showEditMetadata(context, request, response, subInfo);
}
/**
* Do any post-processing after the step's backend processing occurred (in
* the doProcessing() method).
* <P>
* It is this method's job to determine whether processing completed
* successfully, or display another JSP informing the users of any potential
* problems/errors.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
@Override
public void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// check what submit button was pressed in User Interface
String buttonPressed = UIUtil.getSubmitButton(request, DescribeStepExt.NEXT_BUTTON);
// this shouldn't happen...but just in case!
if (subInfo.getSubmissionItem() == null)
{
// In progress submission is lost
log.warn(LogManager.getHeader(context, "integrity_error", UIUtil
.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
return;
}
// if user added an extra input field, stay on the same page
if (status == DescribeStepExt.STATUS_MORE_INPUT_REQUESTED)
{
// reload this same JSP to display extra input boxes
showEditMetadata(context, request, response, subInfo);
}
// if one of the "Remove This Entry" buttons was pressed
else if (buttonPressed.indexOf("remove") > -1)
{
// reload this same JSP to display removed entries
showEditMetadata(context, request, response, subInfo);
}
else if (status == DescribeStepExt.STATUS_MISSING_REQUIRED_FIELDS)
{
List<String> missingFields = DescribeStepExt.getErrorFields(request);
// return to current edit metadata screen if any fields missing
if (missingFields.size() > 0)
{
subInfo.setJumpToField(missingFields.get(0));
subInfo.setMissingFields(missingFields);
// reload this same JSP to display missing fields info
showEditMetadata(context, request, response, subInfo);
}
}
}
/**
* Show the page which displays all the Initial Questions to the user
*
* @param context
* current DSpace context
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
*
*/
private void showEditMetadata(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws SQLException, ServletException, IOException
{
Locale sessionLocale = null;
sessionLocale = UIUtil.getSessionLocale(request);
String formFileName = I18nUtil.getInputFormsFileName(sessionLocale);
// determine collection
Collection c = subInfo.getSubmissionItem().getCollection();
// requires configurable form info per collection
try
{
List<String> listoftypes = DescribeStepExt.getInputsReader(formFileName).getTypesListforCollection(c.getHandle());
request.setAttribute("submission.types", listoftypes);
String doctype = (String)request.getAttribute("submission.doctype");
if(doctype==null)
{
DCValue[] values = subInfo.getSubmissionItem().getItem().getMetadata("dc", "type", null, Item.ANY);
if (values.length > 0)
{
doctype = values[0].value; // item has already a type/template ... maybe
}
else
{
if(listoftypes.size() > 0)
doctype = listoftypes.get(0);
else
doctype = ""; //nothing at all
}
}
request.setAttribute("submission.inputs", DescribeStepExt.getInputsReader(formFileName).getInputs(c
.getHandle(), doctype));
}
catch (DCInputsReaderException e)
{
throw new ServletException(e);
}
// forward to edit-metadata JSP
JSPStepManager.showJSP(request, response, subInfo, DISPLAY_JSP);
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
@Override
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return REVIEW_JSP;
}
}
| 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.webui.submit.step;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.util.Util;
import org.dspace.app.webui.servlet.SubmissionController;
import org.dspace.app.webui.submit.JSPStep;
import org.dspace.app.webui.submit.JSPStepManager;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Item;
import org.dspace.content.LicenseUtils;
import org.dspace.content.WorkspaceItem;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.license.CreativeCommons;
import org.dspace.submit.step.LicenseStep;
/**
* License step for DSpace JSP-UI. Presents the user with license information
* required for all items submitted into DSpace.
* <P>
* This JSPStep class works with the SubmissionController servlet
* for the JSP-UI
* <P>
* The following methods are called in this order:
* <ul>
* <li>Call doPreProcessing() method</li>
* <li>If showJSP() was specified from doPreProcessing(), then the JSP
* specified will be displayed</li>
* <li>If showJSP() was not specified from doPreProcessing(), then the
* doProcessing() method is called an the step completes immediately</li>
* <li>Call doProcessing() method on appropriate AbstractProcessingStep after the user returns from the JSP, in order
* to process the user input</li>
* <li>Call doPostProcessing() method to determine if more user interaction is
* required, and if further JSPs need to be called.</li>
* <li>If there are more "pages" in this step then, the process begins again
* (for the new page).</li>
* <li>Once all pages are complete, control is forwarded back to the
* SubmissionController, and the next step is called.</li>
* </ul>
*
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
* @see org.dspace.submit.step.LicenseStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPLicenseStep extends JSPStep
{
/** JSP which displays default license information * */
private static final String LICENSE_JSP = "/submit/show-license.jsp";
/** JSP which displays Creative Commons license information * */
private static final String CC_LICENSE_JSP = "/submit/creative-commons.jsp";
/** JSP which displays information after a license is rejected * */
private static final String LICENSE_REJECT_JSP = "/submit/license-rejected.jsp";
/** log4j logger */
private static Logger log = Logger.getLogger(JSPLicenseStep.class);
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// if creative commons licensing is enabled, then it is page #1
if (CreativeCommons.isEnabled() && LicenseStep.getCurrentPage(request) == 1)
{
showCCLicense(context, request, response, subInfo);
}
else
// otherwise load default DSpace license agreement
{
showLicense(context, request, response, subInfo);
}
}
/**
* Do any post-processing after the step's backend processing occurred (in
* the doProcessing() method).
* <P>
* It is this method's job to determine whether processing completed
* successfully, or display another JSP informing the users of any potential
* problems/errors.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
public void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException
{
String buttonPressed = Util.getSubmitButton(request, LicenseStep.CANCEL_BUTTON);
// JSP-UI Specific (only JSP UI has a "reject" button):
// License was explicitly rejected
if (buttonPressed.equals("submit_reject"))
{
// User has rejected license.
log.info(LogManager.getHeader(context, "reject_license",
subInfo.getSubmissionLogInfo()));
// If the license page was the 1st page in the Submission process,
// then delete the submission if they reject the license!
if (!subInfo.isInWorkflow()
&& (SubmissionController.getStepReached(subInfo) <= SubmissionController.FIRST_STEP))
{
WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem();
wi.deleteAll();
// commit changes
context.commit();
}
// Show the license rejected page
JSPManager.showJSP(request, response, LICENSE_REJECT_JSP);
}
}
/**
* Show the DSpace license page to the user
*
* @param context
* current DSpace context
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
*/
private void showLicense(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws SQLException, ServletException, IOException
{
String license = LicenseUtils.getLicenseText(
context.getCurrentLocale(), subInfo.getSubmissionItem()
.getCollection(),
subInfo.getSubmissionItem().getItem(), subInfo
.getSubmissionItem().getSubmitter());
request.setAttribute("license", license);
JSPStepManager.showJSP(request, response, subInfo, LICENSE_JSP);
}
/**
* Show the Creative Commons license page to the user
*
* @param context
* current DSpace context
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
*/
private void showCCLicense(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws SQLException, ServletException, IOException
{
// Do we already have a CC license?
Item item = subInfo.getSubmissionItem().getItem();
boolean exists = CreativeCommons.hasLicense(context, item);
request.setAttribute("cclicense.exists", Boolean.valueOf(exists));
JSPStepManager.showJSP(request, response, subInfo, CC_LICENSE_JSP);
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return NO_JSP; //signing off on license does not require reviewing
}
}
| 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.webui.submit.step;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.app.webui.submit.JSPStep;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
/**
* This is the JSP binding class which defines what happens once a submission completes!
* <P>
* This JSPCompleteStep class works with the SubmissionController servlet and
* when using the JSP-UI
* <P>
* This step is non-interactive (i.e. no user interface), and simply performs
* the processing that is necessary after a submission has been completed!
* <P>
* SubmissionController servlet will automatically display the
* confirmation page which tells the user the submission is now completed!
*
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPCompleteStep extends JSPStep
{
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
//No pre-processing necessary, since submission is complete!
}
/**
* Do any post-processing after the step's backend processing occurred (in
* the doProcessing() method).
* <P>
* It is this method's job to determine whether processing completed
* successfully, or display another JSP informing the users of any potential
* problems/errors.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
public void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException
{
//No post-processing necessary, since submission is complete!
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return NO_JSP; //no need to return a Review JSP as we are completed!
}
}
| 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.webui.submit.step;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.app.util.DCInputsReader;
import org.dspace.app.util.DCInputsReaderException;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.webui.submit.JSPStep;
import org.dspace.app.webui.submit.JSPStepManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.core.Context;
import org.dspace.submit.step.InitialQuestionsStep;
/**
* Initial Submission servlet for DSpace JSP-UI. Handles the initial questions which
* are asked to users to gather information regarding what metadata needs to be
* gathered.
* <P>
* This JSPStep class works with the SubmissionController servlet
* for the JSP-UI
*
* The following methods are called in this order:
* <ul>
* <li>Call doPreProcessing() method</li>
* <li>If showJSP() was specified from doPreProcessing(), then the JSP
* specified will be displayed</li>
* <li>If showJSP() was not specified from doPreProcessing(), then the
* doProcessing() method is called an the step completes immediately</li>
* <li>Call doProcessing() method on appropriate AbstractProcessingStep after the user returns from the JSP, in order
* to process the user input</li>
* <li>Call doPostProcessing() method to determine if more user interaction is
* required, and if further JSPs need to be called.</li>
* <li>If there are more "pages" in this step then, the process begins again
* (for the new page).</li>
* <li>Once all pages are complete, control is forwarded back to the
* SubmissionController, and the next step is called.</li>
* </ul>
*
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
* @see org.dspace.submit.step.InitialQuestionsStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPInitialQuestionsStep extends JSPStep
{
/** JSP which displays initial questions * */
private static final String INITIAL_QUESTIONS_JSP = "/submit/initial-questions.jsp";
/** JSP which verifies users wants to change answers * */
private static final String VERIFY_PRUNE_JSP = "/submit/verify-prune.jsp";
/** JSP which tells the user that theses are not allowed * */
private static final String NO_THESES_JSP = "/submit/no-theses.jsp";
/** JSP which displays information to be reviewed during 'verify step' * */
private static final String REVIEW_JSP = "/submit/review-init.jsp";
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// prepare & show the initial questions page, by default
showInitialQuestions(context, request, response, subInfo);
}
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
public void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// Get the values from the initial questions form
boolean multipleTitles = UIUtil.getBoolParameter(request,
"multiple_titles");
boolean publishedBefore = UIUtil.getBoolParameter(request,
"published_before");
boolean multipleFiles = UIUtil.getBoolParameter(request,
"multiple_files");
// If we actually came from the "verify prune" page,
// then prune any excess data.
if (JSPStepManager.getLastJSPDisplayed(request).equals(VERIFY_PRUNE_JSP))
{
if (status == InitialQuestionsStep.STATUS_CANCEL_PRUNE)
{
// User cancelled pruning (show initial questions again)
showInitialQuestions(context, request, response, subInfo);
return;
}
}
else
// Otherwise, if just coming from "initial questions" page
{
if (status == InitialQuestionsStep.STATUS_THESIS_REJECTED)
{
// Display no-theses JSP to user
JSPStepManager.showJSP(request, response, subInfo, NO_THESES_JSP);
return;
}
// If anything is going to be removed from the item as a result
// of changing the answer to one of the questions, we need
// to inform the user and make sure that's OK
if (status == InitialQuestionsStep.STATUS_VERIFY_PRUNE)
{
showVerifyPrune(context, request, response, subInfo,
multipleTitles, publishedBefore, multipleFiles);
return;
}
}
}
/**
* Show the page which displays all the Initial Questions to the user
*
* @param context
* current DSpace context
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
*
*/
private void showInitialQuestions(Context context,
HttpServletRequest request, HttpServletResponse response,
SubmissionInfo subInfo) throws SQLException, ServletException,
IOException
{
// determine collection
Collection c = subInfo.getSubmissionItem().getCollection();
try
{
// read configurable submissions forms data
DCInputsReader inputsReader = new DCInputsReader();
// load the proper submission inputs to be used by the JSP
request.setAttribute("submission.inputs", inputsReader.getInputs(c
.getHandle()));
}
catch (DCInputsReaderException e)
{
throw new ServletException(e);
}
// forward to initial questions JSP
JSPStepManager.showJSP(request, response, subInfo, INITIAL_QUESTIONS_JSP);
}
/**
* Show the page which warns the user that by changing the answer to one of
* these questions, some previous data may be deleted.
*
* @param context
* current DSpace context
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
* @param multipleTitles
* if there is multiple titles
* @param publishedBefore
* if published before
* @param multipleFiles
* if there will be multiple files
* @param willRemoveTitles
* if a title needs to be removed
* @param willRemoveDate
* if a date needs to be removed
* @param willRemoveFiles
* if one or more files need to be removed
*/
private void showVerifyPrune(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo,
boolean multipleTitles, boolean publishedBefore,
boolean multipleFiles) throws SQLException, ServletException,
IOException
{
// Verify pruning of extra bits
request.setAttribute("multiple.titles", Boolean.valueOf(multipleTitles));
request.setAttribute("published.before", Boolean.valueOf(publishedBefore));
request.setAttribute("multiple.files", Boolean.valueOf(multipleFiles));
request.setAttribute("button.pressed", UIUtil.getSubmitButton(request,
InitialQuestionsStep.NEXT_BUTTON));
// forward to verify prune JSP
JSPStepManager.showJSP(request, response, subInfo, VERIFY_PRUNE_JSP);
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return REVIEW_JSP;
}
}
| 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.webui.submit.step;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.webui.submit.JSPStep;
import org.dspace.app.webui.submit.JSPStepManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.submit.AbstractProcessingStep;
import org.dspace.submit.step.SampleStep;
/**
* This is a Sample Step class which can be used as template for creating new
* custom JSP-UI Step classes!
* <p>
* Please Note: This class works in conjunction with the
* org.dspace.submit.step.SampleStep , which is a sample step
* processing class!
* <p>
* This step can be added to any Submission process (for testing purposes) by
* adding the following to the appropriate <submission-process> tag in the
* /config/item-submission.xml:
*
* <step>
* <heading>Sample</heading>
* <processing-class>org.dspace.submit.step.SampleStep</processing-class>
* <jspui-binding>org.dspace.app.webui.submit.step.JSPSampleStep</jspui-binding>
* <workflow-editable>true</workflow-editable>
* </step>
*
* <P>
* The following methods are called in this order:
* <ul>
* <li>Call doPreProcessing() method</li>
* <li>If showJSP() was specified from doPreProcessing(), then the JSP
* specified will be displayed</li>
* <li>If showJSP() was not specified from doPreProcessing(), then the
* doProcessing() method is called an the step completes immediately</li>
* <li>Call doProcessing() method on appropriate AbstractProcessingStep after the user returns from the JSP, in order
* to process the user input</li>
* <li>Call doPostProcessing() method to determine if more user interaction is
* required, and if further JSPs need to be called.</li>
* <li>If there are more "pages" in this step then, the process begins again
* (for the new page).</li>
* <li>Once all pages are complete, control is forwarded back to the
* SubmissionController, and the next step is called.</li>
* </ul>
*
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
* @see org.dspace.submit.step.SampleStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPSampleStep extends JSPStep
{
/** JSP which displays the step to the user * */
private static final String DISPLAY_JSP = "/submit/sample-step.jsp";
/** JSP which displays information to be reviewed during 'verify step' * */
private static final String REVIEW_JSP = "/submit/review-sample.jsp";
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
/*
* In this method, you should do any pre-processing required before the
* Step's JSP can be displayed, and call the first JSP to display (using
* the showJSP() method of JSPStepManager)
*
*
* Pre-processing may include, but is not limited to:
*
* 1) Gathering necessary data (to be displayed on the JSP) from
* database or other DSpace classes. This data should be stored in the
* HttpServletRequest object (using request.setAttribute()) so that your
* JSP can access it! 2) Based on the input, determine which JSP you
* actually want to load! This can be especially important for Steps
* which use multiple JSPs. 3) For steps with multiple "pages", you may
* want to use the inherited getCurrentPage() method to determine which
* page you are currently on, so that you know which JSP to show!
*
* In order for your JSP to load after this doPreProcessing() step, you
* *MUST* call the inherited showJSP() method!
*
* NOTE: a Step need not even use a JSP (if it's just a step which does
* backend processing, and doesn't require a Web User Interface). For
* these types of "processing-only" Steps, you should perform all of
* your processing in the "doProcessing()" method, and this
* doPreProcessing() method should be left EMPTY!
*
*/
/*
* FAQ:
*
* 1) How many times is doPreProcessing() called for a single Step?
*
* It's called once for each page in the step. So, if getNumberOfPages()
* returns 1, it's called only once. If getNumberOfPages() returns 2,
* it's called twice (once for each page), etc.
*/
/*
* Here's some example code that sets a Request attribute for the
* sample-step.jsp to use, and then Loads the sample-step.jsp
*/
// retrieve my DSpace URL from the Configuration File!
String myDSpaceURL = ConfigurationManager.getProperty("dspace.url");
request.setAttribute("my.url", myDSpaceURL);
// Tell JSPStepManager class to load "sample-step.jsp"
JSPStepManager.showJSP(request, response, subInfo, DISPLAY_JSP);
}
/**
* Do any post-processing after the step's backend processing occurred (in
* the doProcessing() method).
* <P>
* It is this method's job to determine whether processing completed
* successfully, or display another JSP informing the users of any potential
* problems/errors.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
public void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException
{
/*
* In this method, you should do any post-processing of errors or
* messages returned by doProcessing() method, to determine if the user
* has completed this step or if further user input is required.
*
* This method is called immediately AFTER doProcessing(), and any
* errors or messages returned by doProcessing() are passed to this
* method as an input.
*
* Post-processing includes, but is not limited to: 1) Validating that
* the user filled out required fields (and if not, forwarding him/her
* back to appropriate JSP) 2) Determining which JSP to display based on
* the error or status message which was passed into this method from
* doProcessing()
*
* NOTE: If this step has multiple "pages" defined (i.e. the below
* getNumberOfPages() method returns > 1), then you DO NOT need to load
* the next page here! After the post-processing of the first page
* completes, the JSPStepManager class will call "doPreProcessing()"
* automatically for page #2, etc.
*
* Once post-processing completes, and the JSPStepManager class
* determines there are no more pages to this step, control is sent back
* to the SubmissionController (and the next step is called).
*/
/***********************************************************************
* IMPORTANT FUNCTIONS to be aware of :
**********************************************************************/
// This function retrieves the path of the JSP which just submitted its
// form to this class (e.g. "/submit/sample-step.jsp", in this case)
// String lastJSPDisplayed = JSPStepManager.getLastJSPDisplayed(request);
// This function retrieves the number of the current "page"
// within this Step. This is useful if your step actually
// has more than one "page" within the Progress Bar. It can
// help you determine which Page the user just came from,
// as well as determine which JSP to load in doPreProcessing()
// int currentPageNum = SampleStep.getCurrentPage(request);
// This function returns the NAME of the button the user
// just pressed in order to submit the form.
// In this case, we are saying default to the "Next" button,
// if it cannot be determined which button was pressed.
// (requires you use the AbstractProcessingStep.PREVIOUS_BUTTON,
// AbstractProcessingStep.NEXT_BUTTON, and AbstractProcessingStep.CANCEL_BUTTON
// constants in your JSPs)
String buttonPressed = UIUtil.getSubmitButton(request,
AbstractProcessingStep.NEXT_BUTTON);
// We also have some Button Name constants to work with.
// Assuming you used these constants to NAME your submit buttons,
// we can do different processing based on which button was pressed
if (buttonPressed.equals(AbstractProcessingStep.NEXT_BUTTON))
{
// special processing for "Next" button
// YOU DON'T NEED TO ATTEMPT TO REDIRECT/FORWARD TO THE NEXT PAGE
// HERE,
// the SubmissionController will do that automatically!
}
else if (buttonPressed.equals(AbstractProcessingStep.PREVIOUS_BUTTON))
{
// special processing for "Previous" button
// YOU DON'T NEED TO ATTEMPT TO REDIRECT/FORWARD TO THE PREVIOUS
// PAGE HERE,
// the SubmissionController will do that automatically!
}
else if (buttonPressed.equals(AbstractProcessingStep.CANCEL_BUTTON))
{
// special processing for "Cancel/Save" button
// YOU DON'T NEED TO ATTEMPT TO REDIRECT/FORWARD TO THE CANCEL/SAVE
// PAGE HERE,
// the SubmissionController will do that automatically!
}
// Here's some sample error message processing!
if (status == SampleStep.STATUS_USER_INPUT_ERROR)
{
// special processing for this error message
}
/***********************************************************************
* SAMPLE CODE (all of which is commented out)
*
* (For additional sample code, see any of the existing JSPStep classes)
**********************************************************************/
/*
* HOW-TO RELOAD PAGE BECAUSE OF INVALID INPUT!
*
* If you have already validated the form inputs, and determined that
* one or more is invalid, you can RELOAD the JSP by calling
* JSPStepManger.showJSP() like:
*
* JSPStepManger.showJSP(request, response, subInfo, "/submit/sample-step.jsp");
*
* You should make sure to pass a flag to your JSP to let it know which
* fields were invalid, so that it can display an error message next to
* them:
*
* request.setAttribute("invalid-fields", listOfInvalidFields);
*/
/*
* HOW-TO GO TO THE NEXT "PAGE" IN THIS STEP
*
* If this step has multiple "pages" that appear in the Progress Bar,
* you can step to the next page AUTOMATICALLY by just NOT calling
* "JSPStepManger.showJSP()" in your doPostProcessing() method.
*
*/
/*
* HOW-TO COMPLETE/END THIS STEP
*
* In order to complete this step, just do NOT call JSPStepManger.showJSP()! Once all
* pages are finished, the JSPStepManager class will report to the
* SubmissionController that this step is now finished!
*/
}
/**
* Retrieves the number of pages that this "step" extends over. This method
* is used by the SubmissionController to build the progress bar.
* <P>
* This method may just return 1 for most steps (since most steps consist of
* a single page). But, it should return a number greater than 1 for any
* "step" which spans across a number of HTML pages. For example, the
* configurable "Describe" step (configured using input-forms.xml) overrides
* this method to return the number of pages that are defined by its
* configuration file.
* <P>
* Steps which are non-interactive (i.e. they do not display an interface to
* the user) should return a value of 1, so that they are only processed
* once!
*
*
* @param request
* The HTTP Request
* @param subInfo
* The current submission information object
*
* @return the number of pages in this step
*/
public int getNumberOfPages(HttpServletRequest request,
SubmissionInfo subInfo) throws ServletException
{
/*
* This method tells the SubmissionController how many "pages" to put in
* the Progress Bar for this Step.
*
* Most steps should just return 1 (which means the Step only appears
* once in the Progress Bar).
*
* If this Step should be shown as multiple "Pages" in the Progress Bar,
* then return a value higher than 1. For example, return 2 in order to
* have this Step appear twice in a row within the Progress Bar.
*
* If you return 0, this Step will not appear in the Progress Bar at
* ALL! Therefore it is important for non-interactive steps to return 0.
*/
// in most cases, you'll want to just return 1
return 1;
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return REVIEW_JSP;
}
}
| 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.webui.submit.step;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.webui.submit.JSPStep;
import org.dspace.app.webui.submit.JSPStepManager;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.submit.step.SelectCollectionStep;
/**
* Step which controls selecting a Collection for the Item Submission process
* for DSpace JSP-UI
* <P>
* This JSPStep class works with the SubmissionController servlet
* for the JSP-UI
* <P>
* The following methods are called in this order:
* <ul>
* <li>Call doPreProcessing() method</li>
* <li>If showJSP() was specified from doPreProcessing(), then the JSP
* specified will be displayed</li>
* <li>If showJSP() was not specified from doPreProcessing(), then the
* doProcessing() method is called an the step completes immediately</li>
* <li>Call doProcessing() method on appropriate AbstractProcessingStep after the user returns from the JSP, in order
* to process the user input</li>
* <li>Call doPostProcessing() method to determine if more user interaction is
* required, and if further JSPs need to be called.</li>
* <li>If there are more "pages" in this step then, the process begins again
* (for the new page).</li>
* <li>Once all pages are complete, control is forwarded back to the
* SubmissionController, and the next step is called.</li>
* </ul>
*
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
* @see org.dspace.submit.step.SelectCollectionStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPSelectCollectionStep extends JSPStep
{
/** JSP which displays HTML for this Class * */
private static final String SELECT_COLLECTION_JSP = "/submit/select-collection.jsp";
/** log4j logger */
private static Logger log = Logger.getLogger(JSPSelectCollectionStep.class);
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
/*
* Possible parameters from JSP:
*
* collection= <collection_id> - a collection that has already been
* selected!
*
* With no parameters, this servlet prepares for display of the Select
* Collection JSP.
*/
String collectionID = request.getParameter("collection");
Collection col = null;
if (collectionID != null)
{
col = Collection.find(context, Integer.parseInt(collectionID));
}
// if we already have a valid collection, then we can forward directly
// to post-processing
if (col != null)
{
log
.debug("Select Collection page skipped, since a Collection ID was already found. Collection ID="
+ collectionID);
}
else
{
// gather info for JSP page
Community com = UIUtil.getCommunityLocation(request);
Collection[] collections;
if (com != null)
{
// In a community. Show collections in that community only.
collections = Collection.findAuthorized(context, com,
Constants.ADD);
}
else
{
// Show all collections
collections = Collection.findAuthorized(context, null,
Constants.ADD);
}
// This is a special case, where the user came back to this
// page after not selecting a collection. This will display
// the "Please select a collection" message to the user
if (collectionID != null && Integer.parseInt(collectionID) == -1)
{
// specify "no collection" error message should be displayed
request.setAttribute("no.collection", Boolean.TRUE);
}
// save collections to request for JSP
request.setAttribute("collections", collections);
// we need to load the select collection JSP
JSPStepManager.showJSP(request, response, subInfo, SELECT_COLLECTION_JSP);
}
}
/**
* Do any post-processing after the step's backend processing occurred (in
* the doProcessing() method).
* <P>
* It is this method's job to determine whether processing completed
* successfully, or display another JSP informing the users of any potential
* problems/errors.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
public void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// if the user didn't select a collection,
// send him/her back to "select a collection" page
if (status == SelectCollectionStep.STATUS_NO_COLLECTION)
{
// specify "no collection" error message should be displayed
request.setAttribute("no.collection", Boolean.TRUE);
// reload this page, by re-calling doPreProcessing()
doPreProcessing(context, request, response, subInfo);
}
else if (status == SelectCollectionStep.STATUS_INVALID_COLLECTION)
{
JSPManager.showInvalidIDError(request, response, request
.getParameter("collection"), Constants.COLLECTION);
}
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return NO_JSP; //at this time, you cannot review what collection you selected.
}
}
| 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.webui.submit.step;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.util.DCInputsReader;
import org.dspace.app.util.DCInputsReaderException;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.webui.submit.JSPStep;
import org.dspace.app.webui.submit.JSPStepManager;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
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.FormatIdentifier;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.submit.step.UploadStep;
/**
* Upload step for DSpace JSP-UI. Handles the pages that revolve around uploading files
* (and verifying a successful upload) for an item being submitted into DSpace.
* <P>
* This JSPStep class works with the SubmissionController servlet
* for the JSP-UI
* <P>
* The following methods are called in this order:
* <ul>
* <li>Call doPreProcessing() method</li>
* <li>If showJSP() was specified from doPreProcessing(), then the JSP
* specified will be displayed</li>
* <li>If showJSP() was not specified from doPreProcessing(), then the
* doProcessing() method is called an the step completes immediately</li>
* <li>Call doProcessing() method on appropriate AbstractProcessingStep after the user returns from the JSP, in order
* to process the user input</li>
* <li>Call doPostProcessing() method to determine if more user interaction is
* required, and if further JSPs need to be called.</li>
* <li>If there are more "pages" in this step then, the process begins again
* (for the new page).</li>
* <li>Once all pages are complete, control is forwarded back to the
* SubmissionController, and the next step is called.</li>
* </ul>
*
* @see org.dspace.app.webui.servlet.SubmissionController
* @see org.dspace.app.webui.submit.JSPStep
* @see org.dspace.submit.step.UploadStep
*
* @author Tim Donohue
* @version $Revision: 5845 $
*/
public class JSPUploadStep extends JSPStep
{
/** JSP to choose files to upload * */
private static final String CHOOSE_FILE_JSP = "/submit/choose-file.jsp";
/** JSP to show files that were uploaded * */
private static final String UPLOAD_LIST_JSP = "/submit/upload-file-list.jsp";
/** JSP to single file that was upload * */
private static final String UPLOAD_FILE_JSP = "/submit/show-uploaded-file.jsp";
/** JSP to edit file description * */
private static final String FILE_DESCRIPTION_JSP = "/submit/change-file-description.jsp";
/** JSP to edit file format * */
private static final String FILE_FORMAT_JSP = "/submit/get-file-format.jsp";
/** JSP to show any upload errors * */
private static final String UPLOAD_ERROR_JSP = "/submit/upload-error.jsp";
/** JSP to review uploaded files * */
private static final String REVIEW_JSP = "/submit/review-upload.jsp";
/** log4j logger */
private static Logger log = Logger.getLogger(JSPUploadStep.class);
/**
* Do any pre-processing to determine which JSP (if any) is used to generate
* the UI for this step. This method should include the gathering and
* validating of all data required by the JSP. In addition, if the JSP
* requires any variable to passed to it on the Request, this method should
* set those variables.
* <P>
* If this step requires user interaction, then this method must call the
* JSP to display, using the "showJSP()" method of the JSPStepManager class.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public void doPreProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// pass on the fileupload setting
if (subInfo != null)
{
Collection c = subInfo.getSubmissionItem().getCollection();
try
{
DCInputsReader inputsReader = new DCInputsReader();
request.setAttribute("submission.inputs", inputsReader.getInputs(c
.getHandle()));
}
catch (DCInputsReaderException e)
{
throw new ServletException(e);
}
// show whichever upload page is appropriate
// (based on if this item already has files or not)
showUploadPage(context, request, response, subInfo, false);
}
else
{
throw new IllegalStateException("SubInfo must not be null");
}
}
/**
* Do any post-processing after the step's backend processing occurred (in
* the doProcessing() method).
* <P>
* It is this method's job to determine whether processing completed
* successfully, or display another JSP informing the users of any potential
* problems/errors.
* <P>
* If this step doesn't require user interaction OR you are solely using
* Manakin for your user interface, then this method may be left EMPTY,
* since all step processing should occur in the doProcessing() method.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @param status
* any status/errors reported by doProcessing() method
*/
public void doPostProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo, int status)
throws ServletException, IOException, SQLException,
AuthorizeException
{
String buttonPressed = UIUtil.getSubmitButton(request, UploadStep.NEXT_BUTTON);
// Do we need to skip the upload entirely?
boolean fileRequired = ConfigurationManager.getBooleanProperty("webui.submit.upload.required", true);
if (buttonPressed.equalsIgnoreCase(UploadStep.SUBMIT_SKIP_BUTTON) ||
(buttonPressed.equalsIgnoreCase(UploadStep.SUBMIT_UPLOAD_BUTTON) && !fileRequired))
{
Bundle[] bundles = subInfo.getSubmissionItem().getItem()
.getBundles("ORIGINAL");
boolean fileAlreadyUploaded = false;
for (Bundle bnd : bundles)
{
fileAlreadyUploaded = bnd.getBitstreams().length > 0;
if (fileAlreadyUploaded)
{
break;
}
}
// if user already has uploaded at least one file
if (fileAlreadyUploaded)
{
// return to list of uploaded files
showUploadFileList(context, request, response, subInfo, true,
false);
}
return; // return immediately, since we are skipping upload
}
//If upload failed in JSPUI (just came from upload-error.jsp), user can retry the upload
if(buttonPressed.equalsIgnoreCase("submit_retry"))
{
showUploadPage(context, request, response, subInfo, false);
}
// ------------------------------
// Check for Errors!
// ------------------------------
// if an error or message was passed back, determine what to do!
if (status != UploadStep.STATUS_COMPLETE)
{
if (status == UploadStep.STATUS_INTEGRITY_ERROR)
{
// Some type of integrity error occurred
log.warn(LogManager.getHeader(context, "integrity_error",
UIUtil.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
}
else if (status == UploadStep.STATUS_UPLOAD_ERROR || status == UploadStep.STATUS_NO_FILES_ERROR)
{
// There was a problem uploading the file!
//First, check if we just removed our uploaded file
if(buttonPressed.startsWith("submit_remove_"))
{
//if file was just removed, go back to upload page
showUploadPage(context, request, response, subInfo, false);
}
else
{
// We need to show the file upload error page
if (subInfo != null)
{
try
{
Collection c = subInfo.getSubmissionItem().getCollection();
DCInputsReader inputsReader = new DCInputsReader();
request.setAttribute("submission.inputs", inputsReader
.getInputs(c.getHandle()));
}
catch (DCInputsReaderException e)
{
throw new ServletException(e);
}
}
JSPStepManager.showJSP(request, response, subInfo, UPLOAD_ERROR_JSP);
}
}
else if (status == UploadStep.STATUS_UNKNOWN_FORMAT)
{
// user uploaded a file where the format is unknown to DSpace
// forward user to page to request the file format
showGetFileFormat(context, request, response, subInfo);
}
}
// As long as there are no errors, clicking Next
// should immediately send them to the next step
if (status == UploadStep.STATUS_COMPLETE && buttonPressed.equals(UploadStep.NEXT_BUTTON))
{
// just return, so user will continue on to next step!
return;
}
// ------------------------------
// Check for specific buttons
// ------------------------------
if (buttonPressed.equals(UploadStep.SUBMIT_MORE_BUTTON))
{
// Upload another file (i.e. show the Choose File jsp again)
showChooseFile(context, request, response, subInfo);
}
else if (buttonPressed.equals("submit_show_checksums"))
{
// Show the checksums
showUploadFileList(context, request, response, subInfo, false, true);
}
else if (buttonPressed.startsWith("submit_describe_"))
{
// Change the description of a bitstream
Bitstream bitstream;
// Which bitstream does the user want to describe?
try
{
int id = Integer.parseInt(buttonPressed.substring(16));
bitstream = Bitstream.find(context, id);
}
catch (NumberFormatException nfe)
{
bitstream = null;
}
if (bitstream == null)
{
// Invalid or mangled bitstream ID
// throw an error and return immediately
log.warn(LogManager.getHeader(context, "integrity_error",
UIUtil.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
}
// save the bitstream
subInfo.setBitstream(bitstream);
// load the change file description page
showFileDescription(context, request, response, subInfo);
}
else if (buttonPressed.startsWith("submit_format_"))
{
// A "format is wrong" button must have been pressed
Bitstream bitstream;
// Which bitstream does the user want to describe?
try
{
int id = Integer.parseInt(buttonPressed.substring(14));
bitstream = Bitstream.find(context, id);
}
catch (NumberFormatException nfe)
{
bitstream = null;
}
if (bitstream == null)
{
// Invalid or mangled bitstream ID
// throw an error and return immediately
log.warn(LogManager.getHeader(context, "integrity_error",
UIUtil.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
}
subInfo.setBitstream(bitstream);
showGetFileFormat(context, request, response, subInfo);
}
else
{
// BY DEFAULT: just display either the first upload page or the
// upload file listing
String contentType = request.getContentType();
boolean fileUpload = false;
// if multipart form, then we just finished a file upload
if ((contentType != null)
&& (contentType.indexOf("multipart/form-data") != -1))
{
fileUpload = true;
}
// show the appropriate upload page
// (based on if a file has just been uploaded or not)
showUploadPage(context, request, response, subInfo, fileUpload);
}
}
/**
* Display the appropriate upload page in the file upload sequence. Which
* page this is depends on whether the user has uploaded any files in this
* item already.
*
* @param context
* the DSpace context object
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
* @param justUploaded
* true, if the user just finished uploading a file
*/
private void showUploadPage(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo,
boolean justUploaded) throws SQLException, ServletException,
IOException
{
Bundle[] bundles = subInfo.getSubmissionItem().getItem().getBundles(
"ORIGINAL");
boolean fileAlreadyUploaded = false;
if (!justUploaded)
{
for (Bundle bnd : bundles)
{
fileAlreadyUploaded = bnd.getBitstreams().length > 0;
if (fileAlreadyUploaded)
{
break;
}
}
}
// if user already has uploaded at least one file
if (justUploaded || fileAlreadyUploaded)
{
// The item already has files associated with it.
showUploadFileList(context, request, response, subInfo,
justUploaded, false);
}
else
{
// show the page to choose a file to upload
showChooseFile(context, request, response, subInfo);
}
}
/**
* Show the page which allows the user to choose another file to upload
*
* @param context
* current DSpace context
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
*/
private void showChooseFile(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws SQLException, ServletException, IOException
{
// set to null the bitstream in subInfo, we need to process a new file
// we don't need any info about previous files...
subInfo.setBitstream(null);
// load JSP which allows the user to select a file to upload
JSPStepManager.showJSP(request, response, subInfo, CHOOSE_FILE_JSP);
}
/**
* Show the page which lists all the currently uploaded files
*
* @param context
* current DSpace context
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
* @param justUploaded
* pass in true if the user just successfully uploaded a file
* @param showChecksums
* pass in true if checksums should be displayed
*/
private void showUploadFileList(Context context,
HttpServletRequest request, HttpServletResponse response,
SubmissionInfo subInfo, boolean justUploaded, boolean showChecksums)
throws SQLException, ServletException, IOException
{
// Set required attributes
request.setAttribute("just.uploaded", Boolean.valueOf(justUploaded));
request.setAttribute("show.checksums", Boolean.valueOf(showChecksums));
// Always go to advanced view in workflow mode
if (subInfo.isInWorkflow()
|| subInfo.getSubmissionItem().hasMultipleFiles())
{
// next, load JSP listing multiple files
JSPStepManager.showJSP(request, response, subInfo, UPLOAD_LIST_JSP);
}
else
{
// next, load JSP listing a single file
JSPStepManager.showJSP(request, response, subInfo, UPLOAD_FILE_JSP);
}
}
/**
* Show the page which allows the user to change the format of the file that
* was just uploaded
*
* @param context
* context object
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
*/
private void showGetFileFormat(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws SQLException, ServletException, IOException
{
if (subInfo == null || subInfo.getBitstream() == null)
{
// We have an integrity error, since we seem to have lost
// which bitstream was just uploaded
log.warn(LogManager.getHeader(context, "integrity_error", UIUtil
.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
}
BitstreamFormat[] formats = BitstreamFormat.findNonInternal(context);
request.setAttribute("bitstream.formats", formats);
// What does the system think it is?
BitstreamFormat guess = FormatIdentifier.guessFormat(context, subInfo
.getBitstream());
request.setAttribute("guessed.format", guess);
// display choose file format JSP next
JSPStepManager.showJSP(request, response, subInfo, FILE_FORMAT_JSP);
}
/**
* Show the page which allows the user to edit the description of already
* uploaded files
*
* @param context
* context object
* @param request
* the request object
* @param response
* the response object
* @param subInfo
* the SubmissionInfo object
*/
private void showFileDescription(Context context,
HttpServletRequest request, HttpServletResponse response,
SubmissionInfo subInfo) throws SQLException, ServletException,
IOException
{
// load JSP which allows the user to select a file to upload
JSPStepManager.showJSP(request, response, subInfo, FILE_DESCRIPTION_JSP);
}
/**
* Return the URL path (e.g. /submit/review-metadata.jsp) of the JSP
* which will review the information that was gathered in this Step.
* <P>
* This Review JSP is loaded by the 'Verify' Step, in order to dynamically
* generate a submission verification page consisting of the information
* gathered in all the enabled submission steps.
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*/
public String getReviewJSP(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
{
return REVIEW_JSP;
}
}
| 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.webui.components;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Community;
import org.dspace.core.Context;
import org.dspace.plugin.CommunityHomeProcessor;
import org.dspace.plugin.PluginException;
import org.dspace.app.webui.components.RecentSubmissionsManager;
/**
* This class obtains recent submissions to the given community by
* implementing the CommunityHomeProcessor.
*
* @author Richard Jones
*
*/
public class RecentCommunitySubmissions implements CommunityHomeProcessor
{
/**
* blank constructor - does nothing
*
*/
public RecentCommunitySubmissions()
{
}
/* (non-Javadoc)
* @see org.dspace.plugin.CommunityHomeProcessor#process(org.dspace.core.Context, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.dspace.content.Community)
*/
public void process(Context context, HttpServletRequest request, HttpServletResponse response, Community community)
throws PluginException, AuthorizeException
{
try
{
RecentSubmissionsManager rsm = new RecentSubmissionsManager(context);
RecentSubmissions recent = rsm.getRecentSubmissions(community);
request.setAttribute("recently.submitted", recent);
}
catch (RecentSubmissionsException e)
{
throw new PluginException(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.webui.components;
import org.apache.commons.lang.ArrayUtils;
import java.util.List;
/**
*
* @author Kim Shepherd
*/
public class StatisticsBean implements java.io.Serializable
{
private String name;
private int hits;
private String[][] matrix;
private List<String> colLabels;
private List<String> rowLabels;
public StatisticsBean()
{
}
public String getName()
{
return this.name;
}
public void setName(final String name)
{
this.name = name;
}
public int getHits()
{
return this.hits;
}
public void setHits(final int hits)
{
this.hits = hits;
}
public List<String> getColLabels()
{
return this.colLabels;
}
public void setColLabels(final List<String> colLabels)
{
this.colLabels = colLabels;
}
public List<String> getRowLabels()
{
return this.rowLabels;
}
public void setRowLabels(final List<String> rowLabels)
{
this.rowLabels = rowLabels;
}
public String[][] getMatrix()
{
return (String[][]) ArrayUtils.clone(this.matrix);
}
public void setMatrix(final String[][] matrix)
{
this.matrix = (String[][]) ArrayUtils.clone(matrix);
}
}
| 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.webui.components;
import org.apache.commons.lang.ArrayUtils;
import org.dspace.content.Item;
/**
* Basic class for representing the set of items which are recent submissions
* to the archive
*
* @author Richard Jones
*
*/
public class RecentSubmissions
{
/** The set of items being represented */
private Item[] items;
/**
* Construct a new RecentSubmissions object to represent the passed
* array of items
*
* @param items
*/
public RecentSubmissions(Item[] items)
{
this.items = (Item[]) ArrayUtils.clone(items);
}
/**
* obtain the number of recent submissions available
*
* @return the number of items
*/
public int count()
{
return items.length;
}
/**
* Obtain the array of items
*
* @return an array of items
*/
public Item[] getRecentSubmissions()
{
return (Item[])ArrayUtils.clone(items);
}
/**
* Get the item which is in the i'th position. Therefore i = 1 gets the
* most recently submitted item, while i = 3 gets the 3rd most recently
* submitted item
*
* @param i the position of the item to retrieve
* @return the Item
*/
public Item getRecentSubmission(int i)
{
if (i < items.length)
{
return items[i];
}
else
{
return null;
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.components;
/**
* General exception to be thrown by code working with recent submissions
*
* @author Richard Jones
*
*/
public class RecentSubmissionsException extends Exception
{
public RecentSubmissionsException()
{
super();
// TODO Auto-generated constructor stub
}
public RecentSubmissionsException(String message)
{
super(message);
// TODO Auto-generated constructor stub
}
public RecentSubmissionsException(String message, Throwable cause)
{
super(message, cause);
// TODO Auto-generated constructor stub
}
public RecentSubmissionsException(Throwable cause)
{
super(cause);
// TODO Auto-generated constructor stub
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.components;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.core.Context;
import org.dspace.plugin.CollectionHomeProcessor;
import org.dspace.plugin.PluginException;
import org.dspace.app.webui.components.RecentSubmissionsManager;
/**
* This class obtains recent submissions to the given collection by
* implementing the CollectionHomeProcessor.
*
* @author Richard Jones
*
*/
public class RecentCollectionSubmissions implements CollectionHomeProcessor
{
/**
* blank constructor - does nothing.
*
*/
public RecentCollectionSubmissions()
{
}
/* (non-Javadoc)
* @see org.dspace.plugin.CommunityHomeProcessor#process(org.dspace.core.Context, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.dspace.content.Community)
*/
public void process(Context context, HttpServletRequest request, HttpServletResponse response, Collection collection)
throws PluginException, AuthorizeException
{
try
{
RecentSubmissionsManager rsm = new RecentSubmissionsManager(context);
RecentSubmissions recent = rsm.getRecentSubmissions(collection);
request.setAttribute("recently.submitted", recent);
}
catch (RecentSubmissionsException e)
{
throw new PluginException(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.webui.components;
import org.dspace.core.Context;
import org.dspace.content.DSpaceObject;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowserScope;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseException;
import org.dspace.sort.SortOption;
import org.dspace.sort.SortException;
import org.dspace.core.ConfigurationManager;
import org.dspace.content.Item;
import org.apache.log4j.Logger;
/**
* Class that obtains recent submissions to DSpace containers.
* @author rdjones
*
*/
public class RecentSubmissionsManager
{
/** logger */
private static Logger log = Logger.getLogger(RecentSubmissionsManager.class);
/** DSpace context */
private Context context;
/**
* Construct a new RecentSubmissionsManager with the given DSpace context
*
* @param context
*/
public RecentSubmissionsManager(Context context)
{
this.context = context;
}
/**
* Obtain the recent submissions from the given container object. This
* method uses the configuration to determine which field and how many
* items to retrieve from the DSpace Object.
*
* If the object you pass in is not a Community or Collection (e.g. an Item
* is a DSpaceObject which cannot be used here), an exception will be thrown
*
* @param dso DSpaceObject: Community or Collection
* @return The recently submitted items
* @throws RecentSubmissionsException
*/
public RecentSubmissions getRecentSubmissions(DSpaceObject dso)
throws RecentSubmissionsException
{
try
{
// get our configuration
String source = ConfigurationManager.getProperty("recent.submissions.sort-option");
String count = ConfigurationManager.getProperty("recent.submissions.count");
// prep our engine and scope
BrowseEngine be = new BrowseEngine(context);
BrowserScope bs = new BrowserScope(context);
BrowseIndex bi = BrowseIndex.getItemBrowseIndex();
// fill in the scope with the relevant gubbins
bs.setBrowseIndex(bi);
bs.setOrder(SortOption.DESCENDING);
bs.setResultsPerPage(Integer.parseInt(count));
bs.setBrowseContainer(dso);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(source))
{
bs.setSortBy(so.getNumber());
}
}
BrowseInfo results = be.browseMini(bs);
Item[] items = results.getItemResults(context);
RecentSubmissions rs = new RecentSubmissions(items);
return rs;
}
catch (SortException se)
{
log.error("caught exception: ", se);
throw new RecentSubmissionsException(se);
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new RecentSubmissionsException(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.webui.filter;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.Authenticate;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
/**
* DSpace filter that only allows requests from authenticated shib users
* to proceed. Anonymous requests prompt the authentication procedure.
*
* @author <a href="mailto:bliong@melcoe.mq.edu.au">Bruc Liong, MELCOE</a>
* @author <a href="mailto:kli@melcoe.mq.edu.au">Xiang Kevin Li, MELCOE</a>
* @version $Revision: 5845 $
*/
public class ShibbolethFilter implements Filter
{
/** log4j category */
private static Logger log = Logger.getLogger(ShibbolethFilter.class);
public void init(FilterConfig config)
{
// Do nothing
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws ServletException, IOException
{
Context context = null;
// We need HTTP request objects
HttpServletRequest hrequest = (HttpServletRequest) request;
HttpServletResponse hresponse = (HttpServletResponse) response;
try
{
// Obtain a context
context = UIUtil.obtainContext(hrequest);
if (context.getCurrentUser() == null)
{
java.util.Enumeration names = ((HttpServletRequest) request).getHeaderNames();
String name;
while(names.hasMoreElements())
{
name = names.nextElement().toString();
log.debug("header:" + name + "=" + ((HttpServletRequest) request).getHeader(name));
}
// No current user, prompt authentication
Authenticate.startAuthentication(context, hrequest, hresponse);
}else{
chain.doFilter(hrequest, hresponse);
return;
}
}
catch (SQLException se)
{
log.warn(LogManager.getHeader(context,
"database_error",
se.toString()), se);
JSPManager.showInternalError(hrequest, hresponse);
}
// Abort the context if it's still valid
if (context != null && context.isValid())
{
context.abort();
}
}
public void destroy()
{
// Nothing
}
}
| 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.webui.filter;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.Authenticate;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
/**
* DSpace filter that only allows requests from authenticated administrators to
* proceed. Anonymous requests prompt the authentication procedure. Requests
* from authenticated non-admins result in an authorisation error.
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class AdminOnlyFilter implements Filter
{
/** log4j category */
private static Logger log = Logger.getLogger(RegisteredOnlyFilter.class);
public void init(FilterConfig config)
{
// Do nothing
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException
{
Context context = null;
// We need HTTP request objects
HttpServletRequest hrequest = (HttpServletRequest) request;
HttpServletResponse hresponse = (HttpServletResponse) response;
try
{
// Obtain a context
context = UIUtil.obtainContext(hrequest);
// Continue if logged in or startAuthentication finds a user;
// otherwise it will issue redirect so just return.
if (context.getCurrentUser() != null ||
Authenticate.startAuthentication(context, hrequest, hresponse))
{
// User is authenticated
if (AuthorizeManager.isAdmin(context))
{
// User is an admin, allow request to proceed
chain.doFilter(hrequest, hresponse);
}
else
{
// User is not an admin
log.info(LogManager.getHeader(context, "admin_only", ""));
JSPManager.showAuthorizeError(hrequest, hresponse, null);
}
}
}
catch (SQLException se)
{
log.warn(LogManager.getHeader(context, "database_error", se
.toString()), se);
JSPManager.showInternalError(hrequest, hresponse);
}
// Abort the context if it's still valid
if ((context != null) && context.isValid())
{
context.abort();
}
}
public void destroy()
{
// Nothing
}
}
| 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.webui.filter;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.Authenticate;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
/**
* DSpace filter that only allows requests from individual authenticated users
* to proceed. Other requests prompt the authentication procedure.
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class RegisteredOnlyFilter implements Filter
{
/** log4j category */
private static Logger log = Logger.getLogger(RegisteredOnlyFilter.class);
public void init(FilterConfig config)
{
// Do nothing
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException
{
Context context = null;
// We need HTTP request objects
HttpServletRequest hrequest = (HttpServletRequest) request;
HttpServletResponse hresponse = (HttpServletResponse) response;
try
{
// Obtain a context
context = UIUtil.obtainContext(hrequest);
// Continue if logged in or startAuthentication finds a user;
// otherwise it will issue redirect so just return.
if (context.getCurrentUser() != null ||
Authenticate.startAuthentication(context, hrequest, hresponse))
{
// Allow request to proceed
chain.doFilter(hrequest, hresponse);
}
}
catch (SQLException se)
{
log.warn(LogManager.getHeader(context, "database_error", se
.toString()), se);
JSPManager.showInternalError(hrequest, hresponse);
}
// Abort the context if it's still valid
if ((context != null) && context.isValid())
{
context.abort();
}
}
public void destroy()
{
// Nothing
}
}
| 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.webui.util;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
/**
* This is the standard (until 1.4.x) configuration mode based on owning collection handle
* Style name is case insensitive.
*
* @author Andrea Bollini
* @version $Revision: 5845 $
*
*/
public class CollectionStyleSelection extends AKeyBasedStyleSelection
{
/** Hashmap of collection Handles to styles to use, from dspace.cfg */
private static java.util.Map<String, String> styles;
/** log4j logger */
private static Logger log = Logger.getLogger(CollectionStyleSelection.class);
/**
* Get the style using the owning collection handle
*/
public String getStyleForItem(Item item) throws SQLException
{
Collection c = item.getOwningCollection();
if(c!=null)
{
// Style specified & exists
return getFromMap(c.getHandle());
}
else
{
return "default"; //no specific style - item is an in progress Submission
}
}
/**
* Put collection handle/style name mapping in an in-memory map.
*/
private void readKeyStyleConfig()
{
styles = new HashMap<String, String>();
Enumeration<String> e = (Enumeration<String>)ConfigurationManager.propertyNames();
while (e.hasMoreElements())
{
String key = e.nextElement();
if (key.startsWith("webui.itemdisplay.")
&& key.endsWith(".collections"))
{
String styleName = key.substring("webui.itemdisplay.".length(),
key.length() - ".collections".length());
String[] collections = ConfigurationManager.getProperty(key)
.split(",");
for (int i = 0; i < collections.length; i++)
{
styles.put(collections[i].trim(), styleName.toLowerCase());
}
}
}
}
/**
* Get the style associated with the handle from the in-memory map. If the map is not already
* initialized read it from dspace.cfg
* Check for the style configuration: return the default style if no configuration has found.
*
* @param handle
* @return the specific style or the default if not properly defined
*/
public String getFromMap(String handle)
{
if (styles == null)
{
readKeyStyleConfig();
}
String styleName = (String) styles.get(handle);
if (styleName == null)
{
// No specific style specified for this collection
return "default";
}
// Specific style specified. Check style exists
if (isConfigurationDefinedForStyle(styleName))
{
log.warn("dspace.cfg specifies undefined item display style '"
+ styleName + "' for collection handle " + handle + ". Using default");
return "default";
}
return styleName;
}
}
| 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.webui.util;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.dspace.core.ConfigurationManager;
/**
* Based on the com.oreilly.servlet.MultipartWrapper object, this is an HTTP
* request wrapper for multi-part (MIME) POSTs. It uses DSpace configuration
* properties to determine the temporary directory to use and the maximum
* allowable upload size.
*
* @author Robert Tansley
* @version $Revision: 6158 $
*/
public class FileUploadRequest extends HttpServletRequestWrapper
{
private Map<String, String> parameters = new HashMap<String, String>();
private Map<String, FileItem> fileitems = new HashMap<String, FileItem>();
private List<String> filenames = new ArrayList<String>();
private String tempDir = null;
/** Original request */
private HttpServletRequest original = null;
/**
* Parse a multipart request and extracts the files
*
* @param req
* the original request
*/
public FileUploadRequest(HttpServletRequest req) throws IOException, FileSizeLimitExceededException
{
super(req);
original = req;
tempDir = ConfigurationManager.getProperty("upload.temp.dir");
long maxSize = ConfigurationManager.getLongProperty("upload.max");
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(tempDir));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
upload.setSizeMax(maxSize);
List<FileItem> items = upload.parseRequest(req);
for (FileItem item : items)
{
if (item.isFormField())
{
parameters.put(item.getFieldName(), item.getString("UTF-8"));
}
else
{
parameters.put(item.getFieldName(), item.getName());
fileitems.put(item.getFieldName(), item);
filenames.add(item.getName());
String filename = getFilename(item.getName());
if (filename != null && !"".equals(filename))
{
item.write(new File(tempDir + File.separator
+ filename));
}
}
}
}
catch (Exception e)
{
if(e.getMessage().contains("exceeds the configured maximum"))
{
// ServletFileUpload is not throwing the correct error, so this is workaround
// the request was rejected because its size (11302) exceeds the configured maximum (536)
int startFirstParen = e.getMessage().indexOf("(")+1;
int endFirstParen = e.getMessage().indexOf(")");
String uploadedSize = e.getMessage().substring(startFirstParen, endFirstParen).trim();
Long actualSize = Long.parseLong(uploadedSize);
throw new FileSizeLimitExceededException(e.getMessage(), actualSize, maxSize);
}
throw new IOException(e.getMessage(), e);
}
}
// Methods to replace HSR methods
public Enumeration getParameterNames()
{
Collection<String> c = parameters.keySet();
return Collections.enumeration(c);
}
public String getParameter(String name)
{
return parameters.get(name);
}
public String[] getParameterValues(String name)
{
return parameters.values().toArray(new String[parameters.values().size()]);
}
public Map getParameterMap()
{
Map<String, String[]> map = new HashMap<String, String[]>();
Enumeration eNum = getParameterNames();
while (eNum.hasMoreElements())
{
String name = (String) eNum.nextElement();
map.put(name, getParameterValues(name));
}
return map;
}
public String getFilesystemName(String name)
{
String filename = getFilename((fileitems.get(name))
.getName());
return tempDir + File.separator + filename;
}
public String getContentType(String name)
{
return (fileitems.get(name)).getContentType();
}
public File getFile(String name)
{
FileItem temp = fileitems.get(name);
String tempName = temp.getName();
String filename = getFilename(tempName);
if ("".equals(filename.trim()))
{
return null;
}
return new File(tempDir + File.separator + filename);
}
public Enumeration<String> getFileParameterNames()
{
Collection<String> c = fileitems.keySet();
return Collections.enumeration(c);
}
public Enumeration<String> getFileNames()
{
return Collections.enumeration(filenames);
}
/**
* Get back the original HTTP request object
*
* @return the original HTTP request
*/
public HttpServletRequest getOriginalRequest()
{
return original;
}
// Required due to the fact the contents of getName() may vary based on
// browser
private String getFilename(String filepath)
{
String filename = filepath.trim();
int index = filepath.lastIndexOf(File.separator);
if (index > -1)
{
filename = filepath.substring(index);
}
return filename;
}
}
| 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.webui.util;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
/**
* Methods for displaying UI pages to the user.
*
* @author Robert Tansley
* @version $Revision: 6158 $
*/
public class JSPManager
{
/*
* All displaying of UI pages should be performed using this manager for
* future-proofing, since any future localisation effort will probably use
* this manager.
*/
/** log4j logger */
private static Logger log = Logger.getLogger(JSPManager.class);
/**
* Forwards control of the request to the display JSP passed in.
*
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param jsp
* the JSP page to display, relative to the webapps directory
*/
public static void showJSP(HttpServletRequest request,
HttpServletResponse response, String jsp) throws ServletException,
IOException
{
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader((Context) request
.getAttribute("dspace.context"), "view_jsp", jsp));
}
// For the moment, a simple forward
request.getRequestDispatcher(jsp).forward(request, response);
}
/**
* Display an internal server error message - for example, a database error
*
* @param request
* the HTTP request
* @param response
* the HTTP response
*/
public static void showInternalError(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
showJSP(request, response, "/error/internal.jsp");
}
/**
* Display an integrity error message. Use when the POSTed data from a
* request doesn't make sense.
*
* @param request
* the HTTP request
* @param response
* the HTTP response
*/
public static void showIntegrityError(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
showJSP(request, response, "/error/integrity.jsp");
}
/**
* Display an authorization failed error message. The exception should be
* passed in if possible so that the error message can be descriptive.
*
* @param request
* the HTTP request
* @param response
* the HTTP response
* @param exception
* the AuthorizeException leading to this error, passing in
* <code>null</code> will display default error message
*/
public static void showAuthorizeError(HttpServletRequest request,
HttpServletResponse response, AuthorizeException exception)
throws ServletException, IOException
{
// FIXME: Need to work out which error message to display?
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
showJSP(request, response, "/error/authorize.jsp");
}
/**
* Display an "invalid ID" error message. Passing in information about the
* bad ID and what the ID was supposed to represent (collection etc.) should
* result in a more descriptive and helpful error message.
*
* @param request
* the HTTP request
* @param response
* the HTTP response
* @param badID
* the bad identifier, or <code>null</code>
* @param type
* the type of object, from
* <code>org.dspace.core.Constants</code>, or <code>-1</code>
* for a default message
*/
public static void showInvalidIDError(HttpServletRequest request,
HttpServletResponse response, String badID, int type)
throws ServletException, IOException
{
request.setAttribute("bad.id", StringEscapeUtils.escapeHtml(badID));
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
if (type != -1)
{
request.setAttribute("bad.type", Integer.valueOf(type));
}
showJSP(request, response, "/error/invalid-id.jsp");
}
/**
* Display a "file upload was too large" error message. Passing in information
* about the size of the file uploaded, and the maximum file size limit so
* the user knows why they encountered an error.
* @param request
* @param response
* @param message
* @param actualSize
* @param permittedSize
* @throws ServletException
* @throws IOException
*/
public static void showFileSizeLimitExceededError(HttpServletRequest request,
HttpServletResponse response, String message, long actualSize, long permittedSize) throws ServletException, IOException
{
request.setAttribute("error.message", message);
request.setAttribute("actualSize", actualSize);
request.setAttribute("permittedSize", permittedSize);
response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
showJSP(request, response, "/error/exceeded-size.jsp");
}
}
| 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.webui.util;
import java.sql.SQLException;
import org.dspace.content.Item;
/**
* Interface for a strategy of style selection
*
* @author Andrea Bollini
* @version $Revision: 5845 $
*/
public interface StyleSelection
{
/**
* Define which display style use for the item.
*
* @param item
* @return the style name to use for display simple metadata of the item
* @throws SQLException
*/
public String getStyleForItem(Item item) throws SQLException;
/**
* Get the configuration of the style passed as argument.
* The configuration has the following syntax: <code>schema.element[.qualifier|.*][(display-option)]</code>
*
* @param style
* @return
*/
public String getConfigurationForStyle(String style);
}
| 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.webui.util;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
/**
* Use the value of the metadata specified with the key <code>webui.display.metadata-style</code>
* as name for the display style of the item. Style name is case insensitive.
*
* @author Andrea Bollini
* @version $Revision: 5845 $
*
*/
public class MetadataStyleSelection extends AKeyBasedStyleSelection
{
/** log4j logger */
private static Logger log = Logger
.getLogger(MetadataStyleSelection.class);
/**
* Get the style using an item metadata
*/
public String getStyleForItem(Item item) throws SQLException
{
String metadata = ConfigurationManager.getProperty("webui.itemdisplay.metadata-style");
DCValue[] value = item.getMetadata(metadata);
String styleName = "default";
if (value.length > 0)
{
if (value.length >= 1)
{
log
.warn("more then one value for metadata '"
+ metadata
+ "'. Using the first one");
}
styleName = value[0].value.toLowerCase();
}
// Specific style specified. Check style exists
if (isConfigurationDefinedForStyle(styleName))
{
log.warn("metadata '" + metadata + "' specify undefined item display style '"
+ styleName + "'. Using default");
return "default";
}
// Style specified & exists
return styleName;
}
}
| 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.webui.util;
import org.dspace.core.ConfigurationManager;
/**
* Simple abstract class that provide utility method for get/check style configuration from dspace.cfg file
* @author Andrea Bollini
* @version $Revision: 5845 $
*
*/
public abstract class AKeyBasedStyleSelection implements StyleSelection
{
public String getConfigurationForStyle(String style)
{
return ConfigurationManager.getProperty("webui.itemdisplay." + style);
}
protected boolean isConfigurationDefinedForStyle(String style)
{
return ConfigurationManager.getProperty("webui.itemdisplay." + style) == 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.webui.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.core.Config;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.util.Util;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCDate;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.Email;
import org.dspace.core.I18nUtil;
import org.dspace.eperson.EPerson;
/**
* Miscellaneous UI utility methods
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class UIUtil extends Util
{
/** Whether to look for x-forwarded headers for logging IP addresses */
private static Boolean useProxies;
/** log4j category */
public static final Logger log = Logger.getLogger(UIUtil.class);
/**
* Pattern used to get file.ext from filename (which can be a path)
*/
private static Pattern p = Pattern.compile("[^/]*$");
/**
* Obtain a new context object. If a context object has already been created
* for this HTTP request, it is re-used, otherwise it is created. If a user
* has authenticated with the system, the current user of the context is set
* appropriately.
*
* @param request
* the HTTP request
*
* @return a context object
*/
public static Context obtainContext(HttpServletRequest request)
throws SQLException
{
//Set encoding to UTF-8, if not set yet
//This avoids problems of using the HttpServletRequest
//in the getSpecialGroups() for an AuthenticationMethod,
//which causes the HttpServletRequest to default to
//non-UTF-8 encoding.
try
{
if(request.getCharacterEncoding()==null)
{
request.setCharacterEncoding(Constants.DEFAULT_ENCODING);
}
}
catch(Exception e)
{
log.error("Unable to set encoding to UTF-8.", e);
}
Context c = (Context) request.getAttribute("dspace.context");
if (c == null)
{
// No context for this request yet
c = new Context();
HttpSession session = request.getSession();
// See if a user has authentication
Integer userID = (Integer) session.getAttribute(
"dspace.current.user.id");
if (userID != null)
{
String remAddr = (String)session.getAttribute("dspace.current.remote.addr");
if (remAddr != null && remAddr.equals(request.getRemoteAddr()))
{
EPerson e = EPerson.find(c, userID.intValue());
Authenticate.loggedIn(c, request, e);
}
else
{
log.warn("POSSIBLE HIJACKED SESSION: request from "+
request.getRemoteAddr()+" does not match original "+
"session address: "+remAddr+". Authentication rejected.");
}
}
// Set any special groups - invoke the authentication mgr.
int[] groupIDs = AuthenticationManager.getSpecialGroups(c, request);
for (int i = 0; i < groupIDs.length; i++)
{
c.setSpecialGroup(groupIDs[i]);
log.debug("Adding Special Group id="+String.valueOf(groupIDs[i]));
}
// Set the session ID and IP address
String ip = request.getRemoteAddr();
if (useProxies == null) {
useProxies = ConfigurationManager.getBooleanProperty("useProxies", false);
}
if(useProxies && request.getHeader("X-Forwarded-For") != null)
{
/* This header is a comma delimited list */
for(String xfip : request.getHeader("X-Forwarded-For").split(","))
{
if(!request.getHeader("X-Forwarded-For").contains(ip))
{
ip = xfip.trim();
}
}
}
c.setExtraLogInfo("session_id=" + request.getSession().getId() + ":ip_addr=" + ip);
// Store the context in the request
request.setAttribute("dspace.context", c);
}
// Set the locale to be used
Locale sessionLocale = getSessionLocale(request);
Config.set(request.getSession(), Config.FMT_LOCALE, sessionLocale);
c.setCurrentLocale(sessionLocale);
return c;
}
/**
* Get the current community location, that is, where the user "is". This
* returns <code>null</code> if there is no location, i.e. "all of DSpace"
* is the location.
*
* @param request
* current HTTP request
*
* @return the current community location, or null
*/
public static Community getCommunityLocation(HttpServletRequest request)
{
return ((Community) request.getAttribute("dspace.community"));
}
/**
* Get the current collection location, that is, where the user "is". This
* returns null if there is no collection location, i.e. the location is
* "all of DSpace" or a community.
*
* @param request
* current HTTP request
*
* @return the current collection location, or null
*/
public static Collection getCollectionLocation(HttpServletRequest request)
{
return ((Collection) request.getAttribute("dspace.collection"));
}
/**
* Put the original request URL into the request object as an attribute for
* later use. This is necessary because forwarding a request removes this
* information. The attribute is only written if it hasn't been before; thus
* it can be called after a forward safely.
*
* @param request
* the HTTP request
*/
public static void storeOriginalURL(HttpServletRequest request)
{
String orig = (String) request.getAttribute("dspace.original.url");
if (orig == null)
{
String fullURL = request.getRequestURL().toString();
if (request.getQueryString() != null)
{
fullURL = fullURL + "?" + request.getQueryString();
}
request.setAttribute("dspace.original.url", fullURL);
}
}
/**
* Get the original request URL.
*
* @param request
* the HTTP request
*
* @return the original request URL
*/
public static String getOriginalURL(HttpServletRequest request)
{
// Make sure there's a URL in the attribute
storeOriginalURL(request);
return ((String) request.getAttribute("dspace.original.url"));
}
/**
* Write a human-readable version of a DCDate.
*
* @param d
* the date
* @param time
* if true, display the time with the date
* @param localTime
* if true, adjust for local timezone, otherwise GMT
* @param request
* the servlet request
*
* @return the date in a human-readable form.
*/
public static String displayDate(DCDate d, boolean time, boolean localTime, HttpServletRequest request)
{
return d.displayDate(time, localTime, getSessionLocale(request));
}
/**
* Return a string for logging, containing useful information about the
* current request - the URL, the method and parameters.
*
* @param request
* the request object.
* @return a multi-line string containing information about the request.
*/
public static String getRequestLogInfo(HttpServletRequest request)
{
StringBuilder report = new StringBuilder();
report.append("-- URL Was: ").append(getOriginalURL(request)).append("\n").toString();
report.append("-- Method: ").append(request.getMethod()).append("\n").toString();
// First write the parameters we had
report.append("-- Parameters were:\n");
Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
String name = (String) e.nextElement();
if (name.equals("login_password"))
{
// We don't want to write a clear text password
// to the log, even if it's wrong!
report.append("-- ").append(name).append(": *not logged*\n").toString();
}
else
{
report.append("-- ").append(name).append(": \"")
.append(request.getParameter(name)).append("\"\n");
}
}
return report.toString();
}
/**
* Get the Locale for a session according to the user's language selection or language preferences.
* Order of selection
* - language selected via UI
* - language as set by application
* - language browser default
*
* @param request
* the request Object
* @return supportedLocale
* Locale supported by this DSpace Instance for this request
*/
public static Locale getSessionLocale(HttpServletRequest request)
{
String paramLocale = request.getParameter("locale");
Locale sessionLocale = null;
Locale supportedLocale = null;
if (!StringUtils.isEmpty(paramLocale))
{
/* get session locale according to user selection */
sessionLocale = new Locale(paramLocale);
}
if (sessionLocale == null)
{
/* get session locale set by application */
HttpSession session = request.getSession();
sessionLocale = (Locale) Config.get(session, Config.FMT_LOCALE);
}
/*
* if session not set by selection or application then default browser
* locale
*/
if (sessionLocale == null)
{
sessionLocale = request.getLocale();
}
if (sessionLocale == null)
{
sessionLocale = I18nUtil.DEFAULTLOCALE;
}
supportedLocale = I18nUtil.getSupportedLocale(sessionLocale);
return supportedLocale;
}
/**
* Send an alert to the designated "alert recipient" - that is, when a
* database error or internal error occurs, this person is sent an e-mail
* with details.
* <P>
* The recipient is configured via the "alert.recipient" property in
* <code>dspace.cfg</code>. If this property is omitted, no alerts are
* sent.
* <P>
* This method "swallows" any exception that might occur - it will just be
* logged. This is because this method will usually be invoked as part of an
* error handling routine anyway.
*
* @param request
* the HTTP request leading to the error
* @param exception
* the exception causing the error, or null
*/
public static void sendAlert(HttpServletRequest request, Exception exception)
{
String logInfo = UIUtil.getRequestLogInfo(request);
Context c = (Context) request.getAttribute("dspace.context");
Locale locale = getSessionLocale(request);
EPerson user = null;
try
{
String recipient = ConfigurationManager
.getProperty("alert.recipient");
if (recipient != null)
{
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(locale, "internal_error"));
email.addRecipient(recipient);
email.addArgument(ConfigurationManager
.getProperty("dspace.url"));
email.addArgument(new Date());
email.addArgument(request.getSession().getId());
email.addArgument(logInfo);
String stackTrace;
if (exception != null)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
pw.flush();
stackTrace = sw.toString();
}
else
{
stackTrace = "No exception";
}
email.addArgument(stackTrace);
try
{
user = c.getCurrentUser();
}
catch (Exception e)
{
log.warn("No context, the database might be down or the connection pool exhausted.");
}
if (user != null)
{
email.addArgument(user.getFullName() + " (" + user.getEmail() + ")");
}
else
{
email.addArgument("Anonymous");
}
email.addArgument(request.getRemoteAddr());
email.send();
}
}
catch (Exception e)
{
// Not much we can do here!
log.warn("Unable to send email alert", e);
}
}
/**
* Evaluate filename and client and encode appropriate disposition
*
* @param filename
* @param request
* @param response
* @throws UnsupportedEncodingException
*/
public static void setBitstreamDisposition(String filename, HttpServletRequest request,
HttpServletResponse response)
{
String name = filename;
Matcher m = p.matcher(name);
if (m.find() && !m.group().equals(""))
{
name = m.group();
}
try
{
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 != agent.indexOf("MSIE"))
{
name = URLEncoder.encode(name, "UTF8");
}
else if (null != agent && -1 != agent.indexOf("Mozilla"))
{
name = MimeUtility.encodeText(name, "UTF8", "B");
}
}
catch (UnsupportedEncodingException e)
{
log.error(e.getMessage(),e);
}
finally
{
response.setHeader("Content-Disposition", "attachment;filename=" + 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.webui.util;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Hashtable;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
* This class provides a set of static methods to load and transform XML
* documents. It supports parameter-aware stylesheets (XSLT).
*
* @author Miguel Ferreira
*
*/
public class XMLUtil
{
/**
* Loads a W3C XML document from a file.
*
* @param filename
* The name of the file to be loaded
* @return a document object model object representing the XML file
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
public static Document loadXML(String filename) throws IOException,
ParserConfigurationException, SAXException
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
return builder.parse(new File(filename));
}
/**
* Applies a stylesheet to a given xml document.
*
* @param xmlDocument
* the xml document to be transformed
* @param xsltFilename
* the filename of the stylesheet
* @return the transformed xml document
* @throws Exception
*/
public static Document transformDocument(Document xmlDocument,
String xsltFilename) throws Exception
{
return transformDocument(xmlDocument, new Hashtable(), xsltFilename);
}
/**
* Applies a stylesheet (that receives parameters) to a given xml document.
*
* @param xmlDocument
* the xml document to be transformed
* @param parameters
* the hashtable with the parameters to be passed to the
* stylesheet
* @param xsltFilename
* the filename of the stylesheet
* @return the transformed xml document
* @throws Exception
*/
public static Document transformDocument(Document xmlDocument, Map<String, String> parameters, String xsltFilename) throws Exception
{
// Generate a Transformer.
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(new StreamSource(xsltFilename));
// set transformation parameters
if (parameters != null)
{
for (Map.Entry<String, String> param : parameters.entrySet())
{
transformer.setParameter(param.getKey(), param.getValue());
}
}
// Create an empy DOMResult object for the output.
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
dFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
Document dstDocument = dBuilder.newDocument();
DOMResult domResult = new DOMResult(dstDocument);
// Perform the transformation.
transformer.transform(new DOMSource(xmlDocument), domResult);
// Now you can get the output Node from the DOMResult.
return dstDocument;
}
/**
* Applies a stylesheet (that receives parameters) to a given xml document.
* The resulting XML document is converted to a string after transformation.
*
* @param xmlDocument
* the xml document to be transformed
* @param parameters
* the hashtable with the parameters to be passed to the
* stylesheet
* @param xsltFilename
* the filename of the stylesheet
* @return the transformed xml document as a string
* @throws Exception
*/
public static String transformDocumentAsString(Document xmlDocument, Map<String, String> parameters, String xsltFilename) throws Exception
{
// Generate a Transformer.
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(new StreamSource(xsltFilename));
// set transformation parameters
if (parameters != null)
{
for (Map.Entry<String, String> param : parameters.entrySet())
{
transformer.setParameter(param.getKey(), param.getValue());
}
}
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
// Perform the transformation.
transformer.transform(new DOMSource(xmlDocument), streamResult);
// Now you can get the output Node from the DOMResult.
return stringWriter.toString();
}
/**
* Applies a stylesheet to a given xml document.
*
* @param xmlDocument
* the xml document to be transformed
* @param xsltFilename
* the filename of the stylesheet
* @return the transformed xml document
* @throws Exception
*/
public static String transformDocumentAsString(Document xmlDocument,
String xsltFilename) throws Exception
{
// Generate a Transformer.
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(new StreamSource(xsltFilename));
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
// Perform the transformation.
transformer.transform(new DOMSource(xmlDocument), streamResult);
// Now you can get the output Node from the DOMResult.
return stringWriter.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.webui.util;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.core.Config;
import org.apache.log4j.Logger;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.authenticate.AuthenticationMethod;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.eperson.EPerson;
/**
* Methods for authenticating the user. This is DSpace platform code, as opposed
* to the site-specific authentication code, that resides in implementations of
* the <code>org.dspace.eperson.AuthenticationMethod</code> interface.
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class Authenticate
{
/** log4j category */
private static Logger log = Logger.getLogger(Authenticate.class);
/**
* Return the request that the system should be dealing with, given the
* request that the browse just sent. If the incoming request is from a
* redirect resulting from successful authentication, a request object
* corresponding to the original request that prompted authentication is
* returned. Otherwise, the request passed in is returned.
*
* @param request
* the incoming HTTP request
* @return the HTTP request the DSpace system should deal with
*/
public static HttpServletRequest getRealRequest(HttpServletRequest request)
{
HttpSession session = request.getSession();
if (session.getAttribute("resuming.request") != null)
{
// Get info about the interrupted request
RequestInfo requestInfo = (RequestInfo) session
.getAttribute("interrupted.request.info");
HttpServletRequest actualRequest;
if (requestInfo == null)
{
// Can't find the wrapped request information.
// FIXME: Proceed with current request - correct?
actualRequest = request;
}
else
{
/*
* Wrap the current request to make it look like the interruped
* one
*/
actualRequest = requestInfo.wrapRequest(request);
}
// Remove the info from the session so it isn't resumed twice
session.removeAttribute("resuming.request");
session.removeAttribute("interrupted.request.info");
session.removeAttribute("interrupted.request.url");
// Return the wrapped request
return actualRequest;
}
else
{
return request;
}
}
/**
* Resume a previously interrupted request. This is invoked when a user has
* been successfully authenticated. The request which led to authentication
* will be resumed.
*
* @param request
* <em>current</em> HTTP request
* @param response
* HTTP response
*/
public static void resumeInterruptedRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
HttpSession session = request.getSession();
String originalURL = (String) session
.getAttribute("interrupted.request.url");
if (originalURL == null)
{
// If for some reason we don't have the original URL, redirect
// to My DSpace
originalURL = request.getContextPath() + "/mydspace";
}
else
{
// Set the flag in the session, so that when the redirect is
// followed, we'll know to resume the interrupted request
session.setAttribute("resuming.request", Boolean.TRUE);
}
// Send the redirect
response.sendRedirect(response.encodeRedirectURL(originalURL));
}
/**
* Start the authentication process. This packages up the request that led
* to authentication being required, and then invokes the site-specific
* authentication method.
*
* If it returns true, the user was authenticated without any
* redirection (e.g. by an X.509 certificate or other implicit method) so
* the process that called this can continue and send its own response.
* A "false" result means this method has sent its own redirect.
*
* @param context
* current DSpace context
* @param request
* current HTTP request - the one that prompted authentication
* @param response
* current HTTP response
*
* @return true if authentication is already finished (implicit method)
*/
public static boolean startAuthentication(Context context,
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession();
/*
* Authenticate:
* 1. try implicit methods first, since that may work without
* a redirect. return true if no redirect needed.
* 2. if those fail, redirect to enter credentials.
* return false.
*/
if (AuthenticationManager.authenticateImplicit(context, null, null,
null, request) == AuthenticationMethod.SUCCESS)
{
loggedIn(context, request, context.getCurrentUser());
log.info(LogManager.getHeader(context, "login", "type=implicit"));
return true;
}
else
{
// Since we may be doing a redirect, make sure the redirect is not
// cached
response.addDateHeader("expires", 1);
response.addHeader("Pragma", "no-cache");
response.addHeader("Cache-control", "no-store");
// Store the data from the request that led to authentication
RequestInfo info = new RequestInfo(request);
session.setAttribute("interrupted.request.info", info);
// Store the URL of the request that led to authentication
session.setAttribute("interrupted.request.url", UIUtil
.getOriginalURL(request));
/*
* Grovel over authentication methods, counting the
* ones with a "redirect" login page -- if there's only one,
* go directly there. If there is a choice, go to JSP chooser.
*/
Iterator ai = AuthenticationManager.authenticationMethodIterator();
AuthenticationMethod am;
int count = 0;
String url = null;
while (ai.hasNext())
{
String s;
am = (AuthenticationMethod)ai.next();
s = am.loginPageURL(context, request, response);
if (s != null)
{
url = s;
++count;
}
}
if (count == 1)
{
response.sendRedirect(url);
}
else
{
JSPManager.showJSP(request, response, "/login/chooser.jsp");
}
}
return false;
}
/**
* Store information about the current user in the request and context
*
* @param context
* DSpace context
* @param request
* HTTP request
* @param eperson
* the eperson logged in
*/
public static void loggedIn(Context context,
HttpServletRequest request,
EPerson eperson)
{
HttpSession session = request.getSession();
// For security reasons after login, give the user a new session
if ((!session.isNew()) && (session.getAttribute("dspace.current.user.id") == null))
{
// Keep the user's locale setting if set
Locale sessionLocale = UIUtil.getSessionLocale(request);
// Get info about the interrupted request, if set
RequestInfo requestInfo = (RequestInfo) session.getAttribute("interrupted.request.info");
// Get the original URL of interrupted request, if set
String requestUrl = (String) session.getAttribute("interrupted.request.url");
// Invalidate session unless dspace.cfg says not to
if(ConfigurationManager.getBooleanProperty("webui.session.invalidate", true))
{
session.invalidate();
}
// Give the user a new session
session = request.getSession();
// Restore the session locale
if (sessionLocale != null)
{
Config.set(request.getSession(), Config.FMT_LOCALE, sessionLocale);
}
// Restore interrupted request information and url to new session
if (requestInfo != null && requestUrl != null) {
session.setAttribute("interrupted.request.info", requestInfo);
session.setAttribute("interrupted.request.url", requestUrl);
}
}
context.setCurrentUser(eperson);
boolean isAdmin = false;
try
{
isAdmin = AuthorizeManager.isAdmin(context);
}
catch (SQLException se)
{
log.warn("Unable to use AuthorizeManager " + se);
}
finally
{
request.setAttribute("is.admin", Boolean.valueOf(isAdmin));
}
// We store the current user in the request as an EPerson object...
request.setAttribute("dspace.current.user", eperson);
// and in the session as an ID
session.setAttribute("dspace.current.user.id", Integer.valueOf(eperson.getID()));
// and the remote IP address to compare against later requests
// so we can detect session hijacking.
session.setAttribute("dspace.current.remote.addr",
request.getRemoteAddr());
}
/**
* Log the user out
*
* @param context
* DSpace context
* @param request
* HTTP request
*/
public static void loggedOut(Context context, HttpServletRequest request)
{
HttpSession session = request.getSession();
context.setCurrentUser(null);
request.removeAttribute("is.admin");
request.removeAttribute("dspace.current.user");
session.removeAttribute("dspace.current.user.id");
// Keep the user's locale setting if set
Locale sessionLocale = UIUtil.getSessionLocale(request);
// Invalidate session unless dspace.cfg says not to
if(ConfigurationManager.getBooleanProperty("webui.session.invalidate", true))
{
session.invalidate();
}
// Restore the session locale
if (sessionLocale != null)
{
Config.set(request.getSession(), Config.FMT_LOCALE, sessionLocale);
}
}
}
| 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.webui.util;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Stores information about an HTTP request. This is used so that the request
* can be replicated during a later request, once authentication has
* successfully occurred.
*
* Note: Implements Serializable as it will be saved to the current session during submission.
* Please ensure that nothing is added to this class that isn't also serializable
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class RequestInfo implements Serializable
{
/** The original parameters */
private Map originalParameterMap;
/** The original method */
private String originalMethod;
/** The original query */
private String originalQueryString;
/**
* Construct a request info object storing information about the given
* request
*
* @param request
* the request to get information from
*/
public RequestInfo(HttpServletRequest request)
{
originalParameterMap = new HashMap(request.getParameterMap());
originalMethod = request.getMethod();
originalQueryString = request.getQueryString();
}
/**
* Wrap an incoming request to make it look like the request that the
* constructor was called with
*
* @param request
* the request to wrap
*
* @return a wrapper around the request passed into this method, wrapped so
* that it looks like the request passed into the constructor
*/
public HttpServletRequest wrapRequest(HttpServletRequest request)
{
return new MyWrapper(request);
}
/**
* Our own flavour of HTTP request wrapper, that uses information from= this
* RequestInfo object
*/
class MyWrapper extends HttpServletRequestWrapper
{
public MyWrapper(HttpServletRequest request)
{
super(request);
}
// ====== Methods below here are the wrapped methods ======
public String getParameter(String name)
{
String[] vals = (String[]) originalParameterMap.get(name);
if (vals == null)
{
// Delegate to wrapped object
// FIXME: This is possibly a bug in Tomcat
return super.getParameter(name);
}
else
{
return vals[0];
}
}
public Map getParameterMap()
{
return originalParameterMap;
}
public Enumeration getParameterNames()
{
Iterator i = originalParameterMap.keySet().iterator();
return new EnumIterator(i);
}
public String[] getParameterValues(String name)
{
return ((String[]) originalParameterMap.get(name));
}
public String getMethod()
{
return originalMethod;
}
public String getQueryString()
{
return originalQueryString;
}
/**
* This class converts an interator into an enumerator. This is done
* because we have the parameters as a Map (JDK 1.2 style), but for some
* weird reason the HttpServletRequest interface returns an Enumeration
* from getParameterNames() (JDK1.0 style.) JDK apparently offers no way
* of simply changing between the new styles.
*/
class EnumIterator implements Enumeration
{
private Iterator iterator;
public EnumIterator(Iterator i)
{
iterator = i;
}
public boolean hasMoreElements()
{
return iterator.hasNext();
}
public Object nextElement()
{
return iterator.next();
}
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.jsptag;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.dspace.app.util.MetadataExposure;
import org.dspace.app.webui.util.StyleSelection;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.browse.BrowseException;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.authority.MetadataAuthorityManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.I18nUtil;
import org.dspace.core.PluginManager;
import org.dspace.core.Utils;
/**
* <P>
* JSP tag for displaying an item.
* </P>
* <P>
* The fields that are displayed can be configured in <code>dspace.cfg</code>
* using the <code>webui.itemdisplay.(style)</code> property. The form is
* </P>
*
* <PRE>
*
* <schema prefix>.<element>[.<qualifier>|.*][(date)|(link)], ...
*
* </PRE>
*
* <P>
* For example:
* </P>
*
* <PRE>
*
* dc.title = Dublin Core element 'title' (unqualified)
* dc.title.alternative = DC element 'title', qualifier 'alternative'
* dc.title.* = All fields with Dublin Core element 'title' (any or no qualifier)
* dc.identifier.uri(link) = DC identifier.uri, render as a link
* dc.date.issued(date) = DC date.issued, render as a date
* dc.identifier.doi(doi) = DC identifier.doi, render as link to http://dx.doi.org
* dc.identifier.hdl(handle) = DC identifier.hanlde, render as link to http://hdl.handle.net
* dc.relation.isPartOf(resolver) = DC relation.isPartOf, render as link to the base url of the resolver
* according to the specified urn in the metadata value (doi:xxxx, hdl:xxxxx,
* urn:issn:xxxx, etc.)
*
* </PRE>
*
* <P>
* When using "resolver" in webui.itemdisplay to render identifiers as resolvable
* links, the base URL is taken from <code>webui.resolver.<n>.baseurl</code>
* where <code>webui.resolver.<n>.urn</code> matches the urn specified in the metadata value.
* The value is appended to the "baseurl" as is, so the baseurl need to end with slash almost in any case.
* If no urn is specified in the value it will be displayed as simple text.
*
* <PRE>
*
* webui.resolver.1.urn = doi
* webui.resolver.1.baseurl = http://dx.doi.org/
* webui.resolver.2.urn = hdl
* webui.resolver.2.baseurl = http://hdl.handle.net/
*
* </PRE>
*
* For the doi and hdl urn defaults values are provided, respectively http://dx.doi.org/ and
* http://hdl.handle.net/ are used.<br>
*
* If a metadata value with style: "doi", "handle" or "resolver" matches a URL
* already, it is simply rendered as a link with no other manipulation.
* </P>
*
* <PRE>
*
* <P>
* If an item has no value for a particular field, it won't be displayed. The
* name of the field for display will be drawn from the current UI dictionary,
* using the key:
* </P>
*
* <PRE>
*
* "metadata.<style.>.<field>"
*
* e.g. "metadata.thesis.dc.title" "metadata.thesis.dc.contributor.*"
* "metadata.thesis.dc.date.issued"
*
*
* if this key is not found will be used the more general one
*
* "metadata.<field>"
*
* e.g. "metadata.dc.title" "metadata.dc.contributor.*"
* "metadata.dc.date.issued"
*
* </PRE>
*
* <P>
* You need to specify which strategy use for select the style for an item.
* </P>
*
* <PRE>
*
* plugin.single.org.dspace.app.webui.util.StyleSelection = \
* org.dspace.app.webui.util.CollectionStyleSelection
* #org.dspace.app.webui.util.MetadataStyleSelection
*
* </PRE>
*
* <P>
* With the Collection strategy you can also specify which collections use which
* views.
* </P>
*
* <PRE>
*
* webui.itemdisplay.<style>.collections = <collection handle>, ...
*
* </PRE>
*
* <P>
* FIXME: This should be more database-driven
* </P>
*
* <PRE>
*
* webui.itemdisplay.thesis.collections = 123456789/24, 123456789/35
*
* </PRE>
*
* <P>
* With the Metadata strategy you MUST specify which metadata use as name of the
* style.
* </P>
*
* <PRE>
*
* webui.itemdisplay.metadata-style = schema.element[.qualifier|.*]
*
* e.g. "dc.type"
*
* </PRE>
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class ItemTag extends TagSupport
{
private static final String HANDLE_DEFAULT_BASEURL = "http://hdl.handle.net/";
private static final String DOI_DEFAULT_BASEURL = "http://dx.doi.org/";
/** Item to display */
private transient Item item;
/** Collections this item appears in */
private transient Collection[] collections;
/** The style to use - "default" or "full" */
private String style;
/** Whether to show preview thumbs on the item page */
private boolean showThumbs;
/** Default DC fields to display, in absence of configuration */
private static String defaultFields = "dc.title, dc.title.alternative, dc.contributor.*, dc.subject, dc.date.issued(date), dc.publisher, dc.identifier.citation, dc.relation.ispartofseries, dc.description.abstract, dc.description, dc.identifier.govdoc, dc.identifier.uri(link), dc.identifier.isbn, dc.identifier.issn, dc.identifier.ismn, dc.identifier";
/** log4j logger */
private static Logger log = Logger.getLogger(ItemTag.class);
private StyleSelection styleSelection = (StyleSelection) PluginManager.getSinglePlugin(StyleSelection.class);
/** Hashmap of linked metadata to browse, from dspace.cfg */
private static Map<String,String> linkedMetadata;
/** Hashmap of urn base url resolver, from dspace.cfg */
private static Map<String,String> urn2baseurl;
/** regex pattern to capture the style of a field, ie <code>schema.element.qualifier(style)</code> */
private Pattern fieldStylePatter = Pattern.compile(".*\\((.*)\\)");
private static final long serialVersionUID = -3841266490729417240L;
static {
int i;
linkedMetadata = new HashMap<String, String>();
String linkMetadata;
i = 1;
do {
linkMetadata = ConfigurationManager.getProperty("webui.browse.link."+i);
if (linkMetadata != null) {
String[] linkedMetadataSplit = linkMetadata.split(":");
String indexName = linkedMetadataSplit[0].trim();
String metadataName = linkedMetadataSplit[1].trim();
linkedMetadata.put(indexName, metadataName);
}
i++;
} while (linkMetadata != null);
urn2baseurl = new HashMap<String, String>();
String urn;
i = 1;
do {
urn = ConfigurationManager.getProperty("webui.resolver."+i+".urn");
if (urn != null) {
String baseurl = ConfigurationManager.getProperty("webui.resolver."+i+".baseurl");
if (baseurl != null){
urn2baseurl.put(urn, baseurl);
} else {
log.warn("Wrong webui.resolver configuration, you need to specify both webui.resolver.<n>.urn and webui.resolver.<n>.baseurl: missing baseurl for n = "+i);
}
}
i++;
} while (urn != null);
// Set sensible default if no config is found for doi & handle
if (!urn2baseurl.containsKey("doi")){
urn2baseurl.put("doi",DOI_DEFAULT_BASEURL);
}
if (!urn2baseurl.containsKey("hdl")){
urn2baseurl.put("hdl",HANDLE_DEFAULT_BASEURL);
}
}
public ItemTag()
{
super();
getThumbSettings();
}
public int doStartTag() throws JspException
{
try
{
if (style == null || style.equals(""))
{
style = styleSelection.getStyleForItem(item);
}
if (style.equals("full"))
{
renderFull();
}
else
{
render();
}
}
catch (SQLException sqle)
{
throw new JspException(sqle);
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
/**
* Get the item this tag should display
*
* @return the item
*/
public Item getItem()
{
return item;
}
/**
* Set the item this tag should display
*
* @param itemIn
* the item to display
*/
public void setItem(Item itemIn)
{
item = itemIn;
}
/**
* Get the collections this item is in
*
* @return the collections
*/
public Collection[] getCollections()
{
return (Collection[]) ArrayUtils.clone(collections);
}
/**
* Set the collections this item is in
*
* @param collectionsIn
* the collections
*/
public void setCollections(Collection[] collectionsIn)
{
collections = (Collection[]) ArrayUtils.clone(collectionsIn);
}
/**
* Get the style this tag should display
*
* @return the style
*/
public String getStyle()
{
return style;
}
/**
* Set the style this tag should display
*
* @param styleIn
* the Style to display
*/
public void setStyle(String styleIn)
{
style = styleIn;
}
public void release()
{
style = "default";
item = null;
collections = null;
}
/**
* Render an item in the given style
*/
private void render() throws IOException, SQLException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
Context context = UIUtil.obtainContext(request);
String configLine = styleSelection.getConfigurationForStyle(style);
if (configLine == null)
{
configLine = defaultFields;
}
out.println("<center><table class=\"itemDisplayTable\">");
/*
* Break down the configuration into fields and display them
*
* FIXME?: it may be more efficient to do some processing once, perhaps
* to a more efficient intermediate class, but then it would become more
* difficult to reload the configuration "on the fly".
*/
StringTokenizer st = new StringTokenizer(configLine, ",");
while (st.hasMoreTokens())
{
String field = st.nextToken().trim();
boolean isDate = false;
boolean isLink = false;
boolean isResolver = false;
String style = null;
Matcher fieldStyleMatcher = fieldStylePatter.matcher(field);
if (fieldStyleMatcher.matches()){
style = fieldStyleMatcher.group(1);
}
String browseIndex;
try
{
browseIndex = getBrowseField(field);
}
catch (BrowseException e)
{
log.error(e);
browseIndex = null;
}
// Find out if the field should rendered with a particular style
if (style != null)
{
isDate = style.equals("date");
isLink = style.equals("link");
isResolver = style.equals("resolver") || urn2baseurl.keySet().contains(style);
field = field.replaceAll("\\("+style+"\\)", "");
}
// Get the separate schema + element + qualifier
String[] eq = field.split("\\.");
String schema = eq[0];
String element = eq[1];
String qualifier = null;
if (eq.length > 2 && eq[2].equals("*"))
{
qualifier = Item.ANY;
}
else if (eq.length > 2)
{
qualifier = eq[2];
}
// check for hidden field, even if it's configured..
if (MetadataExposure.isHidden(context, schema, element, qualifier))
{
continue;
}
// FIXME: Still need to fix for metadata language?
DCValue[] values = item.getMetadata(schema, element, qualifier, Item.ANY);
if (values.length > 0)
{
out.print("<tr><td class=\"metadataFieldLabel\">");
String label = null;
try
{
label = I18nUtil.getMessage("metadata."
+ (style != null ? style + "." : "") + field,
context);
}
catch (MissingResourceException e)
{
// if there is not a specific translation for the style we
// use the default one
label = LocaleSupport.getLocalizedMessage(pageContext,
"metadata." + field);
}
out.print(label);
out.print(": </td><td class=\"metadataFieldValue\">");
for (int j = 0; j < values.length; j++)
{
if (values[j] != null && values[j].value != null)
{
if (j > 0)
{
out.print("<br />");
}
if (isLink)
{
out.print("<a href=\"" + values[j].value + "\">"
+ Utils.addEntities(values[j].value) + "</a>");
}
else if (isDate)
{
DCDate dd = new DCDate(values[j].value);
// Parse the date
out.print(UIUtil.displayDate(dd, false, false, (HttpServletRequest)pageContext.getRequest()));
}
else if (isResolver)
{
String value = values[j].value;
if (value.startsWith("http://")
|| value.startsWith("https://")
|| value.startsWith("ftp://")
|| value.startsWith("ftps://"))
{
// Already a URL, print as if it was a regular link
out.print("<a href=\"" + value + "\">"
+ Utils.addEntities(value) + "</a>");
}
else
{
String foundUrn = null;
if (!style.equals("resolver"))
{
foundUrn = style;
}
else
{
for (String checkUrn : urn2baseurl.keySet())
{
if (value.startsWith(checkUrn))
{
foundUrn = checkUrn;
}
}
}
if (foundUrn != null)
{
if (value.startsWith(foundUrn + ":"))
{
value = value.substring(foundUrn.length()+1);
}
String url = urn2baseurl.get(foundUrn);
out.print("<a href=\"" + url
+ value + "\">"
+ Utils.addEntities(values[j].value)
+ "</a>");
}
else
{
out.print(value);
}
}
}
else if (browseIndex != null)
{
String argument, value;
if ( values[j].authority != null &&
values[j].confidence >= MetadataAuthorityManager.getManager()
.getMinConfidence( values[j].schema, values[j].element, values[j].qualifier))
{
argument = "authority";
value = values[j].authority;
}
else
{
argument = "value";
value = values[j].value;
}
out.print("<a class=\"" + ("authority".equals(argument)?"authority ":"") + browseIndex + "\""
+ "href=\"" + request.getContextPath() + "/browse?type=" + browseIndex + "&" + argument + "="
+ URLEncoder.encode(value, "UTF-8") + "\">" + Utils.addEntities(values[j].value)
+ "</a>");
}
else
{
out.print(Utils.addEntities(values[j].value));
}
}
}
out.println("</td></tr>");
}
}
listCollections();
out.println("</table></center><br/>");
listBitstreams();
if (ConfigurationManager
.getBooleanProperty("webui.licence_bundle.show"))
{
out.println("<br/><br/>");
showLicence();
}
}
/**
* Render full item record
*/
private void renderFull() throws IOException, SQLException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
Context context = UIUtil.obtainContext(request);
// Get all the metadata
DCValue[] values = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
out.println("<p align=\"center\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.full") + "</p>");
// Three column table - DC field, value, language
out.println("<center><table class=\"itemDisplayTable\">");
out.println("<tr><th id=\"s1\" class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.dcfield")
+ "</th><th id=\"s2\" class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.value")
+ "</th><th id=\"s3\" class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.lang")
+ "</th></tr>");
for (int i = 0; i < values.length; i++)
{
if (!MetadataExposure.isHidden(context, values[i].schema, values[i].element, values[i].qualifier))
{
out.print("<tr><td headers=\"s1\" class=\"metadataFieldLabel\">");
out.print(values[i].schema);
out.print("." + values[i].element);
if (values[i].qualifier != null)
{
out.print("." + values[i].qualifier);
}
out.print("</td><td headers=\"s2\" class=\"metadataFieldValue\">");
out.print(Utils.addEntities(values[i].value));
out.print("</td><td headers=\"s3\" class=\"metadataFieldValue\">");
if (values[i].language == null)
{
out.print("-");
}
else
{
out.print(values[i].language);
}
out.println("</td></tr>");
}
}
listCollections();
out.println("</table></center><br/>");
listBitstreams();
if (ConfigurationManager
.getBooleanProperty("webui.licence_bundle.show"))
{
out.println("<br/><br/>");
showLicence();
}
}
/**
* List links to collections if information is available
*/
private void listCollections() throws IOException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
if (collections != null)
{
out.print("<tr><td class=\"metadataFieldLabel\">");
if (item.getHandle()==null) // assume workspace item
{
out.print(LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.submitted"));
}
else
{
out.print(LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.appears"));
}
out.print("</td><td class=\"metadataFieldValue\">");
for (int i = 0; i < collections.length; i++)
{
out.print("<a href=\"");
out.print(request.getContextPath());
out.print("/handle/");
out.print(collections[i].getHandle());
out.print("\">");
out.print(collections[i].getMetadata("name"));
out.print("</a><br/>");
}
out.println("</td></tr>");
}
}
/**
* List bitstreams in the item
*/
private void listBitstreams() throws IOException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
out.print("<table align=\"center\" class=\"miscTable\"><tr>");
out.println("<td class=\"evenRowEvenCol\"><p><strong>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.files")
+ "</strong></p>");
try
{
Bundle[] bundles = item.getBundles("ORIGINAL");
boolean filesExist = false;
for (Bundle bnd : bundles)
{
filesExist = bnd.getBitstreams().length > 0;
if (filesExist)
{
break;
}
}
// if user already has uploaded at least one file
if (!filesExist)
{
out.println("<p>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.files.no")
+ "</p>");
}
else
{
boolean html = false;
String handle = item.getHandle();
Bitstream primaryBitstream = null;
Bundle[] bunds = item.getBundles("ORIGINAL");
Bundle[] thumbs = item.getBundles("THUMBNAIL");
// if item contains multiple bitstreams, display bitstream
// description
boolean multiFile = false;
Bundle[] allBundles = item.getBundles();
for (int i = 0, filecount = 0; (i < allBundles.length)
&& !multiFile; i++)
{
filecount += allBundles[i].getBitstreams().length;
multiFile = (filecount > 1);
}
// check if primary bitstream is html
if (bunds[0] != null)
{
Bitstream[] bits = bunds[0].getBitstreams();
for (int i = 0; (i < bits.length) && !html; i++)
{
if (bits[i].getID() == bunds[0].getPrimaryBitstreamID())
{
html = bits[i].getFormat().getMIMEType().equals(
"text/html");
primaryBitstream = bits[i];
}
}
}
out
.println("<table cellpadding=\"6\"><tr><th id=\"t1\" class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.file")
+ "</th>");
if (multiFile)
{
out
.println("<th id=\"t2\" class=\"standard\">"
+ LocaleSupport
.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.description")
+ "</th>");
}
out.println("<th id=\"t3\" class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.filesize")
+ "</th><th id=\"t4\" class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.fileformat")
+ "</th></tr>");
// if primary bitstream is html, display a link for only that one to
// HTMLServlet
if (html)
{
// If no real Handle yet (e.g. because Item is in workflow)
// we use the 'fake' Handle db-id/1234 where 1234 is the
// database ID of the item.
if (handle == null)
{
handle = "db-id/" + item.getID();
}
out.print("<tr><td headers=\"t1\" class=\"standard\">");
out.print("<a target=\"_blank\" href=\"");
out.print(request.getContextPath());
out.print("/html/");
out.print(handle + "/");
out
.print(UIUtil.encodeBitstreamName(primaryBitstream
.getName(), Constants.DEFAULT_ENCODING));
out.print("\">");
out.print(primaryBitstream.getName());
out.print("</a>");
if (multiFile)
{
out.print("</td><td headers=\"t2\" class=\"standard\">");
String desc = primaryBitstream.getDescription();
out.print((desc != null) ? desc : "");
}
out.print("</td><td headers=\"t3\" class=\"standard\">");
out.print(UIUtil.formatFileSize(primaryBitstream.getSize()));
out.print("</td><td headers=\"t4\" class=\"standard\">");
out.print(primaryBitstream.getFormatDescription());
out
.print("</td><td class=\"standard\"><a target=\"_blank\" href=\"");
out.print(request.getContextPath());
out.print("/html/");
out.print(handle + "/");
out
.print(UIUtil.encodeBitstreamName(primaryBitstream
.getName(), Constants.DEFAULT_ENCODING));
out.print("\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.view")
+ "</a></td></tr>");
}
else
{
for (int i = 0; i < bundles.length; i++)
{
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int k = 0; k < bitstreams.length; k++)
{
// Skip internal types
if (!bitstreams[k].getFormat().isInternal())
{
// Work out what the bitstream link should be
// (persistent
// ID if item has Handle)
String bsLink = "<a target=\"_blank\" href=\""
+ request.getContextPath();
if ((handle != null)
&& (bitstreams[k].getSequenceID() > 0))
{
bsLink = bsLink + "/bitstream/"
+ item.getHandle() + "/"
+ bitstreams[k].getSequenceID() + "/";
}
else
{
bsLink = bsLink + "/retrieve/"
+ bitstreams[k].getID() + "/";
}
bsLink = bsLink
+ UIUtil.encodeBitstreamName(bitstreams[k]
.getName(),
Constants.DEFAULT_ENCODING) + "\">";
out
.print("<tr><td headers=\"t1\" class=\"standard\">");
out.print(bsLink);
out.print(bitstreams[k].getName());
out.print("</a>");
if (multiFile)
{
out
.print("</td><td headers=\"t2\" class=\"standard\">");
String desc = bitstreams[k].getDescription();
out.print((desc != null) ? desc : "");
}
out
.print("</td><td headers=\"t3\" class=\"standard\">");
out.print(UIUtil.formatFileSize(bitstreams[k].getSize()));
out
.print("</td><td headers=\"t4\" class=\"standard\">");
out.print(bitstreams[k].getFormatDescription());
out
.print("</td><td class=\"standard\" align=\"center\">");
// is there a thumbnail bundle?
if ((thumbs.length > 0) && showThumbs)
{
String tName = bitstreams[k].getName() + ".jpg";
String tAltText = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.thumbnail");
Bitstream tb = thumbs[0]
. getBitstreamByName(tName);
if (tb != null)
{
String myPath = request.getContextPath()
+ "/retrieve/"
+ tb.getID()
+ "/"
+ UIUtil.encodeBitstreamName(tb
.getName(),
Constants.DEFAULT_ENCODING);
out.print(bsLink);
out.print("<img src=\"" + myPath + "\" ");
out.print("alt=\"" + tAltText
+ "\" /></a><br />");
}
}
out
.print(bsLink
+ LocaleSupport
.getLocalizedMessage(
pageContext,
"org.dspace.app.webui.jsptag.ItemTag.view")
+ "</a></td></tr>");
}
}
}
}
out.println("</table>");
}
}
catch(SQLException sqle)
{
throw new IOException(sqle.getMessage(), sqle);
}
out.println("</td></tr></table>");
}
private void getThumbSettings()
{
showThumbs = ConfigurationManager
.getBooleanProperty("webui.item.thumbnail.show");
}
/**
* Link to the item licence
*/
private void showLicence() throws IOException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
Bundle[] bundles = null;
try
{
bundles = item.getBundles("LICENSE");
}
catch(SQLException sqle)
{
throw new IOException(sqle.getMessage(), sqle);
}
out.println("<table align=\"center\" class=\"attentionTable\"><tr>");
out.println("<td class=\"attentionCell\"><p><strong>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.itemprotected")
+ "</strong></p>");
for (int i = 0; i < bundles.length; i++)
{
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int k = 0; k < bitstreams.length; k++)
{
out.print("<div align=\"center\" class=\"standard\">");
out.print("<strong><a target=\"_blank\" href=\"");
out.print(request.getContextPath());
out.print("/retrieve/");
out.print(bitstreams[k].getID() + "/");
out.print(UIUtil.encodeBitstreamName(bitstreams[k].getName(),
Constants.DEFAULT_ENCODING));
out
.print("\">"
+ LocaleSupport
.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.viewlicence")
+ "</a></strong></div>");
}
}
out.println("</td></tr></table>");
}
/**
* Return the browse index related to the field. <code>null</code> if the field is not a browse field
* (look for <cod>webui.browse.link.<n></code> in dspace.cfg)
*
* @param field
* @return the browse index related to the field. Null otherwise
* @throws BrowseException
*/
private String getBrowseField(String field) throws BrowseException
{
for (String indexName : linkedMetadata.keySet())
{
StringTokenizer bw_dcf = new StringTokenizer(linkedMetadata.get(indexName), ".");
String[] bw_tokens = { "", "", "" };
int i = 0;
while(bw_dcf.hasMoreTokens())
{
bw_tokens[i] = bw_dcf.nextToken().toLowerCase().trim();
i++;
}
String bw_schema = bw_tokens[0];
String bw_element = bw_tokens[1];
String bw_qualifier = bw_tokens[2];
StringTokenizer dcf = new StringTokenizer(field, ".");
String[] tokens = { "", "", "" };
int j = 0;
while(dcf.hasMoreTokens())
{
tokens[j] = dcf.nextToken().toLowerCase().trim();
j++;
}
String schema = tokens[0];
String element = tokens[1];
String qualifier = tokens[2];
if (schema.equals(bw_schema) // schema match
&& element.equals(bw_element) // element match
&& (
(bw_qualifier != null) && ((qualifier != null && qualifier.equals(bw_qualifier)) // both not null and equals
|| bw_qualifier.equals("*")) // browse link with jolly
|| (bw_qualifier == null && qualifier == null)) // both null
)
{
return indexName;
}
}
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.webui.jsptag;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.lang.ArrayUtils;
import org.dspace.eperson.EPerson;
/**
* <p>
* Tag for producing an e-person select widget in a form. Somewhat analogous to
* the HTML SELECT element. An input field is produced with a button which pops
* up a window from which e-people can be selected. Selected e-epeople are added
* to the field in the form. If the selector is for multiple e-people, a 'remove
* selected from list' button is also added.
* </p>
*
* <p>
* On any form that has a selecteperson tag (only one allowed per page), you
* need to include the following Javascript code on all of the submit buttons,
* to ensure that the e-people IDs are posted and that the popup window is
* closed:
* </p>
*
* <p>
* <code>onclick="javascript:finishEPerson();"</code>
* </p>
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class SelectEPersonTag extends TagSupport
{
/** Multiple e-people? */
private boolean multiple;
/** Which eperson/epeople are initially in the list? */
private transient EPerson[] epeople;
private static final long serialVersionUID = -7323789442034590853L;
public SelectEPersonTag()
{
super();
}
/**
* Setter for multiple attribute
*
* @param s
* attribute from JSP
*/
public void setMultiple(String s)
{
if ((s != null)
&& (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")))
{
multiple = true;
}
else
{
multiple = false;
}
}
/**
* Setter for e-people in list
*
* @param e
* attribute from JSP
*/
public void setSelected(Object e)
{
if (e instanceof EPerson)
{
epeople = new EPerson[1];
epeople[0] = (EPerson) e;
}
else if (e instanceof EPerson[])
{
epeople = (EPerson[])ArrayUtils.clone((EPerson[])e);
}
}
public void release()
{
multiple = false;
epeople = null;
}
public int doStartTag() throws JspException
{
try
{
JspWriter out = pageContext.getOut();
HttpServletRequest req = (HttpServletRequest) pageContext
.getRequest();
out.print("<table><tr><td colspan=\"2\" align=\"center\"><select multiple=\"multiple\" name=\"eperson_id\" size=\"");
out.print(multiple ? "10" : "1");
out.println("\">");
// ensure that if no eperson is selected that a blank option is displayed - xhtml compliance
if (epeople == null || epeople.length == 0)
{
out.print("<option value=\"\"> </option>");
}
if (epeople != null)
{
for (int i = 0; i < epeople.length; i++)
{
out.print("<option value=\"" + epeople[i].getID() + "\">");
out.print(epeople[i].getFullName() + " ("
+ epeople[i].getEmail() + ")");
out.println("</option>");
}
}
// add blank option value if no person selected to ensure that code is xhtml compliant
//out.print("<option/>");
out.print("</select></td>");
if (multiple)
{
out.print("</tr><tr><td width=\"50%\" align=\"center\">");
}
else
{
out.print("<td>");
}
String p = (multiple ?
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectEPersonTag.selectPeople")
: LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectEPersonTag.selectPerson") );
out.print("<input type=\"button\" value=\"" + p
+ "\" onclick=\"javascript:popup_window('"
+ req.getContextPath() + "/tools/eperson-list?multiple="
+ multiple + "', 'eperson_popup');\" />");
if (multiple)
{
out.print("</td><td width=\"50%\" align=\"center\">");
out.print("<input type=\"button\" value=\""
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectEPersonTag.removeSelected")
+ "\" onclick=\"javascript:removeSelected(window.document.epersongroup.eperson_id);\"/>");
}
out.println("</td></tr></table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
}
| 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.webui.jsptag;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Simple include tag that can include locally-modified JSPs
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class IncludeTag extends TagSupport
{
/** Path of default JSP version */
private String page;
/**
* Get the JSP to display (default version)
*
* @return the page to display
*/
public String getPage()
{
return page;
}
/**
* Set the JSP to display (default version)
*
* @param s
* the page to display
*/
public void setPage(String s)
{
page = s;
}
public int doStartTag() throws JspException
{
try
{
pageContext.include(page);
}
catch (IOException ie)
{
throw new JspException(ie);
}
catch (ServletException se)
{
throw new JspException(se);
}
return SKIP_BODY;
}
}
| 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.webui.jsptag;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.lang.ArrayUtils;
import org.dspace.content.Community;
/**
* Tag for display a list of communities
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class CommunityListTag extends TagSupport
{
/** Communities to display */
private transient Community[] communities;
private static final long serialVersionUID = 5788338729470292501L;
public CommunityListTag()
{
super();
}
public int doStartTag() throws JspException
{
JspWriter out = pageContext.getOut();
try
{
out.println("<table align=\"center\" class=\"miscTable\" title=\"Community List\">");
// Write column headings
out.print("<tr><th id=\"t5\" class=\"oddRowOddCol\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.CommunityListTag.communityName")
+ "</th></tr>");
// Row: toggles between Odd and Even
String row = "even";
for (int i = 0; i < communities.length; i++)
{
// name
String name = communities[i].getMetadata("name");
// first and only column is 'name'
out.print("<tr><td headers=\"t5\" class=\"" + row + "RowEvenCol\">");
out.print("<a href=\"");
HttpServletRequest hrq = (HttpServletRequest) pageContext
.getRequest();
out.print(hrq.getContextPath() + "/handle/");
out.print(communities[i].getHandle());
out.print("\">");
out.print(name);
out.print("</a>");
out.println("</td></tr>");
row = (row.equals("odd") ? "even" : "odd");
}
out.println("</table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
/**
* Get the communities to list
*
* @return the communities
*/
public Community[] getCommunities()
{
return (Community[]) ArrayUtils.clone(communities);
}
/**
* Set the communities to list
*
* @param communitiesIn
* the communities
*/
public void setCommunities(Community[] communitiesIn)
{
communities = (Community[]) ArrayUtils.clone(communitiesIn);
}
public void release()
{
communities = 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.webui.jsptag;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.CrossLinks;
import org.dspace.content.Bitstream;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.Thumbnail;
import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.Utils;
import org.dspace.sort.SortOption;
import org.dspace.storage.bitstore.BitstreamStorageManager;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import org.dspace.content.authority.MetadataAuthorityManager;
/**
* Tag for display a list of items
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class ItemListTag extends TagSupport
{
private static Logger log = Logger.getLogger(ItemListTag.class);
/** Items to display */
private transient Item[] items;
/** Row to highlight, -1 for no row */
private int highlightRow = -1;
/** Column to emphasise - null, "title" or "date" */
private String emphColumn;
/** Config value of thumbnail view toggle */
private static boolean showThumbs;
/** Config browse/search width and height */
private static int thumbItemListMaxWidth;
private static int thumbItemListMaxHeight;
/** Config browse/search thumbnail link behaviour */
private static boolean linkToBitstream = false;
/** Config to include an edit link */
private boolean linkToEdit = false;
/** Config to disable cross links */
private boolean disableCrossLinks = false;
/** The default fields to be displayed when listing items */
private static final String DEFAULT_LIST_FIELDS;
/** The default widths for the columns */
private static final String DEFAULT_LIST_WIDTHS;
/** The default field which is bound to the browse by date */
private static String dateField = "dc.date.issued";
/** The default field which is bound to the browse by title */
private static String titleField = "dc.title";
private static String authorField = "dc.contributor.*";
private int authorLimit = -1;
private transient SortOption sortOption = null;
private static final long serialVersionUID = 348762897199116432L;
static
{
getThumbSettings();
if (showThumbs)
{
DEFAULT_LIST_FIELDS = "thumbnail, dc.date.issued(date), dc.title, dc.contributor.*";
DEFAULT_LIST_WIDTHS = "*, 130, 60%, 40%";
}
else
{
DEFAULT_LIST_FIELDS = "dc.date.issued(date), dc.title, dc.contributor.*";
DEFAULT_LIST_WIDTHS = "130, 60%, 40%";
}
// get the date and title fields
String dateLine = ConfigurationManager.getProperty("webui.browse.index.date");
if (dateLine != null)
{
dateField = dateLine;
}
String titleLine = ConfigurationManager.getProperty("webui.browse.index.title");
if (titleLine != null)
{
titleField = titleLine;
}
String authorLine = ConfigurationManager.getProperty("webui.browse.author-field");
if (authorLine != null)
{
authorField = authorLine;
}
}
public ItemListTag()
{
super();
}
public int doStartTag() throws JspException
{
JspWriter out = pageContext.getOut();
HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest();
boolean emphasiseDate = false;
boolean emphasiseTitle = false;
if (emphColumn != null)
{
emphasiseDate = emphColumn.equalsIgnoreCase("date");
emphasiseTitle = emphColumn.equalsIgnoreCase("title");
}
// get the elements to display
String configLine = null;
String widthLine = null;
if (sortOption != null)
{
if (configLine == null)
{
configLine = ConfigurationManager.getProperty("webui.itemlist.sort." + sortOption.getName() + ".columns");
widthLine = ConfigurationManager.getProperty("webui.itemlist.sort." + sortOption.getName() + ".widths");
}
if (configLine == null)
{
configLine = ConfigurationManager.getProperty("webui.itemlist." + sortOption.getName() + ".columns");
widthLine = ConfigurationManager.getProperty("webui.itemlist." + sortOption.getName() + ".widths");
}
}
if (configLine == null)
{
configLine = ConfigurationManager.getProperty("webui.itemlist.columns");
widthLine = ConfigurationManager.getProperty("webui.itemlist.widths");
}
// Have we read a field configration from dspace.cfg?
if (configLine != null)
{
// If thumbnails are disabled, strip out any thumbnail column from the configuration
if (!showThumbs && configLine.contains("thumbnail"))
{
// Ensure we haven't got any nulls
configLine = configLine == null ? "" : configLine;
widthLine = widthLine == null ? "" : widthLine;
// Tokenize the field and width lines
StringTokenizer llt = new StringTokenizer(configLine, ",");
StringTokenizer wlt = new StringTokenizer(widthLine, ",");
StringBuilder newLLine = new StringBuilder();
StringBuilder newWLine = new StringBuilder();
while (llt.hasMoreTokens() || wlt.hasMoreTokens())
{
String listTok = llt.hasMoreTokens() ? llt.nextToken() : null;
String widthTok = wlt.hasMoreTokens() ? wlt.nextToken() : null;
// Only use the Field and Width tokens, if the field isn't 'thumbnail'
if (listTok == null || !listTok.trim().equals("thumbnail"))
{
if (listTok != null)
{
if (newLLine.length() > 0)
{
newLLine.append(",");
}
newLLine.append(listTok);
}
if (widthTok != null)
{
if (newWLine.length() > 0)
{
newWLine.append(",");
}
newWLine.append(widthTok);
}
}
}
// Use the newly built configuration file
configLine = newLLine.toString();
widthLine = newWLine.toString();
}
}
else
{
configLine = DEFAULT_LIST_FIELDS;
widthLine = DEFAULT_LIST_WIDTHS;
}
// Arrays used to hold the information we will require when outputting each row
String[] fieldArr = configLine == null ? new String[0] : configLine.split("\\s*,\\s*");
String[] widthArr = widthLine == null ? new String[0] : widthLine.split("\\s*,\\s*");
boolean isDate[] = new boolean[fieldArr.length];
boolean emph[] = new boolean[fieldArr.length];
boolean isAuthor[] = new boolean[fieldArr.length];
boolean viewFull[] = new boolean[fieldArr.length];
String[] browseType = new String[fieldArr.length];
String[] cOddOrEven = new String[fieldArr.length];
try
{
// Get the interlinking configuration too
CrossLinks cl = new CrossLinks();
// Get a width for the table
String tablewidth = ConfigurationManager.getProperty("webui.itemlist.tablewidth");
// If we have column widths, output a fixed layout table - faster for browsers to render
// but not if we have to add an 'edit item' button - we can't know how big it will be
if (widthArr.length > 0 && widthArr.length == fieldArr.length && !linkToEdit)
{
// If the table width has been specified, we can make this a fixed layout
if (!StringUtils.isEmpty(tablewidth))
{
out.println("<table style=\"width: " + tablewidth + "; table-layout: fixed;\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
}
else
{
// Otherwise, don't constrain the width
out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
}
// Output the known column widths
out.print("<colgroup>");
for (int w = 0; w < widthArr.length; w++)
{
out.print("<col width=\"");
// For a thumbnail column of width '*', use the configured max width for thumbnails
if (fieldArr[w].equals("thumbnail") && widthArr[w].equals("*"))
{
out.print(thumbItemListMaxWidth);
}
else
{
out.print(StringUtils.isEmpty(widthArr[w]) ? "*" : widthArr[w]);
}
out.print("\" />");
}
out.println("</colgroup>");
}
else if (!StringUtils.isEmpty(tablewidth))
{
out.println("<table width=\"" + tablewidth + "\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
}
else
{
out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
}
// Output the table headers
out.println("<tr>");
for (int colIdx = 0; colIdx < fieldArr.length; colIdx++)
{
String field = fieldArr[colIdx].toLowerCase().trim();
cOddOrEven[colIdx] = (((colIdx + 1) % 2) == 0 ? "Odd" : "Even");
// find out if the field is a date
if (field.indexOf("date") > 0)
{
field = field.replaceAll("\\(date\\)", "");
isDate[colIdx] = true;
}
// Cache any modifications to field
fieldArr[colIdx] = field;
// find out if this is the author column
if (field.equals(authorField))
{
isAuthor[colIdx] = true;
}
// find out if this field needs to link out to other browse views
if (cl.hasLink(field))
{
browseType[colIdx] = cl.getLinkType(field);
viewFull[colIdx] = BrowseIndex.getBrowseIndex(browseType[colIdx]).isItemIndex();
}
// find out if we are emphasising this field
if (field.equals(emphColumn))
{
emph[colIdx] = true;
}
else if ((field.equals(dateField) && emphasiseDate) ||
(field.equals(titleField) && emphasiseTitle))
{
emph[colIdx] = true;
}
// prepare the strings for the header
String id = "t" + Integer.toString(colIdx + 1);
String css = "oddRow" + cOddOrEven[colIdx] + "Col";
String message = "itemlist." + field;
// output the header
out.print("<th id=\"" + id + "\" class=\"" + css + "\">"
+ (emph[colIdx] ? "<strong>" : "")
+ LocaleSupport.getLocalizedMessage(pageContext, message)
+ (emph[colIdx] ? "</strong>" : "") + "</th>");
}
if (linkToEdit)
{
String id = "t" + Integer.toString(cOddOrEven.length + 1);
String css = "oddRow" + cOddOrEven[cOddOrEven.length - 2] + "Col";
// output the header
out.print("<th id=\"" + id + "\" class=\"" + css + "\">"
+ (emph[emph.length - 2] ? "<strong>" : "")
+ " " //LocaleSupport.getLocalizedMessage(pageContext, message)
+ (emph[emph.length - 2] ? "</strong>" : "") + "</th>");
}
out.print("</tr>");
// now output each item row
for (int i = 0; i < items.length; i++)
{
// now prepare the XHTML frag for this division
out.print("<tr>");
String rOddOrEven;
if (i == highlightRow)
{
rOddOrEven = "highlight";
}
else
{
rOddOrEven = ((i & 1) == 1 ? "odd" : "even");
}
for (int colIdx = 0; colIdx < fieldArr.length; colIdx++)
{
String field = fieldArr[colIdx];
// get the schema and the element qualifier pair
// (Note, the schema is not used for anything yet)
// (second note, I hate this bit of code. There must be
// a much more elegant way of doing this. Tomcat has
// some weird problems with variations on this code that
// I tried, which is why it has ended up the way it is)
StringTokenizer eq = new StringTokenizer(field, ".");
String[] tokens = { "", "", "" };
int k = 0;
while(eq.hasMoreTokens())
{
tokens[k] = eq.nextToken().toLowerCase().trim();
k++;
}
String schema = tokens[0];
String element = tokens[1];
String qualifier = tokens[2];
// first get hold of the relevant metadata for this column
DCValue[] metadataArray;
if (qualifier.equals("*"))
{
metadataArray = items[i].getMetadata(schema, element, Item.ANY, Item.ANY);
}
else if (qualifier.equals(""))
{
metadataArray = items[i].getMetadata(schema, element, null, Item.ANY);
}
else
{
metadataArray = items[i].getMetadata(schema, element, qualifier, Item.ANY);
}
// save on a null check which would make the code untidy
if (metadataArray == null)
{
metadataArray = new DCValue[0];
}
// now prepare the content of the table division
String metadata = "-";
if (field.equals("thumbnail"))
{
metadata = getThumbMarkup(hrq, items[i]);
}
if (metadataArray.length > 0)
{
// format the date field correctly
if (isDate[colIdx])
{
DCDate dd = new DCDate(metadataArray[0].value);
metadata = Integer.toString(dd.getYear());//UIUtil.displayDate(dd, false, false, hrq);
}
// format the title field correctly for withdrawn items (ie. don't link)
else if (field.equals(titleField) && items[i].isWithdrawn())
{
metadata = Utils.addEntities(metadataArray[0].value);
}
// format the title field correctly
else if (field.equals(titleField))
{
metadata = "<a href=\"" + hrq.getContextPath() + "/handle/"
+ items[i].getHandle() + "\">"
+ Utils.addEntities(metadataArray[0].value)
+ "</a>";
}
// format all other fields
else
{
// limit the number of records if this is the author field (if
// -1, then the limit is the full list)
boolean truncated = false;
int loopLimit = metadataArray.length;
if (isAuthor[colIdx])
{
int fieldMax = (authorLimit > 0 ? authorLimit : metadataArray.length);
loopLimit = (fieldMax > metadataArray.length ? metadataArray.length : fieldMax);
truncated = (fieldMax < metadataArray.length);
log.debug("Limiting output of field " + field + " to " + Integer.toString(loopLimit) + " from an original " + Integer.toString(metadataArray.length));
}
StringBuilder sb = new StringBuilder();
for (int j = 0; j < loopLimit; j++)
{
String startLink = "";
String endLink = "";
if (!StringUtils.isEmpty(browseType[colIdx]) && !disableCrossLinks)
{
String argument;
String value;
if (metadataArray[j].authority != null &&
metadataArray[j].confidence >= MetadataAuthorityManager.getManager()
.getMinConfidence(metadataArray[j].schema, metadataArray[j].element, metadataArray[j].qualifier))
{
argument = "authority";
value = metadataArray[j].authority;
}
else
{
argument = "value";
value = metadataArray[j].value;
}
if (viewFull[colIdx])
{
argument = "vfocus";
}
startLink = "<a href=\"" + hrq.getContextPath() + "/browse?type=" + browseType[colIdx] + "&" +
argument + "=" + URLEncoder.encode(value,"UTF-8");
if (metadataArray[j].language != null)
{
startLink = startLink + "&" +
argument + "_lang=" + URLEncoder.encode(metadataArray[j].language, "UTF-8");
}
if ("authority".equals(argument))
{
startLink += "\" class=\"authority " +browseType[colIdx] + "\">";
}
else
{
startLink = startLink + "\">";
}
endLink = "</a>";
}
sb.append(startLink);
sb.append(Utils.addEntities(metadataArray[j].value));
sb.append(endLink);
if (j < (loopLimit - 1))
{
sb.append("; ");
}
}
if (truncated)
{
String etal = LocaleSupport.getLocalizedMessage(pageContext, "itemlist.et-al");
sb.append(", ").append(etal);
}
metadata = "<em>" + sb.toString() + "</em>";
}
}
// prepare extra special layout requirements for dates
String extras = "";
if (isDate[colIdx])
{
extras = "nowrap=\"nowrap\" align=\"right\"";
}
String id = "t" + Integer.toString(colIdx + 1);
out.print("<td headers=\"" + id + "\" class=\""
+ rOddOrEven + "Row" + cOddOrEven[colIdx] + "Col\" " + extras + ">"
+ (emph[colIdx] ? "<strong>" : "") + metadata + (emph[colIdx] ? "</strong>" : "")
+ "</td>");
}
// Add column for 'edit item' links
if (linkToEdit)
{
String id = "t" + Integer.toString(cOddOrEven.length + 1);
out.print("<td headers=\"" + id + "\" class=\""
+ rOddOrEven + "Row" + cOddOrEven[cOddOrEven.length - 2] + "Col\" nowrap>"
+ "<form method=\"get\" action=\"" + hrq.getContextPath() + "/tools/edit-item\">"
+ "<input type=\"hidden\" name=\"handle\" value=\"" + items[i].getHandle() + "\" />"
+ "<input type=\"submit\" value=\"Edit Item\" /></form>"
+ "</td>");
}
out.println("</tr>");
}
// close the table
out.println("</table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
catch (BrowseException e)
{
throw new JspException(e);
}
return SKIP_BODY;
}
public int getAuthorLimit()
{
return authorLimit;
}
public void setAuthorLimit(int al)
{
authorLimit = al;
}
public boolean getLinkToEdit()
{
return linkToEdit;
}
public void setLinkToEdit(boolean edit)
{
this.linkToEdit = edit;
}
public boolean getDisableCrossLinks()
{
return disableCrossLinks;
}
public void setDisableCrossLinks(boolean links)
{
this.disableCrossLinks = links;
}
public SortOption getSortOption()
{
return sortOption;
}
public void setSortOption(SortOption so)
{
sortOption = so;
}
/**
* Get the items to list
*
* @return the items
*/
public Item[] getItems()
{
return (Item[]) ArrayUtils.clone(items);
}
/**
* Set the items to list
*
* @param itemsIn
* the items
*/
public void setItems(Item[] itemsIn)
{
items = (Item[]) ArrayUtils.clone(itemsIn);
}
/**
* Get the row to highlight - null or -1 for no row
*
* @return the row to highlight
*/
public String getHighlightrow()
{
return String.valueOf(highlightRow);
}
/**
* Set the row to highlight
*
* @param highlightRowIn
* the row to highlight or -1 for no highlight
*/
public void setHighlightrow(String highlightRowIn)
{
if ((highlightRowIn == null) || highlightRowIn.equals(""))
{
highlightRow = -1;
}
else
{
try
{
highlightRow = Integer.parseInt(highlightRowIn);
}
catch (NumberFormatException nfe)
{
highlightRow = -1;
}
}
}
/**
* Get the column to emphasise - "title", "date" or null
*
* @return the column to emphasise
*/
public String getEmphcolumn()
{
return emphColumn;
}
/**
* Set the column to emphasise - "title", "date" or null
*
* @param emphColumnIn
* column to emphasise
*/
public void setEmphcolumn(String emphColumnIn)
{
emphColumn = emphColumnIn;
}
public void release()
{
highlightRow = -1;
emphColumn = null;
items = null;
}
/* get the required thumbnail config items */
private static void getThumbSettings()
{
showThumbs = ConfigurationManager
.getBooleanProperty("webui.browse.thumbnail.show");
if (showThumbs)
{
thumbItemListMaxHeight = ConfigurationManager
.getIntProperty("webui.browse.thumbnail.maxheight");
if (thumbItemListMaxHeight == 0)
{
thumbItemListMaxHeight = ConfigurationManager
.getIntProperty("thumbnail.maxheight");
}
thumbItemListMaxWidth = ConfigurationManager
.getIntProperty("webui.browse.thumbnail.maxwidth");
if (thumbItemListMaxWidth == 0)
{
thumbItemListMaxWidth = ConfigurationManager
.getIntProperty("thumbnail.maxwidth");
}
}
String linkBehaviour = ConfigurationManager
.getProperty("webui.browse.thumbnail.linkbehaviour");
if ("bitstream".equals(linkBehaviour))
{
linkToBitstream = true;
}
}
/*
* Get the (X)HTML width and height attributes. As the browser is being used
* for scaling, we only scale down otherwise we'll get hideously chunky
* images. This means the media filter should be run with the maxheight and
* maxwidth set greater than or equal to the size of the images required in
* the search/browse
*/
private String getScalingAttr(HttpServletRequest hrq, Bitstream bitstream)
throws JspException
{
BufferedImage buf;
try
{
Context c = UIUtil.obtainContext(hrq);
InputStream is = BitstreamStorageManager.retrieve(c, bitstream
.getID());
//AuthorizeManager.authorizeAction(bContext, this, Constants.READ);
// read in bitstream's image
buf = ImageIO.read(is);
is.close();
}
catch (SQLException sqle)
{
throw new JspException(sqle.getMessage(), sqle);
}
catch (IOException ioe)
{
throw new JspException(ioe.getMessage(), ioe);
}
// now get the image dimensions
float xsize = (float) buf.getWidth(null);
float ysize = (float) buf.getHeight(null);
// scale by x first if needed
if (xsize > (float) thumbItemListMaxWidth)
{
// calculate scaling factor so that xsize * scale = new size (max)
float scale_factor = (float) thumbItemListMaxWidth / xsize;
// now reduce x size and y size
xsize = xsize * scale_factor;
ysize = ysize * scale_factor;
}
// scale by y if needed
if (ysize > (float) thumbItemListMaxHeight)
{
float scale_factor = (float) thumbItemListMaxHeight / ysize;
// now reduce x size
// and y size
xsize = xsize * scale_factor;
ysize = ysize * scale_factor;
}
StringBuffer sb = new StringBuffer("width=\"").append(xsize).append(
"\" height=\"").append(ysize).append("\"");
return sb.toString();
}
/* generate the (X)HTML required to show the thumbnail */
private String getThumbMarkup(HttpServletRequest hrq, Item item)
throws JspException
{
try
{
Context c = UIUtil.obtainContext(hrq);
Thumbnail thumbnail = ItemService.getThumbnail(c, item.getID(), linkToBitstream);
if (thumbnail == null)
{
return "";
}
StringBuffer thumbFrag = new StringBuffer();
if (linkToBitstream)
{
Bitstream original = thumbnail.getOriginal();
String link = hrq.getContextPath() + "/bitstream/" + item.getHandle() + "/" + original.getSequenceID() + "/" +
UIUtil.encodeBitstreamName(original.getName(), Constants.DEFAULT_ENCODING);
thumbFrag.append("<a target=\"_blank\" href=\"" + link + "\" />");
}
else
{
String link = hrq.getContextPath() + "/handle/" + item.getHandle();
thumbFrag.append("<a href=\"" + link + "\" />");
}
Bitstream thumb = thumbnail.getThumb();
String img = hrq.getContextPath() + "/retrieve/" + thumb.getID() + "/" +
UIUtil.encodeBitstreamName(thumb.getName(), Constants.DEFAULT_ENCODING);
String alt = thumb.getName();
String scAttr = getScalingAttr(hrq, thumb);
thumbFrag.append("<img src=\"")
.append(img)
.append("\" alt=\"").append(alt).append("\" ")
.append(scAttr)
.append("/ border=\"0\"></a>");
return thumbFrag.toString();
}
catch (SQLException sqle)
{
throw new JspException(sqle.getMessage(), sqle);
}
catch (UnsupportedEncodingException e)
{
throw new JspException("Server does not support DSpace's default encoding. ", 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.webui.jsptag;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
* Tag for producing a popup window link. Takes advantage of Javascript to
* produce a small window that is brought to the front every time a popup link
* is pressed. If Javascript is not available, a simple HTML link is used as a
* fallback. The contents of the tag are used as the text of the link.
*
* Additionally, this will link to the "local" version of the URL, if a locally
* modified version exists.
*
* FIXME: Currently supports a single popup window at a hardcoded size; extra
* attributes could be added at a later date (e.g. name, width, height)
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class PopupTag extends BodyTagSupport
{
/** Path of default JSP version */
private String page;
public PopupTag()
{
super();
}
/**
* Get the JSP to display (default version)
*
* @return the page to display
*/
public String getPage()
{
return page;
}
/**
* Set the JSP to display (default version)
*
* @param s
* the page to display
*/
public void setPage(String s)
{
page = s;
}
public int doAfterBody() throws JspException
{
/*
* The output is the following, with PAGE and TEXT replaced
* appropriately:
*
* <script type="text/javascript"> <!-- document.write(' <a href="#"
* onClick="var popupwin =
* window.open(\'PAGE\',\'dspacepopup\',\'height=600,width=550,resizable,scrollbars\');popupwin.focus();return
* false;">TEXT <\/a>'); // --> </script> <noscript> <a href="PAGE"
* target="dspacepopup">TEXT </a>. </noscript>
*
* The script writes a Javascripted link which opens the popup window
* 600x550, or brings it to the front if it's already open. If
* Javascript is not available, plain HTML link in the NOSCRIPT element
* is used.
*/
BodyContent bc = getBodyContent();
String linkText = bc.getString();
bc.clearBody();
HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest();
String actualPage = hrq.getContextPath() + page;
String html = "<script type=\"text/javascript\">\n"
+ "<!-- Javascript starts here\n"
+ "document.write('<a href=\"#\" onClick=\"var popupwin = window.open(\\'"
+ actualPage
+ "\\',\\'dspacepopup\\',\\'height=600,width=550,resizable,scrollbars\\');popupwin.focus();return false;\">"
+ linkText + "<\\/a>');\n" + "// -->\n"
+ "</script><noscript><a href=\"" + actualPage
+ "\" target=\"dspacepopup\">" + linkText + "</a></noscript>";
try
{
getPreviousOut().print(html);
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
}
| 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.webui.jsptag;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.lang.ArrayUtils;
import org.dspace.content.Collection;
/**
* Tag for display a list of collections
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class CollectionListTag extends TagSupport
{
/** Collections to display */
private transient Collection[] collections;
private static final long serialVersionUID = -9040013543196580904L;
public CollectionListTag()
{
super();
}
public int doStartTag() throws JspException
{
JspWriter out = pageContext.getOut();
try
{
out.println("<table align=\"center\" class=\"miscTable\" title=\"Collection List\">");
// Write column headings
out.print("<tr><th id=\"t4\" class=\"oddRowOddCol\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.CollectionListTag.collectionName")
+ "</th></tr>");
// Row: toggles between Odd and Even
String row = "even";
for (int i = 0; i < collections.length; i++)
{
// name
String name = collections[i].getMetadata("name");
// first and only column is 'name'
out.print("<tr><td headers=\"t4\" class=\"" + row + "RowEvenCol\">");
out.print("<a href=\"");
HttpServletRequest hrq = (HttpServletRequest) pageContext
.getRequest();
out.print(hrq.getContextPath() + "/handle/");
out.print(collections[i].getHandle());
out.print("\">");
out.print(name);
out.print("</a>");
out.println("</td></tr>");
row = (row.equals("odd") ? "even" : "odd");
}
out.println("</table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
/**
* Get the collections to list
*
* @return the collections
*/
public Collection[] getCollections()
{
return (Collection[]) ArrayUtils.clone(collections);
}
/**
* Set the collections to list
*
* @param collectionsIn
* the collections
*/
public void setCollections(Collection[] collectionsIn)
{
collections = (Collection[]) ArrayUtils.clone(collectionsIn);
}
public void release()
{
collections = 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.webui.jsptag;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.browse.*;
import org.dspace.content.Bitstream;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.Thumbnail;
import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.Utils;
import org.dspace.storage.bitstore.BitstreamStorageManager;
import org.dspace.sort.SortOption;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.StringTokenizer;
import org.dspace.content.authority.MetadataAuthorityManager;
/**
* Tag for display a list of items
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class BrowseListTag extends TagSupport
{
/** log4j category */
private static Logger log = Logger.getLogger(BrowseListTag.class);
/** Items to display */
private transient BrowseItem[] items;
/** Row to highlight, -1 for no row */
private int highlightRow = -1;
/** Column to emphasise, identified by metadata field */
private String emphColumn;
/** Config value of thumbnail view toggle */
private static boolean showThumbs;
/** Config browse/search width and height */
private static int thumbItemListMaxWidth;
private static int thumbItemListMaxHeight;
/** Config browse/search thumbnail link behaviour */
private static boolean linkToBitstream = false;
/** Config to include an edit link */
private boolean linkToEdit = false;
/** Config to disable cross links */
private boolean disableCrossLinks = false;
/** The default fields to be displayed when listing items */
private static final String DEFAULT_LIST_FIELDS;
/** The default widths for the columns */
private static final String DEFAULT_LIST_WIDTHS;
/** The default field which is bound to the browse by date */
private static String dateField = "dc.date.issued";
/** The default field which is bound to the browse by title */
private static String titleField = "dc.title";
private static String authorField = "dc.contributor.*";
private int authorLimit = -1;
private transient BrowseInfo browseInfo;
private static final long serialVersionUID = 8091584920304256107L;
static
{
getThumbSettings();
if (showThumbs)
{
DEFAULT_LIST_FIELDS = "thumbnail, dc.date.issued(date), dc.title, dc.contributor.*";
DEFAULT_LIST_WIDTHS = "*, 130, 60%, 40%";
}
else
{
DEFAULT_LIST_FIELDS = "dc.date.issued(date), dc.title, dc.contributor.*";
DEFAULT_LIST_WIDTHS = "130, 60%, 40%";
}
// get the date and title fields
String dateLine = ConfigurationManager.getProperty("webui.browse.index.date");
if (dateLine != null)
{
dateField = dateLine;
}
String titleLine = ConfigurationManager.getProperty("webui.browse.index.title");
if (titleLine != null)
{
titleField = titleLine;
}
// get the author truncation config
String authorLine = ConfigurationManager.getProperty("webui.browse.author-field");
if (authorLine != null)
{
authorField = authorLine;
}
}
public BrowseListTag()
{
super();
}
@Override
public int doStartTag() throws JspException
{
JspWriter out = pageContext.getOut();
HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest();
/* just leave this out now
boolean emphasiseDate = false;
boolean emphasiseTitle = false;
if (emphColumn != null)
{
emphasiseDate = emphColumn.equalsIgnoreCase("date");
emphasiseTitle = emphColumn.equalsIgnoreCase("title");
}
*/
// get the elements to display
String browseListLine = null;
String browseWidthLine = null;
// As different indexes / sort options may require different columns to be displayed
// try to obtain a custom configuration based for the browse that has been performed
if (browseInfo != null)
{
SortOption so = browseInfo.getSortOption();
BrowseIndex bix = browseInfo.getBrowseIndex();
// We have obtained the index that was used for this browse
if (bix != null)
{
// First, try to get a configuration for this browse and sort option combined
if (so != null && browseListLine == null)
{
browseListLine = ConfigurationManager.getProperty("webui.itemlist.browse." + bix.getName() + ".sort." + so.getName() + ".columns");
browseWidthLine = ConfigurationManager.getProperty("webui.itemlist.browse." + bix.getName() + ".sort." + so.getName() + ".widths");
}
// We haven't got a sort option defined, so get one for the index
// - it may be required later
if (so == null)
{
so = bix.getSortOption();
}
}
// If no config found, attempt to get one for this sort option
if (so != null && browseListLine == null)
{
browseListLine = ConfigurationManager.getProperty("webui.itemlist.sort." + so.getName() + ".columns");
browseWidthLine = ConfigurationManager.getProperty("webui.itemlist.sort." + so.getName() + ".widths");
}
// If no config found, attempt to get one for this browse index
if (bix != null && browseListLine == null)
{
browseListLine = ConfigurationManager.getProperty("webui.itemlist.browse." + bix.getName() + ".columns");
browseWidthLine = ConfigurationManager.getProperty("webui.itemlist.browse." + bix.getName() + ".widths");
}
// If no config found, attempt to get a general one, using the sort name
if (so != null && browseListLine == null)
{
browseListLine = ConfigurationManager.getProperty("webui.itemlist." + so.getName() + ".columns");
browseWidthLine = ConfigurationManager.getProperty("webui.itemlist." + so.getName() + ".widths");
}
// If no config found, attempt to get a general one, using the index name
if (bix != null && browseListLine == null)
{
browseListLine = ConfigurationManager.getProperty("webui.itemlist." + bix.getName() + ".columns");
browseWidthLine = ConfigurationManager.getProperty("webui.itemlist." + bix.getName() + ".widths");
}
}
if (browseListLine == null)
{
browseListLine = ConfigurationManager.getProperty("webui.itemlist.columns");
browseWidthLine = ConfigurationManager.getProperty("webui.itemlist.widths");
}
// Have we read a field configration from dspace.cfg?
if (browseListLine != null)
{
// If thumbnails are disabled, strip out any thumbnail column from the configuration
if (!showThumbs && browseListLine.contains("thumbnail"))
{
// Ensure we haven't got any nulls
browseListLine = browseListLine == null ? "" : browseListLine;
browseWidthLine = browseWidthLine == null ? "" : browseWidthLine;
// Tokenize the field and width lines
StringTokenizer bllt = new StringTokenizer(browseListLine, ",");
StringTokenizer bwlt = new StringTokenizer(browseWidthLine, ",");
StringBuilder newBLLine = new StringBuilder();
StringBuilder newBWLine = new StringBuilder();
while (bllt.hasMoreTokens() || bwlt.hasMoreTokens())
{
String browseListTok = bllt.hasMoreTokens() ? bllt.nextToken() : null;
String browseWidthTok = bwlt.hasMoreTokens() ? bwlt.nextToken() : null;
// Only use the Field and Width tokens, if the field isn't 'thumbnail'
if (browseListTok == null || !browseListTok.trim().equals("thumbnail"))
{
if (browseListTok != null)
{
if (newBLLine.length() > 0)
{
newBLLine.append(",");
}
newBLLine.append(browseListTok);
}
if (browseWidthTok != null)
{
if (newBWLine.length() > 0)
{
newBWLine.append(",");
}
newBWLine.append(browseWidthTok);
}
}
}
// Use the newly built configuration file
browseListLine = newBLLine.toString();
browseWidthLine = newBWLine.toString();
}
}
else
{
browseListLine = DEFAULT_LIST_FIELDS;
browseWidthLine = DEFAULT_LIST_WIDTHS;
}
// Arrays used to hold the information we will require when outputting each row
String[] fieldArr = browseListLine == null ? new String[0] : browseListLine.split("\\s*,\\s*");
String[] widthArr = browseWidthLine == null ? new String[0] : browseWidthLine.split("\\s*,\\s*");
boolean isDate[] = new boolean[fieldArr.length];
boolean emph[] = new boolean[fieldArr.length];
boolean isAuthor[] = new boolean[fieldArr.length];
boolean viewFull[] = new boolean[fieldArr.length];
String[] browseType = new String[fieldArr.length];
String[] cOddOrEven = new String[fieldArr.length];
try
{
// Get the interlinking configuration too
CrossLinks cl = new CrossLinks();
// Get a width for the table
String tablewidth = ConfigurationManager.getProperty("webui.itemlist.tablewidth");
// If we have column widths, try to use a fixed layout table - faster for browsers to render
// but not if we have to add an 'edit item' button - we can't know how big it will be
if (widthArr.length > 0 && widthArr.length == fieldArr.length && !linkToEdit)
{
// If the table width has been specified, we can make this a fixed layout
if (!StringUtils.isEmpty(tablewidth))
{
out.println("<table style=\"width: " + tablewidth + "; table-layout: fixed;\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
}
else
{
// Otherwise, don't constrain the width
out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
}
// Output the known column widths
out.print("<colgroup>");
for (int w = 0; w < widthArr.length; w++)
{
out.print("<col width=\"");
// For a thumbnail column of width '*', use the configured max width for thumbnails
if (fieldArr[w].equals("thumbnail") && widthArr[w].equals("*"))
{
out.print(thumbItemListMaxWidth);
}
else
{
out.print(StringUtils.isEmpty(widthArr[w]) ? "*" : widthArr[w]);
}
out.print("\" />");
}
out.println("</colgroup>");
}
else if (!StringUtils.isEmpty(tablewidth))
{
out.println("<table width=\"" + tablewidth + "\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
}
else
{
out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
}
// Output the table headers
out.println("<tr>");
for (int colIdx = 0; colIdx < fieldArr.length; colIdx++)
{
String field = fieldArr[colIdx].toLowerCase().trim();
cOddOrEven[colIdx] = (((colIdx + 1) % 2) == 0 ? "Odd" : "Even");
// find out if the field is a date
if (field.indexOf("date") > 0)
{
field = field.replaceAll("\\(date\\)", "");
isDate[colIdx] = true;
}
// Cache any modifications to field
fieldArr[colIdx] = field;
// find out if this is the author column
if (field.equals(authorField))
{
isAuthor[colIdx] = true;
}
// find out if this field needs to link out to other browse views
if (cl.hasLink(field))
{
browseType[colIdx] = cl.getLinkType(field);
viewFull[colIdx] = BrowseIndex.getBrowseIndex(browseType[colIdx]).isItemIndex();
}
// find out if we are emphasising this field
/*
if ((field.equals(dateField) && emphasiseDate) ||
(field.equals(titleField) && emphasiseTitle))
{
emph[colIdx] = true;
}
*/
if (field.equals(emphColumn))
{
emph[colIdx] = true;
}
// prepare the strings for the header
String id = "t" + Integer.toString(colIdx + 1);
String css = "oddRow" + cOddOrEven[colIdx] + "Col";
String message = "itemlist." + field;
// output the header
// START Code Dimitri Surinx
if (!field.equals("dc.identifier.citation") && !field.equals("dc.contributor.*"))
{
out.print("<th id=\"" + id + "\" class=\"latestLayoutTitle\">"
+ (emph[colIdx] ? "<strong>" : "")
+ LocaleSupport.getLocalizedMessage(pageContext, message)
+ (emph[colIdx] ? "</strong>" : "") + "</th>");
}
// END Code Dimitri Surinx
}
if (linkToEdit)
{
String id = "t" + Integer.toString(cOddOrEven.length + 1);
String css = "oddRow" + cOddOrEven[cOddOrEven.length - 2] + "Col";
// output the header
out.print("<th id=\"" + id + "\" class=\"" + css + "\">"
+ (emph[emph.length - 2] ? "<strong>" : "")
+ " " //LocaleSupport.getLocalizedMessage(pageContext, message)
+ (emph[emph.length - 2] ? "</strong>" : "") + "</th>");
}
out.print("</tr>");
// now output each item row
for (int i = 0; i < items.length; i++)
{
// START Code Dimitri Surinx
String bufferConc = "";
// END Code Dimitri Surinx
out.print("<tr>");
// now prepare the XHTML frag for this division
String rOddOrEven;
if (i == highlightRow)
{
rOddOrEven = "highlight";
}
else
{
rOddOrEven = ((i & 1) == 1 ? "odd" : "even");
}
for (int colIdx = 0; colIdx < fieldArr.length; colIdx++)
{
String field = fieldArr[colIdx];
// get the schema and the element qualifier pair
// (Note, the schema is not used for anything yet)
// (second note, I hate this bit of code. There must be
// a much more elegant way of doing this. Tomcat has
// some weird problems with variations on this code that
// I tried, which is why it has ended up the way it is)
StringTokenizer eq = new StringTokenizer(field, ".");
String[] tokens = { "", "", "" };
int k = 0;
while(eq.hasMoreTokens())
{
tokens[k] = eq.nextToken().toLowerCase().trim();
k++;
}
String schema = tokens[0];
String element = tokens[1];
String qualifier = tokens[2];
// first get hold of the relevant metadata for this column
DCValue[] metadataArray;
if (qualifier.equals("*"))
{
metadataArray = items[i].getMetadata(schema, element, Item.ANY, Item.ANY);
}
else if (qualifier.equals(""))
{
metadataArray = items[i].getMetadata(schema, element, null, Item.ANY);
}
else
{
metadataArray = items[i].getMetadata(schema, element, qualifier, Item.ANY);
}
// save on a null check which would make the code untidy
if (metadataArray == null)
{
metadataArray = new DCValue[0];
}
// now prepare the content of the table division
String metadata = "";
if (field.equals("thumbnail"))
{
metadata = getThumbMarkup(hrq, items[i]);
}
else if (metadataArray.length > 0)
{
// format the date field correctly
if (isDate[colIdx])
{
DCDate dd = new DCDate(metadataArray[0].value);
metadata = Integer.toString(dd.getYear());//UIUtil.displayDate(dd, false, false, hrq);
}
// format the title field correctly for withdrawn items (ie. don't link)
else if (field.equals(titleField) && items[i].isWithdrawn())
{
metadata = Utils.addEntities(metadataArray[0].value);
}
// format the title field correctly (as long as the item isn't withdrawn, link to it)
else if (field.equals(titleField))
{
metadata = "<a href=\"" + hrq.getContextPath() + "/handle/"
+ items[i].getHandle() + "\">"
+ Utils.addEntities(metadataArray[0].value)
+ "</a>";
}
// format all other fields
else
{
// limit the number of records if this is the author field (if
// -1, then the limit is the full list)
boolean truncated = false;
int loopLimit = metadataArray.length;
if (isAuthor[colIdx])
{
int fieldMax = (authorLimit == -1 ? metadataArray.length : authorLimit);
loopLimit = (fieldMax > metadataArray.length ? metadataArray.length : fieldMax);
truncated = (fieldMax < metadataArray.length);
log.debug("Limiting output of field " + field + " to " + Integer.toString(loopLimit) + " from an original " + Integer.toString(metadataArray.length));
}
StringBuilder sb = new StringBuilder();
for (int j = 0; j < loopLimit; j++)
{
String startLink = "";
String endLink = "";
if (!StringUtils.isEmpty(browseType[colIdx]) && !disableCrossLinks)
{
String argument;
String value;
if (metadataArray[j].authority != null &&
metadataArray[j].confidence >= MetadataAuthorityManager.getManager()
.getMinConfidence(metadataArray[j].schema, metadataArray[j].element, metadataArray[j].qualifier))
{
argument = "authority";
value = metadataArray[j].authority;
}
else
{
argument = "value";
value = metadataArray[j].value;
}
if (viewFull[colIdx])
{
argument = "vfocus";
}
startLink = "<a href=\"" + hrq.getContextPath() + "/browse?type=" + browseType[colIdx] + "&" +
argument + "=" + URLEncoder.encode(value,"UTF-8");
if (metadataArray[j].language != null)
{
startLink = startLink + "&" +
argument + "_lang=" + URLEncoder.encode(metadataArray[j].language, "UTF-8");
}
if ("authority".equals(argument))
{
startLink += "\" class=\"authority " +browseType[colIdx] + "\">";
}
else
{
startLink = startLink + "\">";
}
endLink = "</a>";
}
sb.append(startLink);
sb.append(Utils.addEntities(metadataArray[j].value));
sb.append(endLink);
if (j < (loopLimit - 1))
{
sb.append("; ");
}
}
if (truncated)
{
String etal = LocaleSupport.getLocalizedMessage(pageContext, "itemlist.et-al");
sb.append(", ").append(etal);
}
metadata = "<em>" + sb.toString() + "</em>";
}
}
// prepare extra special layout requirements for dates
String extras = "";
if (isDate[colIdx])
{
extras = "nowrap=\"nowrap\" align=\"right\"";
}
String id = "t" + Integer.toString(colIdx + 1);
// START Code Dimitri Surinx
if (field.equals("dc.identifier.citation"))
{
if (!"".equals(metadata))
bufferConc = bufferConc + "<div>" + metadata + "</div>";
else
bufferConc = bufferConc + metadata;
}
else if (field.equals("dc.contributor.*"))
{
out.print(bufferConc + "<div style=\"margin-left: 0px\">" + metadata + "</div>" + "</td>");
}
else if (!field.equals(titleField))
{
out.print("<td align=\"right\" headers=\"" + id + "\" width=\"10px\" valign=\"top\" class=\"latestLayout\">"
+ (emph[colIdx] ? "<strong>" : "") + metadata + (emph[colIdx] ? "</strong>" : "")
+ "</td>");
}
else if (field.equals(titleField))
{
bufferConc = "<td headers=\"" + id + "\" valign=\"top\" class=\"latestLayout\">"
+ (emph[colIdx] ? "<strong>" : "") + metadata + (emph[colIdx] ? "</strong>" : "");
} // end Code Dimitri surinx end
else
{
out.print("<td headers=\"" + id + "\" class=\""
+ rOddOrEven + "Row" + cOddOrEven[colIdx] + "Col\" " + extras + ">"
+ (emph[colIdx] ? "<strong>" : "") + metadata + (emph[colIdx] ? "</strong>" : "")
+ "</td>");
}
}
// Add column for 'edit item' links
if (linkToEdit)
{
String id = "t" + Integer.toString(cOddOrEven.length + 1);
out.print("<td headers=\"" + id + "\" class=\""
+ rOddOrEven + "Row" + cOddOrEven[cOddOrEven.length - 2] + "Col\" nowrap>"
+ "<form method=\"get\" action=\"" + hrq.getContextPath() + "/tools/edit-item\">"
+ "<input type=\"hidden\" name=\"handle\" value=\"" + items[i].getHandle() + "\" />"
+ "<input type=\"submit\" value=\"Edit Item\" /></form>"
+ "</td>");
}
out.println("</tr>");
}
// close the table
out.println("</table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
catch (SQLException e)
{
throw new JspException(e);
}
catch (BrowseException e)
{
throw new JspException(e);
}
return SKIP_BODY;
}
public BrowseInfo getBrowseInfo()
{
return browseInfo;
}
public void setBrowseInfo(BrowseInfo browseInfo)
{
this.browseInfo = browseInfo;
setItems(browseInfo.getBrowseItemResults());
authorLimit = browseInfo.getEtAl();
}
public boolean getLinkToEdit()
{
return linkToEdit;
}
public void setLinkToEdit(boolean edit)
{
this.linkToEdit = edit;
}
public boolean getDisableCrossLinks()
{
return disableCrossLinks;
}
public void setDisableCrossLinks(boolean links)
{
this.disableCrossLinks = links;
}
/**
* Get the items to list
*
* @return the items
*/
public BrowseItem[] getItems()
{
return (BrowseItem[]) ArrayUtils.clone(items);
}
/**
* Set the items to list
*
* @param itemsIn
* the items
*/
public void setItems(BrowseItem[] itemsIn)
{
items = (BrowseItem[]) ArrayUtils.clone(itemsIn);
}
/**
* Get the row to highlight - null or -1 for no row
*
* @return the row to highlight
*/
public String getHighlightrow()
{
return String.valueOf(highlightRow);
}
/**
* Set the row to highlight
*
* @param highlightRowIn
* the row to highlight or -1 for no highlight
*/
public void setHighlightrow(String highlightRowIn)
{
if ((highlightRowIn == null) || highlightRowIn.equals(""))
{
highlightRow = -1;
}
else
{
try
{
highlightRow = Integer.parseInt(highlightRowIn);
}
catch (NumberFormatException nfe)
{
highlightRow = -1;
}
}
}
/**
* Get the column to emphasise - "title", "date" or null
*
* @return the column to emphasise
*/
public String getEmphcolumn()
{
return emphColumn;
}
/**
* Set the column to emphasise - "title", "date" or null
*
* @param emphColumnIn
* column to emphasise
*/
public void setEmphcolumn(String emphColumnIn)
{
emphColumn = emphColumnIn;
}
public void release()
{
highlightRow = -1;
emphColumn = null;
items = null;
}
/* get the required thumbnail config items */
private static void getThumbSettings()
{
showThumbs = ConfigurationManager
.getBooleanProperty("webui.browse.thumbnail.show");
if (showThumbs)
{
thumbItemListMaxHeight = ConfigurationManager
.getIntProperty("webui.browse.thumbnail.maxheight");
if (thumbItemListMaxHeight == 0)
{
thumbItemListMaxHeight = ConfigurationManager
.getIntProperty("thumbnail.maxheight");
}
thumbItemListMaxWidth = ConfigurationManager
.getIntProperty("webui.browse.thumbnail.maxwidth");
if (thumbItemListMaxWidth == 0)
{
thumbItemListMaxWidth = ConfigurationManager
.getIntProperty("thumbnail.maxwidth");
}
}
String linkBehaviour = ConfigurationManager
.getProperty("webui.browse.thumbnail.linkbehaviour");
if (linkBehaviour != null && linkBehaviour.equals("bitstream"))
{
linkToBitstream = true;
}
}
/*
* Get the (X)HTML width and height attributes. As the browser is being used
* for scaling, we only scale down otherwise we'll get hideously chunky
* images. This means the media filter should be run with the maxheight and
* maxwidth set greater than or equal to the size of the images required in
* the search/browse
*/
private String getScalingAttr(HttpServletRequest hrq, Bitstream bitstream)
throws JspException
{
BufferedImage buf;
try
{
Context c = UIUtil.obtainContext(hrq);
InputStream is = BitstreamStorageManager.retrieve(c, bitstream
.getID());
//AuthorizeManager.authorizeAction(bContext, this, Constants.READ);
// read in bitstream's image
buf = ImageIO.read(is);
is.close();
}
catch (SQLException sqle)
{
throw new JspException(sqle.getMessage(), sqle);
}
catch (IOException ioe)
{
throw new JspException(ioe.getMessage(), ioe);
}
// now get the image dimensions
float xsize = (float) buf.getWidth(null);
float ysize = (float) buf.getHeight(null);
// scale by x first if needed
if (xsize > (float) thumbItemListMaxWidth)
{
// calculate scaling factor so that xsize * scale = new size (max)
float scaleFactor = (float) thumbItemListMaxWidth / xsize;
// now reduce x size and y size
xsize = xsize * scaleFactor;
ysize = ysize * scaleFactor;
}
// scale by y if needed
if (ysize > (float) thumbItemListMaxHeight)
{
float scaleFactor = (float) thumbItemListMaxHeight / ysize;
// now reduce x size
// and y size
xsize = xsize * scaleFactor;
ysize = ysize * scaleFactor;
}
StringBuffer sb = new StringBuffer("width=\"").append(xsize).append(
"\" height=\"").append(ysize).append("\"");
return sb.toString();
}
/* generate the (X)HTML required to show the thumbnail */
private String getThumbMarkup(HttpServletRequest hrq, BrowseItem item)
throws JspException
{
try
{
Context c = UIUtil.obtainContext(hrq);
Thumbnail thumbnail = ItemService.getThumbnail(c, item.getID(), linkToBitstream);
if (thumbnail == null)
{
return "";
}
StringBuffer thumbFrag = new StringBuffer();
if (linkToBitstream)
{
Bitstream original = thumbnail.getOriginal();
String link = hrq.getContextPath() + "/bitstream/" + item.getHandle() + "/" + original.getSequenceID() + "/" +
UIUtil.encodeBitstreamName(original.getName(), Constants.DEFAULT_ENCODING);
thumbFrag.append("<a target=\"_blank\" href=\"" + link + "\" />");
}
else
{
String link = hrq.getContextPath() + "/handle/" + item.getHandle();
thumbFrag.append("<a href=\"" + link + "\" />");
}
Bitstream thumb = thumbnail.getThumb();
String img = hrq.getContextPath() + "/retrieve/" + thumb.getID() + "/" +
UIUtil.encodeBitstreamName(thumb.getName(), Constants.DEFAULT_ENCODING);
String alt = thumb.getName();
String scAttr = getScalingAttr(hrq, thumb);
thumbFrag.append("<img src=\"")
.append(img)
.append("\" alt=\"").append(alt).append("\" ")
.append(scAttr)
.append("/ border=\"0\"></a>");
return thumbFrag.toString();
}
catch (SQLException sqle)
{
throw new JspException(sqle.getMessage(), sqle);
}
catch (UnsupportedEncodingException e)
{
throw new JspException("Server does not support DSpace's default encoding. ", 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.webui.jsptag;
import java.io.File;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.app.sfx.SFXFileReader;
/**
* Renders an SFX query link. Takes one attribute - "item" which must be an Item
* object.
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class SFXLinkTag extends TagSupport
{
/** Item to display SFX link for */
private transient Item item;
/** The fully qualified pathname of the SFX XML file */
private String sfxFile = ConfigurationManager.getProperty("dspace.dir") + File.separator
+ "config" + File.separator + "sfx.xml";
private static final long serialVersionUID = 7028793612957710128L;
public SFXLinkTag()
{
super();
}
public int doStartTag() throws JspException
{
try
{
String sfxServer = ConfigurationManager
.getProperty("sfx.server.url");
if (sfxServer == null)
{
// No SFX server - SFX linking switched off
return SKIP_BODY;
}
String sfxQuery = "";
sfxQuery = SFXFileReader.loadSFXFile(sfxFile, item);
// Remove initial &, if any
if (sfxQuery.startsWith("&"))
{
sfxQuery = sfxQuery.substring(1);
}
pageContext.getOut().print(sfxServer + sfxQuery);
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
/**
* Get the item this tag should display SFX Link for
*
* @return the item
*/
public Item getItem()
{
return item;
}
/**
* Set the item this tag should display SFX Link for
*
* @param itemIn
* the item
*/
public void setItem(Item itemIn)
{
item = itemIn;
}
}
| 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.webui.jsptag;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.log4j.Logger;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.ConfigurationManager;
import org.dspace.app.webui.servlet.FeedServlet;
/**
* Tag for HTML page layout ("skin").
* <P>
* This tag <em>sets</em> request attributes that should be used by the header
* and footer to render the page appropriately:
* <P>
* <ul>
* <li><code>dspace.layout.title</code> - title of page</li>
* <li><code>dspace.layout.locbar</code> - value will Boolean true or false
* </li>
* <li><code>dspace.layout.parenttitles</code> - a <code>List</code> of
* <code>String</code>s corresponding with titles to put in the location bar.
* Only set if <code>dspace.layout.locbar</code> is true</li>
* <li><code>dspace.layout.parentlinks</code> - a <code>List</code> of
* <code>String</code>s corresponding with links to put in the location bar.
* Empty strings mean no link. Will only be set if
* <code>dspace.layout.locbar</code> is true.</li>
* <li><code>dspace.layout.navbar</code> - value will be "off", or the
* navigation bar to include, e.g. "/layout/navbar_default.jsp"</li>
* <li><code>dspace.layout.sidebar</code> - contents of the sidebar</li>
* <li><code>dspace.current.user</code> - the EPerson currently logged in, or
* <code>null</code> if anonymous access</li>
* <li><code>dspace.layout.feeddata</code> - <code>String</code>. "NONE"
* means no feed from this page; otherwise the Handle of object (community or
* collection) the feed is from</li>
* <li><code>dspace.layout.linkparts</code> - <code>String[]</code>. A
* cycling sequence of: 2nd part of MIME type (e.g. <code>rdf+rss</code>);
* title of feed; path component to go after /feed/ for the actual feed URL
* (e.g. <code>rss_1.0</code>). Hence, this array will have 3<i>n</i>
* elements where <i>n</i> is the number of feeds.</li>
* </ul>
* <p>
*
* * Additionally the following parameter may be set elsewhere in a Servlet.
* <p>
* <ul>
* <li><code>dspace.layout.head</code> - extra data to include verbatim in
* the <head> element of the page</li>
* </ul>
*
* Furthermore it sets the content type of the response to text/html using UTF-8
* to ensure this will be returned in the HTTP header.
* </p>
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class LayoutTag extends TagSupport
{
/** log4j logger */
private static Logger log = Logger.getLogger(LayoutTag.class);
/** layout style name */
private String style;
/** title */
private String title;
/** title key (from message dictionary) */
private String titleKey;
/** Navigation bar type, null means none */
private String navbar;
/** Location bar type */
private String locbar;
/** Name of "parent" page */
private String parentTitle;
/** Name of "parent" page key (from message dictionary) */
private String parentTitleKey;
/** Link to "parent" page */
private String parentLink;
/** Contents of side bar */
private String sidebar;
/** Whether to add headers to prevent browsers caching the page */
private String noCache;
/** Syndication feed "autodiscovery" link data */
private String feedData;
public LayoutTag()
{
super();
}
public int doStartTag() throws JspException
{
ServletRequest request = pageContext.getRequest();
// header file
String header = "/layout/header-default.jsp";
// Choose default style unless one is specified
if (style != null)
{
header = "/layout/header-" + style.toLowerCase() + ".jsp";
}
// Sort out location bar
if (locbar == null)
{
locbar = "auto";
}
// These lists will contain titles and links to put in the location
// bar
List<String> parents = new ArrayList<String>();
List<String> parentLinks = new ArrayList<String>();
if (locbar.equalsIgnoreCase("off"))
{
// No location bar
request.setAttribute("dspace.layout.locbar", Boolean.FALSE);
}
else
{
// We'll always add "DSpace Home" to the a location bar
parents.add(ConfigurationManager.getProperty("dspace.name"));
if (locbar.equalsIgnoreCase("nolink"))
{
parentLinks.add("");
}
else
{
parentLinks.add("/");
}
// Add other relevant components to the location bar
if (locbar.equalsIgnoreCase("link"))
{
// "link" mode - next thing in location bar is taken from
// parameters of tag, with a link
if (parentTitle != null)
{
parents.add(parentTitle);
parentLinks.add(parentLink);
}
else if (parentTitleKey != null)
{
parents.add(LocaleSupport.getLocalizedMessage(pageContext,
parentTitleKey));
parentLinks.add(parentLink);
}
}
else if (locbar.equalsIgnoreCase("commLink"))
{
// "commLink" mode - show all parent communities
Community[] comms = (Community[]) request
.getAttribute("dspace.communities");
if (comms != null)
{
for (int i = 0; i < comms.length; i++)
{
parents.add(comms[i].getMetadata("name"));
parentLinks.add("/handle/" + comms[i].getHandle());
}
}
}
else if (locbar.equalsIgnoreCase("nolink"))
{
// "nolink" mode - next thing in location bar is taken from
// parameters of tag, with no link
if (parentTitle != null)
{
parents.add(parentTitle);
parentLinks.add("");
}
}
else
{
// Grab parents from the URL - these should have been picked up
// by the HandleServlet
Collection col = (Collection) request
.getAttribute("dspace.collection");
Community[] comms = (Community[]) request
.getAttribute("dspace.communities");
if (comms != null)
{
for (int i = 0; i < comms.length; i++)
{
parents.add(comms[i].getMetadata("name"));
parentLinks.add("/handle/" + comms[i].getHandle());
}
if (col != null)
{
parents.add(col.getMetadata("name"));
parentLinks.add("/handle/" + col.getHandle());
}
}
}
request.setAttribute("dspace.layout.locbar", Boolean.TRUE);
}
request.setAttribute("dspace.layout.parenttitles", parents);
request.setAttribute("dspace.layout.parentlinks", parentLinks);
// Navigation bar: "default" is default :)
if (navbar == null)
{
navbar = "default";
}
if (navbar.equals("off"))
{
request.setAttribute("dspace.layout.navbar", "off");
}
else
{
request.setAttribute("dspace.layout.navbar", "/layout/navbar-"
+ navbar + ".jsp");
}
// Set title
if (title != null)
{
request.setAttribute("dspace.layout.title", title);
}
else if (titleKey != null)
{
request.setAttribute("dspace.layout.title", LocaleSupport
.getLocalizedMessage(pageContext, titleKey));
}
else
{
request.setAttribute("dspace.layout.title", "NO TITLE");
}
// Set feedData if present
if (feedData != null && ! "NONE".equals(feedData))
{
// set the links' reference - community or collection
boolean commLinks = feedData.startsWith("comm:");
boolean collLinks = feedData.startsWith("coll:");
if ( commLinks )
{
Community com = (Community)request.getAttribute("dspace.community");
request.setAttribute("dspace.layout.feedref", com.getHandle());
}
else if( collLinks )
{
Collection col = (Collection)request.getAttribute("dspace.collection");
request.setAttribute("dspace.layout.feedref", col.getHandle());
}
else //feed is across all of DSpace and not Community/Collection specific
{
request.setAttribute("dspace.layout.feedref", FeedServlet.SITE_FEED_KEY);
}
// build a list of link attributes for each link format
String[] formats = feedData.substring(feedData.indexOf(':')+1).split(",");
List<String> linkParts = new ArrayList<String>();
// each link has a mime-type, title, and format (used in href URL)
for (int i = 0; i < formats.length; i++)
{
if("rss_1.0".equals(formats[i]))
{
linkParts.add("rdf+xml");
}
else
{
linkParts.add("rss+xml");
}
if (commLinks)
{
linkParts.add("Items in Community");
}
else if(collLinks)
{
linkParts.add("Items in Collection");
}
else
{
linkParts.add("Items in " + ConfigurationManager.getProperty("dspace.name"));
}
linkParts.add(formats[i]);
}
request.setAttribute("dspace.layout.linkparts", linkParts);
}
else
{
request.setAttribute("dspace.layout.feedref", "NONE" );
}
// Now include the header
try
{
HttpServletResponse response = (HttpServletResponse) pageContext
.getResponse();
// Set headers to prevent browser caching, if appropriate
if ((noCache != null) && noCache.equalsIgnoreCase("true"))
{
response.addDateHeader("expires", 1);
response.addHeader("Pragma", "no-cache");
response.addHeader("Cache-control", "no-store");
}
// Ensure the HTTP header will declare that UTF-8 is used
// in the response.
response.setContentType("text/html; charset=UTF-8");
ServletConfig config = pageContext.getServletConfig();
RequestDispatcher rd = config.getServletContext()
.getRequestDispatcher(header);
rd.include(request, response);
}
catch (IOException ioe)
{
throw new JspException("Got IOException: " + ioe);
}
catch (ServletException se)
{
log.warn("Exception", se.getRootCause());
throw new JspException("Got ServletException: " + se);
}
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspException
{
// Footer file to use
String footer = "/layout/footer-default.jsp";
// Choose default flavour unless one is specified
if (style != null)
{
footer = "/layout/footer-" + style.toLowerCase() + ".jsp";
}
try
{
// Ensure body is included before footer
pageContext.getOut().flush();
// Context objects
ServletRequest request = pageContext.getRequest();
ServletResponse response = pageContext.getResponse();
ServletConfig config = pageContext.getServletConfig();
if (sidebar != null)
{
request.setAttribute("dspace.layout.sidebar", sidebar);
}
RequestDispatcher rd = config.getServletContext()
.getRequestDispatcher(footer);
rd.include(request, response);
}
catch (ServletException se)
{
throw new JspException("Got ServletException: " + se);
}
catch (IOException ioe)
{
throw new JspException("Got IOException: " + ioe);
}
return EVAL_PAGE;
}
/**
* Get the value of title.
*
* @return Value of title.
*/
public String getTitle()
{
return title;
}
/**
* Set the value of title.
*
* @param v
* Value to assign to title.
*/
public void setTitle(String v)
{
this.title = v;
}
/**
* @return Returns the titleKey.
*/
public String getTitlekey()
{
return titleKey;
}
/**
* @param titleKey The titleKey to set.
*/
public void setTitlekey(String titleKey)
{
this.titleKey = titleKey;
}
/**
* Get the value of navbar.
*
* @return Value of navbar.
*/
public String getNavbar()
{
return navbar;
}
/**
* Set the value of navbar.
*
* @param v
* Value to assign to navbar.
*/
public void setNavbar(String v)
{
this.navbar = v;
}
/**
* Get the value of locbar.
*
* @return Value of locbar.
*/
public String getLocbar()
{
return locbar;
}
/**
* Set the value of locbar.
*
* @param v
* Value to assign to locbar.
*/
public void setLocbar(String v)
{
this.locbar = v;
}
/**
* Get the value of parentTitle.
*
* @return Value of parentTitle.
*/
public String getParenttitle()
{
return parentTitle;
}
/**
* Set the value of parent.
*
* @param v
* Value to assign to parent.
*/
public void setParenttitle(String v)
{
this.parentTitle = v;
}
/**
* get parent title key (from message dictionary)
*
* @return Returns the parentTitleKey.
*/
public String getParenttitlekey()
{
return parentTitleKey;
}
/**
* set parent title key (from message dictionary)
*
* @param parentTitleKey The parentTitleKey to set.
*/
public void setParenttitlekey(String parentTitleKey)
{
this.parentTitleKey = parentTitleKey;
}
/**
* Get the value of parentlink.
*
* @return Value of parentlink.
*/
public String getParentlink()
{
return parentLink;
}
/**
* Set the value of parentlink.
*
* @param v
* Value to assign to parentlink.
*/
public void setParentlink(String v)
{
this.parentLink = v;
}
/**
* Get the value of style.
*
* @return Value of style.
*/
public String getStyle()
{
return style;
}
/**
* Set the value of style.
*
* @param v
* Value to assign to style.
*/
public void setStyle(String v)
{
this.style = v;
}
/**
* Get the value of sidebar.
*
* @return Value of sidebar.
*/
public String getSidebar()
{
return sidebar;
}
/**
* Set the value of sidebar.
*
* @param v
* Value to assign to sidebar.
*/
public void setSidebar(String v)
{
this.sidebar = v;
}
/**
* Get the value of sidebar.
*
* @return Value of sidebar.
*/
public String getNocache()
{
return noCache;
}
/**
* Set the value of sidebar.
*
* @param v
* Value to assign to sidebar.
*/
public void setNocache(String v)
{
this.noCache = v;
}
/**
* Get the value of feedData.
*
* @return Value of feedData.
*/
public String getFeedData()
{
return feedData;
}
/**
* Set the value of feedData.
*
* @param v
* Value to assign to feedData.
*/
public void setFeedData(String v)
{
this.feedData = v;
}
public void release()
{
style = null;
title = null;
sidebar = null;
navbar = null;
locbar = null;
parentTitle = null;
parentLink = null;
noCache = null;
feedData = 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.webui.jsptag;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.lang.ArrayUtils;
import org.dspace.eperson.Group;
/**
* <P>Tag for producing an e-person select widget in a form. Somewhat
* analogous to the HTML SELECT element. An input
* field is produced with a button which pops up a window from which
* e-people can be selected. Selected e-epeople are added to the field
* in the form. If the selector is for multiple e-people, a 'remove
* selected from list' button is also added.</P>
*
* <P>On any form that has a selecteperson tag (only one allowed per page),
* you need to include the following Javascript code on all of the submit
* buttons, to ensure that the e-people IDs are posted and that the popup
* window is closed:</P>
*
* <P><code>onclick="javascript:finishEPerson();"</code></P>
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class SelectGroupTag extends TagSupport
{
/** Multiple groups? */
private boolean multiple;
/** Which groups are initially in the list? */
private transient Group[] groups;
private static final long serialVersionUID = -3330389128849427302L;
public SelectGroupTag()
{
super();
}
/**
* Setter for multiple attribute
*
* @param s attribute from JSP
*/
public void setMultiple(String s)
{
if (s != null && (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")))
{
multiple = true;
}
else
{
multiple = false;
}
}
/**
* Setter for groups in list
*
* @param g attribute from JSP
*/
public void setSelected(Object g)
{
if (g instanceof Group)
{
groups = new Group[1];
groups[0] = (Group) g;
}
else if(g instanceof Group[])
{
groups = (Group[])ArrayUtils.clone((Group[]) g);
}
}
public void release()
{
multiple = false;
groups = null;
}
public int doStartTag()
throws JspException
{
try
{
JspWriter out = pageContext.getOut();
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
out.print("<table><tr><td colspan=\"2\" align=\"center\"><select multiple=\"multiple\" name=\"group_ids\" size=\"");
out.print(multiple ? "10" : "1");
out.println("\">");
//ensure that if no group is selected that a blank option is displayed - xhtml compliance
if (groups == null || groups.length == 0)
{
out.print("<option value=\"\"> </option>");
}
if (groups != null)
{
for (int i = 0; i < groups.length; i++)
{
out.print("<option value=\"" + groups[i].getID() + "\">");
out.print(groups[i].getName() + " (" + groups[i].getID() + ")");
out.println("</option>");
}
}
out.print("</select></td>");
if (multiple)
{
out.print("</tr><tr><td width=\"50%\" align=\"center\">");
}
else
{
out.print("<td>");
}
String p = (multiple ?
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectGroupTag.selectGroups")
: LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectGroupTag.selectGroup") );
out.print("<input type=\"button\" value=\"" + p
+ "\" onclick=\"javascript:popup_window('"
+ req.getContextPath() + "/tools/group-select-list?multiple="
+ multiple + "', 'group_popup');\" />");
if (multiple)
{
out.print("</td><td width=\"50%\" align=\"center\">");
out.print("<input type=\"button\" value=\""
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectGroupTag.removeSelected")
+ "\" onclick=\"javascript:removeSelected(window.document.epersongroup.group_ids);\"/>");
}
out.println("</td></tr></table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
}
| 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.webui.jsptag;
import java.io.File;
import java.io.FilenameFilter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.XMLUtil;
import org.dspace.core.ConfigurationManager;
import org.w3c.dom.Document;
/**
* A Tag to load and display controlled vocabularies
*
* @author Miguel Ferreira
* @version $Revision: 5845 $
*
*/
public class ControlledVocabularyTag extends TagSupport
{
// path to the jsp that outputs the results of this tag
private static final String CONTROLLEDVOCABULARY_JSPTAG = "/controlledvocabulary/controlledvocabularyTag.jsp";
// the log
private static Logger log = Logger.getLogger(ControlledVocabularyTag.class);
// a tag attribute that contains the words used to trim the vocabulary tree
private String filter;
// a tag attribute that activates multiple selection of vocabulary terms
private boolean allowMultipleSelection;
// a tag attribute that specifies the vocabulary to be displayed
private String vocabulary;
// an hashtable containing all the loaded vocabularies
public Map<String, Document> controlledVocabularies;
/**
* Process tag
*/
public int doStartTag() throws JspException
{
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
String vocabulariesPath = ConfigurationManager
.getProperty("dspace.dir")
+ "/config/controlled-vocabularies/";
String addonBaseDirectory = pageContext.getServletContext()
.getRealPath("")
+ "/controlledvocabulary/";
String vocabularyPrunningXSLT = addonBaseDirectory
+ "vocabularyprune.xsl";
String controlledVocabulary2HtmlXSLT = addonBaseDirectory
+ "vocabulary2html.xsl";
// Load vocabularies on startup
controlledVocabularies = (Map<String, Document>) pageContext.getServletContext().getAttribute("controlledvocabulary.controlledVocabularies");
if (controlledVocabularies == null)
{
controlledVocabularies = loadControlledVocabularies(vocabulariesPath);
pageContext.getServletContext().setAttribute("controlledvocabulary.controlledVocabularies", controlledVocabularies);
}
try
{
Map<String, Document> prunnedVocabularies = needsFiltering() ?
filterVocabularies(controlledVocabularies, vocabularyPrunningXSLT)
: controlledVocabularies;
String html = "";
if (vocabulary != null && !vocabulary.equals(""))
{
html = renderVocabularyAsHTML(prunnedVocabularies.get(vocabulary + ".xml"),
controlledVocabulary2HtmlXSLT,
isAllowMultipleSelection(), request.getContextPath());
}
else
{
html = renderVocabulariesAsHTML(prunnedVocabularies,
controlledVocabulary2HtmlXSLT,
isAllowMultipleSelection(), request.getContextPath());
}
request.getSession().setAttribute(
"controlledvocabulary.vocabularyHTML", html);
pageContext.include(CONTROLLEDVOCABULARY_JSPTAG);
}
catch (Exception e)
{
log.warn("Exception", e);
}
return SKIP_BODY;
}
/**
* End processing tag
*/
public int doEndTag()
{
return EVAL_PAGE;
}
/**
* Do we gave a filter to apply to the controlled vocabularies?
*
* @return true if a filter was provided.
*/
private boolean needsFiltering()
{
return getFilter() != null && getFilter().length() > 0;
}
/**
* Converts a XML Vocabulary to a HTML tree
*
* @param vocabularies
* A hashtable with all the XML taxonomies/vocabularies loaded as
* values
* @param xslt
* the filename of the stylesheet to apply the XML taxonomies
* @param allowMultipleSelection
* include checkboxes next to the taxonomy terms
* @param contextPath
* The context path
* @return the HTML that represents the vocabularies
*/
private String renderVocabulariesAsHTML(Map<String, Document> vocabularies,
String xslt, boolean allowMultipleSelection, String contextPath)
{
StringBuilder result = new StringBuilder();
Iterator<Document> iter = vocabularies.values().iterator();
while (iter.hasNext())
{
Document controlledVocabularyXML = iter.next();
result.append(renderVocabularyAsHTML(controlledVocabularyXML, xslt,
allowMultipleSelection, contextPath));
}
return result.toString();
}
/**
* Applies a filter to the vocabularies, i.e. it prunes the trees by
* removing all the branches that do not contain the words in the filter.
*
* @param vocabularies
* A hashtable with all the XML taxonomies/vocabularies loaded as
* values
* @param vocabularyPrunningXSLT
* the filename of the stylesheet that trimms the taxonomies
* @return An hashtable with all the filtered vocabularies
*/
private Map<String, Document> filterVocabularies(Map<String, Document> vocabularies, String vocabularyPrunningXSLT)
{
Map<String, Document> prunnedVocabularies = new HashMap<String, Document>();
for (Map.Entry<String, Document> entry : vocabularies.entrySet())
{
prunnedVocabularies.put(entry.getKey(), filterVocabulary(entry.getValue(), vocabularyPrunningXSLT, getFilter()));
}
return prunnedVocabularies;
}
/**
* Renders a taxonomy as HTML by applying a stylesheet.
*
* @param vocabulary
* The XML document representing a taxonomy
* @param controlledVocabulary2HtmlXSLT
* The filename of the stylesheet that converts the taxonomy to
* HTML
* @param allowMultipleSelection
* include checkboxes next to the taxonomy terms
* @param contextPath
* The context path
* @return the provided taxonomy as HTML.
*/
public String renderVocabularyAsHTML(Document vocabulary,
String controlledVocabulary2HtmlXSLT,
boolean allowMultipleSelection, String contextPath)
{
if (vocabulary == null)
{
return "";
}
String result = "";
try
{
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("allowMultipleSelection", allowMultipleSelection ? "yes" : "no");
parameters.put("contextPath", contextPath);
result = XMLUtil.transformDocumentAsString(vocabulary, parameters, controlledVocabulary2HtmlXSLT);
}
catch (Exception e)
{
log.error("Error rendering HTML", e);
}
return result;
}
/**
* Applies a filter to the provided vocabulary, i.e. it prunes the tree by
* removing all the branches that do not contain the words in the filter.
*
* @param vocabulary
* The vocabulary to be trimmed
* @param vocabularyPrunningXSLT
* The filename of the stylesheet that trims the vocabulary
* @param filter
* The filter to be applied
* @return The trimmed vocabulary.
*/
public Document filterVocabulary(Document vocabulary, String vocabularyPrunningXSLT, String filter)
{
if (vocabulary == null)
{
return null;
}
try
{
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("filter", filter);
return XMLUtil.transformDocument(vocabulary, parameters, vocabularyPrunningXSLT);
}
catch (Exception e)
{
log.error("Error filtering vocabulary", e);
return null;
}
}
/**
* Loads into memory all the vocabularies found in the given directory. All
* files with .xml extension are considered to be controlled vocabularies.
*
* @param directory
* where the files are positioned
* @return an hashtable with the filenames of the vocabularies as keys and
* the XML documents representing the vocabularies as values.
*/
private static Map<String, Document> loadControlledVocabularies(String directory)
{
Map<String, Document> controlledVocabularies = new HashMap<String, Document>();
File dir = new File(directory);
FilenameFilter filter = new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".xml");
}
};
String[] children = dir.list(filter);
if (children != null && children.length > 0)
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
try
{
Document controlledVocabulary = XMLUtil.loadXML(directory + filename);
controlledVocabularies.put(filename, controlledVocabulary);
log.warn("Loaded vocabulary: " + filename);
}
catch (Exception e)
{
log.warn("Failed to load vocabulary from " + filename, e);
}
}
}
else
{
log.warn("Could not find any vocabularies...");
}
return controlledVocabularies;
}
/**
* Gets the filter provided as parameter to the tag
*
* @return the filter
*/
public String getFilter()
{
return filter;
}
/**
* Sets the filter
*
* @param filter
* the filter
*/
public void setFilter(String filter)
{
this.filter = filter;
}
/**
* Returns the value of the multiple selection parameter
*
* @return true if the multiple selection was selected
*/
public boolean isAllowMultipleSelection()
{
return allowMultipleSelection;
}
/**
* Defines if we want to be able to select multiple terms of the taxonomy
*
* @param allowMultipleSelection
* true if we want to be able to select more than on term
*/
public void setAllowMultipleSelection(boolean allowMultipleSelection)
{
this.allowMultipleSelection = allowMultipleSelection;
}
/**
* Gets the name of the vocabulary to be displayed
*
* @return the name of the vocabulary
*/
public String getVocabulary()
{
return vocabulary;
}
/**
* Sets the name of the vocabulary to be displayed. If no name is provided,
* all vocabularies loaded will be rendered to the output
*
* @param vocabulary
* the name of the vocabulary to be selected
*/
public void setVocabulary(String vocabulary)
{
this.vocabulary = vocabulary;
}
}
| 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.webui.jsptag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Tag for including a "sidebar" - a column on the right-hand side of the page.
* Must be used within a dspace:layout tag.
*
* @author Peter Breton
* @version $Revision: 5845 $
*/
public class SidebarTag extends BodyTagSupport
{
public SidebarTag()
{
super();
}
public int doAfterBody() throws JspException
{
LayoutTag tag = (LayoutTag) TagSupport.findAncestorWithClass(this,
LayoutTag.class);
if (tag == null)
{
throw new JspException(
"Sidebar tag must be in an enclosing Layout tag");
}
tag.setSidebar(getBodyContent().getString());
return SKIP_BODY;
}
}
| 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.webui.jsptag;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.content.DCDate;
/**
* Date rendering tag for DCDates. Takes two parameter - "date", a DCDate, and
* "notime", which, if present, means the date is rendered without the time
*
* @author Robert Tansley
* @version $Revision: 5845 $
*/
public class DateTag extends TagSupport
{
/** The date to display */
private transient DCDate date;
/** Display the time? */
private boolean displayTime = true;
private static final long serialVersionUID = 6665825578727713535L;
/**
* Get the date
*
* @return the date to display
*/
public DCDate getDate()
{
return date;
}
/**
* Set the date
*
* @param d
* the date to display
*/
public void setDate(DCDate d)
{
date = d;
}
/**
* Get the "don't display the time" flag
*
* @return the date to display
*/
public String getNotime()
{
// Note inverse of internal flag
return (displayTime ? "false" : "true");
}
/**
* Set the "don't display the time" flag
*
* @param dummy
* can be anything - always sets the flag if present
*/
public void setNotime(String dummy)
{
displayTime = false;
}
public int doStartTag() throws JspException
{
String toDisplay = UIUtil.displayDate(date, displayTime, true, (HttpServletRequest)pageContext.getRequest());
try
{
pageContext.getOut().print(toDisplay);
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
}
| 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.webui.jsptag;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/**
* <p>
* JSP tag for displaying a preview version of an item. For this tag to
* output anything, the preview feature must be activated in DSpace.
* </p>
*
* @author Scott Yeadon
* @version $Revision: 5845 $
*/
public class ItemPreviewTag extends TagSupport
{
/** Item to display */
private transient Item item;
private static final long serialVersionUID = -5535762797556685631L;
public ItemPreviewTag()
{
super();
}
public int doStartTag() throws JspException
{
if (!ConfigurationManager.getBooleanProperty("webui.preview.enabled"))
{
return SKIP_BODY;
}
try
{
showPreview();
}
catch (SQLException sqle)
{
throw new JspException(sqle);
}
catch (IOException ioe)
{
throw new JspException(ioe);
}
return SKIP_BODY;
}
public void setItem(Item itemIn)
{
item = itemIn;
}
private void showPreview() throws SQLException, IOException
{
JspWriter out = pageContext.getOut();
// Only shows 1 preview image at the moment (the first encountered) regardless
// of the number of bundles/bitstreams of this type
Bundle[] bundles = item.getBundles("BRANDED_PREVIEW");
if (bundles.length > 0)
{
Bitstream[] bitstreams = bundles[0].getBitstreams();
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
out.println("<br/><p align=\"center\">");
out.println("<img src=\""
+ request.getContextPath() + "/retrieve/"
+ bitstreams[0].getID() + "/"
+ UIUtil.encodeBitstreamName(bitstreams[0].getName(),
Constants.DEFAULT_ENCODING)
+ "\"/>");
// Currently only one metadata item supported. Only the first match is taken
String s = ConfigurationManager.getProperty("webui.preview.dc");
if (s != null)
{
DCValue[] dcValue;
int i = s.indexOf('.');
if (i == -1)
{
dcValue = item.getDC(s, Item.ANY, Item.ANY);
}
else
{
dcValue = item.getDC(s.substring(0,1), s.substring(i + 1), Item.ANY);
}
if (dcValue.length > 0)
{
out.println("<br/>" + dcValue[0].value);
}
}
out.println("</p>");
}
}
public void release()
{
item = 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/
*/
/*
* Made by Dimitri Surinx
* Hasselt University
* Class to generate the recent submissions list
*/
package proj.oceandocs.components;
import org.dspace.content.Item;
import java.sql.*;
import java.util.List;
import org.dspace.core.Context;
public class RecentSubm {
public static String GenerateHTML(Context context, int amount,String contextPath) throws SQLException{
String layout = "";
List<String> result;
String citation="";
for(int i = 0;i<amount;i++){
int latestId = Item.latestAdditionsId(context)[i];
if(latestId != 0){
layout+="<tr><td class=\"latestLayout\">";
//String handle = Item.getHandleMod(context,latestId);
layout += "<a href=\"" + contextPath + "/handle/"+ Item.getHandleMod(context,latestId) +"\">";
result = Item.latestAdditionsText(context,latestId,"title","");
if(!result.isEmpty())
layout += result.get(0);
layout +="</a>";
result = Item.latestAdditionsText(context,latestId,"identifier","citation");
if(!result.isEmpty())
citation = result.get(0);
else
citation = "";
if(citation != null && !citation.equals("")){
layout +="<div>" + citation +"</div>";
}
boolean haveauthors = false;
result = Item.latestAdditionsText(context,latestId,"contributor","author");
layout+="<div style=\"margin-left: 0px\">";
for(int t=0;t < result.size(); t++)
{
if(t > 0)
layout += "; ";
layout += "<a href=\"" + contextPath + "/browse?type=author&value=" + result.get(t) +"\"> "+
result.get(t) + "</a>";
haveauthors = true;
}
result = Item.latestAdditionsText(context,latestId,"contributor","editor");
for(int t=0;t < result.size(); t++)
{
if(t > 0 || haveauthors)
layout += "; ";
layout += "<a href=\"" + contextPath + "/browse?type=author&value=" + result.get(t) +"\"> "+
result.get(t) + "</a>";
haveauthors = true;
}
result = Item.latestAdditionsText(context,latestId,"contributor","corpauthor");
for(int t=0;t < result.size(); t++)
{
if(t > 0 || haveauthors)
layout += "; ";
layout += "<a href=\"" + contextPath + "/browse?type=author&value=" + result.get(t) +"\"> "+
result.get(t) + "</a>";
haveauthors = true;
}
layout+="</div>";
layout +="</td><td align=\"right\" valign=\"top\" width=\"10px\" class=\"latestLayout\">";
result = Item.latestAdditionsText(context,latestId,"type","");
if(!result.isEmpty())
layout += result.get(0);
layout += "</td></tr>";
}
}
return layout;
}
} | 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/
*/
/*
* Made by Dimitri Surinx
* Hasselt University
* Class to generate a item list for a specified user/collection
* New types can be added on request (mail me at firstname.lastname@student.uhasselt.be)
* This class can also be used to pick up authority fields from a specified user
*/
package proj.oceandocs.components;
import org.dspace.content.Item;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import org.dspace.core.Context;
public class BrowseAC
{
// Show type
static public enum Type
{
AUTHOR, COLLECTION
}
// Generate the html for a given Type and a given parameter (for example: collection id)
public static String GenerateHTML(Context context, Type type, String param, String contextPath, String beginY, String endY) throws SQLException
{
// Pickup the metadata_field_id for a given element and a qualifier (from the metadatafieldregistry)
int autId = Item.returnId(context, "contributor", "author");
int citId = Item.returnId(context, "identifier", "citation");
int titleId = Item.returnId(context, "title", "");
int dateId = Item.returnId(context, "date", "issued");
int typeId = Item.returnId(context, "type", "");
boolean stop = false;
String typ = "";
//Get a vector with the IDs of the requested items
List<Integer> ids = GetIds(context, dateId, type, param, beginY, endY);
// actual HTML string
String result = "";
int currentYear = 0;
// Construct the html string
for (int i = 0; i < ids.size(); ++i)
{
String auth = "";
// pickup the metadata from the DB
List<String> authors = Item.latestAdditionsText(context, ids.get(i), autId, 0);
List<String> citations = Item.latestAdditionsText(context, ids.get(i), citId);
List<String> titles = Item.latestAdditionsText(context, ids.get(i), titleId);
List<String> dates = Item.latestAdditionsText(context, ids.get(i), dateId);
List<String> types = Item.latestAdditionsText(context, ids.get(i), typeId);
int year = getYear(dates.get(0));
// incase this items year differs from the last one, display a new year header
if (year != currentYear)
{
currentYear = year;
if (year != 0)
{
result += "</ul>";
}
result += "<h2 class=\"dateItem\" style=\"cursor: pointer;\" onclick=\"Effect.toggle('" + year + "', 'blind')\">" + year + "</h2><ul id=\"" + year + "\">";
}
// incase this items type differs from the last one, display a new type header
if (!typ.equals(types.get(0)))
{
typ = types.get(0);
result += "<li><h3>" + typ + "</h3></li>";
}
// display all authors
for (int j = 0; j < authors.size() && !stop; ++j)
{
if (j < (authors.size() - 1))
{
auth += "<a href=\"" + contextPath + "/browse?type=author&value=" + Item.latestAdditionsText(context, ids.get(i), "contributor", "author").get(0) + "\">" + Item.latestAdditionsText(context, ids.get(i), "contributor", "author").get(0) + "</a>; ";
}
else if (authors.get(j) == null)
{
stop = false;
}
else
{
auth += "<a href=\"" + contextPath + "/browse?type=author&value=" + Item.latestAdditionsText(context, ids.get(i), "contributor", "author").get(0) + "\">" + Item.latestAdditionsText(context, ids.get(i), "contributor", "author").get(0) + "</a> ";
}
}
// display the other important metadata
result += "<ul class=\"collectionListItem\"><li class=\"metadataFieldValue\" style=\"list-style-type: none;\">" + auth + " (" + year + ") <em>" + "<a href=\"" + contextPath + "/handle/" + Item.getHandleMod(context, ids.get(i)) + "\"/>" + titles.get(0) + "</a><br/>" + "</em>" + citations.get(0) + "</li></ul>";
}
// close the year tag!
if (currentYear != 0)
{
result += "</ul>";
}
return result;
}
// Extract a year from a string formed as followed (yyyy-mm-dd)
private static int getYear(String str)
{
return Integer.parseInt(str.substring(0, 4));
}
// picks up the authority field from a user
public static String pickupAuthorityFromAuthor(Context con, String authorName) throws SQLException
{
// String query = "SELECT authority FROM bi_2_dis WHERE value = ?";
// PreparedStatement statement = con.getDBConnection().prepareStatement(query);
// statement.setString(1, authorName);
// ResultSet rs = statement.executeQuery();
// while (rs.next())
// {
// return rs.getString("authority");
// }
return null;
}
// Get item ids from a given type and a parameter ( from example: collection, collectionid)
private static List<Integer> GetIds(Context context, int dateId, Type type, String param, String beginY, String endY) throws SQLException
{
String subQuery = null;
int typeId = Item.returnId(context, "type", "");
String begin = "";
String end = "";
begin += beginY + "-01-01";
end += endY + "-12-31";
// Different subqueries for different types
if (type == Type.COLLECTION)
{
subQuery = "(SELECT item_id FROM collection2item WHERE collection_id = ?) a";
}
else if (type == Type.AUTHOR)
{
subQuery = "(SELECT item_id FROM metadatavalue WHERE metadata_field_id = ? AND text_value = ?) a";
}
// Main query
String query = "SELECT item.item_id FROM item,handle, "
+ "(SELECT metadata_value_id ,metadatavalue.item_id,metadatavalue.text_value FROM metadatavalue WHERE metadatavalue.text_value >= ? AND metadatavalue.text_value <= ? AND metadata_field_id = ? "
+ "ORDER BY metadatavalue.text_value DESC) e, (SELECT item_id, metadatavalue.text_value FROM metadatavalue WHERE metadata_field_id = ?) g, " + subQuery + " WHERE g.item_id = item.item_id AND a.item_id = item.item_id AND item.item_id = e.item_id AND item.item_id = handle.resource_id AND "
+ "handle.resource_type_id = 2 AND in_archive AND NOT withdrawn ORDER BY e.text_value DESC, g.text_value";
List<Integer> ids = new ArrayList<Integer>();
PreparedStatement statement = context.getDBConnection().prepareStatement(query);
statement.setString(1, begin); // fill in boundries
statement.setString(2, end);
statement.setInt(3, dateId); // fill in dateId
statement.setInt(4, typeId); // fill in type id
// Fill in the given parameters depending on type, add custom types here incase needed!
if (type == Type.COLLECTION)
{
int col = Integer.parseInt(param);
statement.setInt(5, col);
}
else if (type == Type.AUTHOR)
{
int id = Item.returnId(context, "contributor", "author");
statement.setInt(5, id);
statement.setString(6, param);
}
ResultSet rs = statement.executeQuery();
int i = 0;
while (rs.next())
{
ids.add(rs.getInt("item_id"));
}
return ids;
}
}
| 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.sword;
import org.dspace.content.*;
import org.dspace.core.Context;
import org.dspace.core.ConfigurationManager;
import org.dspace.authorize.AuthorizeException;
import org.purl.sword.base.Deposit;
import org.purl.sword.base.SWORDErrorException;
import org.purl.sword.base.ErrorCodes;
import java.io.*;
import java.sql.SQLException;
public class ItemDepositor extends Depositor
{
private Item item;
public ItemDepositor(SWORDService swordService, DSpaceObject dso)
throws DSpaceSWORDException
{
super(swordService, dso);
if (!(dso instanceof Item))
{
throw new DSpaceSWORDException("You tried to initialise the item depositor with something" +
"other than an item object");
}
this.item = (Item) dso;
}
public DepositResult doDeposit(Deposit deposit) throws SWORDErrorException, DSpaceSWORDException
{
// get the things out of the service that we need
Context context = swordService.getContext();
SWORDConfiguration swordConfig = swordService.getSwordConfig();
SWORDUrlManager urlManager = swordService.getUrlManager();
// FIXME: the spec is unclear what to do in this situation. I'm going
// the throw a 415 (ERROR_CONTENT) until further notice
//
// determine if this is an acceptable file format
if (!swordConfig.isAcceptableContentType(context, deposit.getContentType(), item))
{
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT,
"Unacceptable content type in deposit request: " + deposit.getContentType());
}
// determine if this is an acceptable packaging type for the deposit
// if not, we throw a 415 HTTP error (Unsupported Media Type, ERROR_CONTENT)
if (!swordConfig.isSupportedMediaType(deposit.getPackaging(), this.item))
{
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT,
"Unacceptable packaging type in deposit request: " + deposit.getPackaging());
}
// Obtain the relevant ingester from the factory
SWORDIngester si = SWORDIngesterFactory.getInstance(context, deposit, item);
swordService.message("Loaded ingester: " + si.getClass().getName());
// do the deposit
DepositResult result = si.ingest(swordService, deposit, item);
swordService.message("Archive ingest completed successfully");
// if there's an item availalble, and we want to keep the original
// then do that
try
{
if (swordConfig.isKeepOriginal())
{
swordService.message("DSpace will store an original copy of the deposit file, " +
"as well as attaching it to the item");
// in order to be allowed to add the file back to the item, we need to ignore authorisations
// for a moment
boolean ignoreAuth = context.ignoreAuthorization();
context.setIgnoreAuthorization(true);
String bundleName = ConfigurationManager.getProperty("sword.bundle.name");
if (bundleName == null || "".equals(bundleName))
{
bundleName = "SWORD";
}
Bundle[] bundles = item.getBundles(bundleName);
Bundle swordBundle = null;
if (bundles.length > 0)
{
swordBundle = bundles[0];
}
if (swordBundle == null)
{
swordBundle = item.createBundle(bundleName);
}
String fn = swordService.getFilename(context, deposit, true);
Bitstream bitstream;
FileInputStream fis = null;
try
{
fis = new FileInputStream(deposit.getFile());
bitstream = swordBundle.createBitstream(fis);
}
finally
{
if (fis != null)
{
fis.close();
}
}
bitstream.setName(fn);
bitstream.setDescription("Original file deposited via SWORD");
BitstreamFormat bf = BitstreamFormat.findByMIMEType(context, deposit.getContentType());
if (bf != null)
{
bitstream.setFormat(bf);
}
bitstream.update();
swordBundle.update();
item.update();
swordService.message("Original package stored as " + fn + ", in item bundle " + swordBundle);
// now reset the context ignore authorisation
context.setIgnoreAuthorization(ignoreAuth);
// set the media link for the created item
result.setMediaLink(urlManager.getMediaLink(bitstream));
}
else
{
// set the media link for the created item using the archived version (since it's just a file)
result.setMediaLink(urlManager.getMediaLink(result.getBitstream()));
}
}
catch (SQLException e)
{
throw new DSpaceSWORDException(e);
}
catch (AuthorizeException e)
{
throw new DSpaceSWORDException(e);
}
catch (FileNotFoundException e)
{
throw new DSpaceSWORDException(e);
}
catch (IOException e)
{
throw new DSpaceSWORDException(e);
}
return result;
}
public void undoDeposit(DepositResult result) throws DSpaceSWORDException
{
try
{
SWORDContext sc = swordService.getSwordContext();
// obtain the bitstream's owning bundles and remove the bitstream
// from them. This will ensure that the bitstream is physically
// removed from the disk.
Bitstream bs = result.getBitstream();
Bundle[] bundles = bs.getBundles();
for (int i = 0; i < bundles.length; i++)
{
bundles[i].removeBitstream(bs);
bundles[i].update();
}
swordService.message("Removing temporary files from disk");
// abort the context, so no database changes are written
sc.abort();
swordService.message("Database changes aborted");
}
catch (IOException e)
{
//log.error("caught exception: ", e);
throw new DSpaceSWORDException(e);
}
catch (AuthorizeException e)
{
//log.error("authentication problem; caught exception: ", e);
throw new DSpaceSWORDException(e);
}
catch (SQLException e)
{
//log.error("caught exception: ", e);
throw new DSpaceSWORDException(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.sword;
import org.dspace.content.Bitstream;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.purl.sword.base.SWORDEntry;
import org.purl.sword.base.Deposit;
import org.purl.sword.atom.Author;
import org.purl.sword.atom.Contributor;
import org.purl.sword.atom.Generator;
/**
* Class to represent a DSpace Item as an ATOM Entry. This
* handles the objects in a default way, but the intention is
* for you to be able to extend the class with your own
* representation if necessary.
*
* @author Richard Jones
*
*/
public abstract class DSpaceATOMEntry
{
/** the SWORD ATOM entry which this class effectively decorates */
protected SWORDEntry entry;
/** the item this ATOM entry represents */
protected Item item = null;
/** The bitstream this ATOM entry represents */
protected Bitstream bitstream = null;
/** the deposit result */
protected DepositResult result = null;
/** sword service implementation */
protected SWORDService swordService;
/** the original deposit */
protected Deposit deposit = null;
/**
* Create a new atom entry object around the given service
*
* @param service
*/
protected DSpaceATOMEntry(SWORDService service)
{
this.swordService = service;
}
/**
* Reset all the internal variables of the class to their original values
*/
public void reset()
{
this.entry = new SWORDEntry();
this.item = null;
this.bitstream = null;
this.result = null;
this.deposit = null;
}
/**
* get the sword entry for the given dspace object. In this case, we should be
* responding to requests for the media link, so this method will throw an error
* unless the dspace object is an instance of the Bitstream
*
* @param dso
* @return
* @throws DSpaceSWORDException
*/
public SWORDEntry getSWORDEntry(DSpaceObject dso)
throws DSpaceSWORDException
{
// reset the object, just in case
this.reset();
// NOTE: initially this exists just for the purposes of responding to media-link
// requests, so should only ever respond to entries on Bitstreams
if (dso instanceof Bitstream)
{
this.bitstream = (Bitstream) dso;
}
else
{
throw new DSpaceSWORDException("Can only recover a sword entry for a bitstream via this method");
}
this.constructEntry();
return entry;
}
/**
* Construct the SWORDEntry object which represents the given
* item with the given handle. An argument as to whether this
* is a NoOp request is required because in that event the
* assigned identifier for the item will not be added to the
* SWORDEntry as it will be invalid.
*
* @param result the result of the deposit operation
* @param deposit the original deposit request
* @return the SWORDEntry for the item
*/
public SWORDEntry getSWORDEntry(DepositResult result, Deposit deposit)
throws DSpaceSWORDException
{
this.reset();
this.entry = new SWORDEntry();
this.item = result.getItem();
this.bitstream = result.getBitstream();
this.result = result;
this.deposit = deposit;
this.constructEntry();
return entry;
}
/**
* Construct the entry
*
* @throws DSpaceSWORDException
*/
protected void constructEntry()
throws DSpaceSWORDException
{
// set the generator
this.addGenerator();
// add the authors to the sword entry
this.addAuthors();
// add the category information to the sword entry
this.addCategories();
// add a content element to the sword entry
this.addContentElement();
// add a packaging element to the sword entry
this.addPackagingElement();
// add contributors (authors plus any other bits) to the sword entry
this.addContributors();
// add the identifier for the item, if the id is going
// to be valid by the end of the request
this.addIdentifier();
// add any appropriate links
this.addLinks();
// add the publish date
this.addPublishDate();
// add the rights information
this.addRights();
// add the summary of the item
this.addSummary();
// add the title of the item
this.addTitle();
// add the date on which the entry was last updated
this.addLastUpdatedDate();
// set the treatment
this.addTreatment();
}
/**
* Add deposit treatment text
*/
protected void addTreatment()
{
if (result != null)
{
entry.setTreatment(result.getTreatment());
}
}
/**
* add the generator field content
*/
protected void addGenerator()
{
boolean identify = ConfigurationManager.getBooleanProperty("sword.identify-version");
SWORDUrlManager urlManager = swordService.getUrlManager();
String softwareUri = urlManager.getGeneratorUrl();
if (identify)
{
Generator generator = new Generator();
generator.setUri(softwareUri);
generator.setVersion(SWORDProperties.VERSION);
entry.setGenerator(generator);
}
}
/**
* set the packaging format of the deposit
*/
protected void addPackagingElement()
{
if (deposit != null)
{
entry.setPackaging(deposit.getPackaging());
}
}
/**
* add the author names from the bibliographic metadata. Does
* not supply email addresses or URIs, both for privacy, and
* because the data is not so readily available in DSpace.
*
*/
protected void addAuthors()
{
if (deposit != null)
{
String username = this.deposit.getUsername();
Author author = new Author();
author.setName(username);
entry.addAuthors(author);
}
}
/**
* Add the list of contributors to the item. This will include
* the authors, and any other contributors that are supplied
* in the bibliographic metadata
*
*/
protected void addContributors()
{
if (deposit != null)
{
String obo = deposit.getOnBehalfOf();
if (obo != null)
{
Contributor cont = new Contributor();
cont.setName(obo);
entry.addContributor(cont);
}
}
}
/**
* Add all the subject classifications from the bibliographic
* metadata.
*
*/
abstract void addCategories() throws DSpaceSWORDException;
/**
* Set the content type that DSpace received. This is just
* "application/zip" in this default implementation.
*
*/
abstract void addContentElement() throws DSpaceSWORDException;
/**
* Add the identifier for the item. If the item object has
* a handle already assigned, this is used, otherwise, the
* passed handle is used. It is set in the form that
* they can be used to access the resource over http (i.e.
* a real URL).
*/
abstract void addIdentifier() throws DSpaceSWORDException;
/**
* Add links associated with this item.
*
*/
abstract void addLinks() throws DSpaceSWORDException;
/**
* Add the date of publication from the bibliographic metadata
*
*/
abstract void addPublishDate() throws DSpaceSWORDException;
/**
* Add rights information. This attaches an href to the URL
* of the item's licence file
*
*/
abstract void addRights() throws DSpaceSWORDException;
/**
* Add the summary/abstract from the bibliographic metadata
*
*/
abstract void addSummary() throws DSpaceSWORDException;
/**
* Add the title from the bibliographic metadata
*
*/
abstract void addTitle() throws DSpaceSWORDException;
/**
* Add the date that this item was last updated
*
*/
abstract void addLastUpdatedDate() throws DSpaceSWORDException;
}
| 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.sword;
/**
* Some URIs for DSpace specific errors which may be reported through the SWORDErrorException
*/
public interface DSpaceSWORDErrorCodes
{
/** if unpackaging the package fails */
public static final String UNPACKAGE_FAIL = SWORDProperties.SOFTWARE_URI + "/errors/UnpackageFail";
/** if the url of the request does not resolve to something meaningful */
public static final String BAD_URL = SWORDProperties.SOFTWARE_URI + "/errors/BadUrl";
/** if the media requested is unavailable */
public static final String MEDIA_UNAVAILABLE = SWORDProperties.SOFTWARE_URI + "/errors/MediaUnavailable";
/* additional codes */
/** Invalid package */
public static final String PACKAGE_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/PackageError";
/** Missing resources in package */
public static final String PACKAGE_VALIDATION_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/PackageValidationError";
/** Crosswalk error */
public static final String CROSSWALK_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/CrosswalkError";
/** Invalid collection for linking */
public static final String COLLECTION_LINK_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/CollectionLinkError";
/** Database or IO Error when installing new item */
public static final String REPOSITORY_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/RepositoryError";
}
| 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.sword;
import java.sql.SQLException;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
/**
* This class holds information about authenticated users (both the
* depositing user and the on-behalf-of user), and their associated
* DSpace Context objects.
*
* Since this class will be used to make authentication requests on
* both user types, it may hold up to 2 active DSpace Context objects
* at any one time
*
* WARNING: failure to use the contexts used in this class in the
* appropriate way may result in exceptions or data loss. Unless
* you are performing authentication processes, you should always
* access the context under which to deposit content into the archive
* from:
*
* getContext()
*
* and not from any of the other context retrieval methods in this
* class
*
* @author Richard Jones
*
*/
public class SWORDContext
{
/** The primary authenticated user for the request */
private EPerson authenticated = null;
/** The onBehalfOf user for the request */
private EPerson onBehalfOf = null;
/** The primary context, representing the on behalf of user if exists, and the authenticated user if not */
private Context context;
/** the context for the authenticated user, which may not, therefore, be the primary context also */
private Context authenticatorContext;
/**
* @return the authenticated user
*/
public EPerson getAuthenticated()
{
return authenticated;
}
/**
* @param authenticated the eperson to set
*/
public void setAuthenticated(EPerson authenticated)
{
this.authenticated = authenticated;
}
/**
* @return the onBehalfOf user
*/
public EPerson getOnBehalfOf()
{
return onBehalfOf;
}
/**
* @param onBehalfOf the eperson to set
*/
public void setOnBehalfOf(EPerson onBehalfOf)
{
this.onBehalfOf = onBehalfOf;
}
/**
* Returns the most appropriate context for operations on the
* database. This is the on-behalf-of user's context if the
* user exists, or the authenticated user's context otherwise
*
* @return
*/
public Context getContext()
{
return context;
}
public void setContext(Context context)
{
this.context = context;
}
/**
* Get the context of the user who authenticated. This should only be
* used for authentication purposes. If there is an on-behalf-of user,
* that context should be used to write database changes. Use:
*
* getContext()
*
* on this class instead.
*
* @return
*/
public Context getAuthenticatorContext()
{
return authenticatorContext;
}
public void setAuthenticatorContext(Context authenticatorContext)
{
this.authenticatorContext = authenticatorContext;
}
/**
* Get the context of the on-behalf-of user. This method should only
* be used for authentication purposes. In all other cases, use:
*
* getContext()
*
* on this class instead. If there is no on-behalf-of user, this
* method will return null.
*
* @return
*/
public Context getOnBehalfOfContext()
{
// return the obo context if this is an obo deposit, else return null
if (this.onBehalfOf != null)
{
return context;
}
return null;
}
/**
* Abort all of the contexts held by this class. No changes will
* be written to the database
*/
public void abort()
{
// abort both contexts
if (context != null && context.isValid())
{
context.abort();
}
if (authenticatorContext != null && authenticatorContext.isValid())
{
authenticatorContext.abort();
}
}
/**
* Commit the primary context held by this class, and abort the authenticated
* user's context if it is different. This ensures that only changes written
* through the appropriate user's context is persisted, and all other
* operations are flushed. You should, in general, not try to commit the contexts directly
* when using the sword api.
*
* @throws DSpaceSWORDException
*/
public void commit()
throws DSpaceSWORDException
{
try
{
// commit the primary context
if (context != null && context.isValid())
{
context.commit();
}
// the secondary context is for filtering permissions by only, and is
// never committed, so we abort here
if (authenticatorContext != null && authenticatorContext.isValid())
{
authenticatorContext.abort();
}
}
catch (SQLException e)
{
throw new DSpaceSWORDException(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.sword;
import org.dspace.content.DSpaceObject;
import org.purl.sword.base.Deposit;
import org.purl.sword.base.SWORDErrorException;
/**
* Interface behind which can be implemented ingest mechanisms
* for SWORD deposit requests. Instances of this class should
* be obtained via the SWORDIngesterFactory class.
*
* @author Richard Jones
*
*/
public interface SWORDIngester
{
/**
* Ingest the package as described in the given Deposit object
* within the given DSpace Context
*
* @param deposit
* @return the result of the deposit
* @throws DSpaceSWORDException
*/
DepositResult ingest(SWORDService service, Deposit deposit, DSpaceObject target) throws DSpaceSWORDException, SWORDErrorException;
}
| 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.sword;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.core.ConfigurationManager;
import org.dspace.handle.HandleManager;
import org.purl.sword.atom.Content;
import org.purl.sword.atom.ContentType;
import org.purl.sword.atom.InvalidMediaTypeException;
import org.purl.sword.atom.Link;
import org.purl.sword.atom.Rights;
import org.purl.sword.atom.Summary;
import org.purl.sword.atom.Title;
import org.apache.log4j.Logger;
import java.sql.SQLException;
/**
* @author Richard Jones
*
* Class to generate an ATOM Entry document for a DSpace Item
*/
public class ItemEntryGenerator extends DSpaceATOMEntry
{
/** logger */
private static Logger log = Logger.getLogger(ItemEntryGenerator.class);
protected ItemEntryGenerator(SWORDService service)
{
super(service);
}
/**
* Add all the subject classifications from the bibliographic
* metadata.
*
*/
protected void addCategories()
{
DCValue[] dcv = item.getMetadata("dc.subject.*");
if (dcv != null)
{
for (int i = 0; i < dcv.length; i++)
{
entry.addCategory(dcv[i].value);
}
}
}
/**
* Set the content type that DSpace received. This is just
* "application/zip" in this default implementation.
*
*/
protected void addContentElement()
throws DSpaceSWORDException
{
// get the things we need out of the service
SWORDUrlManager urlManager = swordService.getUrlManager();
try
{
if (!this.deposit.isNoOp())
{
String handle = "";
if (item.getHandle() != null)
{
handle = item.getHandle();
}
if (handle != null && !"".equals(handle))
{
boolean keepOriginal = ConfigurationManager.getBooleanProperty("sword.keep-original-package");
String swordBundle = ConfigurationManager.getProperty("sword.bundle.name");
if (swordBundle == null || "".equals(swordBundle))
{
swordBundle = "SWORD";
}
// if we keep the original, then expose this as the content element
// otherwise, expose the unpacked version
if (keepOriginal)
{
Content con = new Content();
Bundle[] bundles = item.getBundles(swordBundle);
if (bundles.length > 0)
{
Bitstream[] bss = bundles[0].getBitstreams();
for (int i = 0; i < bss.length; i++)
{
BitstreamFormat bf = bss[i].getFormat();
String format = "application/octet-stream";
if (bf != null)
{
format = bf.getMIMEType();
}
con.setType(format);
// calculate the bitstream link.
String bsLink = urlManager.getBitstreamUrl(bss[i]);
con.setSource(bsLink);
entry.setContent(con);
}
}
}
else
{
// return a link to the DSpace entry page
Content content = new Content();
content.setType("text/html");
content.setSource(HandleManager.getCanonicalForm(handle));
entry.setContent(content);
}
}
}
}
catch (InvalidMediaTypeException e)
{
// do nothing; we'll live without the content type declaration!
}
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Add the identifier for the item. If the item object has
* a handle already assigned, this is used, otherwise, the
* passed handle is used. It is set in the form that
* they can be used to access the resource over http (i.e.
* a real URL).
*/
protected void addIdentifier()
{
// it's possible that the item hasn't been assigned a handle yet
if (!this.deposit.isNoOp())
{
String handle = "";
if (item.getHandle() != null)
{
handle = item.getHandle();
}
if (handle != null && !"".equals(handle))
{
entry.setId(HandleManager.getCanonicalForm(handle));
return;
}
}
// if we get this far, then we just use the dspace url as the
// property
String cfg = ConfigurationManager.getProperty("dspace.url");
entry.setId(cfg);
// FIXME: later on we will maybe have a workflow page supplied
// by the sword interface?
}
/**
* Add links associated with this item.
*
*/
protected void addLinks()
throws DSpaceSWORDException
{
SWORDUrlManager urlManager = swordService.getUrlManager();
try
{
// if there is no handle, we can't generate links
String handle = "";
if (item.getHandle() != null)
{
handle = item.getHandle();
}
else
{
return;
}
// link to all the files in the item
Bundle[] bundles = item.getBundles("ORIGINAL");
for (int i = 0; i < bundles.length ; i++)
{
Bitstream[] bss = bundles[i].getBitstreams();
for (int j = 0; j < bss.length; j++)
{
Link link = new Link();
String url = urlManager.getBitstreamUrl(bss[j]);
link.setHref(url);
link.setRel("part");
BitstreamFormat bsf = bss[j].getFormat();
if (bsf != null)
{
link.setType(bsf.getMIMEType());
}
entry.addLink(link);
}
}
// link to the item splash page
Link splash = new Link();
splash.setHref(HandleManager.getCanonicalForm(handle));
splash.setRel("alternate");
splash.setType("text/html");
entry.addLink(splash);
}
catch (SQLException e)
{
throw new DSpaceSWORDException(e);
}
}
/**
* Add the date of publication from the bibliographic metadata
*
*/
protected void addPublishDate()
{
DCValue[] dcv = item.getMetadata("dc.date.issued");
if (dcv != null && dcv.length == 1)
{
entry.setPublished(dcv[0].value);
}
}
/**
* Add rights information. This attaches an href to the URL
* of the item's licence file
*
*/
protected void addRights()
throws DSpaceSWORDException
{
SWORDUrlManager urlManager = swordService.getUrlManager();
try
{
String handle = this.item.getHandle();
// if there's no handle, we can't give a link
if (handle == null || "".equals(handle))
{
return;
}
String base = ConfigurationManager.getProperty("dspace.url");
// if there's no base URL, we are stuck
if (base == null)
{
return;
}
StringBuilder rightsString = new StringBuilder();
Bundle[] bundles = item.getBundles("LICENSE");
for (int i = 0; i < bundles.length; i++)
{
Bitstream[] bss = bundles[i].getBitstreams();
for (int j = 0; j < bss.length; j++)
{
String url = urlManager.getBitstreamUrl(bss[j]);
rightsString.append(url + " ");
}
}
Rights rights = new Rights();
rights.setContent(rightsString.toString());
rights.setType(ContentType.TEXT);
entry.setRights(rights);
}
catch (SQLException e)
{
throw new DSpaceSWORDException(e);
}
}
/**
* Add the summary/abstract from the bibliographic metadata
*
*/
protected void addSummary()
{
DCValue[] dcv = item.getMetadata("dc.description.abstract");
if (dcv != null)
{
for (int i = 0; i < dcv.length; i++)
{
Summary summary = new Summary();
summary.setContent(dcv[i].value);
summary.setType(ContentType.TEXT);
entry.setSummary(summary);
}
}
}
/**
* Add the title from the bibliographic metadata
*
*/
protected void addTitle()
{
DCValue[] dcv = item.getMetadata("dc.title");
if (dcv != null)
{
for (int i = 0; i < dcv.length; i++)
{
Title title = new Title();
title.setContent(dcv[i].value);
title.setType(ContentType.TEXT);
entry.setTitle(title);
}
}
}
/**
* Add the date that this item was last updated
*
*/
protected void addLastUpdatedDate()
{
String config = ConfigurationManager.getProperty("sword.updated.field");
DCValue[] dcv = item.getMetadata(config);
if (dcv != null && dcv.length == 1)
{
DCDate dcd = new DCDate(dcv[0].value);
entry.setUpdated(dcd.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.sword;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.purl.sword.atom.Content;
import org.purl.sword.atom.ContentType;
import org.purl.sword.atom.InvalidMediaTypeException;
import org.purl.sword.atom.Link;
import org.purl.sword.atom.Rights;
import org.purl.sword.atom.Title;
import org.apache.log4j.Logger;
import java.sql.SQLException;
/**
* @author Richard Jones
*
* Class to generate ATOM Entry documents for DSpace Bitstreams
*/
public class BitstreamEntryGenerator extends DSpaceATOMEntry
{
/** logger */
private static Logger log = Logger.getLogger(BitstreamEntryGenerator.class);
/**
* Create a new ATOM Entry generator which can provide a SWORD Entry for
* a bitstream
*
* @param service
*/
protected BitstreamEntryGenerator(SWORDService service)
{
super(service);
log.debug("Create new instance of BitstreamEntryGenerator");
}
/**
* Add all the subject classifications from the bibliographic
* metadata.
*
*/
protected void addCategories()
{
// do nothing
}
/**
* Set the content type that DSpace received.
*
*/
protected void addContentElement()
throws DSpaceSWORDException
{
try
{
// get the things we need out of the service
SWORDUrlManager urlManager = swordService.getUrlManager();
// if this is a deposit which is no op we can't do anything here
if (this.deposit != null && this.deposit.isNoOp())
{
return;
}
String bsurl = urlManager.getBitstreamUrl(this.bitstream);
BitstreamFormat bf = this.bitstream.getFormat();
String format = "application/octet-stream";
if (bf != null)
{
format = bf.getMIMEType();
}
Content con = new Content();
con.setType(format);
con.setSource(bsurl);
entry.setContent(con);
log.debug("Adding content element with url=" + bsurl);
}
catch (InvalidMediaTypeException e)
{
log.error("caught and swallowed exception: ", e);
// do nothing; we'll live without the content type declaration!
}
}
/**
* Add the identifier for the item. If the item object has
* a handle already assigned, this is used, otherwise, the
* passed handle is used. It is set in the form that
* they can be used to access the resource over http (i.e.
* a real URL).
*/
protected void addIdentifier()
throws DSpaceSWORDException
{
// if this is a deposit which is no op we can't do anything here
if (this.deposit != null && this.deposit.isNoOp())
{
// just use the dspace url as the
// property
String cfg = ConfigurationManager.getProperty("dspace.url");
entry.setId(cfg);
return;
}
SWORDUrlManager urlManager = swordService.getUrlManager();
// for a bitstream, we just use the url for the bitstream
// as the identifier
String bsurl = urlManager.getBitstreamUrl(this.bitstream);
entry.setId(bsurl);
log.debug("Added identifier for bitstream with url=" + bsurl);
return;
// FIXME: later on we will maybe have a workflow page supplied
// by the sword interface?
}
/**
* Add links associated with this item.
*
*/
protected void addLinks()
throws DSpaceSWORDException
{
// if this is a deposit which is no op we can't do anything here
if (this.deposit != null && this.deposit.isNoOp())
{
return;
}
// get the things we need out of the service
SWORDUrlManager urlManager = swordService.getUrlManager();
String bsurl = urlManager.getBitstreamUrl(this.bitstream);
BitstreamFormat bf = this.bitstream.getFormat();
String format = "application/octet-stream";
if (bf != null)
{
format = bf.getMIMEType();
}
Link link = new Link();
link.setType(format);
link.setHref(bsurl);
link.setRel("alternate");
entry.addLink(link);
log.debug("Added link entity to entry for url " + bsurl);
}
/**
* Add the date of publication from the bibliographic metadata
*
*/
protected void addPublishDate()
{
// do nothing
}
/**
* Add rights information. This attaches an href to the URL
* of the item's licence file
*
*/
protected void addRights()
throws DSpaceSWORDException
{
try
{
// work our way up to the item
Bundle[] bundles = this.bitstream.getBundles();
if (bundles.length == 0)
{
log.error("Found orphaned bitstream: " + bitstream.getID());
throw new DSpaceSWORDException("Orphaned bitstream discovered");
}
Item[] items = bundles[0].getItems();
if (items.length == 0)
{
log.error("Found orphaned bundle: " + bundles[0].getID());
throw new DSpaceSWORDException("Orphaned bundle discovered");
}
Item item = items[0];
// now get the licence out of the item
SWORDUrlManager urlManager = swordService.getUrlManager();
StringBuilder rightsString = new StringBuilder();
Bundle[] lbundles = item.getBundles("LICENSE");
for (int i = 0; i < lbundles.length; i++)
{
Bitstream[] bss = lbundles[i].getBitstreams();
for (int j = 0; j < bss.length; j++)
{
String url = urlManager.getBitstreamUrl(bss[j]);
rightsString.append(url + " ");
}
}
Rights rights = new Rights();
rights.setContent(rightsString.toString());
rights.setType(ContentType.TEXT);
entry.setRights(rights);
log.debug("Added rights entry to entity");
}
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Add the summary/abstract from the bibliographic metadata
*
*/
protected void addSummary()
{
// do nothing
}
/**
* Add the title from the bibliographic metadata
*
*/
protected void addTitle()
{
Title title = new Title();
title.setContent(this.bitstream.getName());
title.setType(ContentType.TEXT);
entry.setTitle(title);
log.debug("Added title to entry");
}
/**
* Add the date that this item was last updated
*
*/
protected void addLastUpdatedDate()
{
// do nothing
}
}
| 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.sword;
import org.dspace.core.Context;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.authenticate.AuthenticationMethod;
/**
* This class offers a thin wrapper for the default DSpace
* authentication module for the SWORD implementation
*
* @author Richard Jones
*
*/
public class SWORDAuthentication
{
/**
* Does the given username and password authenticate for the
* given DSpace Context?
*
* @param context
* @param un
* @param pw
* @return true if yes, false if not
*/
public boolean authenticates(Context context, String un, String pw)
{
int auth = AuthenticationManager.authenticate(context, un, pw, null, null);
if (auth == AuthenticationMethod.SUCCESS)
{
return true;
}
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.sword;
import org.purl.sword.base.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Community;
import org.apache.log4j.Logger;
public class CommunityCollectionGenerator extends ATOMCollectionGenerator
{
private static Logger log = Logger.getLogger(CommunityCollectionGenerator.class);
public CommunityCollectionGenerator(SWORDService service)
{
super(service);
log.debug("Created instance of CommunityCollectionGenerator");
}
public Collection buildCollection(DSpaceObject dso)
throws DSpaceSWORDException
{
if (!(dso instanceof Community))
{
log.error("buildCollection passed something other than a Community object");
throw new DSpaceSWORDException("Incorrect ATOMCollectionGenerator instantiated");
}
// get the things we need out of the service
SWORDConfiguration swordConfig = swordService.getSwordConfig();
SWORDUrlManager urlManager = swordService.getUrlManager();
Community com = (Community) dso;
Collection scol = new Collection();
// prepare the parameters to be put in the sword collection
String location = urlManager.getDepositLocation(com);
scol.setLocation(location);
// collection title is just the community name
String title = com.getMetadata("name");
if (title != null && !"".equals(title))
{
scol.setTitle(title);
}
// FIXME: the community has no obvious licence
// the collection policy is the licence to which the collection adheres
// String collectionPolicy = col.getLicense();
// abstract is the short description of the collection
String dcAbstract = com.getMetadata("short_description");
if (dcAbstract != null && !"".equals(dcAbstract))
{
scol.setAbstract(dcAbstract);
}
// do we support mediated deposit
scol.setMediation(swordConfig.isMediated());
// NOTE: for communities, there are no MIME types that it accepts.
// the list of mime types that we accept
// offer up the collections from this item as deposit targets
String subService = urlManager.constructSubServiceUrl(com);
scol.setService(subService);
log.debug("Created ATOM Collection for DSpace Community");
return scol;
}
}
| 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.sword;
import org.dspace.core.Context;
import org.dspace.core.PluginManager;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.purl.sword.base.Deposit;
import org.purl.sword.base.SWORDErrorException;
import org.purl.sword.base.ErrorCodes;
/**
* Factory class which will mint objects conforming to the
* SWORDIngester interface.
*
* @author Richard Jones
*
*/
public class SWORDIngesterFactory
{
/**
* Generate an object which conforms to the SWORDIngester interface.
* This Factory method may use the given DSpace context and the given
* SWORD Deposit request to decide on the most appropriate implementation
* of the interface to return.
*
* To configure how this method will respond, configure the package ingester
* for the appropriate media types and defaults. See the sword configuration
* documentation for more details.
*
* @param context
* @param deposit
* @return
* @throws DSpaceSWORDException
*/
public static SWORDIngester getInstance(Context context, Deposit deposit, DSpaceObject dso)
throws DSpaceSWORDException, SWORDErrorException
{
if (dso instanceof Collection)
{
SWORDIngester ingester = (SWORDIngester) PluginManager.getNamedPlugin(SWORDIngester.class, deposit.getPackaging());
if (ingester == null)
{
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT, "No ingester configured for this package type");
}
return ingester;
}
else if (dso instanceof Item)
{
SWORDIngester ingester = (SWORDIngester) PluginManager.getNamedPlugin(SWORDIngester.class, "SimpleFileIngester");
if (ingester == null)
{
throw new DSpaceSWORDException("SimpleFileIngester is not configured in plugin manager");
}
return ingester;
}
throw new DSpaceSWORDException("No ingester could be found which works for this DSpace Object");
}
}
| 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.sword;
public interface SWORDProperties
{
/** The version of the SWORD service we are offering */
public static final String VERSION = "1.3";
public static final String SOFTWARE_URI = "http://www.dspace.org/ns/sword/1.3.1";
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.sword;
import org.purl.sword.base.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.apache.log4j.Logger;
import java.util.Map;
import java.util.List;
/**
* Class to generate ATOM Collection Elements which represent
* DSpace Collections
*
*/
public class CollectionCollectionGenerator extends ATOMCollectionGenerator
{
/** logger */
private static Logger log = Logger.getLogger(CollectionCollectionGenerator.class);
/**
* Construct an object taking the sword service instance an argument
* @param service
*/
public CollectionCollectionGenerator(SWORDService service)
{
super(service);
log.debug("Create new instance of CollectionCollectionGenerator");
}
/**
* Build the collection for the given DSpaceObject. In this implementation,
* if the object is not a DSpace COllection, it will throw an exception
* @param dso
* @return
* @throws DSpaceSWORDException
*/
public Collection buildCollection(DSpaceObject dso) throws DSpaceSWORDException
{
if (!(dso instanceof org.dspace.content.Collection))
{
log.error("buildCollection passed argument which is not of type Collection");
throw new DSpaceSWORDException("Incorrect ATOMCollectionGenerator instantiated");
}
// get the things we need out of the service
SWORDConfiguration swordConfig = swordService.getSwordConfig();
SWORDUrlManager urlManager = swordService.getUrlManager();
org.dspace.content.Collection col = (org.dspace.content.Collection) dso;
Collection scol = new Collection();
// prepare the parameters to be put in the sword collection
String location = urlManager.getDepositLocation(col);
// collection title is just its name
String title = col.getMetadata("name");
// the collection policy is the licence to which the collection adheres
String collectionPolicy = col.getLicense();
// FIXME: what is the treatment? Doesn't seem appropriate for DSpace
// String treatment = " ";
// abstract is the short description of the collection
String dcAbstract = col.getMetadata("short_description");
// we just do support mediation
boolean mediation = swordConfig.isMediated();
// load up the sword collection
scol.setLocation(location);
// add the title if it exists
if (title != null && !"".equals(title))
{
scol.setTitle(title);
}
// add the collection policy if it exists
if (collectionPolicy != null && !"".equals(collectionPolicy))
{
scol.setCollectionPolicy(collectionPolicy);
}
// FIXME: leave the treatment out for the time being,
// as there is no analogue
// scol.setTreatment(treatment);
// add the abstract if it exists
if (dcAbstract != null && !"".equals(dcAbstract))
{
scol.setAbstract(dcAbstract);
}
scol.setMediation(mediation);
List<String> accepts = swordService.getSwordConfig().getCollectionAccepts();
for (String accept : accepts)
{
scol.addAccepts(accept);
}
// add the accept packaging values
Map<String, Float> aps = swordConfig.getAcceptPackaging(col);
for (Map.Entry<String, Float> ap : aps.entrySet())
{
scol.addAcceptPackaging(ap.getKey(), ap.getValue());
}
// should we offer the items in the collection up as deposit
// targets?
boolean itemService = ConfigurationManager.getBooleanProperty("sword.expose-items");
if (itemService)
{
String subService = urlManager.constructSubServiceUrl(col);
scol.setService(subService);
}
log.debug("Created ATOM Collection for DSpace Collection");
return scol;
}
}
| 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.sword;
import java.io.FileInputStream;
import org.purl.sword.base.Deposit;
import org.purl.sword.base.SWORDErrorException;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.Context;
import org.dspace.authorize.AuthorizeException;
import java.sql.SQLException;
import java.io.IOException;
/**
* @author Richard Jones
*
* An implementation of the SWORDIngester interface for ingesting single
* files into a DSpace Item
*
*/
public class SimpleFileIngester implements SWORDIngester
{
/**
* perform the ingest using the given deposit object onto the specified
* target dspace object, using the sword service implementation
*
* @param service
* @param deposit
* @param target
* @return
* @throws DSpaceSWORDException
* @throws SWORDErrorException
*/
public DepositResult ingest(SWORDService service, Deposit deposit, DSpaceObject target)
throws DSpaceSWORDException, SWORDErrorException
{
try
{
if (!(target instanceof Item))
{
throw new DSpaceSWORDException("SimpleFileIngester can only be loaded for deposit onto DSpace Items");
}
Item item = (Item) target;
// now set the sword service
SWORDService swordService = service;
// get the things out of the service that we need
Context context = swordService.getContext();
SWORDUrlManager urlManager = swordService.getUrlManager();
Bundle[] bundles = item.getBundles("ORIGINAL");
Bundle original;
if (bundles.length > 0)
{
original = bundles[0];
}
else
{
original = item.createBundle("ORIGINAL");
}
Bitstream bs;
FileInputStream fis = null;
try
{
fis = new FileInputStream(deposit.getFile());
bs = original.createBitstream(fis);
}
finally
{
if (fis != null)
{
fis.close();
}
}
String fn = swordService.getFilename(context, deposit, false);
bs.setName(fn);
swordService.message("File created in item with filename " + fn);
BitstreamFormat bf = BitstreamFormat.findByMIMEType(context, deposit.getContentType());
if (bf != null)
{
bs.setFormat(bf);
}
// to do the updates, we need to ignore authorisation in the context
boolean ignoreAuth = context.ignoreAuthorization();
context.setIgnoreAuthorization(true);
bs.update();
original.update();
item.update();
// reset the ignore authorisation
context.setIgnoreAuthorization(ignoreAuth);
DepositResult result = new DepositResult();
result.setHandle(urlManager.getBitstreamUrl(bs));
result.setTreatment(this.getTreatment());
result.setBitstream(bs);
return result;
}
catch (SQLException e)
{
throw new DSpaceSWORDException(e);
}
catch (AuthorizeException e)
{
throw new DSpaceSWORDException(e);
}
catch (IOException e)
{
throw new DSpaceSWORDException(e);
}
}
/**
* Get the description of the treatment this class provides to the deposit
*
* @return
*/
private String getTreatment()
{
return "The file has been attached to the specified item";
}
}
| 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.sword;
import java.io.File;
import java.util.Date;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.packager.PackageIngester;
import org.dspace.content.packager.PackageParameters;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.PluginManager;
import org.dspace.handle.HandleManager;
import org.purl.sword.base.Deposit;
import org.purl.sword.base.SWORDErrorException;
public class SWORDMETSIngester implements SWORDIngester
{
private SWORDService swordService;
/** Log4j logger */
public static final Logger log = Logger.getLogger(SWORDMETSIngester.class);
/* (non-Javadoc)
* @see org.dspace.sword.SWORDIngester#ingest(org.dspace.core.Context, org.purl.sword.base.Deposit)
*/
public DepositResult ingest(SWORDService service, Deposit deposit, DSpaceObject dso)
throws DSpaceSWORDException, SWORDErrorException
{
try
{
// first, make sure this is the right kind of ingester, and set the collection
if (!(dso instanceof Collection))
{
throw new DSpaceSWORDException("Tried to run an ingester on wrong target type");
}
Collection collection = (Collection) dso;
// now set the sword service
swordService = service;
// get the things out of the service that we need
Context context = swordService.getContext();
// get deposited file as InputStream
File depositFile = deposit.getFile();
// load the plugin manager for the required configuration
String cfg = ConfigurationManager.getProperty("sword.mets-ingester.package-ingester");
if (cfg == null || "".equals(cfg))
{
cfg = "METS"; // default to METS
}
swordService.message("Using package manifest format: " + cfg);
PackageIngester pi = (PackageIngester) PluginManager.getNamedPlugin(PackageIngester.class, cfg);
swordService.message("Loaded package ingester: " + pi.getClass().getName());
// the licence is either in the zip or the mets manifest. Either way
// it's none of our business here
String licence = null;
// Initialize parameters to packager
PackageParameters params = new PackageParameters();
// Force package ingester to respect Collection workflows
params.setWorkflowEnabled(true);
// ingest the item from the temp file
DSpaceObject ingestedObject = pi.ingest(context, collection, depositFile, params, licence);
if (ingestedObject == null)
{
swordService.message("Failed to ingest the package; throwing exception");
throw new SWORDErrorException(DSpaceSWORDErrorCodes.UNPACKAGE_FAIL, "METS package ingester failed to unpack package");
}
//Verify we have an Item as a result -- SWORD can only ingest Items
if (!(ingestedObject instanceof Item))
{
throw new DSpaceSWORDException("DSpace Ingester returned wrong object type -- not an Item result.");
}
else
{
//otherwise, we have an item, and a workflow should have already been started for it.
swordService.message("Workflow process started");
}
// get reference to item so that we can report on it
Item installedItem = (Item)ingestedObject;
// update the item metadata to inclue the current time as
// the updated date
this.setUpdatedDate(installedItem);
// DSpace ignores the slug value as suggested identifier, but
// it does store it in the metadata
this.setSlug(installedItem, deposit.getSlug());
// in order to write these changes, we need to bypass the
// authorisation briefly, because although the user may be
// able to add stuff to the repository, they may not have
// WRITE permissions on the archive.
boolean ignore = context.ignoreAuthorization();
context.setIgnoreAuthorization(true);
installedItem.update();
context.setIgnoreAuthorization(ignore);
// for some reason, DSpace will not give you the handle automatically,
// so we have to look it up
String handle = HandleManager.findHandle(context, installedItem);
swordService.message("Ingest successful");
swordService.message("Item created with internal identifier: " + installedItem.getID());
if (handle != null)
{
swordService.message("Item created with external identifier: " + handle);
}
else
{
swordService.message("No external identifier available at this stage (item in workflow)");
}
DepositResult dr = new DepositResult();
dr.setItem(installedItem);
dr.setHandle(handle);
dr.setTreatment(this.getTreatment());
return dr;
}
catch (RuntimeException re)
{
log.error("caught exception: ", re);
throw re;
}
catch (Exception e)
{
log.error("caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Add the current date to the item metadata. This looks up
* the field in which to store this metadata in the configuration
* sword.updated.field
*
* @param item
* @throws DSpaceSWORDException
*/
private void setUpdatedDate(Item item)
throws DSpaceSWORDException
{
String field = ConfigurationManager.getProperty("sword.updated.field");
if (field == null || "".equals(field))
{
throw new DSpaceSWORDException("No configuration, or configuration is invalid for: sword.updated.field");
}
DCValue dc = this.configToDC(field, null);
item.clearMetadata(dc.schema, dc.element, dc.qualifier, Item.ANY);
DCDate date = new DCDate(new Date());
item.addMetadata(dc.schema, dc.element, dc.qualifier, null, date.toString());
swordService.message("Updated date added to response from item metadata where available");
}
/**
* Store the given slug value (which is used for suggested identifiers,
* and which DSpace ignores) in the item metadata. This looks up the
* field in which to store this metadata in the configuration
* sword.slug.field
*
* @param item
* @param slugVal
* @throws DSpaceSWORDException
*/
private void setSlug(Item item, String slugVal)
throws DSpaceSWORDException
{
// if there isn't a slug value, don't set it
if (slugVal == null)
{
return;
}
String field = ConfigurationManager.getProperty("sword.slug.field");
if (field == null || "".equals(field))
{
throw new DSpaceSWORDException("No configuration, or configuration is invalid for: sword.slug.field");
}
DCValue dc = this.configToDC(field, null);
item.clearMetadata(dc.schema, dc.element, dc.qualifier, Item.ANY);
item.addMetadata(dc.schema, dc.element, dc.qualifier, null, slugVal);
swordService.message("Slug value set in response where available");
}
/**
* utility method to turn given metadata fields of the form
* schema.element.qualifier into DCValue objects which can be
* used to access metadata in items.
*
* The def parameter should be null, * or "" depending on how
* you intend to use the DCValue object
*
* @param config
* @param def
* @return
*/
private DCValue configToDC(String config, String def)
{
DCValue dcv = new DCValue();
dcv.schema = def;
dcv.element= def;
dcv.qualifier = def;
StringTokenizer stz = new StringTokenizer(config, ".");
dcv.schema = stz.nextToken();
dcv.element = stz.nextToken();
if (stz.hasMoreTokens())
{
dcv.qualifier = stz.nextToken();
}
return dcv;
}
/**
* The human readable description of the treatment this ingester has
* put the deposit through
*
* @return
* @throws DSpaceSWORDException
*/
private String getTreatment() throws DSpaceSWORDException
{
return "The package has been deposited into DSpace. Each file has been unpacked " +
"and provided with a unique identifier. The metadata in the manifest has been " +
"extracted and attached to the DSpace item, which has been provided with " +
"an identifier leading to an HTML splash page.";
}
}
| 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.sword;
import javax.servlet.http.HttpServlet;
import org.dspace.core.ConfigurationManager;
/**
* Simple servlet to load in DSpace and log4j configurations. Should always be
* started up before other servlets (use <loadOnStartup>)
*
* This class holds code to be removed in the next version of the DSpace XMLUI,
* it is now managed by a Shared Context Listener inthe dspace-api project.
*
* It is deprecated, rather than removed to maintain backward compatibility for
* local DSpace 1.5.x customized overlays.
*
* TODO: Remove in trunk
*
* @deprecated Use Servlet Context Listener provided in dspace-api (remove in >
* 1.5.x)
*
* @author Robert Tansley
*/
public class LoadDSpaceConfig extends HttpServlet
{
public void init()
{
if(!ConfigurationManager.isConfigured())
{
// Get config parameter
String config = getServletContext().getInitParameter("dspace-config");
// Load in DSpace config
ConfigurationManager.loadConfig(config);
}
}
}
| 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.sword;
import org.purl.sword.base.AtomDocumentResponse;
import org.purl.sword.base.SWORDErrorException;
import org.purl.sword.base.SWORDEntry;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Bitstream;
/**
* @author Richard Jones
*
* Class to provide tools to manage media links and media entries for sword
*
*/
public class MediaEntryManager
{
/** sword service implementation */
private SWORDService swordService;
public MediaEntryManager(SWORDService swordService)
{
this.swordService = swordService;
}
/**
* Get the media entry for the given URL request. If the url is unavailable
* this method will throw the appropriate sword errors, with DSpace custom
* URLs
*
* @param url
* @return
* @throws DSpaceSWORDException
* @throws SWORDErrorException
*/
public AtomDocumentResponse getMediaEntry(String url)
throws DSpaceSWORDException, SWORDErrorException
{
SWORDUrlManager urlManager = swordService.getUrlManager();
AtomDocumentResponse response = new AtomDocumentResponse(200);
if (url == null || urlManager.isBaseMediaLinkUrl(url))
{
// we are dealing with a default media-link, indicating that something
// is wrong
// FIXME: what do we actually do about this situation?
// throwing an error for the time being
throw new SWORDErrorException(DSpaceSWORDErrorCodes.MEDIA_UNAVAILABLE, "The media link you requested is not available");
}
// extract the thing that we are trying to get a media entry on
DSpaceObject dso = urlManager.extractDSpaceObject(url);
// now, the media entry should always be to an actual file, so we only care that this is a bitstream
if (!(dso instanceof Bitstream))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The url you provided does not resolve to an appropriate object");
}
// now construct the atom entry for the bitstream
DSpaceATOMEntry dsatom = new BitstreamEntryGenerator(swordService);
SWORDEntry entry = dsatom.getSWORDEntry(dso);
response.setEntry(entry);
return response;
}
}
| 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.sword;
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.handle.HandleManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.purl.sword.base.SWORDErrorException;
import java.sql.SQLException;
import java.net.URL;
import java.net.MalformedURLException;
/**
* @author Richard Jones
*
* Class responsible for constructing and de-constructing sword url space
* urls
*/
public class SWORDUrlManager
{
/** the sword configuration */
private SWORDConfiguration config;
/** the active dspace context */
private Context context;
public SWORDUrlManager(SWORDConfiguration config, Context context)
{
this.config = config;
this.context = context;
}
/**
* Get the generator url for atom entry documents. This can be
* overridden from the default in configuration
*
* @return
*/
public String getGeneratorUrl()
{
String cfg = ConfigurationManager.getProperty("sword.generator.url");
if (cfg == null || "".equals(cfg))
{
return SWORDProperties.SOFTWARE_URI;
}
return cfg;
}
/**
* Obtain the deposit URL for the given collection. These URLs
* should not be considered persistent, but will remain consistent
* unless configuration changes are made to DSpace
*
* @param collection
* @return The Deposit URL
* @throws DSpaceSWORDException
*/
public String getDepositLocation(Collection collection)
throws DSpaceSWORDException
{
return this.getBaseDepositUrl() + "/" + collection.getHandle();
}
/**
* Obtain the deposit URL for the given item. These URLs
* should not be considered persistent, but will remain consistent
* unless configuration changes are made to DSpace
*
* @param item
* @return The Deposit URL
* @throws DSpaceSWORDException
*/
public String getDepositLocation(Item item)
throws DSpaceSWORDException
{
return this.getBaseDepositUrl() + "/" + item.getHandle();
}
/**
* Obtain the deposit URL for the given community. These URLs
* should not be considered persistent, but will remain consistent
* unless configuration changes are made to DSpace
*
* @param community
* @return The Deposit URL
* @throws DSpaceSWORDException
*/
public String getDepositLocation(Community community)
throws DSpaceSWORDException
{
// FIXME: there is no deposit url for communities yet, so this could
// be misleading
return this.getBaseDepositUrl() + "/" + community.getHandle();
}
/**
* Obtain the collection which is represented by the given
* URL
*
* @param context the DSpace context
* @param location the URL to resolve to a collection
* @return The collection to which the url resolves
* @throws DSpaceSWORDException
*/
// FIXME: we need to generalise this to DSpaceObjects, so that we can support
// Communities, Collections and Items separately
public Collection getCollection(Context context, String location)
throws DSpaceSWORDException, SWORDErrorException
{
try
{
String baseUrl = this.getBaseDepositUrl();
if (baseUrl.length() == location.length())
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL is incomplete");
}
String handle = location.substring(baseUrl.length());
if (handle.startsWith("/"))
{
handle = handle.substring(1);
}
if ("".equals(handle))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL is incomplete");
}
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
if (!(dso instanceof Collection))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL does not resolve to a valid collection");
}
return (Collection) dso;
}
catch (SQLException e)
{
// log.error("Caught exception:", e);
throw new DSpaceSWORDException("There was a problem resolving the collection", e);
}
}
/**
* Obtain the collection which is represented by the given
* URL
*
* @param context the DSpace context
* @param location the URL to resolve to a collection
* @return The collection to which the url resolves
* @throws DSpaceSWORDException
*/
public DSpaceObject getDSpaceObject(Context context, String location)
throws DSpaceSWORDException, SWORDErrorException
{
try
{
String baseUrl = this.getBaseDepositUrl();
if (baseUrl.length() == location.length())
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL is incomplete");
}
String handle = location.substring(baseUrl.length());
if (handle.startsWith("/"))
{
handle = handle.substring(1);
}
if ("".equals(handle))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL is incomplete");
}
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
if (!(dso instanceof Collection) && !(dso instanceof Item))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL does not resolve to a valid deposit target");
}
return dso;
}
catch (SQLException e)
{
// log.error("Caught exception:", e);
throw new DSpaceSWORDException("There was a problem resolving the collection", e);
}
}
/**
* Construct the service document url for the given object, which will
* be supplied in the sword:service element of other service document entries
*
* @param community
* @return
* @throws DSpaceSWORDException
*/
public String constructSubServiceUrl(Community community)
throws DSpaceSWORDException
{
String base = this.getBaseServiceDocumentUrl();
String handle = community.getHandle();
return base + "/" + handle;
}
/**
* Construct the service document url for the given object, which will
* be supplied in the sword:service element of other service document entries
*
* @param collection
* @return
* @throws DSpaceSWORDException
*/
public String constructSubServiceUrl(Collection collection)
throws DSpaceSWORDException
{
String base = this.getBaseServiceDocumentUrl();
String handle = collection.getHandle();
return base + "/" + handle;
}
/**
* Extract a DSpaceObject from the given url. If this method is unable to
* locate a meaningful and appropriate dspace object it will throw the
* appropriate sword error
* @param url
* @return
* @throws DSpaceSWORDException
* @throws SWORDErrorException
*/
public DSpaceObject extractDSpaceObject(String url)
throws DSpaceSWORDException, SWORDErrorException
{
try
{
String sdBase = this.getBaseServiceDocumentUrl();
String mlBase = this.getBaseMediaLinkUrl();
if (url.startsWith(sdBase))
{
// we are dealing with a service document request
// first, let's find the beginning of the handle
url = url.substring(sdBase.length());
if (url.startsWith("/"))
{
url = url.substring(1);
}
if (url.endsWith("/"))
{
url = url.substring(0, url.length() - 1);
}
DSpaceObject dso = HandleManager.resolveToObject(context, url);
if (dso instanceof Collection || dso instanceof Community)
{
return dso;
}
else
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"Service Document request does not refer to a DSpace Collection or Community");
}
}
else if (url.startsWith(mlBase))
{
// we are dealing with a bitstream media link
// find the index of the "/bitstream/" segment of the url
int bsi = url.indexOf("/bitstream/");
// subtsring the url from the end of this "/bitstream/" string, to get the bitstream id
String bsid = url.substring(bsi + 11);
// strip off extraneous slashes
if (bsid.endsWith("/"))
{
bsid = bsid.substring(0, url.length() - 1);
}
return Bitstream.find(context, Integer.parseInt(bsid));
}
else
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"Unable to recognise URL as a valid service document: " + url);
}
}
catch (SQLException e)
{
throw new DSpaceSWORDException(e);
}
}
/**
* get the base url for service document requests
*
* @return
* @throws DSpaceSWORDException
*/
public String getBaseServiceDocumentUrl()
throws DSpaceSWORDException
{
String depositUrl = ConfigurationManager.getProperty("sword.servicedocument.url");
if (depositUrl == null || "".equals(depositUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSWORDException("Unable to construct service document urls, due to missing/invalid " +
"config in sword.servicedocument.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
depositUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/sword/servicedocument").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSWORDException("Unable to construct service document urls, due to invalid dspace.baseUrl " +
e.getMessage(),e);
}
}
return depositUrl;
}
/**
* Get the base deposit URL for the DSpace SWORD implementation. This
* is effectively the URL of the servlet which deals with deposit
* requests, and is used as the basis for the individual Collection
* URLs
*
* If the configuration sword.deposit.url is set, this will be returned,
* but if not, it will construct the url as follows:
*
* [dspace.baseUrl]/sword/deposit
*
* where dspace.baseUrl is also in the configuration file.
*
* @return the base URL for sword deposit
* @throws DSpaceSWORDException
*/
public String getBaseDepositUrl()
throws DSpaceSWORDException
{
String depositUrl = ConfigurationManager.getProperty("sword.deposit.url");
if (depositUrl == null || "".equals(depositUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSWORDException("Unable to construct deposit urls, due to missing/invalid config in " +
"sword.deposit.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
depositUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/sword/deposit").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSWORDException("Unable to construct deposit urls, due to invalid dspace.baseUrl " +
e.getMessage(),e);
}
}
return depositUrl;
}
/**
* is the given url the base service document url
*
* @param url
* @return
* @throws DSpaceSWORDException
*/
public boolean isBaseServiceDocumentUrl(String url)
throws DSpaceSWORDException
{
return this.getBaseServiceDocumentUrl().equals(url);
}
/**
* is the given url the base media link url
*
* @param url
* @return
* @throws DSpaceSWORDException
*/
public boolean isBaseMediaLinkUrl(String url)
throws DSpaceSWORDException
{
return this.getBaseMediaLinkUrl().equals(url);
}
/**
* Central location for constructing usable urls for dspace bitstreams. There
* is no place in the main DSpace code base for doing this.
*
* @param bitstream
* @return
* @throws DSpaceSWORDException
*/
public String getBitstreamUrl(Bitstream bitstream)
throws DSpaceSWORDException
{
try
{
Bundle[] bundles = bitstream.getBundles();
Bundle parent = null;
if (bundles.length > 0)
{
parent = bundles[0];
}
else
{
throw new DSpaceSWORDException("Encountered orphaned bitstream");
}
Item[] items = parent.getItems();
Item item;
if (items.length > 0)
{
item = items[0];
}
else
{
throw new DSpaceSWORDException("Encountered orphaned bundle");
}
String handle = item.getHandle();
String bsLink = ConfigurationManager.getProperty("dspace.url");
if (handle != null && !"".equals(handle))
{
bsLink = bsLink + "/bitstream/" + handle + "/" + bitstream.getSequenceID() + "/" + bitstream.getName();
}
else
{
bsLink = bsLink + "/retrieve/" + bitstream.getID();
}
return bsLink;
}
catch (SQLException e)
{
throw new DSpaceSWORDException(e);
}
}
/**
* get the base media link url
*
* @return
* @throws DSpaceSWORDException
*/
public String getBaseMediaLinkUrl()
throws DSpaceSWORDException
{
String mlUrl = ConfigurationManager.getProperty("sword.media-link.url");
if (mlUrl == null || "".equals(mlUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSWORDException("Unable to construct media-link urls, due to missing/invalid config in " +
"sword.media-link.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
mlUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/sword/media-link").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSWORDException("Unable to construct media-link urls, due to invalid dspace.baseUrl " +
e.getMessage(),e);
}
}
return mlUrl;
}
/**
* get the media link url for the given item
*
* @param dso
* @return
* @throws DSpaceSWORDException
*/
private String getMediaLink(Item dso)
throws DSpaceSWORDException
{
String ml = this.getBaseMediaLinkUrl();
String handle = dso.getHandle();
if (handle != null)
{
ml = ml + "/" + dso.getHandle();
}
return ml;
}
/**
* get the media link url for the given bitstream
*
* @param bitstream
* @return
* @throws DSpaceSWORDException
*/
public String getMediaLink(Bitstream bitstream)
throws DSpaceSWORDException
{
try
{
Bundle[] bundles = bitstream.getBundles();
Bundle parent = null;
if (bundles.length > 0)
{
parent = bundles[0];
}
else
{
throw new DSpaceSWORDException("Encountered orphaned bitstream");
}
Item[] items = parent.getItems();
Item item;
if (items.length > 0)
{
item = items[0];
}
else
{
throw new DSpaceSWORDException("Encountered orphaned bundle");
}
String itemUrl = this.getMediaLink(item);
if (itemUrl.equals(this.getBaseMediaLinkUrl()))
{
return itemUrl;
}
String bsUrl = itemUrl + "/bitstream/" + bitstream.getID();
return bsUrl;
}
catch (SQLException e)
{
throw new DSpaceSWORDException(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.sword;
import org.purl.sword.base.Collection;
import org.dspace.content.DSpaceObject;
/**
* @author Richard Jones
*
* Define an abstract interface for classes wishing to generate ATOM Collections
* for SWORD service documents
*/
public abstract class ATOMCollectionGenerator
{
/** the sword service definition */
protected SWORDService swordService;
/**
* Create a new ATOM collection generator using the given sword service
*
* @param service
*/
public ATOMCollectionGenerator(SWORDService service)
{
this.swordService = service;
}
/**
* Build the ATOM Collection which represents the given DSpace Object
*
* @param dso
* @return
* @throws DSpaceSWORDException
*/
public abstract Collection buildCollection(DSpaceObject dso) throws DSpaceSWORDException;
}
| 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.sword;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.BitstreamFormat;
import org.purl.sword.base.SWORDErrorException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.sql.SQLException;
import org.apache.log4j.Logger;
/**
* @author Richard Jones
*
* Class to represent the principal configurations of the sword
* service being offered. Not all configuration is available through
* this class, but the most useful common options, and those with
* default values are available
*
* Note that changes to values via the api will not be persisted
* between sword requests.
*
* For detailed descriptions of configuration values, see the sword
* configuration documentation
*
*/
public class SWORDConfiguration
{
/** logger */
public static final Logger log = Logger.getLogger(SWORDConfiguration.class);
/** whether we can support noOp */
private boolean noOp = true;
/** whether we can be verbose */
private boolean verbose = true;
/** what our default max upload size is */
private int maxUploadSize = -1;
/** do we support mediation */
private boolean mediated = false;
/** should we keep the original package as bitstream */
private boolean keepOriginal = false;
/** item bundle in which sword deposits are stored */
private String swordBundle = "SWORD";
/** should we keep the original package as a file on ingest error */
private boolean keepPackageOnFailedIngest = false;
/** location of directory to store packages on ingest error */
private String failedPackageDir = null;
/** Accepted formats */
private List<String> swordaccepts;
/**
* Initialise the sword configuration. It is at this stage that the
* object will interrogate the DSpace Configuration for details
*/
public SWORDConfiguration()
{
// set the max upload size
int mus = ConfigurationManager.getIntProperty("sword.max-upload-size");
if (mus > 0)
{
this.maxUploadSize = mus;
}
// set the mediation value
this.mediated = ConfigurationManager.getBooleanProperty("sword.on-behalf-of.enable");
// find out if we keep the original as bitstream
this.keepOriginal = ConfigurationManager.getBooleanProperty("sword.keep-original-package");
// get the sword bundle
String bundle = ConfigurationManager.getProperty("sword.bundle.name");
if (bundle != null && "".equals(bundle))
{
this.swordBundle = bundle;
}
// find out if we keep the package as a file in specified directory
this.keepPackageOnFailedIngest = ConfigurationManager.getBooleanProperty("sword.keep-package-on-fail", false);
// get directory path and name
this.failedPackageDir = ConfigurationManager.getProperty("sword.failed-package.dir");
// Get the accepted formats
String acceptsProperty = ConfigurationManager.getProperty("sword.accepts");
swordaccepts = new ArrayList<String>();
if (acceptsProperty == null)
{
acceptsProperty = "application/zip";
}
for (String element : acceptsProperty.split(","))
{
swordaccepts.add(element.trim());
}
}
/**
* Get the bundle name that sword will store its original deposit packages in, when
* storing them inside an item
* @return
*/
public String getSwordBundle()
{
return swordBundle;
}
/**
* Set the bundle name that sword will store its original deposit packages in, when
* storing them inside an item
* @param swordBundle
*/
public void setSwordBundle(String swordBundle)
{
this.swordBundle = swordBundle;
}
/**
* is this a no-op deposit
* @return
*/
public boolean isNoOp()
{
return noOp;
}
/**
* set whether this is a no-op deposit
*
* @param noOp
*/
public void setNoOp(boolean noOp)
{
this.noOp = noOp;
}
/**
* is this a verbose deposit
* @return
*/
public boolean isVerbose()
{
return verbose;
}
/**
* set whether this is a verbose deposit
* @param verbose
*/
public void setVerbose(boolean verbose)
{
this.verbose = verbose;
}
/**
* what is the max upload size (in bytes) for the sword interface
* @return
*/
public int getMaxUploadSize()
{
return maxUploadSize;
}
/**
* set the max uplaod size (in bytes) for the sword interface
* @param maxUploadSize
*/
public void setMaxUploadSize(int maxUploadSize)
{
this.maxUploadSize = maxUploadSize;
}
/**
* does the server support mediated deposit (aka on-behalf-of)
* @return
*/
public boolean isMediated()
{
return mediated;
}
/**
* set whether the server supports mediated deposit (aka on-behalf-of)
* @param mediated
*/
public void setMediated(boolean mediated)
{
this.mediated = mediated;
}
/**
* should the repository keep the original package
* @return
*/
public boolean isKeepOriginal()
{
return keepOriginal;
}
/**
* set whether the repository should keep copies of the original package
* @param keepOriginal
*/
public void setKeepOriginal(boolean keepOriginal)
{
this.keepOriginal = keepOriginal;
}
/**
* set whether the repository should write file of the original package if ingest fails
* @param keepOriginalOnFail
*/
public void setKeepPackageOnFailedIngest(boolean keepOriginalOnFail)
{
keepPackageOnFailedIngest = keepOriginalOnFail;
}
/**
* should the repository write file of the original package if ingest fails
* @return keepPackageOnFailedIngest
*/
public boolean isKeepPackageOnFailedIngest()
{
return keepPackageOnFailedIngest;
}
/**
* set the directory to write file of the original package
* @param dir
*/
public void setFailedPackageDir(String dir)
{
failedPackageDir = dir;
}
/**
* directory location of the files with original packages
* for failed ingests
* @return failedPackageDir
*/
public String getFailedPackageDir()
{
return failedPackageDir;
}
/**
* Get the list of mime types that the given dspace object will
* accept as packages
*
* @param context
* @param dso
* @return
* @throws DSpaceSWORDException
*/
public List<String> getAccepts(Context context, DSpaceObject dso)
throws DSpaceSWORDException
{
try
{
List<String> accepts = new ArrayList<String>();
if (dso instanceof Collection)
{
for (String format : swordaccepts)
{
accepts.add(format);
}
}
else if (dso instanceof Item)
{
BitstreamFormat[] bfs = BitstreamFormat.findNonInternal(context);
for (int i = 0; i < bfs.length; i++)
{
accepts.add(bfs[i].getMIMEType());
}
}
return accepts;
}
catch (SQLException e)
{
throw new DSpaceSWORDException(e);
}
}
/**
* Get the list of mime types that a Collection will accept as packages
*
* @return the list of mime types
* @throws DSpaceSWORDException
*/
public List<String> getCollectionAccepts() throws DSpaceSWORDException
{
List<String> accepts = new ArrayList<String>();
for (String format : swordaccepts)
{
accepts.add(format);
}
return accepts;
}
/**
* Get a map of packaging URIs to Q values for the packaging types which
* the given collection will accept.
*
* The URI should be a unique identifier for the packaging type,
* such as:
*
* http://purl.org/net/sword-types/METSDSpaceSIP
*
* and the Q value is a floating point between 0 and 1 which defines
* how much the server "likes" this packaging type
*
* @param col
* @return
*/
public Map<String, Float> getAcceptPackaging(Collection col)
{
Map<String, String> identifiers = new HashMap<String, String>();
Map<String, String> qs = new HashMap<String, String>();
String handle = col.getHandle();
// build the holding maps of identifiers and q values
Properties props = ConfigurationManager.getProperties();
Set keyset = props.keySet();
for (Object keyObj : keyset)
{
String sw = "sword.accept-packaging.";
if (!(keyObj instanceof String))
{
continue;
}
String key = (String) keyObj;
if (!key.startsWith(sw))
{
continue;
}
// extract the configuration into the holding Maps
String suffix = key.substring(sw.length());
String[] bits = suffix.split("\\.");
if (bits.length == 2)
{
// global settings
String value = props.getProperty(key);
if (bits[1].equals("identifier"))
{
identifiers.put(bits[0], value);
}
else if (bits[1].equals("q"))
{
qs.put(bits[0], value);
}
}
// collection settings
if (bits.length == 3 && bits[0].equals(handle))
{
// this is configuration for our collection
String value = props.getProperty(key);
if (bits[2].equals("identifier"))
{
identifiers.put(bits[1], value);
}
else if (bits[2].equals("q"))
{
qs.put(bits[1], value);
}
}
}
// merge the holding maps into the Accept Packaging settings
Map<String, Float> ap = new HashMap<String, Float>();
for (String ik : identifiers.keySet())
{
String id = identifiers.get(ik);
String qv = qs.get(ik);
Float qf = Float.parseFloat(qv);
ap.put(id, qf);
}
return ap;
}
/**
* is the given packaging/media type supported by the given dspace object
*
* @param mediaType
* @param dso
* @return
* @throws DSpaceSWORDException
* @throws SWORDErrorException
*/
public boolean isSupportedMediaType(String mediaType, DSpaceObject dso)
throws DSpaceSWORDException, SWORDErrorException
{
if (mediaType == null || "".equals(mediaType))
{
return true;
}
if (dso instanceof Collection)
{
Map<String, Float> accepts = this.getAcceptPackaging((Collection) dso);
for (String accept : accepts.keySet())
{
if (accept.equals(mediaType))
{
return true;
}
}
}
else if (dso instanceof Item)
{
// items don't unpackage, so they don't care what the media type is
return true;
}
return false;
}
/**
* is the given content mimetype acceptable to the given dspace object
* @param context
* @param type
* @param dso
* @return
* @throws DSpaceSWORDException
*/
public boolean isAcceptableContentType(Context context, String type, DSpaceObject dso)
throws DSpaceSWORDException
{
List<String> accepts = this.getAccepts(context, dso);
return accepts.contains(type);
}
/**
* Get the temp directory for storing files during deposit
*
* @return
* @throws DSpaceSWORDException
*/
public String getTempDir()
throws DSpaceSWORDException
{
String tempDir = ConfigurationManager.getProperty("upload.temp.dir");
if (tempDir == null || "".equals(tempDir))
{
throw new DSpaceSWORDException("There is no temporary upload directory specified in configuration: upload.temp.dir");
}
return tempDir;
}
}
| 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.sword;
import org.purl.sword.base.ServiceDocument;
import org.purl.sword.base.SWORDErrorException;
import org.purl.sword.base.Service;
import org.purl.sword.base.Workspace;
import org.purl.sword.atom.Generator;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.content.Community;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import java.util.List;
public class ServiceDocumentManager
{
private SWORDService swordService;
private SWORDAuthenticator swordAuth;
public ServiceDocumentManager(SWORDService service)
{
this.swordService = service;
this.swordAuth = new SWORDAuthenticator();
}
/**
* Obtain the service document for the repository based on the
* DSpace context and the SWORD context which must be set for
* this object prior to calling this method.
*
* @return The service document based on the context of the request
* @throws DSpaceSWORDException
*/
public ServiceDocument getServiceDocument()
throws DSpaceSWORDException, SWORDErrorException
{
return this.getServiceDocument(null);
}
public ServiceDocument getServiceDocument(String url)
throws DSpaceSWORDException, SWORDErrorException
{
// extract the things we need from the service
Context context = swordService.getContext();
SWORDContext swordContext = swordService.getSwordContext();
SWORDConfiguration swordConfig = swordService.getSwordConfig();
SWORDUrlManager urlManager = swordService.getUrlManager();
// construct the ATOM collection generators that we might use
ATOMCollectionGenerator comGen = new CommunityCollectionGenerator(swordService);
ATOMCollectionGenerator colGen = new CollectionCollectionGenerator(swordService);
ATOMCollectionGenerator itemGen = new ItemCollectionGenerator(swordService);
// first check that the context and sword context have
// been set
if (context == null)
{
throw new DSpaceSWORDException("The Context is null; please set it before calling getServiceDocument");
}
if (swordContext == null)
{
throw new DSpaceSWORDException("The SWORD Context is null; please set it before calling getServiceDocument");
}
// construct a new service document
Service service = new Service(SWORDProperties.VERSION, swordConfig.isNoOp(), swordConfig.isVerbose());
// set the max upload size
service.setMaxUploadSize(swordConfig.getMaxUploadSize());
// Set the generator
this.addGenerator(service);
//
if (url == null || urlManager.isBaseServiceDocumentUrl(url))
{
// we are dealing with the default service document
// set the title of the workspace as per the name of the DSpace installation
String ws = ConfigurationManager.getProperty("dspace.name");
Workspace workspace = new Workspace();
workspace.setTitle(ws);
// next thing to do is determine whether the default is communities or collections
boolean swordCommunities = ConfigurationManager.getBooleanProperty("sword.expose-communities");
if (swordCommunities)
{
List<Community> comms = swordAuth.getAllowedCommunities(swordContext);
for (Community comm : comms)
{
org.purl.sword.base.Collection scol = comGen.buildCollection(comm);
workspace.addCollection(scol);
}
}
else
{
List<Collection> cols = swordAuth.getAllowedCollections(swordContext);
for (Collection col : cols)
{
org.purl.sword.base.Collection scol = colGen.buildCollection(col);
workspace.addCollection(scol);
}
}
service.addWorkspace(workspace);
}
else
{
// we are dealing with a partial or sub-service document
DSpaceObject dso = urlManager.extractDSpaceObject(url);
if (dso instanceof Collection)
{
Collection collection = (Collection) dso;
Workspace workspace = new Workspace();
workspace.setTitle(collection.getMetadata("name"));
List<Item> items = swordAuth.getAllowedItems(swordContext, collection);
for (Item item : items)
{
org.purl.sword.base.Collection scol = itemGen.buildCollection(item);
workspace.addCollection(scol);
}
service.addWorkspace(workspace);
}
else if (dso instanceof Community)
{
Community community = (Community) dso;
Workspace workspace = new Workspace();
workspace.setTitle(community.getMetadata("name"));
List<Collection> collections = swordAuth.getAllowedCollections(swordContext, community);
for (Collection collection : collections)
{
org.purl.sword.base.Collection scol = colGen.buildCollection(collection);
workspace.addCollection(scol);
}
List<Community> communities = swordAuth.getCommunities(swordContext, community);
for (Community comm : communities)
{
org.purl.sword.base.Collection scol = comGen.buildCollection(comm);
workspace.addCollection(scol);
}
service.addWorkspace(workspace);
}
}
return new ServiceDocument(service);
}
/**
* Add the generator field content
*
* @param service The service document to add the generator to
*/
private void addGenerator(Service service)
{
boolean identify = ConfigurationManager.getBooleanProperty("sword.identify-version", false);
SWORDUrlManager urlManager = swordService.getUrlManager();
String softwareUri = urlManager.getGeneratorUrl();
if (identify)
{
Generator generator = new Generator();
generator.setUri(softwareUri);
generator.setVersion(SWORDProperties.VERSION);
service.setGenerator(generator);
}
}
}
| 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.sword;
import org.dspace.content.DSpaceObject;
import org.purl.sword.base.Deposit;
import org.purl.sword.base.SWORDErrorException;
/**
* @author Richard Jones
*
* Abstract class for depositing content into the archive.
*/
public abstract class Depositor
{
/**
* The sword service implementation
*/
protected SWORDService swordService;
/**
* Construct a new Depositor with the given sword service on the given
* dspace object. It is anticipated that extensions of this class will
* specialise in certain kinds of dspace object
*
* @param swordService
* @param dso
*/
public Depositor(SWORDService swordService, DSpaceObject dso)
{
this.swordService = swordService;
}
/**
* Execute the deposit process with the given sword deposit
*
* @param deposit
* @return
* @throws SWORDErrorException
* @throws DSpaceSWORDException
*/
public abstract DepositResult doDeposit(Deposit deposit) throws SWORDErrorException, DSpaceSWORDException;
/**
* Undo any changes to the archive effected by the deposit
*
* @param result
* @throws DSpaceSWORDException
*/
public abstract void undoDeposit(DepositResult result) throws DSpaceSWORDException;
}
| 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.sword;
import org.purl.sword.base.Collection;
import org.dspace.content.*;
import org.dspace.core.Context;
import java.util.List;
/**
* @author Richard Jones
*
* Class to generate ATOM Collection elements for DSpace Items
*/
public class ItemCollectionGenerator extends ATOMCollectionGenerator
{
public ItemCollectionGenerator(SWORDService service)
{
super(service);
}
/**
* Build the collection around the give DSpaceObject. If the object is not an
* instance of a DSpace Item this method will throw an exception
*
* @param dso
* @return
* @throws DSpaceSWORDException
*/
public Collection buildCollection(DSpaceObject dso) throws DSpaceSWORDException
{
if (!(dso instanceof Item))
{
throw new DSpaceSWORDException("Incorrect ATOMCollectionGenerator instantiated");
}
// get the things we need out of the service
SWORDConfiguration swordConfig = swordService.getSwordConfig();
SWORDUrlManager urlManager = swordService.getUrlManager();
Context context = swordService.getContext();
Item item = (Item) dso;
Collection scol = new Collection();
// prepare the parameters to be put in the sword collection
String location = urlManager.getDepositLocation(item);
scol.setLocation(location);
// the item title is the sword collection title, or "untitled" otherwise
String title = "Untitled";
DCValue[] dcv = item.getMetadata("dc.title");
if (dcv.length > 0)
{
title = dcv[0].value;
}
scol.setTitle(title);
// FIXME: there is no collection policy for items that is obvious to provide.
// the collection policy is the licence to which the collection adheres
// String collectionPolicy = col.getLicense();
// abstract is the short description of the item, if it exists
String dcAbstract = "";
DCValue[] dcva = item.getMetadata("dc.description.abstract");
if (dcva.length > 0)
{
dcAbstract = dcva[0].value;
}
if (dcAbstract != null && !"".equals(dcAbstract))
{
scol.setAbstract(dcAbstract);
}
// do we suppot mediated deposit
scol.setMediation(swordConfig.isMediated());
// the list of mime types that we accept, which we take from the
// bitstream format registry
List<String> acceptFormats = swordConfig.getAccepts(context, item);
for (String acceptFormat : acceptFormats)
{
scol.addAccepts(acceptFormat);
}
return scol;
}
}
| 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.sword;
import org.apache.log4j.Logger;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.purl.sword.server.SWORDServer;
import org.purl.sword.base.AtomDocumentRequest;
import org.purl.sword.base.AtomDocumentResponse;
import org.purl.sword.base.Deposit;
import org.purl.sword.base.DepositResponse;
import org.purl.sword.base.SWORDAuthenticationException;
import org.purl.sword.base.SWORDErrorException;
import org.purl.sword.base.SWORDException;
import org.purl.sword.base.ServiceDocument;
import org.purl.sword.base.ServiceDocumentRequest;
/**
* An implementation of the SWORDServer interface to allow SWORD deposit
* operations on DSpace. See:
*
* http://www.ukoln.ac.uk/repositories/digirep/index/SWORD_APP_Profile_0.5
*
* @author Richard Jones
*/
public class DSpaceSWORDServer implements SWORDServer
{
/** Log4j logger */
public static final Logger log = Logger.getLogger(DSpaceSWORDServer.class);
// methods required by SWORDServer interface
////////////////////////////////////////////
/* (non-Javadoc)
* @see org.purl.sword.SWORDServer#doServiceDocument(org.purl.sword.base.ServiceDocumentRequest)
*/
public ServiceDocument doServiceDocument(ServiceDocumentRequest request)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
{
// gah. bloody variable scoping.
// set up a dummy sword context for the "finally" block
SWORDContext sc = null;
try
{
// first authenticate the request
// note: this will build our various DSpace contexts for us
SWORDAuthenticator auth = new SWORDAuthenticator();
sc = auth.authenticate(request);
Context context = sc.getContext();
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_do_service_document", ""));
}
// log the request
log.info(LogManager.getHeader(context, "sword_service_document_request", "username=" + request.getUsername() + ",on_behalf_of=" + request.getOnBehalfOf()));
// prep the service request, then get the service document out of it
SWORDService service = new SWORDService(sc);
ServiceDocumentManager manager = new ServiceDocumentManager(service);
ServiceDocument doc = manager.getServiceDocument(request.getLocation());
return doc;
}
catch (DSpaceSWORDException e)
{
log.error("caught exception: ", e);
throw new SWORDException("The DSpace SWORD interface experienced an error", e);
}
finally
{
// this is a read operation only, so there's never any need to commit the context
if (sc != null)
{
sc.abort();
}
}
}
/* (non-Javadoc)
* @see org.purl.sword.SWORDServer#doSWORDDeposit(org.purl.sword.server.Deposit)
*/
public DepositResponse doDeposit(Deposit deposit)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
{
// gah. bloody variable scoping.
// set up a dummy sword context for the "finally" block
SWORDContext sc = null;
try
{
// first authenticate the request
// note: this will build our various DSpace contexts for us
SWORDAuthenticator auth = new SWORDAuthenticator();
sc = auth.authenticate(deposit);
Context context = sc.getContext();
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_do_deposit", ""));
}
// log the request
log.info(LogManager.getHeader(context, "sword_deposit_request", "username=" + deposit.getUsername() + ",on_behalf_of=" + deposit.getOnBehalfOf()));
// prep and execute the deposit
SWORDService service = new SWORDService(sc);
service.setVerbose(deposit.isVerbose());
DepositManager dm = new DepositManager(service);
DepositResponse response = dm.deposit(deposit);
// if something hasn't killed it already (allowed), then complete the transaction
sc.commit();
return response;
}
catch (DSpaceSWORDException e)
{
log.error("caught exception:", e);
throw new SWORDException("There was a problem depositing the item", e);
}
finally
{
// if, for some reason, we wind up here with a not null context
// then abort it (the above should commit it if everything works fine)
if (sc != null)
{
sc.abort();
}
}
}
/* (non-Javadoc)
* @see org.purl.sword.SWORDServer#doSWORDDeposit(org.purl.sword.server.Deposit)
*/
public AtomDocumentResponse doAtomDocument(AtomDocumentRequest adr)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
{
// gah. bloody variable scoping.
// set up a dummy sword context for the "finally" block
SWORDContext sc = null;
try
{
// first authenticate the request
// note: this will build our various DSpace contexts for us
SWORDAuthenticator auth = new SWORDAuthenticator();
sc = auth.authenticate(adr);
Context context = sc.getContext();
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_do_atom_document", ""));
}
// log the request
log.info(LogManager.getHeader(context, "sword_atom_document_request", "username=" + adr.getUsername()));
// prep the service request, then get the service document out of it
SWORDService service = new SWORDService(sc);
MediaEntryManager manager = new MediaEntryManager(service);
AtomDocumentResponse doc = manager.getMediaEntry(adr.getLocation());
return doc;
}
catch (DSpaceSWORDException e)
{
log.error("caught exception: ", e);
throw new SWORDException("The DSpace SWORD interface experienced an error", e);
}
finally
{
// this is a read operation only, so there's never any need to commit the context
if (sc != null)
{
sc.abort();
}
}
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.sword;
import org.dspace.core.Context;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.LogManager;
import org.dspace.core.Constants;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.authenticate.AuthenticationMethod;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.*;
import org.apache.log4j.Logger;
import org.purl.sword.base.*;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
/**
* This class offers a thin wrapper for the default DSpace
* authentication module for the SWORD implementation
*
* @author Richard Jones
*
*/
public class SWORDAuthenticator
{
/** logger */
private static Logger log = Logger.getLogger(SWORDAuthenticator.class);
/**
* Does the given username and password authenticate for the
* given DSpace Context?
*
* @param context
* @param un
* @param pw
* @return true if yes, false if not
*/
public boolean authenticates(Context context, String un, String pw)
{
int auth = AuthenticationManager.authenticate(context, un, pw, null, null);
if (auth == AuthenticationMethod.SUCCESS)
{
return true;
}
return false;
}
/**
* Construct the context object member variable of this class
* using the passed IP address as part of the loggable
* information
*
* @param ip the ip address of the incoming request
* @throws org.purl.sword.base.SWORDException
*/
private Context constructContext(String ip)
throws SWORDException
{
try
{
Context context = new Context();
// Set the session ID and IP address
context.setExtraLogInfo("session_id=0:ip_addr=" + ip);
return context;
}
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new SWORDException("There was a problem with the database", e);
}
}
/**
* Authenticate the given service document request. This extracts the appropriate
* information from the request and forwards to the appropriate authentication
* method
*
* @param request
* @return
* @throws SWORDException
* @throws SWORDErrorException
* @throws SWORDAuthenticationException
*/
public SWORDContext authenticate(ServiceDocumentRequest request)
throws SWORDException, SWORDErrorException, SWORDAuthenticationException
{
Context context = this.constructContext(request.getIPAddress());
SWORDContext sc = null;
try
{
sc = this.authenticate(context, request);
}
catch (SWORDException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
catch (SWORDErrorException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
catch (SWORDAuthenticationException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
catch (RuntimeException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
return sc;
}
/**
* Authenticate the given atom document request. This extracts the appropriate information
* from the request, and forwards to the appropriate authentication method
*
* @param request
* @return
* @throws SWORDException
* @throws SWORDErrorException
* @throws SWORDAuthenticationException
*/
public SWORDContext authenticate(AtomDocumentRequest request)
throws SWORDException, SWORDErrorException, SWORDAuthenticationException
{
Context context = this.constructContext(request.getIPAddress());
SWORDContext sc = null;
try
{
sc = this.authenticate(context, request);
}
catch (SWORDException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
catch (SWORDErrorException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
catch (SWORDAuthenticationException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
catch (RuntimeException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
return sc;
}
/**
* Authenticate the incoming service document request. Calls:
*
* authenticatate(username, password, onBehalfOf)
*
* @param request
* @return a SWORDContext object containing the relevant users
* @throws org.purl.sword.base.SWORDAuthenticationException
* @throws SWORDException
*/
private SWORDContext authenticate(Context context, AtomDocumentRequest request)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
{
return this.authenticate(context, request.getUsername(), request.getPassword(), null, request.getIPAddress());
}
/**
* Authenticate the incoming service document request. Calls:
*
* authenticatate(username, password, onBehalfOf)
*
* @param request
* @return a SWORDContext object containing the relevant users
* @throws org.purl.sword.base.SWORDAuthenticationException
* @throws SWORDException
*/
private SWORDContext authenticate(Context context, ServiceDocumentRequest request)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
{
return this.authenticate(context, request.getUsername(), request.getPassword(), request.getOnBehalfOf(), request.getIPAddress());
}
/**
* Authenticate the deposit request.
*
* @param deposit
* @return
* @throws SWORDException
* @throws SWORDErrorException
* @throws SWORDAuthenticationException
*/
public SWORDContext authenticate(Deposit deposit)
throws SWORDException, SWORDErrorException, SWORDAuthenticationException
{
Context context = this.constructContext(deposit.getIPAddress());
SWORDContext sc = null;
try
{
sc = this.authenticate(context, deposit);
}
catch (SWORDException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
catch (SWORDErrorException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
catch (SWORDAuthenticationException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
catch (RuntimeException e)
{
if (context != null && context.isValid())
{
context.abort();
}
throw e;
}
return sc;
}
/**
* Authenticate the incoming deposit request. Calls:
*
* authenticate(username, password, onBehalfOf)
*
* @param deposit
* @return a SWORDContext object containing the relevant users
* @throws SWORDAuthenticationException
* @throws SWORDException
*/
private SWORDContext authenticate(Context context, Deposit deposit)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
{
return this.authenticate(context, deposit.getUsername(), deposit.getPassword(), deposit.getOnBehalfOf(), deposit.getIPAddress());
}
/**
* Authenticate the given username/password pair, in conjunction with
* the onBehalfOf user. The rules are that the username/password pair
* must successfully authenticate the user, and the onBehalfOf user
* must exist in the user database.
*
* @param un
* @param pw
* @param obo
* @return a SWORD context holding the various user information
* @throws SWORDAuthenticationException
* @throws SWORDException
*/
private SWORDContext authenticate(Context context, String un, String pw, String obo, String ip)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
{
// smooth out the OnBehalfOf request, so that empty strings are
// treated as null
if ("".equals(obo))
{
obo = null;
}
// first find out if we support on-behalf-of deposit
boolean mediated = ConfigurationManager.getBooleanProperty("sword.on-behalf-of.enable");
if (!mediated && obo != null)
{
// user is trying to do a mediated deposit on a repository which does not support it
log.error("Attempted mediated deposit on service not configured to do so");
throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED, "Mediated deposit to this service is not permitted");
}
log.info(LogManager.getHeader(context, "sword_authenticate", "username=" + un + ",on_behalf_of=" + obo));
try
{
// attempt to authenticate the primary user
SWORDContext sc = new SWORDContext();
EPerson ep = null;
boolean authenticated = false;
if (this.authenticates(context, un, pw))
{
// if authenticated, obtain the eperson object
ep = context.getCurrentUser();
if (ep != null)
{
authenticated = true;
sc.setAuthenticated(ep);
// Set any special groups - invoke the authentication mgr.
int[] groupIDs = AuthenticationManager.getSpecialGroups(context, null);
for (int i = 0; i < groupIDs.length; i++)
{
context.setSpecialGroup(groupIDs[i]);
log.debug("Adding Special Group id="+String.valueOf(groupIDs[i]));
}
sc.setAuthenticatorContext(context);
sc.setContext(context);
}
// if there is an onBehalfOfuser, then find their eperson
// record, and if it exists set it. If not, then the
// authentication process fails
EPerson epObo = null;
if (obo != null)
{
epObo = EPerson.findByEmail(context, obo);
if (epObo == null)
{
epObo = EPerson.findByNetid(context, obo);
}
if (epObo != null)
{
sc.setOnBehalfOf(epObo);
Context oboContext = this.constructContext(ip);
oboContext.setCurrentUser(epObo);
// Set any special groups - invoke the authentication mgr.
int[] groupIDs = AuthenticationManager.getSpecialGroups(oboContext, null);
for (int i = 0; i < groupIDs.length; i++)
{
oboContext.setSpecialGroup(groupIDs[i]);
log.debug("Adding Special Group id="+String.valueOf(groupIDs[i]));
}
sc.setContext(oboContext);
}
else
{
authenticated = false;
throw new SWORDErrorException(ErrorCodes.TARGET_OWNER_UKNOWN, "unable to identify on-behalf-of user: " + obo);
}
}
}
if (!authenticated)
{
// decide what kind of error to throw
if (ep != null)
{
log.info(LogManager.getHeader(context, "sword_unable_to_set_user", "username=" + un));
throw new SWORDAuthenticationException("Unable to authenticate the supplied used");
}
else
{
// FIXME: this shouldn't ever happen now, but may as well leave it in just in case
// there's a bug elsewhere
log.info(LogManager.getHeader(context, "sword_unable_to_set_on_behalf_of", "username=" + un + ",on_behalf_of=" + obo));
throw new SWORDAuthenticationException("Unable to authenticate the onBehalfOf account");
}
}
return sc;
}
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new SWORDException("There was a problem accessing the repository user database", e);
}
catch (AuthorizeException e)
{
log.error("caught exception: ", e);
throw new SWORDAuthenticationException("There was a problem authenticating or authorising the user", e);
}
}
/**
* Can the users contained in this object's member SWORDContext
* make a successful submission to the selected collection.
*
* See javadocs for individual canSubmitTo methods to see the conditions
* which are applied in each situation
*
* @return true if yes, false if not
* @throws DSpaceSWORDException
*/
public boolean canSubmit(SWORDService swordService, Deposit deposit, DSpaceObject dso)
throws DSpaceSWORDException, SWORDErrorException
{
// get the things we need out of the service
SWORDContext swordContext = swordService.getSwordContext();
// determine if we can submit
boolean submit = this.canSubmitTo(swordContext, dso);
if (submit)
{
swordService.message("User is authorised to submit to collection");
}
else
{
swordService.message("User is not authorised to submit to collection");
}
return submit;
}
/**
* Is the authenticated user a DSpace administrator? This translates
* as asking the question of whether the given eperson is a member
* of the special DSpace group Administrator, with id 1
*
* @param swordContext
* @return true if administrator, false if not
* @throws SQLException
*/
public boolean isUserAdmin(SWORDContext swordContext)
throws DSpaceSWORDException
{
try
{
EPerson authenticated = swordContext.getAuthenticated();
if (authenticated != null)
{
return AuthorizeManager.isAdmin(swordContext.getAuthenticatorContext());
}
return false;
}
catch (SQLException e)
{
log.error("Caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Is the given onBehalfOf user DSpace administrator? This translates
* as asking the question of whether the given eperson is a member
* of the special DSpace group Administrator, with id 1
*
* @param swordContext
* @return true if administrator, false if not
* @throws SQLException
*/
public boolean isOnBehalfOfAdmin(SWORDContext swordContext)
throws DSpaceSWORDException
{
EPerson onBehalfOf = swordContext.getOnBehalfOf();
try
{
if (onBehalfOf != null)
{
return AuthorizeManager.isAdmin(swordContext.getOnBehalfOfContext());
}
return false;
}
catch (SQLException e)
{
log.error("Caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Is the authenticated user a member of the given group
* or one of its sub groups?
*
* @param group
* @return
*/
public boolean isUserInGroup(SWORDContext swordContext, Group group)
{
EPerson authenticated = swordContext.getAuthenticated();
if (authenticated != null)
{
return isInGroup(group, authenticated);
}
return false;
}
/**
* Is the onBehalfOf user a member of the given group or
* one of its sub groups
*
* @param group
* @return
*/
public boolean isOnBehalfOfInGroup(SWORDContext swordContext, Group group)
{
EPerson onBehalfOf = swordContext.getOnBehalfOf();
if (onBehalfOf != null)
{
return isInGroup(group, onBehalfOf);
}
return false;
}
/**
* Is the given eperson in the given group, or any of the groups
* that are also members of that group. This method recurses
* until it has exhausted the tree of groups or finds the given
* eperson
*
* @param group
* @param eperson
* @return true if in group, false if not
*/
public boolean isInGroup(Group group, EPerson eperson)
{
EPerson[] eps = group.getMembers();
Group[] groups = group.getMemberGroups();
// is the user in the current group
for (int i = 0; i < eps.length; i++)
{
if (eperson.getID() == eps[i].getID())
{
return true;
}
}
// is the eperson in the sub-groups (recurse)
if (groups != null && groups.length > 0)
{
for (int j = 0; j < groups.length; j++)
{
if (isInGroup(groups[j], eperson))
{
return true;
}
}
}
// ok, we didn't find you
return false;
}
/**
* Get an array of all the communities that the current SWORD
* context will allow deposit onto in the given DSpace context
*
* The user may submit to a community if the following conditions
* are met:
*
* IF: the authenticated user is an administrator
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to READ
* OR the on-behalf-of user is null)
* OR IF: the authenticated user is authorised to READ
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to READ
* OR the on-behalf-of user is null)
*
* @param swordContext
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public List<Community> getAllowedCommunities(SWORDContext swordContext)
throws DSpaceSWORDException
{
// a community is allowed if the following conditions are met
//
// - the authenticated user is an administrator
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to READ
// -- the on-behalf-of user is null
// - the authenticated user is authorised to READ
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to READ
// -- the on-behalf-of user is null
try
{
// locate all the top level communities
Context context = swordContext.getContext();
List<Community> allowed = new ArrayList<Community>();
Community[] comms = Community.findAllTop(context);
for (int i = 0; i < comms.length; i++)
{
boolean authAllowed = false;
boolean oboAllowed = false;
// check for obo null
if (swordContext.getOnBehalfOf() == null)
{
oboAllowed = true;
}
// look up the READ policy on the community. This will include determining if the user is an administrator
// so we do not need to check that separately
if (!authAllowed)
{
authAllowed = AuthorizeManager.authorizeActionBoolean(swordContext.getAuthenticatorContext(), comms[i], Constants.READ);
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = AuthorizeManager.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), comms[i], Constants.READ);
}
// final check to see if we are allowed to READ
if (authAllowed && oboAllowed)
{
allowed.add(comms[i]);
}
}
return allowed;
}
catch (SQLException e)
{
log.error("Caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Get an array of all the collections that the current SWORD
* context will allow deposit onto in the given DSpace context
*
* The user may submit to a community if the following conditions
* are met:
*
* IF: the authenticated user is an administrator
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to READ
* OR the on-behalf-of user is null)
* OR IF: the authenticated user is authorised to READ
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to READ
* OR the on-behalf-of user is null)
*
* @param community
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public List<Community> getCommunities(SWORDContext swordContext, Community community)
throws DSpaceSWORDException
{
// a community is allowed if the following conditions are met
//
// - the authenticated user is an administrator
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to READ
// -- the on-behalf-of user is null
// - the authenticated user is authorised to READ
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to READ
// -- the on-behalf-of user is null
try
{
Community[] comms = community.getSubcommunities();
List<Community> allowed = new ArrayList<Community>();
for (int i = 0; i < comms.length; i++)
{
boolean authAllowed = false;
boolean oboAllowed = false;
// check for obo null
if (swordContext.getOnBehalfOf() == null)
{
oboAllowed = true;
}
// look up the READ policy on the community. This will include determining if the user is an administrator
// so we do not need to check that separately
if (!authAllowed)
{
authAllowed = AuthorizeManager.authorizeActionBoolean(swordContext.getAuthenticatorContext(), comms[i], Constants.READ);
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = AuthorizeManager.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), comms[i], Constants.READ);
}
// final check to see if we are allowed to READ
if (authAllowed && oboAllowed)
{
allowed.add(comms[i]);
}
}
return allowed;
}
catch (SQLException e)
{
log.error("Caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Get an array of all the collections that the current SWORD
* context will allow deposit onto in the given DSpace context
*
* Forwards to:
*
* getAllowedCollections(swordContext, null)
*
* See that method for details of the conditions applied
*
* @param swordContext
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public List<org.dspace.content.Collection> getAllowedCollections(SWORDContext swordContext)
throws DSpaceSWORDException
{
return this.getAllowedCollections(swordContext, null);
}
/**
* Get an array of all the collections that the current SWORD
* context will allow deposit onto in the given DSpace context
*
* IF: the authenticated user is an administrator
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to ADD
* OR the on-behalf-of user is null)
* OR IF: the authenticated user is authorised to ADD
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to ADD
* OR the on-behalf-of user is null)
*
* @param swordContext
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public List<org.dspace.content.Collection> getAllowedCollections(SWORDContext swordContext, Community community)
throws DSpaceSWORDException
{
// a collection is allowed if the following conditions are met
//
// - the authenticated user is an administrator
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to ADD
// -- the on-behalf-of user is null
// - the authenticated user is authorised to ADD
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to ADD
// -- the on-behalf-of user is null
try
{
// get the context of the authenticated user
Context authContext = swordContext.getAuthenticatorContext();
// short cut by obtaining the collections to which the authenticated user can submit
org.dspace.content.Collection[] cols = org.dspace.content.Collection.findAuthorized(authContext, community, Constants.ADD);
List<org.dspace.content.Collection> allowed = new ArrayList<org.dspace.content.Collection>();
// now find out if the obo user is allowed to submit to any of these collections
for (int i = 0; i < cols.length; i++)
{
boolean oboAllowed = false;
// check for obo null
if (swordContext.getOnBehalfOf() == null)
{
oboAllowed = true;
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = AuthorizeManager.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), cols[i], Constants.ADD);
}
// final check to see if we are allowed to READ
if (oboAllowed)
{
allowed.add(cols[i]);
}
}
return allowed;
}
catch (SQLException e)
{
log.error("Caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Get a list of all the items that the current SWORD
* context will allow deposit onto in the given DSpace context
*
* IF: the authenticated user is an administrator
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
* OR the on-behalf-of user is null)
* OR IF: the authenticated user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
* OR the on-behalf-of user is null)
*
* @param swordContext
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public List<Item> getAllowedItems(SWORDContext swordContext, org.dspace.content.Collection collection)
throws DSpaceSWORDException
{
// an item is allowed if the following conditions are met
//
// - the authenticated user is an administrator
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
// -- the on-behalf-of user is null
// - the authenticated user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
// -- the on-behalf-of user is null
try
{
List<Item> allowed = new ArrayList<Item>();
ItemIterator ii = collection.getItems();
while (ii.hasNext())
{
Item item = ii.next();
boolean authAllowed = false;
boolean oboAllowed = false;
// check for obo null
if (swordContext.getOnBehalfOf() == null)
{
oboAllowed = true;
}
// get the "ORIGINAL" bundle(s)
Bundle[] bundles = item.getBundles("ORIGINAL");
// look up the READ policy on the community. This will include determining if the user is an administrator
// so we do not need to check that separately
if (!authAllowed)
{
boolean write = AuthorizeManager.authorizeActionBoolean(swordContext.getAuthenticatorContext(), item, Constants.WRITE);
boolean add = false;
for (int i = 0; i < bundles.length; i++)
{
add = AuthorizeManager.authorizeActionBoolean(swordContext.getAuthenticatorContext(), bundles[i], Constants.ADD);
if (!add)
{
break;
}
}
authAllowed = write && add;
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
boolean write = AuthorizeManager.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), item, Constants.WRITE);
boolean add = false;
for (int i = 0; i < bundles.length; i++)
{
add = AuthorizeManager.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), bundles[i], Constants.ADD);
if (!add)
{
break;
}
}
oboAllowed = write && add;
}
// final check to see if we are allowed to READ
if (authAllowed && oboAllowed)
{
allowed.add(item);
}
}
return allowed;
}
catch (SQLException e)
{
throw new DSpaceSWORDException(e);
}
}
/**
* Can the current SWORD Context permit deposit into the given
* collection in the given DSpace Context
*
* IF: the authenticated user is an administrator
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to ADD
* OR the on-behalf-of user is null)
* OR IF: the authenticated user is authorised to ADD
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to ADD
* OR the on-behalf-of user is null)
*
* @param swordContext
* @param collection
* @return
* @throws DSpaceSWORDException
*/
public boolean canSubmitTo(SWORDContext swordContext, org.dspace.content.Collection collection)
throws DSpaceSWORDException
{
// a user can submit to a collection in the following conditions:
//
// - the authenticated user is an administrator
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to ADD/in the submission group
// -- the on-behalf-of user is null
// - the authenticated user is authorised to ADD/in the submission group
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to ADD/in the submission group
// -- the on-behalf-of user is null
try
{
boolean authAllowed = false;
boolean oboAllowed = false;
// check for obo null
if (swordContext.getOnBehalfOf() == null)
{
oboAllowed = true;
}
// look up the READ policy on the collection. This will include determining if the user is an administrator
// so we do not need to check that separately
if (!authAllowed)
{
authAllowed = AuthorizeManager.authorizeActionBoolean(swordContext.getAuthenticatorContext(), collection, Constants.ADD);
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = AuthorizeManager.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), collection, Constants.ADD);
}
// final check to see if we are allowed to READ
return (authAllowed && oboAllowed);
}
catch (SQLException e)
{
log.error("Caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Does the given context have the authority to submit to the given item.
*
* The context has permission of the following conditions are met:
*
* IF: the authenticated user is an administrator
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
* OR the on-behalf-of user is null)
* OR IF: the authenticated user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
* AND:
* (the on-behalf-of user is an administrator
* OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
* OR the on-behalf-of user is null)
*
* @param swordContext
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public boolean canSubmitTo(SWORDContext swordContext, Item item)
throws DSpaceSWORDException
{
// a user can submit to a collection in the following conditions:
//
// - the authenticated user is an administrator
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
// -- the on-behalf-of user is null
// - the authenticated user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
// -- the on-behalf-of user is an administrator
// -- the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
// -- the on-behalf-of user is null
try
{
boolean authAllowed = false;
boolean oboAllowed = false;
// check for obo null
if (swordContext.getOnBehalfOf() == null)
{
oboAllowed = true;
}
// get the "ORIGINAL" bundle(s)
Bundle[] bundles = item.getBundles("ORIGINAL");
// look up the READ policy on the community. This will include determining if the user is an administrator
// so we do not need to check that separately
if (!authAllowed)
{
boolean write = AuthorizeManager.authorizeActionBoolean(swordContext.getAuthenticatorContext(), item, Constants.WRITE);
boolean add = false;
for (int i = 0; i < bundles.length; i++)
{
add = AuthorizeManager.authorizeActionBoolean(swordContext.getAuthenticatorContext(), bundles[i], Constants.ADD);
if (!add)
{
break;
}
}
authAllowed = write && add;
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
boolean write = AuthorizeManager.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), item, Constants.WRITE);
boolean add = false;
for (int i = 0; i < bundles.length; i++)
{
add = AuthorizeManager.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), bundles[i], Constants.ADD);
if (!add)
{
break;
}
}
oboAllowed = write && add;
}
// final check to see if we are allowed to READ
return (authAllowed && oboAllowed);
}
catch (SQLException e)
{
log.error("Caught exception: ", e);
throw new DSpaceSWORDException(e);
}
}
/**
* Can the given context submit to the specified dspace object.
*
* This forwards to the individual methods for different object types; see
* their documentation for details of the conditions.
*
* @param context
* @param dso
* @return
* @throws DSpaceSWORDException
*/
public boolean canSubmitTo(SWORDContext context, DSpaceObject dso)
throws DSpaceSWORDException
{
if (dso instanceof org.dspace.content.Collection)
{
return this.canSubmitTo(context, (org.dspace.content.Collection) dso);
}
else if (dso instanceof Item)
{
return this.canSubmitTo(context, (Item) dso);
}
else
{
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.sword;
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.Item;
import org.dspace.core.Context;
import org.dspace.core.ConfigurationManager;
import org.dspace.authorize.AuthorizeException;
import org.purl.sword.base.Deposit;
import org.purl.sword.base.SWORDErrorException;
import org.purl.sword.base.ErrorCodes;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
/**
* @author Richard Jones
*
* A depositor which can deposit content into a DSpace Collection
*
*/
public class CollectionDepositor extends Depositor
{
/** logger */
private static Logger log = Logger.getLogger(CollectionDepositor.class);
/**
* The DSpace Collection we are depositing into
*/
private Collection collection;
/**
* Construct a depositor for the given service instance on the
* given DSpaceObject. If the DSpaceObject is not an instance of Collection
* this constructor will throw an Exception
*
* @param swordService
* @param dso
* @throws DSpaceSWORDException
*/
public CollectionDepositor(SWORDService swordService, DSpaceObject dso)
throws DSpaceSWORDException
{
super(swordService, dso);
if (!(dso instanceof Collection))
{
throw new DSpaceSWORDException("You tried to initialise the collection depositor with something" +
"other than a collection object");
}
this.collection = (Collection) dso;
log.debug("Created instance of CollectionDepositor");
}
/**
* Perform a deposit, using the supplied SWORD Deposit object
*
* @param deposit
* @return
* @throws SWORDErrorException
* @throws DSpaceSWORDException
*/
public DepositResult doDeposit(Deposit deposit)
throws SWORDErrorException, DSpaceSWORDException
{
// get the things out of the service that we need
Context context = swordService.getContext();
SWORDConfiguration swordConfig = swordService.getSwordConfig();
SWORDUrlManager urlManager = swordService.getUrlManager();
// FIXME: the spec is unclear what to do in this situation. I'm going
// the throw a 415 (ERROR_CONTENT) until further notice
//
// determine if this is an acceptable file format
if (!swordConfig.isAcceptableContentType(context, deposit.getContentType(), collection))
{
log.error("Unacceptable content type detected: " + deposit.getContentType() + " for collection " + collection.getID());
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT,
"Unacceptable content type in deposit request: " + deposit.getContentType());
}
// determine if this is an acceptable packaging type for the deposit
// if not, we throw a 415 HTTP error (Unsupported Media Type, ERROR_CONTENT)
if (!swordConfig.isSupportedMediaType(deposit.getPackaging(), this.collection))
{
log.error("Unacceptable packaging type detected: " + deposit.getPackaging() + "for collection" + collection.getID());
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT,
"Unacceptable packaging type in deposit request: " + deposit.getPackaging());
}
// Obtain the relevant ingester from the factory
SWORDIngester si = SWORDIngesterFactory.getInstance(context, deposit, collection);
swordService.message("Loaded ingester: " + si.getClass().getName());
// do the deposit
DepositResult result = si.ingest(swordService, deposit, collection);
swordService.message("Archive ingest completed successfully");
// if there's an item availalble, and we want to keep the original
// then do that
try
{
if (swordConfig.isKeepOriginal())
{
swordService.message("DSpace will store an original copy of the deposit, " +
"as well as ingesting the item into the archive");
// in order to be allowed to add the file back to the item, we need to ignore authorisations
// for a moment
boolean ignoreAuth = context.ignoreAuthorization();
context.setIgnoreAuthorization(true);
String bundleName = ConfigurationManager.getProperty("sword.bundle.name");
if (bundleName == null || "".equals(bundleName))
{
bundleName = "SWORD";
}
Item item = result.getItem();
Bundle[] bundles = item.getBundles(bundleName);
Bundle swordBundle = null;
if (bundles.length > 0)
{
swordBundle = bundles[0];
}
if (swordBundle == null)
{
swordBundle = item.createBundle(bundleName);
}
String fn = swordService.getFilename(context, deposit, true);
Bitstream bitstream;
FileInputStream fis = null;
try
{
fis = new FileInputStream(deposit.getFile());
bitstream = swordBundle.createBitstream(fis);
}
finally
{
if (fis != null)
{
fis.close();
}
}
bitstream.setName(fn);
bitstream.setDescription("SWORD deposit package");
BitstreamFormat bf = BitstreamFormat.findByMIMEType(context, deposit.getContentType());
if (bf != null)
{
bitstream.setFormat(bf);
}
bitstream.update();
swordBundle.update();
item.update();
swordService.message("Original package stored as " + fn + ", in item bundle " + swordBundle);
// now reset the context ignore authorisation
context.setIgnoreAuthorization(ignoreAuth);
// set the media link for the created item
result.setMediaLink(urlManager.getMediaLink(bitstream));
}
else
{
// set the vanilla media link, which doesn't resolve to anything
result.setMediaLink(urlManager.getBaseMediaLinkUrl());
}
}
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new DSpaceSWORDException(e);
}
catch (AuthorizeException e)
{
log.error("caught exception: ", e);
throw new DSpaceSWORDException(e);
}
catch (FileNotFoundException e)
{
log.error("caught exception: ", e);
throw new DSpaceSWORDException(e);
}
catch (IOException e)
{
log.error("caught exception: ", e);
throw new DSpaceSWORDException(e);
}
return result;
}
/**
* Reverse any changes which may have resulted as the consequence of a deposit.
*
* This is inteded for use during no-op deposits, and should be called at the
* end of such a deposit process in order to remove any temporary files and
* to abort the database connection, so no changes are written.
*
* @param result
* @throws DSpaceSWORDException
*/
public void undoDeposit(DepositResult result) throws DSpaceSWORDException
{
SWORDContext sc = swordService.getSwordContext();
// abort the context, so no database changes are written
// uploaded files will be deleted by the cleanup script
sc.abort();
swordService.message("Database changes aborted");
}
}
| 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.sword;
import java.sql.SQLException;
import java.util.Date;
import java.text.SimpleDateFormat;
import org.apache.log4j.Logger;
import org.dspace.core.Context;
import org.dspace.content.BitstreamFormat;
import org.purl.sword.base.Deposit;
/**
* @author Richard Jones
*
* This class represents the actual sword service provided by dspace. It
* is the central location for the authentcated contexts, the installation
* specific configuration, and the url management.
*
* It is ubiquotous in the sword implementation, and all related
* information and services should be retrived via this api
*
*/
public class SWORDService
{
/** Log4j logging instance */
public static final Logger log = Logger.getLogger(SWORDService.class);
/** The SWORD context of the request */
private SWORDContext swordContext;
/** The configuration of the sword server instance */
private SWORDConfiguration swordConfig;
/** The URL Generator */
private SWORDUrlManager urlManager;
/** a holder for the messages coming through from the implementation */
private StringBuilder verboseDescription = new StringBuilder();
/** is this a verbose operation */
private boolean verbose = false;
/** date formatter */
private SimpleDateFormat dateFormat;
/**
* Construct a new service instance around the given authenticated
* sword context
*
* @param sc
*/
public SWORDService(SWORDContext sc)
{
this.swordContext = sc;
this.swordConfig = new SWORDConfiguration();
this.urlManager = new SWORDUrlManager(this.swordConfig, this.swordContext.getContext());
dateFormat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss.S]");
}
public SWORDUrlManager getUrlManager()
{
return urlManager;
}
public void setUrlManager(SWORDUrlManager urlManager)
{
this.urlManager = urlManager;
}
public SWORDContext getSwordContext()
{
return swordContext;
}
public void setSwordContext(SWORDContext swordContext)
{
this.swordContext = swordContext;
}
public SWORDConfiguration getSwordConfig()
{
return swordConfig;
}
public void setSwordConfig(SWORDConfiguration swordConfig)
{
this.swordConfig = swordConfig;
}
public Context getContext()
{
return this.swordContext.getContext();
}
public boolean isVerbose()
{
return verbose;
}
public void setVerbose(boolean verbose)
{
this.verbose = verbose;
}
public StringBuilder getVerboseDescription()
{
return verboseDescription;
}
/**
* shortcut to registering a message with the verboseDescription
* member variable. This checks to see if the request is
* verbose, meaning we don't have to do it inline and break nice
* looking code up
*
* @param message
*/
public void message(String message)
{
// build the processing message
String msg = dateFormat.format(new Date()) + " " + message + "; \n\n";
// if this is a verbose deposit, then log it
if (this.verbose)
{
verboseDescription.append(msg);
}
// add to server logs anyway
log.info(msg);
}
/**
* Construct the most appropriate filename for the incoming deposit
*
* @param context
* @param deposit
* @param original
* @return
* @throws DSpaceSWORDException
*/
public String getFilename(Context context, Deposit deposit, boolean original)
throws DSpaceSWORDException
{
try
{
BitstreamFormat bf = BitstreamFormat.findByMIMEType(context, deposit.getContentType());
String[] exts = null;
if (bf != null)
{
exts = bf.getExtensions();
}
String fn = deposit.getFilename();
if (fn == null || "".equals(fn))
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
fn = "sword-" + sdf.format(new Date());
if (original)
{
fn = fn + ".original";
}
if (exts != null)
{
fn = fn + "." + exts[0];
}
}
return fn;
}
catch (SQLException e)
{
throw new DSpaceSWORDException(e);
}
}
/**
* Get the name of the temp files that should be used
*
* @return
*/
public String getTempFilename()
{
return "sword-" + (new Date()).getTime();
}
}
| 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.sword;
import java.io.*;
import java.util.Date;
import org.apache.log4j.Logger;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.core.Utils;
import org.purl.sword.base.Deposit;
import org.purl.sword.base.DepositResponse;
import org.purl.sword.base.SWORDAuthenticationException;
import org.purl.sword.base.SWORDEntry;
import org.purl.sword.base.SWORDErrorException;
/**
* This class is responsible for initiating the process of
* deposit of SWORD Deposit objects into the DSpace repository
*
* @author Richard Jones
*
*/
public class DepositManager
{
/** Log4j logger */
public static final Logger log = Logger.getLogger(DepositManager.class);
/** The SWORD service implementation */
private SWORDService swordService;
/**
* Construct a new DepositManager using the given instantiation of
* the SWORD service implementation
*
* @param service
*/
public DepositManager(SWORDService service)
{
this.swordService = service;
log.debug("Created instance of DepositManager");
}
public DSpaceObject getDepositTarget(Deposit deposit)
throws DSpaceSWORDException, SWORDErrorException
{
SWORDUrlManager urlManager = swordService.getUrlManager();
Context context = swordService.getContext();
// get the target collection
String loc = deposit.getLocation();
DSpaceObject dso = urlManager.getDSpaceObject(context, loc);
swordService.message("Performing deposit using location: " + loc);
if (dso instanceof Collection)
{
swordService.message("Location resolves to collection with handle: " + dso.getHandle() +
" and name: " + ((Collection) dso).getMetadata("name"));
}
else if (dso instanceof Item)
{
swordService.message("Location resolves to item with handle: " + dso.getHandle());
}
return dso;
}
/**
* Once this object is fully prepared, this method will execute
* the deposit process. The returned DepositRequest can be
* used then to assemble the SWORD response.
*
* @return the response to the deposit request
* @throws DSpaceSWORDException
*/
public DepositResponse deposit(Deposit deposit)
throws DSpaceSWORDException, SWORDErrorException, SWORDAuthenticationException
{
// start the timer, and initialise the verboseness of the request
Date start = new Date();
swordService.message("Initialising verbose deposit");
// get the things out of the service that we need
SWORDContext swordContext = swordService.getSwordContext();
Context context = swordService.getContext();
// get the deposit target
DSpaceObject dso = this.getDepositTarget(deposit);
// find out if the supplied SWORDContext can submit to the given
// dspace object
SWORDAuthenticator auth = new SWORDAuthenticator();
if (!auth.canSubmit(swordService, deposit, dso))
{
// throw an exception if the deposit can't be made
String oboEmail = "none";
if (swordContext.getOnBehalfOf() != null)
{
oboEmail = swordContext.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "deposit_failed_authorisation", "user=" +
swordContext.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SWORDAuthenticationException("Cannot submit to the given collection with this context");
}
// make a note of the authentication in the verbose string
swordService.message("Authenticated user: " + swordContext.getAuthenticated().getEmail());
if (swordContext.getOnBehalfOf() != null)
{
swordService.message("Depositing on behalf of: " + swordContext.getOnBehalfOf().getEmail());
}
// determine which deposit engine we initialise
Depositor dep = null;
if (dso instanceof Collection)
{
swordService.message("Initialising depositor for an Item in a Collection");
dep = new CollectionDepositor(swordService, dso);
}
else if (dso instanceof Item)
{
swordService.message("Initialising depositor for a Bitstream in an Item");
dep = new ItemDepositor(swordService, dso);
}
if (dep == null)
{
log.error("The specified deposit target does not exist, or is not a collection or an item");
throw new DSpaceSWORDException("Deposit target is not a collection or an item");
}
DepositResult result = null;
try
{
result = dep.doDeposit(deposit);
}
catch(DSpaceSWORDException e)
{
if (swordService.getSwordConfig().isKeepPackageOnFailedIngest())
{
try
{
storePackageAsFile(deposit);
}
catch(IOException e2)
{
log.warn("Unable to store SWORD package as file: " + e);
}
}
throw e;
}
catch(SWORDErrorException e)
{
if (swordService.getSwordConfig().isKeepPackageOnFailedIngest())
{
try
{
storePackageAsFile(deposit);
}
catch(IOException e2)
{
log.warn("Unable to store SWORD package as file: " + e);
}
}
throw e;
}
// now construct the deposit response. The response will be
// CREATED if the deposit is in the archive, or ACCEPTED if
// the deposit is in the workflow. We use a separate record
// for the handle because DSpace will not supply the Item with
// a record of the handle straight away.
String handle = result.getHandle();
int state = Deposit.CREATED;
if (handle == null || "".equals(handle))
{
state = Deposit.ACCEPTED;
}
DepositResponse response = new DepositResponse(state);
response.setLocation(result.getMediaLink());
DSpaceATOMEntry dsatom = null;
if (result.getItem() != null)
{
swordService.message("Initialising ATOM entry generator for an Item");
dsatom = new ItemEntryGenerator(swordService);
}
else if (result.getBitstream() != null)
{
swordService.message("Initialising ATOM entry generator for a Bitstream");
dsatom = new BitstreamEntryGenerator(swordService);
}
if (dsatom == null)
{
log.error("The deposit failed, see exceptions for explanation");
throw new DSpaceSWORDException("Result of deposit did not yield an Item or a Bitstream");
}
SWORDEntry entry = dsatom.getSWORDEntry(result, deposit);
// if this was a no-op, we need to remove the files we just
// deposited, and abort the transaction
if (deposit.isNoOp())
{
dep.undoDeposit(result);
swordService.message("NoOp Requested: Removed all traces of submission");
}
entry.setNoOp(deposit.isNoOp());
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
swordService.message("Total time for deposit processing: " + delta + " ms");
entry.setVerboseDescription(swordService.getVerboseDescription().toString());
response.setEntry(entry);
return response;
}
/**
* Store original package on disk and companion file containing SWORD headers as found in the deposit object
* Also write companion file with header info from the deposit object.
*
* @param deposit
*/
private void storePackageAsFile(Deposit deposit) throws IOException
{
String path = swordService.getSwordConfig().getFailedPackageDir();
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory())
{
throw new IOException("Directory does not exist for writing packages on ingest error.");
}
String filenameBase = "sword-" + deposit.getUsername() + "-" + (new Date()).getTime();
File packageFile = new File(path, filenameBase);
File headersFile = new File(path, filenameBase + "-headers");
InputStream is = new BufferedInputStream(new FileInputStream(deposit.getFile()));
OutputStream fos = new BufferedOutputStream(new FileOutputStream(packageFile));
Utils.copy(is, fos);
fos.close();
is.close();
//write companion file with headers
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(headersFile)));
pw.println("Content-Disposition=" + deposit.getContentDisposition());
pw.println("Content-Type=" + deposit.getContentType());
pw.println("Packaging=" + deposit.getPackaging());
pw.println("Location=" + deposit.getLocation());
pw.println("On Behalf of=" + deposit.getOnBehalfOf());
pw.println("Slug=" + deposit.getSlug());
pw.println("User name=" + deposit.getUsername());
pw.close();
}
}
| 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.sword;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.handle.HandleManager;
/**
* This class provides a single point of contact for
* resolving Collections from SWORD Deposit URLs and for
* generating SWORD Deposit URLs from Collections
*
* @author Richard Jones
*
*/
public class CollectionLocation
{
/** Log4j logger */
public static final Logger log = Logger.getLogger(CollectionLocation.class);
/**
* Obtain the deposit URL for the given collection. These URLs
* should not be considered persistent, but will remain consistent
* unless configuration changes are made to DSpace
*
* @param collection
* @return The Deposit URL
* @throws DSpaceSWORDException
*/
public String getLocation(Collection collection)
throws DSpaceSWORDException
{
return this.getBaseUrl() + "/" + collection.getHandle();
}
/**
* Obtain the collection which is represented by the given
* URL
*
* @param context the DSpace context
* @param location the URL to resolve to a collection
* @return The collection to which the url resolves
* @throws DSpaceSWORDException
*/
public Collection getCollection(Context context, String location)
throws DSpaceSWORDException
{
try
{
String baseUrl = this.getBaseUrl();
if (baseUrl.length() == location.length())
{
throw new DSpaceSWORDException("The deposit URL is incomplete");
}
String handle = location.substring(baseUrl.length());
if (handle.startsWith("/"))
{
handle = handle.substring(1);
}
if ("".equals(handle))
{
throw new DSpaceSWORDException("The deposit URL is incomplete");
}
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
if (!(dso instanceof Collection))
{
throw new DSpaceSWORDException("The deposit URL does not resolve to a valid collection");
}
return (Collection) dso;
}
catch (SQLException e)
{
log.error("Caught exception:", e);
throw new DSpaceSWORDException("There was a problem resolving the collection", e);
}
}
/**
* Get the base deposit URL for the DSpace SWORD implementation. This
* is effectively the URL of the servlet which deals with deposit
* requests, and is used as the basis for the individual Collection
* URLs
*
* If the configuration sword.deposit.url is set, this will be returned,
* but if not, it will construct the url as follows:
*
* [dspace.baseUrl]/sword/deposit
*
* where dspace.baseUrl is also in the configuration file.
*
* @return the base URL for sword deposit
* @throws DSpaceSWORDException
*/
private String getBaseUrl()
throws DSpaceSWORDException
{
String depositUrl = ConfigurationManager.getProperty("sword.deposit.url");
if (depositUrl == null || "".equals(depositUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSWORDException("Unable to construct deposit urls, due to missing/invalid config in sword.deposit.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
depositUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/sword/deposit").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSWORDException("Unable to construct deposit urls, due to invalid dspace.baseUrl " + e.getMessage(),e);
}
}
return depositUrl;
}
}
| 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.sword;
import org.dspace.content.Item;
import org.dspace.content.Bitstream;
/**
* The DSpace class for representing the results of a deposit
* request. This class can be used to hold all of the relevant
* components required to later build the SWORD response
*
* @author Richard Jones
*
*/
public class DepositResult
{
/** the handle assigned to the item, if available */
private String handle;
/** the item created during deposit */
private Item item;
/** Bitstream created as a result of the deposit */
private Bitstream bitstream;
/** The treatment of the item during deposit */
private String treatment;
/** The media linkto the created object */
private String mediaLink;
public Bitstream getBitstream()
{
return bitstream;
}
public void setBitstream(Bitstream bitstream)
{
this.bitstream = bitstream;
}
public String getTreatment()
{
return treatment;
}
public void setTreatment(String treatment)
{
this.treatment = treatment;
}
/**
* @return the item
*/
public Item getItem()
{
return item;
}
/**
* @param item the item to set
*/
public void setItem(Item item)
{
this.item = item;
}
/**
* @return the handle
*/
public String getHandle()
{
return handle;
}
/**
* @param handle the item handle
*/
public void setHandle(String handle)
{
this.handle = handle;
}
public String getMediaLink()
{
return mediaLink;
}
public void setMediaLink(String mediaLink)
{
this.mediaLink = mediaLink;
}
}
| 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.sword;
/**
* This Exception class can be thrown by the internals of the
* DSpace SWORD implementation
*
* @author Richard Jones
*
*/
public class DSpaceSWORDException extends Exception
{
public DSpaceSWORDException()
{
super();
}
public DSpaceSWORDException(String arg0, Throwable arg1)
{
super(arg0, arg1);
}
public DSpaceSWORDException(String arg0)
{
super(arg0);
}
public DSpaceSWORDException(Throwable arg0)
{
super(arg0);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.purl.sword.base;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import nu.xom.Element;
import nu.xom.Elements;
import org.apache.log4j.Logger;
import org.purl.sword.atom.ContentType;
import org.purl.sword.atom.Title;
/**
* Represents an Atom Publishing Protocol Workspace element.
*
* @author Neil Taylor
*/
public class Workspace extends XmlElement implements SwordElementInterface
{
/**
* The title for the workspace.
*/
private Title title;
/**
* A list of collections associated with this workspace.
*/
private List<Collection> collections;
/**
* The logger.
*/
private static Logger log = Logger.getLogger(Workspace.class);
/**
* Local name part of this element.
*/
@Deprecated
public static final String ELEMENT_NAME = "workspace";
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_APP, "workspace", Namespaces.NS_APP);
/**
* Create a new instance of the workspace, with no title.
*/
public Workspace( )
{
super(XML_NAME);
initialise();
}
public static XmlName elementName()
{
return XML_NAME;
}
/**
* Create a new instance of the workspace with the specified title.
*
* @param title The title.
*/
public Workspace( String title )
{
this();
setTitle(title);
}
/**
* Initialise the object, ready for use.
*/
protected final void initialise()
{
collections = new ArrayList<Collection>();
title = null;
}
/**
* Set the title. The type for the title will be set to
* <code>ContentType.TEXT</code>
*
* @param title The title.
*/
public final void setTitle( String title )
{
if( this.title == null)
{
this.title = new Title();
}
this.title.setContent(title);
this.title.setType(ContentType.TEXT);
}
/**
* Get the content of the Title element.
*
* @return The title.
*/
public final String getTitle( )
{
if( title == null )
{
return null;
}
return title.getContent();
}
/**
* Add a collection to the Workspace.
*
* @param collection The collection.
*/
public void addCollection( Collection collection )
{
collections.add(collection);
}
/**
* Get an Iterator over the collections.
*
* @return An iterator.
*/
public Iterator<Collection> collectionIterator( )
{
return collections.iterator();
}
/**
* Get a list of the collections
*
* @return A list.
*/
public List<Collection> getCollections( )
{
return collections;
}
/**
* Marshal the data in this element to an Element.
*
* @return An element that contains the data in this object.
*/
public Element marshall( )
{
// convert data into XOM elements and return the 'root', i.e. the one
// that represents the collection.
Element workspace = new Element(xmlName.getQualifiedName(), xmlName.getNamespace());
if( title != null )
{
workspace.appendChild(title.marshall());
}
for( Collection item : collections )
{
workspace.appendChild(item.marshall());
}
return workspace;
}
/**
* Unmarshal the workspace element into the data in this object.
*
* @throws UnmarshallException If the element does not contain a
* workspace element or if there are problems
* accessing the data.
*/
public void unmarshall( Element workspace )
throws UnmarshallException
{
unmarshall(workspace, null);
}
/**
*
* @param workspace
* @param validationProperties
* @return
* @throws org.purl.sword.base.UnmarshallException
*/
public SwordValidationInfo unmarshall( Element workspace, Properties validationProperties )
throws UnmarshallException
{
if( ! isInstanceOf(workspace, xmlName))
{
return handleIncorrectElement(workspace, validationProperties);
}
ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>();
try
{
initialise();
// FIXME - process the attributes
// retrieve all of the sub-elements
Elements elements = workspace.getChildElements();
Element element = null;
int length = elements.size();
for(int i = 0; i < length; i++ )
{
element = elements.get(i);
if( isInstanceOf(element, Title.elementName() ) )
{
if( title == null )
{
title = new Title();
validationItems.add(title.unmarshall(element, validationProperties));
}
else
{
SwordValidationInfo info =
new SwordValidationInfo(Title.elementName(),
SwordValidationInfo.DUPLICATE_ELEMENT,
SwordValidationInfoType.WARNING);
info.setContentDescription(element.getValue());
validationItems.add(info);
}
}
else if( isInstanceOf(element, Collection.elementName() ))
{
Collection collection = new Collection( );
validationItems.add(collection.unmarshall(element, validationProperties));
collections.add(collection);
}
else if( validationProperties != null )
{
validationItems.add(new SwordValidationInfo(new XmlName(element),
SwordValidationInfo.UNKNOWN_ELEMENT,
SwordValidationInfoType.INFO));
}
}
}
catch( Exception ex )
{
log.error("Unable to parse an element in workspace: " + ex.getMessage());
throw new UnmarshallException("Unable to parse element in workspace.", ex);
}
SwordValidationInfo result = null;
if( validationProperties != null )
{
result = validate(validationItems, validationProperties);
}
return result;
}
/**
*
* @return A validation object that specifies the status of this object.
*/
@Override
public SwordValidationInfo validate(Properties validationContext)
{
return validate(null, validationContext);
}
/**
*
* @param existing
* @return
*/
protected SwordValidationInfo validate(List<SwordValidationInfo> existing,
Properties validationContext)
{
boolean validateAll = (existing == null );
SwordValidationInfo result = new SwordValidationInfo(xmlName);
if( collections == null || collections.size() == 0 )
{
result.addValidationInfo(new SwordValidationInfo(Collection.elementName(),
SwordValidationInfo.MISSING_ELEMENT_WARNING,
SwordValidationInfoType.WARNING ));
}
if( validateAll )
{
if( title != null )
{
result.addValidationInfo(title.validate(validationContext));
}
if( collections.size() > 0 )
{
Iterator<Collection> iterator = collections.iterator();
while( iterator.hasNext() )
{
result.addValidationInfo(iterator.next().validate(validationContext));
}
}
}
result.addUnmarshallValidationInfo(existing, null);
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.purl.sword.base;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import nu.xom.Element;
import nu.xom.Elements;
import org.apache.log4j.Logger;
import org.purl.sword.atom.Generator;
/**
* Represents an Atom Publishing Protocol Service element, with
* SWORD extensions.
*
* @author Neil Taylor
*/
public class Service extends XmlElement implements SwordElementInterface
{
private SwordVersion swordVersion;
private SwordNoOp swordNoOp;
private SwordVerbose swordVerbose;
private SwordMaxUploadSize swordMaxUploadSize;
/**
* The details of the server software that generated the service document.
*/
private Generator generator;
/**
* List of Workspaces.
*/
private List<Workspace> workspaces;
/** Logger */
private static Logger log = Logger.getLogger(Service.class);
/**
* MaxUploadSize
*/
@Deprecated
public static final String ELEMENT_GENERATOR = "generator";
/**
* Name for this element.
*/
@Deprecated
public static final String ELEMENT_NAME = "service";
/**
* The XML NAME (prefix, local name and namespace) for this element.
*/
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_APP, "service", Namespaces.NS_APP);
/**
* Create a new instance.
*/
public Service()
{
super(XML_NAME);
initialise();
}
/**
* Create a new instance.
*
* @param version The service compliance level.
*/
public Service(String version)
{
this();
setVersion(version);
}
/**
* Create a new instance with the specified compliance level, noOp and
* verbose values.
*
* @param version The service compliance level.
* @param noOp The noOp.
* @param verbose The verbose element.
*/
public Service(String version, boolean noOp, boolean verbose)
{
this();
setVersion(version);
setNoOp(noOp);
setVerbose(verbose);
}
public static XmlName elementName()
{
return XML_NAME;
}
/**
* Initialise the data structures in this tool.
*/
private void initialise()
{
workspaces = new ArrayList<Workspace>();
swordVersion = null;
swordNoOp = null;
swordVerbose = null;
swordMaxUploadSize = null;
generator = null;
}
/**
* Get the SWORD version.
*
* @return The version.
*/
public final String getVersion()
{
if( swordVersion == null )
{
return null;
}
return swordVersion.getContent();
}
/**
* Set the SWORD version.
*
* @param version The version.
*/
public final void setVersion(String version)
{
if( version == null )
{
// clear the value
swordVersion = null;
return;
}
swordVersion = new SwordVersion(version);
}
/**
* Get the NoOp value.
*
* @return The value.
*/
public final boolean isNoOp()
{
if( swordNoOp == null )
{
return false;
}
return swordNoOp.getContent();
}
/**
* Set the NoOp value.
*
* @param noOp The value.
*/
public final void setNoOp(boolean noOp)
{
swordNoOp = new SwordNoOp(noOp);
}
/**
* Determine if the NoOp value has been set. This should be called to
* check if an item has been programmatically set and does not have a
* default value.
*
* @return True if it has been set programmatically. Otherwise, false.
*/
public final boolean isNoOpSet()
{
if( swordNoOp == null )
{
return false;
}
return swordNoOp.isSet();
}
/**
* Get the Verbose setting.
*
* @return The value.
*/
public final boolean isVerbose()
{
if( swordVerbose == null )
{
return false;
}
return swordVerbose.getContent();
}
/**
* Set the Verbose value.
*
* @param verbose The value.
*/
public final void setVerbose(boolean verbose)
{
swordVerbose = new SwordVerbose(verbose);
}
/**
* Determine if the Verbose value has been set. This should be called to
* check if an item has been programmatically set and does not have a
* default value.
*
* @return True if it has been set programmatically. Otherwise, false.
*/
public final boolean isVerboseSet()
{
if( swordVerbose == null )
{
return false;
}
return swordVerbose.isSet();
}
/**
* Set the maximum file upload size in kB
*
* @param maxUploadSize Max upload file size in kB
*/
public final void setMaxUploadSize(int maxUploadSize)
{
swordMaxUploadSize = new SwordMaxUploadSize(maxUploadSize);
}
/**
* Get the maximum upload file size (in kB)
*
* @return the maximum file upload size. If no value has been set, this will
* be equal to Integer.MIN_VALUE.
*/
public final int getMaxUploadSize()
{
if( swordMaxUploadSize == null )
{
return Integer.MIN_VALUE;
}
return swordMaxUploadSize.getContent();
}
public final Generator getGenerator()
{
return generator;
}
public final void setGenerator(Generator generator)
{
this.generator = generator;
}
/**
* Get an Iterator over the workspaces.
*
* @return The workspace.
*/
public final Iterator<Workspace> getWorkspaces()
{
return workspaces.iterator();
}
/**
* Get a List of workspaces
*
* @return The workspaces in a List
*/
public final List<Workspace> getWorkspacesList()
{
return workspaces;
}
/**
* Add a workspace.
*
* @param workspace The workspace.
*/
public final void addWorkspace(Workspace workspace)
{
this.workspaces.add(workspace);
}
/**
* Clear the list of workspaces.
*/
public final void clearWorkspaces()
{
this.workspaces.clear();
}
/**
* Marshal the data in this object to an Element object.
*
* @return A XOM Element that holds the data for this Content element.
*/
public final Element marshall( )
{
Element service = new Element(getQualifiedName(), Namespaces.NS_APP);
service.addNamespaceDeclaration(Namespaces.PREFIX_ATOM, Namespaces.NS_ATOM);
service.addNamespaceDeclaration(Namespaces.PREFIX_DC_TERMS, Namespaces.NS_DC_TERMS);
service.addNamespaceDeclaration(Namespaces.PREFIX_SWORD, Namespaces.NS_SWORD);
if( swordVersion != null )
{
service.appendChild(swordVersion.marshall());
}
if( swordVerbose != null )
{
service.appendChild(swordVerbose.marshall());
}
if( swordNoOp != null )
{
service.appendChild(swordNoOp.marshall());
}
if( swordMaxUploadSize != null )
{
service.appendChild(swordMaxUploadSize.marshall());
}
if( generator != null )
{
service.appendChild(generator.marshall());
}
for (Workspace item : workspaces)
{
service.appendChild(item.marshall());
}
return service;
}
/**
* Unmarshal the content element into the data in this object.
*
* @throws UnmarshallException If the element does not contain a
* content element or if there are problems
* accessing the data.
*/
public final void unmarshall( Element service )
throws UnmarshallException
{
unmarshall(service, null);
}
/**
*
* @param service
* @param validationProperties
* @return
* @throws org.purl.sword.base.UnmarshallException
*/
public final SwordValidationInfo unmarshall( Element service, Properties validationProperties)
throws UnmarshallException
{
if (!isInstanceOf(service, xmlName))
{
return handleIncorrectElement(service, validationProperties);
}
ArrayList<SwordValidationInfo> validationItems =
new ArrayList<SwordValidationInfo>();
try
{
initialise();
// Retrieve all of the sub-elements
Elements elements = service.getChildElements();
Element element = null;
int length = elements.size();
for (int i = 0; i < length; i++ )
{
element = elements.get(i);
if (isInstanceOf(element, SwordVersion.elementName() ) )
{
//validationItems.add(unmarshallVersion(element, validate));
if( swordVersion == null )
{
swordVersion = new SwordVersion();
validationItems.add(swordVersion.unmarshall(element, validationProperties));
}
else if( validationProperties != null )
{
SwordValidationInfo info = new SwordValidationInfo(SwordVersion.elementName(),
SwordValidationInfo.DUPLICATE_ELEMENT,
SwordValidationInfoType.WARNING);
info.setContentDescription(element.getValue());
validationItems.add(info);
}
}
else if (isInstanceOf(element, SwordVerbose.elementName()))
{
if( swordVerbose == null )
{
swordVerbose = new SwordVerbose();
validationItems.add(swordVerbose.unmarshall(element, validationProperties));
}
else if( validationProperties != null )
{
SwordValidationInfo info = new SwordValidationInfo(SwordVerbose.elementName(),
SwordValidationInfo.DUPLICATE_ELEMENT,
SwordValidationInfoType.WARNING);
info.setContentDescription(element.getValue());
validationItems.add(info);
}
}
else if (isInstanceOf(element, SwordNoOp.elementName()) )
{
if( swordNoOp == null )
{
swordNoOp = new SwordNoOp();
validationItems.add(swordNoOp.unmarshall(element, validationProperties));
}
else if( validationProperties != null )
{
SwordValidationInfo info = new SwordValidationInfo(SwordNoOp.elementName(),
SwordValidationInfo.DUPLICATE_ELEMENT,
SwordValidationInfoType.WARNING);
info.setContentDescription(element.getValue());
validationItems.add(info);
}
}
else if (isInstanceOf(element, SwordMaxUploadSize.elementName()))
{
if( swordMaxUploadSize == null )
{
swordMaxUploadSize = new SwordMaxUploadSize();
validationItems.add(swordMaxUploadSize.unmarshall(element, validationProperties));
}
else if( validationProperties != null )
{
SwordValidationInfo info = new SwordValidationInfo(SwordNoOp.elementName(),
SwordValidationInfo.DUPLICATE_ELEMENT,
SwordValidationInfoType.WARNING);
info.setContentDescription(element.getValue());
validationItems.add(info);
}
}
else if (isInstanceOf(element, Generator.elementName()))
{
if( generator == null )
{
generator = new Generator();
validationItems.add(generator.unmarshall(element, validationProperties));
}
else if( validationProperties != null )
{
SwordValidationInfo info = new SwordValidationInfo(Generator.elementName(),
SwordValidationInfo.DUPLICATE_ELEMENT,
SwordValidationInfoType.WARNING);
info.setContentDescription(element.getValue());
validationItems.add(info);
}
}
else if (isInstanceOf(element, Workspace.elementName() ))
{
Workspace workspace = new Workspace( );
validationItems.add(workspace.unmarshall(element, validationProperties));
workspaces.add(workspace);
}
else if( validationProperties != null )
{
// report on any additional items. They are permitted because of
// the Atom/APP specification. Report the items for information
XmlName name = new XmlName(element.getNamespacePrefix(),
element.getLocalName(),
element.getNamespaceURI());
validationItems.add(new SwordValidationInfo(name,
SwordValidationInfo.UNKNOWN_ELEMENT,
SwordValidationInfoType.INFO));
}
}
}
catch( Exception ex )
{
log.error("Unable to parse an element in Service: " + ex.getMessage());
ex.printStackTrace();
throw new UnmarshallException("Unable to parse element in Service", ex);
}
// now process the validation information
SwordValidationInfo result = null;
if( validationProperties != null )
{
result = validate(validationItems, validationProperties);
}
return result;
}
public SwordValidationInfo validate(Properties validationContext)
{
return validate(null, validationContext);
}
/**
*
* @param existing
* @return
*/
protected SwordValidationInfo validate(List<SwordValidationInfo> existing,
Properties validationContext)
{
boolean validateAll = (existing != null);
SwordValidationInfo result = new SwordValidationInfo(xmlName);
// process the basic rules
if( swordVersion == null )
{
SwordValidationInfo info = new SwordValidationInfo(SwordVersion.elementName(),
SwordValidationInfo.MISSING_ELEMENT_WARNING,
SwordValidationInfoType.WARNING);
result.addValidationInfo(info);
}
if( generator == null )
{
SwordValidationInfo info = new SwordValidationInfo(Generator.elementName(),
SwordValidationInfo.MISSING_ELEMENT_WARNING,
SwordValidationInfoType.WARNING);
result.addValidationInfo(info);
}
if( workspaces == null || workspaces.size() == 0 )
{
SwordValidationInfo info = new SwordValidationInfo(Workspace.elementName(),
"This element SHOULD be included unless the authenticated user does not have permission to deposit.",
SwordValidationInfoType.WARNING);
result.addValidationInfo(info);
}
if( validateAll )
{
if( swordVersion != null )
{
result.addValidationInfo(swordVersion.validate(validationContext));
}
if( swordNoOp != null )
{
result.addValidationInfo(swordNoOp.validate(validationContext));
}
if( swordVerbose != null )
{
result.addValidationInfo(swordVerbose.validate(validationContext));
}
if( swordMaxUploadSize != null )
{
result.addValidationInfo(swordMaxUploadSize.validate(validationContext));
}
if( generator != null )
{
result.addValidationInfo(generator.validate(validationContext));
}
Iterator<Workspace> iterator = workspaces.iterator();
while( iterator.hasNext() )
{
result.addValidationInfo(iterator.next().validate(validationContext));
}
}
result.addUnmarshallValidationInfo(existing, null);
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.purl.sword.base;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class SwordVerboseDescription extends BasicStringContentElement
{
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_SWORD, "verboseDescription", Namespaces.NS_SWORD);
public SwordVerboseDescription()
{
super(XML_NAME);
}
public SwordVerboseDescription(String version)
{
this();
setContent(version);
}
public static XmlName elementName()
{
return XML_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.purl.sword.base;
import java.util.Properties;
import nu.xom.Element;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class BasicBooleanContentElement extends BasicContentElement
{
private boolean content;
private boolean isSet;
public BasicBooleanContentElement(String prefix, String localName, String namespaceUri)
{
super(prefix, localName, namespaceUri);
}
public BasicBooleanContentElement(XmlName name)
{
super(name);
}
public boolean getContent()
{
return content;
}
public void setContent(boolean value)
{
isSet = true;
content = value;
}
public boolean isSet()
{
return isSet;
}
protected void marshallContent(Element element)
{
element.appendChild(Boolean.toString(content));
}
protected void unmarshallContent(Element element)
throws UnmarshallException
{
setContent(unmarshallBoolean(element));
}
protected SwordValidationInfo validateContent(Properties validationContext)
{
SwordValidationInfo result = null;
if( ! isSet )
{
result = new SwordValidationInfo(xmlName,
SwordValidationInfo.MISSING_CONTENT,
SwordValidationInfoType.WARNING);
}
return result;
}
protected String getContentAsString()
{
return Boolean.toString(content);
}
}
| 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.purl.sword.base;
/**
* Represents a generic SWORD exception. If this thrown by a repository,
* it would result in a HTTP 500 message being returned to the user.
*
* @author Stuart Lewis
* @author Neil Taylor
*/
public class SWORDException extends Exception
{
private String errorCode;
/**
* Create a new instance and store the specified message and source data.
*
* @param message The message for the exception.
* @param source The original exception that lead to this exception. This
* can be <code>null</code>.
*/
public SWORDException(String message, Exception source)
{
super(message, source);
}
/**
* Create a new instance and store the specified message and source data.
*
* @param message The message for the exception.
* @param source The original exception that lead to this exception. This
* can be <code>null</code>.
* @param errorCode The error code to sed back with the request
*/
public SWORDException(String message, Exception source, String errorCode)
{
super(message, source);
this.errorCode = errorCode;
}
/**
* Create a new instance and store the specified message.
*
* @param message The message for the exception.
*/
public SWORDException(String message)
{
super(message);
}
/**
* Get the error code
*
* @return The error code
*/
public String getErrorCode() {
return errorCode;
}
} | 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.purl.sword.base;
/**
* Definition of the error codes that will be used in
* SWORD error documents.
*
* @see SWORDErrorDocument
*
* @author Stuart Lewis
*/
public interface ErrorCodes
{
/**
* ErrorContent - where the supplied format is not the same as that
* identified in the X-Format-Namespace and/or that supported by the
* server
*/
public static final String ERROR_CONTENT = "http://purl.org/net/sword/error/ErrorContent";
/**
* ErrorChecksumMismatch - where the checksum of the file received does
* not match the checksum given in the header
*/
public static final String ERROR_CHECKSUM_MISMATCH = "http://purl.org/net/sword/error/ErrorChecksumMismatch";
/**
* ErrorBadRequest - where parameters are not understood
*/
public static final String ERROR_BAD_REQUEST = "http://purl.org/net/sword/error/ErrorBadRequest";
/**
* TargetOwnerUnknown - where the server cannot identify the specified
* TargetOwner
*/
public static final String TARGET_OWNER_UKNOWN = "http://purl.org/net/sword/error/TargetOwnerUnknown";
/**
* MediationNotAllowed - where a client has attempted a mediated deposit,
* but this is not supported by the server
*/
public static final String MEDIATION_NOT_ALLOWED = "http://purl.org/net/sword/error/MediationNotAllowed";
/**
* MediationNotAllowed - where a client has attempted a mediated deposit,
* but this is not supported by the server
*/
public static final String MAX_UPLOAD_SIZE_EXCEEDED = "http://purl.org/net/sword/error/MAX_UPLOAD_SIZE_EXCEEDED";
}
| 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.purl.sword.base;
/**
*
* @author Neil Taylor
*/
public enum SwordValidationInfoType {
VALID,
INFO,
WARNING,
ERROR;
}
| 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.purl.sword.base;
import java.util.Properties;
import nu.xom.Element;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class BasicIntegerContentElement extends BasicContentElement
{
private int content = 0;
private boolean isSet;
public BasicIntegerContentElement(String prefix, String localName, String namespaceUri)
{
super(prefix, localName, namespaceUri);
}
public BasicIntegerContentElement(XmlName name)
{
super(name);
}
public int getContent()
{
return content;
}
public void setContent(int value)
{
isSet = true;
content = value;
}
public boolean isSet()
{
return isSet;
}
protected void marshallContent(Element element)
{
element.appendChild(Integer.toString(content));
}
protected void unmarshallContent(Element element)
throws UnmarshallException
{
setContent(unmarshallInteger(element));
}
protected SwordValidationInfo validateContent(Properties validationContext)
{
SwordValidationInfo result = null;
if( ! isSet )
{
result = new SwordValidationInfo(xmlName,
SwordValidationInfo.MISSING_CONTENT,
SwordValidationInfoType.WARNING);
}
return result;
}
protected String getContentAsString()
{
return Integer.toString(content);
}
}
| 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.purl.sword.base;
/**
* Represents information about an exception that is generated during
* the Unmarshall process.
*
* @author Neil Taylor
*/
public class UnmarshallException extends Exception
{
/**
* Create a new instance and store the specified message and source data.
*
* @param message The message for the exception.
* @param source The original exception that lead to this exception. This
* can be <code>null</code>.
*/
public UnmarshallException(String message, Exception source)
{
super(message, source);
}
/**
* Create a new instance and store the specified message.
*
* @param message The message for the exception.
*/
public UnmarshallException(String message)
{
super(message);
}
}
| Java |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.purl.sword.base;
import nu.xom.Element;
/**
* Common methods that should be supported by all classes that
* represent data in the SWORD api.
*
* @author Neil Taylor
*/
public interface SwordElementInterface
{
/**
* Marshall the data in the object to the XOM Element.
*
* @return The Element.
*/
public Element marshall( );
/**
* Unmarshall the data in the specified element and store it
* in the object.
*
* @param element The data to unmarshall.
* @throws UnmarshallException If the element is not of the
* correct type, or if there is an error unmarshalling the data.
*/
public void unmarshall( Element element )
throws UnmarshallException;
}
| 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.purl.sword.base;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.ParsingException;
import nu.xom.Serializer;
/**
* A representation of a SWORD Service Document.
*
* http://www.ukoln.ac.uk/repositories/digirep/index/SWORD_APP_Profile_0.5
*
* @author Stuart Lewis
* @author Neil Taylor
*/
public class ServiceDocument {
/**
* The Service object that is held by this object.
*/
private Service service;
/**
* Create a new instance and set the initial service level to Zero.
*/
public ServiceDocument() {
}
/**
* Create a new instance and set the specified service level.
*
* @param version
* The SWORD version.
*/
public ServiceDocument(String version) {
service = new Service(version);
}
/**
* Create a new instance and store the specified Service document.
*
* @param service
* The Service object.
*/
public ServiceDocument(Service service) {
this.service = service;
}
/**
* Set the service object associated with this document.
*
* @param service
* The new Service object.
*/
public void setService(Service service) {
this.service = service;
}
/**
* Retrieve the Service object associated with this document.
*
* @return The Service object.
*/
public Service getService() {
return service;
}
/**
* Return the Service Document in it's XML form.
*
* @return The ServiceDocument
*/
public String toString() {
return marshall();
}
/**
* Marshall the data in the Service element and generate a String
* representation. The returned string is UTF-8 format.
*
* @return A string of XML, or <code>null</code> if there was an error
* marshalling the data.
*/
public String marshall() {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Serializer serializer = new Serializer(stream, "UTF-8");
serializer.setIndent(3);
//serializer.setMaxLength(64);
Document doc = new Document(service.marshall());
serializer.write(doc);
return stream.toString();
} catch (IOException ex) {
System.err.println(ex);
}
return null;
}
/**
* Convert the specified XML string into a set of objects used within the
* service. A new Service object will be created and stored. This will
* dispose of any previous Service object associated with this object.
*
* @param xml
* The XML string.
* @throws UnmarshallException
* If there was a problem unmarshalling the data. This might be
* as a result of an error in parsing the XML string, extracting
* information.
*/
public void unmarshall(String xml) throws UnmarshallException
{
unmarshall(xml, null);
}
/**
*
* @param xml
* @param validationProperties
* @return
* @throws org.purl.sword.base.UnmarshallException
*/
public SwordValidationInfo unmarshall(String xml, Properties validationProperties)
throws UnmarshallException
{
try {
Builder builder = new Builder();
Document doc = builder.build(xml, Namespaces.PREFIX_APP);
Element root = doc.getRootElement();
return unmarshall(root, validationProperties);
} catch (ParsingException ex) {
throw new UnmarshallException("Unable to parse the XML", ex);
} catch (IOException ex) {
throw new UnmarshallException("Error acessing the file?", ex);
}
}
/**
* Unmarshall the specified element. This version does not generate any
* valiation information.
*
* @param element
* @throws org.purl.sword.base.UnmarshallException
*/
public void unmarshall(Element element)
throws UnmarshallException
{
unmarshall(element, null);
}
/**
* Unmarshall the specified element, and return the generated validation
* information.
*
* @param element
* @param validationProperties
* @return
* @throws org.purl.sword.base.UnmarshallException
*/
public SwordValidationInfo unmarshall(Element element, Properties validationProperties)
throws UnmarshallException
{
service = new Service();
try {
return service.unmarshall(element, validationProperties);
} catch (UnmarshallException e) {
throw new UnmarshallException("Unable to parse the XML", e);
}
}
public SwordValidationInfo validate()
{
if( service == null )
{
return null;
}
return service.validate(new Properties());
}
public SwordValidationInfo validate(Properties validationContext)
{
if( service == null)
{
return null;
}
return service.validate(validationContext);
}
} | 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.purl.sword.base;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class SwordMediation extends BasicBooleanContentElement
{
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_SWORD, "mediation", Namespaces.NS_SWORD);
public SwordMediation()
{
super(XML_NAME.getPrefix(), XML_NAME.getLocalName(), XML_NAME.getNamespace());
}
public SwordMediation(boolean value)
{
this();
setContent(value);
}
public static XmlName elementName()
{
return XML_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.purl.sword.base;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class SwordService extends BasicStringContentElement
{
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_SWORD, "service", Namespaces.NS_SWORD);
public SwordService()
{
super(XML_NAME);
}
public SwordService(String version)
{
this();
setContent(version);
}
public static XmlName elementName()
{
return XML_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.purl.sword.base;
import java.util.Properties;
import nu.xom.Attribute;
import nu.xom.Element;
/**
* Extension of the SWORD Entry class, specialized for Error Documents.
*
* @author Stuart Lewis (sdl@aber.ac.uk)
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class SWORDErrorDocument extends SWORDEntry
{
/**
* Local name for the element.
*/
@Deprecated
public static final String ELEMENT_NAME = "error";
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_SWORD, "error", Namespaces.NS_SWORD);
private static final XmlName ATTRIBUTE_HREF_NAME =
new XmlName(Namespaces.PREFIX_SWORD, "href", Namespaces.NS_SWORD);
/**
* The Error URI
*/
private String errorURI;
/**
* Create the error document (intended to be used when unmarshalling an error document
* as this will set the errorURI)
*/
public SWORDErrorDocument() {
super(XML_NAME.getPrefix(),
XML_NAME.getLocalName(),
XML_NAME.getNamespace());
}
/**
* Create the error document
*
* @param errorURI The URI of the error
*/
public SWORDErrorDocument(String errorURI) {
this();
this.errorURI = errorURI;
}
/**
* Get the element name.
*
* @return
*/
public static XmlName elementName()
{
return XML_NAME;
}
/**
* Overrides the marshal method in the parent SWORDEntry. This will
* call the parent marshal method and then add the additional
* elements that have been added in this subclass.
*/
public Element marshall()
{
Element entry = new Element(getQualifiedName(), Namespaces.NS_SWORD);
entry.addNamespaceDeclaration(Namespaces.PREFIX_SWORD, Namespaces.NS_SWORD);
entry.addNamespaceDeclaration(Namespaces.PREFIX_ATOM, Namespaces.NS_ATOM);
Attribute error = new Attribute("href", errorURI);
entry.addAttribute(error);
super.marshallElements(entry);
return entry;
}
/**
* Overrides the unmarshal method in the parent SWORDEntry. This will
* call the parent method to parse the general Atom elements and
* attributes. This method will then parse the remaining sword
* extensions that exist in the element.
*
* @param entry The entry to parse.
*
* @throws UnmarshallException If the entry is not an atom:entry
* or if there is an exception extracting the data.
*/
public void unmarshall(Element entry) throws UnmarshallException
{
unmarshall(entry, null);
}
/**
*
* @param entry
* @param validationProperties
* @return
* @throws org.purl.sword.base.UnmarshallException
*/
public SwordValidationInfo unmarshall(Element entry, Properties validationProperties)
throws UnmarshallException
{
SwordValidationInfo result = super.unmarshall(entry, validationProperties);
result.clearValidationItems();
errorURI = entry.getAttributeValue(ATTRIBUTE_HREF_NAME.getLocalName());
if( validationProperties != null )
{
result = validate(result, validationProperties);
}
return result;
}
/**
* This method overrides the XmlElement definition so that it can allow
* the definition of the href attribute. All other attributes are
* shown as 'Unknown Attribute' info elements.
*
* @param element The element that contains the attributes
* @param info The info object that will hold the validation info.
*/
@Override
protected void processUnexpectedAttributes(Element element, SwordValidationInfo info)
{
int attributeCount = element.getAttributeCount();
Attribute attribute = null;
for( int i = 0; i < attributeCount; i++ )
{
attribute = element.getAttribute(i);
if( ! ATTRIBUTE_HREF_NAME.getLocalName().equals(attribute.getQualifiedName()) )
{
XmlName attributeName = new XmlName(attribute.getNamespacePrefix(),
attribute.getLocalName(),
attribute.getNamespaceURI());
SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName,
SwordValidationInfo.UNKNOWN_ATTRIBUTE,
SwordValidationInfoType.INFO);
item.setContentDescription(attribute.getValue());
info.addUnmarshallAttributeInfo(item);
}
}
}
/**
*
* @return
*/
public SwordValidationInfo validate(Properties validationContext)
{
return validate(null, validationContext);
}
/**
*
* @param info
* @param validationContext
* @return
*/
protected SwordValidationInfo validate(SwordValidationInfo info,
Properties validationContext)
{
if( errorURI == null )
{
info.addValidationInfo(new SwordValidationInfo(xmlName, ATTRIBUTE_HREF_NAME,
SwordValidationInfo.MISSING_ATTRIBUTE_WARNING,
SwordValidationInfoType.WARNING));
}
else
{
boolean validUri = true;
if(errorURI.startsWith("http://purl.org/net/sword/error/"))
{
// check that the list of codes
if( ! (errorURI.equals(ErrorCodes.ERROR_CONTENT) ||
errorURI.equals(ErrorCodes.ERROR_CHECKSUM_MISMATCH) ||
errorURI.equals(ErrorCodes.ERROR_BAD_REQUEST) ||
errorURI.equals(ErrorCodes.TARGET_OWNER_UKNOWN) ||
errorURI.equals(ErrorCodes.MEDIATION_NOT_ALLOWED)) )
{
info.addValidationInfo(new SwordValidationInfo(xmlName,
ATTRIBUTE_HREF_NAME,
"Errors in the SWORD namespace are reserved and legal values are enumerated in the SWORD 1.3 specification. Implementations MAY define their own errors, but MUST use a different namespace to do so.",
SwordValidationInfoType.ERROR));
validUri = false;
}
}
if( validUri )
{
SwordValidationInfo item = new SwordValidationInfo(xmlName, ATTRIBUTE_HREF_NAME);
item.setContentDescription(errorURI);
info.addAttributeValidationInfo(item);
}
}
return info;
}
/**
* Get the error URI
*
* @return the error URI
*/
public String getErrorURI()
{
return errorURI;
}
/**
* set the error URI
*
* @param error the error URI
*/
public void setErrorURI(String error)
{
errorURI = error;
}
/**
* Main method to perform a brief test of the class
*
* @param args
*/
/*public static void main(String[] args)
{
SWORDErrorDocumentTest sed = new SWORDErrorDocumentTest(ErrorCodes.MEDIATION_NOT_ALLOWED);
sed.setNoOp(true);
sed.setTreatment("Short back and shine");
sed.setId("123456789");
Title t = new Title();
t.setContent("My first book");
sed.setTitle(t);
Author a = new Author();
a.setName("Lewis, Stuart");
a.setEmail("stuart@example.com");
sed.addAuthors(a);
System.out.println(sed.marshall().toXML());
}
*/
} | 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.purl.sword.base;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class SwordVerbose extends BasicBooleanContentElement
{
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_SWORD, "verbose", Namespaces.NS_SWORD);
public SwordVerbose()
{
super(XML_NAME);
}
public SwordVerbose(boolean value)
{
this();
setContent(value);
}
public static XmlName elementName()
{
return XML_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.purl.sword.base;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class SwordNoOp extends BasicBooleanContentElement
{
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_SWORD, "noOp", Namespaces.NS_SWORD);
public SwordNoOp()
{
super(XML_NAME.getPrefix(), XML_NAME.getLocalName(), XML_NAME.getNamespace());
}
public SwordNoOp(boolean value)
{
this();
setContent(value);
}
public static XmlName elementName()
{
return XML_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.purl.sword.base;
/**
* Represents a deposit response. This holds the SWORD Entry element.
*
* @author Stuart Lewis
*/
public class AtomDocumentResponse extends DepositResponse
{
/**
* Create a new response with the specified http code.
*
* @param httpResponse Response code.
*/
public AtomDocumentResponse(int httpResponse)
{
super(httpResponse);
}
}
| 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.purl.sword.base;
import java.util.Properties;
import nu.xom.Element;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class BasicStringContentElement extends BasicContentElement
{
private String content;
public BasicStringContentElement(String prefix, String localName, String namespaceUri)
{
super(prefix, localName, namespaceUri);
}
public BasicStringContentElement(XmlName name)
{
super(name);
}
public String getContent()
{
return content;
}
public void setContent(String value)
{
content = value;
}
protected void marshallContent(Element element)
{
if( content != null )
{
element.appendChild(content);
}
}
protected void unmarshallContent(Element element)
throws UnmarshallException
{
setContent(unmarshallString(element));
}
protected SwordValidationInfo validateContent(Properties validationContext)
{
SwordValidationInfo result = null;
if( content == null )
{
result = new SwordValidationInfo(xmlName,
SwordValidationInfo.MISSING_CONTENT,
SwordValidationInfoType.WARNING);
}
return result;
}
protected String getContentAsString()
{
return content;
}
}
| 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.purl.sword.base;
/**
* List of the namespaces that are used by SWORD.
*
* Last updated on: $Date: 2010-11-12 00:34:07 -0500 (Fri, 12 Nov 2010) $
*
* @author Neil Taylor
* @version $Revision: 5845 $
*
*/
public interface Namespaces {
/**
* Atom Publishing Protocol (APP) Namespace.
*/
public static final String NS_APP = "http://www.w3.org/2007/app";
/**
* APP Prefix.
*/
public static final String PREFIX_APP = "app";
/**
* ATOM Namespace.
*/
public static final String NS_ATOM = "http://www.w3.org/2005/Atom";
/**
* ATOM Prefix.
*/
public static final String PREFIX_ATOM = "atom";
/**
* Sword Namespace.
*/
public static final String NS_SWORD = "http://purl.org/net/sword/";
/**
* SWORD Prefix.
*/
public static final String PREFIX_SWORD = "sword";
/**
* DC Terms Namespace.
*/
public static final String NS_DC_TERMS = "http://purl.org/dc/terms/";
/**
* DC Terms Prefix.
*/
public static final String PREFIX_DC_TERMS = "dcterms";
}
| 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.purl.sword.base;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class SwordUserAgent extends BasicStringContentElement
{
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_SWORD, "userAgent", Namespaces.NS_SWORD);
public SwordUserAgent()
{
super(XML_NAME);
}
public SwordUserAgent(String version)
{
this();
setContent(version);
}
public static XmlName elementName()
{
return XML_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.purl.sword.base;
import java.util.List;
import java.util.Properties;
import nu.xom.Attribute;
import nu.xom.Element;
import nu.xom.Node;
import org.apache.log4j.Logger;
/**
* Parent class for all classes that represent an XML element. This provides
* some common utility methods that are useful for marshalling and
* unmarshalling data.
*
* @author Neil Taylor
*/
public abstract class XmlElement
{
/** Logger */
private static Logger log = Logger.getLogger(XmlElement.class);
/**
*
*/
protected XmlName xmlName;
public XmlName getXmlName()
{
// FIXME - should this be a clone?
return xmlName;
}
/**
* The name to use for the prefix. E.g. atom:title, atom is the prefix.
*/
//protected String prefix;
/**
* The local name of the element. E.g. atom:title, title is the local name.
*/
//protected String localName;
/**
* Create a new instance. Set the local name that will be used.
*
* @param localName The local name for the element.
*/
public XmlElement(String localName)
{
this("", localName);
}
/**
* Create a new instance. Set the prefix and local name.
*
* @param prefix The prefix for the element.
* @param localName The local name for the element.
*/
public XmlElement(String prefix, String localName)
{
this.xmlName = new XmlName(prefix, localName, "");
}
/**
* Create a new insatnce. Set the prefix, local name and the namespace URI.
*
* @param prefix The prefix.
* @param localName The element's local name.
* @param namespaceUri The namespace URI.
*/
public XmlElement(String prefix, String localName, String namespaceUri)
{
this.xmlName = new XmlName(prefix, localName, namespaceUri);
}
/**
*
* @param name
*/
public XmlElement(XmlName name)
{
xmlName = name;
}
/**
* The Date format that is used to parse dates to and from the ISO format
* in the XML data.
*/
protected static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
/**
* Array of possible date formats that are permitted for date elements.
*/
protected static final String[] DATE_FORMATS =
{
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SZ",
"yyyy-MM-dd'T'HH:mm:ss.Sz",
"yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd'T'HH:mm:ssz",
"yyyy-MM-dd'T'HH:mmZZZZ",
"yyyy-MM-dd'T'HH:mmzzzz",
"yyyy-MM-dd'T'HHZZZZ",
"yyyy-MM-dd'T'HHzzzz",
"yyyy-MM-dd'T'HH:mm:ss.S",
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd'T'HH:mm",
"yyyy-MM-dd'T'HH",
"yyyy-MM-dd",
"yyyy-MM",
"yyyy"
};
/**
* Extract a boolean value from the specified element. The boolean value
* is represented as the string 'true' or 'false' as the only child
* of the specified element.
*
* @param element The element that contains the boolean value.
* @return True or false, based on the string in the element's content.
* @throws UnmarshallException If the element does not contain a single child, or if
* the child does not contain the value 'true' or 'false'.
*/
protected boolean unmarshallBoolean( Element element )
throws UnmarshallException
{
if( element.getChildCount() != 1 )
{
throw new UnmarshallException("Missing Boolean Value", null);
}
// ok to get the single child element. This should be a text element.
try
{
Node child = element.getChild(0);
String value = child.getValue();
if( "true".equals(value) )
{
return true;
}
else if( "false".equals(value))
{
return false;
}
else
{
throw new UnmarshallException("Illegal Value");
}
}
catch( IndexOutOfBoundsException ex )
{
throw new UnmarshallException("Error accessing Boolean element", ex);
}
}
/**
* Extract a string value from the specified element. The value
* is the only child of the specified element.
*
* @param element The element that contains the string value.
* @return The string.
* @throws UnmarshallException If the element does not contain a single child.
*/
protected String unmarshallString( Element element )
throws UnmarshallException
{
if( element.getChildCount() != 1 )
{
throw new UnmarshallException("Missing String Value", null);
}
// ok to get the single child element. This should be a text element.
try
{
Node child = element.getChild(0);
return child.getValue();
}
catch( IndexOutOfBoundsException ex )
{
throw new UnmarshallException("Error accessing String element", ex);
}
}
/**
* Extract an integer value from the specified element. The integer value
* is represented as a string in the only child
* of the specified element.
*
* @param element The element that contains the integer.
* @return The integer.
* @throws UnmarshallException If the element does not contain a single child, or if
* the child does not contain the valid integer.
*/
protected int unmarshallInteger( Element element )
throws UnmarshallException
{
if( element.getChildCount() != 1 )
{
throw new UnmarshallException("Missing Integer Value", null);
}
// ok to get the single child element. This should be a text element.
try
{
Node child = element.getChild(0);
return Integer.parseInt( child.getValue() );
}
catch( IndexOutOfBoundsException ex )
{
throw new UnmarshallException("Error accessing Integer", ex);
}
catch( NumberFormatException nfex )
{
throw new UnmarshallException("Error formatting the number", nfex);
}
}
/**
* Determines if the specified element is an instance of the element name. If
* you are checking the name title in the ATOM namespace, then the local name
* should be 'title' and the namespaceURI is the URI for the ATOM namespace.
*
* @param element The specified element.
* @param localName The local name for the element.
* @param namespaceURI The namespace for the element.
* @return True if the element matches the localname and namespace. Otherwise, false.
*/
protected boolean isInstanceOf(Element element, String localName, String namespaceURI )
{
return (localName.equals(element.getLocalName()) &&
namespaceURI.equals(element.getNamespaceURI()) );
}
/**
*
* @param element
* @param xmlName
* @return
*/
protected boolean isInstanceOf(Element element, XmlName xmlName)
{
return (xmlName.getLocalName().equals(element.getLocalName()) &&
xmlName.getNamespace().equals(element.getNamespaceURI()));
}
/**
* Retrieve the qualified name for this object. This uses the
* prefix and local name stored in this object.
*
* @return A string of the format 'prefix:localName'
*/
public String getQualifiedName()
{
return getQualifiedName(xmlName.getLocalName());
}
/**
* Retrieve the qualified name. The prefix for this object is prepended
* onto the specified local name.
*
* @param name the specified local name.
* @return A string of the format 'prefix:name'
*/
public String getQualifiedName(String name)
{
return xmlName.getQualifiedName();
}
/**
* Get the qualified name for the given prefix and name
*
* @param prefix the prefix
* @param name the name
* @return the qualified name
*/
public String getQualifiedNameWithPrefix(String prefix, String name)
{
return prefix + ":" + name;
}
public abstract SwordValidationInfo validate(Properties validationContext);
protected void processUnexpectedAttributes(Element element, List<SwordValidationInfo> attributeItems)
{
int attributeCount = element.getAttributeCount();
Attribute attribute = null;
for( int i = 0; i < attributeCount; i++ )
{
attribute = element.getAttribute(i);
XmlName attributeName = new XmlName(attribute.getNamespacePrefix(),
attribute.getLocalName(),
attribute.getNamespaceURI());
SwordValidationInfo info = new SwordValidationInfo(xmlName, attributeName,
SwordValidationInfo.UNKNOWN_ATTRIBUTE,
SwordValidationInfoType.INFO);
info.setContentDescription(attribute.getValue());
attributeItems.add(info);
}
}
/**
* Add the information to the unmarshall attribute section of the specified
* info object.
*
* @param element
* @param info
*/
protected void processUnexpectedAttributes(Element element, SwordValidationInfo info)
{
int attributeCount = element.getAttributeCount();
Attribute attribute = null;
for( int i = 0; i < attributeCount; i++ )
{
attribute = element.getAttribute(i);
XmlName attributeName = new XmlName(attribute.getNamespacePrefix(),
attribute.getLocalName(),
attribute.getNamespaceURI());
SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName,
SwordValidationInfo.UNKNOWN_ATTRIBUTE,
SwordValidationInfoType.INFO);
item.setContentDescription(attribute.getValue());
info.addUnmarshallAttributeInfo(item);
}
}
protected SwordValidationInfo handleIncorrectElement(Element element, Properties validationProperties)
throws UnmarshallException
{
log.error("Unexpected element. Expected: " + getQualifiedName() + ". Got: " +
((element != null) ? element.getQualifiedName() : "null" ));
if( validationProperties != null )
{
SwordValidationInfo info = new SwordValidationInfo(
new XmlName(element.getNamespacePrefix(), element.getLocalName(), element.getNamespaceURI()),
"This is not the expected element. Received: " + element.getQualifiedName() + " for namespaceUri: " + element.getNamespaceURI(),
SwordValidationInfoType.ERROR
);
return info;
}
else
{
throw new UnmarshallException( "Not a " + getQualifiedName() + " element" );
}
}
protected SwordValidationInfo createValidAttributeInfo(String name, String content)
{
XmlName attributeName = new XmlName(xmlName.getPrefix(),
name,
xmlName.getNamespace());
SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName);
item.setContentDescription(content);
//attributeItems.add(item);
return item;
}
} | 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.purl.sword.base;
/**
* Represents an AtomDocumentRequest.
*
* @author Stuart Lewis
*/
public class AtomDocumentRequest
{
/** The username */
private String username;
/** The password */
private String password;
/** The IP Address */
private String IPAddress;
/** The location */
private String location;
/**
* Retrieve the username.
*
* @return the authenticatedUserName
*/
public String getUsername() {
return username;
}
/**
* Set the username.
*
* @param username the authenticated UserName to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Get the password.
*
* @return the authenticatedUserPassword
*/
public String getPassword() {
return password;
}
/**
* Set the password.
*
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Get the IP address of the user
*
* @return the the IP address
*/
public String getIPAddress() {
return IPAddress;
}
/**
* Set the IP address of the user
*
* @param IPAddress the IP address
*/
public void setIPAddress(String IPAddress) {
this.IPAddress = IPAddress;
}
/**
* Get the location of the service document
*
* @return the location of the service document
*/
public String getLocation() {
return location;
}
/**
* Set the location of the service document
*
* @param location the location
*/
public void setLocation(String location) {
this.location = location;
}
}
| 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.purl.sword.base;
/**
*
* @author Neil Taylor (nst@aber.ac.uk)
*/
public class SwordTreatment extends BasicStringContentElement
{
private static final XmlName XML_NAME =
new XmlName(Namespaces.PREFIX_SWORD, "treatment", Namespaces.NS_SWORD);
public SwordTreatment()
{
super(XML_NAME);
}
public SwordTreatment(String version)
{
this();
setContent(version);
}
public static XmlName elementName()
{
return XML_NAME;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.