use of io.joynr.messaging.MessagingQos in project joynr by bmwcarit.
the class MyRadioConsumerApplication method run.
@SuppressWarnings("checkstyle:methodlength")
@Override
public void run() {
DiscoveryQos discoveryQos = new DiscoveryQos();
// As soon as the arbitration QoS is set on the proxy builder, discovery of suitable providers
// is triggered. If the discovery process does not find matching providers within the
// arbitration timeout duration it will be terminated and you will get an arbitration exception.
discoveryQos.setDiscoveryTimeoutMs(10000);
discoveryQos.setDiscoveryScope(discoveryScope);
// Provider entries in the global capabilities directory are cached locally. Discovery will
// consider entries in this cache valid if they are younger as the max age of cached
// providers as defined in the QoS. All valid entries will be processed by the arbitrator when searching
// for and arbitrating the "best" matching provider.
// NOTE: Valid cache entries might prevent triggering a lookup in the global capabilities
// directory. Therefore, not all providers registered with the global capabilities
// directory might be taken into account during arbitration.
discoveryQos.setCacheMaxAgeMs(Long.MAX_VALUE);
// The discovery process outputs a list of matching providers. The arbitration strategy then
// chooses one or more of them to be used by the proxy.
discoveryQos.setArbitrationStrategy(ArbitrationStrategy.HighestPriority);
// The provider will maintain at least a minimum interval idle time in milliseconds between
// successive notifications, even if on-change notifications are enabled and the value changes more
// often. This prevents the consumer from being flooded by updated values. The filtering happens on
// the provider's side, thus also preventing excessive network traffic.
int minInterval_ms = 0;
// The provider will send notifications every maximum interval in milliseconds, even if the value didn't
// change. It will send notifications more often if on-change notifications are enabled,
// the value changes more often, and the minimum interval QoS does not prevent it. The maximum interval
// can thus be seen as a sort of heart beat.
int maxInterval_ms = 10000;
// The provider will send notifications until the end date is reached. The consumer will not receive any
// notifications (neither value notifications nor missed publication notifications) after
// this date.
long validityMs = 60000;
// If no notification was received within the last alert interval, a missed publication
// notification will be raised.
int alertAfterInterval_ms = 20000;
// Notification messages will be sent with this time-to-live. If a notification message can not be
// delivered within its TTL, it will be deleted from the system.
// NOTE: If a notification message is not delivered due to an expired TTL, it might raise a
// missed publication notification (depending on the value of the alert interval QoS).
int publicationTtl_ms = 5000;
OnChangeWithKeepAliveSubscriptionQos subscriptionQos = new OnChangeWithKeepAliveSubscriptionQos();
subscriptionQos.setMinIntervalMs(minInterval_ms).setMaxIntervalMs(maxInterval_ms).setValidityMs(validityMs);
subscriptionQos.setAlertAfterIntervalMs(alertAfterInterval_ms).setPublicationTtlMs(publicationTtl_ms);
ProxyBuilder<RadioProxy> proxyBuilder = runtime.getProxyBuilder(providerDomain, RadioProxy.class);
try {
// getting an attribute
radioProxy = proxyBuilder.setMessagingQos(new MessagingQos()).setDiscoveryQos(discoveryQos).build();
RadioStation currentStation = radioProxy.getCurrentStation();
LOG.info(PRINT_BORDER + "ATTRIBUTE GET: current station: " + currentStation + PRINT_BORDER);
// subscribe to an attribute
subscriptionFutureCurrentStation = radioProxy.subscribeToCurrentStation(new AttributeSubscriptionAdapter<RadioStation>() {
@Override
public void onReceive(RadioStation value) {
LOG.info(PRINT_BORDER + "ATTRIBUTE SUBSCRIPTION: current station: " + value + PRINT_BORDER);
}
@Override
public void onError(JoynrRuntimeException error) {
LOG.info(PRINT_BORDER + "ATTRIBUTE SUBSCRIPTION: " + error + PRINT_BORDER);
}
}, subscriptionQos);
// broadcast subscription
// The provider will send a notification whenever the value changes.
MulticastSubscriptionQos weakSignalBroadcastSubscriptionQos;
// The consumer will be subscribed to the multicast until the end date is reached, after which the
// consumer will be automatically unsubscribed, and will not receive any further notifications
// this date.
long wsbValidityMs = 60 * 1000;
weakSignalBroadcastSubscriptionQos = new MulticastSubscriptionQos();
weakSignalBroadcastSubscriptionQos.setValidityMs(wsbValidityMs);
weakSignalFuture = subscribeToWeakSignal(weakSignalBroadcastSubscriptionQos);
// susbcribe to weak signal with partition "GERMANY"
weakSignalWithPartitionFuture = subscribeToWeakSignal(weakSignalBroadcastSubscriptionQos, "GERMANY");
// selective broadcast subscription
OnChangeSubscriptionQos newStationDiscoveredBroadcastSubscriptionQos;
int nsdbMinIntervalMs = 2 * 1000;
long nsdbValidityMs = 180 * 1000;
int nsdbPublicationTtlMs = 5 * 1000;
newStationDiscoveredBroadcastSubscriptionQos = new OnChangeSubscriptionQos();
newStationDiscoveredBroadcastSubscriptionQos.setMinIntervalMs(nsdbMinIntervalMs).setValidityMs(nsdbValidityMs).setPublicationTtlMs(nsdbPublicationTtlMs);
NewStationDiscoveredBroadcastFilterParameters newStationDiscoveredBroadcastFilterParams = new NewStationDiscoveredBroadcastFilterParameters();
newStationDiscoveredBroadcastFilterParams.setHasTrafficService("true");
// Munich
GeoPosition positionOfInterest = new GeoPosition(48.1351250, 11.5819810);
String positionOfInterestJson = null;
try {
positionOfInterestJson = objectMapper.writeValueAsString(positionOfInterest);
} catch (JsonProcessingException e1) {
LOG.error("Unable to write position of interest filter parameter to JSON", e1);
}
newStationDiscoveredBroadcastFilterParams.setPositionOfInterest(positionOfInterestJson);
// 200 km
newStationDiscoveredBroadcastFilterParams.setRadiusOfInterestArea("200000");
radioProxy.subscribeToNewStationDiscoveredBroadcast(new RadioBroadcastInterface.NewStationDiscoveredBroadcastAdapter() {
@Override
public void onReceive(RadioStation discoveredStation, GeoPosition geoPosition) {
LOG.info(PRINT_BORDER + "BROADCAST SUBSCRIPTION: new station discovered: " + discoveredStation + " at " + geoPosition + PRINT_BORDER);
}
}, newStationDiscoveredBroadcastSubscriptionQos, newStationDiscoveredBroadcastFilterParams);
boolean success;
try {
// add favorite radio station
RadioStation favoriteStation = new RadioStation("99.3 The Fox Rocks", false, Country.CANADA);
success = radioProxy.addFavoriteStation(favoriteStation);
LOG.info(PRINT_BORDER + "METHOD: added favorite station: " + favoriteStation + ": " + success + PRINT_BORDER);
success = radioProxy.addFavoriteStation(favoriteStation);
} catch (ApplicationException exception) {
AddFavoriteStationErrorEnum error = exception.getError();
switch(error) {
case DUPLICATE_RADIOSTATION:
LOG.info(PRINT_BORDER + "METHOD: addFavoriteStation failed with the following excpected error: " + error);
break;
default:
LOG.error(PRINT_BORDER + "METHOD: addFavoriteStation failed with an unexpected error: " + error);
break;
}
}
try {
// add favorite radio station
RadioStation favoriteStation = new RadioStation("", false, Country.GERMANY);
success = radioProxy.addFavoriteStation(favoriteStation);
LOG.info(PRINT_BORDER + "METHOD: addFavoriteStation completed unexpected with the following output: " + success);
} catch (ApplicationException exception) {
String errorName = exception.getError().name();
LOG.info(PRINT_BORDER + "METHOD: addFavoriteStation failed with the following unexpected ApplicationExcecption: " + errorName);
} catch (ProviderRuntimeException exception) {
String errorName = exception.getMessage();
String expectation = errorName.equals(MyRadioProvider.MISSING_NAME) ? "expected" : "unexpected";
LOG.info(PRINT_BORDER + "METHOD: addFavoriteStation failed with the following " + expectation + " exception: " + errorName);
}
// shuffle the stations
radioProxy.shuffleStations();
currentStation = radioProxy.getCurrentStation();
LOG.info(PRINT_BORDER + "The current radio station after shuffling is: " + currentStation + PRINT_BORDER);
// add favorite radio station async
RadioStation radioStation = new RadioStation("99.4 AFN", false, Country.GERMANY);
Future<Boolean> future = radioProxy.addFavoriteStation(new CallbackWithModeledError<Boolean, AddFavoriteStationErrorEnum>() {
@Override
public void onSuccess(Boolean result) {
LOG.info(PRINT_BORDER + "ASYNC METHOD: added favorite station: callback onSuccess" + PRINT_BORDER);
}
@Override
public void onFailure(JoynrRuntimeException error) {
LOG.info(PRINT_BORDER + "ASYNC METHOD: added favorite station: callback onFailure: " + error.getMessage() + PRINT_BORDER);
}
@Override
public void onFailure(AddFavoriteStationErrorEnum errorEnum) {
switch(errorEnum) {
case DUPLICATE_RADIOSTATION:
LOG.info(PRINT_BORDER + "ASYNC METHOD: added favorite station failed: Duplicate Station!" + PRINT_BORDER);
break;
default:
LOG.error(PRINT_BORDER + "ASYNC METHOD: added favorite station failed: unknown errorEnum:" + errorEnum + PRINT_BORDER);
break;
}
LOG.info(PRINT_BORDER + "ASYNC METHOD: added favorite station: callback onFailure: " + errorEnum + PRINT_BORDER);
}
}, radioStation);
try {
long timeoutInMilliseconds = 8000;
Boolean reply = future.get(timeoutInMilliseconds);
LOG.info(PRINT_BORDER + "ASYNC METHOD: added favorite station: " + radioStation + ": " + reply + PRINT_BORDER);
} catch (InterruptedException | JoynrRuntimeException | ApplicationException e) {
LOG.info(PRINT_BORDER + "ASYNC METHOD: added favorite station: " + radioStation + ": " + e.getClass().getSimpleName() + "!");
}
ConsoleReader console;
try {
console = new ConsoleReader();
int key;
while ((key = console.readCharacter()) != 'q') {
switch(key) {
case 's':
radioProxy.shuffleStations();
LOG.info("called shuffleStations");
break;
case 'm':
GetLocationOfCurrentStationReturned locationOfCurrentStation = radioProxy.getLocationOfCurrentStation();
LOG.info("called getLocationOfCurrentStation. country: " + locationOfCurrentStation.country + ", location: " + locationOfCurrentStation.location);
break;
default:
LOG.info("\n\nUSAGE press\n" + " q\tto quit\n" + " s\tto shuffle stations\n");
break;
}
}
} catch (IOException e) {
LOG.error("error reading input from console", e);
}
} catch (DiscoveryException e) {
LOG.error("No provider found", e);
} catch (JoynrCommunicationException e) {
LOG.error("The message was not sent: ", e);
}
}
use of io.joynr.messaging.MessagingQos in project joynr by bmwcarit.
the class JoynrAndroidExampleApplication method createProxy.
public void createProxy() {
if (runtime == null) {
logger.error("runtime has not been initialized!");
logToOutput("runtime has not been initialized!\n");
}
logToOutput("Creating joynr GPS proxy and requesting location...\n");
// 2 minutes ttl
MessagingQos messagingQos = new MessagingQos(2 * 60 * 1000);
DiscoveryQos discoveryQos = new // 30 second timeout to find a provider
DiscoveryQos(// 30 second timeout to find a provider
30 * 1000, ArbitrationStrategy.HighestPriority, Integer.MAX_VALUE, DiscoveryScope.LOCAL_ONLY);
try {
ProxyBuilder<GpsProxy> builder = runtime.getProxyBuilder(PROVIDER_DOMAIN, GpsProxy.class);
builder.setDiscoveryQos(discoveryQos).setMessagingQos(messagingQos).build(new ProxyBuilder.ProxyCreatedCallback<GpsProxy>() {
@Override
public void onProxyCreationFinished(GpsProxy newProxy) {
logToOutput("Proxy created");
proxy = newProxy;
}
@Override
public void onProxyCreationError(JoynrRuntimeException error) {
logToOutput("Error during proxy creation: " + error.getMessage() + "\n");
}
});
} catch (Exception e) {
logToOutput("ERROR: create proxy failed: " + e.getMessage() + "\n");
logger.error("create proxy failed: ", e);
}
}
use of io.joynr.messaging.MessagingQos in project joynr by bmwcarit.
the class SubscriptionManagerImpl method registerSubscription.
private void registerSubscription(String fromParticipantId, Set<DiscoveryEntryWithMetaInfo> toDiscoveryEntries, SubscriptionInvocation subscriptionInvocation, RegisterDataAndCreateSubscriptionRequest registerDataAndCreateSubscriptionRequest) {
if (!subscriptionInvocation.hasSubscriptionId()) {
subscriptionInvocation.setSubscriptionId(UUID.randomUUID().toString());
}
String subscriptionId = subscriptionInvocation.getSubscriptionId();
subscriptionFutureMap.put(subscriptionId, subscriptionInvocation.getFuture());
registerSubscription(subscriptionInvocation.getQos(), subscriptionId);
SubscriptionRequest subscriptionRequest = registerDataAndCreateSubscriptionRequest.execute();
MessagingQos messagingQos = new MessagingQos();
SubscriptionQos qos = subscriptionRequest.getQos();
if (qos.getExpiryDateMs() == SubscriptionQos.NO_EXPIRY_DATE) {
messagingQos.setTtl_ms(SubscriptionQos.INFINITE_SUBSCRIPTION);
} else {
messagingQos.setTtl_ms(qos.getExpiryDateMs() - System.currentTimeMillis());
}
dispatcher.sendSubscriptionRequest(fromParticipantId, toDiscoveryEntries, subscriptionRequest, messagingQos);
}
use of io.joynr.messaging.MessagingQos in project joynr by bmwcarit.
the class ConnectorTest method setUp.
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
fromParticipantId = "fromParticipantId";
toParticipantId = "toParticipantId";
toDiscoveryEntry = new DiscoveryEntryWithMetaInfo();
toDiscoveryEntry.setParticipantId(toParticipantId);
toDiscoveryEntries = Sets.newHashSet(toDiscoveryEntry);
qosSettings = new MessagingQos();
}
use of io.joynr.messaging.MessagingQos in project joynr by bmwcarit.
the class ProxyTest method setUp.
@SuppressWarnings({ "unchecked", "rawtypes" })
@Before
public void setUp() throws Exception {
navigationProxyCreatedSemaphore = new Semaphore(0);
navigationProxyCreatedCallback = new ProxyCreatedCallback<NavigationProxy>() {
@Override
public void onProxyCreationFinished(NavigationProxy result) {
navigationProxyCreatedSemaphore.release();
}
@Override
public void onProxyCreationError(JoynrRuntimeException error) {
fail("Navigation proxy creation failed: " + error);
}
};
testInterfaceProxyCreatedSemaphore = new Semaphore(0);
testInterfaceProxyCreatedCallback = new ProxyCreatedCallback<TestInterface>() {
@Override
public void onProxyCreationFinished(TestInterface result) {
testInterfaceProxyCreatedSemaphore.release();
}
@Override
public void onProxyCreationError(JoynrRuntimeException error) {
fail("TestInterface proxy creation failed: " + error);
}
};
domain = "TestDomain";
fromParticipantId = "ProxyTestFromParticipantId";
toParticipantId = "ProxyTestToParticipantId";
toDiscoveryEntry = new DiscoveryEntryWithMetaInfo(new Version(47, 11), domain, TestInterface.INTERFACE_NAME, toParticipantId, new ProviderQos(), System.currentTimeMillis(), System.currentTimeMillis() + ONE_MINUTE_IN_MS, "publicKeyId", true);
toDiscoveryEntries = new HashSet<DiscoveryEntryWithMetaInfo>();
toDiscoveryEntries.add(toDiscoveryEntry);
MockitoAnnotations.initMocks(this);
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
requestStaticInjection(RpcUtils.class);
bind(ReplyCallerDirectory.class).toInstance(replyCallerDirectory);
bind(RequestReplyManager.class).toInstance(requestReplyManager);
bind(SubscriptionManager.class).toInstance(subscriptionManager);
bind(MessageRouter.class).toInstance(messageRouter);
bind(RoutingTable.class).toInstance(routingTable);
install(new FactoryModuleBuilder().implement(ProxyInvocationHandler.class, ProxyInvocationHandlerImpl.class).build(ProxyInvocationHandlerFactory.class));
}
@Provides
@Singleton
@Named(SystemServicesSettings.PROPERTY_DISPATCHER_ADDRESS)
Address getDispatcherAddress() {
return new InProcessAddress();
}
});
proxyBuilderFactory = new ProxyBuilderFactoryImpl(localDiscoveryAggregator, injector.getInstance(ProxyInvocationHandlerFactory.class), MAX_TTL_MS, DISCOVERY_TIMEOUT_MS, RETRY_INTERVAL_MS);
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
DiscoveryEntryWithMetaInfo[] fakeCapabilitiesResult = { toDiscoveryEntry };
((Callback) args[0]).resolve((Object) fakeCapabilitiesResult);
return null;
}
}).when(localDiscoveryAggregator).lookup(Mockito.<Callback>any(), Mockito.<String[]>any(), Mockito.<String>any(), Mockito.<joynr.types.DiscoveryQos>any());
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
AttributeSubscribeInvocation request = (AttributeSubscribeInvocation) args[2];
if (request.getSubscriptionId() == null) {
request.setSubscriptionId(UUID.randomUUID().toString());
}
request.getFuture().resolve(request.getSubscriptionId());
return null;
}
}).when(subscriptionManager).registerAttributeSubscription(any(String.class), eq(Sets.newHashSet(toDiscoveryEntry)), Mockito.any(AttributeSubscribeInvocation.class));
Mockito.doAnswer(new // TODO simulate resolve here ! subscription reply bastern ... handle subscriptionreply ausführen..
Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
BroadcastSubscribeInvocation request = (BroadcastSubscribeInvocation) args[2];
if (request.getSubscriptionId() == null) {
request.setSubscriptionId(UUID.randomUUID().toString());
}
request.getFuture().resolve(request.getSubscriptionId());
return null;
}
}).when(subscriptionManager).registerBroadcastSubscription(any(String.class), eq(Sets.newHashSet(toDiscoveryEntry)), Mockito.any(BroadcastSubscribeInvocation.class));
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
MulticastSubscribeInvocation request = (MulticastSubscribeInvocation) args[2];
if (request.getSubscriptionId() == null) {
request.setSubscriptionId(UUID.randomUUID().toString());
}
request.getFuture().resolve(request.getSubscriptionId());
return null;
}
}).when(subscriptionManager).registerMulticastSubscription(any(String.class), eq(Sets.newHashSet(toDiscoveryEntry)), Mockito.any(MulticastSubscribeInvocation.class));
discoveryQos = new DiscoveryQos(10000, ArbitrationStrategy.HighestPriority, Long.MAX_VALUE);
messagingQos = new MessagingQos();
doAnswer(new Answer<Set<DiscoveryEntryWithMetaInfo>>() {
@Override
public Set<DiscoveryEntryWithMetaInfo> answer(InvocationOnMock invocation) throws Throwable {
return (Set<DiscoveryEntryWithMetaInfo>) invocation.getArguments()[1];
}
}).when(discoveryEntryVersionFilter).filter(Mockito.<Version>any(), Mockito.<Set<DiscoveryEntryWithMetaInfo>>any(), Mockito.<Map<String, Set<Version>>>any());
Field discoveryEntryVersionFilterField = ArbitratorFactory.class.getDeclaredField("discoveryEntryVersionFilter");
discoveryEntryVersionFilterField.setAccessible(true);
discoveryEntryVersionFilterField.set(ArbitratorFactory.class, discoveryEntryVersionFilter);
doAnswer(new Answer<Set<DiscoveryEntryWithMetaInfo>>() {
@Override
public Set<DiscoveryEntryWithMetaInfo> answer(InvocationOnMock invocation) throws Throwable {
return (Set<DiscoveryEntryWithMetaInfo>) invocation.getArguments()[1];
}
}).when(discoveryEntryVersionFilter).filter(Mockito.<Version>any(), Mockito.<Set<DiscoveryEntryWithMetaInfo>>any(), Mockito.<Map<String, Set<Version>>>any());
Field schedulerField = ArbitratorFactory.class.getDeclaredField("scheduler");
schedulerField.setAccessible(true);
String name = "TEST.joynr.scheduler.arbitration.arbitratorRunnable";
ThreadFactory joynrThreadFactory = new JoynrThreadFactory(name, true);
scheduler = Executors.newSingleThreadScheduledExecutor(joynrThreadFactory);
schedulerField.set(ArbitratorFactory.class, scheduler);
Field shutdownNotifierField = ArbitratorFactory.class.getDeclaredField("shutdownNotifier");
shutdownNotifierField.setAccessible(true);
shutdownNotifierField.set(ArbitratorFactory.class, shutdownNotifier);
ArbitratorFactory.start();
verify(shutdownNotifier).registerForShutdown(any(ShutdownListener.class));
}
Aggregations