Skip to content

Commit

Permalink
Optimize classed converted from Java to Kotlin way.
Browse files Browse the repository at this point in the history
  • Loading branch information
dddj698 committed Mar 5, 2024
1 parent b2e1c77 commit a916d48
Show file tree
Hide file tree
Showing 32 changed files with 947 additions and 1,078 deletions.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ import io.cloudevents.CloudEventData
import io.cloudevents.core.builder.CloudEventBuilder
import org.eclipse.uprotocol.UprotocolOptions
import org.eclipse.uprotocol.uri.serializer.LongUriSerializer
import org.eclipse.uprotocol.uuid.factory.UuidUtils
import org.eclipse.uprotocol.uuid.factory.getTime
import org.eclipse.uprotocol.uuid.factory.isUuid
import org.eclipse.uprotocol.uuid.serializer.LongUuidSerializer
import org.eclipse.uprotocol.v1.*
import org.eclipse.uprotocol.v1.UUID
Expand Down Expand Up @@ -168,14 +169,14 @@ object UCloudEvent {
}

/**
* Extract the timestamp from the UUIDV8 CloudEvent Id, with Unix epoch as the
* Extract the timestamp from the UUIDV8 CloudEvent ID, with Unix epoch as the
* @param cloudEvent The CloudEvent with the timestamp to extract.
* @return Return the timestamp from the UUIDV8 CloudEvent Id or an empty Optional if timestamp can't be extracted.
* @return Return the timestamp from the UUIDV8 CloudEvent ID or an empty Optional if timestamp can't be extracted.
*/
fun getCreationTimestamp(cloudEvent: CloudEvent): Optional<Long> {
val cloudEventId = cloudEvent.id
val uuid = LongUuidSerializer.instance().deserialize(cloudEventId)
return UuidUtils.getTime(uuid)
val uuid = LongUuidSerializer.INSTANCE.deserialize(cloudEventId)
return Optional.ofNullable(uuid.getTime())
}

/**
Expand Down Expand Up @@ -215,11 +216,11 @@ object UCloudEvent {
return false
}
val cloudEventId: String = cloudEvent.id
val uuid = LongUuidSerializer.instance().deserialize(cloudEventId)
val uuid = LongUuidSerializer.INSTANCE.deserialize(cloudEventId)
if (uuid == UUID.getDefaultInstance()) {
return false
}
val delta: Long = System.currentTimeMillis() - UuidUtils.getTime(uuid).orElse(0L)
val delta: Long = System.currentTimeMillis() - (uuid.getTime()?:0L)
return delta >= ttl
}

Expand All @@ -230,8 +231,8 @@ object UCloudEvent {
*/
fun isCloudEventId(cloudEvent: CloudEvent): Boolean {
val cloudEventId: String = cloudEvent.id
val uuid = LongUuidSerializer.instance().deserialize(cloudEventId)
return UuidUtils.isUuid(uuid)
val uuid = LongUuidSerializer.INSTANCE.deserialize(cloudEventId)
return uuid.isUuid()
}

