Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

March Developer Challenge - CloudEvents: Week 2

ajmaradiaga
Developer Advocate
Developer Advocate
5,427

As we learned last week, CloudEvents is a specification for describing event data in common formats and the goal is to provide interoperability across services, platforms and systems. This week we will expand on what we learnt last week and we will create our first CloudEvent programmatically.

Links to March's developer challenge:

CloudEvent format

Event Formats specify how to serialize a CloudEvent with certain encoding formats. Depending on our requirements it is possible that we might need to use a specific format to encode our CloudEvent message. Maybe we have a requirement where we need to send the data in something different than the JSON format, e.g. AVRO, Protobuf. Check out the specification document if you want to learn more about these different formats.

For simplicity purposes we will stick to the JSON Event format as it is the most common and easiest to interact with.

Now that we are familiar with what a CloudEvent is, what a CloudEvent message looks like, and the different Event Formats available, let's see how we can create one programmatically.

CloudEvents SDK

There are language-specific SDKs that can be used to create a message that complies with the CloudEvents standard. Below is a list of the different languages that there's an SDK for:

You might be thinking, why would I need an SDK when I can create the message "manually" as well? Using an SDK allows us to easily create a CloudEvent message, ensure that it follows the guidelines defined in the standard, and simplify generating the output format. Not only that but it can also be used to parse a CloudEvent message that our application consumes. As an example, I will use the Python SDK to create the CloudEvent message for the Ticket Management System that I used as an example previously.

 

 

from cloudevents.http import CloudEvent
from cloudevents.conversion import to_binary
import requests

ticket_id = "IT00010232"

# Create a CloudEvent
attributes = {
    "type": "com.ajmaradiaga.tms.Ticket.Created.v1",
    "source": "https://tms-prod.ajmaradiaga.com/tickets",
    "subject": ticket_id,
}
data = { 
    "ID": ticket_id,
    "Description": "Install ColdTurkey to block distracting websites.",
    "Urgency": {
      "ID": 1,
      "Description": "High"
    }
  }
event = CloudEvent(attributes, data)

# Creates the HTTP request representation of the CloudEvent in binary content mode
headers, body = to_binary(event)

print(body)

 

 

Week 2 challenge - Create a CloudEvent using an SDK

👉 Your task for this week is: Pick your favourite language from the list above and create the message that you shared as part of week's 1 challenge but this time instead of doing it manually, you will do it using an SDK. To complete this week's challenge, share the code you used to create the CloudEvent message and a screenshot of your program's output.

What if there is no SDK available for your favourite language? Not a problem, you can create the message structure "manually". Just share the code used to generate a message in your programming language and a screenshot of the program's output.

35 REPLIES 35

ajmaradiaga
Developer Advocate
Developer Advocate
5,424

Using as a reference my solution for week 1, I will use the CloudEvents Python SDK.

Code

 

import json

from cloudevents.conversion import to_structured
from cloudevents.http import CloudEvent
import requests

# Create a CloudEvent
# - The CloudEvent "id" is generated if omitted. "specversion" defaults to "1.0".
attributes = {
    "type": "com.ajmaradiaga.tms.Ticket.Created.v1",
    "source": "https://tms-prod.ajmaradiaga.com/tickets",
}
data = {
    "id": "IT00010232",
    "description": "Install ColdTurkey to block distracting websites.",
    "urgency": {
        "id": 1,
        "description": "High"
    }
}
event = CloudEvent(attributes, data)

# Creates the HTTP request representation of the CloudEvent in structured content mode
headers, body = to_structured(event)

print(headers)

json_body = json.loads(body)

# Pretty print json
print(json.dumps(json_body, indent=2))

 

Screenshot of the program running

Week 2 solutionWeek 2 solution

 

r00k13d3v
Participant
5,338

Here is my submission 🖖

Code JS:

const { CloudEvent, HTTP } = require("cloudevents");

const ce = new CloudEvent({
    specversion: "1.0",
    type: "com.example.iot.device.event.v1",
    source: "https://iot-prod.example.com/devices",
    subject: "device12345-temperature-alert",
    id: "e241f360-4b3f-4c9b-a5e4-d35456b27f62",
    time: "2024-03-06 08:34:00",
    datacontenttype: "application/json",
    data: {
        device_id: "Device12345",
        event_type: "temperature-alert",
        description: "Temperature threshold exceeded.",
        data: {
            temperature: 75,
            threshold: 70,
            units: "Celsius",
        },
    },
});

