org.osgi.service.event.EventConstants Java Examples

The following examples show how to use org.osgi.service.event.EventConstants. 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: TestJsonMarshaller.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Test
public void testInnerMap() throws Exception {
    Marshaller marshaller = new JsonMarshaller();

    Map<String, Object> map = new HashMap<>();
    map.put(EventConstants.TIMESTAMP, EXPECTED_TIMESTAMP);
    map.put("test", "test");
    Map<String, Object> inner = new HashMap<>();
    inner.put("other", "other");
    map.put("inner", inner);

    String jsonString = marshaller.marshal(new Event(EXPECTED_TOPIC, map));

    System.out.println(jsonString);

    JsonReader reader = Json.createReader(new StringReader(jsonString));
    JsonObject jsonObject = reader.readObject();
    Assert.assertEquals("Timestamp string", "2016-02-02T15:59:40,634Z", jsonObject.getString("@timestamp"));
    long ts = jsonObject.getJsonNumber(EventConstants.TIMESTAMP).longValue();
    Assert.assertEquals("timestamp long", EXPECTED_TIMESTAMP, ts);

    Assert.assertEquals("test", jsonObject.getString("test"));

    JsonObject innerObject = jsonObject.getJsonObject("inner");
    Assert.assertEquals("other", innerObject.getString("other"));
}
 
Example #2
Source File: Scenario5TestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void runTest() throws Throwable {
  asynchMessages = 0;
  synchMessages = 0;
  System.out
    .println("!!! TO RUN THIS TEST CORRECTLY TWO EVENTADMINS NEEDS TO RUN IN THE FRAMEWORK!!!");
  /* create the hashtable to put properties in */
  Dictionary props = new Hashtable();
  /* determine what topicType to use */
  /* put service.pid property in hashtable */
  props.put(EventConstants.EVENT_TOPIC, topicsToConsume);

  /* register the service */
  serviceRegistration = bundleContext.registerService(
                                                      EventHandler.class.getName(), this, props);

  assertNotNull(getName()
                + " service registration should not be null",
                serviceRegistration);

  if (serviceRegistration == null) {
    fail("Could not get Service Registration ");
  }
}
 
Example #3
Source File: TrackedEventHandler.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void updateEventFilter()
{
  String filterString = (String) sr.getProperty(EventConstants.EVENT_FILTER);
  try {
    if (filterString == null) {
      filter = null;
    } else {
      filter = FrameworkUtil.createFilter(filterString);
    }
  } catch (InvalidSyntaxException e) {
    filter = null;
    setBlacklist(true);
    /*
     * if (Activator.log.doError()) {
     * Activator.log.error("Failure when matching filter '" +filterString
     * +"' in handler with service.id " +sid, handlerSR, err); }
     */
  }
}
 
Example #4
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 #5
Source File: SendUserAdminEventJob.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Creates an event admin event for the user admin event object in
 * this job.
 */
Event getEvent() {
  String    path = getEventAdminPath();
  Hashtable dict = new Hashtable();

  put( dict, EventConstants.EVENT_TOPIC, path );
  put( dict, EventConstants.EVENT, event );
  put( dict, EventConstants.TIMESTAMP,
       new Long(System.currentTimeMillis()) );
  put( dict, "role", event.getRole() );
  put( dict, "role.name", event.getRole().getName() );
  put( dict, "role.type", new Integer(event.getRole().getType()) );
  put( dict, EventConstants.SERVICE, event.getServiceReference() );
  put( dict, EventConstants.SERVICE_ID,
       event.getServiceReference().getProperty(Constants.SERVICE_ID) );
  put( dict, EventConstants.SERVICE_OBJECTCLASS,
       event.getServiceReference().getProperty(Constants.OBJECTCLASS) );
  put( dict, EventConstants.SERVICE_PID,
       event.getServiceReference().getProperty(Constants.SERVICE_PID) );

  return new Event( path, (Dictionary) dict );
}
 
