Handler

Updated at:

A Java handler responds to received events and runs the corresponding business logic. Review the handler concepts, structural features, and examples in this topic.

Note

If you want to use HTTP triggers or custom domain names to access functions, obtain request struct before you define HTTP responses. For more information, see Use an HTTP trigger to invoke a function.

What is a handler?

FC function handlers are the methods in the function code that handle requests. When your function is invoked, Function Compute runs the handler method that you provide to handle the request.

Use the Function Compute console to configure Handler. For functions written in Java, configure the handler in the following format: [package name].[class name]::[method name]. For example, if your package name is example, your class name is HelloFC, and your method name is handleRequest, configure the handler as example.HelloFC::handleRequest.

Configurations of handlers must conform to the configuration specifications of Function Compute. The configuration specifications vary based on the handler type.

Handler interfaces

When you program in Java, you must implement the interface classes provided by Function Compute. The fc-java-core library defines the following two interfaces for handlers.

  • StreamRequestHandler

    Receives the input event as a stream and returns the execution result. Read the input from the input stream when the function is invoked. After processing is complete, write the function execution result to the output stream to return it.

  • PojoRequestHandler

    Receives the input event by using generics and returns the execution result. The input and output types are customizable, but both must be Plain Old Java Object (POJO) types.

StreamRequestHandler

The following example shows the simplest StreamRequestHandler:

package example;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class HelloFC implements StreamRequestHandler {

    @Override
    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
        outputStream.write(new String("hello world").getBytes());
    }
}           
  • Package name and class name

    Because Java has the concept of packages, the execution method differs from that of other languages and must include package information. In the code example, the handler is example.HelloFC::handleRequest, where example is the package name, HelloFC is the class name, and handleRequest is the class method.

    Note

    The package name and class name can be arbitrary, but they must match the Handler field in the function configuration. To configure Handler, see Create an event-triggered function.

  • Implemented interface

    Your code must implement the interface predefined by Function Compute. The preceding code example implements StreamRequestHandler, where the inputStream parameter is the data passed in when the function is invoked. The outputStream parameter returns the execution result of the function.

  • Context parameter

    The Context parameter contains runtime information about the function, such as the RequestId and a temporary AccessKey. Its type is com.aliyun.fc.runtime.Context. For details, see Context.

  • Return value

    A function that implements the StreamRequestHandler interface returns the execution result through the outputStream parameter.

  • Interface library

    The dependency on the com.aliyun.fc.runtime package used in this example can be referenced in the following pom.xml file:

    <dependency>
        <groupId>com.aliyun.fc.runtime</groupId>
        <artifactId>fc-java-core</artifactId>
        <version>1.4.1</version>
    </dependency>           

    Check the Maven repository for the latest version number of fc-java-core.

Before you create a function, package your code and its fc-java-core dependency into a JAR file. For instructions, see Compile and deploy a code package.

PojoRequestHandler

The following example shows the simplest PojoRequestHandler. The SimpleRequest object must support JSON serialization. A POJO meets this requirement.

// HelloFC.java
package example;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;

public class HelloFC implements PojoRequestHandler<SimpleRequest, SimpleResponse> {

    @Override
    public SimpleResponse handleRequest(SimpleRequest request, Context context) {
        String message = "Hello, " + request.getFirstName() + " " + request.getLastName();
        return new SimpleResponse(message);
    }
}            
// SimpleRequest.java
package example;

public class SimpleRequest {
    String firstName;
    String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public SimpleRequest() {}
    public SimpleRequest(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}            
// SimpleResponse.java
package example;

public class SimpleResponse {
    String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public SimpleResponse() {}
    public SimpleResponse(String message) {
        this.message = message;
    }
}            

The following is an example of the event parameter that is passed in:

{
  "firstName": "FC",
  "lastName": "aliyun"
}            

Example: Use an HTTP trigger to invoke a function

Sample code

In the preceding sample code, HTTPTriggerEvent.java declares the request format of the HTTP trigger, and HTTPTriggerResponse.java declares the response format of the HTTP trigger. For details about the HTTP trigger request struct and response struct formats, see Use an HTTP trigger to invoke a function.

HTTPTriggerEvent.java

package example;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Map;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(setterPrefix = "with")
public class HTTPTriggerEvent {
    private String version;
    private String rawPath;
    private Map<String, String> headers;
    private Map<String, String> queryParameters;
    private RequestContext requestContext;

