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

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

Introduction

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

Prototype

boolean isDebugEnabled();

Source Link

Document

Is debug logging currently enabled?

Usage

From source file:org.hyperic.hq.plugin.netdevice.NetworkDevicePlatformDetector.java

public PlatformResource getPlatformResource(ConfigResponse config) throws PluginException {
    String platformIp = config.getValue(ProductPlugin.PROP_PLATFORM_IP);

    // For command-line -DsnmpIp=x.x.x.x usage...
    platformIp = getIpProp(SNMPClient.PROP_IP, platformIp, platformIp);

    String defaultVersion = getIpProp(SNMPClient.PROP_VERSION, platformIp, SNMPClient.VALID_VERSIONS[1]); // v2c

    String fallbackVersion = SNMPClient.VALID_VERSIONS[0]; // v1

    PlatformResource platform = super.getPlatformResource(config);

    Log log = getLog();

    ConfigResponse metricConfig;/*from   www  .jav  a 2  s  .  co m*/

    boolean hasConfig = config.getValue(SNMPClient.PROP_IP) != null;

    if (hasConfig) {
        // We've already been here...
        metricConfig = config;

        if (log.isDebugEnabled()) {
            log.debug("Using approved snmp config=" + metricConfig);
        }
    } else if (this.autoDefaults) {
        // Platform was just created, attempt to auto-configure...
        metricConfig = new ConfigResponse();

        metricConfig.setValue(SNMPClient.PROP_IP, platformIp);
        metricConfig.setValue(SNMPClient.PROP_VERSION, defaultVersion);

        metricConfig.setValue(SNMPClient.PROP_COMMUNITY,
                getIpProp(SNMPClient.PROP_COMMUNITY, platformIp, SNMPClient.DEFAULT_COMMUNITY));

        metricConfig.setValue(SNMPClient.PROP_PORT,
                getIpProp(SNMPClient.PROP_PORT, platformIp, SNMPClient.DEFAULT_PORT_STRING));

        metricConfig.setValue(NetworkDeviceDetector.PROP_IF_IX,
                getIpProp(NetworkDeviceDetector.PROP_IF_IX, platformIp, NetworkDeviceDetector.IF_DESCR));
        if (log.isDebugEnabled()) {
            log.debug("Using default snmp config=" + metricConfig);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Need user input for snmp config=" + config);
        }

        return platform;
    }

    ConfigResponse cprops = new ConfigResponse();

    SNMPSession session;

    if ((session = getSession(metricConfig)) == null) {
        return platform;
    }

    try {
        session.getSingleValue("sysName");
    } catch (SNMPException e) {
        getLog().debug("Unable to connect using " + defaultVersion + ", trying version " + fallbackVersion);

        metricConfig.setValue(SNMPClient.PROP_VERSION, fallbackVersion);

        if ((session = getSession(metricConfig)) == null) {
            return platform;
        }
    }

    String[] keys = getCustomPropertiesSchema().getOptionNames();

    for (int i = 0; i < keys.length; i++) {
        String key = keys[i];

        if (Character.isUpperCase(key.charAt(0))) {
            continue; // Not a MIB name
        }

        String val = getString(session, key);

        if (val == null) {
            log.debug("'" + key + "'==null");

            continue;
        }

        cprops.setValue(key, val);
    }

    if (!hasConfig) {
        // Should only happen when the platform is created...
        config.merge(metricConfig, false);

        platform.setProductConfig(config);
        platform.setMeasurementConfig(new ConfigResponse());

        log.debug("Setting measurement config=" + metricConfig);
    }

    String description = getString(session, "sysDescr");

    if (description != null) {
        platform.setDescription(description);

        boolean hasVersionCprop = getCustomPropertiesSchema().getOption(PROP_VERSION) != null;

        if (hasVersionCprop) {
            // This works for Cisco IOS at least...
            StringTokenizer tok = new StringTokenizer(description, " ,");

            while (tok.hasMoreTokens()) {
                String s = tok.nextToken();

                if (s.equalsIgnoreCase(PROP_VERSION) && tok.hasMoreTokens()) {
                    String version = tok.nextToken();

                    cprops.setValue(PROP_VERSION, version);

                    break;
                }
            }
        }
    }

    platform.setCustomProperties(cprops);

    return platform;
}

From source file:org.hyperic.hq.ui.action.admin.user.RegisterAction.java

