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

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

Introduction

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

Prototype

void trace(Object message);

Source Link

Document

Logs a message with trace log level.

Usage

From source file:org.rhq.enterprise.gui.legacy.portlet.addresource.AddResourcesAction.java

/**
 * Add resources to the user specified in the given <code>AddResourcesForm</code>.
 *///from w  ww  . j  a v a  2s  .  co m
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Log log = LogFactory.getLog(AddResourcesAction.class);
    HttpSession session = request.getSession();
    WebUser user = SessionUtils.getWebUser(session);
    WebUserPreferences preferences = user.getWebPreferences();
    AddResourcesForm addForm = (AddResourcesForm) form;

    ActionForward forward = checkSubmit(request, mapping, form, Constants.USER_PARAM, user.getId());
    if (forward != null) {
        BaseValidatorForm spiderForm = (BaseValidatorForm) form;

        if (spiderForm.isCancelClicked() || spiderForm.isResetClicked()) {
            log.trace("removing pending resources list");
            SessionUtils.removeList(session, Constants.PENDING_RESOURCES_SES_ATTR);
        } else if (spiderForm.isAddClicked()) {
            log.trace("adding to pending resources list");
            SessionUtils.addToList(session, Constants.PENDING_RESOURCES_SES_ATTR,
                    addForm.getAvailableResources());
        } else if (spiderForm.isRemoveClicked()) {
            log.trace("removing from pending resources list");
            SessionUtils.removeFromList(session, Constants.PENDING_RESOURCES_SES_ATTR,
                    addForm.getPendingResources());
        }

        return forward;
    }

    log.trace("getting pending resources list");
    List<String> pendingResourceIds = SessionUtils.getListAsListStr(request.getSession(),
            Constants.PENDING_RESOURCES_SES_ATTR);

    StringBuffer resourcesAsString = new StringBuffer();
    int count = 0;
    for (String pendingId : pendingResourceIds) {
        if (count != 0) {
            resourcesAsString.append(DashboardUtils.DASHBOARD_DELIMITER);
        }
        resourcesAsString.append(pendingId);
        count++;
    }

    SessionUtils.removeList(session, Constants.PENDING_RESOURCES_SES_ATTR);

    RequestUtils.setConfirmation(request, "admin.user.confirm.AddResource");

    preferences.setPreference(addForm.getKey(), resourcesAsString);

    return returnSuccess(request, mapping);
}

From source file:org.rhq.enterprise.gui.legacy.portlet.addresource.AddResourcesPrepareAction.java

@Override
@SuppressWarnings({ "unchecked", "deprecation" })
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Log log = LogFactory.getLog(AddResourcesPrepareAction.class);
    AddResourcesForm addForm = (AddResourcesForm) form;
    HttpSession session = request.getSession();
    WebUser user = RequestUtils.getWebUser(request);
    Subject subject = user.getSubject();
    ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();

    PageControl pcAvail = WebUtility.getPageControl(request, "a");
    PageControl pcPending = WebUtility.getPageControl(request, "p");
    log.trace("available page control: " + pcAvail);
    log.trace("pending page control: " + pcPending);

    // first, get the pending resources (those that have been added to the RHS
    // pending resources are those on the right side of the "add to list" widget that are awaiting association with the group when the form's "ok" button is clicked. */
    log.debug("check session if there are pending resources");
    List<String> pendingResourceList = new ArrayList<String>();

    if (session.getAttribute(Constants.PENDING_RESOURCES_SES_ATTR) == null) {
        // if hitting the page for the first time, load resources already associated with user via preferences
        log.debug("get pending resources from user preferences");
        WebUserPreferences preferences = user.getWebPreferences();
        pendingResourceList = preferences.getPreferenceAsList(addForm.getKey(),
                DashboardUtils.DASHBOARD_DELIMITER);

        if (pendingResourceList != null) {
            // otherwise, we've been here for a while but the user paged, performed changed LHS<->RHS, etc
            log.debug("put entire list of pending resources in session");
            session.setAttribute(Constants.PENDING_RESOURCES_SES_ATTR, pendingResourceList);
        }//from  w w w .ja  v  a 2 s  .co  m
    } else {
        pendingResourceList = SessionUtils.getListAsList(session, Constants.PENDING_RESOURCES_SES_ATTR);
    }

    // get the resources, so we can display name & description in the UI
    log.debug("get page of pending resources selected by user");
    int[] pendingResourceArray = StringUtility.getIntArray(pendingResourceList);
    PageList<Resource> pendingResources = resourceManager.findResourceByIds(subject, pendingResourceArray,
            false, pcPending);

    PageList<DisambiguationReport<Resource>> disambiguatedPendingResources = DisambiguatedResourceListUtil
            .disambiguate(resourceManager, pendingResources, RESOURCE_ID_EXTRACTOR);

    // give 'em to the jsp page
    log.debug("put selected page of pending resources in request");
    request.setAttribute(Constants.PENDING_RESOURCES_ATTR, disambiguatedPendingResources);
    request.setAttribute(Constants.NUM_PENDING_RESOURCES_ATTR, disambiguatedPendingResources.getTotalSize());

    // available resources are all resources in the system that are not associated with the user and are not pending
    log.debug("determine if user wants to filter available resources");
    Integer typeIdFilter = ((addForm.getType() == null) || (addForm.getType() == DEFAULT_RESOURCE_TYPE)) ? null
            : addForm.getType();
    ResourceCategory categoryFilter = (addForm.getCategory() != null)
            ? ResourceCategory.valueOf(addForm.getCategory().toUpperCase())
            : ResourceCategory.PLATFORM;

    int[] excludeIds = StringUtility.getIntArray(pendingResourceList);
    PageList<Resource> availableResources = null;

    availableResources = resourceManager.findAvailableResourcesForDashboardPortlet(subject, typeIdFilter,
            categoryFilter, excludeIds, pcAvail);

    PageList<DisambiguationReport<Resource>> disambiguatedAvailableResources = DisambiguatedResourceListUtil
            .disambiguate(resourceManager, availableResources, RESOURCE_ID_EXTRACTOR);

    log.debug("put selected page of available resources in request");
    request.setAttribute(Constants.AVAIL_RESOURCES_ATTR, disambiguatedAvailableResources);
    request.setAttribute(Constants.NUM_AVAIL_RESOURCES_ATTR, disambiguatedAvailableResources.getTotalSize());

    log.debug("get the available resources user can filter by");
    setDropDowns(addForm, request, subject, categoryFilter);

    return null;
}