Example #6
Source File: TLAEditorActivator.java    From tlaplus with MIT License 6 votes vote down vote up
public void start(final BundleContext context) throws Exception {
	plugin = this;
	
    super.start(context);
    
	final Dictionary<String, Object> serviceRegistrationProperties = new Hashtable<>();
	serviceRegistrationProperties.put(EventConstants.EVENT_TOPIC, IThemeEngine.Events.THEME_CHANGED);
	
	themeChangeEventRegistration = context.registerService(EventHandler.class.getName(), new EventHandler() {
		@Override
		public void handleEvent(final Event event) {
			tlaCodeScanner = null;
			pcalCodeScanner = null;
			setDarkThemeStatus();
		}
	}, serviceRegistrationProperties);
}
 
Example #7
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 #8
Source File: EventAdminImpl.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * receive a <code>FrameworkEvent</code>.
 * 
 * @param fEvent
 *            the framework event.
 * @see org.osgi.framework.FrameworkListener#frameworkEvent(org.osgi.framework.FrameworkEvent)
 */
public void frameworkEvent(final FrameworkEvent fEvent) {
	Dictionary props = new Hashtable();
	props.put(EventConstants.EVENT, fEvent);
	props.put(EventConstants.TIMESTAMP,
			new Long(System.currentTimeMillis()));
	final Bundle bundle;
	if ((bundle = fEvent.getBundle()) != null) {
		props.put("bundle.id", new Long(bundle.getBundleId()));
		props.put(EventConstants.BUNDLE_SYMBOLICNAME, "null");
		props.put("bundle", bundle);
	}
	final Throwable throwable;
	if ((throwable = fEvent.getThrowable()) != null) {
		props.put(EventConstants.EXECPTION_CLASS, throwable.getClass()
				.getName());
		props.put(EventConstants.EXCEPTION_MESSAGE, throwable.getMessage());
		props.put(EventConstants.EXCEPTION, throwable);

	}
	int t = log2(fEvent.getType());
	String type = t < 5 ? FRAMEWORK_EVENT[t] : "UNDEFINED";
	Event event = new Event("org/osgi/framework/FrameworkEvent/" + type,
			props);
	postEvent(event);
}
 
Example #9
Source File: FuntionalTestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * run the test
 */
public void runTest() throws Throwable {
  /* create the hashtable to put properties in */
  Hashtable props = new Hashtable();
  /* put service.pid property in hashtable */
  props.put(EventConstants.EVENT_TOPIC, topicsToConsume);
  /* register the service */
  serviceRegistration = bundleContext.registerService
    (EventHandler.class.getName(), this, props);


  assertNotNull(getName()
                + " service registration should not be null",
                serviceRegistration);

  if (serviceRegistration == null) {
    fail("Could not get Service Registration ");
  }

}
 
Example #10
Source File: Scenario13TestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * run the test
 */
public void runTest() throws Throwable {
  /* create the hashtable to put properties in */
  Dictionary props = new Hashtable();
  /* put service.pid property in hashtable */
  props.put(EventConstants.EVENT_TOPIC, topicsToConsume);
  /* register the service */
  serviceRegistration = bundleContext.registerService
    (EventHandler.class.getName(), this, props);

  assertNotNull(getName()
                + " service registration should not be null",
                serviceRegistration);

  if (serviceRegistration == null) {
    fail("Could not get Service Registration ");
  }

}
 
Example #11
Source File: Scenario1TestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * run the test
 */
public void runTest() throws Throwable {
  numOfasynchMessages=0;
  numOfsynchMessages=0;
  synchMessageExpectedNumber=0;
  asynchMessageExpectedNumber=0;

  /* create the hashtable to put properties in */
  Dictionary props = new Hashtable();
  /* put service.pid property in hashtable */
  props.put(EventConstants.EVENT_TOPIC, topicsToConsume);
  /* register the service */
  serviceRegistration = bundleContext
    .registerService(EventHandler.class.getName(), this, props);

  assertNotNull(getName()
                + " service registration should not be null",
                serviceRegistration);

  if (serviceRegistration == null) {
    fail("Could not get Service Registration ");
  }

}
 
