Java Code Examples for org.osgi.service.event.Event#getProperty()

The following examples show how to use org.osgi.service.event.Event#getProperty() . 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: 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 2
Source File: AbstractEventSubscriber.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void handleEvent(Event event) {
    String itemName = (String) event.getProperty("item");

    String topic = event.getTopic();
    String[] topicParts = topic.split(TOPIC_SEPERATOR);

    if (!(topicParts.length > 2) || !topicParts[0].equals(TOPIC_PREFIX)) {
        return; // we have received an event with an invalid topic
    }
    String operation = topicParts[1];

    if (operation.equals(EventType.UPDATE.toString())) {
        State newState = (State) event.getProperty("state");
        if (newState != null) {
            receiveUpdate(itemName, newState);
        }
    }
    if (operation.equals(EventType.COMMAND.toString())) {
        Command command = (Command) event.getProperty("command");
        if (command != null) {
            receiveCommand(itemName, command);
        }
    }
}
 
Example 3
Source File: EntityChangeEventListener.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void handleEvent(Event event){
	EntityWithId entity = (EntityWithId) event.getProperty(EntityWithId.class.getName());
	synchronized (listenerMap) {
		List<WeakReference<AbstractIdModelAdapter<?>>> listeners = getListenersFor(entity);
		
		Iterator<WeakReference<AbstractIdModelAdapter<?>>> iter = listeners.iterator();
		while (iter.hasNext()) {
			WeakReference<AbstractIdModelAdapter<?>> reference = iter.next();
			if (reference != null) {
				AbstractIdModelAdapter<?> adapter = reference.get();
				if (adapter != null) {
					adapter.setEntity(entity, false);
				} else {
					iter.remove();
				}
			}
		}
	}
}
 
Example 4
Source File: UpgradeTaskProvider.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void handleEvent ( final Event event )
{
    logger.debug ( "Received event - {}", event.getTopic () );

    final String topic = event.getTopic ();
    final Object op = event.getProperty ( "operation" );

    if ( topic.startsWith ( "drone/channel/" ) )
    {
        if ( "remove".equals ( op ) || "refresh".equals ( op ) )
        {
            refresh ();
        }
    }
}
 
Example 5
Source File: InitialPerspectiveStorageAddon.java    From codeexamples-eclipse with Eclipse Public License 1.0 6 votes vote down vote up
@Inject
@Optional
public void selectedElement(@EventTopic(UIEvents.ElementContainer.TOPIC_SELECTEDELEMENT) Event event, EModelService modelService) {
	if (!UIEvents.isSET(event)) {
		return;
	}

	Object newlySelectedPerspective = event.getProperty(EventTags.NEW_VALUE);
	if (newlySelectedPerspective instanceof MPerspective) {
		MPerspective perspectiveToBeCloned = (MPerspective) newlySelectedPerspective;

		MWindow topLevelWindow = modelService.getTopLevelWindowFor(perspectiveToBeCloned);
		
		// try to find already existing snippet
		if (null == modelService.findSnippet(topLevelWindow, perspectiveToBeCloned.getElementId())) {
			// clone perspective in case there is no snippet yet
			modelService.cloneElement(perspectiveToBeCloned, topLevelWindow);
		}
	}
}
 
Example 6
Source File: EventCollector.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Override
public void handleEvent(Event event) {
    String topic = event.getTopic();
    Map<String, Object> data = new HashMap<>();
    data.put("type", "eventadmin");

    for (String property : event.getPropertyNames()) {
        if (property.equals("type")) {
            if (event.getProperty(property) != null) {
                data.put("eventType", (event.getProperty(property) != null) ? event.getProperty(property).toString() : null);
            } else {
                data.put("eventType", "eventadmin");
            }
        } else if (property.equalsIgnoreCase("subject")) {
            if (event.getProperty(property) != null && (event.getProperty(property) instanceof Subject)) {
                data.put(property, convertSubject((Subject) event.getProperty(property)));
            }
        } else {
            data.put(property, event.getProperty(property));
        }
    }

    try {
        PropertiesPreparator.prepare(data, properties);
    } catch (Exception e) {
        // nothing to do
    }

    Event bridge = new Event("decanter/collect/eventadmin/" + topic, data);
    dispatcher.sendEvent(bridge);
}
 
