org.eclipse.jdt.annotation.NonNullByDefault Java Examples

The following examples show how to use org.eclipse.jdt.annotation.NonNullByDefault. 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: PersistentInbox.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@NonNullByDefault({})
public Stream<DiscoveryResult> stream() {
    final Storage<DiscoveryResult> discoveryResultStorage = this.discoveryResultStorage;
    if (discoveryResultStorage == null) {
        final ScheduledFuture<?> timeToLiveChecker = this.timeToLiveChecker;
        logger.error("The OSGi lifecycle has been violated (storage: {}, ttl checker cancelled: {}).",
                this.discoveryResultStorage == null ? "null" : this.discoveryResultStorage,
                timeToLiveChecker == null ? "null" : timeToLiveChecker.isCancelled());
        return Stream.empty();
    }
    final Collection<@Nullable DiscoveryResult> values = discoveryResultStorage.getValues();
    if (values == null) {
        logger.warn(
                "The storage service violates the nullness requirements (get values must not return null) (storage class: {}).",
                discoveryResultStorage.getClass());
        return Stream.empty();
    }
    return values.stream().filter(Objects::nonNull);
}
 
Example #2
Source File: AudioServlet.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void doGet(@NonNullByDefault({}) HttpServletRequest req, @NonNullByDefault({}) HttpServletResponse resp)
        throws ServletException, IOException {
    removeTimedOutStreams();

    final String streamId = substringBefore(substringAfterLast(req.getRequestURI(), "/"), ".");

    try (final InputStream stream = prepareInputStream(streamId, resp)) {
        if (stream == null) {
            logger.debug("Received request for invalid stream id at {}", req.getRequestURI());
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            stream.transferTo(resp.getOutputStream());
            resp.flushBuffer();
        }
    } catch (final AudioException ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}
 
Example #3
Source File: CallStackPresentationProvider.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@NonNullByDefault({})
public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) {
    Map<String, String> retMap = super.getEventHoverToolTipInfo(event, hoverTime);
    if (retMap == null) {
        retMap = new LinkedHashMap<>(1);
    }

    if (!(event instanceof TimeEvent) || !((TimeEvent) event).hasValue() ||
            !(event.getEntry() instanceof TimeGraphEntry)) {
        return retMap;
    }

    TimeGraphEntry entry = (TimeGraphEntry) event.getEntry();
    ITimeGraphDataProvider<? extends TimeGraphEntryModel> dataProvider = BaseDataProviderTimeGraphView.getProvider(entry);
    TmfModelResponse<@NonNull Map<@NonNull String, @NonNull String>> response = dataProvider.fetchTooltip(
            FetchParametersUtils.selectionTimeQueryToMap(new SelectionTimeQueryFilter(hoverTime, hoverTime, 1, Collections.singletonList(entry.getEntryModel().getId()))), null);
    Map<@NonNull String, @NonNull String> tooltipModel = response.getModel();
    if (tooltipModel != null) {
        retMap.putAll(tooltipModel);
    }

    return retMap;
}
 
Example #4
Source File: JavaCommPortProvider.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@NonNullByDefault({})
public void forEachRemaining(Consumer<? super T> action) {
    while (e.hasMoreElements()) {
        action.accept(e.nextElement());
    }
}
 
Example #5
Source File: RxTxPortProvider.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@NonNullByDefault({})
public void forEachRemaining(Consumer<? super T> action) {
    while (e.hasMoreElements()) {
        action.accept(e.nextElement());
    }
}
 
Example #6
Source File: RxTxPortProvider.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@NonNullByDefault({})
public boolean tryAdvance(Consumer<? super T> action) {
    if (e.hasMoreElements()) {
        action.accept(e.nextElement());
        return true;
    }
    return false;
}
 
Example #7
Source File: JavaCommPortProvider.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@NonNullByDefault({})
public void forEachRemaining(Consumer<? super T> action) {
    while (e.hasMoreElements()) {
        action.accept(e.nextElement());
    }
}
 