const { headers, body } = HTTP.structured(ce);

console.log("Headers:");
console.log(JSON.stringify(headers, null, 2) + "\n");

console.log("Body:");
console.log(JSON.stringify(JSON.parse(body), null, 2) + "\n");

 Result:

r00k13d3v_0-1710256792872.png

 

5,201

Code PWS:

 

$cloudEvent = New-CloudEvent `
    -Type 'com.example.iot.device.event.v1' `
    -Source 'https://iot-prod.example.com/devices' `
    -Id 'e241f360-4b3f-4c9b-a5e4-d35456b27f62' `
    -Time '2024-03-06 08:34:00' `

$cloudEvent | Set-CloudEventJsonData -Data @{
    specversion = "1.0"
    type = "com.example.iot.device.event.v1"
    source = "https://iot-prod.example.com/devices"
    subject = "device12345-temperature-alert"
    id = "e241f360-4b3f-4c9b-a5e4-d35456b27f62"
    time = "2024-03-06 08:34:00"
    datacontenttype = "application/json"
    data = @{
        device_id = "Device12345"
        event_type = "temperature-alert"
        description = "Temperature threshold exceeded."
        data = @{
            temperature = 75
            threshold = 70
            units = "Celsius"
        }
    }
} > $null

$cloudEventStructuredHttpMessage = $cloudEvent | ConvertTo-HttpMessage -ContentMode Structured

Write-Host
Write-Host "Headers:" -ForegroundColor Green
$cloudEventStructuredHttpMessage.Headers

Write-Host
Write-Host "Body:" -ForegroundColor Green
Read-CloudEventData -CloudEvent $cloudEvent

 

  Result:

r00k13d3v_1-1710275852344.png

 

 

5,157

@r00k13d3v Absolutely love this.... it never crossed my mind that someone would share something using the Powershell SDK... AMAZING!

4,899

I don't want to lie... I tried because it's something that blows my mind, 🤣

Alpesa1990
Participant
5,272

My reference for week 1:

https://community.sap.com/t5/application-development-discussions/march-developer-challenge-cloudeven...

 

My JS code:

const { CloudEvent, HTTP} = require("cloudevents");

// Create a new CloudEvent
const ce = new CloudEvent({ 
  "specversion": "1.0",
  "id": "62706ed3-3f4c-4a48-a2e7-8f201301822b",
  "type": ".com.alpesadevcha.v1",
  "source": "/alpesadev/test",
  "time": "2024-03-07T08:00:00Z",
  "datacontenttype": "application/json",
  "data": {
    "employee": "80001000"
    }
}); 

//
const { headers, body } = HTTP.structured(ce);

console.log(
   "Headers:", "\n",
    JSON.stringify(headers, null, 2), "\n",
    "Body:", "\n",
    JSON.stringify(JSON.parse(body), null, 2));

Output:

Headers: 
 {
  "content-type": "application/cloudevents+json; charset=utf-8"
}
 Body:
 {
  "id": "62706ed3-3f4c-4a48-a2e7-8f201301822b",
  "time": "2024-03-07T08:00:00.000Z",
  "type": ".com.alpesadevcha.v1",
  "source": "/alpesadev/test",
  "specversion": "1.0",
  "datacontenttype": "application/json",
  "data": {
    "employee": "80001000"
  }
}

emiliocampo
Explorer
5,246

My previous solution Week 1

Code

emiliocampo_0-1710267937855.png

Screenshot

emiliocampo_1-1710268001074.png

 

0 Kudos
5,155

@emiliocampo Thanks for sharing the to_binary representation, so others can see what the difference is when outputting to_structured and to_binary. Great example!

PriyankaChak
Active Contributor
5,095

Screenshot 2024-03-13 at 5.05.46 PM.png

 

from cloudevents.conversion import to_structured
from cloudevents.http import CloudEvent
import json

attributes = {
    "type": "com.servicechannel.WorkOrder.Created.v1",
    "source": "https://test.servicechannel.com/workorders",
}
data = {
        "purchaseNumber": "84409626",
        "status": {
            "primary": "open"
        }
    }
event = CloudEvent(attributes, data)

headers, body = to_structured(event)
print(f"Content-Type: {headers['content-type']}\n")
json_body = json.loads(body)
print(f"Sample Cloud Event: \n{json.dumps(json_body, indent=2)}")

 

xavisanse
Active Participant
4,994

 

//Importing Cloud Event libraries.

const { CloudEvent, HTTP } = require("cloudevents");

const type = "com.awesome_company.sales_order.Updated.v1"
const source = "https://prod.illidian.awesome_company.com/sales_orders" 
const salesOrderID = "9024000013"
const company = "AWO01"
const year = 2024
const statusSO = "Shipped"

const subject = company + salesOrderID + year

const data = {
    "salesOrder": salesOrderID,
    "company": company,
    "year": year,
    "status": statusSO
}

//creating and calling event

const soEvent = new CloudEvent({type,source,subject,data})

const { headers, body } = HTTP.structured(soEvent);

//print the log

console.log("### March Developer Challenge - CloudEvents: Week 2 ###\n");
console.log("- HTTP Event Headers - \n")
for (const key in headers) {
    console.log(`Key: "${key}", Value: "${headers[key]}"`);
  }

console.log("\n - HTTP Event Body - \n");
console.log(JSON.stringify(JSON.parse(body), null, 1) + "\n");

JS!

 

xavisanse_1-1710345603047.png

 

 

Dan_Wroblewski
Developer Advocate
Developer Advocate
4,982

Dan_Wroblewski_0-1710347944337.png

Dan_Wroblewski_1-1710348024650.png

 

 




--------------
See all my blogs and connect with me on Twitter / LinkedIn

fjaviergar07
Participant
4,881

Why not creating the CloudEvent in Groovy if we want to use Integration Suite for that?

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap
import java.text.SimpleDateFormat

def Message processData(Message message) {

    //read properties
        def properties = message.getProperties()
        specversion = properties.get("specversion")
        type = properties.get("type")
        source = properties.get("source")
        id = properties.get("id")

    //create timestamp
        def date = new Date()
        def sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

    //read data from body

        def data = message.getBody(String)

    //create CloudEvent

        message.setBody("{\r\n\"specversion\": \"" + specversion +"\",\r\n\"type\": \""+ type +"\",\r\n\"source\": \""+ source +"\",\r\n\"id\": \""+ id +"\",\r\n\"time\": \""+ sdf.format(date) +"\",\r\n\"datacontenttype\": \"application/json\",\r\n\"data\":" + data + "}")
    return message
    
}

fjaviergar07_0-1710365990244.png

 

ceedee666
Active Contributor
4,736
import json

from cloudevents.conversion import to_json
from cloudevents.http import CloudEvent

attributes = {
    "type": "sap.s4.beh.productionorder.v1.ProductionOrder.Created.v1",
    "source": "https://m32z.ucc.ovgu.de/",
}

data = {
    "ProductionOrder": "1000206",
    "ProductionOrderType": "PP01",
    "ProductionPlant": "HD00",
}

event = CloudEvent(attributes, data)
print(json.dumps(json.loads(to_json(event)), indent=2))

CleanShot 2024-03-14 at 10.27.47.png

pamoli_banerjee
Explorer
4,730

Hello , 

Here is my Week1 response.

Below is my JS code to populate the same Cloud Event :

 

const { CloudEvent, HTTP } = require("cloudevents");
const CloudEvent = new CloudEvent({
  type: "com.example.iot.device.event.v1",
  specversion: "1.0",
  source: "/default/sap.s4.beh/SXXXXXX",
  id: "a590d392-80be-1ede-a598-d34338408017",
  time: "2023-12-07T06:05:25Z",
  datacontenttype: "application/json",
  data: {
    SalesOrder: "9999",
    EventRaisedDateTime: "2023-12-07T06:05:19.578802Z",
    SalesOrderType: "TA",
    SalesOrganization: "1710",
    DistributionChannel: "10",
    OrganizationDivision: "00",
    SoldToParty: "17100001",
  },
});
const { body } = HTTP.structured(CloudEvent);
console.log(JSON.stringify(JSON.parse(body), null, 2) + "\n");
 
 
Here is the output : 
pamoli_banerjee_0-1710409541010.png

 

SyambabuAllu
Contributor
4,722

Here is my submission

const { CloudEvent, HTTP } = require("cloudevents");

const ce = new CloudEvent({
    specversion: "1.0",
    type: "sap.s4.beh.centralrequestforquotation.v1.CentralRequestForQuotation.SuccssrDocCrted.v1",
    source: "/default/sap.s4.beh/s4hc",
    id: "QgEK7wzuHtqdeJwqCS+VOA==",
    time: "2024-03-11T13:00:00Z",
    datacontenttype: "application/json",
    data: {
        CentralRequestForQuotation: "7500000012"
    },
});

const { headers, body } = HTTP.structured(ce);

console.log("Headers:");
console.log(JSON.stringify(headers, null, 2) + "\n");

console.log("Body:");
console.log(JSON.stringify(JSON.parse(body), null, 2) + "\n");

 

Headers:
{
  "content-type": "application/cloudevents+json; charset=utf-8"
}

Body:
{
  "id": "QgEK7wzuHtqdeJwqCS+VOA==",
  "time": "2024-03-11T13:00:00.000Z",
  "type": "sap.s4.beh.centralrequestforquotation.v1.CentralRequestForQuotation.SuccssrDocCrted.v1",
  "source": "/default/sap.s4.beh/s4hc",
  "specversion": "1.0",
  "datacontenttype": "application/json",
  "data": {
    "CentralRequestForQuotation": "7500000012"
  }
}

ajos
Explorer

Ruthiel
Product and Topic Expert
Product and Topic Expert
4,642

This is the reference for my week 1 proposal:

Ruthiel_0-1710425710926.png

 

amitcruz
Participant
4,546

Here is my submission for Week 2:

amitcruz_0-1710479186891.png

 

 

tobiasz_h
Active Participant
4,475

Hello,

My solution for week 1: week-1-solution , I will use python sdk

Code:

import json

from cloudevents.conversion import to_structured
from cloudevents.http import CloudEvent


# Create a CloudEvent
# - The CloudEvent "id" is generated if omitted. "specversion" defaults to "1.0".
attributes = {
    "type": "sap.s4.beh.product.v1.Product.Changed.v1",
    "source": "../dictionary",
    "subject": "productId:123",
}
data = {
    "Product": "123",
    "ProductCategory": "TELE",
    "ProductType": "LCD"
}
event = CloudEvent(attributes, data)

# Creates the HTTP request representation of the CloudEvent in structured content mode
headers, body = to_structured(event)

print("headers:")
print(headers)
print()


json_body = json.loads(body)

# Pretty print json
print("body:")
print(json.dumps(json_body, indent=2))

Screenshot of the output:

tobiasz_h_0-1710501791501.png

 

NoeJC
Explorer
4,440

Here is my submission for Week 2:

NoeJC_0-1710506990023.png

Here is the output,

NoeJC_1-1710507026851.png

 

thomas_jung
Developer Advocate
Developer Advocate
4,399

I used the Rust SDK (although I'm a little rusty 😉😞

 

use cloudevents::{EventBuilder, EventBuilderV10};
use serde_json::json;
use http::request::Request;
use std::str;
use chrono::Utc;

fn main() {
    let now = Utc::now().to_rfc3339();
    let event = EventBuilderV10::new()
        .id("A234-1234-1234")
        .source("/myapp/resources/1234567890")
        .ty("com.example.myapp.resource.created")
        .time(now)
        .data(
            "application/json",
            json!({
                "resourceId": "1234567890",
                "resourceName": "My Resource",
                "resourceType": "myapp.com/resources"
            }),
        )
        .build()
        .unwrap();

    // Convert the event to a HTTP representation in binary content mode
    let http_request = Request::builder()
        .method("POST")
        .uri("http://example.com")
        .header("ce-specversion", "1.0")
        .header("ce-type", "com.example.myapp.resource.created")
        .header("ce-source", "/myapp/resources/1234567890")
        .header("ce-id", "A234-1234-1234")
        .header("ce-time", "2023-03-05T18:00:00Z")
        .header("Content-Type", "application/json")
        .body(serde_json::to_vec(&event).unwrap())
        .unwrap();

    // Print out the HTTP request
    println!("HTTP Method: {}", http_request.method());
    println!("URI: {}", http_request.uri());
    for (key, value) in http_request.headers() {
        println!("Header: {}={}", key, value.to_str().unwrap());
    }
    println!("Body: {}", str::from_utf8(http_request.body()).unwrap());
}

 

The results:

2024-03-15_13-56-25.png

4,371

Here's a solution in C#

 

using CloudNative.CloudEvents;
using CloudNative.CloudEvents.Http;
using CloudNative.CloudEvents.NewtonsoftJson;
using System.Net.Mime;
using Newtonsoft.Json;

namespace CloudEventsApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            DateTime currentTimeUtc = DateTime.UtcNow;
            var cloudEvent = new CloudEvent
            {
                Id = "A234-1234-1234",
                Type = "com.example.myapp.resource.created",
                Source = new Uri("urn:/myapp/resources/1234567890"),
                Time = currentTimeUtc, //DateTime.Parse("2023-03-05T18:00:00Z").ToUniversalTime(),
                DataContentType = MediaTypeNames.Application.Json,
                Data = JsonConvert.SerializeObject(new
                {
                    resourceId = "1234567890",
                    resourceName = "My Resource",
                    resourceType = "myapp.com/resources"
                })
            };

            var httpClient = new HttpClient();
            var content = cloudEvent.ToHttpContent(ContentMode.Structured, new JsonEventFormatter());

            foreach (var header in content.Headers)
            {
                Console.WriteLine($"Header: {header.Key}={string.Join(", ", header.Value)}");
            }
             string contentString = await content.ReadAsStringAsync();
            Console.WriteLine(contentString);
           
            //If you want to acatually send the request
            //var result = await httpClient.PostAsync(Url, content);
            // Console.WriteLine($"Response status code: {response.StatusCode}");           

        }
    }
}
​

 

2024-03-15_16-52-12.png

0 Kudos
4,129

Thanks for sharing this. It is great to see solutions in programming languages different from the usual suspects :-).

Nagarajan-K
Explorer
4,389
const { HTTP, CloudEvent } = require('cloudevents');

// Create a new CloudEvent
const ce = new CloudEvent({
    "specversion": "1.0",
    "type": "com.nk.cloudevents.PurchaseOrder.Created.v1",
    "source": "https://cloudevents.nk.com/PO",
    "subject": "New PO 4500000001 Created",
    "id": "b93ac0f9-86e8-4d85-bbdd-6da5e474ba1d",
    "time": "2024-03-15 07:10:00",
    "datacontenttype": "application/json",
    "data": {
        "PurchaseOrder": "4500000001",
        "POType": "NB",
        "POOrg": "1000"
    }
})

const binaryMessage = HTTP.binary(ce);
const structuredMessage = HTTP.structured(ce);

console.log(ce.toJSON())
console.log('--------------BINARY MESSAGE--------------------')
console.log(binaryMessage)
console.log('------------STRUCTURED MESSAGE----------------------')
console.log(structuredMessage)

Output

NagarajanK_0-1710528238701.png

 

spassaro
Participant
4,202
const { HTTP, CloudEvent } = require("cloudevents");



const ce = new CloudEvent({
    "type": "sap.s4.beh.purchaserequisition.v1.PurchaseRequisition.Changed.v1",
    "specversion": "1.0",
    "source": "nedgia/eventmeshdev/dev",
    "id": "AA06tkhWHt6FoCOmSZ/6+Q==",
    "time": "2023-06-27T15:40:17Z",
    "datacontenttype": "application/json",
    "data": {
    "PurchaseRequisition": "60004767"
    }
    });
const message = HTTP.structured(ce)

console.log(message)

 

 

spassaro_0-1710605551977.png

 

MatLakaemper
Participant
4,095

----------------------------------------------------------------------------------------------------------------
Node-Js:
----------------------------------------------------------------------------------------------------------------

 


------Source


const { CloudEvent, HTTP} = require("cloudevents");

const ce = new CloudEvent(
    {
        "type": "sap-business-One-fake",
        "specversion": "1.0",
        "source": "/default/sap.s4.beh/244572008",
        "id": "63d6a150-c6a1-4c5b-bcc3-27d90c07941c",
        "time": "2024-02-26T10:53:06Z",
        "datacontenttype": "application/json",
        "data": {
            "BusinessPartner": "Rübennase",
            "Theme": "Life of Brian"
        }
    }
);

const { headers, body } = HTTP.structured(ce);
headers.authorization = "Bearer ...";
console.log(
   "Headers:", "\n",
    JSON.stringify(headers, null, 2), "\n",
    "Body:", "\n",
    JSON.stringify(JSON.parse(body), null, 2));

console.log("Finish") ;

----- Result

MatLakaemper_0-1710662573890.png

----------------------------------------------------------------------------------------------------------------
DotNet c#
----------------------------------------------------------------------------------------------------------------

Source: 

public void generateCloudEvent()
{

dynamic dataObject = new JObject();
dataObject.BusinessPartner = "Rübennase";
dataObject.Theme = "Life of Brian";

string source = "urn:example-com:mysource:abc";
var cloudEvent = new CloudEvent
{
Id = Guid.NewGuid().ToString(),
Time = DateTime.Now,
Type = "sap-business-One-fake",
Source = new Uri(source),
DataContentType = MediaTypeNames.Application.Json,
Data = dataObject // JsonConvert.SerializeObject(dataOjbect)
};
Newtonsoft.Json.JsonSerializer newtonSoftSer = new Newtonsoft.Json.JsonSerializer();
newtonSoftSer.Formatting = Newtonsoft.Json.Formatting.Indented;
var content = cloudEvent.ToHttpContent(ContentMode.Structured, new JsonEventFormatter(newtonSoftSer));
string sContent = content.ReadAsStringAsync().Result;
log.Debug($"Content: {System.Environment.NewLine}{sContent}");

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "..");

httpClient.DefaultRequestHeaders.Add("x-qos", "1");

string sHilf = "udina/portal/ems/mat-queue";
string sEncoded = HttpUtility.UrlEncode(sHilf);

string sEventmeshUrl = $"https://enterprise-messaging-pubsub.cfapps.eu10.hana.ondemand.com/messagingrest/v1/queues/{sEncoded}...";
var eventMeshResult = httpClient.PostAsync(sEventmeshUrl, content).Result;

log.Debug($"Result: {eventMeshResult.StatusCode} ");


}

Result: 

MatLakaemper_1-1710662791102.png

 

 

MarcelloUrbani
Active Contributor
4,018

well, I used an SDK in the first place, so here you go:

// a JSON object was enough, but the idea is learning...
import { CloudEvent, CloudEventV1 } from "cloudevents"
import { v1 } from "uuid"
import Ajv from "ajv"
import schema from "./cloudeventschema.json"

const payload: CloudEventV1<any> = {
  id: v1(),
  specversion: "1.0",
  source: "week1testprog",
  type: "week1testprog.demoevent",
  datacontenttype: "application/json",
  data: {
    salutation: "hello"
  }
}

const msg = new CloudEvent(payload) // basically checks the schema and adds the time

// redundant - check schema
const validator = new Ajv({ strict: false }).compile(schema)
const valid = validator(msg)
if (valid) console.log(JSON.stringify(msg, null, 1))
else throw new Error("Invalid cloud event")

The output includes a bunch of warning from a JSON schema validator. Should be totally redundant but wanted to try it

MarcelloUrbani_0-1710692854837.png

 

0 Kudos
3,977

@MarcelloUrbaniI've seen those format errors before.... You can include the formats by adding them to ajv. You will also need to npm install ajv-formats. See ajv-formats.

 

const Ajv = require('ajv');
const addFormats = require("ajv-formats");

const ajv = new Ajv();
addFormats(ajv);

 

 

dagoca_abapcl
Discoverer
4,009

 

Sending Challenge 2

from cloudevents.http import CloudEvent
from cloudevents.conversion import to_binary
import requests

username = "David"
userLastName = "Gonzalez"
password = "MTIzNA=="
country = "CL"
subject = "Creacion Usuarios" + username

# Create a CloudEvent
attributes = {
    "type": "com.sap.build.app.Launched.v1",
    "source": "https://cloud.dagoca.com/events/spec/pull",
    "subject": subject,
}
data = { 
   "users":[
      {
          "name": username,
          "lastName": userLastName,
          "password": password,
          "country": country

      }  
   ]
  }
event = CloudEvent(attributes, data)

# Creates the HTTP request representation of the CloudEvent in binary content mode
headers, body = to_binary(event)

print(body)

dagoca_abapcl_0-1710694023931.png

 

 

ajmaradiaga
Developer Advocate
Developer Advocate
3,930

A sneak peek at the challenge for week 3.... more details coming tomorrow. Stay tuned 📺!

Week 3 dev challenge data flowWeek 3 dev challenge data flow

 

saitgunacorel
Discoverer
3,879

My answer from last week Re: March Developer Challenge - CloudEvents: Week ... - SAP Community

Event Class:

package com.sait.week2sdk.model;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;

@AllArgsConstructor
@ToString
@Getter
public class OrderUpdatedEvent {
    private String id;
    private String changedBy;
    private String dataUrl;
}

 Test class for creating the Cloud Event and validating the output

@SpringBootTest
class Week2SdkApplicationTests {

    @test
    void cloudEventsCreationTest() throws UnsupportedEncodingException, JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        OrderUpdatedEvent eventToPublish = new OrderUpdatedEvent(
                "OR10001001",
                "TechnicalUser01",
                "https://sales.example.com/api/orders('OR10001001')"
        );

        String eventDataJSON = objectMapper.writeValueAsString(eventToPublish);

        CloudEvent event = CloudEventBuilder.v1()
                .withType("com.example.sales.Order.Updated.v1")
                .withSource(URI.create("https://sales.example.com/orders"))
                .withSubject("OR10001001")
                .withId("fc04acbf-9112-4b5f-8898-ad01f2a18b34")
                .withTime(OffsetDateTime.of(2024, 03, 06, 15, 45, 0, 0, ZoneOffset.UTC))
                .withData("application/json", eventDataJSON.getBytes("UTF-8"))
                .build();

        Assertions.assertEquals(
                eventDataJSON,
                new String(event.getData().toBytes())
        );

        byte[] serializedCloudEvent = EventFormatProvider.getInstance()
                .resolveFormat(JsonFormat.CONTENT_TYPE)
                .serialize(event);

        String cloudEventJson = new String(serializedCloudEvent);
        System.out.println(cloudEventJson);

        Assertions.assertEquals(
                """
                        {"specversion":"1.0","id":"fc04acbf-9112-4b5f-8898-ad01f2a18b34","source":"https://sales.example.com/orders","type":"com.example.sales.Order.Updated.v1","datacontenttype":"application/json","subject":"OR10001001","time":"2024-03-06T15:45:00Z","data":{
                          "id" : "OR10001001",
                          "changedBy" : "TechnicalUser01",
                          "dataUrl" : "https://sales.example.com/api/orders('OR10001001')"
                        }}""",
                cloudEventJson
        );


    }

}

Console output:

saitgunacorel_0-1710755509186.png

 

MioYasutake
Active Contributor
3,820

I used JavaScript SDK:

const { HTTP, CloudEvent } = require("cloudevents");

const ce = new CloudEvent({
    type: "my.bank.account.balanceChange",
    source: "/my/bank/account",
    datacontenttype: "application/json",
    data: {
        "account": "12345678"
    }
});
const message = HTTP.binary(ce);
console.log(message);

Output:

MioYasuatke_0-1710794625896.png

 

spirit2681
Explorer
3,724

Here is my submission:

const { CloudEvent, HTTP } = require("cloudevents");

const ce = new CloudEvent({
  "specversion": "1.0",
  "type": "com.sonal.plm.NPDI.Created.v1",
  "source": "https://plm-prod.sonal.com/npdis",
  "subject": "NPDI000000001",
  "id": "196179a2-6cf1-4166-9975-51f9afdb3a0d",
  "time": "2024-03-06 12:00:00",
  "datacontenttype": "application/json",
  "data": { 
    "id": "NPDI000000001",
    "description": "New Product Development and Introduction Created"
  }
})
const { headers, body } = HTTP.structured(ce);

console.log(
   "Headers:", "\n",
    JSON.stringify(headers, null, 2), "\n",
    "Body:", "\n",
    JSON.stringify(JSON.parse(body), null, 2));

Output: 

spirit2681_0-1710849281848.png

 

geek
Participant
3,551

As an ABAPer have borrowed liberally from other contributors:

const { CloudEvent, HTTP} = require("cloudevents");

// Create a new CloudEvent
const ce = new CloudEvent({ 
  "specversion": "1.0",
  "id": "6caee628-04a1-4565-ae1e-8eb6d4370c96",
  "type": "this.is.made.up.create",
  "source": "/who/knows",
  "time": "2024-03-07T08:00:00Z",
  "datacontenttype": "application/json",
  "data": {
    "number": "987654321"
}
}); 

//
const { headers, body } = HTTP.structured(ce);

console.log(
   "Headers:", "\n",
    JSON.stringify(headers, null, 2), "\n",
    "Body:", "\n",
    JSON.stringify(JSON.parse(body), null, 2));

geek_0-1711042531470.png

 

ajmaradiaga
Developer Advocate
Developer Advocate
0 Kudos
3,295

Interested in learning more about SAP Integration Suite, advanced event mesh? How about you join us in this in-person event that will take place on the 6th of May @ the SAP office in Madrid, Spain - https://community.sap.com/t5/sap-codejam/event-driven-integrations-with-sap-integration-suite-advanc...