Example usage for org.apache.commons.logging Log debug

List of usage examples for org.apache.commons.logging Log debug

Introduction

In this page you can find the example usage for org.apache.commons.logging Log debug.

Prototype

void debug(Object message);

Source Link

Document

Logs a message with debug log level.

Usage

From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java

/**
 * Process a type 3 NTLM message/*from   w  ww  .  ja  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.
 * //w w w.j a v  a2s  .c  o  m
 * @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.traitextender.AJExtender.java

/**
 * Logs each method routing path once per session.
 * /*ww  w . java 2  s. co  m*/
 * @param logger
 * @param route
 */
static void oneTimeLiveLog(Log logger, ExtensionRoute route) {
    synchronized (AJExtender.class) {
        if (oneTimeLogSet == null) {
            oneTimeLogSet = new ConcurrentHashSet<>();
        }
    }

    synchronized (oneTimeLogSet) {
        if (oneTimeLogSet.contains(route)) {
            return;
        } else {
            logger.debug(route.toString());
            oneTimeLogSet.add(route);
        }
    }
}

From source file:org.alfresco.util.LogUtil.java

/**
 * Log an I18Nized message to DEBUG.// w  w  w  . j a  v  a 2  s  .  com
 * 
 * @param logger        the logger to use
 * @param messageKey    the message key
 * @param args          the required message arguments
 */
public static final void debug(Log logger, String messageKey, Object... args) {
    logger.debug(I18NUtil.getMessage(messageKey, args));
}

From source file:org.alfresco.web.app.Application.java

/**
 * Handles errors thrown from servlets//from  ww  w.j  a  va  2 s .  c o  m
 * 
 * @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.
 * //from  w w w.j  a v a2  s  .  co  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 ww.j  a  va2 s. com*/
 * 
 * @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.//  w w w .ja  v a  2 s  . 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);
    }
}

From source file:org.anyframe.iam.admin.common.aspect.LoggingAspect.java

/**
 * catch and logging through aspect service ( setting :
 * [src/main/resources/spring/common/context-aspect.xml] )
 * /*from   w w w . j  a  v  a  2  s.  co  m*/
 * @param thisJoinPoint aspect service JoinPoint
 */
public void beforeLogging(JoinPoint thisJoinPoint) {

    Object target = thisJoinPoint.getTarget();

    while (target instanceof Advised) {
        try {
            target = ((Advised) target).getTargetSource().getTarget();
        } catch (Exception e) {
            LogFactory.getLog(this.getClass()).error("Fail to get target object from JointPoint.", e);
        }
    }

    if (target == null)
        return;

    String className = target.getClass().getSimpleName();
    String opName = (thisJoinPoint.getSignature().getName());

    StringBuffer buf = new StringBuffer();
    buf.append("\n** Logging Aspect : executed " + opName + "() in " + className + " Class.");
    Object[] arguments = thisJoinPoint.getArgs();
    if (arguments.length > 0) {
        buf.append("\n************* " + arguments[0].getClass().getName() + " *************\n");
        buf.append(arguments[0].toString());
        buf.append("\n*********************************************************\n");
    } else
        buf.append("\nNo arguments\n");

    Log logger = LogFactory.getLog(target.getClass());
    if (logger.isDebugEnabled())
        logger.debug(buf.toString());
}

From source file:org.anyframe.oden.admin.aspect.LoggingAspect.java

@Before("execution(* org.anyframe.oden..*Impl.*(..))")
public void beforeLogging(JoinPoint thisJoinPoint) {
    Class<? extends Object> clazz = thisJoinPoint.getTarget().getClass();
    String methodName = thisJoinPoint.getSignature().getName();
    Object[] arguments = thisJoinPoint.getArgs();

    StringBuffer argBuf = new StringBuffer();
    StringBuffer argValueBuf = new StringBuffer();
    int i = 0;/*from   w  w w  .java  2  s .  c om*/
    for (Object argument : arguments) {
        String argClassName = argument.getClass().getSimpleName();
        if (i > 0) {
            argBuf.append(", ");
        }
        String arg = argClassName + " arg" + ++i;
        argBuf.append(arg);
        argValueBuf.append(".arg" + i + " : " + argument.toString() + "\n");
    }

    if (i == 0) {
        argValueBuf.append("No arguments\n");
    }

    StringBuffer messageBuf = new StringBuffer();
    messageBuf.append("before executing " + methodName + "(" + argBuf.toString() + ") method");
    messageBuf.append("\n-------------------------------------------------------------------------------\n");
    messageBuf.append(argValueBuf.toString());
    messageBuf.append("-------------------------------------------------------------------------------");

    Log logger = LogFactory.getLog(clazz);
    if (logger.isDebugEnabled()) {
        logger.debug(messageBuf.toString());
    }
}