Example #8
Source File: JavaCommPortProvider.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@NonNullByDefault({})
public boolean tryAdvance(Consumer<? super T> action) {
    if (e.hasMoreElements()) {
        action.accept(e.nextElement());
        return true;
    }
    return false;
}
 
Example #9
Source File: RuleEngineImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @return copy of current context in rule engine
 */
private Map<String, Object> getContext(String ruleUID, @Nullable Set<Connection> connections) {
    @NonNullByDefault({})
    Map<String, Object> context = contextMap.get(ruleUID);
    if (context == null) {
        context = new HashMap<String, Object>();
        contextMap.put(ruleUID, context);
    }
    if (connections != null) {
        StringBuffer sb = new StringBuffer();
        for (Connection c : connections) {
            String outputModuleId = c.getOutputModuleId();
            if (outputModuleId != null) {
                sb.append(outputModuleId).append(OUTPUT_SEPARATOR).append(c.getOutputName());
                Object outputValue = context.get(sb.toString());
                sb.setLength(0);
                if (outputValue != null) {
                    if (c.getReference() == null) {
                        context.put(c.getInputName(), outputValue);
                    } else {
                        context.put(c.getInputName(), ReferenceResolver.resolveComplexDataReference(outputValue,
                                ReferenceResolver.splitReferenceToTokens(c.getReference())));
                    }
                }
            } else {
                // get reference from context
                String ref = c.getReference();
                final Object value = ReferenceResolver.resolveReference(ref, context);

                if (value != null) {
                    context.put(c.getInputName(), value);
                }
            }
        }
    }
    return context;
}
 
Example #10
Source File: BaseDataProviderTimeGraphPresentationProvider.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@NonNullByDefault({})
public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) {
    if (event != null && !(event instanceof NullTimeEvent)) {
        Map<String, String> tooltipInfo = new LinkedHashMap<>();
        synchronized (fProviders) {
            fProviders.values().forEach(tooltipResolver -> tooltipInfo.putAll(tooltipResolver.apply(event, hoverTime)));
        }
        return tooltipInfo;
    }
    return Collections.emptyMap();
}
 
Example #11
Source File: TmfViewFactory.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a new view. <br>
 * If a view with the corresponding id already exists and no suffix were
 * added the existing view will be given focus.
 *
 * @param viewId
 *            The id of the view to be created. <br>
 *            Format: primary_id[:secondary_id[&uuid]|:uuid]
 * @param generateSuffix
 *            Add or replace a generated suffix id (UUID). This allows
 *            multiple views with the same id to be displayed.
 * @return The view instance, or null if an error occurred.
 */
@NonNullByDefault
public static @Nullable IViewPart newView(String viewId, boolean generateSuffix) {
    IViewPart viewPart = null;
    String primaryId = null;
    String secondaryId = null;

    /* Parse the view id */
    int index = viewId.indexOf(TmfView.VIEW_ID_SEPARATOR);
    if (index != -1) {
        primaryId = viewId.substring(0, index);
        secondaryId = getBaseSecId(viewId.substring(index + 1));
    } else {
        primaryId = viewId;
    }

    if (generateSuffix) {
        if (secondaryId == null) {
            secondaryId = UUID.randomUUID().toString();
        } else {
            secondaryId += INTERNAL_SECONDARY_ID_SEPARATOR + UUID.randomUUID().toString();
        }
    }

    IWorkbench workbench = PlatformUI.getWorkbench();
    IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
    IWorkbenchPage page = workbenchWindow.getActivePage();
    try {
        viewPart = page.showView(primaryId, secondaryId, IWorkbenchPage.VIEW_ACTIVATE);
        page.activate(viewPart);
    } catch (PartInitException e) {
        /* Simply return null on error */
    }

    return viewPart;
}
 
Example #12
Source File: AbstractTimeGraphView.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Generate the predicate for every property from the regexes
 *
 * @return A map of predicate by property
 * @since 5.0
 */