Example #12
Source File: Scenario2TestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void runTest() throws Throwable {
  asynchMessages=0;
  synchMessages=0;
  /* create the hashtable to put properties in */
  Dictionary props = new Hashtable();
  /* put service.pid property in hashtable */
  props.put(EventConstants.EVENT_TOPIC, topicsToConsume);
  /* register the service */
  serviceRegistration = bundleContext.registerService(
                                                      EventHandler.class.getName(), this, props);

  assertNotNull(getName()
                + " service registration should not be null",
                serviceRegistration);

  if (serviceRegistration == null) {
    fail("Could not get Service Registration ");
  }
}
 
Example #13
Source File: Scenario7TestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void runTest() throws Throwable {
  asynchMessages = 0;
  synchMessages = 0;
  /* create the hashtable to put properties in */
  Dictionary props = new Hashtable();
  /* determine what topicType to use */
  /* put service.pid property in hashtable */
  props.put(EventConstants.EVENT_TOPIC, topicsToConsume);

  /* register the service */
  serviceRegistration = bundleContext.registerService(
                                                      EventHandler.class.getName(), this, props);

  assertNotNull(getName()
                + " service registration should not be null",
                serviceRegistration);

  if (serviceRegistration == null) {
    fail("Could not get Service Registration ");
  }
}
 
Example #14
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 #15
Source File: Scenario7TestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void runTest() throws Throwable {
  asynchMessages = 0;
  synchMessages = 0;
  /* create the hashtable to put properties in */
  Dictionary props = new Hashtable();
  /* determine what topicType to use */
  /* put service.pid property in hashtable */
  props.put(EventConstants.EVENT_TOPIC, topicsToConsume);

  /* register the service */
  serviceRegistration = bundleContext.registerService(
                                                      EventHandler.class.getName(), this, props);

  assertNotNull(getName()
                + " service registration should not be null",
                serviceRegistration);

  if (serviceRegistration == null) {
    fail("Could not get Service Registration ");
  }
}
 
Example #16
Source File: JmsCollector.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Activate
public void activate(ComponentContext componentContext) throws Exception {
    properties = componentContext.getProperties();
    username = getProperty(properties, "username", null);
    password = getProperty(properties, "password", null);
    destinationName = getProperty(properties, "destination.name", "decanter");
    destinationType = getProperty(properties, "destination.type", "queue");
    dispatcherTopic = getProperty(properties, EventConstants.EVENT_TOPIC, "decanter/collect/jms/decanter");

    connection = createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = createDestination(session);
    MessageConsumer consumer = session.createConsumer(destination);
    consumer.setMessageListener(new DecanterMessageListener(dispatcher, unmarshaller));
    connection.start();
}
 
Example #17
Source File: Scenario4TestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void runTest() throws Throwable {
  asynchMessages=0;
  synchMessages=0;
  unidentMessages=0;
  /* create the hashtable to put properties in */
  Dictionary props = new Hashtable();
  /* put service.pid property in hashtable */
  props.put(EventConstants.EVENT_TOPIC, topicsToConsume);
  /*if the filter to consume isn't null */
  if (filterToConsume != null){
    /* put service.pid property in hashtable */
    props.put(EventConstants.EVENT_FILTER, filterToConsume);
  }

  /* register the service */
  serviceRegistration = bundleContext.registerService(
                                                      EventHandler.class.getName(), this, props);

  assertNotNull(getName()
                + " service registration should not be null",
                serviceRegistration);

  if (serviceRegistration == null) {
    fail("Could not get Service Registration ");
  }
}
 
Example #18
Source File: Scenario14TestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * run the test
 */
public void runTest() throws Throwable {
  /* create the hashtable to put properties in */
  Dictionary props = new Hashtable();
  /* put service.pid property in hashtable */
  props.put(EventConstants.EVENT_TOPIC, topicsToConsume);
  /* register the service */
  serviceRegistration = bundleContext.registerService
    (EventHandler.class.getName(), this, props);

  assertNotNull(getName() +" service registration should not be null",
                serviceRegistration);

  if (serviceRegistration == null) {
    fail("Could not get Service Registration ");
  }

}
 
