Example usage for com.amazonaws.services.lambda AWSLambda invoke

List of usage examples for com.amazonaws.services.lambda AWSLambda invoke

Introduction

In this page you can find the example usage for com.amazonaws.services.lambda AWSLambda invoke.

Prototype

InvokeResult invoke(InvokeRequest invokeRequest);

Source Link

Document

Invokes a Lambda function.

Usage

From source file:br.com.ingenieux.mojo.beanstalk.bundle.CodeCommitFastDeployMojo.java

License:Apache License

@Override
protected String lookupVersionLabelForCommitId(String commitId) throws Exception {
    String s3Bucket = getService().createStorageLocation().getS3Bucket();

    ObjectNode payload = objectMapper.createObjectNode();

    payload.put("applicationName", applicationName);

    payload.put("commitId", commitId);

    payload.put("repoName", repoName);

    payload.put("description", versionDescription);

    payload.put("accessKey", getAWSCredentials().getCredentials().getAWSAccessKeyId());

    payload.put("secretKey", getAWSCredentials().getCredentials().getAWSSecretKey());

    payload.put("region", getRegion().getName());

    payload.put("targetPath",
            format("s3://%s/apps/%s/versions/git-%s.zip", s3Bucket, applicationName, commitId));

    AWSLambda lambda = getClientFactory().getService(AWSLambdaClient.class);

    final String payloadAsString = objectMapper.writeValueAsString(payload);

    getLog().info("Calling beanstalk-codecommit-deployer with arguments set to: " + redact(payloadAsString));

    final InvokeResult invoke = lambda.invoke(new InvokeRequest()
            .withFunctionName("beanstalker-codecommit-deployer").withPayload(payloadAsString));

    String resultAsString = new String(invoke.getPayload().array(), "utf-8");

    if (isNotBlank(invoke.getFunctionError())) {
        final String errorMessage = "Unexpected: " + invoke.getFunctionError();

        getLog().info(errorMessage);/*from w w  w .j  a v  a  2s .c  o m*/

        throw new RuntimeException(errorMessage);
    } else {
        List<String> messages = objectMapper.readValue(resultAsString, new TypeReference<List<String>>() {
        });

        for (String m : messages) {
            getLog().info(m);
        }
    }

    return super.lookupVersionLabelForCommitId(commitId);
}

From source file:com.netflix.spinnaker.clouddriver.lambda.deploy.ops.InvokeLambdaAtomicOperation.java

License:Apache License

private InvokeResult invokeFunction(String functionName, String payload) {
        AWSLambda client = getLambdaClient();
        InvokeRequest req = new InvokeRequest().withFunctionName(functionName).withLogType(LogType.Tail)
                .withPayload(payload);// ww w  .j a  v a  2  s .  c  o m

        String qualifierRegex = "|[a-zA-Z0-9$_-]+";
        if (description.getQualifier().matches(qualifierRegex)) {
            req.setQualifier(description.getQualifier());
        }

        InvokeResult result = client.invoke(req);
        updateTaskStatus("Finished Invoking of AWS Lambda Function Operation...");
        return result;
    }

From source file:example.lambda.InvokeLambdaFunction.java

License:Apache License

public static void main(String[] args) {
    String function_name = "HelloFunction";
    String function_input = "{\"who\":\"AWS SDK for Java\"}";

    AWSLambda lambda = AWSLambdaClientBuilder.defaultClient();
    InvokeRequest req = new InvokeRequest().withFunctionName(function_name)
            .withPayload(ByteBuffer.wrap(function_input.getBytes()));

    InvokeResult res = lambda.invoke(req);
    if (res.getStatusCode() == 200) {
        System.out.println("Lambda function returned:");
        ByteBuffer response_payload = res.getPayload();
        System.out.println(new String(response_payload.array()));
    } else {//from   www. j a v a  2s  .  co m
        System.out.format("Received a non-OK response from AWS: %d\n", res.getStatusCode());
    }
}

From source file:jp.classmethod.aws.gradle.lambda.AWSLambdaInvokeTask.java

License:Apache License

