com.amazonaws.services.lambda.AWSLambdaClient Java Examples

The following examples show how to use com.amazonaws.services.lambda.AWSLambdaClient. 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: JobExecutionManagerServiceImplTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Before
  public void setUp() throws Exception{
      awsLambdaClient = mock(AWSLambdaClient.class);
      amazonCloudWatchEvents = mock(AmazonCloudWatchEvents.class);
      invokeResult = mock(InvokeResult.class);
      PowerMockito.whenNew(ObjectMapper.class).withNoArguments().thenReturn(mapper);
      invokeRequest = Mockito.spy(new InvokeRequest());
      putRuleRequest = Mockito.spy(new PutRuleRequest());
      putRuleResult = Mockito.spy(new PutRuleResult());
      putTargetsResult = Mockito.spy(new PutTargetsResult());
      putTargetsRequest = Mockito.spy(new PutTargetsRequest());
      AWSCredentials awsCredentialsProperty = buildAWSCredentials();
when(config.getAws()).thenReturn(awsCredentialsProperty);
      PowerMockito.whenNew(AWSLambdaClient.class).withAnyArguments().thenReturn(awsLambdaClient);  
      when(amazonClient.getAWSLambdaClient(anyString())).thenReturn(awsLambdaClient);
when(amazonClient.getAmazonCloudWatchEvents(anyString())).thenReturn(amazonCloudWatchEvents);
  }
 
Example #2
Source File: RuleServiceImplTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Before
  public void setUp() throws Exception{
      awsLambdaClient = mock(AWSLambdaClient.class);
      amazonCloudWatchEvents = mock(AmazonCloudWatchEvents.class);
     // invokeRequest = mock(InvokeRequest.class);
      invokeResult = mock(InvokeResult.class);
      PowerMockito.whenNew(ObjectMapper.class).withNoArguments().thenReturn(mapper);
      invokeRequest = Mockito.spy(new InvokeRequest());
      getPolicyResult = Mockito.spy(new GetPolicyResult());
      putRuleRequest = Mockito.spy(new PutRuleRequest());
      putRuleResult = Mockito.spy(new PutRuleResult());
      putTargetsResult = Mockito.spy(new PutTargetsResult());
      putTargetsRequest = Mockito.spy(new PutTargetsRequest());
      AWSCredentials awsCredentialsProperty = buildAWSCredentials();
when(config.getAws()).thenReturn(awsCredentialsProperty);
      PowerMockito.whenNew(AWSLambdaClient.class).withAnyArguments().thenReturn(awsLambdaClient);  
      when(amazonClient.getAWSLambdaClient(anyString())).thenReturn(awsLambdaClient);
when(amazonClient.getAmazonCloudWatchEvents(anyString())).thenReturn(amazonCloudWatchEvents);
  }
 
Example #3
Source File: SkillClient.java    From alexa-meets-polly with Apache License 2.0 6 votes vote down vote up
public String translate(final String testPhrase, final String language) {
    final Map<String, Slot> slots = new HashMap<>();
    slots.put("termA", Slot.builder().withName("termA").withValue(testPhrase).build());
    slots.put("termB", Slot.builder().withName("termB").build());
    slots.put("language", Slot.builder().withName("language").withValue(language).build());
    final SpeechletRequestEnvelope envelope = givenIntentSpeechletRequestEnvelope("Translate", slots);
    final ObjectMapper mapper = new ObjectMapper();
    String response = null;
    try {
        final AWSLambdaClient awsLambda = new AWSLambdaClient();
        final InvokeRequest invokeRequest = new InvokeRequest()
                .withInvocationType(InvocationType.RequestResponse)
                .withFunctionName(lambdaName)
                .withPayload(mapper.writeValueAsString(envelope));
        final InvokeResult invokeResult = awsLambda.invoke(invokeRequest);
        response = new String(invokeResult.getPayload().array());
    } catch (JsonProcessingException e) {
        log.error(e.getMessage());
    }
    return response;
}
 
Example #4
Source File: BackendServiceFactory.java    From jrestless-examples with Apache License 2.0 6 votes vote down vote up
@Inject
public BackendServiceFactory(InjectionManager serviceLocator) {
	awsLambdaClient = new AWSLambdaClient();
	awsLambdaClient.configureRegion(BACKEND_SERVICE_REGION);
	backendService = Feign.builder()
			.client(FeignLambdaServiceInvokerClient.builder()
					.setRegion(BACKEND_SERVICE_REGION)
					.setFunctionName(BACKEND_SERVICE_FUNCTION_NAME)
					.build())
			.decoder(new JacksonDecoder())
			.encoder(new JacksonEncoder())
			.logger(new Slf4jLogger())
			.target(new LambdaServiceFunctionTarget<BackendService>(BackendService.class) {
				@Override
				public Request apply(RequestTemplate input) {
					// TODO inject the context directly => requires the context to be bound as proxy
					Context lambdaContext = serviceLocator.getInstance(Context.class);
					// propagate the AWS request ID => the called service can log the original AWS request ID
					input.header("X-Base-Aws-Request-Id", lambdaContext.getAwsRequestId());
					return super.apply(input);
				}
			});
}
 