Example #19
Source File: TestCsvMarshaller.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Test
public void testInnerMap() throws Exception {
    Marshaller marshaller = new CsvMarshaller();

    Map<String, Object> map = new HashMap<>();
    map.put(EventConstants.TIMESTAMP, EXPECTED_TIMESTAMP);
    map.put("test", "test");
    Map<String, Object> inner = new HashMap<>();
    inner.put("other", "other");
    map.put("inner", inner);

    String marshalled = marshaller.marshal(new Event(EXPECTED_TOPIC, map));

    System.out.println(marshalled);

    Assert.assertEquals("test=test,inner={other=other},timestamp=1454428780634,event.topics=testTopic", marshalled);
}
 
Example #20
Source File: TestJsonMarshaller.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Test
public void testMarshal() throws Exception {
    Marshaller marshaller = new JsonMarshaller();

    Map<String, Object> map = new HashMap<>();
    map.put(EventConstants.TIMESTAMP, EXPECTED_TIMESTAMP);
    map.put("c", "d");
    String jsonSt = marshaller.marshal(new Event(EXPECTED_TOPIC, map));
    System.out.println(jsonSt);
    JsonReader reader = Json.createReader(new StringReader(jsonSt));
    JsonObject jsonO = reader.readObject();
    Assert.assertEquals("Timestamp string", "2016-02-02T15:59:40,634Z",jsonO.getString("@timestamp"));
    long ts = jsonO.getJsonNumber(EventConstants.TIMESTAMP).longValue();
    Assert.assertEquals("timestamp long", EXPECTED_TIMESTAMP, ts);
    Assert.assertEquals("Topic", EXPECTED_TOPIC, jsonO.getString(EventConstants.EVENT_TOPIC.replace('.', '_')));
}
 
Example #21
Source File: Scenario12TestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void runTest() throws Throwable {
    msgs = new Hashtable();
    msgs.put(ERROR_MSG, Boolean.FALSE);
    msgs.put(WARN_MSG, Boolean.FALSE);
    msgs.put(INFO_MSG, Boolean.FALSE);
    msgs.put(DEBUG_MSG, Boolean.FALSE);
    /* create the hashtable to put properties in */
    Hashtable props = new Hashtable();
    /* put service.pid property in hashtable */
    props.put(EventConstants.EVENT_TOPIC, topicsToConsume);
    /* register the service */
    serviceRegistration = bundleContext.registerService(EventHandler.class
            .getName(), this, props);
    /* assert not null */
    assertNotNull(displayName + " Can't get service", serviceRegistration);
}
 
Example #22
Source File: SystemCollectorTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    // configure system collector
    File file = new File(System.getProperty("karaf.etc"), "org.apache.karaf.decanter.collector.system.cfg");
    try (PrintWriter writer = new PrintWriter(new FileWriter(file))) {
        writer.write("command.df=df -h");
    }

    // create event handler
    List<Event> received = new ArrayList();
    EventHandler eventHandler = new EventHandler() {
        @Override
        public void handleEvent(Event event) {
            received.add(event);
        }
    };
    Hashtable serviceProperties = new Hashtable();
    serviceProperties.put(EventConstants.EVENT_TOPIC, "decanter/collect/*");
    bundleContext.registerService(EventHandler.class, eventHandler, serviceProperties);

    // install decanter
    System.out.println(executeCommand("feature:repo-add decanter " + System.getProperty("decanter.version")));
    System.out.println(executeCommand("feature:install decanter-collector-system", new RolePrincipal("admin")));

    System.out.println("Waiting scheduler ...");
    while (received.size() == 0) {
        Thread.sleep(500);
    }

    Assert.assertTrue(received.size() >= 1);

    Assert.assertEquals("decanter/collect/system/command_df", received.get(0).getTopic());
    Assert.assertNotNull(received.get(0).getProperty("command.df"));
    Assert.assertEquals("system", received.get(0).getProperty("type"));
    Assert.assertEquals("root", received.get(0).getProperty("karafName"));
}
 
