org.osgi.service.event.Event Java Examples

The following examples show how to use org.osgi.service.event.Event. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InternalAdminEvent.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized TimeoutDeliver deliver(final Object caller,
                                           final Event event,
                                           final TrackedEventHandler handler)
{
  if (timeoutDeliver == null) {
    timeoutDeliver = new TimeoutDeliver();
    timeoutDeliver.start();
  }

  if (timeoutDeliver.isActive()) {
    timeoutDeliver.close();
    timeoutDeliver = new TimeoutDeliver();
    timeoutDeliver.start();
  }

  timeoutDeliver.deliver(caller, event, handler);
  return timeoutDeliver;
}
 
Example #2
Source File: SoapCollectorTest.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithBadUrl() throws Exception {
    EventAdminMock eventAdminMock = new EventAdminMock();

    SoapCollector collector = new SoapCollector();
    Dictionary<String, Object> config = new Hashtable<>();
    config.put("soap.request", "test");
    config.put("url", "http://foo.bar/foo");
    collector.dispatcher = eventAdminMock;
    collector.activate(config);
    collector.run();

    Assert.assertEquals(1, eventAdminMock.postedEvents.size());

    Event event = eventAdminMock.postedEvents.get(0);
    Assert.assertEquals("java.net.UnknownHostException: foo.bar", event.getProperty("error"));
}
 
Example #3
Source File: FileAppenderTest.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    // install decanter
    System.out.println(executeCommand("feature:repo-add decanter " + System.getProperty("decanter.version")));
    System.out.println(executeCommand("feature:install decanter-appender-file", new RolePrincipal("admin")));

    // send event
    EventAdmin eventAdmin = getOsgiService(EventAdmin.class);
    HashMap<String, String> data = new HashMap<>();
    data.put("foo", "bar");
    Event event = new Event("decanter/collect/test", data);
    eventAdmin.sendEvent(event);

    // read file
    File file = new File(System.getProperty("karaf.data"), "decanter");
    StringBuilder builder = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        builder.append(reader.readLine()).append("\n");
    }

    Assert.assertTrue(builder.toString().contains("foo=bar"));
}
 
Example #4
Source File: MqttAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Override
public void handleEvent(Event event) {
    if (EventFilter.match(event, config)) {
        try {
            MqttMessage message = new MqttMessage();
            String jsonSt = marshaller.marshal(event);
            message.setPayload(jsonSt.getBytes(StandardCharsets.UTF_8));
            client.publish(
                    getValue(config, TOPIC_PROPERTY, TOPIC_DEFAULT),
                    message);
        } catch (Exception e) {
            LOGGER.warn("Error sending to MQTT server " + client.getServerURI(), e);
            try {
                client.disconnect();
                client.connect();
            } catch (MqttException e1) {
                e1.printStackTrace();
            }
        }
    }
}
 
Example #5
Source File: TimescaleDbAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Override
public void handleEvent(Event event) {
    if (EventFilter.match(event, config)) {
        try (Connection connection = dataSource.getConnection()) {
            String tableName = getValue(config, TABLE_NAME_PROPERTY, TABLE_NAME_DEFAULT);
            String jsonSt = marshaller.marshal(event);
            String insertQuery = insertQueryTemplate.replaceAll("TABLENAME", tableName);
            Long timestamp = (Long) event.getProperty(EventConstants.TIMESTAMP);
            if (timestamp == null) {
                timestamp = System.currentTimeMillis();
            }
            try (PreparedStatement insertStatement = connection.prepareStatement(insertQuery)) {
                insertStatement.setLong(1, timestamp);
                insertStatement.setString(2, jsonSt);
                insertStatement.executeUpdate();
                LOGGER.trace("Data inserted into {} table", tableName);
            }
        } catch (Exception e) {
            LOGGER.error("Can't store in the database", e);
        }
    }
}
 
Example #6
Source File: JdbcAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Override
public void handleEvent(Event event) {
    if (EventFilter.match(event, config)) {
        try (Connection connection = dataSource.getConnection()) {
            String jsonSt = marshaller.marshal(event);
            String insertQuery = insertQueryTemplate.replaceAll("TABLENAME", getValue(config, TABLE_NAME_PROPERTY, TABLE_NAME_DEFAULT));
            Long timestamp = (Long) event.getProperty(EventConstants.TIMESTAMP);
            if (timestamp == null) {
                timestamp = System.currentTimeMillis();
            }
            try (PreparedStatement insertStatement = connection.prepareStatement(insertQuery)) {
                insertStatement.setLong(1, timestamp);
                insertStatement.setString(2, jsonSt);
                insertStatement.executeUpdate();
                LOGGER.trace("Data inserted into {} table", getValue(config, TABLE_NAME_PROPERTY, TABLE_NAME_DEFAULT));
            }
        } catch (Exception e) {
            LOGGER.error("Can't store in the database", e);
        }
    }
}
 
