Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat:Support Bytes to UUID UDF Function #9640

Merged
merged 10 commits into from
Oct 20, 2022
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
import io.confluent.ksql.function.FunctionCategory;
import io.confluent.ksql.function.udf.Udf;
import io.confluent.ksql.function.udf.UdfDescription;
import io.confluent.ksql.function.udf.UdfParameter;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;

@UdfDescription(
name = "UUID",
Expand All @@ -31,4 +34,20 @@ public class Uuid {
public String uuid() {
return java.util.UUID.randomUUID().toString();
}

@Udf
public String uuid(@UdfParameter final ByteBuffer bytes) {
if (bytes == null || bytes.capacity() != 16) {
return null;
}

try {
final long firstLong = bytes.getLong();
final long secondLong = bytes.getLong();

return new java.util.UUID(firstLong, secondLong).toString();
} catch (BufferUnderflowException ex) {
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@

package io.confluent.ksql.function.udf.string;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
import org.junit.Before;
import org.junit.Test;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class UuidTest {

Expand Down Expand Up @@ -59,4 +59,34 @@ public void shouldHaveCorrectOutputFormat() {
}
}

@Test
public void nullValueShouldReturnNullValue() {
final String uuid = udf.uuid(null);

assertThat(uuid, is(nullValue()));
}

@Test
public void invalidCapacityShouldReturnNullValue() {
final ByteBuffer bytes = ByteBuffer.wrap(new byte[17]);

final String uuid = udf.uuid(bytes);

assertThat(uuid, is(nullValue()));
}

@Test
public void shouldReturnCorrectOutputFormat() {
// aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
final String anUuid = udf.uuid();

final java.util.UUID uuid = java.util.UUID.fromString(anUuid);
final ByteBuffer bytes = ByteBuffer.wrap(new byte[16]);
bytes.putLong(uuid.getMostSignificantBits());
bytes.putLong(uuid.getLeastSignificantBits());
byte[] byteArrays = bytes.array();

final String toUuid = udf.uuid(ByteBuffer.wrap(byteArrays));
assertThat(toUuid, is(anUuid));
}
}