Developing Functions in Java (Using Eclipse)
Function Syntax
The following is the syntax for creating a handler function in Java:
Scope Return parameter Function name (User-defined parameter, Context)
- Scope: It must be defined as public for the function that FunctionGraph invokes to execute your code.
- Return parameter: user-defined output, which is converted into a character string and returned as an HTTP response. The HTTP response is a JSON string.
- Function name: user-defined function name.
- User-defined parameter: FunctionGraph supports only one user-defined parameter. For complex parameters, define them as an object and provide data through JSON strings. When invoking a function, FunctionGraph parses the JSON strings as an object.
- Context: runtime information provided for executing the function. For details, see SDK APIs.
When creating a function in Java, define a handler in the format of [Package name].[Class name].[Function name].
Java Initializer
FunctionGraph supports the following Java runtime:
- Java 8
- Java 11
Initializer syntax:
[Package name].[Class name].[Execution function name]
For example, if the initializer is named com.huawei.Demo.my_initializer, FunctionGraph loads the my_initializer function defined in the com.huawei file.
To use Java to build initialization logic, define a Java function as the initializer. The following is a simple initializer:
public void my_initializer(Context context) { RuntimeLogger log = context.getLogger(); log.log(String.format("ak:%s", context.getAccessKey())); }
- Function Name
The function name my_initializer must be the initializer function name specified for a function.
For example, if the initializer is named com.huawei.Demo.my_initializer, FunctionGraph loads the my_initializer function defined in the com.huawei file.
- context
The context parameter contains the runtime information about a function. For example, request ID, temporary AK, and function metadata.
SDK APIs
The Java SDK (verification file: fss-java-sdk-2.0.5.sha256) provides context, event, and logging APIs.
- Event APIs
Event structure definitions are added to the Java SDK. Currently, DMS, DIS, SMN, timer, APIG, and Kafka triggers are supported. The definitions make coding much simpler when triggers are required.
- APIG trigger
- APIGTriggerEvent methods
Table 1 APIGTriggerEvent methods Method
Description
isBase64Encoded()
Checks whether the body of an event is encoded using Base64.
getHttpMethod()
Obtains the HTTP request method.
getPath()
Obtains the HTTP request path.
getBody()
Obtains the HTTP request body.
getPathParameters()
Obtains all path parameters.
getRequestContext()
Obtains API Gateway configurations (returned as an APIGRequestContext object).
getHeaders()
Obtains the HTTP request header.
getQueryStringParameters()
Obtains query parameters.
NOTE:The value of a query parameter cannot be an array. To support an array, customize the corresponding event structure.
getRawBody()
Obtains the content before Base64 encoding.
getUserData()
Obtains the user data set in the APIG custom authorizer.
- APIGTriggerResponse methods
Table 3 APIGTriggerResponse construction methods Method
Description
APIGTriggerResponse()
Set the following parameters:
- headers: null
- statusCode: 200
- body: ""
- isBase64Encoded: false
APIGTriggerResponse(statusCode, headers, body)
Set the value of isBase64Encoded to false, and use the input values of other parameters.
APIGTriggerResponse(statusCode, headers, isBase64Encoded, body)
Set the parameters in sequence.
Table 4 APIGTriggerResponse methods Method
Description
setBody(String body)
Sets the message body.
setHeaders(Map<String,String> headers)
Sets the HTTP response header to be returned.
setStatusCode(int statusCode)
Sets the HTTP status code.
setBase64Encoded(boolean isBase64Encoded)
Configures Base64 encoding for the response body.
setBase64EncodedBody(String body)
Encodes the input with Base64 and configures it in the body.
addHeader(String key, String value)
Adds a group of HTTP headers.
removeHeader(String key)
Removes the specified header.
addHeaders(Map<String,String> headers)
Adds multiple headers.
APIGTriggerResponse methods have the headers attribute, which can be initialized using the setHeaders method or a constructor function with the headers parameter.
- APIGTriggerEvent methods
- DIS trigger
Table 5 DISTriggerEvent methods Method
Description
getShardID()
Obtains the partition ID.
getMessage()
Obtains the DIS message body (DISMessage structure).
getTag()
Obtains the version of a function.
getStreamName()
Obtains the stream name.
Table 6 DISMessage methods Method
Description
getNextPatitionCursor()
Obtains the next partition cursor.
getRecords()
Obtains message records (DISRecord structure).
getMillisBehindLatest()
Reserved (Currently, 0 is returned.)
- DMS trigger
Table 8 DMSTriggerEvent methods Method
Description
getQueueId()
Obtains the queue ID.
getRegion()
Obtains the region name.
getEventType()
Obtains the event type (MessageCreated is returned).
getConsumerGroupId()
Obtains the consumer group ID.
getMessages()
Obtains the DMS message (DMSMessage structure).
- SMN trigger
Table 10 SMNTriggerEvent method Method
Description
getRecord()
Obtains message records (SMNRecord structure).
Table 11 SMNRecord methods Method
Description
getEventVersion()
Obtains the event version. (Currently, the version is 1.0.)
getEventSubscriptionUrn()
Obtains the subscription Uniform Resource Name (URN).
getEventSource()
Obtains the event source.
getSmn()
Obtains the message body (SMNBody structure).
Table 12 SMNBody methods Method
Description
getTopicUrn()
Obtains the topic URN.
getTimeStamp()
Obtains the timestamp of a message.
getMessageAtrributes()
Obtains the message attribute set.
getMessage()
Obtains the message body.
getType()
Obtains the message type.
getMessageId()
Obtains the message ID.
getSubject()
Obtains the message topic.
- Timer trigger
Table 13 TimerTriggerEvent methods Method
Description
getVersion()
Obtains the version. (Currently, the version is v1.0.)
getTime()
Obtains the current time.
getTriggerType()
Obtains the trigger type (Timer).
getTriggerName()
Obtains the trigger name.
getUserEvent()
Obtains the additional information of the trigger.
- Kafka trigger
Table 14 Kafka trigger Method
Description
getEventVersion
Obtains event version.
getRegion
Obtains region information.
getEventTime
Obtains event time.
getTriggerType
Obtains trigger type.
getInstanceId
Obtains instance ID.
getRecords
Obtains record.
- When using an APIG trigger, set the first parameter of the handler function (for example, handler) to handler(APIGTriggerEvent event, Context context).
- The preceding TriggerEvent methods have corresponding set methods, which are recommended for local debugging. DIS and LTS triggers have getRawData() methods, but do not have setRawData() methods.
- APIG trigger
- Context APIs
The context APIs are used to obtain the context, such as agency AK/SK, current request ID, allocated memory space, and number of CPUs, required for executing a function.
Table 15 describes the context APIs provided by FunctionGraph.
Table 15 Context methods Method
Description
getRequestID( )
Obtains a request ID.
getRemainingTimeInMilliSeconds ( )
Obtains the remaining running time of a function.
getAccessKey( )
Obtains the AK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.
NOTE:FunctionGraph has stopped maintaining the getAccessKey API in the Runtime SDK. You cannot use this API to obtain a temporary AK.
getSecretKey( )
Obtains the SK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.
NOTE:FunctionGraph has stopped maintaining the getSecretKey API in the Runtime SDK. You cannot use this API to obtain a temporary SK.
getSecurityAccessKey( )
Obtains the SecurityAccessKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.
getSecuritySecretKey( )
Obtains the SecuritySecretKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.
getSecurityToken( )
Obtains the SecurityToken (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.
getUserData(string key)
Uses keys to obtain the values passed by environment variables.
getFunctionName( )
Obtains the name of a function.
getRunningTimeInSeconds ( )
Obtains the timeout of a function.
getVersion( )
Obtains the version of a function.
getMemorySize( )
Obtains the allocated memory.
getCPUNumber( )
CPU usage of a function.
getPackage( )
Obtains a function group, that is, an app.
getToken( )
Obtains the token (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.
getLogger( )
Obtains the logger method provided by the context. By default, information such as the time and request ID is output.
getAlias
Obtains function alias.
Results returned by using the getToken(), getAccessKey(), and getSecretKey() methods contain sensitive information. Exercise caution when using these methods.
- Logging API
Table 16 describes the logging API provided in the Java SDK.
Developing a Java Function
Perform the following procedure to develop a Java function:
- Create a function project.
- Configure Eclipse and create a Java project named JavaTest, as shown in Figure 1.
- Add a dependency to the project.
Download the Java SDK to a local development environment, and decompress the SDK package, as shown in Figure 2.
- Configure the dependency.
Create a folder named lib in the project directory, copy the Runtime-2.0.5.jar file in the SDK package to the lib folder, and add the JAR file as a dependency of the project, as shown in Figure 3.
- Create a function.
- Create a package named com.huawei.demo, and then create a class named TriggerTests under the package, as shown in Figure 4.
- Define the function handler in TriggerTests.java, as shown in Figure 5.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
package com.huawei.demo; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import com.huawei.services.runtime.Context; import com.huawei.services.runtime.entity.apig.APIGTriggerEvent; import com.huawei.services.runtime.entity.apig.APIGTriggerResponse; import com.huawei.services.runtime.entity.dis.DISTriggerEvent; import com.huawei.services.runtime.entity.dms.DMSTriggerEvent; import com.huawei.services.runtime.entity.smn.SMNTriggerEvent; import com.huawei.services.runtime.entity.timer.TimerTriggerEvent; public class TriggerTests { public APIGTriggerResponse apigTest(APIGTriggerEvent event, Context context){ System.out.println(event); Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); return new APIGTriggerResponse(200, headers, event.toString()); } public String smnTest(SMNTriggerEvent event, Context context){ System.out.println(event); return "ok"; } public String dmsTest(DMSTriggerEvent event, Context context){ System.out.println(event); return "ok"; } public String timerTest(TimerTriggerEvent event, Context context){ System.out.println(event); return "ok"; } public String disTest(DISTriggerEvent event, Context context) throws UnsupportedEncodingException{ System.out.println(event); System.out.println(event.getMessage().getRecords()[0].getRawData()); return "ok"; } }
For details about the constraints for the APIG event source, see Base64 Decoding and Response Structure.
- Package the project files.
- Log in to the FunctionGraph console, create a Java function, and upload the code package.
- Test the function.
- Create a test event.
- Click Test.
The function execution result consists of three parts: function output (returned by callback), summary, and logs (output by using the console.log or getLogger() method).
- Create an APIG trigger.
- Access the API URL, as shown in Figure 9.
Change the handler to com.huawei.demo.TriggerTests.smnTest and change the event template to smn-event-template.
- Use a user-defined parameter in the Java code.
Create a Person class in the project, as shown in Figure 10.Create a class named PersonTest.java, and add a handler function to the class, as shown in Figure 11.
Upload the exported JAR file on the function details page, change the handler to com.huawei.demo.PersonTest.personTest, and save the change.
Figure 12 Uploading a JAR file
In the Configure Test Event dialog box, select blank-template, and enter a test event.
Click Create, and then click Test.
Execution Result
The execution result consists of the function output, summary, and log output.
Parameter |
Successful Execution |
Failed Execution |
---|---|---|
Function Output |
The defined function output information is returned. |
A JSON file that contains errorMessage and stackTrace is returned. The format is as follows: { "errorMessage": "", "stackTrace": [] } errorMessage: Error message returned by the runtime. stackTrace: Stack error information returned by the runtime. |
Summary |
Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed. |
Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed. |
Log Output |
Function logs are printed. A maximum of 4 KB logs can be displayed. |
Error information is printed. A maximum of 4 KB logs can be displayed. |
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot