use of joynr.Request in project joynr by bmwcarit.
the class SerializationTest method serializeRequest.
@Test
public void serializeRequest() throws JsonGenerationException, JsonMappingException, IOException {
GpsPosition[] parameter = { new GpsPosition(49.0065, 11.65) };
Object[] parameters = { parameter };
Class<?>[] parameterTypes = { GpsPosition[].class };
Request request = new Request("updateRoute", parameters, parameterTypes);
String writeValueAsString = objectMapper.writeValueAsString(request);
Request receivedRequest = objectMapper.readValue(writeValueAsString, Request.class);
Assert.assertEquals(request, receivedRequest);
}
use of joynr.Request in project joynr by bmwcarit.
the class DispatcherImpl method messageArrived.
@Override
public void messageArrived(final ImmutableMessage message) {
if (message == null) {
logger.error("received message was null");
return;
}
if (!message.isTtlAbsolute()) {
logger.error("received message with relative ttl (not supported)");
return;
}
final long expiryDate = message.getTtlMs();
final Map<String, String> customHeaders = message.getCustomHeaders();
if (DispatcherUtils.isExpired(expiryDate)) {
logger.debug("TTL expired, discarding message : {}", message);
return;
}
String payload;
try {
payload = new String(message.getUnencryptedBody(), Charsets.UTF_8);
} catch (EncodingException e) {
logger.error("Error reading SMRF message. msgId: {}. from: {} to: {}. Reason: {}. Discarding joynr message.", new Object[] { message.getSender(), message.getRecipient(), message.getId(), e.getMessage() });
return;
}
String type = message.getType();
try {
if (Message.VALUE_MESSAGE_TYPE_REPLY.equals(type)) {
Reply reply = objectMapper.readValue(payload, Reply.class);
logger.trace("Parsed reply from message payload :" + payload);
handle(reply);
} else if (Message.VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY.equals(type)) {
SubscriptionReply subscriptionReply = objectMapper.readValue(payload, SubscriptionReply.class);
logger.trace("Parsed subscription reply from message payload :" + payload);
handle(subscriptionReply);
} else if (Message.VALUE_MESSAGE_TYPE_REQUEST.equals(type)) {
final Request request = objectMapper.readValue(payload, Request.class);
request.setCreatorUserId(message.getCreatorUserId());
request.setContext(message.getContext());
logger.trace("Parsed request from message payload :" + payload);
handle(request, message.getSender(), message.getRecipient(), expiryDate, customHeaders, message.isCompressed());
} else if (Message.VALUE_MESSAGE_TYPE_ONE_WAY.equals(type)) {
OneWayRequest oneWayRequest = objectMapper.readValue(payload, OneWayRequest.class);
oneWayRequest.setCreatorUserId(message.getCreatorUserId());
oneWayRequest.setContext(message.getContext());
logger.trace("Parsed one way request from message payload :" + payload);
handle(oneWayRequest, message.getRecipient(), expiryDate);
} else if (Message.VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST.equals(type) || Message.VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST.equals(type) || Message.VALUE_MESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST.equals(type)) {
SubscriptionRequest subscriptionRequest = objectMapper.readValue(payload, SubscriptionRequest.class);
logger.trace("Parsed subscription request from message payload :" + payload);
handle(subscriptionRequest, message.getSender(), message.getRecipient());
} else if (Message.VALUE_MESSAGE_TYPE_SUBSCRIPTION_STOP.equals(type)) {
SubscriptionStop subscriptionStop = objectMapper.readValue(payload, SubscriptionStop.class);
logger.trace("Parsed subscription stop from message payload :" + payload);
handle(subscriptionStop);
} else if (Message.VALUE_MESSAGE_TYPE_PUBLICATION.equals(type)) {
SubscriptionPublication publication = objectMapper.readValue(payload, SubscriptionPublication.class);
logger.trace("Parsed publication from message payload :" + payload);
handle(publication);
} else if (Message.VALUE_MESSAGE_TYPE_MULTICAST.equals(type)) {
MulticastPublication multicastPublication = objectMapper.readValue(payload, MulticastPublication.class);
logger.trace("Parsed multicast publication from message payload: {}", payload);
handle(multicastPublication);
}
} catch (IOException e) {
logger.error("Error parsing payload. msgId: {}. from: {} to: {}. Reason: {}. Discarding joynr message.", message.getId(), message.getSender(), message.getRecipient(), e.getMessage());
return;
}
}
use of joynr.Request in project joynr by bmwcarit.
the class DispatcherImpl method error.
@Override
public void error(ImmutableMessage message, Throwable error) {
if (message == null) {
logger.error("error: ", error);
return;
}
String type = message.getType();
String payload;
try {
payload = new String(message.getUnencryptedBody(), Charsets.UTF_8);
} catch (EncodingException e) {
logger.error("Error extracting payload for message {}. Reason: {}", new Object[] { message.getId(), e.getMessage() });
return;
}
try {
if (type.equals(Message.VALUE_MESSAGE_TYPE_REQUEST)) {
Request request = objectMapper.readValue(payload, Request.class);
requestReplyManager.handleError(request, error);
}
} catch (IOException e) {
logger.error("Error extracting payload for message " + message.getId() + ", raw payload: " + payload, e.getMessage());
}
}
use of joynr.Request in project joynr by bmwcarit.
the class JoynrMessagingConnectorInvocationHandler method executeAsyncMethod.
@SuppressWarnings("unchecked")
@Override
public Future<?> executeAsyncMethod(Method method, Object[] params, Future<?> future) {
if (method == null) {
throw new IllegalArgumentException("Method cannot be null");
}
if (toDiscoveryEntries.size() > 1) {
throw new JoynrIllegalStateException("You can't execute async methods for multiple participants.");
}
if (toDiscoveryEntries.isEmpty()) {
throw new JoynrIllegalStateException("You must have exactly one participant to be able to execute an async method.");
}
MethodMetaInformation methodMetaInformation = JoynrMessagingConnectorFactory.ensureMethodMetaInformationPresent(method);
if (methodMetaInformation.getCallbackAnnotation() == null) {
throw new JoynrIllegalStateException("All async methods need to have a annotated callback parameter.");
}
int callbackIndex = methodMetaInformation.getCallbackIndex();
ICallback callback = (ICallback) params[callbackIndex];
Object[] paramsWithoutCallback = new Object[params.length - 1];
copyArrayWithoutElement(params, paramsWithoutCallback, callbackIndex);
Class<?>[] paramDatatypes = method.getParameterTypes();
Class<?>[] paramDatatypesWithoutCallback = new Class<?>[paramDatatypes.length - 1];
copyArrayWithoutElement(paramDatatypes, paramDatatypesWithoutCallback, callbackIndex);
Request request = new Request(method.getName(), paramsWithoutCallback, paramDatatypesWithoutCallback);
String requestReplyId = request.getRequestReplyId();
@SuppressWarnings("rawtypes") RpcAsyncRequestReplyCaller<?> callbackWrappingReplyCaller = new RpcAsyncRequestReplyCaller(requestReplyId, callback, future, method, methodMetaInformation);
ExpiryDate expiryDate = DispatcherUtils.convertTtlToExpirationDate(qosSettings.getRoundTripTtl_ms());
replyCallerDirectory.addReplyCaller(requestReplyId, callbackWrappingReplyCaller, expiryDate);
requestReplyManager.sendRequest(fromParticipantId, toDiscoveryEntries.iterator().next(), request, qosSettings);
return future;
}
use of joynr.Request in project joynr by bmwcarit.
the class RpcStubbingTest method setUp.
@Before
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NULL_PARAM_DEREF", justification = "NPE in test would fail test")
public void setUp() throws JoynrCommunicationException, JoynrSendBufferFullException, JsonGenerationException, JsonMappingException, IOException, JoynrMessageNotSentException {
Deferred<GpsLocation> deferredGpsLocation = new Deferred<GpsLocation>();
deferredGpsLocation.resolve(gpsValue);
when(testMock.returnsGpsLocation()).thenReturn(new Promise<Deferred<GpsLocation>>(deferredGpsLocation));
Deferred<List<GpsLocation>> deferredGpsLocationList = new Deferred<List<GpsLocation>>();
deferredGpsLocationList.resolve(gpsList);
when(testMock.returnsGpsLocationList()).thenReturn(new Promise<Deferred<List<GpsLocation>>>(deferredGpsLocationList));
DeferredVoid deferredVoid = new DeferredVoid();
deferredVoid.resolve();
when(testMock.noParamsNoReturnValue()).thenReturn(new Promise<DeferredVoid>(deferredVoid));
when(testMock.takesTwoSimpleParams(any(Integer.class), any(String.class))).thenReturn(new Promise<DeferredVoid>(deferredVoid));
fromParticipantId = UUID.randomUUID().toString();
toParticipantId = UUID.randomUUID().toString();
toDiscoveryEntry = new DiscoveryEntryWithMetaInfo();
toDiscoveryEntry.setParticipantId(toParticipantId);
// required to inject static members of JoynMessagingConnectorFactory
injector = Guice.createInjector(new JoynrPropertiesModule(PropertyLoader.loadProperties(MessagingPropertyKeys.DEFAULT_MESSAGING_PROPERTIES_FILE)), new JsonMessageSerializerModule(), new AbstractModule() {
@Override
protected void configure() {
requestStaticInjection(RpcUtils.class);
install(new JoynrMessageScopeModule());
MapBinder<Class<? extends Address>, AbstractMiddlewareMessagingStubFactory<? extends IMessagingStub, ? extends Address>> messagingStubFactory;
messagingStubFactory = MapBinder.newMapBinder(binder(), new TypeLiteral<Class<? extends Address>>() {
}, new TypeLiteral<AbstractMiddlewareMessagingStubFactory<? extends IMessagingStub, ? extends Address>>() {
}, Names.named(MessagingStubFactory.MIDDLEWARE_MESSAGING_STUB_FACTORIES));
messagingStubFactory.addBinding(InProcessAddress.class).to(InProcessMessagingStubFactory.class);
}
});
final RequestInterpreter requestInterpreter = injector.getInstance(RequestInterpreter.class);
final RequestCallerFactory requestCallerFactory = injector.getInstance(RequestCallerFactory.class);
when(requestReplyManager.sendSyncRequest(eq(fromParticipantId), eq(toDiscoveryEntry), any(Request.class), any(SynchronizedReplyCaller.class), eq(messagingQos))).thenAnswer(new Answer<Reply>() {
@Override
public Reply answer(InvocationOnMock invocation) throws Throwable {
RequestCaller requestCaller = requestCallerFactory.create(testMock);
Object[] args = invocation.getArguments();
Request request = null;
for (Object arg : args) {
if (arg instanceof Request) {
request = (Request) arg;
break;
}
}
final Future<Reply> future = new Future<Reply>();
ProviderCallback<Reply> callback = new ProviderCallback<Reply>() {
@Override
public void onSuccess(Reply result) {
future.onSuccess(result);
}
@Override
public void onFailure(JoynrException error) {
future.onFailure(error);
}
};
requestInterpreter.execute(callback, requestCaller, request);
return future.get();
}
});
JoynrMessagingConnectorFactory joynrMessagingConnectorFactory = new JoynrMessagingConnectorFactory(requestReplyManager, replyCallerDirectory, subscriptionManager);
connector = joynrMessagingConnectorFactory.create(fromParticipantId, Sets.newHashSet(toDiscoveryEntry), messagingQos);
}
Aggregations