Skip to content

Instantly share code, notes, and snippets.

@donhuvy
Forked from jreijn/Function.java
Created March 12, 2024 10:36
Show Gist options
  • Save donhuvy/9bc972f2e3dcb097e5916bc612afe789 to your computer and use it in GitHub Desktop.
Save donhuvy/9bc972f2e3dcb097e5916bc612afe789 to your computer and use it in GitHub Desktop.
Read File from S3 in Java
public static final String TYPE_QUERY_PARAM = "type";
public static final String JSON_FILE_EXTENSION = ".json";
public static final String PAGE_PREFIX = "_p";
private S3Client s3Client = S3Client.builder()
.region(Region.EU_WEST_1)
.httpClient(UrlConnectionHttpClient.builder().build())
.credentialsProvider(EnvironmentVariableCredentialsProvider.create())
.build();
@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
Map<String, String> queryStringParameters = input.getQueryStringParameters();
String page = queryStringParameters.getOrDefault("page", "1");
String type;
if(!queryStringParameters.containsKey(TYPE_QUERY_PARAM)){
throw new MissingTypeException("Parameter Type cannot be null");
} else {
type = queryStringParameters.get(TYPE_QUERY_PARAM);
}
String key = type + PAGE_PREFIX + page + JSON_FILE_EXTENSION;
ResponseInputStream<GetObjectResponse> s3ClientObject = s3Client
.getObject(GetObjectRequest
.builder()
.bucket("apigatelambdas3integrationdemo")
.key(key)
.build());
return new APIGatewayProxyResponseEvent()
.withStatusCode(200)
.withHeaders(
Map.of("Content-Type", s3ClientObject.response().contentType(),
"Content-Length", s3ClientObject.response().contentLength().toString()))
.withBody(getFileContentAsString(context, s3ClientObject));
}
private String getFileContentAsString(Context context, ResponseInputStream<GetObjectResponse> s3ClientObject) {
String fileAsString = "";
try (BufferedReader reader = new BufferedReader(new InputStreamReader(s3ClientObject))) {
fileAsString = reader.lines().collect(Collectors.joining(System.lineSeparator()));
} catch (IOException e) {
context.getLogger().log("Oops! Something went wrong while converting the file from S3 to a String");
e.printStackTrace();
}
return fileAsString;
}
#set($type = $input.params('type')
#set($page = $input.params('page'))
#if( $page == '')
#set($context.requestOverride.path.fileName = $type + '_p1.json')
#else
#set($context.requestOverride.path.fileName = $type + '_p'+ $page + '.json')
#end
Request body mapping template Response body mapping template
$context.requestOverride.header.header_name $context.responseOverride.header.header_name
$context.requestOverride.path.path_name $context.responseOverride.status
$context.requestOverride.querystring.querystring_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment