Agentic Design Patterns using Java and N8N – Pipeline Pattern

The prompt chaining, or pipeline, pattern passes output from one task to the next. This article follows a laptop description through two model calls: one extracts its specifications, and the other formats them as JSON. The examples use Spring AI, the OpenAI Java SDK, LangChain4j, and n8n.

The example presented here adapts the prompt chaining workflow from Antonio Gullí’s Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems. Each implementation processes the same product description and requests the keys cpu, memory, and storage.

The examples use the following product description and two sets of instructions. Each Java handler receives the instructions for its stage.

Info: The prompt texts were altered slightly in this post from the book’s example.

Product description

Experience the power to take on your day with a laptop built around a
3.5 GHz octa-core processor and 16GB of RAM. Whether you’re moving between
work projects, browsing your favorite sites, or enjoying your downtime,
this combination puts capable performance at your fingertips.
A spacious 1TB NVMe SSD gives you room for your documents, photos,
applications, and media, along with fast access to the files you need.
From your first task of the morning to your next creative project,
this laptop brings processing power, memory, and storage together
to help you keep moving.

Extraction instructions

Extract the technical specifications from the following text.

Formatting instructions

Transform the following specifications into a JSON object with
"cpu", "memory", and "storage" as keys.
Return only the JSON object.
Do not include Markdown code fences, explanations, or other text.

The first stage extracts specifications from the product description. The second receives those specifications and organizes them as JSON.

Info: The GitHub project contains the Java source code and the importable n8n pipeline workflow for this blog post.

Prompt Chaining with Spring AI

For a Spring application, prompt chaining provides a way to organize AI processing around tasks with defined responsibilities. Each stage receives the information it needs, performs one operation, and supplies a result to the next stage. The Spring AI example applies this approach to the laptop description, separating the identification of specifications from their presentation as JSON.

Info: The example classes are intentionally simple to keep the focus on the prompt chaining pattern and the flow of data between its stages.

The Spring AI example resides in com.jamesabrannan.agenticpatterns.springai.pipeline and its handlers subpackage. PipelineExampleService starts the workflow by calling PipelineAgent.executePipeline(). The agent holds an ExtractHandler and a FormatHandler, each responsible for one stage.

Both handlers extend the project’s RequestHandler and receive an org.springframework.ai.chat.client.ChatClient through their constructors. This interface provides the prompt API used to send instructions and input to the model. The inherited method creates a prompt, sets the system instructions with system(instructions), supplies the stage input with user(request), sends the request with call(), and retrieves the response text with content().

String response = chatClient.prompt()
        .system(instructions)
        .user(request)
        .call()
        .content();

ExtractHandler.handle(request) passes the product description and extraction instructions to the inherited method. FormatHandler.handle(request) passes the extracted specifications and instructions requesting a JSON object. Each handler returns the model’s text to PipelineAgent.

Executing the two model calls

The following sequence diagram illustrates the application’s workflow.

PipelineExampleService.runExample() calls PipelineAgent.executePipeline(). The agent passes the product description to ExtractHandler, trims the response, and passes the extracted specifications to FormatHandler.

String response = this.extractHandler.handle(inputText).trim();
String result = this.formatHandler.handle(response).trim();
return result;

After the agent returns, PipelineExampleService parses the result with Jackson and prints it with indentation. readTree(result) parses the returned text; the writer then serializes that tree for console output.

String result = agent.executePipeline();
JsonMapper mapper = JsonMapper.builder().build();
String prettyJson = mapper.writerWithDefaultPrettyPrinter()
        .writeValueAsString(mapper.readTree(result));
System.out.println("Final JSON output:");
System.out.println(prettyJson);

Here, the application controls the sequence and transfers results between stages. Spring AI supplies the model-call API, while the Java classes define the workflow.

Prompt Chaining with OpenAI Java SDK

A pipeline does not require a framework dedicated to agent workflows. The OpenAI Java SDK and Spring AI leave workflow composition to application code, while LangChain4j provides abstractions for connecting agents. As the previous section demonstrated, an application implements a pipeline by dividing a task into stages and passing results between them. The OpenAI Java SDK example follows this approach: two model requests form a workflow, with the second using the output of the first.

The OpenAI Java SDK example resides in com.jamesabrannan.agenticpatterns.openai.pipeline. PipelineExample.main() creates the client and the shared OpenAiTextService, then passes the service to PipelineAgent. The agent constructs both handlers with that service.

The com.openai.client.okhttp.OpenAIOkHttpClient.fromEnv() method creates a client using environment settings. The returned com.openai.client.OpenAIClient exposes the API operations used by the text service. ProviderModelSettings.MODEL_NAME supplies the model name when the application constructs the service.

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
try {
    OpenAiTextService textService =
            new OpenAiTextService(client, ProviderModelSettings.MODEL_NAME);
    PipelineAgent agent = new PipelineAgent(textService);
    String jsonString = agent.executePipeline();
    JsonMapper mapper = JsonMapper.builder().build();
    String prettyJson = mapper.writerWithDefaultPrettyPrinter()
            .writeValueAsString(mapper.readTree(jsonString));
    System.out.println("Final JSON output:");
    System.out.println(prettyJson);
} finally {
    client.close();
}

After the pipeline returns, PipelineExample parses the text with Jackson’s com.fasterxml.jackson.databind.json.JsonMapper and prints it with indentation. The entry point declares throws JsonProcessingException using com.fasterxml.jackson.core.JsonProcessingException, so parsing failures propagate to the caller. The finally block closes the client even if parsing fails.

ExtractHandler and FormatHandler implement the project’s RequestHandler interface. Each defines handle(String request) and calls textService.generate(INSTRUCTIONS, request). The extraction handler requests specifications; the formatting handler requests a JSON object with the three output keys.

Executing the two Responses API calls

The sequence diagram follows PipelineAgent.executePipeline() through extraction and formatting.

public String executePipeline() {
    String response = extractHandler.handle(inputText).trim();
    response = formatHandler.handle(response).trim();
    return response;
}

The agent passes the product description to ExtractHandler, trims the returned specifications, then passes them to FormatHandler.

For each stage, the text service builds a com.openai.models.responses.ResponseCreateParams instance. The builder selects the model with model(modelName), supplies instructions with instructions(instructions), and sets the input with input(request). The call client.responses().create(params) sends the request and returns a com.openai.models.responses.Response containing its status and output.

ResponseCreateParams params = ResponseCreateParams.builder()
        .model(modelName)
        .instructions(instructions)
        .input(request)
        .build();
Response response = client.responses().create(params);

The application creates the chain by passing one request’s result to the next. The SDK sends the requests; the Java pipeline determines their order and connects their results.

Prompt Chaining with LangChain4j

As a workflow grows, it needs a way to define execution order and pass results between stages. LangChain4j provides abstractions for composing agents into workflows. This example declares extraction and formatting as a sequence, with the result of the first stage supplying the input for the second.

The workflow builders come from langchain4j-agentic. This project uses version 1.24.0-beta34 alongside LangChain4j 1.24.0. The agentic module documentation identifies the module as experimental, so its APIs may change between versions.

The classes in com.jamesabrannan.agenticpatterns.langchain4j.pipeline define the stages as interfaces and build a sequence from them. The PipelineExample class creates a dev.langchain4j.model.openai.OpenAiChatModel using the configured API key and model name. This class implements the dev.langchain4j.model.chat.ChatModel interface accepted by PipelineAgent.

OpenAiChatModel model = OpenAiChatModel.builder()
        .apiKey(ProviderModelSettings.API_KEY)
        .modelName(ProviderModelSettings.MODEL_NAME)
        .build();
PipelineAgent agent = new PipelineAgent(model);

The ExtractHandler interface declares the extraction operation. @dev.langchain4j.agentic.Agent marks the method as an agent operation. @dev.langchain4j.service.SystemMessage supplies its instructions, while @dev.langchain4j.service.UserMessage defines the input template. @dev.langchain4j.service.V("inputText") names the argument that fills {{inputText}}.

@Agent("Extracts technical specifications")
@SystemMessage(INSTRUCTIONS)
@UserMessage("{{inputText}}")
String handle(@V("inputText") String request);

FormatHandler declares the same return type with a different input name. Its @dev.langchain4j.service.UserMessage("{{specifications}}") template receives the extraction result through the argument marked @dev.langchain4j.service.V("specifications"). Its system instructions request JSON.

@Agent("Formats extracted specifications as JSON")
@SystemMessage(INSTRUCTIONS)
@UserMessage("{{specifications}}")
String handle(@V("specifications") String specifications);

dev.langchain4j.agentic.AgenticServices.agentBuilder() creates implementations of the two interfaces. The chatModel(model) setting assigns the shared model, and outputKey(...) names the state entry that receives the agent’s return value. The extractor writes to specifications; the formatter writes to json.

ExtractHandler extractHandler = AgenticServices.agentBuilder(ExtractHandler.class)
        .chatModel(model)
        .outputKey("specifications")
        .build();
FormatHandler formatHandler = AgenticServices.agentBuilder(FormatHandler.class)
        .chatModel(model)
        .outputKey("json")
        .build();

Passing named state through the sequence

The following sequence diagram illustrates the processing.

The dev.langchain4j.agentic.AgenticServices.sequenceBuilder() builds a workflow whose subAgents(extractHandler, formatHandler) setting fixes the execution order. The output function reads the json entry after the formatter finishes. PipelineAgent stores the workflow as a dev.langchain4j.agentic.UntypedAgent, which accepts a map of named inputs and returns an object.

The extractor stores its result under specifications. The sequence uses that entry to supply the formatter’s parameter marked @dev.langchain4j.service.V("specifications"). The formatter stores its result under json, which becomes the pipeline’s return value.

this.pipeline = AgenticServices.sequenceBuilder()
     .subAgents(extractHandler, formatHandler)
     .output(scope -> scope.readState("json"))
     .build();

executePipeline(inputText) supplies the product description under the inputText key. The workflow returns the formatter’s output, which the method casts to a string and trims.

String result = ((String) pipeline.invoke(
        Map.of("inputText", inputText))).trim();
return result;

PipelineExample parses the returned text with Jackson, rejects trailing tokens, requires the root value to be an object, and prints the JSON with indentation. These checks do not verify the specification values or require the three requested keys.

LangChain4j defines and runs the sequence through its workflow API. The agents describe the tasks, while the sequence manages their execution and passes results between them.

Prompt Chaining with N8N

A visual workflow offers another way to express the dependencies between AI tasks. In n8n, the pipeline appears as a path from the product description to the resulting JSON, with each stage represented in the workflow. This view places the processing steps and the movement of information together on one canvas.

The workflow expresses the two stages through connected nodes. A Manual Trigger starts the execution. Format input and instructions creates the product description and prompts. Extract specifications makes the first model call; Format specifications receives its result and makes the second. Each chain connects to an OpenAI Chat Model node, and the formatting chain also connects to a Structured Output Parser.

Creating the input and instructions

Format input and instructions uses an Edit Fields node in JSON mode to create one item with three fields: input, extract, and format. The input field holds the laptop description. The extract field asks for specifications stated in the text and tells the model to omit missing specifications and assumptions. The format field requests a JSON object containing cpu, memory, and storage.

The output pane shows these fields together. The extraction chain reads the description and extraction instructions from this item. The formatting chain later retrieves the formatting instructions from the same node.

Extracting the specifications

Extract specifications uses a Basic LLM Chain. Its prompt source is Define below. The Prompt (User Message) field reads {{ $json.extract }}, and a User chat message reads {{ $json.input }}. These expressions supply the extraction instruction and product description to the first model call.

The chain returns the specifications in its text field. The screenshot shows the processor, RAM, and storage extracted from the description. The next chain receives this item through the connection between the two nodes.

Formatting the extraction result

Format specifications uses a second Basic LLM Chain. Its prompt reads {{ $('Format input and instructions').item.json.format }} to retrieve the formatting instructions. Its User chat message reads {{ $json.text }} to pass the extractor’s result to the model.

Require Specific Output Format is enabled, and the chain connects to the Structured Output Parser. The screenshot shows an object under output with cpu, memory, and storage fields. The second call restructures the first call’s output into those fields.

Defining the output structure