    @JsonProperty("isBase64Encoded")
    private boolean IsBase64Encoded;
    private String body;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder(setterPrefix = "with")
    public static class RequestContext {
        private String accountId;
        private String domainName;
        private String domainPrefix;
        private HttpInfo http;
        private String requestId;
        private String time;
        private String timeEpoch;

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        @Builder(setterPrefix = "with")
        public static class HttpInfo {
            private String method;
            private String path;
            private String protocol;
            private String sourceIp;
            private String userAgent;
        }
    }

}

HTTPTriggerResponse.java

package example;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;

import com.fasterxml.jackson.annotation.JsonProperty;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(setterPrefix = "with")
public class HTTPTriggerResponse {
    private int statusCode;
    private Map<String, String> headers;

    @JsonProperty("isBase64Encoded")
    private boolean IsBase64Encoded;
    private String body;
}

App.java defines the function entry point class.

App.java

package example;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;

/**
 * HTTP Trigger demo
 *
 */
public class App implements PojoRequestHandler<HTTPTriggerEvent, HTTPTriggerResponse> {

    @Override
    public HTTPTriggerResponse handleRequest(HTTPTriggerEvent request, Context context) {
        context.getLogger().info("Receive HTTP Trigger request: " + request.toString());
        String requestBody = request.getBody();
        if (request.isIsBase64Encoded()) {
            requestBody = new String(java.util.Base64.getDecoder().decode(request.getBody()), StandardCharsets.UTF_8);
        }
        String message = "HTTP Trigger request body: " + requestBody;
        context.getLogger().info(message);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "text/plain");
        return HTTPTriggerResponse.builder().withStatusCode(200).withHeaders(headers).withBody(request.getBody())
                .withIsBase64Encoded(request.isIsBase64Encoded()).build();
    }
}

In addition to the fc-java-core library, this sample program also requires two additional libraries, jackson and lombok. Add these dependencies to the Maven configuration file pom.xml.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.16.1</version>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.30</version>
</dependency>

Prerequisites

You have used the preceding example to create a function that uses the Java runtime, and created an HTTP trigger. For instructions, see Create an event-triggered function and Configure an HTTP trigger.

Procedure

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Triggers tab. On the Triggers page, get the public network access address of the HTTP trigger.

  4. Invoke the function with the following curl command:

    curl -i "https://dev-jav-test-fc-luiqas****.cn-shanghai.fcapp.run" -d 'hello fc3.0'

    In the preceding command, https://dev-jav-test-fc-luiqas****.cn-shanghai.fcapp.run is the public network access address of the HTTP trigger that you obtained.

    The following response is returned:

    HTTP/1.1 200 OK
    Content-Disposition: attachment
    Content-Length: 11
    Content-Type: application/json
    X-Fc-Request-Id: 1-652503f2-afbfd2b1dc4dd0fcb0230959
    Date: Tue, 10 Oct 2023 07:57:38 GMT
    
    hello fc3.0% 
    Important
    • If the Authentication Method of the HTTP trigger is No Authentication, you can use Postman or the Curl tool to invoke the function directly. For instructions, see Procedure in this topic.

    • If the Authentication Method of the HTTP trigger is Signature Authentication, JWT authentication, or Bearer authentication, use the signature method, JWT authentication, or Bearer authentication to invoke the function. For instructions, see Authentication and authorization.

Error analysis

This sample code supports invocation by using an HTTP trigger or a custom domain name. If you invoke the function by using an API but the configured test parameters do not comply with the HTTP trigger request format specification, an error is reported.

For example, when you invoke the function in the console, set the request parameter to "Hello, FC!", and click Test Function. The following response is returned:

{
    "errorType": "com.fasterxml.jackson.databind.exc.MismatchedInputException",
    "errorMessage": "Cannot construct instance of `example.HTTPTriggerEvent` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('Hello, FC!')\n at [Source: (byte[])\"\"Hello, FC!\"\"; line: 1, column: 1]",
    "stackTrace": [
        "com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)",
        "com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1588)",
        "com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1213)",
        "com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromString(StdDeserializer.java:311)",
        "com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1495)",
        "com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:207)",
        "com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:197)",
        "com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:322)",
        "com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4593)",
        "com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3643)"
    ]
}

Sample programs

Function Compute's official library contains sample applications that use various handler types and interfaces. Each sample application includes a method for easy compilation and deployment. For example: