package helloworld; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; /** * Handler for requests to Lambda function. */ public class App implements RequestHandler { static { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("[runtime] ShutdownHook triggered"); System.out.println("[runtime] Cleaning up"); // perform actual clean up work here. try { Thread.sleep(200); } catch (Exception e) { System.out.println(e); } System.out.println("[runtime] exiting"); System.exit(0); } }); } public Object handleRequest(final Object input, final Context context) { Map headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("X-Custom-Header", "application/json"); try { final String pageContents = this.getPageContents("https://checkip.amazonaws.com"); String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents); return new GatewayResponse(output, headers, 200); } catch (IOException e) { return new GatewayResponse("{}", headers, 500); } } private String getPageContents(String address) throws IOException { URL url = new URL(address); try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { return br.lines().collect(Collectors.joining(System.lineSeparator())); } } }