Example #7
Source File: RestAppenderTest.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Test
public void testPut() throws URISyntaxException {
    RestAppender appender = new RestAppender();
    Dictionary<String, Object> config= new Hashtable<>();
    config.put("uri", "http://localhost:9091/test/echo");
    config.put("request.method", "PUT");
    appender.marshaller = new JsonMarshaller();
    appender.activate(config);

    HashMap<String, Object> data = new HashMap<>();
    data.put("foo", "bar");
    Event event = new Event("put", data);

    appender.handleEvent(event);

    Assert.assertEquals(1, testService.putMessages.size());
    Assert.assertTrue(testService.putMessages.get(0).contains("\"foo\":\"bar\""));
}
 
Example #8
Source File: FuntionalTestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void publish() {
  int i=0;
  while(running) {
    /* a Hash table to store message in */
    Dictionary message = new Hashtable();
    /* put some properties into the messages */
    message.put("Synchronus message",new Integer(i));
    /* put the sender */
    message.put("FROM",this);

    if(publisherId>5) {
      /* send the message */
      eventAdmin.sendEvent(new Event(topicToPublish, message));
    } else {
      /* send the message */
      eventAdmin.postEvent(new Event(topicToPublish, message));
    }

    i++;

  }

}
 
Example #9
Source File: RedisCollector.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    Map<String, Object> data = new HashMap<>();
    data.put("type", "redis");
    String map = (config.get("map") != null) ? config.get("map").toString() : "Decanter";
    String keyPattern = (config.get("keyPattern") != null) ? config.get("keyPattern").toString() : "*";
    RMap rmap = redissonClient.getMap(map);
    for (Object key : rmap.keySet(keyPattern)) {
        data.put(key.toString(), rmap.get(key));
    }
    try {
        PropertiesPreparator.prepare(data, config);
    } catch (Exception e) {
        LOGGER.warn("Can't prepare data", e);
    }
    dispatcher.postEvent(new Event("decanter/collect/redis", data));
}
 
Example #10
Source File: SolrPageListener.java    From aem-solr-search with Apache License 2.0 6 votes vote down vote up
public void handleEvent(final Event event) {
		if (disabled) return;

		SolrClient solr = getSolrIndexClient();

		PageEvent pageEvent = PageEvent.fromEvent(event);
		if (pageEvent == null) return;

		ResourceResolver resourceResolver = null;
		try {
				resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
				for (Iterator<PageModification> iter = pageEvent.getModifications(); iter.hasNext(); )
						handlePageModification(iter.next(), solr, resourceResolver);
		} catch (Exception e) {
				LOG.error("Could not get ResourceResolver instance or handle page modification", e);
				return;
		} finally {
				if (resourceResolver != null && resourceResolver.isLive())
						resourceResolver.close();
		}
}
 
Example #11
Source File: CamelAppenderTest.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    CamelAppender appender = new CamelAppender();
    Hashtable<String, Object> config = new Hashtable<>();
    config.put(CamelAppender.DESTINATION_URI_KEY, "direct-vm:decanter");
    appender.open(config);

    Map<String, Object> data = new HashMap<>();
    data.put(EventConstants.TIMESTAMP, TIMESTAMP);
    data.put("testKey", "testValue");
    Event event = new Event(TOPIC, data);

    appender.handleEvent(event);

    Map<String, Object> expected = new HashMap<>();
    expected.put("event.topics", "decanter/collect/jmx");
    expected.putAll(data);
    MockEndpoint mock = (MockEndpoint) camelContext.getEndpoint("mock:assert");
    mock.expectedMessageCount(1);
    mock.message(0).body().isEqualTo(expected);
    mock.assertIsSatisfied();
}
 
Example #12
Source File: EventAdminImpl.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * send an event asynchronously.
 * 
 * @param event
 *            the Event.
 * 
 * @see org.osgi.service.event.EventAdmin#postEvent(org.osgi.service.event.Event)
 */
