Search in sources :

Example 41 with ServiceReference

use of org.osgi.framework.ServiceReference in project sling by apache.

the class SlingLogPanel method configureLogger.

/**
     * Configures the logger with the given pid. If the pid is empty a new logger configuration is created.
     *
     * @param pid      configuration pid of the logger
     * @param logLevel the log level to set
     * @param loggers  list of logger categories to set
     * @param logFile  log file (relative path is ok)
     * @param additive logger additivity
     * @throws IOException            when an existing configuration couldn't be updated or a configuration couldn't be created.
     * @throws ConfigurationException when mandatory parameters where not specified
     */
private void configureLogger(final String pid, final String logLevel, final String[] loggers, final String logFile, boolean additive) throws IOException, ConfigurationException {
    // try to get the configadmin service reference
    ServiceReference sr = this.bundleContext.getServiceReference(ConfigurationAdmin.class.getName());
    if (sr != null) {
        try {
            if (logLevel == null) {
                throw new ConfigurationException(LogConfigManager.LOG_LEVEL, "Log level has to be specified.");
            }
            if (loggers == null) {
                throw new ConfigurationException(LogConfigManager.LOG_LOGGERS, "Logger categories have to be specified.");
            }
            if (logFile == null) {
                throw new ConfigurationException(LogConfigManager.LOG_FILE, "LogFile name has to be specified.");
            }
            // try to get the configadmin
            final ConfigurationAdmin configAdmin = (ConfigurationAdmin) this.bundleContext.getService(sr);
            if (configAdmin != null) {
                Configuration config;
                if (pid == null || pid.length() == 0) {
                    config = configAdmin.createFactoryConfiguration(LogConfigManager.FACTORY_PID_CONFIGS);
                } else {
                    config = configAdmin.getConfiguration(pid);
                }
                if (config != null) {
                    Dictionary<String, Object> dict = new Hashtable<String, Object>();
                    dict.put(LogConfigManager.LOG_LEVEL, logLevel.toLowerCase());
                    dict.put(LogConfigManager.LOG_LOGGERS, loggers);
                    dict.put(LogConfigManager.LOG_FILE, logFile);
                    if (additive) {
                        dict.put(LogConfigManager.LOG_ADDITIV, "true");
                    } else {
                        dict.put(LogConfigManager.LOG_ADDITIV, "false");
                    }
                    config.update(dict);
                }
            }
        } finally {
            // release the configadmin reference
            this.bundleContext.ungetService(sr);
        }
    }
}
Also used : Configuration(org.osgi.service.cm.Configuration) ConfigurationException(org.apache.sling.commons.log.logback.internal.config.ConfigurationException) Hashtable(java.util.Hashtable) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) ServiceReference(org.osgi.framework.ServiceReference)

Example 42 with ServiceReference

use of org.osgi.framework.ServiceReference in project sling by apache.

the class LogSupport method logOut.

/**
     * Actually logs the given log entry to the logger for the bundle recorded
     * in the log entry.
     */
private void logOut(LogEntry logEntry) {
    // get the logger for the bundle
    Logger log = getLogger(logEntry.getBundle());
    if (logEntry.getLevel() > getLevel(log))
        // early Exit, this message will not be logged, don't do any work...
        return;
    final StringBuilder msg = new StringBuilder();
    ServiceReference sr = logEntry.getServiceReference();
    if (sr != null) {
        msg.append("Service [");
        if (sr.getProperty(Constants.SERVICE_PID) != null) {
            msg.append(sr.getProperty(Constants.SERVICE_PID)).append(',');
        } else if (sr.getProperty(COMPONENT_NAME) != null) {
            msg.append(sr.getProperty(COMPONENT_NAME)).append(',');
        } else if (sr.getProperty(Constants.SERVICE_DESCRIPTION) != null) {
            msg.append(sr.getProperty(Constants.SERVICE_DESCRIPTION)).append(',');
        }
        msg.append(sr.getProperty(Constants.SERVICE_ID)).append(", ").append(Arrays.toString((String[]) sr.getProperty(Constants.OBJECTCLASS))).append("] ");
    }
    if (logEntry.getMessage() != null) {
        msg.append(logEntry.getMessage());
    }
    Throwable exception = logEntry.getException();
    if (exception != null) {
        msg.append(" (").append(exception).append(')');
    }
    String message = msg.toString();
    switch(logEntry.getLevel()) {
        case LogService.LOG_DEBUG:
            log.debug(message, exception);
            break;
        case LogService.LOG_INFO:
            log.info(message, exception);
            break;
        case LogService.LOG_WARNING:
            log.warn(message, exception);
            break;
        case LogService.LOG_ERROR:
            log.error(message, exception);
            break;
        default:
            if (logEntry.getLevel() > LogService.LOG_DEBUG) {
                log.trace(message, exception);
            } else if (logEntry.getLevel() < LogService.LOG_ERROR) {
                log.error(message, exception);
            }
            break;
    }
}
Also used : Logger(org.slf4j.Logger) ServiceReference(org.osgi.framework.ServiceReference)