/**
 * Create the user with the attributes specified in the given
 * <code>NewForm</code> and save it into the session attribute
 * <code>Constants.USER_ATTR</code>.
 *//*from w  ww .j  a  va 2 s.  co m*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final Log log = LogFactory.getLog(RegisterAction.class.getName());
    final boolean debug = log.isDebugEnabled();

    Integer sessionId = RequestUtils.getSessionId(request);
    EditForm userForm = (EditForm) form;
    HttpSession session = request.getSession(false);
    ActionForward forward = checkSubmit(request, mapping, form);

    if (forward != null) {
        return forward;
    }

    //get the spiderSubjectValue of the user to be deleated.
    ServletContext ctx = getServlet().getServletContext();
    WebUser webUser = RequestUtils.getWebUser(session);

    // password was saved off when the user logged in
    String password = (String) session.getAttribute(Constants.PASSWORD_SES_ATTR);

    session.removeAttribute(Constants.PASSWORD_SES_ATTR);

    // use the overlord to register the subject, and don't add
    // a principal
    if (debug)
        log.debug("registering subject [" + webUser.getUsername() + "]");

    Integer authzSubjectId = userForm.getId();
    AuthzSubject target = authzSubjectManager.findSubjectById(authzSubjectId);

    authzBoss.updateSubject(sessionId, target, Boolean.TRUE, HQConstants.ApplicationName,
            userForm.getDepartment(), userForm.getEmailAddress(), userForm.getFirstName(),
            userForm.getLastName(), userForm.getPhoneNumber(), userForm.getSmsAddress(), null);

    // nuke the temporary bizapp session and establish a new
    // one for this subject.. must be done before pulling the
    // new subject in order to do it with his own credentials
    // TODO need to make sure this is valid
    sessionManager.invalidate(sessionId);

    sessionId = sessionManager.put(authzSubjectManager.findSubjectById(authzSubjectId));

    if (debug)
        log.debug("finding subject [" + webUser.getUsername() + "]");

    // the new user has no prefs, but we still want to pick up
    // the defaults
    ConfigResponse preferences = (ConfigResponse) ctx.getAttribute(Constants.DEF_USER_PREFS);

    // look up the user's permissions
    if (debug)
        log.debug("getting all operations");

    Map<String, Boolean> userOpsMap = new HashMap<String, Boolean>();
    List<Operation> userOps = authzBoss.getAllOperations(sessionId);

    // TODO come back to this and see why this is done...
    for (Operation op : userOps) {
        userOpsMap.put(op.getName(), Boolean.TRUE);
    }

    // we also need to create up a new web user
    webUser = new WebUser(target, sessionId, preferences, false);

    session.setAttribute(Constants.WEBUSER_SES_ATTR, webUser);
    session.setAttribute(Constants.USER_OPERATIONS_ATTR, userOpsMap);

    Map<String, Object> parms = new HashMap<String, Object>(1);

    parms.put(Constants.USER_PARAM, target.getId());

    return returnSuccess(request, mapping, parms, false);
}

From source file:org.impalaframework.extension.mvc.util.RequestModelHelper.java

/**
 * /*from w w w  .j ava 2 s  .  co m*/
 * @param logger
 * @param request
 */
public static void maybeDebugRequest(Log logger, HttpServletRequest request) {

    if (logger.isDebugEnabled()) {

        logger.debug("#####################################################################################");
        logger.debug("---------------------------- Request details ---------------------------------------");
        logger.debug("Request context path: " + request.getContextPath());
        logger.debug("Request path info: " + request.getPathInfo());
        logger.debug("Request path translated: " + request.getPathTranslated());
        logger.debug("Request query string: " + request.getQueryString());
        logger.debug("Request servlet path: " + request.getServletPath());
        logger.debug("Request request URI: " + request.getRequestURI());
        logger.debug("Request request URL: " + request.getRequestURL());
        logger.debug("Request session ID: " + request.getRequestedSessionId());

        logger.debug("------------------------------------------------ ");
        logger.debug("Parameters ------------------------------------- ");
        final Enumeration<String> parameterNames = request.getParameterNames();

        Map<String, String> parameters = new TreeMap<String, String>();

        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String value = request.getParameter(name);
            final String lowerCase = name.toLowerCase();
            if (lowerCase.contains("password") || lowerCase.contains("cardnumber")) {
                value = "HIDDEN";
            }
            parameters.put(name, value);
        }

        //now output            
        final Set<String> parameterKeys = parameters.keySet();
        for (String key : parameterKeys) {
            logger.debug(key + ": " + parameters.get(key));
        }

        logger.debug("------------------------------------------------ ");

        Map<String, Object> attributes = new TreeMap<String, Object>();

        logger.debug("Attributes ------------------------------------- ");
        final Enumeration<String> attributeNames = request.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String name = attributeNames.nextElement();
            Object value = request.getAttribute(name);
            final String lowerCase = name.toLowerCase();
            if (lowerCase.contains("password") || lowerCase.contains("cardnumber")) {
                value = "HIDDEN";
            }
            attributes.put(name, value);
        }

        //now output
        final Set<String> keys = attributes.keySet();
        for (String name : keys) {
            Object value = attributes.get(name);
            logger.debug(name + ": " + (value != null ? value.toString() : value));
        }

        logger.debug("------------------------------------------------ ");
        logger.debug("#####################################################################################");
    } else {
        if (logger.isInfoEnabled()) {
            logger.info(
                    "#####################################################################################");
            logger.info("Request query string: " + request.getQueryString());
            logger.info("Request request URI: " + request.getRequestURI());
            logger.info(
                    "#####################################################################################");
        }
    }
}