public void postEvent(final Event event) {
	if (security != null) {
		// TODO: cache permissions
		security.checkPermission(new TopicPermission(event.getTopic(),
				TopicPermission.PUBLISH));
	}

	final Subscription[] subscriptions = (Subscription[]) eventHandlerSubscriptions.values()
			.toArray(new Subscription[eventHandlerSubscriptions.size()]);
	final ArrayList handlers = new ArrayList(subscriptions.length);
	for (int i = 0; i < subscriptions.length; i++) {
		if (subscriptions[i].matches(event)) {
			handlers.add(subscriptions[i].getHandler());
		}
	}

	synchronized (eventQueue) {
		eventQueue.add(new QueueElement(event, (EventHandler[]) handlers
				.toArray(new EventHandler[handlers.size()])));
		eventQueue.notifyAll();
	}
}
 
Example #13
Source File: JEventTable.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Event getEventEntry(Event e, int delta) {
   int ix = model.getEntries().indexOf(e);
   if(ix != -1) {
     int i = ix + delta;
     if(i >= 0 && i < model.getEntries().size()) {
return (Event)model.getEntries().get(i);
     }
   }
   return null;
 }
 
Example #14
Source File: JEventPanel.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void copyToClipBoard() {
  StringBuffer sb = new StringBuffer();

  for(Event entry : model.getEntries()) {
    sb.append(entry.toString());
    sb.append("\n");
  }

  setClipboardContents(sb.toString());
}
 
Example #15
Source File: AggregateProcessorTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithoutOverwrite() throws Exception {
    MockDispatcher dispatcher = new MockDispatcher();
    AggregateProcessor aggregateProcessor = new AggregateProcessor();
    aggregateProcessor.setDispatcher(dispatcher);
    Hashtable<String, Object> configuration = new Hashtable<>();
    configuration.put("period", "2");
    aggregateProcessor.activate(configuration);

    HashMap<String, Object> data1 = new HashMap<>();
    data1.put("foo", "first");
    Event event1 = new Event("decanter/collect/foo", data1);
    aggregateProcessor.handleEvent(event1);

    HashMap<String, Object> data2 = new HashMap<>();
    data2.put("foo", "second");
    Event event2 = new Event("decanter/collect/foo", data2);
    aggregateProcessor.handleEvent(event2);

    Thread.sleep(4000);

    Assert.assertEquals(1, dispatcher.postedEvents.size());
    Assert.assertEquals("first", dispatcher.postedEvents.get(0).getProperty("0.foo"));
    Assert.assertEquals("second", dispatcher.postedEvents.get(0).getProperty("1.foo"));

    aggregateProcessor.deactivate();
}
 
Example #16
Source File: LogAppender.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
private void appendInternal(PaxLoggingEvent event) throws Exception {
    if (isIgnored(event.getLoggerName(), ignoredCategories)) {
        LOGGER.debug("{} logger is ignored by the log collector", event.getLoggerName());
        return;
    }

    LOGGER.debug("Publishing log event to the appenders ...");

    Map<String, Object> data = new HashMap<>();
    data.put("type", "log");

    data.put("timestamp", event.getTimeStamp());
    data.put("loggerClass", event.getFQNOfLoggerClass());
    data.put("loggerName", event.getLoggerName());
    data.put("threadName", event.getThreadName());
    data.put("message", event.getMessage());
    data.put("level", event.getLevel().toString());
    data.put("renderedMessage", event.getRenderedMessage());
    data.put("MDC", event.getProperties());
    if (locationDisabledCategories == null || !isIgnored(event.getLoggerName(), locationDisabledCategories)) {
        putLocation(data, event.getLocationInformation());
    }
    String[] throwableAr = event.getThrowableStrRep();
    if (throwableAr != null) {
        data.put("throwable", join(throwableAr));
    }

    PropertiesPreparator.prepare(data, properties);

    String loggerName = event.getLoggerName();
    if (loggerName == null || loggerName.isEmpty()) {
        loggerName = "default";
    }
    String topic = "decanter/collect/log/" + cleanLoggerName(loggerName);
    this.dispatcher.postEvent(new Event(topic, data));
}
 
Example #17
Source File: JEventEntryDetail.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void setEntry(Event e)
{
  String s = "";
  if (e != null) {
    s = Util.toHTML(e);
    // String s = Util.toString(e);
  }
  super.setText(s);
}
 
Example #18
Source File: PrometheusCollector.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        URLConnection connection = prometheusURL.openConnection();
        Map<String, Object> data = new HashMap<>();
        data.put("type", "prometheus");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.matches("# TYPE .* gauge")) {
                    line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    String[] split = line.split(" ");
                    if (split.length == 2) {
                        String property = split[0];
                        double value = Double.parseDouble(split[1]);
                        data.put(property, value);
                    }
                }
            }
        }
        PropertiesPreparator.prepare(data, properties);
        dispatcher.postEvent(new Event("decanter/collect/prometheus", data));
    } catch (Exception e) {
        LOGGER.warn("Can't get Prometheus metrics", e);
        e.printStackTrace();
    }
}
 
