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.");
}
}
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);
}
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();
});
}
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();
}
}
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();
}
Aggregations