Example #23
Source File: SocketCollectorTest.java    From karaf-decanter with Apache License 2.0 5 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-collector-socket", new RolePrincipal("admin")));

    Thread.sleep(2000);

    // create event handler
    List<Event> received = new ArrayList();
    EventHandler eventHandler = new EventHandler() {
        @Override
        public void handleEvent(Event event) {
            received.add(event);
        }
    };
    Hashtable serviceProperties = new Hashtable();
    serviceProperties.put(EventConstants.EVENT_TOPIC, "decanter/collect/*");
    bundleContext.registerService(EventHandler.class, eventHandler, serviceProperties);

    Socket socket = new Socket("localhost", 34343);
    try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()))) {
        writer.write("{\"test\":\"test\"}");
    }

    while (received.size() == 0) {
        Thread.sleep(500);
    }

    Assert.assertEquals(1, received.size());

    Assert.assertEquals("decanter/collect/socket", received.get(0).getTopic());
    Assert.assertEquals("test", received.get(0).getProperty("test"));
    Assert.assertEquals("root", received.get(0).getProperty("karafName"));
    Assert.assertEquals("socket", received.get(0).getProperty("type"));
}
 
Example #24
Source File: CassandraAppenderTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Marshaller marshaller = new JsonMarshaller();
    CassandraAppender appender = new CassandraAppender();
    Dictionary<String, Object> config = new Hashtable<>();
    config.put(CassandraAppender.CASSANDRA_PORT_PROPERTY, CASSANDRA_HOST);
    config.put(CassandraAppender.CASSANDRA_PORT_PROPERTY, CASSANDRA_PORT);
    config.put(CassandraAppender.KEYSPACE_PROPERTY, KEYSPACE);
    config.put(CassandraAppender.TABLE_PROPERTY, TABLE_NAME);
    appender.marshaller = marshaller;
    appender.activate(config);
    
    Map<String, Object> properties = new HashMap<>();
    properties.put(EventConstants.TIMESTAMP, TIMESTAMP);
    Event event = new Event(TOPIC, properties);
    
    appender.handleEvent(event);
    appender.deactivate();

    CqlSession session = getSession();

    ResultSet execute = session.execute("SELECT * FROM "+ KEYSPACE+"."+TABLE_NAME+";");
    List<Row> all = execute.all();
    Assert.assertEquals(1, all.size());
    assertThat(all, not(nullValue()));
    
    assertThat(all.get(0).getInstant("timeStamp").toEpochMilli(), is(TIMESTAMP));
    
    session.close();
}
 
Example #25
Source File: EventAdminImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * receive a <code>BundleEvent</code>.
 * 
 * @param bEvent
 *            the bundle event.
 * @see org.osgi.framework.BundleListener#bundleChanged(org.osgi.framework.BundleEvent)
 */
public void bundleChanged(final BundleEvent bEvent) {
	Dictionary props = new Hashtable();
	props.put(EventConstants.TIMESTAMP,
			new Long(System.currentTimeMillis()));
	Bundle bundle = bEvent.getBundle();
	props.put(EventConstants.EVENT, bEvent);
	props.put("bundle.id", new Long(bundle.getBundleId()));
	props.put("bundle", bundle);
	int t = log2(bEvent.getType());
	String type = t < 7 ? BUNDLE_EVENT[t] : "UNDEFINED";
	Event event = new Event("org/osgi/framework/BundleEvent/" + type, props);
	postEvent(event);
}
 
Example #26
Source File: TestJdbcAppender.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws SQLException {
    System.setProperty("derby.stream.error.file", "target/derby.log");
    Marshaller marshaller = new JsonMarshaller();
    EmbeddedDataSource dataSource = new EmbeddedDataSource();
    dataSource.setDatabaseName("target/testDB");
    dataSource.setCreateDatabase("create");
    
    deleteTable(dataSource);
    
    JdbcAppender appender = new JdbcAppender();
    appender.marshaller = marshaller;
    appender.dataSource = dataSource;
    Dictionary<String, Object> config = new Hashtable<>();
    config.put("dialect", "derby");
    appender.open(config);
    
    Map<String, Object> data = new HashMap<>();
    data.put(EventConstants.TIMESTAMP, TIMESTAMP);
    Event event = new Event(TOPIC, data);
    appender.handleEvent(event);

    try (Connection con = dataSource.getConnection(); Statement statement = con.createStatement();) {
        ResultSet res = statement.executeQuery("select timestamp, content from " + TABLE_NAME);
        res.next();
        long dbTimeStamp = res.getLong(1);
        String json = res.getString(2);
        JsonReader reader = Json.createReader(new StringReader(json));
        JsonObject jsonO = reader.readObject();
        Assert.assertEquals("Timestamp db", TIMESTAMP, dbTimeStamp);
        Assert.assertEquals("Timestamp string", "2016-02-02T15:59:40,634Z",jsonO.getString("@timestamp"));
        Assert.assertEquals("timestamp long", TIMESTAMP, jsonO.getJsonNumber(EventConstants.TIMESTAMP).longValue());
        Assert.assertEquals("Topic", TOPIC, jsonO.getString(EventConstants.EVENT_TOPIC.replace('.','_')));
        Assert.assertFalse(res.next());
    }
}
 
