Files
alfresco-community-repo/source/java/org/alfresco/web/app/servlet/BaseDownloadContentServlet.java
Dave Ward e0e04abccd Merged V3.3-BUG-FIX to HEAD
22215: Fix compilation error
   22240: ALF-4207: Download servlets show error page with permissions error rather than login page when non-guest user has insufficient permissions
   22241: ALF-4469: External Access Servlet should also show status 403 errors to non-guest users, as in ALF-4207
   22244: ALF-4599: CIFS access to alfresco with Kerberos authentication creates wrong users with domain suffix
      ALF-4395: recognize Kerberos machine accounts with lower case names
   22247: ALF-4397: Properly handle null values in SortableSelectItem.compareTo()
   22248: Merged DEV/TEMPORARY to V3.3-BUG-FIX
      21963: ALF-4390: ModuleManagementTool is not returning error code in case of failure
         Error code constants and appropriate System.exit(code) invokations were added.
   22260: ALF-4597: InviteContentUsersWizard was caching permissions in a non-type-specific cache
      - removed the cache - didn't allow for dynamic model updates either
   22269: Merged V3.3 to V3.3-BUG-FIX (RECORD ONLY)
      22268: Merged V3.3-BUG-FIX to V3.3
         - Merged across all differences from V3.3-BUG-FIX
   22270: Incremented revision number
   22467: Merge from V3.3 to V3.3BUG-FIX. Fix for ALF-4741.
      V3.3: 22466 Merge from V3.2 to V3.3. Fix for ALF-4741.
         V3.2: 22465 Fix for ALF-4741. Repository Web Scripts can produce a corrupted response after a transaction collision/retry.
   22667: Merged DEV/TEMPORARY to V3.3-BUG-FIX
      22665: ALF-4825: Unlocking checked out content cause both original & working copy un-usable.
         Do not include unlock in the actions list when a node has a working copy.
   22691: Add missing "logAbandoned" (= false) prop to config - follow on to r15133 (related to ALF-4020 / ETWOTWO-562)
   22710: ALF-3948 - from time to time we have exception "Failed to init dictionaryRegistry"
   22718: Merge from V3.3 to V3.3-BUG-FIX
      r 22715 Merge from V3.2 to V3.3
         r 22713 Fix for ALF-4946 Possible NullPointerException during creation of thumbnails whose names are null-valued.
   22722: Merged V3.3 to V3.3-BUG-FIX
      22271: ALF-3712: Merged HEAD to V3.3
         22249: Bin contents were not being packaged.
      22272: Merged DEV/TEMPORARY to V3.3
         22067: ALF-4479: when using webdav inline edit on webdav + MS Word 2003 +IE6, one gets: Unable to check in Content Node due to system error. Access Denied. You do not have the appropriate permissions to perform this operation.
            - Do not unlock a working copy.
      22273: Merged DEV/TEMPORARY to V3.3
         21729: ALF-3112: Property parameterTemplates not resolved correctly for SimpleTemplateActionDefinition
            The temporary fix for unconfigurable valueSeparator property.
            https://jira.springframework.org/browse/SPR-7429
      22274: Merged DEV/TEMPORARY to V3.3
         21993: ALF-4396: webdav "supportedlock" propfind request returns malformed response
            WebDAV supported lock elements were wrapped by “lockentry” elements according to the WebDAV specification.
      22276: ALF-3890: FTP Change Working Directory (CWD) command works with root-relative paths with more than one component
      22277: Merged DEV/TEMPORARY to V3.3
         22076: ALF-3579: Open the Details Page URL removes the header, navigation bar etc
            The identifiers for modify action tag and details' actions tag should be different in the details pages. For documents:
            in the filelink-details.jsp and document-details.jsp. For spaces: in the space-details.jsp and spacelink-details.jsp.
      22285: Merged HEAD to V3.3
         22284: Fix for ALF-3063 "Incorrect behaviour on filtering by tag in Repository". Labels updated to more accurately reflect behaviour.
      22299: Fix for ALF-3893: lucene.indexer.mergerTargetIndexCount is redundant
         - this property is now used to control the merging of indexes as was intended
      22309: Merged DEV/TEMPORARY to V3.3 (Approved by Roy)
         21035: ALF-2588: RM: Export and import of file plan causes disposition errors
            When content is imported from acp the actionId that points to the action NodeRef is old in the imported content and NullPointerExcepption appears.
            To avoid this we changed DispositionScheduleImpl. Now it stores the action that has different name and ID (when action is create it name equals id) in a separate map. And when getDispositionActionDefinition(String id) method is called it tries to retrieve the action from this map, if it hasn’t been found earlier.
      22325: Fix for ALF-4428: Incorrect behaviour of Consumer and Contributor permissions with Quickr
         - unit test pass
      22334: Merged HEAD to V3.3
         22331: Fixes: ALF-3558: Input and variable encoding issues in Share Calendar & API JSON data.
      22355: ALF-4489: Special Characters Create Stack Overflow Exception in the Group Admin Console for Share in Internet Explorer.
         Fixed missing encoding and also added guard code to prevent stack overflow problem in case of future error.
      22356: Fix for ALF-4384 - missing JSP page directive
      22360: Fix for ALF-4428: Incorrect behaviour of Consumer and Contributor permissions with Quickr
         - unit test pass
         - no abstain allowed
      22365: Merged DEV/TEMPORARY to V3.3
         21874: ALF-2641: WebDav Permission Issues - MAC OSX Finder
            The createExclusive field was introduced instead of m_scope. New algorithm of lockscope determination was added.
            Also ALF-4008 compliant fix provided with this.
         21812: ALF-4008: save a MS Word change over webdav after a 2-3 minutes delay causes the error 'XXX.doc is currently in use. Please try again later.'
            Modified LOCK method, it gets a scope from NodeRef property if m_scope field is not defined.
      22367: Merged DEV/TEMPORARY to V3.3
         21442: ALF-2587: WEBDAV error in Windows 7
            - variant generateLockDiscoveryXML methods were factored into a single one capable of generating a namespaced LOCK response compatible with Windows 7 when its user agent header is detected.
      22368: Merged DEV/TEMPORARY to V3.3
         20919: ALF-2834: All day events created in Outlook not appearing in Meeting Workspace
            Different date format is used by Outlook when creating all day meeting request and meeting request specifying date and time. The code was changed to handle both situations accordingly.
      22369: Merged DEV/TEMPORARY to V3.3 (With simplifications)
         21470: ALF-3796: Locale is not always set/reset on every request thread
            - A GlobalLocalizationFilter sits in front of ALL requests and sets a default fallback locale on I18NUtil
            - Moved BaseServlet.setLanguageFromRequestHeader into this filter and made sure it always falls back to a default locale
            - Subsequent filters / servlets in faces chain may override this with user preferred locale after authentication
      22370: ALF-3868: Fix for compatibility with Sun Directory Server
      22371: Merged DEV/TEMPORARY to V3.3
         21811: ALF-4067: Display Value for Action Constraint breaking a java eval in Share
            When a node doesn't have a ContentModel.PROP_TITLE property it is added to AllowableValues with PROP_NAME value.
         21795: ALF-4067: Display Value for Action Constraint breaking a java eval in Share
            The fix introduces the code which doesn't add a node to AllowableValues if it doesn't have a ContentModel.PROP_TITLE property.
      22378: ALF-3796: Fixed compilation error - BaseServlet.setLanguageFromRequestHeader replaced by global filter
      22380: ALF-3761: War bundles + extension samples now include alfresco-global.properties in correct position in hierarchy
      22386: ALF-3887: Two versions of geronimo-activation are shipped
         - Removed the older version
      22402: WCM - add more debug logging only
      22405: Change notification handler not enabled by the server configuration bean. ALF-4715.
      22407: Merged DEV/TEMPORARY to V3.3
         22231: ALF-4096: Share point module is causing file descriptor leaks.
            The following changes were added to VtiIfHeaderAction and GetDocumentMethod: 
            - code that copies data between streams was replaced by org.apache.commons.io.IOUtils.copy()
            - correct stream closing was added for all cases including exceptions while copying
      22411: Merged DEV/TEMPORARY to V3.3
         21864: ALF-4371: Error occurs if user try to find event from meeting place
            Replaced incorrect NamespaceService.CONTENT_MODEL_PREFIX with NamespaceService.CONTENT_MODEL_1_0_URI in QName creation.
      22412: Merged DEV/TEMPORARY to V3.3
         22018: ALF-4403: Search on users in JSF client and SHARE do not specify "cm:person" type clause in the query leading to incorrect results in user searching.
            People searches in Alfresco and share are restricted by “cm:person” type. 
         21988: ALF-4403: Search on users in JSF client and SHARE do not specify "cm:person" type clause in the query leading to incorrect results in user searching.
            People searches in Alfresco and share are restricted by “cm:person” type. 
      22418: ALF-4578: Avoid ConcurrentModificationException in AVMDeploymentTarget
      22420: Fixed ALF-958: Target associations aren't copied
         - Added CopyBehaviourCallback. getAssociationCopyAction
         - Default behaviour:
           - Remove existing associations of same type when copying OVER an existing node (e.g. check-in)
           - Copy the association using a new target if the target is copied in the same call
           - Copy the association to the original target if the target is not copied in the same call
         - Abstract behaviour (for those that have implemented a CopyBehaviourCallback):
           - Remove existing associations of same type when copying OVER an existing node (e.g. check-in)
           - Only copy the association to a new target if the original target is copied 
      22421: ALF-4641: Strip ticket parameter on login page redirect to avoid endless redirect loop
      22422: Merged DEV/TEMPORARY to V3.3
         21201: ALF-1804: Passthru server check gets confused when a server goes offline
      22423: Merged DEV/TEMPORARY to V3.3
         21891: ALF-3356: Error changing own user role from coordinator to consumer
            When a user changes the Roles, all Permissions are immediately deleted and new selected permissions are created. If all permissions are deleted then the user doesn't have access for permissions creation.
            If the user currently has permission change permission the currently set of permissions is cleared and new permissions are added from a System User authority.
      22424: Merged DEV/TEMPORARY to V3.3
         21182: ALF-1786: Remote Opensearch request mimetype missing
            SearchProxy was changed to provide original User-Agent header. HTTPProxy was extended to set request headers. New overridable method setRequestHeaders was added to provide ability of setting headers.
      22425: Merged DEV/TEMPORARY to V3.3
         22165: ALF-197: When returning to the first step of Advanced Workflow creation from second or third steps it's always Adhoc Task chosen there
            The selectedWorkflow variable was reseting every time on "Choose Workflow" step
      22426:Merged DEV/TEMPORARY to V3.3
         21323: ALF-687: Error when invoking webservices via SSL repository location url.
            Add a new overload of ContentUtils.putContent() method with the isSSL argument at the end. 
            If this parameter value is true then SSLSocket is used and Socket otherwise. 
      22428: ALF-3490: Unfriendly error messages from WebDAV when content doesn't exist
         - Generalized ALF-4207 solution so that the error page instead displays a status 404 message
      22429: Merged DEV/TEMPORARY to V3.3
         21325: ALF-3502: Logging in FacesHelper.getManagedBean on failure to create bean
            Detailed logging of the EvaluationException for ValueBinding was added.
      22430: Merged DEV/TEMPORARY to V3.3
         20974: ALF-2695: mimetypes-extension-context.xml.sample does not use the correct classes
            Changed the type of the bean id="mimetypeConfigService" from “"org.alfresco.config.xml.XMLConfigService” to  “org.springframework.extensions.config.xml.XMLConfigService”
            Renamed mimetypes-extension-context.xml.sample file  to file  mimetypes-extension.xml.sample.  The file mimetypes-extension-context.xml.sample was interpreted like spring context file. It wasn’t correct.
      22431: Merged DEV/TEMPORARY to V3.3
         21099: ALF-3046: UI - Import feature not available to contributor user
            The fix also covers related bug ALF-2802.
            Permission ‘Write’ was replaced by ‘CreateChildren’ for import action because contributor has ‘AddChildren’ (not ‘Write’) permission.
      22432: Merged DEV/TEMPORARY to V3.3
         20973: ALF-3244: alfresco-sample-website.war does not deploy to bundled Tomcat
            The cause of the corrupted alfresco-sample-website.war deployment is the usage of the SSIFilter in the application.
            Only Contexts which are marked as privileged may use SSI features. For this reason, the context has been marked as privileged in META-INF/context.xml
      22433: Merged DEV/TEMPORARY to V3.3
         21190: ALF-3751: Unintentional copy/remove of 'Web Forms' space removes form associations in Web Projects
            Parent validation before deleting was added. Now deleted web form is removed from Web Project only if this form is located in original Web Form folder.
      22434: Merged DEV/TEMPORARY to V3.3
         21490: ALF-4099: Customer concern about String comparison operators == vs equals
            Comparison operator was replaced by equals/EqualsHelper.nullSafeEquals in the ContentFilterLanguagesMap DocumentNavigator UIAjaxTagPicker Presence classes. 
            DocumentNavigator.getAttributeName() method was changed because the previous method's logic always returned escapedLocalName in any case.
      22436: Merged DEV/TEMPORARY to V3.3
         22063: ALF-4494 : Share show error if versionable document has no version history.
            1. evaluator.lib.js was modified to prevent NPE if no version history exists for document.
            2. Result was manually tested.
      22437: ALF-2796: java.naming.referral is set to "follow" in the LDAP contexts to avoid PartialResultExceptions on LDAP sync
      22466: Merge from V3.2 to V3.3. Fix for ALF-4741.
         V3.2: 22465 Fix for ALF-4741. Repository Web Scripts can produce a corrupted response after a transaction collision/retry.
      22469: Fix for CIFS long directory path results in duplicate folder displays. ALF-3938.
         Removed (hopefully) last of the hardcoded buffer length limits.
      22472: Fixed ALF-4670: XAM retainUntil value does not propagate down the space hierarchy
      22473: Fixed ALF-4656: Deleted Content Backup should ignore unrecognised URLs
         - Also fixes ALF-4657: Content stored on XAM is not cleaned up correctly
         - Errors in the listeners are logged only
         - ContentStoreCleanerListener checks and warns if the URL is unsupported
      22474: Fix to web.xml to correctly validate and therefore deploy on JBoss5.1.0
      22485: Fix for NFS losing contents during edit or copy. ALF-4737.
      22492: ALF-4652 XAM bug fixes and improvements: Respect 0 'retentionPeriodDays'
      22501: Fixed ALF-4763 XAM-enabled nodes must not go to the archive://SpacesStore
      22504: Fix for MS Word mimetype is changed when editing via CIFS. ALF-3772.
      22520: ALF-4768: WCM (w/ virt svr) - submit  (no need to virtualize direct submit workflows)
      22526: Externalised setting of BINARIES, plus added bin with jars and dlls
      22561: ALF-4792: WCM virt svr - add experimental option for lazy deployment (defer startup of dependent webapps until accessed)
      22611: Fixed ALF-1893: Windows 7 SSP Read-only.
         Note: Relies on the patched Excel and PowerPoint mimetypes, but also falls back to file exension.
      22612: Merged HEAD to BRANCHES/V3.3:
         22609: Resolve ALF4822, ALF4818
      22628: ALF-3239: Added encoding elements to mysql db url
      22656: Fix for Solaris/Gedit problem, keep a mapping for the original file handle to the new path after a rename. ALF-4843.
      22673: ALF-4845: Person and Group member deletion performance fix
         - Don't batch load all a group's members when trying to delete one of them!
         - Can result in infeasibly large hibernate sessions when trying to delete a person / LDAP sync in a repository with very large groups
         - Switched off batch loading in NodeService.removeChild()
         - Avoided unnecessary use of removeAuthority in PersonService.deletePerson()
      22674: Merged DEV/TEMPORARY to V3.3
         22653: ALF-661: There is no way to determine the protocol, hostname and port from a javascript kicked off by JBPM
            These variables are now available for use in workflow and action javascript and they are wired to the corresponding parameters that already exist in the sysAdmin subsystem.
               urls.alfresco.protocol
               urls.alfresco.host
               urls.alfresco.port
               urls.alfresco.context
               urls.share.protocol
               urls.share.host
               urls.share.port
               urls.share.context
            See bug for example usage
      22676: Merged HEAD to V3.3:
         20306: Google Doc integration fixes:
          - Fixed up inconsistancies in powerpoint and excel mimetypes set throughout the code
          - Unit tests failures for excel sheets fixed
          - Able to now create and checkout docs, sheets and presentations successfullly
          - Docs, sheets and presentations downloadable and viewable
          - Fixed ALF-2700
         (See ALF-4827)
      22715: Merge from V3.2 to V3.3.
         r. 22713. Fix for ALF-4946 Possible NullPointerException during creation of thumbnails whose names are null-valued.


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@22725 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2010-09-27 12:47:35 +00:00

