List of usage examples for org.apache.commons.logging Log error
void error(Object message);
From source file:org.alfresco.repo.action.executer.TransformActionExecuter.java
@Override public boolean onLogException(Log logger, Throwable t, String message) { if (t instanceof UnimportantTransformException) { logger.debug(message);/*from w w w . j a v a 2 s .co m*/ return true; } else if (t instanceof UnsupportedTransformationException) { logger.error(message); return true; } return false; }
From source file:org.alfresco.repo.module.LoggerModuleComponent.java
@Override protected void executeInternal() throws Throwable { String moduleId = super.getModuleId(); String name = super.getName(); Log logger = LogFactory.getLog(moduleId + "." + name); switch (logLevel) { case INFO://from w w w . j ava2 s . c om logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: logger.error(message); break; } }
From source file:org.alfresco.repo.tenant.MultiTAdminServiceImpl.java
@Override public void deployTenants(final TenantDeployer deployer, Log logger) { if (deployer == null) { throw new AlfrescoRuntimeException("Deployer must be provided"); }/*from w w w .ja v a 2 s. c o m*/ if (logger == null) { throw new AlfrescoRuntimeException("Logger must be provided"); } if (tenantService.isEnabled()) { UserTransaction userTransaction = transactionService.getUserTransaction(); authenticationContext.setSystemUserAsCurrentUser(); List<Tenant> tenants = null; try { userTransaction.begin(); tenants = getAllTenants(); userTransaction.commit(); } catch (Throwable e) { // rollback the transaction try { if (userTransaction != null) { userTransaction.rollback(); } } catch (Exception ex) { } throw new AlfrescoRuntimeException("Failed to get tenants", e); } finally { authenticationContext.clearCurrentSecurityContext(); } for (Tenant tenant : tenants) { if (tenant.isEnabled()) { try { // deploy within context of tenant domain TenantUtil.runAsSystemTenant(new TenantRunAsWork<Object>() { public Object doWork() { // init the service within tenant context deployer.init(); return null; } }, tenant.getTenantDomain()); } catch (Throwable e) { logger.error("Deployment failed" + e); StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); logger.error(stringWriter.toString()); // tenant deploy failure should not necessarily affect other tenants } } } } }
From source file:org.alfresco.repo.tenant.MultiTAdminServiceImpl.java
@Override public void undeployTenants(final TenantDeployer deployer, Log logger) { if (deployer == null) { throw new AlfrescoRuntimeException("Deployer must be provided"); }/*from ww w .j ava 2 s . com*/ if (logger == null) { throw new AlfrescoRuntimeException("Logger must be provided"); } if (tenantService.isEnabled()) { UserTransaction userTransaction = transactionService.getUserTransaction(); authenticationContext.setSystemUserAsCurrentUser(); List<Tenant> tenants = null; try { userTransaction.begin(); tenants = getAllTenants(); userTransaction.commit(); } catch (Throwable e) { // rollback the transaction try { if (userTransaction != null) { userTransaction.rollback(); } } catch (Exception ex) { } try { authenticationContext.clearCurrentSecurityContext(); } catch (Exception ex) { } throw new AlfrescoRuntimeException("Failed to get tenants", e); } try { AuthenticationUtil.pushAuthentication(); for (Tenant tenant : tenants) { if (tenant.isEnabled()) { try { // undeploy within context of tenant domain TenantUtil.runAsSystemTenant(new TenantRunAsWork<Object>() { public Object doWork() { // destroy the service within tenant context deployer.destroy(); return null; } }, tenant.getTenantDomain()); } catch (Throwable e) { logger.error("Undeployment failed" + e); StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); logger.error(stringWriter.toString()); // tenant undeploy failure should not necessarily affect other tenants } } } } finally { AuthenticationUtil.popAuthentication(); } } }
From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java
/** * Process a type 3 NTLM message// w ww . j a va2 s.c om * * @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.service.cmr.admin.RepoUsageStatus.java
/** * Log warnings and errors to the given logger *//*from ww w. j a va 2 s . c om*/ public void logMessages(Log logger) { for (String msg : warnings) { logger.warn(msg); } for (String msg : errors) { logger.error(msg); } }
From source file:org.alfresco.util.LogUtil.java
/** * Log an I18Nized message to ERROR.//from w ww.jav a 2 s .c om * * @param logger the logger to use * @param messageKey the message key * @param args the required message arguments */ public static final void error(Log logger, String messageKey, Object... args) { logger.error(I18NUtil.getMessage(messageKey, args)); }
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 . j a va2 s. c o m*/ * * @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.apache.axiom.om.util.CommonUtils.java
/** * Writes the om to a log.debug.//from ww w .j a v a 2s. c o m * Also calculates the length of the message. * @param om OMElement * @param log Log * @param limit limit of message to write * @param format OMOutputFormat * @return length of entire message */ public static long logDebug(OMElement om, Log log, int limit, OMOutputFormat format) { LogOutputStream logStream = new LogOutputStream(log, limit); try { om.serialize(logStream, format); logStream.flush(); logStream.close(); } catch (Throwable t) { // Problem occur while logging. Log error and continue log.debug(t); log.error(t); } return logStream.getLength(); }
From source file:org.apache.cayenne.tools.DbGeneratorMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { Log logger = new MavenLogger(this); Injector injector = DIBootstrap.createInjector(new DbSyncModule(), new ToolsModule(logger)); AdhocObjectFactory objectFactory = injector.getInstance(AdhocObjectFactory.class); logger.info(/*from w w w . j a v a 2s . c o m*/ String.format("connection settings - [driver: %s, url: %s, username: %s]", driver, url, username)); logger.info(String.format( "generator options - [dropTables: %s, dropPK: %s, createTables: %s, createPK: %s, createFK: %s]", dropTables, dropPK, createTables, createPK, createFK)); try { final DbAdapter adapterInst = (adapter == null) ? (DbAdapter) objectFactory.newInstance(DbAdapter.class, JdbcAdapter.class.getName()) : (DbAdapter) objectFactory.newInstance(DbAdapter.class, adapter); // Load the data map and run the db generator. DataMap dataMap = loadDataMap(); DbGenerator generator = new DbGenerator(adapterInst, dataMap, NoopJdbcEventLogger.getInstance()); generator.setShouldCreateFKConstraints(createFK); generator.setShouldCreatePKSupport(createPK); generator.setShouldCreateTables(createTables); generator.setShouldDropPKSupport(dropPK); generator.setShouldDropTables(dropTables); // load driver taking custom CLASSPATH into account... DriverDataSource dataSource = new DriverDataSource((Driver) Class.forName(driver).newInstance(), url, username, password); generator.runGenerator(dataSource); } catch (Exception ex) { Throwable th = Util.unwindException(ex); String message = "Error generating database"; if (th.getLocalizedMessage() != null) { message += ": " + th.getLocalizedMessage(); } logger.error(message); throw new MojoExecutionException(message, th); } }