@TaskAction
public void invokeFunction() throws FileNotFoundException, IOException {
    // to enable conventionMappings feature
    String functionName = getFunctionName();

    if (functionName == null) {
        throw new GradleException("functionName is required");
    }//from   w w w  .j a va  2  s. com

    AWSLambdaPluginExtension ext = getProject().getExtensions().getByType(AWSLambdaPluginExtension.class);
    AWSLambda lambda = ext.getClient();

    InvokeRequest request = new InvokeRequest().withFunctionName(functionName)
            .withInvocationType(getInvocationType()).withLogType(getLogType())
            .withClientContext(getClientContext()).withQualifier(getQualifier());
    setupPayload(request);
    invokeResult = lambda.invoke(request);
    getLogger().info("Invoke Lambda function requested: {}", functionName);
}

From source file:org.alanwilliamson.amazon.lambda.LambdaAsyncExecute.java

License:Open Source License

/**
 * Executes a lambda function and returns the result of the execution.
 *//*w ww.j av a2 s .  com*/
@Override
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {

    AmazonKey amazonKey = getAmazonKey(_session, argStruct);

    // Arguments to extract
    String payload = getNamedStringParam(argStruct, "payload", null);
    String functionName = getNamedStringParam(argStruct, "function", null);
    String qualifier = getNamedStringParam(argStruct, "qualifier", null);

    try {

        // Construct the Lambda Client
        InvokeRequest invokeRequest = new InvokeRequest();
        invokeRequest.setInvocationType(InvocationType.Event);
        invokeRequest.setLogType(LogType.Tail);
        invokeRequest.setFunctionName(functionName);
        invokeRequest.setPayload(payload);
        if (qualifier != null) {
            invokeRequest.setQualifier(qualifier);
        }

        // Lambda client must be created with credentials
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(amazonKey.getKey(), amazonKey.getSecret());
        AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                .withRegion(amazonKey.getAmazonRegion().toAWSRegion().getName())
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();

        // Execute
        awsLambda.invoke(invokeRequest);

    } catch (Exception e) {
        throwException(_session, "AmazonLambdaAsyncExecute: " + e.getMessage());
        return cfBooleanData.FALSE;
    }

    return cfBooleanData.TRUE;
}

From source file:org.alanwilliamson.amazon.lambda.LambdaExecute.java

License:Open Source License

/**
 * Executes a lambda function and returns the result of the execution.
 *//* ww w . j a  va 2 s  .  c o m*/
@Override
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {

    AmazonKey amazonKey = getAmazonKey(_session, argStruct);

    // Arguments to extract
    String payload = getNamedStringParam(argStruct, "payload", null);
    String functionName = getNamedStringParam(argStruct, "function", null);
    String qualifier = getNamedStringParam(argStruct, "qualifier", null);

    try {

        // Construct the Lambda Client
        InvokeRequest invokeRequest = new InvokeRequest();
        invokeRequest.setInvocationType(InvocationType.RequestResponse);
        invokeRequest.setLogType(LogType.Tail);
        invokeRequest.setFunctionName(functionName);
        invokeRequest.setPayload(payload);
        if (qualifier != null) {
            invokeRequest.setQualifier(qualifier);
        }

        // Lambda client must be created with credentials
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(amazonKey.getKey(), amazonKey.getSecret());
        AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                .withRegion(amazonKey.getAmazonRegion().toAWSRegion().getName())
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();

        // Execute and process the results
        InvokeResult result = awsLambda.invoke(invokeRequest);

        // Convert the returned result
        ByteBuffer resultPayload = result.getPayload();
        String resultJson = new String(resultPayload.array(), "UTF-8");
        Map<String, Object> resultMap = Jackson.fromJsonString(resultJson, Map.class);

        return tagUtils.convertToCfData(resultMap);

    } catch (Exception e) {
        throwException(_session, "AmazonLambdaExecute: " + e.getMessage());
        return cfBooleanData.FALSE;
    }

}

From source file:org.xmlsh.aws.gradle.lambda.AWSLambdaInvokeTask.java

License:BSD License

@TaskAction
public void deleteFunction() throws FileNotFoundException, IOException {
    // to enable conventionMappings feature
    String functionName = getFunctionName();

    if (functionName == null)
        throw new GradleException("functionName is required");

    AWSLambdaPluginExtension ext = getProject().getExtensions().getByType(AWSLambdaPluginExtension.class);
    AWSLambda lambda = ext.getClient();

    InvokeRequest request = new InvokeRequest().withFunctionName(functionName)
            .withInvocationType(getInvocationType()).withLogType(getLogType())
            .withClientContext(getClientContext());
    setupPayload(request);/*w ww  . j av a  2s.c om*/
    invokeResult = lambda.invoke(request);
    getLogger().info("Invoke Lambda function requested: {}", functionName);
}