Search in sources :

Example 11 with Message

use of org.opensmartgridplatform.oslp.Oslp.Message in project open-smart-grid-platform by OSGP.

the class MockOslpChannelHandler method channelRead0.

@Override
public void channelRead0(final ChannelHandlerContext ctx, final OslpEnvelope message) throws Exception {
    if (message.isValid()) {
        final String deviceUid = MockOslpChannelHandler.getDeviceUid(message);
        final DeviceState deviceState = this.devicesContext.getDeviceState(deviceUid);
        LOGGER.debug("Device {} received a message with sequence number {}", deviceUid, message.getSequenceNumber());
        if (this.isOslpResponse(message)) {
            LOGGER.debug("Device {} received an OSLP Response (before callback): {}", MockOslpChannelHandler.getDeviceUid(message), message.getPayloadMessage());
            // Lookup correct callback and call handle method.
            final String channelId = ctx.channel().id().asLongText();
            final Callback callback = this.callbacks.remove(channelId);
            if (callback == null) {
                LOGGER.warn("Callback for channel {} does not longer exist, dropping response.", channelId);
                return;
            }
            callback.handle(message);
        } else {
            final MessageType messageType = this.getMessageType(message.getPayloadMessage());
            LOGGER.debug("Device {} received an OSLP Request of type {}", deviceUid, messageType);
            if (deviceState.hasMockedResponses(messageType)) {
                // Build the OslpEnvelope.
                final OslpEnvelope.Builder responseBuilder = new OslpEnvelope.Builder().withSignature(this.oslpSignature).withProvider(this.oslpSignatureProvider).withPrimaryKey(this.privateKey).withDeviceId(message.getDeviceId()).withPayloadMessage(this.handleRequest(message));
                // Add the new sequence number to the OslpEnvelope.
                responseBuilder.withSequenceNumber(convertIntegerToByteArray(deviceState.getSequenceNumber()));
                final OslpEnvelope response = responseBuilder.build();
                LOGGER.debug("Device {} is sending an OSLP response with sequence number {}", MockOslpChannelHandler.getDeviceUid(response), convertByteArrayToInteger(response.getSequenceNumber()));
                // wait for the response to actually be written. This
                // improves stability of the tests
                final ChannelFuture future = ctx.channel().writeAndFlush(response);
                final InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
                final InetSocketAddress clientAddress = new InetSocketAddress(remoteAddress.getAddress(), PlatformPubliclightingDefaults.OSLP_ELSTER_SERVER_PORT);
                future.addListener((ChannelFutureListener) ChannelFutureListener -> {
                    Executors.newSingleThreadScheduledExecutor().schedule(() -> {
                        try {
                            MockOslpChannelHandler.this.sendNotifications(clientAddress, message, deviceUid, deviceState);
                        } catch (final DeviceSimulatorException | IOException e) {
                            LOGGER.info("Unable to send notifications", e);
                        }
                    }, 1000, TimeUnit.MILLISECONDS).get();
                    if (!ChannelFutureListener.isSuccess()) {
                        ChannelFutureListener.channel().close();
                    }
                });
                future.await();
                LOGGER.debug("Sent OSLP response: {}", response.getPayloadMessage().toString().split(" ")[0]);
            } else {
                LOGGER.error("Device {} received a message of type {}, but no mocks are available, this test will fail!", deviceUid, messageType);
            }
        }
    } else {
        LOGGER.warn("Received message wasn't properly secured.");
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope) LocalDateTime(java.time.LocalDateTime) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) MessageType(org.opensmartgridplatform.shared.infra.jms.MessageType) Sharable(io.netty.channel.ChannelHandler.Sharable) Base64(org.apache.commons.codec.binary.Base64) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LIGHT(org.opensmartgridplatform.oslp.Oslp.RelayType.LIGHT) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ParseException(java.text.ParseException) Message(org.opensmartgridplatform.oslp.Oslp.Message) Logger(org.slf4j.Logger) ReentrantLock(java.util.concurrent.locks.ReentrantLock) TARIFF(org.opensmartgridplatform.oslp.Oslp.RelayType.TARIFF) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) ChannelFuture(io.netty.channel.ChannelFuture) ByteString(com.google.protobuf.ByteString) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Lock(java.util.concurrent.locks.Lock) PlatformPubliclightingDefaults(org.opensmartgridplatform.cucumber.platform.publiclighting.PlatformPubliclightingDefaults) PrivateKey(java.security.PrivateKey) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DateTimeFormatter(java.time.format.DateTimeFormatter) Oslp(org.opensmartgridplatform.oslp.Oslp) InetSocketAddress(java.net.InetSocketAddress) ByteString(com.google.protobuf.ByteString) IOException(java.io.IOException) MessageType(org.opensmartgridplatform.shared.infra.jms.MessageType) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope)