@NonNullByDefault
protected Map<Integer, Predicate<Multimap<String, Object>>> generateRegexPredicate() {
    Multimap<Integer, String> regexes = getRegexes();
    Map<@NonNull Integer, @NonNull Predicate<@NonNull Multimap<@NonNull String, @NonNull Object>>> predicates = new HashMap<>();
    for (Entry<Integer, Collection<String>> entry : regexes.asMap().entrySet()) {
        String regex = IFilterStrings.mergeFilters(entry.getValue());
        FilterCu cu = FilterCu.compile(regex);
        Predicate<@NonNull Multimap<@NonNull String, @NonNull Object>> predicate = cu != null ? cu.generate() : null;
            if (predicate != null) {
                predicates.put(entry.getKey(), predicate);
            }
    }
    return predicates;
}
 
Example #13
Source File: AbstractTimeGraphView.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Filter the given eventList using the predicates
 *
 * @param entry
 *            The timegraph entry
 * @param eventList
 *            The event list at this zoom level
 * @param predicates
 *            The predicate for the filter dialog text box
 * @since 6.0
 */
@NonNullByDefault
protected void doFilterEventList(TimeGraphEntry entry, List<ITimeEvent> eventList, Map<Integer, Predicate<Multimap<String, Object>>> predicates) {
    if (!predicates.isEmpty()) {
        // For each event in the events list, test each predicates and set the
        // status of the property associated to the predicate
        eventList.forEach(te -> {
            for (Map.Entry<Integer, Predicate<Multimap<String, Object>>> mapEntry : predicates.entrySet()) {
                Predicate<Multimap<String, Object>> value = Objects.requireNonNull(mapEntry.getValue());
                Multimap<String, Object> toTest = HashMultimap.create();
                for (Entry<String, String> filterEntry : getPresentationProvider().getFilterInput(te).entrySet()) {
                    toTest.put(filterEntry.getKey(), filterEntry.getValue());
                }
                toTest.putAll(te.getMetadata());

                boolean status = value.test(toTest);
                Integer property = mapEntry.getKey();
                if (property == IFilterProperty.DIMMED || property == IFilterProperty.EXCLUDE) {
                    te.setProperty(property, !status);
                } else {
                    te.setProperty(property, status);
                }
            }
        });
    }
    fillWithNullEvents(entry, eventList);
}
 
Example #14
Source File: TmfXmlTraceStub.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@NonNullByDefault({DefaultLocation.TYPE_ARGUMENT})
public void initTrace(@Nullable IResource resource, @Nullable String path, @Nullable Class<? extends ITmfEvent> type) throws TmfTraceException {
    super.initTrace(resource, path, type);
    ITmfContext ctx;

    /* Initialize and read the trace with the 'set_aspects' definition */
    TmfSignalManager.deregister(fTrace);
    fTrace.initTrace(resource, path, type);
    ctx = seekEvent(0L);
    /* If a set_aspects event exists, getNext() will process it */
    getNext(ctx);
    ctx.dispose();
    fTrace.dispose();

    /* Initialize a new trace with the trace events definition */
    fTrace = new CustomXmlTrace(fDefinition);
    TmfSignalManager.deregister(fTrace);
    fTrace.initTrace(resource, path, type);
    /* Set the start and (current) end times for this trace */
    ctx = seekEvent(0L);
    if (ctx == null) {
        return;
    }
    ITmfEvent event = getNext(ctx);
    if (event != null) {
        final ITmfTimestamp curTime = event.getTimestamp();
        this.setStartTime(curTime);
        this.setEndTime(curTime);
    }
    ctx.dispose();
}
 
Example #15
Source File: PcapTrace.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@NonNullByDefault({ DefaultLocation.TYPE_ARGUMENT })
public synchronized void initTrace(@Nullable IResource resource, @Nullable String path, @Nullable Class<? extends ITmfEvent> type) throws TmfTraceException {
    super.initTrace(resource, path, type);
    if (path == null) {
        throw new TmfTraceException("No path has been specified."); //$NON-NLS-1$
    }
    Path filePath = checkNotNull(Paths.get(path));
    try {
        fPcapFile = PcapHelper.getPcapFile(filePath);
    } catch (IOException | BadPcapFileException e) {
        throw new TmfTraceException(e.getMessage(), e);
    }
}
 
