66import com .amazonaws .services .lambda .runtime .events .APIGatewayProxyResponseEvent ;
77
88import gate .*;
9+ import gate .corpora .export .GATEJsonExporter ;
910import gate .creole .ExecutionException ;
1011import gate .creole .ResourceInstantiationException ;
1112import gate .util .GateException ;
1213import gate .util .persistence .PersistenceManager ;
1314import org .apache .log4j .LogManager ;
1415import org .apache .log4j .Logger ;
1516
17+ import java .io .ByteArrayOutputStream ;
1618import java .io .File ;
19+ import java .io .IOException ;
1720import java .net .URL ;
1821import java .util .HashMap ;
1922import java .util .Objects ;
@@ -34,8 +37,10 @@ public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatew
3437
3538 private static final Logger logger = LogManager .getLogger (App .class );
3639 private static final CorpusController application = loadApplication ();
40+ private static final GATEJsonExporter gateJsonExporter = new GATEJsonExporter ();
3741
3842 public APIGatewayProxyResponseEvent handleRequest (APIGatewayProxyRequestEvent input , final Context context ) {
43+ final String responseType = input .getHeaders ().getOrDefault ("Accept" , "application/xml" );
3944 final APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent ()
4045 .withHeaders (new HashMap <>());
4146 response .getHeaders ().put ("Content-Type" , "text/plain" );
@@ -46,9 +51,9 @@ public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent in
4651 corpus .add (doc );
4752 try {
4853 application .execute ();
49- response .getHeaders ().put ("Content-Type" , "application/xml" );
50- return response .withBody (doc . toXml ( )).withStatusCode (200 );
51- } catch (ExecutionException e ) {
54+ response .getHeaders ().put ("Content-Type" , responseType );
55+ return response .withBody (encode ( doc , responseType )).withStatusCode (200 );
56+ } catch (ExecutionException | IOException e ) {
5257 logger .error (e );
5358 return response .withBody (e .getMessage ()).withStatusCode (500 );
5459 } finally {
@@ -61,6 +66,21 @@ public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent in
6166 }
6267 }
6368
69+ /**
70+ * @param doc an instance of gate.Document
71+ * @param responseType One of the supported response types
72+ */
73+ private String encode (Document doc , String responseType ) throws IOException {
74+ final ByteArrayOutputStream baos = new ByteArrayOutputStream ();
75+ if (responseType .equals ("application/json" )) {
76+ gateJsonExporter .export (doc , baos );
77+ return baos .toString ();
78+ }
79+ else {
80+ return doc .toXml ();
81+ }
82+ }
83+
6484 private static CorpusController loadApplication () {
6585 try {
6686 final String gappResourcePah = System .getenv ("GATE_APP_NAME" ) + "/application.xgapp" ;
0 commit comments