Java Code Examples for com.amazonaws.services.lambda.AWSLambda#invoke()

The following examples show how to use com.amazonaws.services.lambda.AWSLambda#invoke() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RuleServiceImpl.java    From pacbot with Apache License 2.0 6 votes vote down vote up
private boolean invokeRule(AWSLambda awsLambdaClient, Rule ruleDetails, String invocationId, List<Map<String, Object>> additionalRuleParams) {
	String ruleParams = ruleDetails.getRuleParams();
	if(invocationId != null) {
		Map<String, Object> ruleParamDetails;
		try {
			ruleParamDetails = mapper.readValue(ruleDetails.getRuleParams(), new TypeReference<Map<String, Object>>(){});
			ruleParamDetails.put("invocationId", invocationId);
			ruleParamDetails.put("additionalParams", mapper.writeValueAsString(additionalRuleParams));
			ruleParams = mapper.writeValueAsString(ruleParamDetails);
		} catch (Exception exception) {
			log.error(UNEXPECTED_ERROR_OCCURRED, exception);
		} 
	}
	String functionName = config.getRule().getLambda().getFunctionName();
	ByteBuffer payload = ByteBuffer.wrap(ruleParams.getBytes());
	InvokeRequest invokeRequest = new InvokeRequest().withFunctionName(functionName).withPayload(payload);
	InvokeResult invokeResult = awsLambdaClient.invoke(invokeRequest);
	if (invokeResult.getStatusCode() == 200) {
		return true;
	} else {
		return false;
	}
}
 
Example 2
Source File: TracingHandlerTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testLambdaInvokeSubsegmentContainsFunctionName() {
    // Setup test
    AWSLambda lambda = AWSLambdaClientBuilder
        .standard()
        .withRequestHandlers(new TracingHandler())
        .withRegion(Regions.US_EAST_1)
        .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
        .build();
    mockHttpClient(lambda, "null"); // Lambda returns "null" on successful fn. with no return value

    // Test logic
    Segment segment = AWSXRay.beginSegment("test");

    InvokeRequest request = new InvokeRequest();
    request.setFunctionName("testFunctionName");
    lambda.invoke(request);

    Assert.assertEquals(1, segment.getSubsegments().size());
    Assert.assertEquals("Invoke", segment.getSubsegments().get(0).getAws().get("operation"));
    Assert.assertEquals("testFunctionName", segment.getSubsegments().get(0).getAws().get("function_name"));
}
 
Example 3
Source File: TracingHandlerTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRaceConditionOnRecorderInitialization() {
    AWSXRay.setGlobalRecorder(null);
    // TracingHandler will not have the initialized recorder
    AWSLambda lambda = AWSLambdaClientBuilder
        .standard()
        .withRequestHandlers(new TracingHandler())
        .withRegion(Regions.US_EAST_1)
        .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
        .build();

    mockHttpClient(lambda, "null");

    // Now init the global recorder
    AWSXRayRecorder recorder = AWSXRayRecorderBuilder.defaultRecorder();
    recorder.setContextMissingStrategy(new LogErrorContextMissingStrategy());
    AWSXRay.setGlobalRecorder(recorder);

    // Test logic
    InvokeRequest request = new InvokeRequest();
    request.setFunctionName("testFunctionName");
    lambda.invoke(request);
}
 
Example 4
Source File: JobExecutionManagerServiceImpl.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private void invokeRule(AWSLambda awsLambdaClient, String lambdaFunctionName, String params) {
	InvokeRequest invokeRequest = new InvokeRequest().withFunctionName(lambdaFunctionName).withPayload(ByteBuffer.wrap(params.getBytes()));
	InvokeResult invokeResult = awsLambdaClient.invoke(invokeRequest);
	if (invokeResult.getStatusCode() == 200) {
		invokeResult.getPayload();
	} else {
		log.error("Received a non-OK response from AWS: "+invokeResult.getStatusCode());
	}
}
 
Example 5
Source File: InvokeLambdaStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected Object run() throws Exception {
	TaskListener listener = this.getContext().get(TaskListener.class);
	AWSLambda client = AWSClientFactory.create(AWSLambdaClientBuilder.standard(), this.getContext());

	String functionName = this.step.getFunctionName();

	listener.getLogger().format("Invoke Lambda function %s%n", functionName);

	InvokeRequest request = new InvokeRequest();
	request.withFunctionName(functionName);
	request.withPayload(this.step.getPayloadAsString());
	request.withLogType(LogType.Tail);

	InvokeResult result = client.invoke(request);

	listener.getLogger().append(this.getLogResult(result));
	String functionError = result.getFunctionError();
	if (functionError != null) {
		throw new RuntimeException("Invoke lambda failed! " + this.getPayloadAsString(result));
	}
	if (this.step.isReturnValueAsString()) {
		return this.getPayloadAsString(result);
	} else {
		return JsonUtils.fromString(this.getPayloadAsString(result));
	}
}
 
Example 6
Source File: LambdaAsyncExecute.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Executes a lambda function and returns the result of the execution.
 */
@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;
}
 
Example 7
Source File: LambdaInvokeFunction.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

         /*
        Function names appear as arn:aws:lambda:us-west-2:335556330391:function:HelloFunction
        you can retrieve the value by looking at the function in the AWS Console
         */
        if (args.length < 1) {
            System.out.println("Please specify a function name");
            System.exit(1);
        }

        // snippet-start:[lambda.java1.invoke.main]
        String functionName = args[0];

        InvokeRequest invokeRequest = new InvokeRequest()
                .withFunctionName(functionName)
                .withPayload("{\n" +
                        " \"Hello \": \"Paris\",\n" +
                        " \"countryCode\": \"FR\"\n" +
                        "}");
        InvokeResult invokeResult = null;

        try {
            AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                    .withCredentials(new ProfileCredentialsProvider())
                    .withRegion(Regions.US_WEST_2).build();

            invokeResult = awsLambda.invoke(invokeRequest);

            String ans = new String(invokeResult.getPayload().array(), StandardCharsets.UTF_8);

            //write out the return value
            System.out.println(ans);

        } catch (ServiceException e) {
            System.out.println(e);
        }

        System.out.println(invokeResult.getStatusCode());
        // snippet-end:[lambda.java1.invoke.main]
    }
 
Example 8
Source File: LambdaExecute.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Executes a lambda function and returns the result of the execution.
 */
@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;
	}

}