Example #16
Source File: JavaCommPortProvider.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@NonNullByDefault({})
public boolean tryAdvance(Consumer<? super T> action) {
    if (e.hasMoreElements()) {
        action.accept(e.nextElement());
        return true;
    }
    return false;
}
 
Example #17
Source File: XmlDocumentBundleTracker.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public final synchronized void open() {
    final OpenState openState = withLock(lockOpenState.writeLock(), () -> {
        if (this.openState == OpenState.CREATED) {
            this.openState = OpenState.OPENED;
        }
        return this.openState;
    });
    if (openState != OpenState.OPENED) {
        logger.warn("Open XML document bundle tracker forbidden (state: {})", openState);
        return;
    }

    relevantBundlesTracker = new BundleTracker(context,
            Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE, null) {
        @Override
        public @Nullable Object addingBundle(@NonNullByDefault({}) Bundle bundle,
                @NonNullByDefault({}) BundleEvent event) {
            return withLock(lockOpenState.readLock(),
                    () -> openState == OpenState.OPENED && isBundleRelevant(bundle) ? bundle : null);
        }
    };
    relevantBundlesTracker.open();

    super.open();
}
 
Example #18
Source File: ChannelCommandDescriptionProviderOSGiTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Bundle resolveBundle(@NonNullByDefault({}) Class<?> clazz) {
    if (clazz != null && clazz.equals(AbstractThingHandler.class)) {
        return testBundle;
    } else {
        return FrameworkUtil.getBundle(clazz);
    }
}
 
Example #19
Source File: XmlDocumentBundleTracker.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public final synchronized void removedBundle(@NonNullByDefault({}) Bundle bundle,
        @NonNullByDefault({}) BundleEvent event, Bundle object) {
    logger.trace("Removing the XML related objects from module '{}'...", ReadyMarkerUtils.getIdentifier(bundle));
    finishedBundles.remove(bundle);
    Future<?> future = queue.remove(bundle);
    if (future != null) {
        future.cancel(true);
    }
    releaseXmlDocumentProvider(bundle);
    unregisterReadyMarker(bundle);
}
 
Example #20
Source File: MDNSDiscoveryService.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void serviceRemoved(@NonNullByDefault({}) ServiceEvent serviceEvent) {
    for (MDNSDiscoveryParticipant participant : participants) {
        if (participant.getServiceType().equals(serviceEvent.getType())) {
            try {
                ThingUID thingUID = participant.getThingUID(serviceEvent.getInfo());
                if (thingUID != null) {
                    thingRemoved(thingUID);
                }
            } catch (Exception e) {
                logger.error("Participant '{}' threw an exception", participant.getClass().getName(), e);
            }
        }
    }
}
 
Example #21
Source File: BaseDataProviderTimeGraphPresentationProvider.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
@Override
@NonNullByDefault({})
public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event) {
    return getEventHoverToolTipInfo(event, event.getTime());
}
 
