com.amazonaws.services.lambda.AWSLambdaClientBuilder Java Examples

The following examples show how to use com.amazonaws.services.lambda.AWSLambdaClientBuilder. 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: ListFunctions.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        // snippet-start:[lambda.java1.list.main]
        ListFunctionsResult functionResult = null;

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

            functionResult = awsLambda.listFunctions();

            List<FunctionConfiguration> list = functionResult.getFunctions();

            for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                FunctionConfiguration config = (FunctionConfiguration)iter.next();

                System.out.println("The function name is "+config.getFunctionName());
            }

        } catch (ServiceException e) {
            System.out.println(e);
        }
        // snippet-end:[lambda.java1.list.main]
    }
 
Example #2
Source File: DeleteFunction.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Please specify a function name");
            System.exit(1);
        }

        // snippet-start:[lambda.java1.delete.main]
        String functionName = args[0];
        try {
            AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                    .withCredentials(new ProfileCredentialsProvider())
                    .withRegion(Regions.US_WEST_2).build();

            DeleteFunctionRequest delFunc = new DeleteFunctionRequest();
            delFunc.withFunctionName(functionName);

            //Delete the functiom
            awsLambda.deleteFunction(delFunc);
            System.out.println("The function is deleted");

        } catch (ServiceException e) {
            System.out.println(e);
        }
        // snippet-end:[lambda.java1.delete.main]
    }
 
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 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 #4
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 #5
Source File: AmazonDockerClientsHolder.java    From spring-localstack with Apache License 2.0 5 votes vote down vote up
@Override
public AWSLambda awsLambda() {
    return decorateWithConfigsAndBuild(
        AWSLambdaClientBuilder.standard(),
        LocalstackDocker::getEndpointLambda
    );
}
 
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: FeignLambdaServiceInvokerClient.java    From jrestless with Apache License 2.0 5 votes vote down vote up
protected AWSLambda resolveAwsLambdaClient() {
	AWSLambda resolvedClient = awsLambdaClient;
	if (resolvedClient == null && region != null) {
		resolvedClient = AWSLambdaClientBuilder.standard().withRegion(region).build();
	}
	return requireToBuild(resolvedClient, "an awsLambdaClient or a region is required");
}
 
Example #8
Source File: LambdaVersionCleanupStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void setupSdk() throws Exception {
	PowerMockito.mockStatic(AWSClientFactory.class);
	this.awsLambda = Mockito.mock(AWSLambda.class);
	this.cloudformation = Mockito.mock(AmazonCloudFormation.class);
	PowerMockito.when(AWSClientFactory.create(Mockito.any(AwsSyncClientBuilder.class), Mockito.any(StepContext.class)))
		.thenAnswer( (x) -> {
			if (x.getArgumentAt(0, AwsSyncClientBuilder.class) instanceof AWSLambdaClientBuilder) {
				return awsLambda;
			} else {
				return cloudformation;
			}
		});
}
 
Example #9
Source File: LambdaVersionCleanupStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public String run() throws Exception {

	AWSLambda client = AWSClientFactory.create(AWSLambdaClientBuilder.standard(), this.getContext());

	if (this.step.functionName != null) {
		deleteAllVersions(client, this.step.functionName);
	}

	if (this.step.stackName != null) {
		deleteAllStackFunctionVersions(client, this.step.stackName);
	}
	return null;
}
 
Example #10
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 #11
Source File: TestInvoker.java    From lambda-selenium with MIT License 5 votes vote down vote up
public TestResult run() {
    final LambdaSeleniumService lambdaService = LambdaInvokerFactory.builder()
            .lambdaClient(AWSLambdaClientBuilder.defaultClient())
            .build(LambdaSeleniumService.class);

    return lambdaService.runTest(request);
}
 