The Structured Output Parser uses Generate From JSON Example. The example defines nested fields for processor frequency, core count, description, memory size, storage size, and storage type. n8n generates a schema from the property names and value types and treats every field as required. It does not fix the output to the example’s literal values: 3.5 and 16 illustrate numeric fields.

The Java examples request three top-level keys without prescribing their internal structure. The n8n example goes further by defining nested fields through its output parser. Parsing JSON checks its form; it does not establish that the extracted specifications are correct.

{
  "cpu": {
    "frequency_ghz": 3.5,
    "cores": 8,
    "description": "octa-core"
  },
  "memory": {
    "size_gb": 16
  },
  "storage": {
    "size_tb": 1,
    "type": "NVMe SSD"
  }
}

The parser processes the formatting chain’s response and returns the parsed object. The schema defines the field names and value types; the model supplies the values from the extracted specifications. The screenshot’s parser output contains the processor, memory, and storage data from the product description.

n8n defines the sequence through node connections and passes results through workflow items. The canvas shows the flow between stages, and the output parser specifies the structure expected from the formatter.

Running the examples

The Java projects target Java 17 and use Maven. Set OPENAI_API_KEY in the process environment before running an example. The source links below identify each project and entry point; launch the Java entry points from your IDE with the project dependencies on the classpath.

Spring AI project: run com.jamesabrannan.agenticpatterns.springai.AgenticpatternsApplication with PIPELINE as the program argument. Spring configuration reads the key from the environment.

OpenAI Java SDK project: run com.jamesabrannan.agenticpatterns.openai.pipeline.PipelineExample. The client reads its settings from the environment.

LangChain4j project: run com.jamesabrannan.agenticpatterns.langchain4j.pipeline.PipelineExample. The model configuration reads the key from the environment.

n8n pipeline workflow: download the JSON file and import it into n8n. Select your OpenAI credential in both model nodes, then start the Manual Trigger. The export omits local credential bindings.

Running any example makes live model requests. For this input, the workflow uses two model calls: one for extraction and one for formatting, excluding retries.

Summary

All four implementations follow the same flow: extract specifications, pass them to the formatting stage, and return JSON. Spring AI and the OpenAI Java SDK use application code to control the sequence. LangChain4j provides workflow builders and named state entries to connect the stages. n8n expresses the pipeline through nodes, expressions, and connections, with a Structured Output Parser defining the output structure. The choice determines where you define and maintain the workflow: in application code, through an orchestration API, or on a visual canvas.

Agentic Design Patterns using N8N – Routing Pattern

Antonio Gulli’s Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems presents 21 patterns for building AI agents, including prompt chaining, routing, planning, and multi-agent collaboration. The book combines explanations with runnable examples using LangChain, LangGraph, CrewAI, and Google ADK, showing how to assemble individual capabilities into more complex AI workflows. The book uses Python as the implementation language. In this series, I implement the book’s examples using Java and n8n.

Info: See Agentic Design Patterns Using Java – Routing Pattern for an implementation of this pattern using Spring AI, LangChain4j, and the OpenAI Java SDK.

The routing pattern directs an incoming request to a suitable handler. A model or predefined rules determine the request’s category, then the application selects the instructions, tool, or workflow that should process it.

This example uses n8n nodes and connections to implement an example of using the routing pattern.

Info: The workflow and supporting documentation are available in the project’s n8n directory.

Organizing the workflow

Two Basic LLM Chain nodes handle the model calls. The first classifies each request. A Switch node after the first LLM node selects a branch containing the appropriate handler instructions. All three branches connect to a shared second chain that generates the answer. The final nodes format each response, convert it into a text file, and save it to disk.

The overview shows the complete path from the Manual Trigger to file output. The model connections beneath the LLM Chains supply model configuration.

CategoryResponsibility
BOOKINGAcknowledge requests concerning flights or hotels.
INFOAnswer general knowledge questions.
UNCLEARRespond to ambiguous requests or requests outside the other categories.

Info: The booking branch does not make reservations, and the information branch does not search the web. This keeps the example focused on routing.

Creating the sample requests

Execute Routing Example is a Manual Trigger. It starts the workflow and passes control to Requests, a Code node that creates the three sample items. Coordinator Instructions then adds the classification prompt.

The connection labels show the transition from one trigger item to three request items. Each request travels through the classification and routing steps independently.

return [
  { json: { request: "Book me a flight to London." } },
  { json: { request: "What is the capital of Italy?" } },
  { json: { request: "Do that thing for me." } }
];

The Code node is configured to Run Once for All Items. It returns three separate n8n items, each with a json.request field.

Defining the coordinator’s instructions

Coordinator Instructions is an Edit Fields node in JSON mode. It adds an INSTRUCTIONS field containing the classification prompt.

{
  "INSTRUCTIONS": "Classify the user's request into exactly one category:\nBOOKING: Requests related to booking flights or hotels.\nINFO: General information questions.\nUNCLEAR: Ambiguous requests or requests outside those categories.\nReturn only BOOKING, INFO, or UNCLEAR. Do not answer the request itself."
}

Include Other Input Fields is enabled, so the original request remains in the output. The screenshot shows both fields on each item. This JSON defines workflow fields; it does not constrain the model’s answer to a JSON schema.

Configuring the model

The OpenAI Chat Model supplies credentials and model settings to the first chain. The screenshot selects gpt-5-mini and enables the Responses API. Select an OpenAI credential and a model available to your account.

The model is connected to the chain’s Model input, as shown below. It supplies the language model used by the chain.

Classifying each request

The first Basic LLM Chain acts as the coordinator. Set the prompt source to Define below, use the current request as the user prompt, and add a System message containing the classification instructions.

SettingValue
Prompt (User Message){{ $json.request }}
System message{{ $json.INSTRUCTIONS }}
Require Specific Output FormatOff

The output pane shows three items whose text values are BOOKING, INFO, and UNCLEAR. The coordinator returns the classification rather than answering the original request. The Basic LLM Chain documentation describes these prompt and message settings.

Selecting a route

Route by Request Category is a Switch node. Its three outputs connect to Booking Instructions, Info Instructions, and Unclear Instructions.

Use Rules mode and compare the classifier’s returned text with each supported category. Each rule reads the following expression:

{{ $json.text.trim() }}
ComparisonOutput
Is equal to BOOKINGBOOKING
Is equal to INFOINFO
Is equal to UNCLEARUNCLEAR

The model determines the category. The Switch performs the comparison and sends the item through the matching connection without making another model call. The screenshot shows one item on each category output.

trim() removes surrounding whitespace. The comparisons remain case-sensitive and do not accept explanatory sentences or quoted category names. The exported workflow has no fallback output, so unexpected classification text does not reach a handler. UNCLEAR is an explicit category, not a fallback for malformed output. See the Switch documentation for fallback options.

Preparing the selected handler

Each instruction branch uses an Edit Fields node to prepare request, category, and handlerInstructions. The booking branch is shown below.

The classifier returns its answer in text. To recover the original request, the branch references the linked item from Coordinator Instructions:

{{ $('Coordinator Instructions').item.json.request }}

n8n’s item linking associates the classification with the request that produced it. Using .item preserves that relationship rather than retrieving the first sample request for every branch.

{{ JSON.stringify({
  request: $('Coordinator Instructions').item.json.request,
  category: $json.text.trim(),
  handlerInstructions: "You are a booking assistant. Acknowledge the user's travel request briefly. Do not ask questions or request additional details. Do not claim to have booked anything or checked live availability."
}) }}

JSON.stringify() produces the JSON text expected by this node’s JSON-mode parameter. The resulting output exposes the three values as workflow fields.

The information branch supplies instructions to answer briefly, acknowledge uncertainty, and avoid claims of live research. The unclear branch asks for the fixed answer Your request was unclear. without follow-up questions.

Generating the answer

All three instruction nodes connect to Handle Request, a second Basic LLM Chain with its own connected OpenAI Chat Model node.

The selected branch supplies the system instructions, while the original request remains the user prompt. Set the prompt source to Define below and configure these fields:

SettingValue
Prompt (User Message){{ $json.request }}
System message{{ $json.handlerInstructions }}

The input pane exposes the branch data, and the output pane shows the generated text. The selected run in this screenshot includes additional wording after the unclear response. That differs from the requested fixed answer and illustrates why successful node execution still requires output review.

The shared chain keeps model-call configuration in one place. The branches vary its behavior through their instructions. These converging connections do not collect all answers into one item or synchronize the branches. The chain processes the items arriving from each branch.

Normal successful processing of the three samples requires six model calls: three classifications and three responses, excluding retries. The unclear branch also makes a second call, even though its instructions request fixed wording.

Formatting and saving responses

The final three nodes separate presentation from response generation. Format Final Response creates a String field named message with a heading, the handler’s returned text, and a footer. This step formats the answer without making another model call.

Plain Text Response uses Convert to File with Convert to Text File selected. Its Text Input Field is message, and the output binary field is data. The input setting contains the field name, not an expression containing the text. The binary output can be viewed or downloaded.

Read/Write Files from Disk then writes that binary data using this filename expression:

{{ '/files/output/output-' + $execution.id + '-' + ($runIndex + 1) + '.txt' }}

The execution ID distinguishes workflow executions. The run index distinguishes separate invocations of the writing node within an execution. For the three sample requests taking separate branches, filenames can look like:

Running the example

Import the workflow JSON, then select your OpenAI credential in both model nodes.

Info: This example runs in Docker. /files/output is a container path mapped to a host folder by the project’s Compose configuration. Confirm that the mount exists and is writable before running the workflow.

The credential screen below shows a successful connection test. Store the key in n8n’s credential configuration rather than in workflow fields.

Start Execute Routing Example, then inspect the classification output, selected branches, generated responses, and saved files. Execution makes live model requests and writes output files.

RequestExpected route
Book me a flight to London.BOOKING
What is the capital of Italy?INFO
Do that thing for me.UNCLEAR

Successful execution shows that the nodes completed. Review the generated text to confirm that each answer follows its selected instructions. This example uses ordinary text classification and has no configured fallback route or conversation memory.

Info: View the complete workflow as JSON at routing-example-workflow.json.

Summary

The n8n implementation separates classification, routing, and response generation into visible workflow steps. A Basic LLM Chain classifies each request, a Switch selects the instructions, and a shared second chain generates the answer. The same routing pattern used in Java is expressed through items, expressions, and node connections, with each stage available for inspection.

Info: This post was extensively edited with assistance from OpenAI Codex. All work remains the author’s own.

Agentic Design Patterns Using Java – Routing Pattern

Image generated in ChatGPT

The routing pattern directs an incoming request to a suitable handler. A router determines the request’s category or intent, then selects an agent, tool, or workflow. Classification can use predefined rules or a model, allowing each handler to focus on a specific task. In this blog post, you explore using the routing pattern from the book Agentic Design Patterns using Java (Spring AI, LangChain4j, and OpenAI Java SDK).

Info: This post implements the same routing example with Spring AI, the OpenAI Java SDK, and LangChain4j. Using the same requests and instructions makes their differences in configuration, model calls, and handler selection easier to compare.

Antonio Gulli’s Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems presents 21 patterns for building AI agents, including prompt chaining, routing, planning, and multi-agent collaboration. The book combines explanations with runnable examples using LangChain, LangGraph, CrewAI, and Google ADK, showing how to assemble individual capabilities into more complex AI workflows. The book uses Python as the implementation language. In this series, I implement the book’s examples using Java and n8n.

Info: See Agentic Design Patterns Using n8n – Routing Pattern for an implementation of this pattern as an n8n workflow.

The routing example in chapter two of Gulli’s book has three categories.

  • BOOKING: Requests related to flights or hotels.
  • INFO: General information questions.
  • UNCLEAR: Ambiguous requests or requests outside the other categories.

The example uses three sample requests.

  • Book me a flight to London.
  • What is the capital of Italy?
  • Do that thing for me.

The coordinator classifies the input. Java code or a conditional workflow then selects the handler that processes the original request.

The booking handler acknowledges a travel request without making a reservation. The information handler answers from the model’s knowledge without a live search. The unclear handler is instructed to reply, “Your request was unclear.”