Example #22
Source File: IconServlet.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected void doGet(@NonNullByDefault({}) HttpServletRequest req, @NonNullByDefault({}) HttpServletResponse resp)
        throws ServletException, IOException {
    if (req.getDateHeader("If-Modified-Since") > startupTime) {
        resp.setStatus(304);
        return;
    }

    String category = getCategory(req);
    String state = getState(req);
    String iconSetId = getIconSetId(req);

    Format format = getFormat(req);
    Format otherFormat = null;
    if ("true".equalsIgnoreCase(req.getParameter(PARAM_ANY_FORMAT))) {
        otherFormat = (format == Format.PNG) ? Format.SVG : Format.PNG;
    }

    IconProvider provider = getIconProvider(category, iconSetId, format);

    if (otherFormat != null) {
        IconProvider provider2 = getIconProvider(category, iconSetId, otherFormat);
        if (provider2 != null) {
            if (provider == null) {
                provider = provider2;
                format = otherFormat;
            } else if (provider2 != provider) {
                Integer prio = provider.hasIcon(category, iconSetId, format);
                Integer prio2 = provider2.hasIcon(category, iconSetId, otherFormat);
                if ((prio != null && prio2 != null && prio < prio2) || (prio == null && prio2 != null)) {
                    provider = provider2;
                    format = otherFormat;
                }
            }
        }
    }

    if (provider == null) {
        logger.debug("Requested icon category {} provided by no icon provider", category);
        resp.sendError(404);
        return;
    }

    if (Format.SVG.equals(format)) {
        resp.setContentType("image/svg+xml");
    } else {
        resp.setContentType("image/png");
    }
    resp.setDateHeader("Last-Modified", new Date().getTime());
    ServletOutputStream os = resp.getOutputStream();
    try (InputStream is = provider.getIcon(category, iconSetId, state, format)) {
        if (is == null) {
            logger.debug("Requested icon category {} provided by no icon provider", category);
            resp.sendError(404);
            return;
        }
        is.transferTo(os);
        resp.flushBuffer();
    } catch (IOException e) {
        logger.error("Failed sending the icon byte stream as a response: {}", e.getMessage());
        resp.sendError(500, e.getMessage());
    }
}
 
Example #23
Source File: XmlDocumentBundleTracker.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public final synchronized Bundle addingBundle(@NonNullByDefault({}) Bundle bundle,
        @NonNullByDefault({}) BundleEvent event) {
    addingBundle(bundle);
    return bundle;
}
 
Example #24
Source File: ThingManagerOSGiTest.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void thingManagerPostsThingStatusChangedEventsIfTheStatusOfAThingIsChanged() throws Exception {
    registerThingTypeProvider();

    class ThingHandlerState {
        ThingHandlerCallback callback;
    }
    final ThingHandlerState state = new ThingHandlerState();

    ThingHandler thingHandler = mock(ThingHandler.class);
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            state.callback = (ThingHandlerCallback) invocation.getArgument(0);
            return null;
        }
    }).when(thingHandler).setCallback(any(ThingHandlerCallback.class));
    when(thingHandler.getThing()).thenReturn(thing);

    ThingHandlerFactory thingHandlerFactory = mock(ThingHandlerFactory.class);
    when(thingHandlerFactory.supportsThingType(any(ThingTypeUID.class))).thenReturn(true);
    when(thingHandlerFactory.registerHandler(any(Thing.class))).thenReturn(thingHandler);

    registerService(thingHandlerFactory);

    final List<ThingStatusInfoChangedEvent> infoChangedEvents = new ArrayList<>();

    @NonNullByDefault
    EventSubscriber thingStatusEventSubscriber = new EventSubscriber() {
        @Override
        public Set<String> getSubscribedEventTypes() {
            return singleton(ThingStatusInfoChangedEvent.TYPE);
        }

        @Override
        public @Nullable EventFilter getEventFilter() {
            return null;
        }

        @Override
        public void receive(Event event) {
            infoChangedEvents.add((ThingStatusInfoChangedEvent) event);
        }
    };

    registerService(thingStatusEventSubscriber);

    // add thing (UNINITIALIZED -> INITIALIZING)
    managedThingProvider.add(thing);

    waitForAssert(() -> assertThat(infoChangedEvents.size(), is(1)));
    assertThat(infoChangedEvents.get(0).getType(), is(ThingStatusInfoChangedEvent.TYPE));
    assertThat(infoChangedEvents.get(0).getTopic(), is("smarthome/things/binding:type:id/statuschanged"));
    assertThat(infoChangedEvents.get(0).getStatusInfo().getStatus(), is(ThingStatus.INITIALIZING));
    assertThat(infoChangedEvents.get(0).getOldStatusInfo().getStatus(), is(ThingStatus.UNINITIALIZED));
    infoChangedEvents.clear();

    // set status to ONLINE (INITIALIZING -> ONLINE)
    ThingStatusInfo onlineNone = ThingStatusInfoBuilder.create(ThingStatus.ONLINE, ThingStatusDetail.NONE).build();
    state.callback.statusUpdated(thing, onlineNone);

    waitForAssert(() -> assertThat(infoChangedEvents.size(), is(1)));
    assertThat(infoChangedEvents.get(0).getType(), is(ThingStatusInfoChangedEvent.TYPE));
    assertThat(infoChangedEvents.get(0).getTopic(), is("smarthome/things/binding:type:id/statuschanged"));
    assertThat(infoChangedEvents.get(0).getStatusInfo().getStatus(), is(ThingStatus.ONLINE));
    assertThat(infoChangedEvents.get(0).getOldStatusInfo().getStatus(), is(ThingStatus.INITIALIZING));
    infoChangedEvents.clear();

    // set status to ONLINE again
    state.callback.statusUpdated(thing, onlineNone);

    // make sure no event has been sent
    Thread.sleep(500);
    assertThat(infoChangedEvents.size(), is(0));
}
 
Example #25
Source File: InboxOSGITest.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void assertThatInboxEventSubscribersReceiveEventsAboutDiscoveryResultChanges() {
    ThingTypeUID thingTypeUID = new ThingTypeUID("some", "thing");
    ThingUID thingUID = new ThingUID(thingTypeUID, "uid");
    final AsyncResultWrapper<Event> receivedEvent = new AsyncResultWrapper<>();

    @NonNullByDefault
    EventSubscriber inboxEventSubscriber = new EventSubscriber() {
        @Override
        public void receive(Event event) {
            receivedEvent.set(event);
        }

        @Override
        public Set<String> getSubscribedEventTypes() {
            return Stream.of(InboxAddedEvent.TYPE, InboxRemovedEvent.TYPE, InboxUpdatedEvent.TYPE).collect(toSet());
        }

        @Override
        public @Nullable EventFilter getEventFilter() {
            return null;
        }
    };

    registerService(inboxEventSubscriber);

    // add discovery result
    DiscoveryResult discoveryResult = new DiscoveryResultImpl(thingTypeUID, thingUID, null, null, null, null,
            DEFAULT_TTL);
    addDiscoveryResult(discoveryResult);
    waitForAssert(() -> assertThat(receivedEvent.getWrappedObject(), not(nullValue())));
    assertThat(receivedEvent.getWrappedObject(), is(instanceOf(InboxAddedEvent.class)));
    receivedEvent.reset();

    // update discovery result
    discoveryResult = new DiscoveryResultImpl(thingTypeUID, thingUID, null, null, null, null, DEFAULT_TTL);
    addDiscoveryResult(discoveryResult);
    waitForAssert(() -> assertThat(receivedEvent.getWrappedObject(), not(nullValue())));
    assertThat(receivedEvent.getWrappedObject(), is(instanceOf(InboxUpdatedEvent.class)));
    receivedEvent.reset();

    // remove discovery result
    removeDiscoveryResult(thingUID);
    waitForAssert(() -> assertThat(receivedEvent.getWrappedObject(), not(nullValue())));
    assertThat(receivedEvent.getWrappedObject(), is(instanceOf(InboxRemovedEvent.class)));
}
 
Example #26
Source File: JaasAuthenticationProvider.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Authentication authenticate(final Credentials credentials) throws AuthenticationException {
    if (realmName == null) { // configuration is not yet ready or set
        realmName = DEFAULT_REALM;
    }

    if (!(credentials instanceof UsernamePasswordCredentials)) {
        throw new AuthenticationException("Unsupported credentials passed to provider.");
    }

    UsernamePasswordCredentials userCredentials = (UsernamePasswordCredentials) credentials;
    final String name = userCredentials.getUsername();
    final char[] password = userCredentials.getPassword().toCharArray();

    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Principal userPrincipal = new GenericUser(name);
        Subject subject = new Subject(true, Set.of(userPrincipal), Collections.emptySet(), Set.of(userCredentials));

        Thread.currentThread().setContextClassLoader(ManagedUserLoginModule.class.getClassLoader());
        LoginContext loginContext = new LoginContext(realmName, subject, new CallbackHandler() {
            @Override
            public void handle(@NonNullByDefault({}) Callback[] callbacks)
                    throws IOException, UnsupportedCallbackException {
                for (Callback callback : callbacks) {
                    if (callback instanceof PasswordCallback) {
                        ((PasswordCallback) callback).setPassword(password);
                    } else if (callback instanceof NameCallback) {
                        ((NameCallback) callback).setName(name);
                    } else {
                        throw new UnsupportedCallbackException(callback);
                    }
                }
            }
        }, new ManagedUserLoginConfiguration());
        loginContext.login();

        return getAuthentication(name, loginContext.getSubject());
    } catch (LoginException e) {
        throw new AuthenticationException(e.getMessage());
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}
 
