in resources/custom-resources/redshift-table/src/main/java/com/amazon/aws/partners/saasfactory/saasboost/RedshiftTable.java [49:185]
public Object handleRequest(Map<String, Object> event, Context context) {
Utils.logRequestEvent(event);
final String requestType = (String) event.get("RequestType");
Map<String, Object> resourceProperties = (Map<String, Object>) event.get("ResourceProperties");
final String username = (String) resourceProperties.get("Username");
final String passwordParam = (String) resourceProperties.get("Password");
final String tableName = (String) resourceProperties.get("TableName");
final String jdbcUrl = (String) resourceProperties.get("DatabaseUrl");
ExecutorService service = Executors.newSingleThreadExecutor();
ObjectNode responseData = JsonNodeFactory.instance.objectNode();
try {
Runnable r = () -> {
if ("Create".equalsIgnoreCase(requestType)) {
LOGGER.info("CREATE");
Connection connection = null;
Statement statement = null;
LOGGER.info("Getting database password secret from Parameter Store");
String password = null;
try {
password = ssm.getParameter(request -> request.withDecryption(true).name(passwordParam)).parameter().value();
} catch (SdkServiceException ssmError) {
LOGGER.error("ssm:GetParameter error", ssmError.getMessage());
throw ssmError;
}
//LOGGER.info("Password is '" + password + "'");
if (password == null) {
throw new RuntimeException("Password is null");
}
try {
LOGGER.info("Using JDBC Url: {}", jdbcUrl);
Class.forName("com.amazon.redshift.jdbc42.Driver");
Properties properties = new Properties();
properties.setProperty("user", username);
properties.setProperty("password", password);
int attempts = 1;
do {
try {
connection = DriverManager.getConnection(jdbcUrl, properties);
LOGGER.info("Connected to Redshift database");
} catch (Exception e) {
LOGGER.error("Error connecting {}", e.getMessage());
LOGGER.error(Utils.getFullStackTrace(e));
attempts++;
try {
LOGGER.info("Sleep one minute for dns to resolve");
Thread.sleep(60 * 1000);
} catch (InterruptedException te) {
//
}
}
} while (null == connection && attempts < 5);
if (null == connection) {
throw new RuntimeException("Unable to connect to Redshift database after 5 attempts.");
}
//Execute a query
LOGGER.info("Creating table in given database {}", jdbcUrl);
statement = connection.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS public." +
tableName +
"(\n" +
"\"type\" VARCHAR(256) ENCODE lzo\n" +
",workload VARCHAR(256) ENCODE lzo\n" +
",context VARCHAR(256) ENCODE lzo\n" +
",tenant_id VARCHAR(256) ENCODE lzo\n" +
",tenant_name VARCHAR(256) ENCODE lzo\n" +
",tenant_tier VARCHAR(256) ENCODE lzo\n" +
",timerecorded TIMESTAMP WITH TIME ZONE ENCODE az64\n" +
",metric_name VARCHAR(256) ENCODE lzo\n" +
",metric_unit VARCHAR(256) ENCODE lzo\n" +
",metric_value NUMERIC(18,0) ENCODE az64\n" +
",meta_data VARCHAR(256) ENCODE lzo\n" +
")\n" +
"DISTSTYLE AUTO";
statement.executeUpdate(sql);
// Further code to follow
} catch(ClassNotFoundException cnfe) {
String stackTrace = Utils.getFullStackTrace(cnfe);
LOGGER.error(stackTrace);
responseData.put("Reason", stackTrace);
sendResponse(event, context, "FAILED", responseData);
} catch (SQLException sqle) {
String stackTrace = Utils.getFullStackTrace(sqle);
LOGGER.error(stackTrace);
responseData.put("Reason", stackTrace);
sendResponse(event, context, "FAILED", responseData);
} finally{
//finally block used to close resources
try{
if(statement != null) {
connection.close();
}
} catch(SQLException se){
}// do nothing
try {
if (connection != null) {
connection.close();
}
} catch(SQLException se){
se.printStackTrace();
} //end finally try
} //end try
// Tell CloudFormation we're done
sendResponse(event, context, "SUCCESS", responseData);
} else if ("Update".equalsIgnoreCase(requestType)) {
LOGGER.info("UPDATE");
sendResponse(event, context, "SUCCESS", responseData);
} else if ("Delete".equalsIgnoreCase(requestType)) {
LOGGER.info("DELETE");
sendResponse(event, context, "SUCCESS", responseData);
} else {
LOGGER.error("FAILED unknown requestType " + requestType);
responseData.put("Reason", "Unknown RequestType " + requestType);
sendResponse(event, context, "FAILED", responseData);
}
};
Future<?> f = service.submit(r);
f.get(context.getRemainingTimeInMillis() - 1000, TimeUnit.MILLISECONDS);
} catch (final TimeoutException | InterruptedException | ExecutionException e) {
// Timed out
LOGGER.error("FAILED unexpected error or request timed out " + e.getMessage());
String stackTrace = Utils.getFullStackTrace(e);
LOGGER.error(stackTrace);
responseData.put("Reason", stackTrace);
sendResponse(event, context, "FAILED", responseData);
} finally {
service.shutdown();
}
return null;
}