847 lines
32 KiB
Java

/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.web.app.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.model.FileNotFoundException;
import org.alfresco.service.cmr.repository.ContentIOException;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.QName;
import org.alfresco.web.app.Application;
import org.apache.commons.logging.Log;
import org.springframework.extensions.surf.util.URLDecoder;
import org.springframework.extensions.surf.util.URLEncoder;
/**
* Base class for the download content servlets. Provides common
* processing for the request.
*
* @see org.alfresco.web.app.servlet.DownloadContentServlet
* @see org.alfresco.web.app.servlet.GuestDownloadContentServlet
*
* @author Kevin Roast
* @author gavinc
*/
public abstract class BaseDownloadContentServlet extends BaseServlet
{
private static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since";
private static final long serialVersionUID = -4558907921887235967L;
private static final String POWER_POINT_DOCUMENT_MIMETYPE = "application/vnd.ms-powerpoint";
private static final String POWER_POINT_2007_DOCUMENT_MIMETYPE = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
private static final String MULTIPART_BYTERANGES_BOUNDRY = "<ALF4558907921887235966L>";
private static final String MULTIPART_BYTERANGES_HEADER = "multipart/byteranges; boundary=" + MULTIPART_BYTERANGES_BOUNDRY;
private static final String MULTIPART_BYTERANGES_BOUNDRY_SEP = "--" + MULTIPART_BYTERANGES_BOUNDRY;
private static final String MULTIPART_BYTERANGES_BOUNDRY_END = MULTIPART_BYTERANGES_BOUNDRY_SEP + "--";
private static final String HEADER_CONTENT_TYPE = "Content-Type";
private static final String HEADER_CONTENT_RANGE = "Content-Range";
private static final String HEADER_CONTENT_LENGTH = "Content-Length";
private static final String HEADER_ACCEPT_RANGES = "Accept-Ranges";
private static final String HEADER_RANGE = "Range";
private static final String HEADER_ETAG = "ETag";
private static final String HEADER_CACHE_CONTROL = "Cache-Control";
private static final String HEADER_LAST_MODIFIED = "Last-Modified";
private static final String HEADER_USER_AGENT = "User-Agent";
private static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";
/** size of a multi-part byte range output buffer */
private static final int CHUNKSIZE = 64*1024;
protected static final String MIMETYPE_OCTET_STREAM = "application/octet-stream";
protected static final String MSG_ERROR_CONTENT_MISSING = "error_content_missing";
protected static final String MSG_ERROR_NOT_FOUND = "error_not_found";
protected static final String URL_DIRECT = "d";
protected static final String URL_DIRECT_LONG = "direct";
protected static final String URL_ATTACH = "a";
protected static final String URL_ATTACH_LONG = "attach";
protected static final String ARG_PROPERTY = "property";
protected static final String ARG_PATH = "path";
/**
* Gets the logger to use for this request.
* <p>
* This will show all debug entries from this class as though they
* came from the subclass.
*
* @return The logger
*/
protected abstract Log getLogger();
/**
* Processes the download request using the current context i.e. no authentication checks are made, it is presumed
* they have already been done.
*
* @param req
* The HTTP request
* @param res
* The HTTP response
* @param allowLogIn
* Indicates whether guest users without access to the content should be redirected to the log in page. If
* <code>false</code>, a status 403 forbidden page is displayed instead.
*/
protected void processDownloadRequest(HttpServletRequest req, HttpServletResponse res,
boolean allowLogIn, boolean transmitContent)
throws ServletException, IOException
{
Log logger = getLogger();
String uri = req.getRequestURI();
if (logger.isDebugEnabled())
{
String queryString = req.getQueryString();
logger.debug("Processing URL: " + uri +
((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
}
uri = uri.substring(req.getContextPath().length());
StringTokenizer t = new StringTokenizer(uri, "/");
int tokenCount = t.countTokens();
t.nextToken(); // skip servlet name
// attachment mode (either 'attach' or 'direct')
String attachToken = t.nextToken();
boolean attachment = URL_ATTACH.equals(attachToken) || URL_ATTACH_LONG.equals(attachToken);
ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
// get or calculate the noderef and filename to download as
NodeRef nodeRef;
String filename;
// do we have a path parameter instead of a NodeRef?
String path = req.getParameter(ARG_PATH);
if (path != null && path.length() != 0)
{
// process the name based path to resolve the NodeRef and the Filename element
try
{
PathRefInfo pathInfo = resolveNamePath(getServletContext(), path);
nodeRef = pathInfo.NodeRef;
filename = pathInfo.Filename;
}
catch (IllegalArgumentException e)
{
Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND,
HttpServletResponse.SC_NOT_FOUND, logger);
return;
}
}
else
{
// a NodeRef must have been specified if no path has been found
if (tokenCount < 6)
{
throw new IllegalArgumentException("Download URL did not contain all required args: " + uri);
}
// assume 'workspace' or other NodeRef based protocol for remaining URL elements
StoreRef storeRef = new StoreRef(URLDecoder.decode(t.nextToken()), URLDecoder.decode(t.nextToken()));
String id = URLDecoder.decode(t.nextToken());
// build noderef from the appropriate URL elements
nodeRef = new NodeRef(storeRef, id);
if (tokenCount > 6)
{
// found additional relative path elements i.e. noderefid/images/file.txt
// this allows a url to reference siblings nodes via a cm:name based relative path
// solves the issue with opening HTML content containing relative URLs in HREF or IMG tags etc.
List<String> paths = new ArrayList<String>(tokenCount - 5);
while (t.hasMoreTokens())
{
paths.add(URLDecoder.decode(t.nextToken()));
}
filename = paths.get(paths.size() - 1);
try
{
NodeRef parentRef = serviceRegistry.getNodeService().getPrimaryParent(nodeRef).getParentRef();
FileInfo fileInfo = serviceRegistry.getFileFolderService().resolveNamePath(parentRef, paths);
nodeRef = fileInfo.getNodeRef();
}
catch (FileNotFoundException e)
{
Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND,
HttpServletResponse.SC_NOT_FOUND, logger);
return;
}
}
else
{
// filename is last remaining token
filename = t.nextToken();
}
}
// get qualified of the property to get content from - default to ContentModel.PROP_CONTENT
QName propertyQName = ContentModel.PROP_CONTENT;
String property = req.getParameter(ARG_PROPERTY);
if (property != null && property.length() != 0)
{
propertyQName = QName.createQName(property);
}
if (logger.isDebugEnabled())
{
logger.debug("Found NodeRef: " + nodeRef);
logger.debug("Will use filename: " + filename);
logger.debug("For property: " + propertyQName);
logger.debug("With attachment mode: " + attachment);
}
// get the services we need to retrieve the content
NodeService nodeService = serviceRegistry.getNodeService();
ContentService contentService = serviceRegistry.getContentService();
// Check that the node still exists
if (!nodeService.exists(nodeRef))
{
Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND,
HttpServletResponse.SC_NOT_FOUND, logger);
return;
}
try
{
// check that the user has at least READ_CONTENT access - else redirect to an error or login page
if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, allowLogIn))
{
return;
}
// check If-Modified-Since header and set Last-Modified header as appropriate
Date modified = (Date)nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
if (modified != null)
{
long modifiedSince = req.getDateHeader(HEADER_IF_MODIFIED_SINCE);
if (modifiedSince > 0L)
{
// round the date to the ignore millisecond value which is not supplied by header
long modDate = (modified.getTime() / 1000L) * 1000L;
if (modDate <= modifiedSince)
{
if (logger.isDebugEnabled())
logger.debug("Returning 304 Not Modified.");
res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
}
res.setDateHeader(HEADER_LAST_MODIFIED, modified.getTime());
res.setHeader(HEADER_CACHE_CONTROL, "must-revalidate max-age=0");
res.setHeader(HEADER_ETAG, "\"" + Long.toString(modified.getTime()) + "\"");
}
if (attachment == true)
{
// set header based on filename - will force a Save As from the browse if it doesn't recognise it
// this is better than the default response of the browser trying to display the contents
res.setHeader(HEADER_CONTENT_DISPOSITION, "attachment");
}
// get the content reader
ContentReader reader = contentService.getReader(nodeRef, propertyQName);
// ensure that it is safe to use
reader = FileContentReader.getSafeContentReader(
reader,
Application.getMessage(req.getSession(), MSG_ERROR_CONTENT_MISSING),
nodeRef, reader);
String mimetype = reader.getMimetype();
// fall back if unable to resolve mimetype property
if (mimetype == null || mimetype.length() == 0)
{
MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
mimetype = MIMETYPE_OCTET_STREAM;
int extIndex = filename.lastIndexOf('.');
if (extIndex != -1)
{
String ext = filename.substring(extIndex + 1);
mimetype = mimetypeMap.getMimetype(ext);
}
}
// explicitly set the content disposition header if the content is powerpoint
if (!attachment && (mimetype.equals(POWER_POINT_2007_DOCUMENT_MIMETYPE) ||
mimetype.equals(POWER_POINT_DOCUMENT_MIMETYPE)))
{
res.setHeader(HEADER_CONTENT_DISPOSITION, "attachment");
}
// get the content and stream directly to the response output stream
// assuming the repo is capable of streaming in chunks, this should allow large files
// to be streamed directly to the browser response stream.
res.setHeader(HEADER_ACCEPT_RANGES, "bytes");
// for a GET request, transmit the content else just the headers are sent
if (transmitContent)
{
try
{
boolean processedRange = false;
String range = req.getHeader(HEADER_CONTENT_RANGE);
if (range == null)
{
range = req.getHeader(HEADER_RANGE);
}
if (range != null)
{
if (logger.isDebugEnabled())
logger.debug("Found content range header: " + range);
// ensure the range header is starts with "bytes=" and process the range(s)
if (range.length() > 6)
{
processedRange = processRange(
res, reader, range.substring(6), nodeRef, propertyQName,
mimetype, req.getHeader(HEADER_USER_AGENT));
}
}
if (processedRange == false)
{
if (logger.isDebugEnabled())
logger.debug("Sending complete file content...");
// set mimetype for the content and the character encoding for the stream
res.setContentType(mimetype);
res.setCharacterEncoding(reader.getEncoding());
// return the complete entity range
long size = reader.getSize();
res.setHeader(HEADER_CONTENT_RANGE, "bytes 0-" + Long.toString(size-1L) + "/" + Long.toString(size));
res.setHeader(HEADER_CONTENT_LENGTH, Long.toString(size));
reader.getContent( res.getOutputStream() );
}
}
catch (SocketException e1)
{
// the client cut the connection - our mission was accomplished apart from a little error message
if (logger.isDebugEnabled())
logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader);
}
catch (ContentIOException e2)
{
if (logger.isInfoEnabled())
logger.info("Failed stream read:\n\tnode: " + nodeRef + " due to: " + e2.getMessage());
}
catch (Throwable err)
{
if (err.getCause() instanceof SocketException)
{
// the client cut the connection - our mission was accomplished apart from a little error message
if (logger.isDebugEnabled())
logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader);
}
else throw err;
}
}
else
{
if (logger.isDebugEnabled())
logger.debug("HEAD request processed - no content sent.");
res.getOutputStream().close();
}
}
catch (Throwable err)
{
throw new AlfrescoRuntimeException("Error during download content servlet processing: " + err.getMessage(), err);
}
}
/**
* Process a range header - handles single and multiple range requests.
*/
private boolean processRange(HttpServletResponse res, ContentReader reader, String range,
NodeRef ref, QName property, String mimetype, String userAgent)
throws IOException
{
// test for multiple byte ranges present in header
if (range.indexOf(',') == -1)
{
return processSingleRange(res, reader, range, mimetype);
}
else
{
return processMultiRange(res, range, ref, property, mimetype, userAgent);
}
}
/**
* Process a single range request.
*
* @param res HttpServletResponse
* @param reader ContentReader to retrieve content
* @param range Range header value
* @param mimetype Content mimetype
*
* @return true if processed range, false otherwise
*/
private boolean processSingleRange(HttpServletResponse res, ContentReader reader, String range, String mimetype)
throws IOException
{
// return the specific set of bytes as requested in the content-range header
/* Examples of byte-content-range-spec values, assuming that the entity contains total of 1234 bytes:
The first 500 bytes:
bytes 0-499/1234
The second 500 bytes:
bytes 500-999/1234
All except for the first 500 bytes:
bytes 500-1233/1234 */
/* 'Range' header example:
bytes=10485760-20971519 */
boolean processedRange = false;
Range r = null;
try
{
r = Range.constructRange(range, mimetype, reader.getSize());
}
catch (IllegalArgumentException err)
{
if (getLogger().isDebugEnabled())
getLogger().debug("Failed to parse range header - returning 416 status code: " + err.getMessage());
res.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
res.setHeader(HEADER_CONTENT_RANGE, "\"*\"");
res.getOutputStream().close();
return true;
}
// set Partial Content status and range headers
res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
res.setContentType(mimetype);
String contentRange = "bytes " + Long.toString(r.start) + "-" + Long.toString(r.end) + "/" + Long.toString(reader.getSize());
res.setHeader(HEADER_CONTENT_RANGE, contentRange);
res.setHeader(HEADER_CONTENT_LENGTH, Long.toString((r.end - r.start) + 1L));
if (getLogger().isDebugEnabled())
getLogger().debug("Processing: Content-Range: " + contentRange);
InputStream is = null;
try
{
// output the binary data for the range
ServletOutputStream os = res.getOutputStream();
is = reader.getContentInputStream();
streamRangeBytes(r, is, os, 0L);
os.close();
processedRange = true;
}
catch (IOException err)
{
if (getLogger().isDebugEnabled())
getLogger().debug("Unable to process single range due to IO Exception: " + err.getMessage());
throw err;
}
finally
{
if (is != null) is.close();
}
return processedRange;
}
/**
* Process multiple ranges.
*
* @param res HttpServletResponse
* @param range Range header value
* @param ref NodeRef to the content for streaming
* @param property Content Property for the content
* @param mimetype Mimetype of the content
* @param userAgent User Agent of the caller
*
* @return true if processed range, false otherwise
*/
private boolean processMultiRange(
HttpServletResponse res, String range, NodeRef ref, QName property, String mimetype, String userAgent)
throws IOException
{
final Log logger = getLogger();
// return the sets of bytes as requested in the content-range header
// the response will be formatted as multipart/byteranges media type message
/* Examples of byte-ranges-specifier values (assuming an entity-body of length 10000):
- The first 500 bytes (byte offsets 0-499, inclusive): bytes=0-499
- The second 500 bytes (byte offsets 500-999, inclusive):
bytes=500-999
- The final 500 bytes (byte offsets 9500-9999, inclusive):
bytes=-500
- Or bytes=9500-
- The first and last bytes only (bytes 0 and 9999): bytes=0-0,-1
- Several legal but not canonical specifications of byte offsets 500-999, inclusive:
bytes=500-600,601-999
bytes=500-700,601-999 */
boolean processedRange = false;
// get the content reader
ContentService contentService = getServiceRegistry(getServletContext()).getContentService();
ContentReader reader = contentService.getReader(ref, property);
final List<Range> ranges = new ArrayList<Range>(8);
long entityLength = reader.getSize();
for (StringTokenizer t=new StringTokenizer(range, ", "); t.hasMoreTokens(); /**/)
{
try
{
ranges.add(Range.constructRange(t.nextToken(), mimetype, entityLength));
}
catch (IllegalArgumentException err)
{
if (getLogger().isDebugEnabled())
getLogger().debug("Failed to parse range header - returning 416 status code: " + err.getMessage());
res.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
res.setHeader(HEADER_CONTENT_RANGE, "\"*\"");
res.getOutputStream().close();
return true;
}
}
if (ranges.size() != 0)
{
// merge byte ranges if possible - IE handles this well, FireFox not so much
if (userAgent == null || userAgent.indexOf("MSIE ") != -1)
{
Collections.sort(ranges);
for (int i=0; i<ranges.size() - 1; i++)
{
Range first = ranges.get(i);
Range second = ranges.get(i + 1);
if (first.end + 1 >= second.start)
{
if (logger.isDebugEnabled())
logger.debug("Merging byte range: " + first + " with " + second);
if (first.end < second.end)
{
// merge second range into first
first.end = second.end;
}
// else we simply discard the second range - it is contained within the first
// delete second range
ranges.remove(i + 1);
// reset loop index
i--;
}
}
}
// calculate response content length
long length = MULTIPART_BYTERANGES_BOUNDRY_END.length() + 2;
for (Range r : ranges)
{
length += r.getLength();
}
// output headers as we have at least one range to process
res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
res.setHeader(HEADER_CONTENT_TYPE, MULTIPART_BYTERANGES_HEADER);
res.setHeader(HEADER_CONTENT_LENGTH, Long.toString(length));
ServletOutputStream os = res.getOutputStream();
InputStream is = null;
try
{
for (Range r : ranges)
{
if (logger.isDebugEnabled())
logger.debug("Processing: " + r.getContentRange());
try
{
// output the header bytes for the range
r.outputHeader(os);
// output the binary data for the range
// need a new reader for each new InputStream
is = contentService.getReader(ref, property).getContentInputStream();
streamRangeBytes(r, is, os, 0L);
is.close();
is = null;
// section marker and flush stream
os.println();
os.flush();
}
catch (IOException err)
{
if (getLogger().isDebugEnabled())
getLogger().debug("Unable to process multiple range due to IO Exception: " + err.getMessage());
throw err;
}
}
}
finally
{
if (is != null)
{
is.close();
}
}
// end marker
os.println(MULTIPART_BYTERANGES_BOUNDRY_END);
os.close();
processedRange = true;
}
return processedRange;
}
/**
* Stream a range of bytes from the given InputStream to the ServletOutputStream
*
* @param r Byte Range to process
* @param is InputStream
* @param os ServletOutputStream
* @param offset Assumed InputStream position - to calculate skip bytes from
*
* @return current InputStream position - so the stream can be reused if required
*/
private void streamRangeBytes(final Range r, final InputStream is, final ServletOutputStream os, long offset)
throws IOException
{
final Log logger = getLogger();
final boolean trace = logger.isTraceEnabled();
// TODO: investigate using getFileChannel() on ContentReader
if (r.start != 0L)
{
long skipped = offset;
while (skipped < r.start)
{
skipped += is.skip(r.start - skipped);
}
}
long span = (r.end - r.start) + 1L;
long bytesLeft = span;
int read = 0;
byte[] buf = new byte[((int)bytesLeft) < CHUNKSIZE ? (int)bytesLeft : CHUNKSIZE];
while ((read = is.read(buf)) > 0 && bytesLeft != 0L)
{
os.write(buf, 0, read);
bytesLeft -= (long)read;
if (bytesLeft != 0L)
{
int resize = ((int)bytesLeft) < CHUNKSIZE ? (int)bytesLeft : CHUNKSIZE;
if (resize != buf.length)
{
buf = new byte[resize];
}
}
if (trace) logger.trace("...wrote " + read + " bytes, with " + bytesLeft + " to go...");
}
}
/**
* Representation of a single byte range.
*/
private static class Range implements Comparable<Range>
{
private long start;
private long end;
private long entityLength;
private String contentType;
private String contentRange;
/**
* Constructor
*
* @param contentType Mimetype of the range content
* @param start Start position in the parent entity
* @param end End position in the parent entity
* @param entityLength Length of the parent entity
*/
Range(String contentType, long start, long end, long entityLength)
{
this.contentType = HEADER_CONTENT_TYPE + ": " + contentType;
this.start = start;
this.end = end;
this.entityLength = entityLength;
}
/**
* Factory method to construct a byte range from a range header value.
*
* @param range Range header value
* @param contentType Mimetype of the range
* @param entityLength Length of the parent entity
*
* @return Range
*
* @throws IllegalArgumentException for an invalid range
*/
static Range constructRange(String range, String contentType, long entityLength)
{
if (range == null)
{
throw new IllegalArgumentException("Range argument is mandatory");
}
// strip total if present - it does not give us anything useful
if (range.indexOf('/') != -1)
{
range = range.substring(0, range.indexOf('/'));
}
// find the separator
int separator = range.indexOf('-');
if (separator == -1)
{
throw new IllegalArgumentException("Invalid range: " + range);
}
try
{
// split range and parse values
long start = 0L;
if (separator != 0)
{
start = Long.parseLong(range.substring(0, separator));
}
long end = entityLength - 1L;
if (separator != range.length() - 1)
{
end = Long.parseLong(range.substring(separator + 1));
}
// return object to represent the byte-range
return new Range(contentType, start, end, entityLength);
}
catch (NumberFormatException err)
{
throw new IllegalArgumentException("Unable to parse range value: " + range);
}
}
/**
* Output the header bytes for a multi-part byte range header
*/
void outputHeader(ServletOutputStream os) throws IOException
{
// output multi-part boundry separator
os.println(MULTIPART_BYTERANGES_BOUNDRY_SEP);
// output content type and range size sub-header for this part
os.println(this.contentType);
os.println(getContentRange());
os.println();
}
/**
* @return the length in bytes of the byte range content including the header bytes
*/
int getLength()
{
// length in bytes of range plus it's header plus section marker and line feed bytes
return MULTIPART_BYTERANGES_BOUNDRY_SEP.length() + 2 +
this.contentType.length() + 2 +
getContentRange().length() + 4 + (int)(this.end - this.start + 1L) + 2;
}
/**
* @return the Content-Range header string value for this byte range
*/
private String getContentRange()
{
if (this.contentRange == null)
{
this.contentRange = "Content-Range: bytes " + Long.toString(this.start) + "-" +
Long.toString(this.end) + "/" + Long.toString(this.entityLength);
}
return this.contentRange;
}
@Override
public String toString()
{
return this.start + "-" + this.end;
}
/**
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Range o)
{
return this.start > o.start ? 1 : -1;
}
}
/**
* Helper to generate a URL to a content node for downloading content from the server.
*
* @param pattern The pattern to use for the URL
* @param ref NodeRef of the content node to generate URL for (cannot be null)
* @param name File name to return in the URL (cannot be null)
*
* @return URL to download the content from the specified node
*/
protected final static String generateUrl(String pattern, NodeRef ref, String name)
{
return MessageFormat.format(pattern, new Object[] {
ref.getStoreRef().getProtocol(),
ref.getStoreRef().getIdentifier(),
ref.getId(),
URLEncoder.encode(name) } );
}
}