Example #27
Source File: GenericItemProviderTest.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void assertThatItemEventsAreSentOnlyOncePerItemEvenWithMultipleItemFiles() {
    List<AbstractItemRegistryEvent> receivedEvents = new ArrayList<>();

    @NonNullByDefault
    EventSubscriber itemEventSubscriber = new EventSubscriber() {
        @Override
        public void receive(Event event) {
            receivedEvents.add((AbstractItemRegistryEvent) event);
        }

        @Override
        public Set<String> getSubscribedEventTypes() {
            return Stream.of(ItemAddedEvent.TYPE, ItemUpdatedEvent.TYPE, ItemRemovedEvent.TYPE).collect(toSet());
        }

        @Override
        public @Nullable EventFilter getEventFilter() {
            return null;
        }
    };

    registerService(itemEventSubscriber);

    assertThat(itemRegistry.getAll().size(), is(0));

    receivedEvents.clear();
    String model = "String test1 \"Test Item [%s]\" { channel=\"test:test:test:test\" }\n"
            + "String test2 \"Test Item [%s]\" { channel=\"test:test:test:test\" }";
    modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));

    waitForAssert(() -> {
        assertThat(itemRegistry.getAll().size(), is(2));
        assertThat(receivedEvents.size(), is(2));
        assertThat(receivedEvents.stream().filter(e -> "test1".equals(e.getItem().name)).findFirst().get(),
                instanceOf(ItemAddedEvent.class));
        assertThat(receivedEvents.stream().filter(e -> "test2".equals(e.getItem().name)).findFirst().get(),
                instanceOf(ItemAddedEvent.class));
    });

    receivedEvents.clear();

    model = "String test3 \"Test Item [%s]\" { channel=\"test:test:test:test\" }\n"
            + "String test4 \"Test Item [%s]\" { channel=\"test:test:test:test\" }";
    modelRepository.addOrRefreshModel(TESTMODEL_NAME2, new ByteArrayInputStream(model.getBytes()));

    // only ItemAddedEvents for items test3 and test4 should be fired, NOT for test1 and test2 again
    waitForAssert(() -> {
        assertThat(itemRegistry.getAll().size(), is(4));
        assertThat(receivedEvents.size(), is(2));
        assertThat(receivedEvents.stream().filter(e -> "test3".equals(e.getItem().name)).findFirst().get(),
                instanceOf(ItemAddedEvent.class));
        assertThat(receivedEvents.stream().filter(e -> "test4".equals(e.getItem().name)).findFirst().get(),
                instanceOf(ItemAddedEvent.class));
    });
}
 