Example 12 with Message

use of org.opensmartgridplatform.oslp.Oslp.Message in project open-smart-grid-platform by OSGP.

the class SigningService method doSignMessage.

private void doSignMessage(final UnsignedOslpEnvelopeDto unsignedOslpEnvelopeDto, final String correlationUid, final String deviceIdentification, final Destination replyToQueue) {
    final byte[] deviceId = unsignedOslpEnvelopeDto.getDeviceId();
    final byte[] sequenceNumber = unsignedOslpEnvelopeDto.getSequenceNumber();
    final Message payloadMessage = unsignedOslpEnvelopeDto.getPayloadMessage();
    final String organisationIdentification = unsignedOslpEnvelopeDto.getOrganisationIdentification();
    final int messagePriority = unsignedOslpEnvelopeDto.getMessagePriority();
    final boolean scheduled = unsignedOslpEnvelopeDto.isScheduled();
    final OslpEnvelope oslpEnvelope = new OslpEnvelope.Builder().withDeviceId(deviceId).withSequenceNumber(sequenceNumber).withPrimaryKey(this.privateKey).withSignature(this.signature).withProvider(this.signatureProvider).withPayloadMessage(payloadMessage).build();
    ResponseMessage responseMessage;
    if (oslpEnvelope == null) {
        LOGGER.error("Message for device: {} with correlationId: {} NOT SIGNED, sending error to protocol-adapter", deviceIdentification, correlationUid);
        responseMessage = ResponseMessage.newResponseMessageBuilder().withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification).withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK).withOsgpException(new OsgpException(ComponentType.UNKNOWN, "Failed to build signed OslpEnvelope", null)).withDataObject(unsignedOslpEnvelopeDto).withMessagePriority(messagePriority).withScheduled(scheduled).withRetryHeader(new RetryHeader()).build();
    } else {
        LOGGER.info("Message for device: {} with correlationId: {} signed, sending response to protocol-adapter", deviceIdentification, correlationUid);
        final SignedOslpEnvelopeDto signedOslpEnvelopeDto = new SignedOslpEnvelopeDto(oslpEnvelope, unsignedOslpEnvelopeDto);
        responseMessage = ResponseMessage.newResponseMessageBuilder().withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification).withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.OK).withDataObject(signedOslpEnvelopeDto).withMessagePriority(messagePriority).withScheduled(scheduled).withRetryHeader(new RetryHeader()).build();
    }
    this.signingServerResponseMessageSender.send(responseMessage, "SIGNING_RESPONSE", replyToQueue);
}
Also used : OsgpException(org.opensmartgridplatform.shared.exceptionhandling.OsgpException) ResponseMessage(org.opensmartgridplatform.shared.infra.jms.ResponseMessage) Message(org.opensmartgridplatform.oslp.Oslp.Message) SignedOslpEnvelopeDto(org.opensmartgridplatform.oslp.SignedOslpEnvelopeDto) ResponseMessage(org.opensmartgridplatform.shared.infra.jms.ResponseMessage) RetryHeader(org.opensmartgridplatform.shared.infra.jms.RetryHeader) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope)

Example 13 with Message

use of org.opensmartgridplatform.oslp.Oslp.Message in project open-smart-grid-platform by OSGP.

the class OslpEnvelopeEcDsaTest method buildOslpMessageIncorrectProvider.

/**
 * Valid must fail when decryption fails using incorrect keys
 *
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchProviderException
 */
@Test()
public void buildOslpMessageIncorrectProvider() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final byte[] deviceId = new byte[] { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
    final byte[] sequenceNumber = new byte[] { 0, 1 };
    final Message message = this.buildRegisterResponse();
    assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
        new OslpEnvelope.Builder().withSignature(SIGNATURE).withProvider("Incorrect").withPrimaryKey(CertificateHelper.createPrivateKeyFromBase64(PRIVATE_KEY_BASE_64, KEY_TYPE, this.provider())).withDeviceId(deviceId).withSequenceNumber(sequenceNumber).withPayloadMessage(message).build();
    });
}
Also used : Message(org.opensmartgridplatform.oslp.Oslp.Message) Test(org.junit.jupiter.api.Test)

Example 14 with Message

use of org.opensmartgridplatform.oslp.Oslp.Message in project open-smart-grid-platform by OSGP.

the class OslpChannelHandlerServer method channelRead0.