From source file:org.rhq.enterprise.gui.legacy.portlet.search.ViewAction.java

@Override
public ActionForward execute(ComponentContext context, ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {// w  w w.j  av a  2s  .co m
        StopWatch timer = new StopWatch();
        Log timingLog = LogFactory.getLog("DASHBOARD-TIMING");

        ResourceHubForm hubForm = (ResourceHubForm) form;
        for (ResourceCategory category : ResourceCategory.values()) {
            hubForm.addFunction(new LabelValueBean(category.name(), category.name()));
        }

        timingLog.trace("SearchHubPrepare - timing [" + timer.toString() + "]");
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Dashboard Portlet [SavedQueries] experienced an error: " + e.getMessage(), e);
        } else {
            log.error("Dashboard Portlet [SavedQueries] experienced an error: " + e.getMessage());
        }
    } finally {
        // nothing to put in the context for this portlet
    }

    return null;
}

From source file:org.sharetask.utility.log.ErrorInterceptor.java

@Override
protected void writeToLog(final Log logger, final String message, final Throwable ex) {
    if (ex != null) {
        logger.error(message, ex);//from  w  w  w  . java2s. c om
    } else {
        logger.trace(message);
    }
}

From source file:org.springframework.core.log.LogFormatUtils.java

/**
 * Use this to log a message with different levels of detail (or different
 * messages) at TRACE vs DEBUG log levels. Effectively, a substitute for:
 * <pre class="code">//from   w w  w . jav  a  2  s .  c o  m
 * if (logger.isDebugEnabled()) {
 *   String str = logger.isTraceEnabled() ? "..." : "...";
 *   if (logger.isTraceEnabled()) {
 *     logger.trace(str);
 *   }
 *   else {
 *     logger.debug(str);
 *   }
 * }
 * </pre>
 * @param logger the logger to use to log the message
 * @param messageFactory function that accepts a boolean set to the value
 * of {@link Log#isTraceEnabled()}
 */
public static void traceDebug(Log logger, Function<Boolean, String> messageFactory) {
    if (logger.isDebugEnabled()) {
        boolean traceEnabled = logger.isTraceEnabled();
        String logMessage = messageFactory.apply(traceEnabled);
        if (traceEnabled) {
            logger.trace(logMessage);
        } else {
            logger.debug(logMessage);
        }
    }
}

From source file:org.springframework.extensions.surf.core.scripts.ScriptResourceHelper.java