Info: The Java examples are available in the project repository, with subprojects for Spring AI, the OpenAI Java SDK, and LangChain4j.

All three examples use the following classification and handler instructions.

Classify the user's request into exactly one category:
BOOKING: Requests related to booking flights or hotels.
INFO: General information questions.
UNCLEAR: Ambiguous requests or requests outside those categories.
Return only BOOKING, INFO, or UNCLEAR. Do not answer the request itself.

INFO

You are an information assistant.
Answer the user's general knowledge question briefly and clearly.
Acknowledge uncertainty when you do not know the answer.
Do not claim to have searched the web or checked live information.
Do not ask questions or request additional details.

BOOKING

You are a booking assistant.
Acknowledge the user's travel request without asking questions or requesting
additional details.
Keep your response brief.
Do not claim to have booked anything or checked live availability.

UNCLEAR

Reply only with: Your request was unclear.
Do not ask questions or request additional details.

Each successfully processed request normally makes two model calls: one for classification and one for the selected handler’s response. All three versions pass the original request to the handler, including UnclearHandler, which uses a model call even though its instructions request fixed wording.

Routing with Spring AI

Organizing the application

Spring AI uses a shared ChatClient and Spring-managed classes. CoordinatorAgent handles both classification and handler selection.

There are three main responsibilities.

  • AgenticpatternsApplication implements CommandLineRunner and selects the example using the ROUTING argument.
  • RoutingExampleService supplies sample requests and displays their responses.
  • CoordinatorAgent classifies each request, selects a handler, and returns its answer.

Creating the shared client

The ChatClientConfig configuration class provides one shared ChatClient bean.

@Bean
public ChatClient routingChatClient(ChatClient.Builder builder) {
    return builder.build();
}

Spring AI supplies the configured ChatClient.Builder. The coordinator and handlers receive the resulting client through constructor injection.

Info: Sharing a client shares configuration and does not automatically share conversation history or combine the coordinator’s instructions with a handler’s instructions (see chapter 8, Memory Management).

Processing the sample requests

The RoutingExampleService Spring service defines the requests.

private static final List<String> REQUESTS = List.of(
            "Book me a flight to London.",
            "What is the capital of Italy?",
            "Do that thing for me.");

RoutingExampleService receives a CoordinatorAgent. When AgenticpatternsApplication runs with the ROUTING command-line argument, it calls the service’s runExample() method.

The service loops through the requests and calls coordinator.handleRequest(request) for each one.

for (String request : REQUESTS) {
  String response = coordinator.handleRequest(request);
}

Classifying and routing requests

The CoordinatorAgent defines instructions to examine a request and identify it as one of the three RequestCategory values.

private static final String INSTRUCTIONS = """
            Classify the user's request into exactly one category:
            BOOKING: Requests related to booking flights or hotels.
            INFO: General information questions.
            UNCLEAR: Ambiguous requests or requests outside those categories.
            Return only BOOKING, INFO, or UNCLEAR. Do not answer the request itself.
            """;

The classification is represented by the RequestCategory enum.

public enum RequestCategory {
    BOOKING,
    INFO,
    UNCLEAR;
}

The coordinator passes its instructions and the original request to ChatClient. It converts the returned text to RequestCategory with RequestCategory.valueOf(requestType.trim()).

public String handleRequest(String request) {
	String requestType = chatClient.prompt()
		.system(INSTRUCTIONS)
		.user(request)
		.call()
		.content();
		
	RequestCategory category;
	
	try {
		category = RequestCategory.valueOf(requestType.trim());
	} catch (IllegalArgumentException exception) {
		throw new IllegalStateException("Invalid category", exception);
	}
	
	return routeRequest(category, request);
}

.system(INSTRUCTIONS) supplies the classification rules, and .user(request) supplies the original request. .call() performs the model call, and .content() returns the generated text.

The coordinator’s routeRequest() method selects an InfoHandler, BookingHandler, or UnclearHandler and passes the original request with that handler’s instructions.

private String routeRequest(RequestCategory requestCategory, String request) {
	return switch (requestCategory) {
	case INFO -> infoHandler.handle(request, InfoHandler.INSTRUCTIONS);
	case BOOKING -> bookingHandler.handle(request, BookingHandler.INSTRUCTIONS);
	case UNCLEAR -> unclearHandler.handle(request, UnclearHandler.INSTRUCTIONS);
	};
}

Sharing the handler implementation

Each handler extends RequestHandler and inherits its concrete handle(request, instructions) method. The subclasses supply their own INSTRUCTIONS constants without overriding the method.

public String handle(String request, String instructions)
{
     String response = chatClient.prompt()
	   .system(instructions)
           .user(request)
           .call()
           .content();
    return response;
}

The sequence diagram follows a request from RoutingExampleService through classification and response generation. CoordinatorAgent selects the handler and passes the original request with that handler’s instructions.

Info: Spring AI source code on GitHub

Routing with OpenAI Java SDK

The OpenAI Java SDK version constructs its objects directly in main(). The coordinator classifies requests, while RoutingExample selects the handler. A shared OpenAiTextService makes the model calls. OpenAIOkHttpClient.fromEnv() reads client settings from the environment, and ProviderModelSettings.MODEL_NAME supplies the model name.

Creating the client and selecting handlers

RoutingExample.main() creates the OpenAI client, the shared text service, the coordinator, and three handlers. It classifies each sample request, selects a handler with a Java switch, and passes that handler the original request.

public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();
	try {
		OpenAiTextService textService = new OpenAiTextService(client, 
			ProviderModelSettings.MODEL_NAME);
		CoordinatorAgent coordinatorAgent = new CoordinatorAgent(textService);
		BookingHandler bookingHandler = new BookingHandler(textService);
		InfoHandler infoHandler = new InfoHandler(textService);
		UnclearHandler unclearHandler = new UnclearHandler(textService);
		String[] requests = {
			"Book me a flight to London.",
			"What is the capital of Italy?",
			"Do that thing for me."
		};

		for (String request : requests) {
			RequestCategory category = coordinatorAgent.classify(request);
			RequestHandler handler = switch (category) {
				case BOOKING -> bookingHandler;
				case INFO -> infoHandler;
				case UNCLEAR -> unclearHandler;
			};

			String response = handler.handle(request);
		}
	} finally {client.close();}
}

Classifying and routing requests

CoordinatorAgent.classify(request) calls textService.generate(INSTRUCTIONS, request) with the classification instructions. It converts the returned text to RequestCategory using RequestCategory.valueOf(response.trim()). The switch in main() then selects the handler.

Each handler implements the RequestHandler interface and defines handle(String request). That method calls the shared text service with the handler’s own instructions and the original request. In the Spring AI version, the handlers instead inherit a shared implementation from an abstract class.

Calling the model through a shared service

OpenAiTextService holds a shared OpenAIClient that sends requests through the Responses API. Both the coordinator and the handlers use this service.

The generate(instructions, request) method builds the request parameters, calls client.responses().create(params), and extracts the generated text. The project also checks completion status, refusals, and blank output; those checks are omitted from this snippet.

public String generate(String instructions, String request) {
	ResponseCreateParams params = ResponseCreateParams.builder()
		.model(modelName)
		.instructions(instructions)
		.input(request)
		.build();

	Response response = client.responses().create(params);
	
	String text = response.output().stream()
		.flatMap(item -> item.message().stream())
		.flatMap(message -> message.content().stream())
		.flatMap(content -> content.outputText().stream())
		.map(outputText -> outputText.text())
		.collect(Collectors.joining());

	return text;
}

Building parameters and reading the response

ResponseCreateParams is a class in the official OpenAI Java SDK that holds the parameters for a request to the Responses API. Here, .model(modelName) selects the model, .instructions(instructions) supplies the system or developer instructions that guide its behavior, and .input(request) provides the user’s request.

Response is the OpenAI Java SDK class that represents the result returned by the Responses API, including generated output, completion status, and token usage. In this statement, client.responses().create(params) sends the configured request to OpenAI and assigns the returned result to response.

Info: See Creating a model response in the OpenAI Java API reference.

The sequence diagram shows the two model calls made through OpenAiTextService. The coordinator returns a category to RoutingExample, which selects a handler and calls it with the original request.

Info: Github OpenAI SDK example project (openai).

Routing with LangChain4j

The LangChain4j implementation defines the coordinator and handlers as annotated Java interfaces. LangChain4j supplies their implementations at runtime, and its agentic module provides the conditional workflow that selects a handler.

The three steps remain the same: classify the request, select a handler, and generate an answer. Annotations define the model messages, builders create the agents, and workflow state carries data between steps.

Creating the shared model

RoutingExample.main() begins by constructing an OpenAiChatModel.

OpenAiChatModel model = OpenAiChatModel.builder()
        .apiKey(ProviderModelSettings.API_KEY)
        .modelName(ProviderModelSettings.MODEL_NAME)
        .build();

OpenAiChatModel is LangChain4j’s OpenAI chat-model implementation. ProviderModelSettings reads the API key from OPENAI_API_KEY and selects gpt-4o-mini.

The coordinator and all three handlers receive the same model object when built. Each agent still has its own instructions and receives its own input.

The project uses three LangChain4j dependencies: langchain4j supplies the AI Services functionality, langchain4j-open-ai provides the OpenAI integration, and langchain4j-agentic supplies agent construction and workflow orchestration.

Defining model behavior with interfaces

CoordinatorAgent is an interface containing one annotated method.

public interface CoordinatorAgent {

    @Agent("Classifies a request for routing to the appropriate handler")
    @SystemMessage("""
            Classify the user's request into exactly one category:
            BOOKING: Requests related to booking flights or hotels.
            INFO: General information questions.
            UNCLEAR: Ambiguous requests or requests outside those categories.
            Return only BOOKING, INFO, or UNCLEAR. Do not answer the request itself.
            """)
    @UserMessage("{{request}}")
    RequestCategory classify(@V("request") String request);
}

The interface declares classify() without a method body. LangChain4j creates an implementation that builds the messages, calls the model, and converts the output to RequestCategory. The Spring AI and OpenAI SDK examples perform that conversion explicitly in Java (LangChain4j AI Services).

The annotations divide the declaration into four parts.

AnnotationPurpose in this example
@AgentIdentifies the method as an agent operation and supplies its description.
@SystemMessageDefines the classification instructions.
@UserMessageDefines the user-message template.
@V("request")Associates the method argument with the template variable named request.

The handler interfaces follow the same structure. For example, BookingHandler uses these annotations as follows.

@Agent("Handles flight and hotel booking inquiries")
@SystemMessage("""
        You are a booking assistant.
        Acknowledge the user's travel request without asking questions or requesting additional details.
        Keep your response brief.
        Do not claim to have booked anything or checked live availability.
        Do not ask questions or request additional details.
        """)
@UserMessage("{{request}}")
String handle(@V("request") String request);

The handler returns the model’s response as a String. InfoHandler and UnclearHandler use the same method signature with different system instructions.

Building executable agents

An annotated interface describes an agent, but the application still needs an object it can invoke. AgenticServices.agentBuilder() creates that object.

BookingHandler bookingHandler =
        AgenticServices.agentBuilder(BookingHandler.class)
                .chatModel(model)
                .outputKey("response")
                .build();

BookingHandler.class identifies the interface to implement and .chatModel(model) supplies the configured model. The .build() method returns an implementation assignable to BookingHandler. The coordinator, information handler, and unclear handler are constructed in the same way.

AgenticServices provides factory methods for creating agents and workflows (AgenticServices API).

The .outputKey("response") setting names the state entry where the handler’s return value is stored. All three handlers use the same key because each selected branch produces the workflow’s answer.

Defining the conditional workflow

The earlier implementations select a handler with a Java switch. This implementation registers conditions and their associated agents with a conditional workflow.

UntypedAgent handlers = AgenticServices
        .conditionalBuilder()
        .subAgents(
                scope -> scope.readState("category")
                        == RequestCategory.BOOKING,
                bookingHandler)
        .subAgents(
                scope -> scope.readState("category")
                        == RequestCategory.INFO,
                infoHandler)
        .subAgents(
                scope -> scope.readState("category")
                        == RequestCategory.UNCLEAR,
                unclearHandler)
        .output(scope -> scope.readState("response"))
        .build();

Each .subAgents(...) call associates a Java predicate with a handler. The predicate reads the category from workflow state and compares it with an enum constant. For these three mutually exclusive conditions, one handler matches the supplied category.

The model determines the category during classification. The conditional workflow evaluates the Java predicates to determine which handler executes. The descriptions in @Agent do not select these branches (Conditional workflow API).

The final .output(...) function defines the workflow’s return value. After the selected handler stores its answer under "response", this function reads that entry and returns it to the caller.

Passing data through AgenticScope

The scope parameter is an AgenticScope, the shared execution context for a workflow. Conditions and agents read or write its named state entries. This example uses "request" for the original text, "category" for the classification, and "response" for the answer (AgenticScope API).

The application supplies the initial values through a map.

RequestCategory category = coordinatorAgent.classify(request);

Map<String, Object> arguments = Map.of(
        "request", request,
        "category", category
);

Object response = handlers.invoke(arguments);

UntypedAgent provides a general workflow entry point accepting a map of named inputs and returning Object. LangChain4j makes those inputs available in the workflow’s scope. It uses the handler parameter’s @V("request") name to resolve the original request from state. The category controls selection; it is not included in the handler’s user-message template. Agents and Agentic AI

For a booking request, the data moves through the workflow as follows.

  1. coordinatorAgent.classify(request) returns RequestCategory.BOOKING.
  2. The application supplies "request" and "category" to handlers.invoke(...).
  3. The booking predicate matches, and the workflow invokes bookingHandler.
  4. The generated handler implementation calls the model with its booking instructions and the original request.
  5. The handler’s answer is stored under "response", which the workflow returns.

The coordinator is called separately before the conditional workflow. Although its builder also specifies .outputKey("response"), that setting does not populate the handler workflow’s "category" entry. The application explicitly transfers the classification into the input map.

The sequence diagram shows how classification feeds the conditional workflow. The workflow evaluates the category predicates, invokes the matching handler, and returns its response through AgenticScope.

Info: Github LangChain4j example project (langchain4j).

Other Resources

The following documentation and examples provide more detail on the APIs used in this post. Some resources also cover related forms of routing: choosing a model, a provider, or a source of retrieved content.

Spring AI

Start with the reference documentation and examples repository for ChatClient and routing workflows. The community articles below include additional implementations and related model-routing and gateway examples.

ResourceDescriptionLink
Reference documentationModel configuration and the ChatClient API.Spring AI reference
Official examplesSpring AI sample projects, including routing workflows.Examples repository
Routing walkthroughClassification followed by a specialized prompt.Routing Workflow with Spring AI
Patterns overviewRouting alongside other application patterns.Five Spring AI Agentic Patterns
Workflow examplesRouting, failure handling, and model-call costs.Spring AI workflow patterns
Model routingSelects a model using Spring AI TypeSafe and Jev.Model router walkthrough and example code
Provider gatewayProvider routing, failover, and rate limiting.LLM Gateway for Java
Framework sourceSpring AI source code and project documentation.Spring AI repository

OpenAI Java SDK

The SDK reference describes request parameters, response types, and model calls. The repository includes Java examples. In the implementation shown here, the application supplies the classification and handler-selection logic.

ResourceDescriptionLink
API referenceJava request parameters and response types.OpenAI Java API reference
Source and examplesSDK source, setup instructions, and usage examples.OpenAI Java SDK repository
Libraries overviewOpenAI client libraries and installation guidance.OpenAI libraries

LangChain4j

The AI Services and agentic documentation explain the interfaces and conditional workflow used in this post. Model routing and retrieval routing are related features: they select a model or content retriever rather than one of this example’s handler agents.

ResourceDescriptionLink
Reference documentationFramework introduction and integration guides.LangChain4j documentation
AI ServicesAnnotated interfaces, prompt templates, and output conversion.AI Services guide
Agents and workflowsAgent builders, conditional workflows, and AgenticScope.Agents and Agentic AI
Model routingSelects a ChatModel through a ChatModelRouter.Model routing guide
RoutingChatModelSource for the model-routing implementation.API / source
DecisionModelChatModelRouterUses a decision model to select a route.Javadoc
Retrieval routingSelects content retrievers for a query.QueryRouter Javadoc and example code
Decision routerDecisionRouterPlanner for agent selection.Javadoc
Framework sourceLangChain4j source code and project documentation.LangChain4j repository

Summary

All three implementations follow the same routing pattern: classify the request, select a handler, and generate a response. Spring AI uses Spring-managed classes and a shared ChatClient. The OpenAI Java SDK keeps model calls and routing explicit in Java. LangChain4j creates implementations from annotated interfaces and executes handlers through a conditional workflow. The example stays the same, making it easier to compare how each approach handles prompts, classification, and handler selection.

Info: This post was extensively edited with assistance from OpenAI Codex. All work remains the author’s own.

Code Snippet Generation – Postman Killer Feature

The other day I was supporting a client in my day job by helping him use Postman to generate HTTP Post requests. The problem was, that his language of choice was Dart, a language I had never heard of, much less used. I’ve worked with Postman for quite some time, but I never clicked this discrete link to the right of the request.

Imagine my surprise when I clicked that link and a code snippet showing the Dart code.

It generates cURL requests,

Python code snippets,

Node.js code snippets,

and many more. For example, Postman can generate snippets for over 30 different languages or frameworks.

How to Generate Python Code Snippets

Create the request you desire, for example, the following is a simple GET request listing available APIs on the API Guru website.

  • Click the small Code generate button.
  • Select your desired language or framework.
  • Click the copy icon to copy the code snippet to your clipboard.

Here’s a video by a member of the Postman team showing how to use the code snippet generation feature.

Powerful PDF Generation Using DynamicPDF Cloud API

I’ve been working as the Developer Evangelist for DynamicPDF for some time now. As well as our desktop/server product, we offer a cloud version of our software: DynamicPDF Cloud API. It’s a powerful cloud API for creating and manipulating PDFs for your business. In this post, I outline some of its features and why you should use it if you create PDFs for your organization.

The cloud API is built on the powerful DynamicPDF Core Suite, a software platform that has been used for several decades by many of the world’s largest corporations.

The API consists of the following REST endpoints:

  • dlex-layout,
  • pdf-info,
  • pdf-xmp,
  • image-info,
  • and pdf.
ENDPOINTDOCUMENTATIONDESCRIPTION
image-infoCloud API Users Guide – image-infoReturns image metadata as a JSON document.
pdf-infoCloud API Users Guide – pdf-InfoReturns PDF metadata as a JSON document.
pdf-textCloud API Users Guide – pdf-textReturns the text from a PDF as a JSON document.
pdf-xmpCloud API Users Guide – pdf-xmpReturns XMP metadata from a PDF.
pdfCloud API Users Guide – pdfReturns a PDF after performing one of the pdf endpoint’s tasks (page, dlex, html, word, image) or merging.
dlex-layoutCloud API Users Guide – dlex-layoutReturns a PDF after performing one of the PDF endpoint’s tasks (page, dlex, html, word, image) or merging.
REST Endpoint documentation

DynamicPDF Designer Online

DynamiciPDF Cloud API also offers the following client libraries to make using the endpoints easier.

  • C#
  • Java
  • Node.js
  • PHP
  • Go
  • Python

It also offers – arguably the most powerful tool available anywhere online – DynamicPDF Designer Online, a graphical tool for creating rich PDF documents using your organization’s business data.

The API is free to try, and the documentation and support are top-notch. I should know – I wrote most the documentation, tutorials, and example code. There are tons of tutorials, and our support is great.

Sending Data to Kinesis Firehose Using Python

In this tutorial you create a simple Python client that sends records to an AWS Kinesis Firehose stream created in a previous tutorial Using the AWS Toolkit for PyCharm to Create and Deploy a Kinesis Firehose Stream with a Lambda Transformation Function. This tutorial is about sending data to Kinesis Firehose using Python and relies on you completing the previous tutorial.

Here you use the put_record and the put_record_batch functions to write data to the Kinesis Firehose client using Python. If after completing the previous tutorial you wish to refer to more information on using Python with AWS, refer to the following two information sources.

In the previous tutorial you created an AWS Kinesis Firehose stream for streaming data to an S3 bucket. Moreover, you wrote a Lambda function that transformed temperature data from Celsius or Fahrenheit to Kelvin. You also sent individual records to the stream using the Command Line Interface (CLI) and its firehose put-record function.

In this tutorial you write a simple Kinesis Firehose client using Python to the stream created in the last tutorial (sending data to Kinesis Firehose using Python). Specifically, you use the put-record and put-record-batch functions to send individual records and then batched records respectively.

Creating Sample Data

  • Navigate to mockaroo.com and create a free account.
  • Click Schemas to create a new schema.
  • Name the schema, here I named it SampleTempDataForTutorial.

Creating a schema in Mockaroo
  • Create a field named station and assign its type as State (abbrev).
  • Create a field named temp and assign it as Number with a min of one, max of 100, and two decimals.
Creating the SampleTempDataForTutorial data in Mockaroo

  • Click the fx button and create the formula as follows.
if random(0,10) == 10 then this = this + 1000 end
if this > random(0,100) then format(this,2) + 'F' 
elseif this < random(0,100) then format(this,2) + 'f'
elseif this > random(0,75) then format(this,2) + 'c'
else format(this,2) + 'C' end

The formula randomly generates temperatures and randomly assigns an F, f, C, or c postfix. Note that it also generates some invalid temperatures of over 1000 degrees. You will use this aberrant data in a future tutorial illustrating Kinesis Analytics.

Creating a formula in Mockaroo for a field
  • Click Apply to return to the main screen.
  • Enter 1000 for rows, select Json as the format, and check the array checkbox.
  • Click download to download the data.