Example 7
Source File: PCalTranslateAutomaticallyHandler.java    From tlaplus with MIT License 5 votes vote down vote up
@Override
public void handleEvent(final Event event) {
	try {
		final TLAEditor editor = (TLAEditor) event.getProperty(IEventBroker.DATA);
		translate(editor, editor.getSite().getShell(), false);
	} catch (InvocationTargetException | InterruptedException e) {
		throw new RuntimeException(e);
	}
}
 
Example 8
Source File: InfluxDbAppender.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)) {
        String type = "decanter";
        if (event.getProperty("type") != null) {
            type = (String) event.getProperty("type");
        }

        Map<String, Object> eventFields = new HashMap<>();
        Map<String, String> eventTags = new HashMap<>();
        eventTags.putAll(globalTags);

        for (String propertyName : event.getPropertyNames()) {
            Object propertyValue = event.getProperty(propertyName);
            if (propertyValue != null) {
                if (propertyValue instanceof Number || propertyValue instanceof Boolean) {
                    eventFields.put(propertyName, propertyValue);
                }
                else if(propertyValue instanceof String){
                    eventTags.put(propertyName, (String) propertyValue);
                }
            }
        }
        Point point = Point.measurement(type).fields(eventFields).tag(eventTags).build();
        influxDB.write(point);
    }
}
 
Example 9
Source File: RawMarshaller.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 (propertyName != null && propertyValue != null) {
            builder.append(propertyName).append("=").append(propertyValue.toString()).append("\n");
        }
    }
    return builder.toString();
}
 
Example 10
Source File: ContextService.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void handleEvent(Event event){
	Object property = event.getProperty("org.eclipse.e4.data");
	if (property instanceof MApplication) {
		MApplication application = (MApplication) property;
		applicationContext = application.getContext();
		if (getRootContext() != null) {
			((Context) getRootContext()).setEclipseContext(applicationContext);
		}
	}
	// set initial values for injection
	applicationContext.set(IUser.class, getRootContext().getTyped(IUser.class).orElse(null));
}
 
Example 11
Source File: QuitHandlerAddon.java    From offspring with MIT License 5 votes vote down vote up
@Override
public void handleEvent(final Event inEvent) {
  if (!UIEvents.isSET(inEvent)) {
    return;
  }
  final Object lElement = inEvent.getProperty(UIEvents.EventTags.ELEMENT);
  if (!(lElement instanceof MWindow)) {
    return;
  }
  final MWindow lWindow = (MWindow) lElement;
  if ("com.dgex.offspring.application.mainwindow".equals(lWindow
      .getElementId())) {
    logger.trace(UIEvents.Context.TOPIC_CONTEXT);
    if (lWindow.equals(inEvent.getProperty("ChangedElement"))
        && lWindow.getContext() != null) {
      lWindow.getContext().runAndTrack(new RunAndTrack() {

        @Override
        public boolean changed(final IEclipseContext inContext) {
          final Object lHandler = inContext.get(IWindowCloseHandler.class);
          if (!quitHandler.equals(lHandler)) {
            inContext.set(IWindowCloseHandler.class, quitHandler);
          }
          return true;
        }
      });
    }
  }
}
 