/**
 * Recursively resolve imports in the specified scripts, adding the imports to the
 * specific list of scriplets to combine later.
 * /*  ww w  . j  a  v a  2s .  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;
        }
    }

    // Allow a comment marker to immediately precede the IMPORT_PREFIX to assist JS validation.
    if (script.startsWith(IMPORT_COMMENT_MARKER, index)) {
        index += IMPORT_COMMENT_MARKER.length();
    }

    // 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.springframework.kafka.support.SeekUtils.java

/**
 * Seek records to earliest position, optionally skipping the first.
 * @param records the records./*from w ww.j a  v a 2 s  . co  m*/
 * @param consumer the consumer.
 * @param exception the exception
 * @param recoverable true if skipping the first record is allowed.
 * @param skipper function to determine whether or not to skip seeking the first.
 * @param logger a {@link Log} for seek errors.
 * @return true if the failed record was skipped.
 */
public static boolean doSeeks(List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer, Exception exception,
        boolean recoverable, BiPredicate<ConsumerRecord<?, ?>, Exception> skipper, Log logger) {
    Map<TopicPartition, Long> partitions = new LinkedHashMap<>();
    AtomicBoolean first = new AtomicBoolean(true);
    AtomicBoolean skipped = new AtomicBoolean();
    records.forEach(record -> {
        if (recoverable && first.get()) {
            skipped.set(skipper.test(record, exception));
            if (skipped.get() && logger.isDebugEnabled()) {
                logger.debug("Skipping seek of: " + record);
            }
        }
        if (!recoverable || !first.get() || !skipped.get()) {
            partitions.computeIfAbsent(new TopicPartition(record.topic(), record.partition()),
                    offset -> record.offset());
        }
        first.set(false);
    });
    boolean tracing = logger.isTraceEnabled();
    partitions.forEach((topicPartition, offset) -> {
        try {
            if (tracing) {
                logger.trace("Seeking: " + topicPartition + " to: " + offset);
            }
            consumer.seek(topicPartition, offset);
        } catch (Exception e) {
            logger.error("Failed to seek " + topicPartition + " to " + offset, e);
        }
    });
    return skipped.get();
}

From source file:org.talframework.tal.aspects.loggers.http.DefaultRequestLogger.java

/**
 * Helper to log out the request attributes at trace level
 * /*from ww  w  .  ja  va2 s.c om*/
 * @param req The request
 * @param logger The logger
 */
@SuppressWarnings("unchecked")
private void logRequestAttributes(HttpServletRequest req, Log logger) {
    StringBuilder buf = new StringBuilder();
    buf.append("Request Attributes: ");
    buf.append("\n\t**** Request Attributes ****");
    Enumeration e = req.getAttributeNames();
    while (e.hasMoreElements()) {
        String k = (String) e.nextElement();
        buf.append("\n\t").append(k).append("=").append(LoggerHelper.getValue(req.getAttribute(k)));
    }
    buf.append("\n\t**** End Request Attrobites ****");
    logger.trace(buf.toString());
}

From source file:org.talframework.tal.aspects.loggers.trace.DefaultTraceLogger.java

/**
 * Logs out a message to state the method has started with
 * the arguments that is has (if any). The trace logger as
 * a whole must be set at debug level and the actual classes
 * logger must be a trace to see anything.
 *//*from  w  w  w.  jav  a 2s.c  o  m*/
public void traceBefore(JoinPoint jp) {
    if (!logger.isDebugEnabled())
        return;

    Log traceLogger = LoggerHelper.getLogger(jp.getStaticPart().getSignature().getDeclaringType());
    if (traceLogger.isTraceEnabled()) {
        StringBuilder builder = new StringBuilder();

        builder.append(">>> Starting: ").append(jp.getStaticPart().getSignature().getName());
        LoggerHelper.appendArguments(jp.getArgs(), builder);

        traceLogger.trace(builder.toString());
    }
}

From source file:org.talframework.tal.aspects.loggers.trace.DefaultTraceLogger.java

/**
 * Logs out a messages to state the method has ended outputting
 * the return value. The trace logger as a whole must be at 
 * debug level and the actual classes logger must be at trace to
 * see anything.//ww  w  . j  a va  2s  .c om
 */
public void traceAfter(JoinPoint jp, Object retVal) {
    if (!logger.isDebugEnabled())
        return;

    Log traceLogger = LoggerHelper.getLogger(jp.getStaticPart().getSignature().getDeclaringType());
    if (traceLogger.isTraceEnabled()) {
        StringBuilder builder = new StringBuilder();

        builder.append("<<< Ending: ").append(jp.getStaticPart().getSignature().getName());
        if (retVal != null) {
            builder.append("\n\tretVal=").append(retVal);
        }

        traceLogger.trace(builder.toString());
    }
}