[{"station":"OH","temp":"26.39f"},
{"station":"WA","temp":"40.00F"},
{"station":"TX","temp":"15.01F"},
{"station":"NC","temp":"32.36f"},
{"station":"WA","temp":"62.86F"},
{"station":"NC","temp":"49.43f"},
{"station":"MD","temp":"2.30f"},
<< snip >>

You should have a file named SampleTempDataForTutorial.json that contains 1,000 records in Json format. Be certain the data is an array, beginning and ending with square-brackets.

Python Client (PsyCharm)

Here I assume you use PsyCharm, you can use whatever IDE you wish or the Python interactive interpreter if you wish. Let’s first use the put-record command to write records individually to Firehose and then the put-record-batch command to batch the records written to Firehose.

Writing Records Individually (put_record)

  • Start PsyCharm. I assume you have already installed the AWS Toolkit and configured your credentials. Note, here we are using your default developer credentials.

In production software you should use appropriate roles and and a credentials provider, do not rely upon a built-in AWS account as you do here.

Create a new Pure Python project in PsyCharm
  • Create a new file named FireHoseClient.py and import Boto3 and json.
  • Create a new session using the AWS profile you assigned for development.
  • Create a new firehose client from the session.
Creating a session using default AWS credentials
  • Write the following code.
import json
import boto3

session = boto3.Session(profile_name='default')
temperatureClient = session.client('firehose')

with open("sampleTempDataForTutorial.json") as json_file:
    observations = json.load(json_file)
    for observation in observations:
        print(observation)
        response = temperatureClient.put_record(
           DeliveryStreamName='temperatureStream',
           Record={
                'Data': json.dumps(observation)
            }
        )
        print(response)

In the preceding code you open the file as a json and load it into the observations variable. You then loop through each observation and send the record to Firehose using the put_record method. Note that you output the record from json when adding the data to the Record.

You should see the records and the response scroll through the Python Console.

  • Navigate to the AWS Console and then to the S3 bucket.
Data created in S3
  • You should see the records written to the bucket.
  • Open the file to ensure the records were transformed to kelvin.
Data converted to kelvin in S3

Batch Writing Records (put_record_batch)

Writing records individually are sufficient if your client generates data in rapid succession. However, you can also batch data to write at once to Firehose using the put-record-batch method.

  • Replace the code with the following code.

import json
import boto3

session = boto3.Session(profile_name='default')
temperatureClient = session.client('firehose')
records = []

with open("sampleTempDataForTutorial.json") as json_file:
    observations = json.load(json_file)
    count = 1
    for observation in observations:
        if count % 500 == 0:
            response = temperatureClient.put_record_batch(
                DeliveryStreamName='temperatureStream',
                Records= records
            )
            print(response)
            print(len(records))
            records.clear()
        record = {
            "Data": json.dumps(observation)
        }
        records.append(record)
        count = count + 1

    if len(records) > 0:
        print(len(records))
        response = temperatureClient.put_record_batch(
                DeliveryStreamName='temperatureStream',
                Records= records
            )
        print(response)

In the preceding code you create a list named records. You also define a counter named count and initialize it to one. The code loops through the observations. Each observation is written to a record and the count is incremented. When the count is an increment of 500 the records are then written to Firehose. Note that Firehose allows a maximum batch size of 500 records. After looping through all observations, any remaining records are written to Firehose.

The data is written to Firehose using the put_record_batch method. Instead of writing one record, you write list of records to Firehose.

  • Before executing the code, add three more records to the Json data file.
  • Run the code and you should see output similar to the following in the Python Console.
Python Console output
  • Navigate to the S3 bucket in the AWS Console and you should see the dataset written to the bucket.
Data written to S3 bucket
  • Open the records and ensure the data was converted to kelvin.
Data converted to kelvin in S3 bucket

Summary

This tutorial was on sending data to Kinesis Firehose using Python. You wrote a simple python client that wrote records individually to Firehose. You then wrote a simple python client that batched the records and wrote the records as a batch to Firehose. Refer to the Python documentation for more information on both commands. In the next tutorial you will create a Kinesis Analytics Application to perform some analysis to the firehose data stream.

GitHub Project

A Kinesis Firehose Stream and Lambda Function Tutorial.

Warning – Kinesis Firehose Stream Lambda function tutorial could incur an excess cost. Unless you plan on performing the other tutorials, delete your AWS resources to avoid incurring a cost.

This tutorial was tested on OS-X and Windows 10.

In this tutorial you create a semi-realistic example of using AWS Kinesis Firehose. You also create a Kinesis Firehose Stream Lambda function using the AWS Toolkit for Pycharm to create a Lambda transformation function that is deployed to AWS CloudFormation using a Serverless Application Model (SAM) template. After that, you then create the Kinesis Firehose stream and attach the lambda function to the stream to transform the data.

Introduction

Amazon Web Services Kinesis Firehose is a service offered by Amazon for streaming large amounts of data in near real-time. Streaming data is continuously generated data that can be originated by many sources and can be sent simultaneously and in small payloads. Logs, Internet of Things (IoT) devices, and stock market data are three obvious data stream examples. Kinesis Streams Firehose manages scaling for you transparently. Firehose allows you to load streaming data into Amazon S3, Amazon Redshift, Amazon Elasticsearch Service, and Splunk. You can also transform the data using a Lambda function. Firehose also allows easy encryption of data and compressing the data so that data is secure and takes less space. For more information, refer to Amazon’s introduction to Kinesis Firehose.

If you prefer watching a video introduction, the following is a good Kinesis Firehose overview.

AWS Introduction to Kinesis Firehose

Other Tutorials

Although this tutorial stands alone, you might wish to view some more straight-forward tutorials on Kinesis Firehose before continuing with this tutorial. Here we add complexity by using Pycharm and an AWS Serverless Application Model (SAM) template to deploy a Lambda function.

The following is a good video demonstration of using Kinesis Firehose by Arpan Solanki. The example project focuses on the out of the box functionality of Kinesis Firehose and will make this tutorial easier to understand.

AWS Kinesis Firehose demo by Arpan Solanki

Tasks Performed Here

In this tutorial you add more complexity to the more straightforward demonstrations on using Kinesis Firehose. Rather than creating the Lambda function while creating the Kinesis Stream, you create a more realistic Lambda function using Pycharm. Moreover, you deploy that function using an AWS Serverless Application Model (SAM) template. We will perform the following tasks in this tutorial.

  • Create and test a Kinesis Firehose stream.
  • Create a Lambda function that applies a transformation to the stream data.
  • Deploy the Lambda function using a Serverless Application Model (SAM) template.
  • Modify the Kinesis Firehose stream to use the Lambda data transformer.
  • Test the Kinesis Firehose stream.
  • Trace and fix an error in the Lambda function.
  • Redeploy the Lambda function.
  • Test the Kinesis Firehose stream

Sample Project Architecture

Assume we have many locations that record the ambient temperature. We need to aggregate this data from the many different locations in almost real-time. We decide to use AWS Kinesis Firehose to stream data to an S3 bucket for further back-end processing.

Data is recorded as either fahrenheit or celsius depending upon the location sending the data. But the back-end needs the data standardized as kelvin. To transform data in a Kinesis Firehose stream we use a Lambda transform function. The following illustrates the application’s architecture.

Tutorial application architecture

Prerequisites

This tutorial expects you to have an AWS developer account and knowledge of the AWS console. You should have PyCharm with the AWS Toolkit installed and the AWS CLI also installed.

This tutorial requires a rudimentary knowledge of S3, CloudFormation and SAM templates, Lambda functions, and of course, Python. The following links should help if you are missing prerequisites.

Kinesis Firehose

AWS Kinesis Firehose is a fully managed service

Create Stream

  • Log in to the AWS Console and select Services and then Kinesis.
  • Click Get Started if first time visiting Kinesis.
  • Click Create delivery stream in the Firehose panel.
Create delivery stream option on Amazon Kinesis dashboard (if no defined streams)

Name the Stream

  • Name the delivery stream temperatureStream.
  • Accept the default values for the remaining settings.
  • Click Next.
Create delivery stream – first step

A data producer is any application that sends data records to Kinesis Firehose. By selecting Direct PUT or other sources you are allowing producers to write records directly to the stream.

  • Accept the default setting of Disabled for Transform source records with AWS Lambda and Convert record format.
  • Click Next.
Create delivery stream – second step

The Transform source records with AWS Lambda allows you to define a Lambda function. Later in this tutorial you will change this setting and define a Lambda function. For now, leave it disabled.

Configure S3 Bucket

  • Select Amazon S3 as the Destination.
  • Under the S3 destination, click Create new.
  • Name the S3 bucket with a reasonable name (remember all names must be globally unique in S3). Here I use the name temperaturebucket123 as the bucket name and select the appropriate Region.
Create S3 bucket for stream

Configure Permissions

  • Click Next.
  • Accept the defaults and scroll to the Permissions section.
  • Click Create new or choose to associate an IAM role to the stream.
Create new or choose IAM role for stream

  • Create a role named temperature_stream_role (we return to this role in a moment) by accepting the defaults.
  • Click Allow.
  • Click Next after returned to the stream creation.
Create Role
  • Review the delivery stream and click Create delivery stream to create the stream.
Select newly created role by clicking temperature_stream_role
  • You should be taken to the list of streams and the Status of temperatureStream should be …Creating.
Delivery stream console after created.
  • After the stream’s status is Active, click on temperatureStream to be taken to the stream’s configuration page.
  • Click on the IAM role to return to the role settings in IAM.
  • Now, we are being very lazy…you would not do this in production, but delete the attached policy and attach the AWSLambdaFullAccess, AmazonS3FullAccess, and AmazonKinesisFirehoseFullAccess roles.

Here we are granting the role too much access. In reality, you should grant the minimal access needed in a production setting.

For simplicity (not for production use), delete policy and add the following three policies to role

Test Stream

For a simple stream such as what you just developed AWS provides an easy means of testing your data. Let’s test your data before continuing development.

  • If not on the stream configuration screen, select the stream on the Kinesis dashboard to navigate to the stream’s configuration screen.
  • Expand the Test with demo data section.
  • Click the Start sending demo data button.
  • Wait about a minute and click the Stop sending demo data button.
Test data option on stream summary on AWS console
  • From the Amazon S3 destination section click on the bucket name to navigate to the S3 bucket. Be certain to wait five minutes to give the data time to stream to the S3 bucket.

If you tire of waiting five minutes, return to the stream’s configuration and change the buffer time to a smaller interval than 300 seconds.

The Buffer interval allows configuring the time frame for buffering data.
S3 bucket link on stream summary on AWS console
  • Click on the sub-folders until taken to the data file. If you do not see the top level folder, then wait five minutes and refresh the page. Remember, the data is buffered.
S3 Bucket top level folder after test data written

  • Open the file and you should see the test records written to the file.
Test data written to S3 bucket by Kinesis Firehose
  • Navigate to the top level folder and delete the test data. Be certain you delete the top level folder and not the bucket itself.
Delete test data by deleting top level folder
  • Open a command-line terminal on your computer and enter the following aws firehose put-record commands.

These commands worked with cli 1.18.11 on OS-X and they worked in Git-Bash on Windows 10. If you can get these working in Windows 10 command-line, please post in comments, as I wasted hours trying to send using cmd.

> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="99.55F"'
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="33.22C"'
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="57.99f"'

You should see something similar to the following in your command-line terminal.

AWS firehose put-record commands in command-line terminal

For details on the put-record command refer to the AWS reference page on the command (AWS CLI Command Reference: put-record).

  • Return to the AWS Console and navigate to the S3 bucket and note the data was written to the bucket. Remember to allow the records time to process by waiting five minutes.
  • Rather than sending a simple string, modify the commands to send Json. Note that you escape the double-quotes.

See warning above regarding instability of cli accepted input.

> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="{\"station\":\"A1\",\"temp\":\"57.99f\"}"'
  • Return to the AWS Console and you should see a file in the S3 bucket with data formatted as follows. Do not forget to give the record time to stream before checking the S3 bucket.
{"station":"A1","temp":"57.99f"}{"station":"A1","temp":"57.99f"}

In the sample architecture note that the you need to convert the temperature data to kelvin. To accomplish this transformation you create a Lambda transform function for the Kinesis Firehose stream.

Lambda Function

Recall when creating the stream you were provided the option of transforming the data.

Transform source records option

Although you left this feature disabled, the requirements dictate that you need to modify temperature readings from fahrenheit or celsius to kelvin. Kinesis firehose provides an easy way to transform data using a Lambda function. If you referred to any of the linked tutorials above then you know that you can create and edit the Lambda function directly in the AWS console.

Here you develop the Lambda function in a local development environment, debug the function, and then deploy the function to AWS. Here you develop a Python Lambda function locally and deploy it to AWS using a CloudFormation SAM template.

PyCharm

Hopefully you have installed PyCharm and the AWS Toolkit. If not, do so now. Refer to the prerequisites above for information on installing both.

  • Start PyCharm.
  • Create a new AWS Serverless Application named kelvinTempConversion.
Creating a new AWS SAM Project
  • Click No if the following Create Project popup appears.
Select No to this dialog to create a project with new resources
  • Open the template.yaml folder and notice the generated SAM template.
  • Modify the timeout from 3 to 60 seconds (Kinesis Firehose requires a 60 second timeout).
SAM template generated by PyCharm
  • Right click the hello_world folder and select Refactor | Rename to rename the folder to kelvinConversion.
  • After reviewing the changes to be made, click the Do Refactor button.
Refactoring Hello World to kelvinConversion
  • Change all instances of HelloWorld with KelvinConversion in template.yaml.
  • Modify the function timeout (Globals:Function:Timeout:) to 60 seconds, the minimum for Kinesis Firehose.
  • Remove the Events section and the KelvinConversionApi section. These two sections are for building a public rest API. As we are developing a transformation function for our stream, neither is needed.
  • After modifying all instances of the hello world text, template.yaml should appear similar to the following.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  AWS

  Sample SAM Template for AWS

Globals:
  Function:
    Timeout: 60

Resources:
  KelvinConversionFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: kelvinConversion/
      Handler: app.lambda_handler
      Runtime: python3.8

Outputs:
  KelvinConversionFunction:
    Description: "Kelvin Conversion Lambda Function ARN"
    Value: !GetAtt KelvinConversionFunction.Arn
  KelvinConversionFunctionIamRole:
    Description: "Implicit IAM Role created for Kelvin Conversion function"
    Value: !GetAtt KelvinConversionFunctionRole.Arn

  • From the upper right drop down, select Edit Configurations.
  • Modify the template to reflect the new folder.
  • Click Ok.
Runtime configuration
  • Select the dropdown item and click the green arrow to run the application.
/usr/local/bin/sam local invoke --template /Users/jamesabrannan/PycharmProjects/kelvinTempConversion/.aws-sam/build/template.yaml --event "/private/var/folders/xr/j9kyhs2n3gqcc0n1mct4g3lr0000gp/T/[Local] KelvinConversionFunction-event.json" KelvinConversionFunction
Invoking app.lambda_handler (python3.8)

Fetching lambci/lambda:python3.8 Docker container image......
Mounting /Users/jamesabrannan/PycharmProjects/kelvinTempConversion/.aws-sam/build/KelvinConversionFunction as /var/task:ro,delegated inside runtime container
START RequestId: 1ffa20fa-486e-1827-e987-e92f16101778 Version: $LATEST
END RequestId: 1ffa20fa-486e-1827-e987-e92f16101778
REPORT RequestId: 1ffa20fa-486e-1827-e987-e92f16101778	Init Duration: 531.94 ms	Duration: 14.75 ms	Billed Duration: 100 ms	Memory Size: 128 MB	Max Memory Used: 24 MB	

{"statusCode":200,"body":"{\"message\": \"hello world\"}"}

  • Now that you are assured the project is configured correctly and executes locally, open app.py and replace the sample code with the following. Note that the line using the index string function is in error. This error is by design and you will fix it later in the tutorial.
import base64
import json
from decimal import Decimal

def lambda_handler(event, context):
    output = []

    for record in event['records'] :
        print(record['recordId'])
        payload = base64.b64decode(record['data']).decode('utf-8')
        print(payload)
        reading = json.loads(payload)
        print(reading)
        temp = reading['temp']
        print(temp)
        # note: this is in error, if celcius this causes error
        # this is fixed later in tutorial
        isfarenheit = bool(temp.upper().index('F') > 0)
        kelvin = 0

        if isfarenheit:
            print(float(temp.upper().strip('F')))
            kelvin = (float(temp.upper().strip('F')) + 459.67) * 5.0 / 9.0
        else:
            kelvin = float(temp.upper().strip('C')) + 273.15

        print("{:.2f}".format(kelvin))

        reading['temp'] = str("{:.2f}".format(kelvin))

        print(reading)

        output_record = {
            'recordId': record['recordId'],
            'result': 'Ok',
            'data': base64.b64encode(json.dumps(reading).encode('UTF-8'))
        }
        output.append(output_record)

    print('Processed {} records.'.format(len(event['records'])))

    return {'records': output}

Local Testing

To test the record you need to use an event template. There are event types you can choose, depending upon how the Lambda function is to be used.

  • From Event Templates select Kinesis Firehose.
Select Kinesis Firehose template to generate test data
  • Create the sample record {“station”:”A1″,”temp”:”99.33F”} and base64 encode the record. A good site to encode and decode is the base64encode.org website.
Encoding a simple Json record to Base64
  • Replace the data string generated when you selected the Kinesis Firehose Event Template and replace it with the base64 encoded string.
Modify data value with the newly encoded value
  • Run the application locally and you should see the returned record.
Console output from running application locally

  • Copy the data string and decode the record from base64.
Decode result from Base64 to string
  • Validate the converted kelvin measurement is correct.

Note, you only tested fahrenheit. This is by design to illustrate debugging in the AWS Console. You fix this error later in this tutorial.

Deploying Serverless Application

  • Right click on template.yaml and select Deploy Serverless Application from the popup menu.
Right click on template.yaml and select Deploy Serverless Application
  • Select Create Stack and name the stack kelvinTemperatureConversionStack.
  • Select or create an S3 Bucket.
  • Click Deploy.
  • If you receive a credentials error, then you need to configure the AWS Toolkit correctly.
  • At the extreme lower right of the window, click the message telling you the issue.
Error if AWS Toolkit credentials are not configured correctly
Profile settings configured for AWS Toolkit
  • After fixing credentials (if applicable) then try again. A dialog window should appear informing you of the deployment progress.
  • Notice that the window is using CLI Sam commands to deploy the function to AWS.
Deploying application output
Deploying application output

Verifying the Lambda Function

After deploying you should verify the function was deployed correctly.

Lambda Function

  • Navigate to the AWS Lambda service and you should see the newly created Lambda function.
Created Lambda function in AWS console

S3 Bucket

  • Navigate to the S3 buckets and you should see the newly created bucket used for deploying the Lambda function.
Created S3 bucket for deploying serverless application

AWS CloudFormation

  • Navigate to CloudFormation and you should see the created stack.
Cloudformation summary in AWS console

  • Return to the Kinesis Firehose stream to add the Lambda function to the stream.

For more information on using S3 from a Java application, refer to the tutorial Amazon Web Services Simple Queue Service Using the Java 2 Software Development Kit

Modifying Kinesis Firehose Stream

  • Navigate to the temperatureStream configuration page.
  • Click Edit.
  • Enable source record transformation in the Transform source records with AWS Lambda section.
  • Select the Lambda function created and deployed by PyCharm.
  • Click Save.

Testing Kinesis Firehose Stream Using CLI

  • Open a command-line window and send several records to the stream. Be certain to escape the double-quotes, with the exception of the double quotes surrounding the data record.
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="{\"station\":\"A1\",\"temp\":\"57.99f\"}"'
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="{\"station\":\"A1\",\"temp\":\"89.90F\"}"'
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="{\"station\":\"A1\",\"temp\":\"22.20C\"}"'
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="{\"station\":\"A1\",\"temp\":\"12.76C\"}"'
  • After waiting five minutes, navigate to the S3 bucket and you should see a new folder entitled processing-failed.
Processing-failed folder when Kinesis Firehose fails
  • Navigate down the processing-failed folder hierarchy and open the failure records.
Errors written to S3 Bucket
  • The error messages are not very informative. But at least they tell you the Lambda function processing caused the error.
  • Navigate to the stream and select Amazon S3 Logs.
  • The log message is also not very informative.
  • Navigate to the Lambda function details.

  • Select the LogStream from the most recent invocation of the Lambda function.
  • The detailed log records the exact cause of the error, the index function. Unlike some languages such as Java, the Python index function returns an error if the string is not found.

Fixing Error

  • Return to the PyCharm project to fix the error and redeploy the Lambda function to AWS.

You might notice that you can edit a function directly in the AWS Console. DO NOT EDIT! Remember, you deployed this application using SAM in CloudFormation. The correct process is to fix the function and then redeploy it using SAM.

Python implementation in the AWS Console
Data replaced with celcius value after encoding
  • Modify the function to use find rather than the index function.
isfarenheit = bool(temp.upper().find('F') > 0)
Lambda function results in error due to the index function
  • Run the application locally using a celsius value. As before encode and decode and test the converted value.

Lambda function successfully ran with celcius data
  • After testing, right click on template.yaml and redeploy the serverless application.
  • Accept the Update Stack defaults.
Update Stack option in Deploy Serverless Application
  • After clicking Deploy a popup window informs you of the deployment progress.
Redeploying SAM application to AWS
  • Navigate to the Lambda function details in the AWS Console and you should see the corrected source code.

Transformation function reflects changes made in PyCharm
  • From your command-line send several records to the stream.
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="{\"station\":\"A1\",\"temp\":\"12.76C\"}"'
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="{\"station\":\"A1\",\"temp\":\"57.99f\"}"'
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="{\"station\":\"A1\",\"temp\":\"89.90F\"}"'
> aws firehose put-record --delivery-stream-name temperatureStream --record='Data="{\"station\":\"A1\",\"temp\":\"22.20C\"}"'
  • Navigate to the S3 bucket and you should see the transformed records.
Data streamed to S3 bucket

Summary

In this tutorial you created a Kinesis FIrehose stream and created a Lambda transformation function. You configured the stream manually and used SAM to deploy the Lambda function. An obvious next step would be to add the creation of the Kinesis Firehose and associated bucket to the Cloudformation template in your PysCharm project. This tutorial was sparse on explanation, so refer to the many linked resources to understand the technologies demonstrated here better. However, this tutorial was intended to provide a variation on the numerous more straightforward Kinesis Firehose tutorials available.

Kinesis Firehose Stream Github Project

AWS Certified Developer Associate Study Guide

Attached find my study notes for the AWS Certified Developer Associate Exam. These notes were written in September 2019. The test may have changed considerably since then, so be certain to consult other sources.

I prepared for the AWS Certified Developer Associate exam through a combination of the A Cloud Guru’s Video course on Udemy, Whizlab’s practice exams, and my own study notes. I passed by the way.

AWS Key Management System ( AWS KMS) to Encrypt and Decrypt Using the AWS Java 2 SDK

In this tutorial we explore the AWS Key Management System (AWS KMS) to encrypt and decrypt data via the AWS Java 2 SDK. This tutorial encrypts/decrypts two different ways. We first encrypt and decrypt data directly using an AWS customer-managed key (CMK). We then encrypt and decrypt the data using a data key that was generated by the AWS CMK. Of the two, the second is more secure, and the preferred way to encrypt data. Although a CMK can encrypt and decrypt data, a better practice is to use the CMK to generate data keys, which are in turn used with the relevant data. However, for demonstration, we also use the CMK directly.

Introduction to AWS KMS

In this tutorial we use the AWS SDK for Java version 2.x and the AWS KMS for encrypting and decrypting resources.

AWS SDK for Java Version 2.x

In this tutorial we use the Java Version 2.x of the AWS SDK. The SDK provides a convenient wrapper around the AWS services’ lower-level REST calls. Be certain you use version 2.x and not 1.x, as 2.x is a rewrite of the API and so there are considerable differences between the two API versions.

AWS Key Management Service ( AWS KMS)

AWS KMS is a service that enables generating, storing, and managing symmetric keys. The service is integrated with other Amazon offerings such as S3. Actually, most AWS services are integrated with KMS, as this list of over 50 services illustrates. However, KMS can also be used to generate and manage your own application’s keys even if that application is independent of other AWS services.

A symmetric key is a single key used to encrypt/decrypt data. This is in contrast to an asymmetric key, where a private key and public key encrypt/decrypt data. Wikipedia has a good general introduction to key encryption: Key (Cryptography). A typical strategy for symmetric key encryption is as follows. A single master key is used to encrypt/decrypt data encryption keys. These data keys encrypt/decrypt your application’s data. To ensure security, when not in use, the data keys are encrypted/decrypted by the master key. The master key is then stored in a safe location so it can be used as needed.

AWS KMS provides a secure location to store and manage your master keys. CMKs cannot be exported from KMS and can only be used by users with appropriate permissions assigned. The KMS FAQ summarizes KMS.

AWS KMS is a managed service that enables you to easily encrypt your data. AWS KMS provides a highly available key storage, management, and auditing solution for you to encrypt data within your own applications and control the encryption of stored data across AWS services.

AWS Key Management Service FAQs

AWS KMS offers many benefits for developers using AWS services.

If you are a developer who needs to encrypt data in your applications, you should use the AWS Encryption SDK with AWS KMS support to easily use and protect encryption keys. If you’re an IT administrator looking for a scalable key management infrastructure to support your developers and their growing number of applications, you should use AWS KMS to reduce your licensing costs and operational burden. If you’re responsible for proving data security for regulatory or compliance purposes, you should use AWS KMS to verify that data is encrypted consistently across the applications where it is used and stored.

AWS Key Management Service FAQs

AWS KMS offers an integrated cloud environment for managing keys.

You can perform the following key management functions in AWS KMS:


Create keys with a unique alias and description
Import your own key material
Define which IAM users and roles can manage keys
Define which IAM users and roles can use keys to encrypt and decrypt data
Choose to have AWS KMS automatically rotate your keys on an annual basis
Temporarily disable keys so they cannot be used by anyone
Re-enable disabled keys
Delete keys that you no longer use
Audit use of keys by inspecting logs in AWS CloudTrail
Create custom key stores*
Connect and disconnect custom key stores*
Delete custom key stores*

* The use of custom key stores requires CloudHSM resources to be available in your account.

AWS KMS FAQ.

For more introductory information refer to The AWS Key Management Features webpage maintained by Amazon. Also refer to the videos embedded at the end of this tutorial.

In this tutorial we perform the following tasks:

  • create two users, one to manage a CMK and another to use the CMK,
  • create a CMK and assign the users to the key,
  • build an application that uses the CMK directly to encrypt/decrypt data,
  • discuss why using the CMK directly is not an optimal encryption strategy,
  • and create an application that uses the CMK to create a data key to encrypt/decrypt data.

In this tutorial we limit using KMS to generating a data key and to encrypting/decrypting data. You can also manage keys through the Java SDK; however, this tutorial does not cover key management, assuming instead you will do so through the AWS console or AWS Command-line Interface (CLI).

  • It is assumed you have an AWS account, know your way around the AWS Console, and have enough experience with Java programming that you do not require help using an IDE such as Eclipse.

Creating the CMK

Before using the CMK we need to create it. Although you can use the Java SDK to perform all the following tasks, we use the AWS Console for creating the required users and key.

Create Users

We need to create users for our CMK. The first user we create is the key manager. Although this tutorial does not subsequently use this user, we include it as in a real project you would eventually need this user for managing keys. The second user we create is the key user. This is the user that is allowed to use the CMK to encrypt/decrypt data. We do use this data in the Java application.

  • All Users, Keys, and potentially sensitive information will have been removed from my account before this tutorial is posted.

Create Manager

Let’s first create the manager user.

  • Navigate to IAM, Users, and add a User named KmsKeyManager.
  • Assign the user programmatic and console access.
  • Create a password for the user and uncheck the Require password reset checkbox.
Adding the KmsKeyManager user via the Add user page

  • When you add the user to groups, create a new group named KmsKeyTutorialGroup and assign it AdministratorAccess.
Adding policies to a KmsKeyTutorialGroup
  • Add KmsKeyManager to KmsKeyTutorialGroup.
Assing KmsKeyManager to KmsKeyTutorialGroup
  • After creating the user you should see a screen similar to the following. Do not forget to download the access keys so you can use them in your Java program.
KmsKeyManager created successfully

Create Encrypt/Decrypt User

Let’s now create the user we use to encrypt/decrypt data in our Java application.

  • Create a user named KmsTutorialKeyUser and assign programmatic access.
Creating the KmsTutorialKeyUser
  • Do not assign KmsTutorialKeyUser to any groups.
The Users screen with two newly added users, KmsKeyManager and KMSTutorialKeyUser

Create AWS KMS Key

  • Navigate to IAM and then select Encryption keys to bring you to the Key Management Service (KMS).
Customer managed keys screen with no keys
  • Create a new key with the alias, KmsTutorialKey.
  • Select KMS as the Key material origin.
Creating the KmsTutorialKey

  • Assign KmsKeyManager as the key administrator.
Key administration permissions assigned to KmsKeyManager
  • Assign KmsTutorialKeyUser as the key user (can encrypt and decrypt using the key).
Assigning encrypt/decrypt permission to KmsTutorialKeyUser
  • If interested, review the JSON document.
Complete policy document is JSON
  • After finishing, you should see a screen similar to the following.
KMS screen with newly created CMK

Java Project

Let’s create the Java project using Maven. Although I use Eclipse, any IDE or the command-line should work. It is assumed you can create a Java project that uses Maven to build. If you need help accomplishing this task, refer to a tutorial online. The following is a good introductory tutorial for Maven and Eclipse.

Project Setup

  • Create a new Java project that uses Maven to build. Use the following POM.
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.tutorial.aws</groupId>
	<artifactId>KMSTutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<properties>
		<java.version>1.8</java.version>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>software.amazon.awssdk</groupId>
				<artifactId>bom</artifactId>
				<version>2.5.25</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>software.amazon.awssdk</groupId>
			<artifactId>kms</artifactId>
		</dependency>
		<dependency>
			<artifactId>auth</artifactId>
			<groupId>software.amazon.awssdk</groupId>
		</dependency>
		<dependency>
			<artifactId>aws-core</artifactId>
			<groupId>software.amazon.awssdk</groupId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.5</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>1.6.4</version>
		</dependency>
	</dependencies>
</project>

Note the POM includes the following lines. You might not require these lines; however, the Java 2 SDK uses features that require Java 8 or higher, and I could only get the code to compile including these lines. YMMV.

<properties>
  <java.version>1.8</java.version>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
</properties>

The POM adds the AWS Bill of Materials (BOM) to free us from having to manage the library versions, focusing only on including the correct dependencies rather than their versions. The POM also includes the KMS library and the core libraries required by AWS.

  • If using Eclipse, add a file named observation.json to the resource folder.
  • The observation.json file is a simple JSON record.
{
      "stationid": 221,
      "date": "1992-03-12",
      "time": "091312",
      "message":"This is a secret message. Please encrypt it when storing on disk."
}

AWS KMS Client

The AWS SDK is consistent in how you interact with AWS’s different services. The 2.x API version consistently follows the Fluent Interface/Builder pattern. You can find more information on this pattern if interested by starting with the wikipedia page. A good introductory explanation is found in the following blog post: Another builder pattern for Java. Rather than instantiating new instances of a class, you build the class you a builder. When using the AWS SDK, you create a client with the required credentials using the client’s associated builder. For instance a KmsClient has a KmsClient.Builder that builds it. Different services have different clients. The KMS service uses the KmsClient. Clients work with AWS via requests and is returned responses. The KmsClient class, for example, uses requests to encrypt/decrypt, create keys, and manage keys.

Let’s create the KmsClient. But first we need to return to the AWS Console and copy the CMK key’s Amazon Resource Name (ARN). The ARN is how our application’s client will know where to access the CMK in KMS.

  • Navigate to the key and copy the key’s ARN.
Copy the CMK ARN in the AWS Console

An ARN identifies any resource on AWS uniquely. The client uses this to access the CMK.

  • Create a new class in named KMSExample in the com.tutorial.aws.kms package.
  • Although it is not recommended you hardcode keys in your code, for convenience we create the key and secretKey static variables to held the KmsTutorialKeyUser key and secretKey.
  • Create a keyArn static variable and assign it the ARN you copied above from the AWS console.
  • Create a KmsClient variable and build it in the constructor for KMSExample.
  • In main, create a KMSExample instance.

package com.tutorial.aws.kms;

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kms.KmsClient;

public class KMSExample {

  final static String key = "<key_value_here>";
  final static String secretKey = "<secret_key_value_here";
  final static String keyArn = "<key_arn_here>";

  public KmsClient kmsClient;
  
  public KMSExample() {
    AwsBasicCredentials awsCreds = AwsBasicCredentials.create(key,
      secretKey);
    this.kmsClient = KmsClient.builder()
       .credentialsProvider(StaticCredentialsProvider.create(awsCreds))
       .region(Region.US_EAST_1).build();
  }
  
  public static void main(String[] args) {
    try {
      KMSExample kmsExample = new KMSExample();
    } 
    catch (Exception e) {
      e.printStackTrace();
    }
  }	
}
  • Build the application and run the application, just to ensure everything works.

The KMSExample class uses a KmsClientBuilder to build a KmsClient instance. The KmsClientBuilder uses the region, the credentials, and the key’s ARN to create a KmsClient that can interact with our CMK (KmsTutorialKey).

Note that in this tutorial we create the credentials in a rather un-secure manner. We hardcode them and used StaticCredentialsProvider and AwsBasicCredentials. In a production ready application you should use the AWS Security Token Service (AWS STS) to grant temporary credentials when running the application. For more information, refer to the ASW Security Token Service documentation. Also, you might refer to the following AWS Security Blog post: Guidelines for protecting your AWS account while using programmatic access.

  • After becoming familiar with the 2.x API version, translating constructors and methods to the 2.x API’s builder methods becomes intuitive.

Encrypting and Decrypting Using the Customer Key

In the first example we encrypt and decrypt the data directly using the KmsTutorialKey. As discussed earlier, this is not the recommended way to encrypt/decrypt your application’s data. However, we include it here, as a CMK master key can be used directly in your application to encrypt/decrypt data. And, there might be situations where it’s appropriate to use the CMK directly.

Encrypt

Let’s encrypt the data. We do this by building an EncryptRequest using an EncryptRequest.Builder. The builder takes the request, the key’s ARN, and builds the EncryptRequest. We then pass the request to the KmsClient.

  • Add a method named encrypt to KMSTutorial that takes SdkBytes and returns SdkBytes.
  • Create an EncryptRequest by specifying the key’s ARN and the string to encrypt.
  • Have kmsClient encrypt the request and assign the response to an EncryptResponse.
  • Return the response’s data as SdkBytes.
public SdkBytes encrypt(SdkBytes jsonString) {
  EncryptRequest encryptRequest = EncryptRequest.builder()
    .keyId(keyArn).plaintext(jsonString).build();
  EncryptResponse encryptResponse = this.kmsClient
    .encrypt(encryptRequest);
  return encryptResponse.ciphertextBlob();
}

The EncryptRequest returns an EncryptResponse. We use the ciphertextBlob method to extract the encrypted data from the response. Note that this data is Base64 encoded when accessing it through the HTTP API as we do in this tutorial (remember the Java SDK is a wrapper around AWS Rest APIs and Rest is typically – but not always – HTTP/HTTPS).

The SdkBytes class is Amazon’s wrapper around bytes. It can be created from byte arrays, a ByteBuffer, InputStream, or a String. The AWS SDK consistently uses this class rather than the classes the SdkBytes wraps. In the preceding code we used the cipherTextBlob to obtain the encrypted data from the response to our request to encrypt data using the CMK. The cipherTextBlob returns an SdkBytes.

  • Add a method named writeToFile that takes the SdkBytes to write and the path to the file to write the data to.
public static void writeToFile(SdkBytes bytesToWrite, String path ) throws 
  IOException {
  FileChannel fc;
  FileOutputStream outputStream = new FileOutputStream(path);
  fc = outputStream.getChannel();
  fc.write(bytesToWrite.asByteBuffer());
  outputStream.close();
  fc.close();
}

The writeToFile method writes the encrypted data to a file using the Java NIO API standard in the JDK. We use the SDKBytes asByteBuffer method to convert the data to a ByteBuffer so that the FileChannel can write the data to a file.

  • Modify main to open the observation.json file as an InputStream.
  • Create the input SdkBytes from the InputStream.
  • Call the encrypt method and assign the returned SdkBytes to a variable.
  • Save the SdkBytes to a file using the writeToFile method.
public static void main(String[] args) {
  try 
  {
    KMSExample kmsExample = new KMSExample();
    InputStream in = kmsExample.getClass().getClassLoader()
      .getResourceAsStream("observation.json");
    SdkBytes inputBytes = SdkBytes.fromInputStream(in);
    SdkBytes outputBytes = kmsExample.encrypt(inputBytes);
    String path = Paths.get(".").toAbsolutePath().normalize().toString() + 
      "/observation_encrypt.json";
    KMSExample.writeToFile(outputBytes, path);
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}

  • Build and run the application. You should see a new file named observation_encrypted.json. The content is binary and encrypted.

Decrypt

Let’s decrypt the encrypted data using the CMK used to encrypt the data.

  • Add a method named deCrypt to KMSTutorial that takes SdkBytes and returns SdkBytes.
  • Create a DecryptRequest by assigning it the encrypted text.
  • Have the KmsClient decrypt the request and assign the results to a DecryptResponse.
  • Return the response text.
public SdkBytes deCrypt(SdkBytes encryptedJsonString) {
  DecryptRequest decryptRequest = DecryptRequest.builder()
    .ciphertextBlob(encryptedJsonString).build();
  DecryptResponse decryptResponse = this.kmsClient
    .decrypt(decryptRequest);
  return decryptResponse.plaintext();
}

A DecryptRequest uses a DecryptRequest.Builder to build itself. The builder takes the encrypted text and sends it to the KmsClient. Note that it does not require passing the key’s ARN to decrypt.

  • Modify main to decrypt the encrypted file and print the results to the console.
public static void main(String[] args) {
  try 
  {
    KMSExample kmsExample = new KMSExample();
    InputStream in = kmsExample.getClass().getClassLoader()
      .getResourceAsStream("observation.json");
    SdkBytes inputBytes = SdkBytes.fromInputStream(in);
    SdkBytes outputBytes = kmsExample.encrypt(inputBytes);
    String path = Paths.get(".").toAbsolutePath().normalize().toString() + 
      "/observation_encrypt.json";
    KMSExample.writeToFile(outputBytes, path);
    SdkBytes output2Bytes = kmsExample.deCrypt(KMSExample
      .readFromFile(path));

    System.out.println(output2Bytes.asUtf8String());
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}
  • Build and run the application and you should see the decrypted content, the same as the original file’s content, printed to the console.

Complete KMSExample

Follows is the complete source for the KMSExample class.

package com.tutorial.aws.kms;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
import software.amazon.awssdk.services.kms.model.DecryptResponse;
import software.amazon.awssdk.services.kms.model.EncryptRequest;
import software.amazon.awssdk.services.kms.model.EncryptResponse;

public class KMSExample {

  final static String key = "<key_value_here>";
  final static String secretKey = "<secret_key_value_here";
  final static String keyArn = "<key_arn_here>";

  public KmsClient kmsClient;
  
  public KMSExample() {
    AwsBasicCredentials awsCreds = AwsBasicCredentials.create(key,
      secretKey);
    this.kmsClient = KmsClient.builder()
       .credentialsProvider(StaticCredentialsProvider.create(awsCreds))
       .region(Region.US_EAST_1).build();
  }

  public SdkBytes encrypt(SdkBytes jsonString) {
    EncryptRequest encryptRequest = 
    EncryptRequest.builder().keyId(keyArn).plaintext(jsonString).build();
    EncryptResponse encryptResponse = this.kmsClient
      .encrypt(encryptRequest);
    return encryptResponse.ciphertextBlob();
  }
	
  public SdkBytes deCrypt(SdkBytes encryptedJsonString) {
    DecryptRequest decryptRequest = DecryptRequest.builder()
      .ciphertextBlob(encryptedJsonString).build();
    DecryptResponse decryptResponse = this.kmsClient
      .decrypt(decryptRequest);
    return decryptResponse.plaintext();
  
  public static void main(String[] args) {
    try 
    {
      KMSExample kmsExample = new KMSExample();
      InputStream in = kmsExample.getClass().getClassLoader()
        .getResourceAsStream("observation.json");
      SdkBytes inputBytes = SdkBytes.fromInputStream(in);
      SdkBytes outputBytes = kmsExample.encrypt(inputBytes);
      String path = Paths.get(".").toAbsolutePath().normalize()
        .toString() + "/observation_encrypt.json";
      KMSExample.writeToFile(outputBytes, path);
      SdkBytes output2Bytes = kmsExample.deCrypt(KMSExample
        .readFromFile(path));
      System.out.println(output2Bytes.asUtf8String());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void writeToFile(SdkBytes bytesToWrite, 
    String path) throws IOException {

    FileChannel fc;
    FileOutputStream outputStream = new FileOutputStream(path);
    fc = outputStream.getChannel();
    fc.write(bytesToWrite.asByteBuffer());
    outputStream.close();
    fc.close();
  }
	
  public static SdkBytes readFromFile(String path) throws IOException {
    InputStream in2 = new FileInputStream(path);
    return SdkBytes.fromInputStream(in2);
  }
}

Encrypting and Decrypting Using Data Keys

Recall you cannot export CMKs from AWS KMS. You are also limited to encrypting data of 4kb or less. Both these limitations limit what you can encrypt using a CMK. Also note that you must send the data to the AWS KMS to encrypt/decrypt the data. Although convenient, using a CMK as we did in the preceding section is not ideal. Instead we should use the CMK as a master key that generates, encrypts, and decrypts data keys. You then use data keysThe CMK is responsible only for encrypting/decrypting data keys.

Data keys are designed to be used within your external application that resides outside KMS. Data keys can encrypt/decrypt data of any size and are stored in your own application.

Envelope Encryption is how AWS KMS protects the generated data key. The KMS creates a data key, encrypts the data key, and returns the encrypted data key version and the plain-text unencrypted version of the data key. The plain-text version of the key is what your application uses to encrypt and decrypt data. The encrypted version of the key is what your application saves to use later. You should always ensure the plain-text data key is deleted and removed from memory soon after use so your data’s security is not compromised. When your application needs to use the data key again, request that the AWS CMK decrypts the data key and then use that decrypted key locally.

In the example below we use the CMK above to generate a data key and use that data key to encrypt data. The steps to encrypt in this tutorial are as follows.

  1. Request that the CMK in KMS generates a data key.
  2. Load unencrypted data from file.
  3. Use plain-text version of returned data key to encrypt data.
  4. Store encrypted data to a file.
  5. Store encrypted version of key to a file.
Using a data key to encrypt data

After encrypting the data, we then decrypt the data using the data key. However, before we can decrypt the data using the data key we must first use the CMK to decrypt the data key. The process our application uses is as follows.

  1. Load encrypted data key from file.
  2. Request AWS KMS used to originally encrypt the data key to decrypt the data key.
  3. Load encrypted object from file.
  4. Use decrypted data key to decrypt object.
  5. Print decrypted data to console.
Using a data key to decrypt data

Although we use the KMS to work with the CMK, we must work with the data key locally. We do so using the java crypto package.

  • Modify KMSExample so that its import list contains the following.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.DataKeySpec;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
import software.amazon.awssdk.services.kms.model.DecryptResponse;
import software.amazon.awssdk.services.kms.model.EncryptRequest;
import software.amazon.awssdk.services.kms.model.EncryptResponse;
import software.amazon.awssdk.services.kms.model.GenerateDataKeyRequest;
import software.amazon.awssdk.services.kms.model.GenerateDataKeyResponse;

Encrypt Using Data Key

Let’s encrypt the data using a data key.

  • Create a new method named encryptUsingDataKey that takes the data to encrypt as an SDKBytes data object.
  • Create a GenerateDataKeyRequest using the KmsTutorialKey customer key.
  • Use the KmsClient to return the generated data key as a GenerateDataKeyResponse.
  • Use the Java crypto API to create a SecretKeySpec from the generated data key.
  • Create a Cipher and use it to encrypt the jsonString.
  • Write the encrypted data to a file.
  • Get the encrypted data key from the response and save it to a file.
public void encryptUsingDataKey(SdkBytes jsonString) {
  try {
    GenerateDataKeyRequest generateDataKeyRequest = GenerateDataKeyRequest
      .builder().keyId(keyArn)			 
      .keySpec(DataKeySpec.AES_128).build();
    GenerateDataKeyResponse generateDataKeyResponse = this.kmsClient
      .generateDataKey(generateDataKeyRequest);
    
    SecretKeySpec key = new 
      SecretKeySpec(generateDataKeyResponse.plaintext().asByteArray(), 
      "AES");
      Cipher cipher;
      cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, key);
      byte[] encodedSecret = cipher.doFinal(jsonString.asByteArray());
      byte[] encryptedDataKey = key.getEncoded();
      String path = Paths.get(".").toAbsolutePath().normalize().toString() 
        + "/observation_datakey_encrypt.json";
			 
    KMSExample.writeToFile(SdkBytes.fromByteArray(encodedSecret),
     path);
    path = Paths.get(".").toAbsolutePath().normalize().toString() + 
      "/data_key_encrypt.json";
			 
   KMSExample.writeToFile(SdkBytes.fromByteArray(encryptedDataKey), path);
  } catch (Exception ex) {
      ex.printStackTrace();
  }
}

The GenerateDataKeyRequest wraps a request to generate a data key. You create a GenerateDataKeyRequest using a GenerateDataKeyRequest.Builder. The builder uses the CMK’s ARN and data keyspec to build the request. The KmsClient then passes the request to the KMS which uses the specified CMK to generate the data key. The data key is returned in a GenerateDataKeyResponse.

The AES specifies we wish our data key to use the Advanced Encryption Standard. We must use the same keyspec when using our data key that was used to generate the data key.

We take the plain-text (unencrypted) key version from the response and use it to build a SecretKeySpec. We then pass the SecretKeySpec to a Cipher, which encrypts the data using the Java Cryptography Extension framework. You can obtain more information by consulting this resource: Java Cryptography Architecture (JCA) Reference Guide

  • Modify main to call encryptUsingDataKey.
  • Remove the code that used the CMK to encrypt and decrypt the data.
kmsExample.encryptUsingDataKey(inputBytes);

The main method should appear as follows after adding the call to encrypt the data using a data key.

  public static void main(String[] args) {
    try 
    {
      KMSExample kmsExample = new KMSExample();
      String path = Paths.get(".").toAbsolutePath().normalize()
        .toString() + "/observation.json";
      kmsExample.encryptUsingDataKey(inputBytes);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
  • Build and run the program and there should be two files: data_key_encrypt.txt and observation_datakey_encrypt.json, the encrypted data key and the encrypted data respectively.
Encrypted data key stored locally on disk
Encrypted data stored locally on disk

Decrypting Using Data Key

Let’s decrypt the encrypted data key and use it to decrypt the encrypted data. We first decrypt the local data key by passing it to KMS which uses the CMK to decrypt the key. We then use the returned decrypted key to decrypt the data locally.

  • Create a new method named decryptUsingDataKey.
  • Read the encrypted data key from the file.
  • Create a new DecryptRequest from the data key.
  • Decrypt the data key by passing the DecryptRequest to the kmsClient.
  • Create a SecretKeySpec from the decrypted data key.
  • Read the encrypted data from a file.
  • Create a Cipher and use it and the SecretKeySpec to decrypt the data.

public void decryptUsingDataKey() {
  try {
    String path = Paths.get(".").toAbsolutePath().normalize().toString() + 
      "/resource/data_key_encrypt.txt";
    SdkBytes sdkBytes = KMSExample.readFromFile(path);
    DecryptRequest decryptRequest = DecryptRequest.builder()
      .ciphertextBlob(sdkBytes).build();
    DecryptResponse decryptResponse = this.kmsClient
      .decrypt(decryptRequest);
			
    SecretKeySpec secretKeySpec = new SecretKeySpec(decryptResponse
      .plaintext().asByteArray(), "AES");
    path = Paths.get(".").toAbsolutePath().normalize().toString() + 
      "/observation_datakey_encrypt.json";
    sdkBytes = KMSExample.readFromFile(path);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    System.out.println(SdkBytes.fromByteArray(cipher.doFinal(sdkBytes
      .asByteArray())).asUtf8String());	
  } catch(Exception ex) {
      ex.printStackTrace();
    }
}
  • Modify main to call the decryptUsingDataKey method.
kmsExample.decryptUsingDataKey();

The main method should appear as follows.

  public static void main(String[] args) {
    try 
    {
      KMSExample kmsExample = new KMSExample();
      String path = Paths.get(".").toAbsolutePath().normalize()
        .toString() + "/resource/observation.json";
      KMSExample.writeToFile(outputBytes, path);
      SdkBytes output2Bytes = kmsExample.deCrypt(KMSExample
        .readFromFile(path));
      System.out.println(output2Bytes.asUtf8String());

      kmsExample.encryptUsingDataKey(inputBytes);
      kmsExample.decryptUsingDataKey();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
  • Build and run the application. You should see the JSON record printed to the console.
{
      "stationid": 221,
      "date": "1992-03-12",
      "time": "091312",
      "message":"This is a secret message. Please encrypt it when storing on disk."
}

Conclusion

Amazon’s KMS is a convenient and powerful service to manage your organization’s keys. It is integrated with most AWS Services. You can also use it directly in your application, as demonstrated in this tutorial. The most common use pattern is to create a CMK which must reside in KMS as your master key. That CMK is then used to create local data keys. The local data keys encrypt/decrypt the data. Only the encrypted version of the data key should ever be persisted locally. Instead, whenever the local data key is needed it is passed to KMS so that the associated CMK can decrypt the data key.

You can also administer KMS using the Java API; however, in this tutorial we restricted ourselves to decrypting and encrypting data.

More Resources

Here are two introductory videos on KMS. Neither are programming specific, but they both provide a greater understanding of KMS.

If you are interested in becoming certified, check out my AWS Certified Developer Associate exam notes – the notes helped me pass!

Git Project

The github project is available here. https://github.com/jamesabrannan/kmstutorial