/**
Expand Down Expand Up @@ -352,7 +353,7 @@ object UCloudEvent {
}

val msgAttributes = uAttributes {
id = LongUuidSerializer.instance().deserialize(event.id)
id = LongUuidSerializer.INSTANCE.deserialize(event.id)
type = getMessageType(event.type)
source = LongUriSerializer.instance().deserialize(event.source.toString())
if (hasCommunicationStatusProblem(event)) {
Expand All @@ -367,7 +368,7 @@ object UCloudEvent {

getSink(event).ifPresent { sink = LongUriSerializer.instance().deserialize(it) }

getRequestId(event).ifPresent { reqid = LongUuidSerializer.instance().deserialize(it) }
getRequestId(event).ifPresent { reqid = LongUuidSerializer.INSTANCE.deserialize(it) }

getTtl(event).ifPresent { ttl = it }

Expand Down Expand Up @@ -395,7 +396,7 @@ object UCloudEvent {
val attributes: UAttributes = message.attributes ?: UAttributes.getDefaultInstance()
val payload = message.payload ?: UPayload.getDefaultInstance()
val builder: CloudEventBuilder =
CloudEventBuilder.v1().withId(LongUuidSerializer.instance().serialize(attributes.id))
CloudEventBuilder.v1().withId(LongUuidSerializer.INSTANCE.serialize(attributes.id))
builder.withType(getEventType(attributes.type))
builder.withSource(URI.create(LongUriSerializer.instance().serialize(attributes.source)))
val contentType = getContentTypeFromUPayloadFormat(payload.format)
Expand Down Expand Up @@ -427,7 +428,7 @@ object UCloudEvent {
}

if (attributes.hasReqid()) {
builder.withExtension("reqid", LongUuidSerializer.instance().serialize(attributes.reqid))
builder.withExtension("reqid", LongUuidSerializer.INSTANCE.serialize(attributes.reqid))
}

if (attributes.hasPermissionLevel()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 General Motors GTO LLC
* Copyright (c) 2024 General Motors GTO LLC
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
Expand Down Expand Up @@ -29,28 +29,26 @@ import java.util.Base64
/**
* Helper for serializing Base64 protobuf data.
*/
interface Base64ProtobufSerializer {
companion object {
/**
* Deserialize a base64 protobuf payload into a Base64 String.
* @param bytes byte[] data
* @return Returns a String from the base64 protobuf payload.
*/
fun deserialize(bytes: ByteArray?): String {
return if (bytes == null) {
""
} else Base64.getEncoder().encodeToString(bytes)
}
object Base64ProtobufSerializer {
/**
* Deserialize a base64 protobuf payload into a Base64 String.
* @param bytes byte[] data
* @return Returns a String from the base64 protobuf payload.
*/
fun deserialize(bytes: ByteArray?): String {
return if (bytes == null) {
""
} else Base64.getEncoder().encodeToString(bytes)
}

/**
* Serialize a String into Base64 format.
* @param stringToSerialize String to serialize.
* @return Returns the Base64 formatted String as a byte[].
*/
fun serialize(stringToSerialize: String?): ByteArray {
return if (stringToSerialize == null) {
ByteArray(0)
} else Base64.getDecoder().decode(stringToSerialize.toByteArray())
}
/**
* Serialize a String into Base64 format.
* @param stringToSerialize String to serialize.
* @return Returns the Base64 formatted String as a byte[].
*/
fun serialize(stringToSerialize: String?): ByteArray {
return if (stringToSerialize == null) {
ByteArray(0)
} else Base64.getDecoder().decode(stringToSerialize.toByteArray())
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 General Motors GTO LLC
* Copyright (c) 2024 General Motors GTO LLC
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
Expand Down Expand Up @@ -27,16 +27,11 @@ package org.eclipse.uprotocol.cloudevent.serialize
/**
* Provides Singleton instances of the CloudEvent Serializers.
*/
enum class CloudEventSerializers(cloudEventSerializer: CloudEventSerializer) {
enum class CloudEventSerializers(private val cloudEventSerializer: CloudEventSerializer) {
JSON(CloudEventToJsonSerializer()),
PROTOBUF(CloudEventToProtobufSerializer());

private val cloudEventSerializer: CloudEventSerializer
fun serializer(): CloudEventSerializer {
return cloudEventSerializer
}

init {
this.cloudEventSerializer = cloudEventSerializer
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 General Motors GTO LLC
* Copyright (c) 2024 General Motors GTO LLC
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
Expand Down Expand Up @@ -31,16 +31,15 @@ import io.cloudevents.protobuf.ProtobufFormat
* CloudEventSerializer to serialize and deserialize CloudEvents to protobuf format.
*/
class CloudEventToProtobufSerializer : CloudEventSerializer {

companion object {
private val serializer: ProtobufFormat = ProtobufFormat()
}

override fun serialize(cloudEvent: CloudEvent): ByteArray {
return serializer.serialize(cloudEvent)
}

override fun deserialize(bytes: ByteArray): CloudEvent {
return serializer.deserialize(bytes)
}

companion object {
private val serializer: ProtobufFormat = ProtobufFormat()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ import io.cloudevents.CloudEvent
import org.eclipse.uprotocol.cloudevent.factory.UCloudEvent
import org.eclipse.uprotocol.validation.ValidationResult
import org.eclipse.uprotocol.uri.serializer.LongUriSerializer
import org.eclipse.uprotocol.uri.validator.UriValidator
import org.eclipse.uprotocol.uri.validator.isRpcMethod
import org.eclipse.uprotocol.uri.validator.validate
import org.eclipse.uprotocol.v1.*
import java.util.Optional

Expand Down Expand Up @@ -324,7 +325,7 @@ abstract class CloudEventValidator {
}

private fun validateUEntityUri(uri: UUri): ValidationResult {
return UriValidator.validate(uri)
return uri.validate()
}

/**
Expand Down Expand Up @@ -405,7 +406,7 @@ abstract class CloudEventValidator {
)
)
}
return if (!UriValidator.isRpcMethod(uri)) {
return if (!uri.isRpcMethod()) {
ValidationResult.failure("Invalid RPC method uri. UriPart should be the method to be called, or method from response.")
} else ValidationResult.success()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

package org.eclipse.uprotocol.transport.builder

import org.eclipse.uprotocol.uuid.factory.UuidFactory
import org.eclipse.uprotocol.uuid.factory.UUIDV8
import org.eclipse.uprotocol.v1.*

/**
Expand Down Expand Up @@ -159,7 +159,7 @@ class UAttributesBuilder
fun publish(source: UUri, priority: UPriority): UAttributesBuilder {
return UAttributesBuilder(
source,
UuidFactory.Factories.UPROTOCOL.factory().create(),
UUIDV8(),
UMessageType.UMESSAGE_TYPE_PUBLISH, priority
)
}
Expand All @@ -174,7 +174,7 @@ class UAttributesBuilder
fun notification(source: UUri, sink: UUri, priority: UPriority): UAttributesBuilder {
return UAttributesBuilder(
source,
UuidFactory.Factories.UPROTOCOL.factory().create(),
UUIDV8(),
UMessageType.UMESSAGE_TYPE_PUBLISH, priority
).withSink(sink)
}
Expand All @@ -190,7 +190,7 @@ class UAttributesBuilder
fun request(source: UUri, sink: UUri, priority: UPriority, ttl: Int): UAttributesBuilder {
return UAttributesBuilder(
source,
UuidFactory.Factories.UPROTOCOL.factory().create(),
UUIDV8(),
UMessageType.UMESSAGE_TYPE_REQUEST, priority
).withTtl(ttl).withSink(sink)
}
Expand All @@ -206,7 +206,7 @@ class UAttributesBuilder
fun response(source: UUri, sink: UUri, priority: UPriority, reqid: UUID): UAttributesBuilder {
return UAttributesBuilder(
source,
UuidFactory.Factories.UPROTOCOL.factory().create(),
UUIDV8(),
UMessageType.UMESSAGE_TYPE_RESPONSE, priority
).withSink(sink).withReqId(reqid)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import com.google.protobuf.Message
import org.eclipse.uprotocol.v1.UPayload
import org.eclipse.uprotocol.v1.UPayloadFormat
import org.eclipse.uprotocol.v1.uPayload
import java.util.*


object UPayloadBuilder {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,11 @@

package org.eclipse.uprotocol.transport.validate

import org.eclipse.uprotocol.uri.validator.UriValidator
import org.eclipse.uprotocol.uuid.factory.UuidUtils
import org.eclipse.uprotocol.uri.validator.validate
import org.eclipse.uprotocol.uri.validator.validateRpcMethod
import org.eclipse.uprotocol.uri.validator.validateRpcResponse
import org.eclipse.uprotocol.uuid.factory.getTime
import org.eclipse.uprotocol.uuid.factory.isUuid
import org.eclipse.uprotocol.v1.*
import org.eclipse.uprotocol.validation.ValidationResult
import java.util.stream.Collectors
Expand All @@ -51,7 +54,7 @@ abstract class UAttributesValidator {
* invalid configurations.
*/
fun validate(attributes: UAttributes): ValidationResult {
val errorMessage = Stream.of<ValidationResult>(validateType(attributes),
val errorMessage = Stream.of(validateType(attributes),
validateTtl(attributes), validateSink(attributes),
validateCommStatus(attributes), validatePermissionLevel(attributes), validateReqId(attributes))
.filter(ValidationResult::isFailure).map { obj: ValidationResult -> obj.getMessage() }.collect(Collectors.joining(","))
Expand All @@ -69,14 +72,14 @@ abstract class UAttributesValidator {
*/
fun isExpired(uAttributes: UAttributes): Boolean {
val ttl = uAttributes.ttl
val maybeTime = UuidUtils.getTime(uAttributes.id)
val maybeTime = uAttributes.id.getTime()

// if the message does not have a ttl or the original time is not present or the ttl is less than 0
if (!uAttributes.hasTtl() || maybeTime.isEmpty || ttl <= 0) {
if (!uAttributes.hasTtl() || maybeTime==null || ttl <= 0) {
return false
}
// the original time plus the ttl is less than the current time, the message has expired
return (maybeTime.get() + ttl) < System.currentTimeMillis();
return (maybeTime + ttl) < System.currentTimeMillis()
}

/**
Expand Down Expand Up @@ -104,7 +107,7 @@ abstract class UAttributesValidator {
*/
open fun validateSink(attributes: UAttributes): ValidationResult {
return if (attributes.hasSink()) {
UriValidator.validate(attributes.sink)
attributes.sink.validate()
} else {
ValidationResult.success()
}
Expand Down Expand Up @@ -154,7 +157,7 @@ abstract class UAttributesValidator {
* @return Returns a [ValidationResult] that is success or failed with a failure message.
*/
open fun validateReqId(attributes: UAttributes): ValidationResult {
return if (attributes.hasReqid() && !UuidUtils.isUuid(attributes.reqid)) {
return if (attributes.hasReqid() && !attributes.reqid.isUuid()) {
ValidationResult.failure("Invalid UUID")
} else {
ValidationResult.success()
Expand Down Expand Up @@ -226,7 +229,7 @@ abstract class UAttributesValidator {
override fun validateSink(attributes: UAttributes): ValidationResult {
return if (!attributes.hasSink()) {
ValidationResult.failure("Missing Sink")
} else UriValidator.validateRpcMethod(attributes.sink)
} else attributes.sink.validateRpcMethod()
}

/**
Expand Down Expand Up @@ -278,7 +281,7 @@ abstract class UAttributesValidator {
if (!attributes.hasSink() || attributes.sink === UUri.getDefaultInstance()) {
return ValidationResult.failure("Missing Sink")
}
return UriValidator.validateRpcResponse(attributes.sink)
return attributes.sink.validateRpcResponse()
}

/**
Expand All @@ -291,7 +294,7 @@ abstract class UAttributesValidator {
if (!attributes.hasReqid() || attributes.reqid === UUID.getDefaultInstance()) {
return ValidationResult.failure("Missing correlationId")
}
return if (!UuidUtils.isUuid(attributes.reqid)) {
return if (!attributes.reqid.isUuid()) {
ValidationResult.failure(String.format("Invalid correlationId [%s]", attributes.reqid))
} else {
ValidationResult.success()
Expand Down
6 changes: 3 additions & 3 deletions src/main/kotlin/org/eclipse/uprotocol/uri/README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,16 @@ val uri = uUri {
=== Validating
[,kotlin]
----
val status:ValidationResult = UriValidator.validateRpcMethod(uuri)
val status:ValidationResult = uuri.validateRpcMethod()
assertTrue(status.isSuccess())
----

=== Serializing & Deserializing
[,kotlin]
----
val uri: UUri = .../* UUri example above */
val micro: ByteArray = MicroUriSerializer.instance().serialize(uri)
val long: String = LongUriSerializer.instance().serialize(uri)
val micro: ByteArray = MicroUriSerializer.INSTANCE.serialize(uri)
val long: String = LongUriSerializer.INSTANCE.serialize(uri)
val uri2: UUri = UriSerializer.buildResolved(long, micro)
assertTrue(uri.equals(uri2))
----
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ package org.eclipse.uprotocol.uri.factory
import com.google.protobuf.ProtocolMessageEnum
import org.eclipse.uprotocol.v1.UResource
import org.eclipse.uprotocol.v1.uResource
import java.util.*


object UResourceBuilder {
Expand Down
Loading

0 comments on commit a916d48

Please sign in to comment.