Example 43 with ServiceReference

use of org.osgi.framework.ServiceReference in project sling by apache.

the class LogSupportTest method testServiceEvent.

@Test
public void testServiceEvent() throws Exception {
    final Map<String, Object> props = new HashMap<String, Object>();
    props.put(Constants.OBJECTCLASS, new String[] { "some.class.Name" });
    props.put(Constants.SERVICE_ID, 999L);
    ServiceReference sr = Mockito.mock(ServiceReference.class);
    Mockito.when(sr.getBundle()).thenReturn(bundle);
    Mockito.when(sr.getProperty(Mockito.anyString())).then(new Answer<Object>() {

        public Object answer(InvocationOnMock invocation) throws Throwable {
            return props.get(invocation.getArguments()[0]);
        }
    });
    Mockito.when(sr.getPropertyKeys()).thenReturn(props.keySet().toArray(new String[] {}));
    ServiceEvent se = new ServiceEvent(ServiceEvent.REGISTERED, sr);
    logSupport.serviceChanged(se);
    Mockito.verify(testLogger).info("Service [999, [some.class.Name]] ServiceEvent REGISTERED", (Throwable) null);
}
Also used : HashMap(java.util.HashMap) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ServiceEvent(org.osgi.framework.ServiceEvent) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Example 44 with ServiceReference

use of org.osgi.framework.ServiceReference in project sling by apache.

the class LogSupportTest method testEarlyExit.

@Test
public void testEarlyExit() throws Exception {
    ServiceReference sr = Mockito.mock(ServiceReference.class);
    LogEntry le = new LogEntryImpl(bundle, sr, LogService.LOG_DEBUG, "test", null);
    logSupport.fireLogEvent(le);
    // The log message is on DEBUG level while the logger is set to INFO level
    // we don't want the actual log.info() call to be made, neither do we want
    // any preparatory work on the log message being made (which involves
    // inspecting the service reference).
    Mockito.verify(testLogger).isTraceEnabled();
    Mockito.verify(testLogger).isDebugEnabled();
    Mockito.verify(testLogger).isInfoEnabled();
    Mockito.verifyNoMoreInteractions(testLogger);
    Mockito.verifyZeroInteractions(sr);
}
Also used : LogEntry(org.osgi.service.log.LogEntry) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Example 45 with ServiceReference

use of org.osgi.framework.ServiceReference in project sling by apache.

the class AdapterManagerTest method testAdaptExtended2.

@org.junit.Test
public void testAdaptExtended2() throws Exception {
    am.activate(this.createComponentContext());
    final ServiceReference ref = createServiceReference();
    am.bindAdapterFactory(ref);
    final ServiceReference ref2 = createServiceReference2();
    am.bindAdapterFactory(ref2);
    TestSlingAdaptable data = new TestSlingAdaptable();
    Object adapter = am.getAdapter(data, ITestAdapter.class);
    assertNotNull(adapter);
    assertTrue(adapter instanceof ITestAdapter);
    adapter = am.getAdapter(data, TestAdapter.class);
    assertNull(adapter);
    TestSlingAdaptable2 data2 = new TestSlingAdaptable2();
    adapter = am.getAdapter(data2, ITestAdapter.class);
    assertNotNull(adapter);
    assertTrue(adapter instanceof ITestAdapter);
    adapter = am.getAdapter(data2, TestAdapter.class);
    assertNotNull(adapter);
    assertTrue(adapter instanceof TestAdapter);
}
Also used : ServiceReference(org.osgi.framework.ServiceReference)

Aggregations

ServiceReference (org.osgi.framework.ServiceReference)1687 Test (org.junit.Test)926 Properties (java.util.Properties)396 Architecture (org.apache.felix.ipojo.architecture.Architecture)263 CheckService (org.apache.felix.ipojo.runtime.core.test.services.CheckService)233 BundleContext (org.osgi.framework.BundleContext)229 InstanceDescription (org.apache.felix.ipojo.architecture.InstanceDescription)227 ComponentInstance (org.apache.felix.ipojo.ComponentInstance)215 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)182 ArrayList (java.util.ArrayList)167 Bundle (org.osgi.framework.Bundle)144 FooService (org.apache.felix.ipojo.runtime.core.services.FooService)141 Hashtable (java.util.Hashtable)124 IOException (java.io.IOException)107 CheckService (org.apache.felix.ipojo.runtime.core.services.CheckService)92 Dictionary (java.util.Dictionary)82 Configuration (org.osgi.service.cm.Configuration)74 CheckService (org.apache.felix.ipojo.handler.temporal.services.CheckService)70 FooService (org.apache.felix.ipojo.handler.temporal.services.FooService)70 CheckService (org.apache.felix.ipojo.handler.transaction.services.CheckService)65