From source file:org.impalaframework.web.utils.WebPathUtils.java

public static void maybeLogRequest(HttpServletRequest request, Log logger) {

    if (logger.isDebugEnabled()) {
        logger.debug("Request context path: " + request.getContextPath());
        logger.debug("Request local address: " + request.getLocalAddr());
        logger.debug("Request local name: " + request.getLocalName());
        logger.debug("Request path info: " + request.getPathInfo());
        logger.debug("Request path translated: " + request.getPathTranslated());
        logger.debug("Request query string: " + request.getQueryString());
        logger.debug("Request servlet path: " + request.getServletPath());
        logger.debug("Request request URI: " + request.getRequestURI());
        logger.debug("Request request URL: " + request.getRequestURL());
        logger.debug("Request session ID: " + request.getRequestedSessionId());
    }/*  w  w  w. j av a 2  s . c o m*/
}

From source file:org.inwiss.platform.common.util.ConvertUtil.java

/**
 * Converts string to byte array according to specified encoding
 *
 * @param content  String to convert to array
 * @param encoding Encoding string, if <code>null</code> default is used
 * @return byte array//from w  w w . j  a  va  2 s.  co m
 */
public static byte[] convertToByteArray(String content, String encoding) {

    Log log = LogFactory.getLog(ConvertUtil.class);

    if (content == null) {
        return null;
    }
    if (encoding == null) {
        encoding = Constants.DEFAULT_ENCODING;
    }

    if (log.isDebugEnabled()) {
        log.debug("Converting to byte array using: " + encoding);
    }

    byte[] value;
    try {
        value = content.getBytes(encoding);
    } catch (UnsupportedEncodingException ex) {
        if (log.isWarnEnabled()) {
            log.warn(ex);
        }
        return content.getBytes();
    }
    return value;
}

From source file:org.jasig.portal.utils.threading.DoubleCheckedCreator.java

/**
 * Double checking retrieval/creation of an object
 * //www.  j  a va 2 s  .c o  m
 * @param args Optional arguments to pass to {@link #retrieve(Object...)}, {@link #create(Object...)}, and {@link #invalid(Object, Object...)}.
 * @return A retrieved or created object.
 */
public final T get(Object... args) {
    final Log logger = LogFactory.getLog(LOGGER_NAME);
    //Grab a read lock to try retrieving the object
    this.readLock.lock();
    try {

        //See if the object already exists and is valid
        final T value = this.retrieve(args);
        if (!this.invalid(value, args)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Using retrieved Object='" + value + "'");
            }

            return value;
        }
    } finally {
        //Release the read lock
        this.readLock.unlock();
    }

    //Object must not be valid, switch to a write lock
    this.writeLock.lock();
    try {
        //Check again if the object exists and is valid
        T value = this.retrieve(args);
        if (this.invalid(value, args)) {

            //Object is not valid, create it
            value = this.create(args);

            if (logger.isDebugEnabled()) {
                logger.debug("Created new Object='" + value + "'");
            }
        } else if (logger.isDebugEnabled()) {
            logger.debug("Using retrieved Object='" + value + "'");
        }

        return value;
    } finally {
        //switch back to the read lock
        this.writeLock.unlock();
    }
}

From source file:org.jasig.springframework.web.portlet.context.PortletContextLoader.java

/**
 * Initialize Spring's portlet application context for the given portlet context,
 * using the application context provided at construction time, or creating a new one
 * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
 * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
 * @param portletContext current portlet context
 * @return the new PortletApplicationContext
 * @see #CONTEXT_CLASS_PARAM//from ww w  .  j a v a  2 s.co  m
 * @see #CONFIG_LOCATION_PARAM
 */