Example #19
Source File: EventFilterTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
private Event prepareTestEvent() {
    Map<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("other", "other");
    return new Event("test", map);
}
 
Example #20
Source File: FileAppender.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Override
public void handleEvent(Event event) {
    if (EventFilter.match(event, config)) {
        try {
            String marshalled = marshaller.marshal(event);
            writer.write(marshalled);
            writer.newLine();
            writer.flush();
        } catch (Exception e) {
            // nothing to do
        }
    }
}
 
Example #21
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Number getNumber(Event e, String key, Number def) {
  Object v = e.getProperty(key);
  if(!(v instanceof Number)) {
    return def;
  }

  return (Number)v;
}
 
Example #22
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static String toStringLogEntry(Event e) {
  String s = 
    "Time: "      + tf.format(new Date(getTime(e))) + "\n" + 
    "Level: "     + levelString(getLevel(e)) + "\n" + 
    "Message: "   + getMessage(e) + "\n";
  Throwable t = getException(e);
  if(t != null) {
    StringWriter w = new StringWriter();
    t.printStackTrace(new PrintWriter(w));
    s = s + w.toString();
  } 

  return s;
}
 
Example #23
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static String toString(Event e) {
  String topic = e.getTopic();
  if(topic.startsWith("org/osgi/service/log/LogEntry")) {
    return toStringLogEntry(e);
  } else {
    return e.toString();
  }    
}
 
Example #24
Source File: EventReaderDispatcher.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 */
public void handleEvent(final Event ev) {
  SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        model.logged(ev);
      }
    });
}
 
Example #25
Source File: JdbcCollector.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    LOGGER.debug("Karaf Decanter JDBC collector exectutes query {}", query);

    List<Map<String, Object>> dataRows = query();

    for (Map<String, Object> data : dataRows) {
        Event event = new Event(dispatcherTopic, data);
        dispatcher.postEvent(event);
    }
}
 
Example #26
Source File: JEventEntryDetail.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void showNext(int delta)
{
  if (entry != null && table != null) {
    Event e = table.getEventEntry(entry, delta);
    if (e != null) {
      setEntry(e);

      syncUI();
    }
  }
}
 
Example #27
Source File: CsvMarshaller.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
private String marshal(Event event) {
    StringBuilder builder = new StringBuilder();
    for (String propertyName : event.getPropertyNames()) {
        Object propertyValue = event.getProperty(propertyName);
        if (propertyValue != null) {
            builder.append(propertyName).append("=").append(propertyValue.toString()).append(separator);
        }
    }
    String result = builder.toString();
    result = result.substring(0, result.length() - 1);
    return result;
}
 
Example #28
Source File: DecanterTraceEventHandler.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Override
public void traceExchange(ProcessorDefinition<?> node, Processor target, TraceInterceptor traceInterceptor, Exchange exchange) throws Exception {
    HashMap<String, Object> data = new HashMap<>();
    data.put("type", "camelTracer");
    data.put("karafName", System.getProperty("karaf.name"));
    data.put("hostAddress", InetAddress.getLocalHost().getHostAddress());
    data.put("hostName", InetAddress.getLocalHost().getHostName());
    data.put("nodeId", node.getId());
    data.put("timestamp", System.currentTimeMillis());
    new DefaultExchangeExtender().extend(data, exchange);
    for (String property : exchange.getProperties().keySet()) {
        if (property.startsWith("decanter.")) {
            data.put(property.substring("decanter.".length()), exchange.getProperties().get(property));
        }
    }
    dextender.extend(data, exchange);
    if (extender != null)  {
        extender.extend(data, exchange);
    }
    for (String header : exchange.getIn().getHeaders().keySet()) {
        if (header.startsWith("decanter.")) {
            data.put(header.substring("decanter.".length()), exchange.getIn().getHeader(header));
        }
    }
    Event event = new Event("decanter/collect/camel/tracer", data);
    eventAdmin.postEvent(event);
}
 
Example #29
Source File: TimeoutDeliver.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public synchronized void deliver(final Object caller,
                                 final Event event,
                                 final TrackedEventHandler handler)
{
  if (isActive()) {
    throw new IllegalStateException("Delivery already in progress");
  }

  timedOut = false;
  delivered = false;
  this.caller = caller;
  this.event = event;
  this.handler = handler;
  notifyAll();
}
 
Example #30
Source File: EventDisplayer.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void handleEvent(final Event ev) {
  SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        addTopic(ev.getTopic());
        addKeyNames(ev.getPropertyNames());
      }
    });
}