io.cloudevents.CloudEvent Java Examples
The following examples show how to use
io.cloudevents.CloudEvent.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KafkaProducerMessageWriterTest.java From sdk-java with Apache License 2.0 | 7 votes |
@ParameterizedTest @MethodSource("binaryTestArguments") void testRequestWithBinary(CloudEvent event, Headers expectedHeaders, byte[] expectedBody) { String topic = "test"; Integer partition = 10; Long timestamp = System.currentTimeMillis(); String key = "aaa"; ProducerRecord<String, byte[]> producerRecord = KafkaMessageFactory .createWriter(topic, partition, timestamp, key) .writeBinary(event); assertThat(producerRecord.topic()) .isEqualTo(topic); assertThat(producerRecord.partition()) .isEqualTo(partition); assertThat(producerRecord.timestamp()) .isEqualTo(timestamp); assertThat(producerRecord.key()) .isEqualTo(key); assertThat(producerRecord.headers()) .containsExactlyInAnyOrder(expectedHeaders.toArray()); assertThat(producerRecord.value()) .isEqualTo(expectedBody); }
Example #2
Source File: CloudEventImplTest.java From sdk-java with Apache License 2.0 | 6 votes |
@Test public void testGetAttributeNames() { CloudEvent event = CloudEventBuilder.v1() .withId(ID) .withType(TYPE) .withSource(SOURCE) .withTime(TIME) .build(); assertThat(event.getAttributeNames()) .containsExactlyInAnyOrder( "specversion", "id", "type", "source", "time" ); }
Example #3
Source File: CloudEventBuilderTest.java From sdk-java with Apache License 2.0 | 6 votes |
@Test void testNewBuilder() { io.cloudevents.core.v1.CloudEventBuilder templateBuilder = CloudEventBuilder.v1() .withId(ID) .withType(TYPE) .withSource(SOURCE) .withData(DATACONTENTTYPE_JSON, DATASCHEMA, DATA_JSON_SERIALIZED) .withSubject(SUBJECT) .withTime(TIME) .withExtension("astring", "aaa") .withExtension("aboolean", "true") .withExtension("anumber", "10"); CloudEvent event = templateBuilder.build(); CloudEvent cloned = templateBuilder.newBuilder().build(); assertThat(cloned).isEqualTo(event); }
Example #4
Source File: CloudEventDeserializerTest.java From sdk-java with Apache License 2.0 | 6 votes |
@Test public void deserializerShouldWork() { String topic = "test"; CloudEvent inEvent = Data.V1_WITH_JSON_DATA; CloudEventDeserializer deserializer = new CloudEventDeserializer(); // Serialize the event first ProducerRecord<Void, byte[]> inRecord = KafkaMessageFactory .createWriter(topic) .writeBinary(inEvent); CloudEvent outEvent = deserializer.deserialize(topic, inRecord.headers(), inRecord.value()); assertThat(outEvent) .isEqualTo(inEvent); }
Example #5
Source File: CloudEventsProvider.java From sdk-java with Apache License 2.0 | 6 votes |
@Override public void writeTo(CloudEvent event, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Optional<String> structuredEncodingFormat = Arrays .stream(annotations) .filter(a -> a.annotationType().equals(StructuredEncoding.class)) .map(a -> ((StructuredEncoding) a).value()) .findFirst(); if (structuredEncodingFormat.isPresent()) { writeStructured( event, structuredEncodingFormat.get(), new RestfulWSMessageWriter(httpHeaders, entityStream) ); } else { writeBinary( event, new RestfulWSMessageWriter(httpHeaders, entityStream) ); } }
Example #6
Source File: PublishTest.java From liiklus with MIT License | 6 votes |
@Test default void testPublish() throws Exception { var envelope = createEnvelope("key".getBytes()); var offsetInfo = publish(envelope); assertThat(offsetInfo) .satisfies(info -> { assertThat(info.getTopic()).as("topic").isEqualTo(getTopic()); assertThat(info.getOffset()).as("offset").isNotNegative(); }); var receivedRecord = subscribeToPartition(offsetInfo.getPartition()) .flatMap(RecordsStorage.PartitionSource::getPublisher) .blockFirst(Duration.ofSeconds(10)); assertThat(receivedRecord.getEnvelope()).as("envelope") .usingComparatorForType(Comparator.comparing(Json::encode), CloudEvent.class) .isEqualToIgnoringGivenFields(envelope, "keyEncoder", "valueEncoder") .satisfies(it -> { assertThat(it.getRawValue()).isInstanceOf(CloudEvent.class); }); assertThat(receivedRecord.getPartition()).as("partition").isEqualTo(offsetInfo.getPartition()); assertThat(receivedRecord.getOffset()).as("offset").isEqualTo(offsetInfo.getOffset()); }
Example #7
Source File: DistributedTracingExtensionTest.java From sdk-java with Apache License 2.0 | 6 votes |
@Test public void parseExtension() { CloudEvent event = CloudEventBuilder.v1() .withId("aaa") .withSource(URI.create("http://localhost")) .withType("example") .withExtension(DistributedTracingExtension.TRACEPARENT, "parent") .withExtension(DistributedTracingExtension.TRACESTATE, "state") .build(); DistributedTracingExtension tracing = ExtensionProvider .getInstance() .parseExtension(DistributedTracingExtension.class, event); assertThat(tracing).isNotNull(); assertThat(tracing.getTraceparent()).isEqualTo("parent"); assertThat(tracing.getTracestate()).isEqualTo("state"); }
Example #8
Source File: CloudEventImplTest.java From sdk-java with Apache License 2.0 | 6 votes |
@Test public void testEqualityV1() { CloudEvent event1 = CloudEventBuilder.v1() .withId(ID) .withType(TYPE) .withSource(SOURCE) .withData(DATACONTENTTYPE_JSON, DATASCHEMA, DATA_JSON_SERIALIZED) .withSubject(SUBJECT) .withTime(TIME) .build(); CloudEvent event2 = CloudEventBuilder.v1() .withId(ID) .withType(TYPE) .withSource(SOURCE) .withData(DATACONTENTTYPE_JSON, DATASCHEMA, DATA_JSON_SERIALIZED) .withSubject(SUBJECT) .withTime(TIME) .build(); assertThat(event1).isEqualTo(event2); }
Example #9
Source File: CloudEventMessageSerializerTest.java From sdk-java with Apache License 2.0 | 6 votes |
@Test public void serializerShouldWork() { String topic = "test"; CloudEvent event = Data.V1_WITH_JSON_DATA; CloudEventMessageSerializer serializer = new CloudEventMessageSerializer(); Headers headers = new RecordHeaders(); MockBinaryMessageWriter inMessage = new MockBinaryMessageWriter(); CloudEventUtils.toVisitable(event).read(inMessage); byte[] payload = serializer.serialize(topic, headers, inMessage); MessageReader outMessage = KafkaMessageFactory.createReader(headers, payload); assertThat(outMessage.getEncoding()) .isEqualTo(Encoding.BINARY); assertThat(outMessage.toEvent()) .isEqualTo(event); }
Example #10
Source File: CloudEventBuilderTest.java From sdk-java with Apache License 2.0 | 5 votes |
@Test void testToV03() { CloudEvent input = CloudEventBuilder.v1() .withId(ID) .withType(TYPE) .withSource(SOURCE) .withData(DATACONTENTTYPE_JSON, DATASCHEMA, DATA_JSON_SERIALIZED) .withSubject(SUBJECT) .withTime(TIME) .withExtension("astring", "aaa") .withExtension("aboolean", "true") .withExtension("anumber", "10") .build(); CloudEvent expected = CloudEventBuilder.v03() .withId(ID) .withType(TYPE) .withSource(SOURCE) .withData(DATACONTENTTYPE_JSON, DATASCHEMA, DATA_JSON_SERIALIZED) .withSubject(SUBJECT) .withTime(TIME) .withExtension("astring", "aaa") .withExtension("aboolean", "true") .withExtension("anumber", "10") .build(); CloudEvent actual = CloudEventBuilder.v03(input).build(); assertThat(expected.getSpecVersion()) .isEqualTo(SpecVersion.V03); assertThat(actual).isEqualTo(expected); }
Example #11
Source File: EventMessageRoundtripTest.java From sdk-java with Apache License 2.0 | 5 votes |
/** * This test doesn't test extensions in event because the CSVFormat doesn't support it * * @param input */ @ParameterizedTest() @MethodSource("io.cloudevents.core.test.Data#allEventsWithoutExtensions") void structuredToMockStructuredMessageToEvent(CloudEvent input) { assertThat(new MockStructuredMessageReader(input, CSVFormat.INSTANCE).toEvent()) .isEqualTo(input); }
Example #12
Source File: KafkaMessageFactoryTest.java From sdk-java with Apache License 2.0 | 5 votes |
@ParameterizedTest() @MethodSource("binaryTestArguments") public void readBinary(Headers headers, byte[] body, CloudEvent event) { MessageReader message = KafkaMessageFactory.createReader(headers, body); assertThat(message.getEncoding()) .isEqualTo(Encoding.BINARY); assertThat(message.toEvent()) .isEqualTo(event); }
Example #13
Source File: BaseTest.java From sdk-java with Apache License 2.0 | 5 votes |
@Test void getEvent() { Response res = getWebTarget().path("getEvent").request().buildGet().invoke(); CloudEvent outEvent = res.readEntity(CloudEvent.class); assertThat(outEvent) .isEqualTo(Data.V1_WITH_JSON_DATA_WITH_EXT_STRING); }
Example #14
Source File: Data.java From sdk-java with Apache License 2.0 | 5 votes |
public static Stream<CloudEvent> v03EventsWithStringExt() { return v03Events().map(ce -> { io.cloudevents.core.v03.CloudEventBuilder builder = CloudEventBuilder.v03(ce); ce.getExtensionNames().forEach(k -> builder.withExtension(k, Objects.toString(ce.getExtension(k)))); return builder.build(); }); }
Example #15
Source File: JsonFormat.java From sdk-java with Apache License 2.0 | 5 votes |
@Override public byte[] serialize(CloudEvent event) throws EventSerializationException { try { return mapper.writeValueAsBytes(event); } catch (JsonProcessingException e) { throw new EventSerializationException(e); } }
Example #16
Source File: JsonSchemaPreProcessorTest.java From liiklus with MIT License | 5 votes |
@SneakyThrows private void preProcess(JsonSchemaPreProcessor processor, CloudEvent<?, ?> cloudEvent) { try { processor.preProcess(new Envelope( "topic", null, __ -> ByteBuffer.wrap("key".getBytes()), cloudEvent, it -> ByteBuffer.wrap(Json.binaryEncode(it)).asReadOnlyBuffer() )).toCompletableFuture().get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { throw e.getCause(); } }
Example #17
Source File: CloudEventDeserializer.java From sdk-java with Apache License 2.0 | 5 votes |
private void assertNodeType(JsonNode node, JsonNodeType type, String attributeName, String desc) throws JsonProcessingException { if (node.getNodeType() != type) { throw MismatchedInputException.from( p, CloudEvent.class, "Wrong type " + node.getNodeType() + " for attribute " + attributeName + ", expecting " + type + (desc != null ? ". " + desc : "") ); } }
Example #18
Source File: CloudEventsProvider.java From sdk-java with Apache License 2.0 | 5 votes |
private <V extends MessageWriter<V, Void> & CloudEventWriter<Void>> void writeStructured(CloudEvent input, String formatString, V visitor) { EventFormat format = EventFormatProvider.getInstance().resolveFormat(formatString); if (format == null) { throw new IllegalArgumentException("Cannot resolve format " + formatString); } writeStructured(input, format, visitor); }
Example #19
Source File: Data.java From sdk-java with Apache License 2.0 | 5 votes |
public static Stream<CloudEvent> v1Events() { return Stream.of( Data.V1_MIN, Data.V1_WITH_JSON_DATA, Data.V1_WITH_JSON_DATA_WITH_EXT, Data.V1_WITH_XML_DATA, Data.V1_WITH_TEXT_DATA ); }
Example #20
Source File: BaseTest.java From sdk-java with Apache License 2.0 | 5 votes |
@Test void getStructuredEvent() { Response res = getWebTarget().path("getStructuredEvent").request().buildGet().invoke(); CloudEvent outEvent = res.readEntity(CloudEvent.class); assertThat(outEvent) .isEqualTo(Data.V1_MIN); assertThat(res.getHeaderString(HttpHeaders.CONTENT_TYPE)) .isEqualTo(CSVFormat.INSTANCE.serializedContentType()); }
Example #21
Source File: CloudEventBuilder.java From sdk-java with Apache License 2.0 | 5 votes |
@Override public CloudEvent build() { if (id == null) { throw createMissingAttributeException("id"); } if (source == null) { throw createMissingAttributeException("source"); } if (type == null) { throw createMissingAttributeException("type"); } return new CloudEventV1(id, source, type, datacontenttype, dataschema, subject, time, this.data, this.extensions); }
Example #22
Source File: MessageWriter.java From sdk-java with Apache License 2.0 | 5 votes |
/** * Write the provided event as structured. * * @param event event to write. * @param format {@link EventFormat} to use to serialize the event. * @return return value at the end of the write process. */ default R writeStructured(CloudEvent event, String format) { GenericStructuredMessageReader message = GenericStructuredMessageReader.from(event, format); if (message == null) { throw new IllegalArgumentException("Format " + format + " not found"); } return message.read((StructuredMessageWriter<R>) this); }
Example #23
Source File: Data.java From sdk-java with Apache License 2.0 | 5 votes |
public static Stream<CloudEvent> v03Events() { return Stream.of( Data.V03_MIN, Data.V03_WITH_JSON_DATA, Data.V03_WITH_JSON_DATA_WITH_EXT, Data.V03_WITH_XML_DATA, Data.V03_WITH_TEXT_DATA ); }
Example #24
Source File: KafkaProducerMessageWriterTest.java From sdk-java with Apache License 2.0 | 5 votes |
@ParameterizedTest @MethodSource("io.cloudevents.core.test.Data#allEventsWithoutExtensions") void testRequestWithStructured(CloudEvent event) { String expectedContentType = CSVFormat.INSTANCE.serializedContentType(); byte[] expectedBuffer = CSVFormat.INSTANCE.serialize(event); String topic = "test"; Integer partition = 10; Long timestamp = System.currentTimeMillis(); String key = "aaa"; ProducerRecord<String, byte[]> producerRecord = StructuredMessageReader .from(event, CSVFormat.INSTANCE) .read(KafkaMessageFactory.createWriter(topic, partition, timestamp, key)); assertThat(producerRecord.topic()) .isEqualTo(topic); assertThat(producerRecord.partition()) .isEqualTo(partition); assertThat(producerRecord.timestamp()) .isEqualTo(timestamp); assertThat(producerRecord.key()) .isEqualTo(key); assertThat(producerRecord.headers()) .containsExactly(new RecordHeader(KafkaHeaders.CONTENT_TYPE, expectedContentType.getBytes())); assertThat(producerRecord.value()) .isEqualTo(expectedBuffer); }
Example #25
Source File: GenericStructuredMessageReader.java From sdk-java with Apache License 2.0 | 5 votes |
/** * Create a generic structured message from a {@link CloudEvent} * * @param event * @param contentType content type to use to resolve the {@link EventFormat} * @return null if format was not found, otherwise returns the built message */ @Nullable public static GenericStructuredMessageReader from(CloudEvent event, String contentType) { EventFormat format = EventFormatProvider.getInstance().resolveFormat(contentType); if (format == null) { return null; } return from(event, format); }
Example #26
Source File: Data.java From sdk-java with Apache License 2.0 | 5 votes |
public static Stream<CloudEvent> v1EventsWithStringExt() { return v1Events().map(ce -> { io.cloudevents.core.v1.CloudEventBuilder builder = CloudEventBuilder.v1(ce); ce.getExtensionNames().forEach(k -> builder.withExtension(k, Objects.toString(ce.getExtension(k)))); return builder.build(); }); }
Example #27
Source File: SubscribeTest.java From liiklus with MIT License | 5 votes |
@Test default void testSubscribeWithLatest() throws Exception { var key = UUID.randomUUID().toString().getBytes(); var offsetInfos = publishMany(key, 5); var partition = offsetInfos.get(0).getPartition(); var disposeAll = DirectProcessor.<Boolean>create(); try { var recordsSoFar = new ArrayList<RecordsStorage.Record>(); var assigned = new AtomicBoolean(false); subscribeToPartition(partition, "latest") .doOnNext(__ -> assigned.set(true)) .flatMap(RecordsStorage.PartitionSource::getPublisher) .takeUntilOther(disposeAll) .subscribe(recordsSoFar::add); await.untilTrue(assigned); var envelope = createEnvelope(key); var offsetInfo = publish(envelope); await.untilAsserted(() -> { assertThat(recordsSoFar) .hasSize(1) .allSatisfy(it -> { assertThat(it.getEnvelope()).as("envelope") .usingComparatorForType(Comparator.comparing(Json::encode), CloudEvent.class) .isEqualToIgnoringGivenFields(envelope, "keyEncoder", "valueEncoder"); assertThat(it.getPartition()).as("partition").isEqualTo(offsetInfo.getPartition()); assertThat(it.getOffset()).as("offset").isEqualTo(offsetInfo.getOffset()); }); }); } finally { disposeAll.onNext(true); } }
Example #28
Source File: BaseCloudEventBuilder.java From sdk-java with Apache License 2.0 | 5 votes |
@Override public CloudEvent end() { try { return build(); } catch (Exception e) { throw CloudEventRWException.newOther(e); } }
Example #29
Source File: CloudEventUtils.java From sdk-java with Apache License 2.0 | 5 votes |
/** * Convert a {@link CloudEvent} to a {@link CloudEventReader}. This method provides a default implementation * for CloudEvent that doesn't implement CloudEventVisitable * * @param event the event to convert * @return the visitable implementation */ public static CloudEventReader toVisitable(CloudEvent event) { if (event instanceof CloudEventReader) { return (CloudEventReader) event; } else { return new CloudEventReaderAdapter(event); } }
Example #30
Source File: BaseCloudEventBuilder.java From sdk-java with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public BaseCloudEventBuilder(CloudEvent event) { this.self = (SELF) this; this.setAttributes(event); this.data = event.getData(); this.extensions = new HashMap<>(); for (String k : event.getExtensionNames()) { this.extensions.put(k, event.getExtension(k)); } }