Example #5
Source File: AbstractAWSLambdaProcessor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Create client using aws credentials provider. This is the preferred way for creating clients
 */
@Override
protected AWSLambdaClient createClient(final ProcessContext context, final AWSCredentialsProvider credentialsProvider, final ClientConfiguration config) {
    getLogger().info("Creating client using aws credentials provider");

    return new AWSLambdaClient(credentialsProvider, config);
}
 
Example #6
Source File: AbstractAWSLambdaProcessor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Create client using AWSCredentials
 *
 * @deprecated use {@link #createClient(ProcessContext, AWSCredentialsProvider, ClientConfiguration)} instead
 */
@Override
protected AWSLambdaClient createClient(final ProcessContext context, final AWSCredentials credentials, final ClientConfiguration config) {
    getLogger().info("Creating client using aws credentials");

    return new AWSLambdaClient(credentials, config);
}
 
Example #7
Source File: LambdaFunction.java    From lambadaframework with MIT License 5 votes vote down vote up
protected AWSLambda getLambdaClient() {

        if (lambdaClient != null) {
            return lambdaClient;
        }

        return lambdaClient = new AWSLambdaClient(getAWSCredentialsProvideChain()).withRegion(Region.getRegion(Regions.fromName(deployment.getRegion())));
    }
 
Example #8
Source File: LambdaClientConfig.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
public AWSLambdaClient getClient() {
    if(useDefaultAWSCredentials){
        return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration())
                .withRegion(Region.getRegion(Regions.fromName(region)));
    } else {
        return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration())
                .withRegion(Region.getRegion(Regions.fromName(region)));
    }
}
 
Example #9
Source File: TestPutLambda.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    mockLambdaClient = Mockito.mock(AWSLambdaClient.class);
    mockPutLambda = new PutLambda() {
        protected AWSLambdaClient getClient() {
            actualLambdaClient = client;
            return mockLambdaClient;
        }
    };
    runner = TestRunners.newTestRunner(mockPutLambda);
}
 
Example #10
Source File: AbstractAWSLambdaProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Create client using aws credentials provider. This is the preferred way for creating clients
 */
@Override
protected AWSLambdaClient createClient(final ProcessContext context, final AWSCredentialsProvider credentialsProvider, final ClientConfiguration config) {
    getLogger().info("Creating client using aws credentials provider");

    return new AWSLambdaClient(credentialsProvider, config);
}
 
Example #11
Source File: AbstractAWSLambdaProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Create client using AWSCredentials
 *
 * @deprecated use {@link #createClient(ProcessContext, AWSCredentialsProvider, ClientConfiguration)} instead
 */
@Override
protected AWSLambdaClient createClient(final ProcessContext context, final AWSCredentials credentials, final ClientConfiguration config) {
    getLogger().info("Creating client using aws credentials");

    return new AWSLambdaClient(credentials, config);
}
 
Example #12
Source File: PutLambda.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {

    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final String functionName = context.getProperty(AWS_LAMBDA_FUNCTION_NAME).getValue();

    final String qualifier = context.getProperty(AWS_LAMBDA_FUNCTION_QUALIFIER).getValue();

    // Max size of message is 6 MB
    if ( flowFile.getSize() > MAX_REQUEST_SIZE) {
        getLogger().error("Max size for request body is 6mb but was {} for flow file {} for function {}",
            new Object[]{flowFile.getSize(), flowFile, functionName});
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    final AWSLambdaClient client = getClient();

    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        session.exportTo(flowFile, baos);

        InvokeRequest invokeRequest = new InvokeRequest()
            .withFunctionName(functionName)
            .withLogType(LogType.Tail).withInvocationType(InvocationType.RequestResponse)
            .withPayload(ByteBuffer.wrap(baos.toByteArray()))
            .withQualifier(qualifier);
        long startTime = System.nanoTime();

        InvokeResult result = client.invoke(invokeRequest);

        flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_STATUS_CODE, result.getStatusCode().toString());

        if ( !StringUtils.isBlank(result.getLogResult() )) {
            flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_LOG, new String(Base64.decode(result.getLogResult()),Charset.defaultCharset()));
        }

        if ( result.getPayload() != null ) {
            flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_PAYLOAD, new String(result.getPayload().array(),Charset.defaultCharset()));
        }

        if ( ! StringUtils.isBlank(result.getFunctionError()) ){
            flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_FUNCTION_ERROR, result.getFunctionError());
            session.transfer(flowFile, REL_FAILURE);
        } else {
            session.transfer(flowFile, REL_SUCCESS);
            final long totalTimeMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
            session.getProvenanceReporter().send(flowFile, functionName, totalTimeMillis);
        }
    } catch (final InvalidRequestContentException
        | InvalidParameterValueException
        | RequestTooLargeException
        | ResourceNotFoundException
        | UnsupportedMediaTypeException unrecoverableException) {
            getLogger().error("Failed to invoke lambda {} with unrecoverable exception {} for flow file {}",
                new Object[]{functionName, unrecoverableException, flowFile});
            flowFile = populateExceptionAttributes(session, flowFile, unrecoverableException);
            session.transfer(flowFile, REL_FAILURE);
    } catch (final TooManyRequestsException retryableServiceException) {
        getLogger().error("Failed to invoke lambda {} with exception {} for flow file {}, therefore penalizing flowfile",
            new Object[]{functionName, retryableServiceException, flowFile});
        flowFile = populateExceptionAttributes(session, flowFile, retryableServiceException);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    } catch (final AmazonServiceException unrecoverableServiceException) {
        getLogger().error("Failed to invoke lambda {} with exception {} for flow file {} sending to fail",
            new Object[]{functionName, unrecoverableServiceException, flowFile});
        flowFile = populateExceptionAttributes(session, flowFile, unrecoverableServiceException);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    } catch (final Exception exception) {
        getLogger().error("Failed to invoke lambda {} with exception {} for flow file {}",
            new Object[]{functionName, exception, flowFile});
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}
 
