List of usage examples for org.apache.commons.logging Log isDebugEnabled
boolean isDebugEnabled();
From source file:org.alfresco.extension.bulkimport.util.LogUtils.java
public final static boolean debug(final Log log) { return (log.isDebugEnabled()); }
From source file:org.alfresco.repo.admin.Log4JHierarchyInitTest.java
public void testAddingLog4jProperties() throws Throwable { Log log = LogFactory.getLog(this.getClass()); // We expect DEBUG to be on assertTrue("DEBUG was not enabled for logger " + this.getClass(), log.isDebugEnabled()); }
From source file:org.alfresco.repo.forms.processor.FilteredFormProcessor.java
/** * Generates the form.//from w w w.ja v a 2s.co m * * @param item The object to generate a form for * @param fields Restricted list of fields to include * @param forcedFields List of fields to forcibly include * @param form The form object being generated * @param context Map representing optional context that can be used during * retrieval of the form */ protected void internalGenerate(ItemType item, List<String> fields, List<String> forcedFields, Form form, Map<String, Object> context) { Log log = getLogger(); if (log.isDebugEnabled()) log.debug("Generating form for: " + item); // generate the form type and URI for the item. Item formItem = form.getItem(); formItem.setType(getItemType(item)); formItem.setUrl(getItemURI(item)); Object itemData = makeItemData(item); FormCreationData data = new FormCreationDataImpl(itemData, forcedFields, context); populateForm(form, fields, data); if (log.isDebugEnabled()) // log.debug("Generated form: " + form); }
From source file:org.alfresco.repo.web.util.HttpRangeProcessor.java
/** * Process multiple ranges.//from w w w. j a v a 2s.c o m * * @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(Object res, String range, NodeRef ref, QName property, String mimetype, String userAgent) throws IOException { final Log logger = getLogger(); // Handle either HttpServletResponse or WebScriptResponse HttpServletResponse httpServletResponse = null; WebScriptResponse webScriptResponse = null; if (res instanceof HttpServletResponse) { httpServletResponse = (HttpServletResponse) res; } else if (res instanceof WebScriptResponse) { webScriptResponse = (WebScriptResponse) res; } if (httpServletResponse == null && webScriptResponse == null) { // Unknown response object type return false; } // 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 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()); if (httpServletResponse != null) { httpServletResponse.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); httpServletResponse.setHeader(HEADER_CONTENT_RANGE, "\"*\""); httpServletResponse.getOutputStream().close(); } else if (webScriptResponse != null) { webScriptResponse.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); webScriptResponse.setHeader(HEADER_CONTENT_RANGE, "\"*\""); webScriptResponse.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 OutputStream os = null; if (httpServletResponse != null) { httpServletResponse.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); httpServletResponse.setHeader(HEADER_CONTENT_TYPE, MULTIPART_BYTERANGES_HEADER); httpServletResponse.setHeader(HEADER_CONTENT_LENGTH, Long.toString(length)); os = httpServletResponse.getOutputStream(); } else if (webScriptResponse != null) { webScriptResponse.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); webScriptResponse.setHeader(HEADER_CONTENT_TYPE, MULTIPART_BYTERANGES_HEADER); webScriptResponse.setHeader(HEADER_CONTENT_LENGTH, Long.toString(length)); os = webScriptResponse.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 if (os instanceof ServletOutputStream) r.outputHeader((ServletOutputStream) 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 if (os instanceof ServletOutputStream) ((ServletOutputStream) 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 if (os instanceof ServletOutputStream) ((ServletOutputStream) os).println(MULTIPART_BYTERANGES_BOUNDRY_END); os.close(); processedRange = true; } return processedRange; }
From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java
/** * Process a type 3 NTLM message/*from w w w . j a v a 2 s.c o m*/ * * @param type3Msg Type3NTLMMessage * @param req HttpServletRequest * @param res HttpServletResponse * * @exception IOException * @exception ServletException */ protected boolean processType3(Type3NTLMMessage type3Msg, ServletContext context, HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { Log logger = getLogger(); if (logger.isDebugEnabled()) logger.debug("Received type3 " + type3Msg); // Get the existing NTLM details NTLMLogonDetails ntlmDetails = null; SessionUser user = null; user = getSessionUser(context, req, res, true); HttpSession session = req.getSession(); ntlmDetails = (NTLMLogonDetails) session.getAttribute(NTLM_AUTH_DETAILS); // Get the NTLM logon details String userName = type3Msg.getUserName(); String workstation = type3Msg.getWorkstation(); String domain = type3Msg.getDomain(); // ALF-10997 fix, normalize the userName //the system runAs is acceptable because we are resolving a username i.e. it's a system-wide operation that does not need permission checks final String userName_f = userName; String normalized = transactionService.getRetryingTransactionHelper() .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<String>() { public String execute() throws Throwable { return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<String>() { public String doWork() throws Exception { String normalized = personService.getUserIdentifier(userName_f); return normalized; } }, AuthenticationUtil.SYSTEM_USER_NAME); } }, true); if (normalized != null) { userName = normalized; } boolean authenticated = false; // Check if we are using cached details for the authentication if (user != null && ntlmDetails != null && ntlmDetails.hasNTLMHashedPassword()) { // Check if the received NTLM hashed password matches the cached password byte[] ntlmPwd = type3Msg.getNTLMHash(); byte[] cachedPwd = ntlmDetails.getNTLMHashedPassword(); if (ntlmPwd != null) { authenticated = Arrays.equals(cachedPwd, ntlmPwd); } if (logger.isDebugEnabled()) logger.debug("Using cached NTLM hash, authenticated = " + authenticated); onValidate(context, req, res, new NTLMCredentials(userName, ntlmPwd)); // Allow the user to access the requested page return true; } else { WebCredentials credentials; // Check if we are using local MD4 password hashes or passthru authentication if (nltmAuthenticator.getNTLMMode() == NTLMMode.MD4_PROVIDER) { // Check if guest logons are allowed and this is a guest logon if (m_allowGuest && userName.equalsIgnoreCase(authenticationComponent.getGuestUserName())) { credentials = new GuestCredentials(); // Indicate that the user has been authenticated authenticated = true; if (getLogger().isDebugEnabled()) getLogger().debug("Guest logon"); } else { // Get the stored MD4 hashed password for the user, or null if the user does not exist String md4hash = getMD4Hash(userName); if (md4hash != null) { authenticated = validateLocalHashedPassword(type3Msg, ntlmDetails, authenticated, md4hash); credentials = new NTLMCredentials(ntlmDetails.getUserName(), ntlmDetails.getNTLMHashedPassword()); } else { // Check if unknown users should be logged on as guest if (m_mapUnknownUserToGuest) { // Reset the user name to be the guest user userName = authenticationComponent.getGuestUserName(); authenticated = true; credentials = new GuestCredentials(); if (logger.isDebugEnabled()) logger.debug("User " + userName + " logged on as guest, no Alfresco account"); } else { if (logger.isDebugEnabled()) logger.debug("User " + userName + " does not have Alfresco account"); // Bypass NTLM authentication and display the logon screen, // as user account does not exist in Alfresco credentials = new UnknownCredentials(); authenticated = false; } } } } else { credentials = new NTLMCredentials(type3Msg.getUserName(), type3Msg.getNTLMHash()); // Determine if the client sent us NTLMv1 or NTLMv2 if (type3Msg.hasFlag(NTLM.Flag128Bit) && type3Msg.hasFlag(NTLM.FlagNTLM2Key) || (type3Msg.getNTLMHash() != null && type3Msg.getNTLMHash().length > 24)) { // Cannot accept NTLMv2 if we are using passthru auth if (logger.isErrorEnabled()) logger.error("Client " + workstation + " using NTLMv2 logon, not valid with passthru authentication"); } else { if (ntlmDetails == null) { if (logger.isWarnEnabled()) logger.warn( "Authentication failed: NTLM details can not be retrieved from session. Client must support cookies."); restartLoginChallenge(context, req, res); return false; } // Passthru mode, send the hashed password details to the passthru authentication server NTLMPassthruToken authToken = (NTLMPassthruToken) ntlmDetails.getAuthenticationToken(); authToken.setUserAndPassword(type3Msg.getUserName(), type3Msg.getNTLMHash(), PasswordEncryptor.NTLM1); try { // Run the second stage of the passthru authentication nltmAuthenticator.authenticate(authToken); authenticated = true; // Check if the user has been logged on as guest if (authToken.isGuestLogon()) { userName = authenticationComponent.getGuestUserName(); } // Set the authentication context authenticationComponent.setCurrentUser(userName); } catch (BadCredentialsException ex) { if (logger.isDebugEnabled()) logger.debug("Authentication failed, " + ex.getMessage()); } catch (AuthenticationException ex) { if (logger.isDebugEnabled()) logger.debug("Authentication failed, " + ex.getMessage()); } finally { // Clear the authentication token from the NTLM details ntlmDetails.setAuthenticationToken(null); } } } // Check if the user has been authenticated, if so then setup the user environment if (authenticated == true) { boolean userInit = false; if (user == null) { try { user = createUserEnvironment(session, userName); userInit = true; } catch (AuthenticationException ex) { if (logger.isDebugEnabled()) logger.debug("Failed to validate user " + userName, ex); onValidateFailed(context, req, res, session, credentials); return false; } } onValidate(context, req, res, credentials); // Update the NTLM logon details in the session String srvName = getServerName(); if (ntlmDetails == null) { // No cached NTLM details ntlmDetails = new NTLMLogonDetails(userName, workstation, domain, false, srvName); ntlmDetails.setNTLMHashedPassword(type3Msg.getNTLMHash()); session.setAttribute(NTLM_AUTH_DETAILS, ntlmDetails); if (logger.isDebugEnabled()) logger.debug("No cached NTLM details, created"); } else { // Update the cached NTLM details ntlmDetails.setDetails(userName, workstation, domain, false, srvName); ntlmDetails.setNTLMHashedPassword(type3Msg.getNTLMHash()); if (logger.isDebugEnabled()) logger.debug("Updated cached NTLM details"); } if (logger.isDebugEnabled()) logger.debug("User logged on via NTLM, " + ntlmDetails); if (onLoginComplete(context, req, res, userInit)) { // Allow the user to access the requested page return true; } } else { restartLoginChallenge(context, req, res); } } return false; }
From source file:org.alfresco.scripts.ScriptResourceHelper.java
/** * Recursively resolve imports in the specified scripts, adding the imports to the * specific list of scriplets to combine later. * /*from w w w. ja v a 2s . c om*/ * @param location Script location - used to ensure duplicates are not added * @param script The script to recursively resolve imports for * @param scripts The collection of scriplets to execute with imports resolved and removed */ private static void recurseScriptImports(String location, String script, ScriptResourceLoader loader, Map<String, String> scripts, Log logger) { int index = 0; // skip any initial whitespace for (; index < script.length(); index++) { if (Character.isWhitespace(script.charAt(index)) == false) { break; } } // look for the "<import" directive marker if (script.startsWith(IMPORT_PREFIX, index)) { // skip whitespace between "<import" and "resource" boolean afterWhitespace = false; index += IMPORT_PREFIX.length() + 1; for (; index < script.length(); index++) { if (Character.isWhitespace(script.charAt(index)) == false) { afterWhitespace = true; break; } } if (afterWhitespace == true && script.startsWith(IMPORT_RESOURCE, index)) { // found an import line! index += IMPORT_RESOURCE.length(); int resourceStart = index; for (; index < script.length(); index++) { if (script.charAt(index) == '"' && script.charAt(index + 1) == '>') { // found end of import line - so we have a resource path String resource = script.substring(resourceStart, index); if (logger.isDebugEnabled()) logger.debug("Found script resource import: " + resource); if (scripts.containsKey(resource) == false) { // load the script resource (and parse any recursive includes...) String includedScript = loader.loadScriptResource(resource); if (includedScript != null) { if (logger.isDebugEnabled()) logger.debug("Succesfully located script '" + resource + "'"); recurseScriptImports(resource, includedScript, loader, scripts, logger); } } else { if (logger.isDebugEnabled()) logger.debug("Note: already imported resource: " + resource); } // continue scanning this script for additional includes // skip the last two characters of the import directive for (index += 2; index < script.length(); index++) { if (Character.isWhitespace(script.charAt(index)) == false) { break; } } recurseScriptImports(location, script.substring(index), loader, scripts, logger); return; } } // if we get here, we failed to find the end of an import line throw new ScriptException( "Malformed 'import' line - must be first in file, no comments and strictly of the form:" + "\r\n<import resource=\"...\">"); } else { throw new ScriptException( "Malformed 'import' line - must be first in file, no comments and strictly of the form:" + "\r\n<import resource=\"...\">"); } } else { // no (further) includes found - include the original script content if (logger.isDebugEnabled()) logger.debug("Imports resolved, adding resource '" + location); if (logger.isTraceEnabled()) logger.trace(script); scripts.put(location, script); } }
From source file:org.alfresco.web.app.Application.java
/** * Handles errors thrown from servlets/*from w ww.j a v a 2 s . c om*/ * * @param servletContext The servlet context * @param request The HTTP request * @param response The HTTP response * @param error The exception * @param logger The logger */ public static void handleServletError(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, Throwable error, Log logger, String returnPage) throws IOException, ServletException { // get the error bean from the session and set the error that occurred. HttpSession session = request.getSession(); ErrorBean errorBean = (ErrorBean) session.getAttribute(ErrorBean.ERROR_BEAN_NAME); if (errorBean == null) { errorBean = new ErrorBean(); session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean); } errorBean.setLastError(error); errorBean.setReturnPage(returnPage); // try and find the configured error page boolean errorShown = false; String errorPage = getErrorPage(servletContext); if (errorPage != null) { if (logger.isDebugEnabled()) logger.debug("An error has occurred, redirecting to error page: " + errorPage); if (response.isCommitted() == false) { errorShown = true; response.sendRedirect(request.getContextPath() + errorPage); } else { if (logger.isDebugEnabled()) logger.debug("Response is already committed, re-throwing error"); } } else { if (logger.isDebugEnabled()) logger.debug("No error page defined, re-throwing error"); } // if we could not show the error page for whatever reason, re-throw the error if (!errorShown) { if (error instanceof IOException) { throw (IOException) error; } else if (error instanceof ServletException) { throw (ServletException) error; } else { throw new ServletException(error); } } }
From source file:org.alfresco.web.app.Application.java
/** * Handles error conditions detected by servlets. * // w ww.j a va 2 s. c o m * @param servletContext * The servlet context * @param request * The HTTP request * @param response * The HTTP response * @param messageKey * the resource bundle key for the error mesage * @param statusCode * the status code to set on the response * @param logger * The logger * @throws IOException * Signals that an I/O exception has occurred. * @throws ServletException * the servlet exception */ public static void handleSystemError(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, String messageKey, int statusCode, Log logger) throws IOException, ServletException { // get the error bean from the session and set the error that occurred. HttpSession session = request.getSession(); ErrorBean errorBean = (ErrorBean) session.getAttribute(ErrorBean.ERROR_BEAN_NAME); if (errorBean == null) { errorBean = new ErrorBean(); session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean); } errorBean.setErrorMessageKey(messageKey); errorBean.setReturnPage(null); // try and find the configured error page boolean errorShown = false; String errorPage = getErrorPage(servletContext); if (errorPage != null) { if (logger.isDebugEnabled()) logger.debug("An error has occurred, forwarding to error page: " + errorPage); if (!response.isCommitted()) { errorShown = true; response.reset(); response.setStatus(statusCode); response.setContentType(MimetypeMap.MIMETYPE_HTML); response.setCharacterEncoding("utf-8"); servletContext.getRequestDispatcher(errorPage).include(request, response); } else { if (logger.isDebugEnabled()) logger.debug("Response is already committed, re-throwing error"); } } else { if (logger.isDebugEnabled()) logger.debug("No error page defined, re-throwing error"); } // if we could not show the error page for whatever reason, re-throw the error if (!errorShown) { throw new ServletException(getMessage(session, messageKey)); } }
From source file:org.alfresco.web.app.servlet.BaseDownloadContentServlet.java
/** * Processes the download request using the current context i.e. no authentication checks are made, it is presumed * they have already been done.//from w w w . java2 s . c om * * @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) { setHeaderContentDisposition(req, res, filename); } // 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))) { setHeaderContentDisposition(req, res, filename); } // 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) { HttpRangeProcessor rangeProcessor = new HttpRangeProcessor(contentService); processedRange = rangeProcessor.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()); // MNT-10642 Alfresco Explorer has javascript vulnerability opening HTML files if (req.getRequestURI().contains("/d/d/") && (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml") || mimetype.equals("text/xml"))) { String content = reader.getContentString(); if (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml")) { // process with HTML stripper content = StringUtils.stripUnsafeHTMLTags(content, false); } else if (mimetype.equals("text/xml") && mimetype.equals("text/x-component")) { // IE supports "behaviour" which means that css can load a .htc file that could // contain XSS code in the form of jscript, vbscript etc, to stop it form being // evaluated we set the contient type to text/plain res.setContentType("text/plain"); } String encoding = reader.getEncoding(); byte[] bytes = encoding != null ? content.getBytes(encoding) : content.getBytes(); res.setContentLength(bytes.length); res.getOutputStream().write(bytes); return; } // 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); } }
From source file:org.alfresco.web.app.servlet.BaseTemplateContentServlet.java
/** * Processes the template request using the current context i.e. no * authentication checks are made, it is presumed they have already * been done./*from w w w. ja v a 2s . com*/ * * @param req The HTTP request * @param res The HTTP response * @param redirectToLogin Flag to determine whether to redirect to the login * page if the user does not have the correct permissions */ protected void processTemplateRequest(HttpServletRequest req, HttpServletResponse res, boolean redirectToLogin) 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 NodeRef nodeRef = null; NodeRef templateRef = null; try { String contentPath = req.getParameter(ARG_CONTEXT_PATH); if (contentPath != null && contentPath.length() != 0) { // process the name based path to resolve the NodeRef PathRefInfo pathInfo = resolveNamePath(getServletContext(), contentPath); nodeRef = pathInfo.NodeRef; } else if (tokenCount > 3) { // get NodeRef to the content from the URL elements StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken()); nodeRef = new NodeRef(storeRef, t.nextToken()); } // get NodeRef to the template if supplied String templatePath = req.getParameter(ARG_TEMPLATE_PATH); if (templatePath != null && templatePath.length() != 0) { // process the name based path to resolve the NodeRef PathRefInfo pathInfo = resolveNamePath(getServletContext(), templatePath); templateRef = pathInfo.NodeRef; } else if (tokenCount >= 7) { StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken()); templateRef = new NodeRef(storeRef, t.nextToken()); } } catch (AccessDeniedException err) { if (redirectToLogin) { if (logger.isDebugEnabled()) logger.debug("Redirecting to login page..."); redirectToLoginPage(req, res, getServletContext()); } else { if (logger.isDebugEnabled()) logger.debug("Returning 403 Forbidden error..."); res.sendError(HttpServletResponse.SC_FORBIDDEN); } return; } // if no context is specified, use the template itself // TODO: should this default to something else? if (nodeRef == null && templateRef != null) { nodeRef = templateRef; } if (nodeRef == null) { throw new TemplateException("Not enough elements supplied in URL or no 'path' argument specified."); } // get the services we need to retrieve the content ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); NodeService nodeService = serviceRegistry.getNodeService(); TemplateService templateService = serviceRegistry.getTemplateService(); PermissionService permissionService = serviceRegistry.getPermissionService(); // check that the user has at least READ access on any nodes - else redirect to the login page if (permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.DENIED || (templateRef != null && permissionService.hasPermission(templateRef, PermissionService.READ) == AccessStatus.DENIED)) { if (redirectToLogin) { if (logger.isDebugEnabled()) logger.debug("Redirecting to login page..."); redirectToLoginPage(req, res, getServletContext()); } else { if (logger.isDebugEnabled()) logger.debug("Returning 403 Forbidden error..."); res.sendError(HttpServletResponse.SC_FORBIDDEN); } return; } String mimetype = MIMETYPE_HTML; if (req.getParameter(ARG_MIMETYPE) != null) { mimetype = req.getParameter(ARG_MIMETYPE); } res.setContentType(mimetype); try { UserTransaction txn = null; try { txn = serviceRegistry.getTransactionService().getUserTransaction(true); txn.begin(); // if template not supplied, then use the default against the node if (templateRef == null) { if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPLATABLE)) { templateRef = (NodeRef) nodeService.getProperty(nodeRef, ContentModel.PROP_TEMPLATE); } if (templateRef == null) { throw new TemplateException( "Template reference not set against node or not supplied in URL."); } } // create the model - put the supplied noderef in as space/document as appropriate Map<String, Object> model = getModel(serviceRegistry, req, templateRef, nodeRef); // process the template against the node content 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. try { templateService.processTemplate(templateRef.toString(), model, res.getWriter()); // commit the transaction txn.commit(); } catch (SocketException e) { if (e.getMessage().contains("ClientAbortException")) { // the client cut the connection - our mission was accomplished apart from a little error message logger.error("Client aborted stream read:\n node: " + nodeRef + "\n template: " + templateRef); try { if (txn != null) { txn.rollback(); } } catch (Exception tex) { } } else { throw e; } } finally { res.getWriter().close(); } } catch (Throwable txnErr) { try { if (txn != null) { txn.rollback(); } } catch (Exception tex) { } throw txnErr; } } catch (Throwable err) { throw new AlfrescoRuntimeException("Error during template servlet processing: " + err.getMessage(), err); } }