Using the YcFunction interface to set a handler function in Java
You can set a handler function in Java by implementing the YcFunction
Warning
You should specify both values for YcFunction
type parameters: the first one being the input argument type and the second one the type of the return value. The handle
method also has the second argument: the invocation context.
Example of a valid handler:
import yandex.cloud.sdk.functions.YcFunction;
import yandex.cloud.sdk.functions.Context;
public class Handler implements YcFunction<Integer, String> {
@Override
public String handle(Integer i, Context c) {
return String.valueOf(i);
}
}
Examples of invalid handlers:
import yandex.cloud.sdk.functions.YcFunction;
import yandex.cloud.sdk.functions.Context;
// YcFunction has only one parameter type specified
// Handler should not have any type parameters (see the handler requirements)
public class Handler<T> implements YcFunction<T, Integer> {
@Override
public Integer handle(T i, Context c) {
return 2;
}
}
import yandex.cloud.sdk.functions.YcFunction;
import yandex.cloud.sdk.functions.Context;
// YcFunction does not have both parameter types specified
public class Handler implements YcFunction {
@Override
public Object apply(Object i, Context c) {
return i;
}
}
You can use any classes as input and return types.
Note
Fields of these classes may have any access modifiersgetter
/setter
methods for it is optional.
Example of function information output
The following function receives a number as an input, outputs the function data obtained from the invocation context to the execution log, and returns data on whether the received number is even.
Warning
To invoke the function, use the Yandex Cloud CLI or an HTTP request with the ?integration=raw
parameter.
Handler.java
:
import yandex.cloud.sdk.functions.YcFunction;
import yandex.cloud.sdk.functions.Context;
public class Handler implements YcFunction<Integer, Boolean> {
private String format(String f, String s) {
return String.format(f, s);
}
@Override
public Boolean handle(Integer number, Context c) {
System.out.println(format("Function name: %s", c.getFunctionName()));
System.out.println(format("Function version: %s", c.getFunctionVersion()));
// if no service account is selected, an empty line is printed
System.out.println(format("Service account token: %s", c.getTokenJson()));
return number % 2 == 0;
}
}
Example of input data:
41
The log will contain the following:
Function name: <function_name>
Function version: <function_version_ID>
Service account token: <service_account_token>
Returned string:
false