Search in sources :

Example 11 with Request

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);
}
Also used : OneWayRequest(joynr.OneWayRequest) SubscriptionRequest(joynr.SubscriptionRequest) PersistedSubscriptionRequest(io.joynr.dispatching.subscription.PersistedSubscriptionRequest) BroadcastSubscriptionRequest(joynr.BroadcastSubscriptionRequest) Request(joynr.Request) GpsPosition(joynr.types.Localisation.GpsPosition) Test(org.junit.Test)

Example 12 with Request

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;
    }
}
Also used : SubscriptionReply(joynr.SubscriptionReply) EncodingException(io.joynr.smrf.EncodingException) OneWayRequest(joynr.OneWayRequest) MulticastSubscriptionRequest(joynr.MulticastSubscriptionRequest) SubscriptionRequest(joynr.SubscriptionRequest) Request(joynr.Request) IOException(java.io.IOException) OneWayRequest(joynr.OneWayRequest) MulticastSubscriptionRequest(joynr.MulticastSubscriptionRequest) SubscriptionRequest(joynr.SubscriptionRequest) MulticastPublication(joynr.MulticastPublication) SubscriptionPublication(joynr.SubscriptionPublication) SubscriptionReply(joynr.SubscriptionReply) Reply(joynr.Reply) SubscriptionStop(joynr.SubscriptionStop)

Example 13 with Request

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());
    }
}
Also used : EncodingException(io.joynr.smrf.EncodingException) OneWayRequest(joynr.OneWayRequest) MulticastSubscriptionRequest(joynr.MulticastSubscriptionRequest) SubscriptionRequest(joynr.SubscriptionRequest) Request(joynr.Request) IOException(java.io.IOException)

Example 14 with Request

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;
}
Also used : RpcAsyncRequestReplyCaller(io.joynr.dispatching.rpc.RpcAsyncRequestReplyCaller) ExpiryDate(io.joynr.common.ExpiryDate) MethodMetaInformation(joynr.MethodMetaInformation) OneWayRequest(joynr.OneWayRequest) Request(joynr.Request) JoynrIllegalStateException(io.joynr.exceptions.JoynrIllegalStateException)

Example 15 with Request

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);
}
Also used : InProcessAddress(io.joynr.messaging.inprocess.InProcessAddress) Address(joynr.system.RoutingTypes.Address) InProcessAddress(io.joynr.messaging.inprocess.InProcessAddress) Deferred(io.joynr.provider.Deferred) DeferredVoid(io.joynr.provider.DeferredVoid) TypeLiteral(com.google.inject.TypeLiteral) JoynrPropertiesModule(io.joynr.common.JoynrPropertiesModule) List(java.util.List) ProviderCallback(io.joynr.provider.ProviderCallback) JsonMessageSerializerModule(io.joynr.messaging.JsonMessageSerializerModule) Request(joynr.Request) GpsLocation(joynr.types.Localisation.GpsLocation) JoynrException(io.joynr.exceptions.JoynrException) AbstractModule(com.google.inject.AbstractModule) JoynrMessageScopeModule(io.joynr.context.JoynrMessageScopeModule) RequestCaller(io.joynr.dispatching.RequestCaller) AbstractMiddlewareMessagingStubFactory(io.joynr.messaging.AbstractMiddlewareMessagingStubFactory) RequestInterpreter(io.joynr.dispatching.rpc.RequestInterpreter) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Reply(joynr.Reply) IMessagingStub(io.joynr.messaging.IMessagingStub) SynchronizedReplyCaller(io.joynr.dispatching.rpc.SynchronizedReplyCaller) DiscoveryEntryWithMetaInfo(joynr.types.DiscoveryEntryWithMetaInfo) RequestCallerFactory(io.joynr.dispatching.RequestCallerFactory) Before(org.junit.Before)

Aggregations

Request (joynr.Request)18 OneWayRequest (joynr.OneWayRequest)11 SubscriptionRequest (joynr.SubscriptionRequest)8 MessagingQos (io.joynr.messaging.MessagingQos)7 Reply (joynr.Reply)6 AbstractModule (com.google.inject.AbstractModule)5 Injector (com.google.inject.Injector)5 TypeLiteral (com.google.inject.TypeLiteral)5 Method (java.lang.reflect.Method)5 MutableMessage (joynr.MutableMessage)5 Before (org.junit.Before)5 Test (org.junit.Test)5 JoynrIllegalStateException (io.joynr.exceptions.JoynrIllegalStateException)4 MulticastSubscriptionRequest (joynr.MulticastSubscriptionRequest)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 JoynrPropertiesModule (io.joynr.common.JoynrPropertiesModule)3 SynchronizedReplyCaller (io.joynr.dispatching.rpc.SynchronizedReplyCaller)3 JsonMessageSerializerModule (io.joynr.messaging.JsonMessageSerializerModule)3 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)2