Example #27
Source File: JdbcCollector.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
public void open(Dictionary<String, Object> config)  throws Exception {
    query = getProperty(config, "query", null);
    if (query == null) {
        throw new IllegalStateException("Query is mandatory");
    }
    dispatcherTopic = getProperty(config, EventConstants.EVENT_TOPIC, "decanter/collect/jdbc");

    connection = dataSource.getConnection();
    preparedStatement = connection.prepareStatement(query);
}
 
Example #28
Source File: SocketCollector.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
public void activate(Dictionary<String, Object> properties) throws IOException {
    this.properties = properties;
    int port = Integer.parseInt(getProperty(this.properties, "port", "34343"));
    int workers = Integer.parseInt(getProperty(this.properties, "workers", "10"));

    this.protocol = Protocol.valueOf(getProperty(this.properties, "protocol", "tcp").toUpperCase());
    // force TCP protocol if value not in Enum
    if (this.protocol == null) {
        this.protocol = Protocol.TCP;
    }

    eventAdminTopic = getProperty(this.properties, EventConstants.EVENT_TOPIC, "decanter/collect/socket");

    switch (protocol) {
        case TCP:
            this.serverSocket = new ServerSocket(port);
            break;
        case UDP:
            this.datagramSocket = new DatagramSocket(port);
            break;
    }

    // adding 1 for serverSocket handling
    this.executor = Executors.newFixedThreadPool(workers + 1);
    this.executor.execute(this);
    this.open = true;
}
 
Example #29
Source File: ConsoleTrigger.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method is used to set a callback object to the RuleEngine
 *
 * @param ruleCallback a callback object to the RuleEngine.
 */
@Override
public void setCallback(final ModuleHandlerCallback callback) {
    super.setCallback(callback);
    final Dictionary<String, Object> registrationProperties = new Hashtable<String, Object>();
    registrationProperties.put(EventConstants.EVENT_TOPIC, eventTopic);
    registration = context.registerService(EventHandler.class, this, registrationProperties);
}
 
Example #30
Source File: LogCollectorTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    // install log collector
    System.out.println(executeCommand("feature:repo-add decanter " + System.getProperty("decanter.version")));
    System.out.println(executeCommand("feature:install decanter-collector-log", new RolePrincipal("admin")));

    List<Event> received = new ArrayList<>();
    // plugin event handler
    EventHandler eventHandler = new EventHandler() {
        @Override
        public void handleEvent(Event event) {
            received.add(event);
        }
    };
    Hashtable serviceProperties = new Hashtable();
    serviceProperties.put(EventConstants.EVENT_TOPIC, "decanter/collect/*");
    bundleContext.registerService(EventHandler.class, eventHandler, serviceProperties);

    LOGGER.info("This is a test");

    Assert.assertEquals(1, received.size());
    Assert.assertEquals("decanter/collect/log/org_apache_karaf_decanter_itests_collector_LogCollectorTest", received.get(0).getTopic());
    Assert.assertEquals("INFO", received.get(0).getProperty("level"));
    Assert.assertEquals("log", received.get(0).getProperty("type"));
    Assert.assertEquals("This is a test", received.get(0).getProperty("message"));
    Assert.assertEquals("root", received.get(0).getProperty("karafName"));
    Assert.assertEquals("org.apache.karaf.decanter.itests.collector.LogCollectorTest", received.get(0).getProperty("loggerName"));
    Assert.assertEquals("org.ops4j.pax.logging.slf4j.Slf4jLogger", received.get(0).getProperty("loggerClass"));
    Assert.assertEquals("This is a test", received.get(0).getProperty("renderedMessage"));

}