@Override
public void channelRead0(final ChannelHandlerContext ctx, final OslpEnvelope message) throws Exception {
    final ChannelId channelId = ctx.channel().id();
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("channelRead0 called for channel {}.", channelId.asLongText());
    }
    this.loggingService.logMessage(message, true);
    if (message.isValid()) {
        if (OslpUtils.isOslpResponse(message)) {
            LOGGER.warn("{} Received OSLP Response, which is not expected: {}", channelId, message.getPayloadMessage());
            ctx.close();
        } else {
            LOGGER.info("{} Received OSLP Request: {}", channelId, message.getPayloadMessage());
            // Response pay-load to send to device.
            final Message payload;
            // Check which request the device has sent and handle it.
            if (message.getPayloadMessage().hasRegisterDeviceRequest()) {
                payload = this.handleRegisterDeviceRequest(message.getDeviceId(), message.getSequenceNumber(), message.getPayloadMessage().getRegisterDeviceRequest());
            } else if (message.getPayloadMessage().hasConfirmRegisterDeviceRequest()) {
                payload = this.handleConfirmRegisterDeviceRequest(message.getDeviceId(), message.getSequenceNumber(), message.getPayloadMessage().getConfirmRegisterDeviceRequest());
            } else if (message.getPayloadMessage().hasEventNotificationRequest()) {
                payload = this.handleEventNotificationRequest(message.getDeviceId(), message.getSequenceNumber(), message.getPayloadMessage().getEventNotificationRequest());
            } else {
                LOGGER.warn("{} Received unknown payload. Received: {}.", channelId, message.getPayloadMessage());
                ctx.close();
                // Optional extra: return error code to device.
                return;
            }
            // Cache the channel so we can write the response to it later.
            this.channelCache.cacheChannel(ctx.channel());
            // Send message to signing server to get our response signed.
            this.oslpSigningService.buildAndSignEnvelope(message.getDeviceId(), message.getSequenceNumber(), payload, channelId, this);
        }
    } else {
        LOGGER.warn("{} Received message wasn't properly secured.", channelId);
        ctx.close();
    }
}
Also used : Message(org.opensmartgridplatform.oslp.Oslp.Message) ChannelId(io.netty.channel.ChannelId)

Example 15 with Message

use of org.opensmartgridplatform.oslp.Oslp.Message in project open-smart-grid-platform by OSGP.

the class OslpDeviceSteps method aStartDeviceOslpMessageIsSentToSpecificDevice.

/**
 * Verify that a start device OSLP message is sent to specific device.
 *
 * @param deviceIdentification The device identification expected in the message to the device.
 */
@Then("^a start device \"([^\"]*)\" message is sent to device \"([^\"]*)\" with deviceUid \"([^\"]*)\"$")
public void aStartDeviceOslpMessageIsSentToSpecificDevice(final String protocol, final String deviceIdentification, final String deviceUid) throws DeviceSimulatorException {
    final Message message = this.oslpMockServer.waitForRequest(deviceUid, MessageType.START_SELF_TEST);
    assertThat(message).isNotNull();
    assertThat(message.hasStartSelfTestRequest()).isTrue();
}
Also used : Message(org.opensmartgridplatform.oslp.Oslp.Message) Then(io.cucumber.java.en.Then)

Aggregations

Message (org.opensmartgridplatform.oslp.Oslp.Message)28 Then (io.cucumber.java.en.Then)18 ByteString (com.google.protobuf.ByteString)5 IOException (java.io.IOException)4 Oslp (org.opensmartgridplatform.oslp.Oslp)4 ParseException (java.text.ParseException)3 ReadSettingsHelper.getString (org.opensmartgridplatform.cucumber.core.ReadSettingsHelper.getString)3 OslpEnvelope (org.opensmartgridplatform.oslp.OslpEnvelope)3 UnknownHostException (java.net.UnknownHostException)2 Test (org.junit.jupiter.api.Test)2 DeviceSimulatorException (org.opensmartgridplatform.cucumber.platform.publiclighting.mocks.oslpdevice.DeviceSimulatorException)2 EventNotificationResponse (org.opensmartgridplatform.oslp.Oslp.EventNotificationResponse)2 Given (io.cucumber.java.en.Given)1 When (io.cucumber.java.en.When)1 Bootstrap (io.netty.bootstrap.Bootstrap)1 ChannelFuture (io.netty.channel.ChannelFuture)1 ChannelFutureListener (io.netty.channel.ChannelFutureListener)1 Sharable (io.netty.channel.ChannelHandler.Sharable)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 ChannelId (io.netty.channel.ChannelId)1