Example 12
Source File: OSGiEventDistributorTest.java    From camunda-bpm-platform-osgi with Apache License 2.0 5 votes vote down vote up
@Test
public void notifyTask() {
  String processDefinitionId = "123";
  String currActivityId = "Act1234";
  String processInstanceId = "Inst1234";
  String executionId = "Exe4711";
  String taskId = "Task42";
  String taskDefinitionKey = "TaskDef";
  String transitionId = "Trans1";
  DelegateTask task = mock(DelegateTask.class);
  when(task.getProcessDefinitionId()).thenReturn(processDefinitionId);
  when(task.getProcessInstanceId()).thenReturn(processInstanceId);
  when(task.getExecutionId()).thenReturn(executionId);
  when(task.getId()).thenReturn(taskId);
  when(task.getTaskDefinitionKey()).thenReturn(taskDefinitionKey);
  when(task.getEventName()).thenReturn(TaskListener.EVENTNAME_CREATE);
  DelegateExecution execution = mock(DelegateExecution.class);
  when(execution.getCurrentActivityId()).thenReturn(currActivityId);
  when(execution.getCurrentTransitionId()).thenReturn(transitionId);
  when(task.getExecution()).thenReturn(execution);
  EventAdmin eventAdminMock = mock(EventAdmin.class);
  ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
  OSGiEventDistributor distributor = new OSGiEventDistributor(eventAdminMock);
  distributor.notify(task);

  verify(eventAdminMock).postEvent(eventCaptor.capture());
  Event event = eventCaptor.getValue();
  assertThat(event.getTopic(), is(Topics.TASK_EVENT_TOPIC));
  assertThat((String) event.getProperty(BusinessProcessEventProperties.ACTIVITY_ID), is(currActivityId));
  assertThat((String) event.getProperty(BusinessProcessEventProperties.EXECUTION_ID), is(executionId));
  assertThat((String) event.getProperty(BusinessProcessEventProperties.PROCESS_DEFINITION), is(processDefinitionId));
  assertThat((String) event.getProperty(BusinessProcessEventProperties.PROCESS_INSTANCE_ID), is(processInstanceId));
  assertThat((String) event.getProperty(BusinessProcessEventProperties.TASK_DEFINITION_KEY), is(taskDefinitionKey));
  assertThat((String) event.getProperty(BusinessProcessEventProperties.TASK_ID), is(taskId));
  String timestamp = (String) event.getProperty(BusinessProcessEventProperties.TIMESTAMP);
  assertThat(new Date(Long.parseLong(timestamp)), is(beforeOrEqual(new Date())));
  assertThat((String) event.getProperty(BusinessProcessEventProperties.TRANSITION_ID), is(transitionId));
  assertThat((String) event.getProperty(BusinessProcessEventProperties.TYPE), is(TaskListener.EVENTNAME_CREATE));
}
 
Example 13
Source File: FuntionalTestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * This method takes events from the event admin service.
 */
public void handleEvent(Event event) {
  System.out.println("****************************  RECEVIED "
                     +"***********************************");
  String from = (String)event.getProperty("FROM");
  System.err.println(getName() + " recived an event from:" + from
                     +" with topic:"+ event.getTopic());
}
 
Example 14
Source File: Logger.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Override
public void handleEvent(Event event) {
    boolean backToNormal = false;
    if (event.getProperty("alertBackToNormal") != null) {
        backToNormal = (boolean) event.getProperty("alertBackToNormal");
    }
    if (event.getProperty("alertLevel") != null && ((String) event.getProperty("alertLevel")).equalsIgnoreCase("error")) {
        if (backToNormal) {
            LOGGER.info("DECANTER ALERT BACK TO NORMAL: condition {} recover", event.getProperty("alertPattern"));
            LOGGER.info(renderEvent(event));
        } else {
            LOGGER.error("DECANTER ALERT: condition {}", event.getProperty("alertPattern"));
            LOGGER.error(renderEvent(event));
        }
    } else if (event.getProperty("alertLevel") != null && ((String) event.getProperty("alertLevel")).equalsIgnoreCase("warn")) {
        if (backToNormal) {
            LOGGER.info("DECANTER ALERT BACK TO NORMAL: condition {} recover", event.getProperty("alertPattern"));
            LOGGER.info(renderEvent(event));
        } else {
            LOGGER.warn("DECANTER ALERT: condition {}", event.getProperty("alertPattern"));
            LOGGER.warn(renderEvent(event));
        }
    } else {
        if (backToNormal) {
            LOGGER.info("DECANTER ALERT BACK TO NORMAL: condition {} recover", event.getProperty("alertPattern"));
            LOGGER.info(renderEvent(event));
        } else {
            LOGGER.info("DECANTER ALERT ({}): condition {}", event.getProperty("alertLevel"), event.getProperty("alertPattern"));
            LOGGER.info(renderEvent(event));
        }
    }
}
 