Example #12
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch lambda info test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchLambdaInfoTest() throws Exception {
    
    mockStatic(AWSLambdaClientBuilder.class);
    AWSLambda lamdaClient = PowerMockito.mock(AWSLambda.class);
    AWSLambdaClientBuilder awsLambdaClientBuilder = PowerMockito.mock(AWSLambdaClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(awsLambdaClientBuilder.standard()).thenReturn(awsLambdaClientBuilder);
    when(awsLambdaClientBuilder.withCredentials(anyObject())).thenReturn(awsLambdaClientBuilder);
    when(awsLambdaClientBuilder.withRegion(anyString())).thenReturn(awsLambdaClientBuilder);
    when(awsLambdaClientBuilder.build()).thenReturn(lamdaClient);
    
    ListFunctionsResult listFunctionsResult = new ListFunctionsResult();
    List<FunctionConfiguration> functions = new ArrayList<>();
    FunctionConfiguration functionConfiguration = new FunctionConfiguration();
    functionConfiguration.setFunctionArn("functionArn");
    functions.add(functionConfiguration);
    listFunctionsResult.setFunctions(functions);
    when(lamdaClient.listFunctions(anyObject())).thenReturn(listFunctionsResult);
    
    ListTagsResult listTagsResult = new ListTagsResult();
    listTagsResult.setTags(new HashMap<>());
    when(lamdaClient.listTags(anyObject())).thenReturn(listTagsResult);
    assertThat(inventoryUtil.fetchLambdaInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #13
Source File: FederationServiceProvider.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
public static FederationService getService(String lambdaFunction, FederatedIdentity identity, String catalog)
{
    FederationService service = serviceCache.get(lambdaFunction);
    if (service != null) {
        return service;
    }

    service = LambdaInvokerFactory.builder()
            .lambdaClient(AWSLambdaClientBuilder.defaultClient())
            .objectMapper(VersionedObjectMapperFactory.create(BLOCK_ALLOCATOR))
            .lambdaFunctionNameResolver(new Mapper(lambdaFunction))
            .build(FederationService.class);

    PingRequest pingRequest = new PingRequest(identity, catalog, generateQueryId());
    PingResponse pingResponse = (PingResponse) service.call(pingRequest);

    int actualSerDeVersion = pingResponse.getSerDeVersion();
    log.info("SerDe version for function {}, catalog {} is {}", lambdaFunction, catalog, actualSerDeVersion);

    if (actualSerDeVersion != SERDE_VERSION) {
        service = LambdaInvokerFactory.builder()
                .lambdaClient(AWSLambdaClientBuilder.defaultClient())
                .objectMapper(VersionedObjectMapperFactory.create(BLOCK_ALLOCATOR, actualSerDeVersion))
                .lambdaFunctionNameResolver(new Mapper(lambdaFunction))
                .build(FederationService.class);
    }

    serviceCache.put(lambdaFunction, service);
    return service;
}
 
Example #14
Source File: AWSLambdaClientFactory.java    From bender with Apache License 2.0 4 votes vote down vote up
public AWSLambda newInstance() {
  return AWSLambdaClientBuilder.standard().build();
}
 
Example #15
Source File: AWSLambdaConfigurerAdapter.java    From service-block-samples with Apache License 2.0 4 votes vote down vote up
public AWSLambda getLambdaClient() {
    return AWSLambdaClientBuilder.standard()
            .withRegion(Regions.US_EAST_1)
            .withCredentials(new LambdaCredentialsProvider(amazonProperties))
            .build();
}
 
Example #16
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * Fetch lambda info.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static  Map<String,List<LambdaVH>> fetchLambdaInfo(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){

	Map<String,List<LambdaVH>> functions = new LinkedHashMap<>();
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Lambda\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				AWSLambda lamdaClient = AWSLambdaClientBuilder.standard().
					 	withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				ListFunctionsResult listFnRslt ;
				List<FunctionConfiguration> functionsTemp ;
				List<LambdaVH> lambdaList = new ArrayList<>();
				String nextMarker = null;
				do{
					listFnRslt = lamdaClient.listFunctions(new ListFunctionsRequest().withMarker(nextMarker));
					functionsTemp = listFnRslt.getFunctions();
					if( !functionsTemp.isEmpty() ) {
						functionsTemp.forEach( function -> {
							Map<String,String> tags = lamdaClient.listTags(new ListTagsRequest().withResource(function.getFunctionArn())).getTags();
							LambdaVH  lambda = new LambdaVH(function, tags);
							lambdaList.add(lambda);
						});
					}
					nextMarker = listFnRslt.getNextMarker();
				}while(nextMarker!=null);

				if( !lambdaList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Lambda " +region.getName() + " >> "+lambdaList.size());
					functions.put(accountId+delimiter+accountName+delimiter+region.getName(),lambdaList);
				}
			}
		}catch(Exception e){
			if(region.isServiceSupported(AWSLambda.ENDPOINT_PREFIX)){
				log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
				ErrorManageUtil.uploadError(accountId,region.getName(),"lambda",e.getMessage());
			}
		}
	}
	return functions ;
}
 
Example #17
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 #18
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;
	}

}
 
Example #19
Source File: AWSLambdaConfigurerAdapter.java    From service-block-samples with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a proxy instance of a supplied interface that contains methods annotated with
 * {@link LambdaFunction}. Provides automatic credential support to authenticate with an IAM
 * access keys using {@link BasicSessionCredentials} auto-configured from Spring Boot
 * configuration properties in {@link AmazonProperties}.
 *
 * @param type
 * @param <T>
 * @return
 */
public <T> T getFunctionInstance(Class<T> type) {
    return LambdaInvokerFactory.builder()
            .lambdaClient(AWSLambdaClientBuilder.standard()
                    .withRegion(Regions.US_EAST_1)
                    .withCredentials(new LambdaCredentialsProvider(amazonProperties))
                    .build())
            .build(type);
}
 
Example #20
Source File: AmazonClientBuilderService.java    From pacbot with Apache License 2.0 2 votes vote down vote up
/**
    * Service function to get RuleAWSLambda Client
    *
    * @author Nidhish
    * @return AWSLambda Client
    */
public AWSLambda getAWSLambdaClient(final String region) {
	return AWSLambdaClientBuilder.standard().withRegion(region).build();
}