Each technology features compilable, native syntax examples that can be copied or run directly on the online IDE.
Extracts payload and appends attachment to message log.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
def body = message.getBody(java.lang.String) as String;
def messageLog = messageLogFactory.getMessageLog(message);
if(messageLog != null) {
messageLog.addAttachmentAsString("Log", body, "text/plain");
}
return message;
}
Catches camel routing errors and logs stack traces.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
def ex = message.getProperty("CamelExceptionCaught");
if (ex != null) {
message.setProperty("ErrorSummary", ex.getMessage());
}
return message;
}
Injects dynamic correlation headers into exchange.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
message.setHeader("X-Correlation-ID", java.util.UUID.randomUUID().toString());
return message;
}
Stores routing status in pipeline exchange properties.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
def amount = message.getProperty("OrderAmount") ?: "0";
message.setProperty("IsHighPriority", (amount.toInteger() > 5000).toString());
return message;
}
Parses incoming JSON and injects verified timestamp.
import com.sap.gateway.ip.core.customdev.util.Message;
import groovy.json.JsonSlurper;
import groovy.json.JsonBuilder;
def Message processData(Message message) {
def json = new JsonSlurper().parseText(message.getBody(String));
json.processedAt = new Date().format("yyyy-MM-dd HH:mm:ss");
message.setBody(new JsonBuilder(json).toString());
return message;
}
Extracts specific node values from XML payloads.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
def root = new XmlSlurper().parseText(message.getBody(String));
message.setProperty("OrderID", root.Header.OrderID.text());
return message;
}
Cleans prefix namespaces from XML strings.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
String clean = message.getBody(String).replaceAll("xmlns.*?(\"|\\').*?(\"|\\')", "");
message.setBody(clean);
return message;
}
Computes future due dates using TimeCategory.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
use(groovy.time.TimeCategory) {
message.setProperty("DueDate", (new Date() + 30.days).format("yyyy-MM-dd"));
}
return message;
}
Halts iFlow processing if required fields are missing.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
if (!message.getBody(String)) {
throw new Exception("Payload cannot be empty");
}
return message;
}
Encodes message payload into Base64 format.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
String enc = message.getBody(String).bytes.encodeBase64().toString();
message.setBody(enc);
return message;
}
Decodes incoming Base64 payload into plain text.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
byte[] dec = message.getBody(String).decodeBase64();
message.setBody(new String(dec));
return message;
}
Converts comma-separated rows into JSON array.
import com.sap.gateway.ip.core.customdev.util.Message;
import groovy.json.JsonBuilder;
def Message processData(Message message) {
def lines = message.getBody(String).readLines();
def headers = lines[0].split(",");
def data = lines[1..-1].collect { line ->
def vals = line.split(",");
[headers, vals].transpose().collectEntries();
};
message.setBody(new JsonBuilder(data).toString());
return message;
}
Pauses pipeline execution thread safely.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
sleep(1000);
return message;
}
Provides safe defaults when headers are missing.
import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
def sender = message.getHeader("SenderSystem") ?: "DEFAULT_ERP";
message.setProperty("ResolvedSender", sender);
return message;
}
Gracefully terminates iFlow branch execution.
import com.sap.gateway.ip.core.customdev.util.Message;
import com.sap.it.api.exception.IgnoreMessageException;
def Message processData(Message message) {
if (message.getProperty("Skip") == "true") {
throw new IgnoreMessageException();
}
return message;
}
Standard entry point and output stream.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Iterates through an array to determine highest value.
public class Main {
public static void main(String[] args) {
int[] numbers = {14, 82, 3, 99, 45};
int max = numbers[0];
for (int num : numbers) {
if (num > max) max = num;
}
System.out.println("Maximum: " + max);
}
}
Checks if a string reads identically in reverse.
public class Main {
public static void main(String[] args) {
String str = "radar";
String rev = new StringBuilder(str).reverse().toString();
System.out.println(str + " is palindrome: " + str.equalsIgnoreCase(rev));
}
}
Computes the first N numbers in the Fibonacci sequence.
public class Main {
public static void main(String[] args) {
int n = 8, a = 0, b = 1;
System.out.print("Fibonacci: ");
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}
Iterates and manages elements with ArrayList.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Java"); list.add("Python"); list.add("C++");
list.forEach(item -> System.out.println("Course: " + item));
}
}
Associative dictionary mappings in Java.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 100); map.put("B", 200);
System.out.println("Value of A: " + map.get("A"));
}
}
Filters and transforms lists using Java Streams.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> squares = nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println("Even Squares: " + squares);
}
}
Demonstrates classes and getters/setters.
class Employee {
private String name;
public Employee(String name) { this.name = name; }
public String getName() { return this.name; }
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee("Alice");
System.out.println("Employee: " + emp.getName());
}
}
Implements interface contracts across classes.
interface Shape { double area(); }
class Circle implements Shape {
double r;
Circle(double r) { this.r = r; }
public double area() { return Math.PI * r * r; }
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle(5.0);
System.out.println("Circle Area: " + s.area());
}
}
Catches arithmetic exceptions safely.
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error Caught: Division by zero");
} finally {
System.out.println("Execution completed.");
}
}
}
Validates alphanumeric strings via regex.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String pattern = "^[A-Z0-9]+$";
boolean valid = Pattern.matches(pattern, "CODE123");
System.out.println("Is Alphanumeric: " + valid);
}
}
Encodes and decodes standard string bytes.
import java.util.Base64;
public class Main {
public static void main(String[] args) {
String original = "SecureCredentials";
String encoded = Base64.getEncoder().encodeToString(original.getBytes());
String decoded = new String(Base64.getDecoder().decode(encoded));
System.out.println("Encoded: " + encoded + " | Decoded: " + decoded);
}
}
Launches background concurrent threads.
public class Main {
public static void main(String[] args) {
Thread t = new Thread(() -> System.out.println("Worker thread executing"));
t.start();
System.out.println("Main thread executing");
}
}
Executes generic type-safe methods.
public class Main {
public static <T> void printElement(T elem) {
System.out.println("Element: " + elem);
}
public static void main(String[] args) {
printElement("Hello");
printElement(42);
}
}
Calculates date offsets with Java 8+ time API.
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plusDays(7);
System.out.println("Today: " + today + " | Next Week: " + nextWeek);
}
}
Formats and prints string variables.
name = "Python"
print(f"Hello from {name} 3!")
Filters and computes values in a single expression.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens_squared = [x**2 for x in numbers if x % 2 == 0]
print("Even Squares:", evens_squared)
Queries and updates key-value dictionaries.
user = {"id": 101, "name": "User", "role": "Admin"}
user["status"] = "Active"
for key, val in user.items():
print(f"{key}: {val}")
Reverses string slices with step notation.
text = "CodexCareerPrep"
print("Reversed:", text[::-1])
Transforms collections with anonymous functions.
nums = [5, 12, 17, 18, 24, 32]
filtered = list(filter(lambda x: x > 15, nums))
print("Greater than 15:", filtered)
Demonstrates with-statement resource closing.
import io
stream = io.StringIO("First Line\nSecond Line")
with stream as f:
for line in f:
print("Read:", line.strip())
Handles arbitrary arguments and keywords.
def summarize(*args, **kwargs):
print("Sum:", sum(args))
print("Keywords:", kwargs)
summarize(10, 20, 30, platform="Python")
Implements inheritance and super() calls.
class Vehicle:
def __init__(self, brand):
self.brand = brand
def drive(self):
return f"{self.brand} is moving"
class Car(Vehicle):
def __init__(self, brand, doors):
super().__init__(brand)
self.doors = doors
c = Car("Mahindra", 5)
print(c.drive(), "with", c.doors, "doors")
Catches division by zero exceptions.
try:
res = 100 / 0
except ZeroDivisionError as err:
print("Caught error:", err)
finally:
print("Execution complete.")
Serializes and parses JSON records.
import json
data = {"course": "Python", "pages": 10}
json_str = json.dumps(data)
parsed = json.loads(json_str)
print("Parsed Course:", parsed["course"])
Yields values lazily.
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(5)))
Calculates intersection and union.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Intersection:", a & b)
print("Union:", a | b)
Extracts matching email strings.
import re
text = "Contact support at support@codexcareerprep.shop"
match = re.search(r'[\w\.-]+@[\w\.-]+', text)
if match:
print("Found:", match.group(0))
Wraps and inspects functions.
def logger(func):
def wrapper(*args):
print(f"Calling {func.__name__}")
return func(*args)
return wrapper
@logger
def multiply(a, b): return a * b
print("Result:", multiply(6, 7))
Calculates calendar offsets.
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=14)
print("Future Date:", future.strftime("%Y-%m-%d"))
Standard C output stream.
#include <stdio.h>
int main() {
printf("Hello, World from C!\n");
return 0;
}
Inspects pointers and dereferenced values.
#include <stdio.h>
int main() {
int val = 42;
int *ptr = &val;
printf("Value: %d | Address: %p\n", *ptr, ptr);
return 0;
}
Allocates and frees memory with malloc/free.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int*)malloc(3 * sizeof(int));
if (!arr) return 1;
arr[0] = 10; arr[1] = 20; arr[2] = 30;
for(int i = 0; i < 3; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
return 0;
}
Loops until reaching null terminator.
#include <stdio.h>
int main() {
char str[] = "CodexCareerPrep";
int len = 0;
while(str[len] != '\0') len++;
printf("Length: %d\n", len);
return 0;
}
Defines and initializes struct variables.
#include <stdio.h>
struct Student {
int id;
char name[30];
};
int main() {
struct Student s1 = {101, "Student"};
printf("ID: %d | Name: %s\n", s1.id, s1.name);
return 0;
}
Sorts an array in ascending order.
#include <stdio.h>
int main() {
int a[] = {5, 2, 8, 1, 3};
int n = 5;
for(int i = 0; i < n-1; i++) {
for(int j = 0; j < n-i-1; j++) {
if(a[j] > a[j+1]) {
int t = a[j]; a[j] = a[j+1]; a[j+1] = t;
}
}
}
for(int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}
Checks active binary bit flags.
#include <stdio.h>
int main() {
int flags = 0x01 | 0x04;
printf("Is Bit 2 Set: %s\n", (flags & 0x04) ? "YES" : "NO");
return 0;
}
Swaps integers using pointer memory addresses.
#include <stdio.h>
void swap(int *x, int *y) {
int t = *x; *x = *y; *y = t;
}
int main() {
int a = 5, b = 10;
swap(&a, &b);
printf("a=%d, b=%d\n", a, b);
return 0;
}
Computes factorials recursively.
#include <stdio.h>
long factorial(int n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
int main() {
printf("5! = %ld\n", factorial(5));
return 0;
}
Constructs formatted char buffers.
#include <stdio.h>
int main() {
char buffer[50];
sprintf(buffer, "STATUS:%d:OK", 200);
printf("%s\n", buffer);
return 0;
}
Uses named integer constants.
#include <stdio.h>
enum Level { LOW = 1, MEDIUM, HIGH };
int main() {
enum Level l = HIGH;
printf("Level: %d\n", l);
return 0;
}
Finds target element index in array.
#include <stdio.h>
int main() {
int arr[] = {10, 25, 30, 45, 50};
int target = 30, found = -1;
for(int i = 0; i < 5; i++) {
if(arr[i] == target) { found = i; break; }
}
printf("Found at index: %d\n", found);
return 0;
}
Traverses two-dimensional arrays.
#include <stdio.h>
int main() {
int matrix[2][2] = {{1, 2}, {3, 4}};
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) printf("%d ", matrix[i][j]);
printf("\n");
}
return 0;
}
Calls functions dynamically via pointer.
#include <stdio.h>
int add(int a, int b) { return a + b; }
int main() {
int (*op)(int, int) = add;
printf("Result: %d\n", op(12, 8));
return 0;
}
Transforms lowercase character to uppercase.
#include <stdio.h>
int main() {
char c = 'a';
printf("Upper: %c\n", c - ('a' - 'A'));
return 0;
}
Basic PHP output syntax.
<?php
$platform = "CodexCareerPrep";
echo "Welcome to " . $platform . "\n";
?>
Encodes PHP arrays into JSON.
<?php
$record = array(
"status" => "success",
"code" => 200,
"data" => array("course" => "PHP", "modules" => 10)
);
echo json_encode($record, JSON_PRETTY_PRINT);
?>
Filters and transforms arrays.
<?php
$nums = array(1, 2, 3, 4, 5, 6);
$evens = array_filter($nums, function($n) { return $n % 2 === 0; });
$doubled = array_map(function($n) { return $n * 2; }, $evens);
print_r(array_values($doubled));
?>
Splits and joins delimited text.
<?php
$csv = "SAP,Java,Python,PHP";
$arr = explode(",", $csv);
$joined = implode(" | ", $arr);
echo $joined . "\n";
?>
Defines object properties and methods.
<?php
class Course {
public $title;
public $pages;
public function __construct($title, $pages) {
$this->title = $title;
$this->pages = $pages;
}
public function getSummary() {
return $this->title . " (" . $this->pages . " Pages)";
}
}
$c = new Course("PHP Masterclass", 10);
echo $c->getSummary();
?>
Catches runtime exceptions in PHP.
<?php
try {
throw new Exception("Database connection error.");
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
} finally {
echo "Finished execution.\n";
}
?>
Hashes and verifies password strings.
<?php
$password = "SecurePass@123";
$hash = password_hash($password, PASSWORD_BCRYPT);
$matches = password_verify("SecurePass@123", $hash);
echo "Password Matches: " . ($matches ? "YES" : "NO");
?>
Assigns fallbacks for missing keys.
<?php
$config = array("theme" => "dark");
$font = isset($config["font"]) ? $config["font"] : "Inter";
echo "Font: " . $font;
?>
Validates string formats.
<?php
$email = "support@codexcareerprep.shop";
if (preg_match('/^[\w\.-]+@[\w\.-]+$/', $email)) {
echo "Valid Email Address";
}
?>
Manipulates DateTime objects.
<?php
$dt = new DateTime("now", new DateTimeZone("Asia/Kolkata"));
echo "Current Time: " . $dt->format("Y-m-d H:i:s T");
?>
Computes totals using array_reduce.
<?php
$prices = array(10.5, 20.0, 5.5);
$total = array_reduce($prices, function($carry, $item) { return $carry + $item; }, 0);
echo "Total: " . $total;
?>
Evaluates status codes.
<?php
$status = 200;
$msg = ($status === 200) ? "OK" : "Error";
echo "Status: " . $msg;
?>
Filters structured associative arrays.
<?php
$users = array(
array('id' => 1, 'name' => 'Alice'),
array('id' => 2, 'name' => 'Bob')
);
$found = array_filter($users, function($u) { return $u['id'] === 2; });
print_r(array_values($found));
?>
Substitutes text in string templates.
<?php
$template = "Hello, {NAME}! Welcome to {PLATFORM}.";
$output = str_replace(array('{NAME}', '{PLATFORM}'), array('Learner', 'CodexCareerPrep'), $template);
echo $output;
?>
Inspects base directories.
<?php
$path = __DIR__;
echo "Directory: " . basename($path);
?>
Standard C++ stream entry point.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World from C++!" << endl;
return 0;
}
Sorts elements in a standard vector.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {42, 12, 89, 5, 23};
sort(nums.begin(), nums.end());
for(int n : nums) cout << n << " ";
return 0;
}
Defines constructors, getters, and setters.
#include <iostream>
#include <string>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle(int w, int h) : width(w), height(h) {}
int area() { return width * height; }
};
int main() {
Rectangle rect(10, 5);
cout << "Area: " << rect.area() << endl;
return 0;
}
Traverses arrays using memory pointers.
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr;
for(int i = 0; i < 4; i++) {
cout << "Element " << i << ": " << *(ptr + i) << endl;
}
return 0;
}
Creates type-safe generic functions.
#include <iostream>
using namespace std;
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << "Max int: " << getMax(15, 25) << endl;
cout << "Max double: " << getMax(5.5, 2.1) << endl;
return 0;
}
Catches runtime logic errors safely.
#include <iostream>
using namespace std;
int main() {
try {
int numerator = 10, denominator = 0;
if (denominator == 0) throw "Division by zero error!";
int res = numerator / denominator;
} catch (const char* msg) {
cerr << "Caught exception: " << msg << endl;
}
return 0;
}
Manages key-value dictionaries.
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 82;
cout << "Alice Score: " << scores["Alice"] << endl;
return 0;
}
Allocates and releases heap memory.
#include <iostream>
using namespace std;
int main() {
int *val = new int(100);
cout << "Heap Value: " << *val << endl;
delete val;
return 0;
}
Anonymous inline function definitions.
#include <iostream>
using namespace std;
int main() {
auto add = [](int a, int b) { return a + b; };
cout << "Sum: " << add(12, 18) << endl;
return 0;
}
Manages safe automatic memory disposal.
#include <iostream>
#include <memory>
using namespace std;
class Resource {
public:
void show() { cout << "Resource active" << endl; }
};
int main() {
unique_ptr<Resource> res = make_unique<Resource>();
res->show();
return 0;
}
Customizes operator behaviors for classes.
#include <iostream>
using namespace std;
struct Point {
int x, y;
Point operator + (const Point& p) {
return {x + p.x, y + p.y};
}
};
int main() {
Point p1 = {1, 2}, p2 = {3, 4};
Point p3 = p1 + p2;
cout << "Result: " << p3.x << ", " << p3.y << endl;
return 0;
}
Demonstrates virtual runtime functions.
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() { cout << "Base class" << endl; }
};
class Derived : public Base {
public:
void print() override { cout << "Derived class" << endl; }
};
int main() {
Base *b = new Derived();
b->print();
delete b;
return 0;
}
Reverses strings using algorithms.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string text = "Codex";
reverse(text.begin(), text.end());
cout << "Reversed: " << text << endl;
return 0;
}
Computes Fibonacci numbers recursively.
#include <iostream>
using namespace std;
int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
int main() {
cout << "Fibonacci(6): " << fib(6) << endl;
return 0;
}
Writes text content to external files.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("output.txt");
outFile << "Writing text from C++ program.";
outFile.close();
cout << "File written successfully." << endl;
return 0;
}
Standard entry point in C#.
using System;
class Program {
static void Main() {
Console.WriteLine("Hello, World from C#!");
}
}
Queries collections declaratively.
using System;
using System.Linq;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evens = from n in numbers where n % 2 == 0 select n;
Console.WriteLine(string.Join(", ", evens));
}
}
Executes asynchronous background methods.
using System;
using System.Threading.Tasks;
class Program {
static async Task Main() {
string result = await FetchDataAsync();
Console.WriteLine(result);
}
static async Task<string> FetchDataAsync() {
await Task.Delay(100);
return "Data retrieved asynchronously.";
}
}
Implements auto-implemented properties.
using System;
class Employee {
public string Name { get; set; }
public decimal Salary { get; set; }
}
class Program {
static void Main() {
Employee emp = new Employee { Name = "Alice", Salary = 75000M };
Console.WriteLine($"{emp.Name} earns {emp.Salary}");
}
}
Manages key-value stores cleanly.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, string> config = new Dictionary<string, string>();
config["Env"] = "Production";
config["Region"] = "AP-South";
Console.WriteLine("Environment: " + config["Env"]);
}
}
Catches application exceptions safely.
using System;
class Program {
static void Main() {
try {
int val = int.Parse("invalid_number");
} catch (FormatException e) {
Console.WriteLine("Caught format error: " + e.Message);
}
}
}
Extends existing built-in type capabilities.
using System;
public static class StringExtensions {
public static bool IsNullOrEmptyCustom(this string str) {
return string.IsNullOrEmpty(str);
}
}
class Program {
static void Main() {
string text = "Test";
Console.WriteLine(text.IsNullOrEmptyCustom());
}
}
Enforces structured class contracts.
using System;
interface ILogger {
void Log(string message);
}
class ConsoleLogger : ILogger {
public void Log(string message) => Console.WriteLine("[LOG]: " + message);
}
class Program {
static void Main() {
ILogger logger = new ConsoleLogger();
logger.Log("System started.");
}
}
Handles event publisher-subscriber models.
using System;
class Program {
public delegate void Notify(string msg);
public static event Notify OnProcessCompleted;
static void Main() {
OnProcessCompleted += (m) => Console.WriteLine(m);
OnProcessCompleted("Process finished successfully!");
}
}
Reads and writes configuration files.
using System;
using System.IO;
class Program {
static void Main() {
string path = "test.txt";
File.WriteAllText(path, "Hello C# File API");
string content = File.ReadAllText(path);
Console.WriteLine(content);
}
}
Handles null defaults gracefully.
using System;
class Program {
static void Main() {
string input = null;
string result = input ?? "Default Value";
Console.WriteLine(result);
}
}
Evaluates object types concisely.
using System;
class Program {
static void Main() {
object obj = 42;
string desc = obj switch {
int i => $"Integer value {i}",
string s => $"String value {s}",
_ => "Unknown"
};
Console.WriteLine(desc);
}
}
Defines immutable data containers.
using System;
public record Product(int Id, string Title, decimal Price);
class Program {
static void Main() {
Product p = new Product(1, "Laptop", 1200.00M);
Console.WriteLine(p);
}
}
Validates inputs via Regex patterns.
using System;
using System.Text.RegularExpressions;
class Program {
static void Main() {
bool isValid = Regex.IsMatch("AB123", "^[A-Z]{2}[0-9]{3}$");
Console.WriteLine("Is Match: " + isValid);
}
}
Executes concurrent loops across threads.
using System;
using System.Threading.Tasks;
class Program {
static void Main() {
Parallel.For(1, 4, i => {
Console.WriteLine($"Processing index {i}");
});
}
}
Iterates over lists using closure blocks.
def list = [1, 2, 3, 4, 5]
list.each { println "Number: $it" }
Injects variables directly inside double quotes.
def name = "Groovy"
def greeting = "Hello from $name!"
println greeting
Prevents null-pointer exceptions safely.
String str = null
println str?.toUpperCase()
Parses JSON string contents into maps.
import groovy.json.JsonSlurper
def jsonText = '{"name":"Developer","role":"Admin"}'
def obj = new JsonSlurper().parseText(jsonText)
println obj.name
Navigates and extracts nodes from XML.
def xml = '<root><item id="1">Cloud Integration</item></root>'
def root = new XmlSlurper().parseText(xml)
println root.item.text()
Reads line-by-line using concise closures.
def text = "Line 1\nLine 2"
text.eachLine { line -> println line }
Dynamically adds properties and methods at runtime.
def dynamicObj = new Expando()
dynamicObj.name = "Codex"
dynamicObj.greet = { "Hello " + delegate.name }
println dynamicObj.greet()
Provides fallback defaults for null expressions.
def input = null
def result = input ?: "Fallback Value"
println result
Performs advanced switch case matching.
def evaluate(val) {
switch (val) {
case [1, 2, 3]: return "In list"
case String: return "It's a string"
default: return "Unknown"
}
}
println evaluate("Test")
Spreads elements across collections.
def list1 = [1, 2]
def list2 = [0, *list1, 3]
println list2
Matches patterns cleanly using =~.
def text = "Contact: support@codexcareerprep.shop"
if (text =~ /[\w\.-]+@[\w\.-]+/) {
println "Email format detected"
}
Calculates date additions easily.
use(groovy.time.TimeCategory) {
def future = new Date() + 7.days
println "Date after 7 days: $future"
}
Defines and loops over map dictionaries.
def map = [A: 100, B: 200]
map.each { key, val -> println "$key -> $val" }
Validates conditions with descriptive messages.
def x = 10
assert x > 5 : "Value must be greater than 5"
println "Assertion passed successfully."
Generates sequences and handles loops.
def range = 1..5
range.each { print "$it " }
println ""
Outputs basic strings to output screen.
REPORT z_hello_world.
WRITE: / 'Hello, World from SAP ABAP!'.
Defines and loops over local internal tables.
REPORT z_internal_table.
TYPES: BEGIN OF ty_emp,
id TYPE i,
name TYPE string,
END OF ty_emp.
DATA: gt_emp TYPE TABLE OF ty_emp,
gs_emp TYPE ty_emp.
gs_emp-id = 101. gs_emp-name = 'John Doe'. APPEND gs_emp TO gt_emp.
LOOP AT gt_emp INTO gs_emp.
WRITE: / gs_emp-id, gs_emp-name.
ENDLOOP.
Queries database tables with inner joins.
REPORT z_db_select.
DATA: lt_carrier TYPE TABLE OF scarr.
SELECT carrid, carrname FROM scarr INTO TABLE @lt_carrier UP TO 5 ROWS.
LOOP AT lt_carrier INTO DATA(ls_carrier).
WRITE: / ls_carrier-carrid, ls_carrier-carrname.
ENDLOOP.
Defines local classes and methods.
REPORT z_oo_class.
CLASS lcl_calculator DEFINITION.
PUBLIC SECTION.
METHODS add IMPORTING iv_a TYPE i iv_b TYPE i RETURNING VALUE(rv_sum) TYPE i.
ENDCLASS.
CLASS lcl_calculator IMPLEMENTATION.
METHOD add.
rv_sum = iv_a + iv_b.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA(lo_calc) = NEW lcl_calculator().
DATA(lv_res) = lo_calc->add( iv_a = 10 iv_b = 20 ).
WRITE: / 'Sum:', lv_res.
Catches class-based ABAP exceptions.
REPORT z_exception_handling.
DATA: lo_cx TYPE REF TO cx_root.
TRY.
RAISE EXCEPTION NEW cx_sy_zerodivide( ).
CATCH cx_sy_zerodivide INTO lo_cx.
WRITE: / 'Caught division by zero exception.'(001).
ENDTRY.
Simplifies variable typing inline.
REPORT z_inline_declarations.
DATA(lv_message) = 'Welcome to ABAP 7.4+ syntax.'.
WRITE: / lv_message.
DATA(lt_numbers) = VALUE #( ( 1 ) ( 2 ) ( 3 ) ).
LOOP AT lt_numbers INTO DATA(lv_num).
WRITE: / lv_num.
ENDLOOP.
Copies matching fields across structures.
REPORT z_corresponding_demo.
TYPES: BEGIN OF ty_s1, id TYPE i, name TYPE string, END OF ty_s1,
BEGIN OF ty_s2, id TYPE i, name TYPE string, city TYPE string, END OF ty_s2.
DATA(ls_source) = VALUE ty_s1( id = 1 name = 'Alice' ).
DATA(ls_target) = CORRESPONDING ty_s2( ls_source ).
WRITE: / ls_target-id, ls_target-name.
Accesses memory directly using field symbols.
REPORT z_field_symbols.
DATA: lt_nums TYPE TABLE OF i.
lt_nums = VALUE #( ( 10 ) ( 20 ) ( 30 ) ).
LOOP AT lt_nums ASSIGNING FIELD-SYMBOL(<fs_num>).
<fs_num> = <fs_num> * 2.
WRITE: / <fs_num>.
ENDLOOP.
Performs database aggregations and counts.
REPORT z_sql_aggregate.
SELECT carrid, COUNT(*) AS count FROM spfli GROUP BY carrid INTO TABLE @DATA(lt_counts) UP TO 5 ROWS.
LOOP AT lt_counts INTO DATA(ls_count).
WRITE: / ls_count-carrid, ls_count-count.
ENDLOOP.
Efficiently retrieves sorted table rows.
REPORT z_read_binary_search.
DATA: lt_list TYPE TABLE OF i.
lt_list = VALUE #( ( 10 ) ( 20 ) ( 30 ) ( 40 ) ).
READ TABLE lt_list INTO DATA(lv_val) WITH KEY table_line = 30 BINARY SEARCH.
IF sy-subrc = 0.
WRITE: / 'Found value:', lv_val.
ENDIF.
Constructs selection criteria range tables.
REPORT z_range_table.
DATA: lr_carrid TYPE RANGE OF scarr-carrid.
lr_carrid = VALUE #( ( sign = 'I' option = 'EQ' low = 'LH' ) ).
SELECT * FROM scarr WHERE carrid IN @lr_carrid INTO TABLE @DATA(lt_scarr).
WRITE: / 'Records fetched:', lines( lt_scarr ).
Raises standard status/error messages.
REPORT z_message_demo.
WRITE: / 'Message simulation completed.'.
Sorts internal table entries ascending/descending.
REPORT z_sort_table.
DATA(lt_vals) = VALUE #( ( 5 ) ( 2 ) ( 8 ) ( 1 ) ).
SORT lt_vals ASCENDING.
LOOP AT lt_vals INTO DATA(lv_v).
WRITE: lv_v.
ENDLOOP.
Inserts records into custom database tables.
REPORT z_sql_insert.
WRITE: / 'Insert statement simulated.'.
Manipulates string casing utilities.
REPORT z_string_manipulation.
DATA(lv_text) = 'sap abap programming'.
TRANSLATE lv_text TO UPPER CASE.
WRITE: / lv_text.
Transforms XML payloads in SAP PI/PO Java Mapping.
import com.sap.aii.mapping.api.*;
import java.io.*;
public class SimpleXMLMapping implements StreamTransformation {
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter writer = new PrintWriter(out);
String line;
while ((line = reader.readLine()) != null) {
writer.println(line.replace("<OldTag>", "<NewTag>"));
}
writer.flush();
} catch (Exception e) {
throw new StreamTransformationException(e.getMessage());
}
}
}
User Defined Function to lookup values in queues.
public void extractNode(String[] input, Result result, Container container) {
for (int i = 0; i < input.length; i++) {
if (input[i] != null && !input[i].isEmpty()) {
result.addValue(input[i].trim());
}
}
}
Sets dynamic routing attributes in PI/PO Message Header.
import com.sap.aii.mapping.api.*;
public class DynamicConfigMapping implements StreamTransformation {
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
try {
DynamicConfiguration config = (DynamicConfiguration) getTransformationParameters().get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
DynamicConfigurationKey key = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File", "FileName");
config.put(key, "Target_Output.xml");
} catch (Exception e) {
throw new StreamTransformationException(e.getMessage());
}
}
}
Converts timestamps between formats inside graphical mapping.
import java.text.SimpleDateFormat;
import java.util.Date;
public void convertDate(String inDate, Result result, Container container) throws java.text.ParseException {
SimpleDateFormat inFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = inFormat.parse(inDate);
result.addValue(outFormat.format(date));
}
Inspects sender and receiver party attributes.
import com.sap.aii.mapping.api.*;
public class AttrMapping implements StreamTransformation {
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
Map param = getTransformationParameters();
String senderService = (String) param.get(StreamTransformationConstants.SENDER_SERVICE);
}
}
Encodes binary attachment or payloads to Base64.
import java.util.Base64;
public void encodeBase64(String[] payload, Result result, Container container) {
if (payload[0] != null) {
String encoded = Base64.getEncoder().encodeToString(payload[0].getBytes());
result.addValue(encoded);
}
}
Writes custom tracing messages to PI/PO monitor.
import com.sap.aii.mapping.api.*;
public class TraceMapping implements StreamTransformation {
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
AbstractTrace trace = getTrace();
trace.addInfo("Starting custom Java Mapping execution...");
}
}
Pads fields to fixed length requirements.
public void padString(String[] input, Result result, Container container) {
if (input[0] != null) {
String padded = String.format("%-10s", input[0]);
result.addValue(padded);
}
}
Copies input streams to output streams directly.
import com.sap.aii.mapping.api.*;
import java.io.*;
public class CopyMapping implements StreamTransformation {
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
throw new StreamTransformationException(e.getMessage());
}
}
}
Executes database lookups inside message mappings.
public void jdbcLookup(String[] keys, Result result, Container container) {
result.addValue("LookupResult");
}
Strips namespaces to simplify message structures.
import com.sap.aii.mapping.api.*;
public class NamespaceCleaner implements StreamTransformation {
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
}
}
Validates format compliance using regex in UDF.
import java.util.regex.Pattern;
public void validateRegex(String[] val, Result result, Container container) {
if (val[0] != null && Pattern.matches("^[0-9]+$", val[0])) {
result.addValue("VALID");
} else {
result.addValue("INVALID");
}
}
Splits incoming payload into multiple target files.
import com.sap.aii.mapping.api.*;
public class MultiMappingSplitter implements StreamTransformation {
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
}
}
Ensures input values contain valid numbers.
public void isNumeric(String[] value, Result result, Container container) {
try {
Double.parseDouble(value[0]);
result.addValue("true");
} catch (Exception e) {
result.addValue("false");
}
}
Compresses message strings using GZIP streams.
import com.sap.aii.mapping.api.*;
import java.util.zip.GZIPOutputStream;
public class GzipMapping implements StreamTransformation {
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
try {
GZIPOutputStream gzipOut = new GZIPOutputStream(out);
} catch (Exception e) {
throw new StreamTransformationException(e.getMessage());
}
}
}