Example 15
Source File: EventFilter.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
public static boolean match(Event event, Dictionary<String, Object> config) {
    if (config == null) {
        return true;
    }

    String nameExcludeRegex = (config.get(PROPERTY_NAME_EXCLUDE_CONFIG) != null) ? (String) config.get(PROPERTY_NAME_EXCLUDE_CONFIG) : null;
    String nameIncludeRegex = (config.get(PROPERTY_NAME_INCLUDE_CONFIG) != null) ? (String) config.get(PROPERTY_NAME_INCLUDE_CONFIG) : null;
    String valueExcludeRegex = (config.get(PROPERTY_VALUE_EXCLUDE_CONFIG) != null) ? (String) config.get(PROPERTY_VALUE_EXCLUDE_CONFIG) : null;
    String valueIncludeRegex = (config.get(PROPERTY_VALUE_INCLUDE_CONFIG) != null) ? (String) config.get(PROPERTY_VALUE_INCLUDE_CONFIG) : null;

    for (String name : event.getPropertyNames()) {
        if (nameExcludeRegex != null && name.matches(nameExcludeRegex)) {
            return false;
        }

        if (nameIncludeRegex != null && name.matches(nameIncludeRegex)) {
            return true;
        }

        if (event.getProperty(name) != null && event.getProperty(name) instanceof String) {
            if (valueExcludeRegex != null && ((String) event.getProperty(name)).matches(valueExcludeRegex)) {
                return false;
            }
            if (valueIncludeRegex != null && ((String) event.getProperty(name)).matches(valueIncludeRegex)) {
                return true;
            }
        }

    }
    return true;
}
 
Example 16
Source File: AbstractPDFViewerRunnable.java    From tlaplus with MIT License 5 votes vote down vote up
public void handleEvent(final Event event) {
	// Listen for TLAEditor/save to regenerate the PDF and refresh the
	// editor iff the event DATA corresponds to this.specFile. There might
	// be several PDFs open each responsible for a certain spec.
	if (TLAEditor.SAVE_EVENT.equals(event.getTopic())) {
		final Object property = event.getProperty(IEventBroker.DATA);
		if (property instanceof IFile && this.specFile.equals(property)) {
			preUpdate();
			handler.runPDFJob(this, specFile);
		}
	}
}
 
Example 17
Source File: ElasticsearchAppender.java    From karaf-decanter with Apache License 2.0 4 votes vote down vote up
private Date getDate(Event event) {
    Long ts = (Long)event.getProperty("timestamp");
    Date date = ts != null ? new Date(ts) : new Date();
    return date;
}
 
Example 18
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static String toHTML(Event e) {
  StringBuffer sb = new StringBuffer();

  String[] names = e.getPropertyNames();

  Set<String> keys = new TreeSet<String>();
  for(int i = 0; i < names.length; i++) {
    // if(!SKIP_KEYS.contains(names[i])) 
      {
        keys.add(names[i]);
      }
  }

  sb.append("<html>");

  sb.append("<table border=0 width=\"100%\">\n");

  sb.append("<tr bgcolor=\"#eeeeee\">");
  sb.append("<td  valign=top  align=left bgcolor=\"#eeeeee\">" + 
     fontify(tf.format(new Date(getTime(e)))) + "</td>");
  sb.append("<td  valign=top  align=right bgcolor=\"#eeeeee\">" + 
     fontify(e.getTopic()) + "</td>");    
  sb.append("</tr>");

  sb.append("<tr bgcolor=\"#eeeeee\">");
      sb.append("<td  valign=top  colspan=2 align=left bgcolor=\"#eeeeee\">" + 
     fontify(getMessage(e)) + "</td>");
  sb.append("</tr>");
  
  Throwable t = getException(e);

  if(t != null) {
    StringWriter w = new StringWriter();
    t.printStackTrace(new PrintWriter(w));
    sb.append("<td colspan=2>");
    sb.append("<pre>");
    sb.append(w.toString());
    sb.append("</pre>");
    sb.append("</td>");
  } 

  for(Iterator<String> it = keys.iterator(); it.hasNext();) {
    String key = it.next();
    sb.append("<tr>");
    
    sb.append("<td>");
    sb.append(fontify(key));
    sb.append("</td>");

    sb.append("<td>");
    Object val = e.getProperty(key);
    if(SKIP_KEYS.contains(key)) {
      sb.append(fontify("<i>" + val.getClass().getName() + "@" + val.hashCode() + "</i>"));
    } else {
      sb.append(objToHTML(val));
    }
    sb.append("</td>");
    
    sb.append("</tr>");
  }


  sb.append("</tr>\n");

  sb.append("</table>\n");
  sb.append("</html>");

  return sb.toString();
}
 
Example 19
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static String getString(Event e, String key, String def) {
  Object v = e.getProperty(key);
  return v == null ? def : v.toString();
}
 
Example 20
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static Bundle getBundle(Event e) {
  Bundle b = (Bundle)e.getProperty("bundle");
  return b;
}