public PortletApplicationContext initWebApplicationContext(PortletContext portletContext) {
    if (portletContext
            .getAttribute(PortletApplicationContext.ROOT_PORTLET_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
        throw new IllegalStateException(
                "Cannot initialize context because there is already a root portlet application context present - "
                        + "check whether you have multiple PortletContextLoader* definitions in your portlet.xml!");
    }

    Log logger = LogFactory.getLog(PortletContextLoader.class);
    portletContext.log("Initializing Spring root PortletApplicationContext");
    if (logger.isInfoEnabled()) {
        logger.info("Root portlet PortletApplicationContext: initialization started");
    }
    long startTime = System.nanoTime();

    try {
        // Store context in local instance variable, to guarantee that
        // it is available on PortletContext shutdown.
        if (this.context == null) {
            this.context = createPortletApplicationContext(portletContext);
        }
        if (this.context instanceof ConfigurablePortletApplicationContext) {
            configureAndRefreshPortletApplicationContext((ConfigurablePortletApplicationContext) this.context,
                    portletContext);
        }
        portletContext.setAttribute(PortletApplicationContext.ROOT_PORTLET_APPLICATION_CONTEXT_ATTRIBUTE,
                this.context);

        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        if (ccl == PortletContextLoader.class.getClassLoader()) {
            currentContext = this.context;
        } else if (ccl != null) {
            currentContextPerThread.put(ccl, this.context);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Published root PortletApplicationContext as PortletContext attribute with name ["
                    + PortletApplicationContext.ROOT_PORTLET_APPLICATION_CONTEXT_ATTRIBUTE + "]");
        }
        if (logger.isInfoEnabled()) {
            long elapsedTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
            logger.info("Root PortletApplicationContext: initialization completed in " + elapsedTime + " ms");
        }

        return this.context;
    } catch (RuntimeException ex) {
        logger.error("Portlet context initialization failed", ex);
        portletContext.setAttribute(PortletApplicationContext.ROOT_PORTLET_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    } catch (Error err) {
        logger.error("Portlet context initialization failed", err);
        portletContext.setAttribute(PortletApplicationContext.ROOT_PORTLET_APPLICATION_CONTEXT_ATTRIBUTE, err);
        throw err;
    }
}

From source file:org.jboss.netty.logging.CommonsLoggerTest.java

@Test
public void testIsDebugEnabled() {
    org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class);

    expect(mock.isDebugEnabled()).andReturn(true);
    replay(mock);/*  www  . j a v  a2s .c  o m*/

    InternalLogger logger = new CommonsLogger(mock, "foo");
    assertTrue(logger.isDebugEnabled());
    verify(mock);
}

From source file:org.jbpm.graph.def.ProcessDefinition.java

private static List loadModuleClasses(String resource) {
    Properties properties = ClassLoaderUtil.getProperties(resource);
    List moduleClasses = new ArrayList();

    Log log = LogFactory.getLog(ProcessDefinition.class);
    boolean debug = log.isDebugEnabled();

    for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) {
        String moduleClassName = (String) iter.next();
        try {//w ww  . ja va 2s  .  c  o m
            Class moduleClass = ClassLoaderUtil.classForName(moduleClassName);
            moduleClasses.add(moduleClass);
            if (debug)
                log.debug("loaded module " + moduleClassName);
        } catch (ClassNotFoundException e) {
            if (debug)
                log.debug("module class not found: " + moduleClassName, e);
        }
    }
    return moduleClasses;
}

From source file:org.jbpm.jpdl.par.ProcessArchive.java

private static List createParsers(String resource) {
    // read parsers resource
    InputStream resourceStream = ClassLoaderUtil.getStream(resource);
    Element parsersElement = XmlUtil.parseXmlInputStream(resourceStream).getDocumentElement();
    List parsers = new ArrayList();

    Log log = LogFactory.getLog(ProcessArchive.class);
    boolean debug = log.isDebugEnabled();

    for (Iterator iter = XmlUtil.elementIterator(parsersElement, "parser"); iter.hasNext();) {
        Element parserElement = (Element) iter.next();
        String parserClassName = parserElement.getAttribute("class");
        // load parser class
        try {//  w w  w. ja  v  a  2 s .  com
            Class parserClass = ClassLoaderUtil.classForName(parserClassName);
            // instantiate parser
            try {
                ProcessArchiveParser parser = (ProcessArchiveParser) parserClass.newInstance();
                if (parser instanceof ConfigurableParser) {
                    ((ConfigurableParser) parser).configure(parserElement);
                }
                parsers.add(parser);
                if (debug)
                    log.debug("loaded " + parserClass);
            } catch (InstantiationException e) {
                if (debug)
                    log.debug("failed to instantiate " + parserClass, e);
            } catch (IllegalAccessException e) {
                if (debug)
                    log.debug(ProcessArchive.class + " has no access to " + parserClass, e);
            }
        } catch (ClassNotFoundException e) {
            if (debug)
                log.debug("parser not found: " + parserClassName, e);
        }
    }
    return parsers;
}