Example #13
Source File: LambdaDeployService.java    From aws-lambda-jenkins-plugin with MIT License 4 votes vote down vote up
public LambdaDeployService(AWSLambdaClient client, JenkinsLogger logger) {
    this.client = client;
    this.logger = logger;
}
 
Example #14
Source File: LambdaPublishService.java    From aws-lambda-jenkins-plugin with MIT License 4 votes vote down vote up
public LambdaPublishService(AWSLambdaClient client, JenkinsLogger logger) {
    this.client = client;
    this.logger = logger;
}
 
Example #15
Source File: LambdaInvokeService.java    From aws-lambda-jenkins-plugin with MIT License 4 votes vote down vote up
public LambdaInvokeService(AWSLambdaClient client, JenkinsLogger logger) {
    this.client = client;
    this.logger = logger;
}
 
Example #16
Source File: PutLambda.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {

    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final String functionName = context.getProperty(AWS_LAMBDA_FUNCTION_NAME).getValue();

    final String qualifier = context.getProperty(AWS_LAMBDA_FUNCTION_QUALIFIER).getValue();

    // Max size of message is 6 MB
    if ( flowFile.getSize() > MAX_REQUEST_SIZE) {
        getLogger().error("Max size for request body is 6mb but was {} for flow file {} for function {}",
            new Object[]{flowFile.getSize(), flowFile, functionName});
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    final AWSLambdaClient client = getClient();

    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        session.exportTo(flowFile, baos);

        InvokeRequest invokeRequest = new InvokeRequest()
            .withFunctionName(functionName)
            .withLogType(LogType.Tail).withInvocationType(InvocationType.RequestResponse)
            .withPayload(ByteBuffer.wrap(baos.toByteArray()))
            .withQualifier(qualifier);
        long startTime = System.nanoTime();

        InvokeResult result = client.invoke(invokeRequest);

        flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_STATUS_CODE, result.getStatusCode().toString());

        if ( !StringUtils.isBlank(result.getLogResult() )) {
            flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_LOG, new String(Base64.decode(result.getLogResult()),Charset.defaultCharset()));
        }

        if ( result.getPayload() != null ) {
            flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_PAYLOAD, new String(result.getPayload().array(),Charset.defaultCharset()));
        }

        if ( ! StringUtils.isBlank(result.getFunctionError()) ){
            flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_FUNCTION_ERROR, result.getFunctionError());
            session.transfer(flowFile, REL_FAILURE);
        } else {
            session.transfer(flowFile, REL_SUCCESS);
            final long totalTimeMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
            session.getProvenanceReporter().send(flowFile, functionName, totalTimeMillis);
        }
    } catch (final InvalidRequestContentException
        | InvalidParameterValueException
        | RequestTooLargeException
        | ResourceNotFoundException
        | UnsupportedMediaTypeException unrecoverableException) {
            getLogger().error("Failed to invoke lambda {} with unrecoverable exception {} for flow file {}",
                new Object[]{functionName, unrecoverableException, flowFile});
            flowFile = populateExceptionAttributes(session, flowFile, unrecoverableException);
            session.transfer(flowFile, REL_FAILURE);
    } catch (final TooManyRequestsException retryableServiceException) {
        getLogger().error("Failed to invoke lambda {} with exception {} for flow file {}, therefore penalizing flowfile",
            new Object[]{functionName, retryableServiceException, flowFile});
        flowFile = populateExceptionAttributes(session, flowFile, retryableServiceException);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    } catch (final AmazonServiceException unrecoverableServiceException) {
        getLogger().error("Failed to invoke lambda {} with exception {} for flow file {} sending to fail",
            new Object[]{functionName, unrecoverableServiceException, flowFile});
        flowFile = populateExceptionAttributes(session, flowFile, unrecoverableServiceException);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    } catch (final Exception exception) {
        getLogger().error("Failed to invoke lambda {} with exception {} for flow file {}",
            new Object[]{functionName, exception, flowFile});
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}