Search in sources :

Example 1 with OslpEnvelope

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

the class OslpDeviceSteps method theDeviceSendsMultipleEventNotificationsRequestToThePlatform.

@When("^the device sends multiple event notifications request to the platform over \"([^\"]*)\"$")
public void theDeviceSendsMultipleEventNotificationsRequestToThePlatform(final String protocol, final Map<String, String> settings) throws IOException, DeviceSimulatorException {
    final Oslp.EventNotificationRequest.Builder requestBuilder = Oslp.EventNotificationRequest.newBuilder();
    final Oslp.EventNotification.Builder builder = Oslp.EventNotification.newBuilder();
    final String[] events = getString(settings, PlatformPubliclightingKeys.KEY_EVENTS).split(PlatformPubliclightingKeys.SEPARATOR_COMMA), indexes = getString(settings, PlatformPubliclightingKeys.KEY_INDEXES).split(PlatformPubliclightingKeys.SEPARATOR_COMMA);
    for (int i = 0; i < events.length; i++) {
        if (!events[i].isEmpty() && !indexes[i].isEmpty()) {
            builder.setEvent(Event.valueOf(events[i].trim()));
            final String indexValue = indexes[i];
            final Integer index = indexValue == null || "EMPTY".equals(indexValue) ? 0 : Integer.valueOf(indexValue);
            builder.setIndex(ByteString.copyFrom(new byte[] { index.byteValue() }));
            requestBuilder.addNotifications(builder.build());
        }
    }
    this.oslpMockServer.incrementSequenceNumber(this.getDeviceUid(settings));
    final OslpEnvelope request = this.createEnvelopeBuilder(getString(settings, PlatformPubliclightingKeys.KEY_DEVICE_UID, PlatformPubliclightingDefaults.DEVICE_UID), this.oslpMockServer.getSequenceNumber(this.getDeviceUid(settings))).withPayloadMessage(Message.newBuilder().setEventNotificationRequest(requestBuilder.build()).build()).build();
    this.send(request, settings);
}
Also used : ReadSettingsHelper.getInteger(org.opensmartgridplatform.cucumber.core.ReadSettingsHelper.getInteger) EventNotification(org.opensmartgridplatform.oslp.Oslp.EventNotification) ReadSettingsHelper.getString(org.opensmartgridplatform.cucumber.core.ReadSettingsHelper.getString) ByteString(com.google.protobuf.ByteString) EventNotificationRequest(org.opensmartgridplatform.oslp.Oslp.EventNotificationRequest) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope) When(io.cucumber.java.en.When)

Example 2 with OslpEnvelope

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

the class OslpDeviceSteps method theDeviceSendsARegisterDeviceRequestToThePlatform.

@Given("^the device sends a register device request to the platform over \"([^\"]*)\"$")
public void theDeviceSendsARegisterDeviceRequestToThePlatform(final String protocol, final Map<String, String> settings) throws DeviceSimulatorException {
    try {
        this.oslpMockServer.incrementSequenceNumber(this.getDeviceUid(settings));
        final OslpEnvelope request = this.createEnvelopeBuilder(getString(settings, PlatformPubliclightingKeys.KEY_DEVICE_UID, PlatformPubliclightingDefaults.DEVICE_UID), this.oslpMockServer.getSequenceNumber(this.getDeviceUid(settings))).withPayloadMessage(Message.newBuilder().setRegisterDeviceRequest(Oslp.RegisterDeviceRequest.newBuilder().setDeviceIdentification(getString(settings, PlatformPubliclightingKeys.KEY_DEVICE_IDENTIFICATION, PlatformPubliclightingDefaults.DEFAULT_DEVICE_IDENTIFICATION)).setIpAddress(ByteString.copyFrom(InetAddress.getByName(getString(settings, PlatformPubliclightingKeys.IP_ADDRESS, PlatformPubliclightingDefaults.LOCALHOST)).getAddress())).setDeviceType(getEnum(settings, PlatformPubliclightingKeys.KEY_DEVICE_TYPE, DeviceType.class, DeviceType.SSLD)).setHasSchedule(getBoolean(settings, PlatformPubliclightingKeys.KEY_HAS_SCHEDULE, PlatformPubliclightingDefaults.DEFAULT_HASSCHEDULE)).setRandomDevice(getInteger(settings, PlatformPubliclightingKeys.RANDOM_DEVICE, PlatformPubliclightingDefaults.RANDOM_DEVICE))).build()).build();
        this.send(request, settings);
    } catch (final IOException | IllegalArgumentException e) {
        ScenarioContext.current().put("Error", e);
    }
}
Also used : DeviceType(org.opensmartgridplatform.oslp.Oslp.DeviceType) IOException(java.io.IOException) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope) Given(io.cucumber.java.en.Given)

Example 3 with OslpEnvelope

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

the class OslpDeviceSteps method theDeviceSendsAnEventNotificationRequestToThePlatform.

@Given("^the device sends an event notification request to the platform over \"([^\"]*)\"$")
public void theDeviceSendsAnEventNotificationRequestToThePlatform(final String protocol, final Map<String, String> settings) throws IOException, DeviceSimulatorException {
    final Oslp.EventNotification.Builder builder = Oslp.EventNotification.newBuilder().setEvent(getEnum(settings, PlatformKeys.KEY_EVENT, Event.class)).setDescription(getString(settings, PlatformKeys.KEY_DESCRIPTION));
    final String timeStamp = getString(settings, PlatformKeys.TIMESTAMP);
    if (timeStamp != null) {
        builder.setTimestamp(timeStamp);
    }
    final String indexValue = getString(settings, PlatformPubliclightingKeys.KEY_INDEX);
    final Integer index = indexValue == null || "EMPTY".equals(indexValue) ? 0 : Integer.valueOf(indexValue);
    builder.setIndex(ByteString.copyFrom(new byte[] { index.byteValue() }));
    this.oslpMockServer.incrementSequenceNumber(this.getDeviceUid(settings));
    final OslpEnvelope request = this.createEnvelopeBuilder(getString(settings, PlatformPubliclightingKeys.KEY_DEVICE_UID, PlatformPubliclightingDefaults.DEVICE_UID), this.oslpMockServer.getSequenceNumber(this.getDeviceUid(settings))).withPayloadMessage(Message.newBuilder().setEventNotificationRequest(Oslp.EventNotificationRequest.newBuilder().addNotifications(builder.build())).build()).build();
    this.send(request, settings);
}
Also used : ReadSettingsHelper.getInteger(org.opensmartgridplatform.cucumber.core.ReadSettingsHelper.getInteger) EventNotification(org.opensmartgridplatform.oslp.Oslp.EventNotification) ReadSettingsHelper.getString(org.opensmartgridplatform.cucumber.core.ReadSettingsHelper.getString) ByteString(com.google.protobuf.ByteString) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope) Given(io.cucumber.java.en.Given)

Example 4 with OslpEnvelope

use of org.opensmartgridplatform.oslp.OslpEnvelope 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 5 with OslpEnvelope

use of org.opensmartgridplatform.oslp.OslpEnvelope 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)

Aggregations

OslpEnvelope (org.opensmartgridplatform.oslp.OslpEnvelope)42 IOException (java.io.IOException)28 UnsignedOslpEnvelopeDto (org.opensmartgridplatform.oslp.UnsignedOslpEnvelopeDto)22 DeviceResponseHandler (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceResponseHandler)20 DeviceResponse (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceResponse)18 DeviceRequest (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceRequest)17 ByteString (com.google.protobuf.ByteString)7 Device (org.opensmartgridplatform.webdevicesimulator.domain.entities.Device)5 DeviceSimulatorException (org.opensmartgridplatform.webdevicesimulator.exceptions.DeviceSimulatorException)4 Given (io.cucumber.java.en.Given)3 Channel (io.netty.channel.Channel)3 ChannelFuture (io.netty.channel.ChannelFuture)3 UnknownHostException (java.net.UnknownHostException)3 GetStatusDeviceRequest (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.requests.GetStatusDeviceRequest)3 GetStatusDeviceResponse (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.responses.GetStatusDeviceResponse)3 ReadSettingsHelper.getString (org.opensmartgridplatform.cucumber.core.ReadSettingsHelper.getString)3 Oslp (org.opensmartgridplatform.oslp.Oslp)3 Message (org.opensmartgridplatform.oslp.Oslp.Message)3 SocketChannel (io.netty.channel.socket.SocketChannel)2 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)2