Example #28
Source File: GenericItemProviderTest.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void assertThatItemEventsAreSentCorrectly() {
    List<AbstractItemRegistryEvent> receivedEvents = new ArrayList<>();

    @NonNullByDefault
    EventSubscriber itemEventSubscriber = new EventSubscriber() {
        @Override
        public void receive(Event event) {
            receivedEvents.add((AbstractItemRegistryEvent) event);
        }

        @Override
        public Set<String> getSubscribedEventTypes() {
            return Stream.of(ItemAddedEvent.TYPE, ItemUpdatedEvent.TYPE, ItemRemovedEvent.TYPE).collect(toSet());
        }

        @Override
        public @Nullable EventFilter getEventFilter() {
            return null;
        }
    };

    registerService(itemEventSubscriber);

    assertThat(itemRegistry.getAll().size(), is(0));

    receivedEvents.clear();
    String model = "String test1 \"Test Item [%s]\" { channel=\"test:test:test:test\" }\n"
            + "String test2 \"Test Item [%s]\" { channel=\"test:test:test:test\" }";
    modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));

    waitForAssert(() -> {
        assertThat(itemRegistry.getAll().size(), is(2));
        assertThat(receivedEvents.size(), is(2));
        assertThat(receivedEvents.stream().filter(e -> "test1".equals(e.getItem().name)).findFirst().get(),
                instanceOf(ItemAddedEvent.class));
        assertThat(receivedEvents.stream().filter(e -> "test2".equals(e.getItem().name)).findFirst().get(),
                instanceOf(ItemAddedEvent.class));
    });

    receivedEvents.clear();
    model = "String test1 \"Test Item Changed [%s]\" { channel=\"test:test:test:test\" }";
    modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));

    waitForAssert(() -> {
        assertThat(itemRegistry.getAll().size(), is(1));
        assertThat(receivedEvents.size(), is(2));
        assertThat(receivedEvents.stream().filter(e -> "test1".equals(e.getItem().name)).findFirst().get(),
                instanceOf(ItemUpdatedEvent.class));
        assertThat(receivedEvents.stream().filter(e -> "test2".equals(e.getItem().name)).findFirst().get(),
                instanceOf(ItemRemovedEvent.class));
    });

    receivedEvents.clear();
    model = "";
    modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));

    waitForAssert(() -> {
        assertThat(itemRegistry.getAll().size(), is(0));
        assertThat(receivedEvents.size(), is(1));
        assertThat(receivedEvents.stream().filter(e -> "test1".equals(e.getItem().name)).findFirst().get(),
                instanceOf(ItemRemovedEvent.class));
    });
}
 
Example #29
Source File: MDNSDiscoveryService.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void serviceAdded(@NonNullByDefault({}) ServiceEvent serviceEvent) {
    considerService(serviceEvent);
}
 
Example #30
Source File: GenericItemProviderTest.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Make sure the models and items are removed and the removal events have been processed.
 */
@After
public void tearDown() {
    Collection<Item> itemsToRemove = itemRegistry.getAll();
    List<String> modelNamesToRemove = TESTMODEL_NAMES.stream()
            .filter(name -> modelRepository.getModel(name) != null).collect(Collectors.toList());

    if (!modelNamesToRemove.isEmpty()) {
        Set<String> removedModelNames = new HashSet<>();
        ModelRepositoryChangeListener modelListener = new ModelRepositoryChangeListener() {
            @Override
            public void modelChanged(String modelName, EventType type) {
                logger.debug("Received event: {} {}", modelName, type);
                if (type == EventType.REMOVED) {
                    removedModelNames.add(modelName);
                }
            }
        };

        List<AbstractItemRegistryEvent> removedItemEvents = new ArrayList<>();
        @NonNullByDefault
        EventSubscriber itemEventSubscriber = new EventSubscriber() {
            @Override
            public void receive(Event event) {
                logger.debug("Received event: {}", event);
                removedItemEvents.add((AbstractItemRegistryEvent) event);
            }

            @Override
            public Set<String> getSubscribedEventTypes() {
                return Stream.of(ItemRemovedEvent.TYPE).collect(toSet());
            }

            @Override
            public @Nullable EventFilter getEventFilter() {
                return null;
            }
        };

        modelRepository.addModelRepositoryChangeListener(modelListener);
        registerService(itemEventSubscriber);

        modelNamesToRemove.forEach(modelRepository::removeModel);

        waitForAssert(() -> {
            assertThat(removedItemEvents, hasSize(itemsToRemove.size()));
            assertThat(removedModelNames, hasSize(modelNamesToRemove.size()));
        });

        modelRepository.removeModelRepositoryChangeListener(modelListener);
        unregisterService(itemEventSubscriber);
    }
}