package de.butterworks.awscommons.lambdaweb;

import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Segment;
import com.google.gson.JsonObject;
import de.butterworks.awscommons.lambdaweb.actions.AbstractApiAction;
import de.butterworks.awscommons.lambdaweb.exceptions.ExceptionHandler;
import de.butterworks.awscommons.lambdaweb.integration.IntegrationRequestBody;
import de.butterworks.awscommons.lambdaweb.integration.UserInfo;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

public abstract class AbstractLambdaRouter {

    public void doHandle(final InputStream inStream, final OutputStream outStream) throws Exception {

        final Segment handlingSegment = AWSXRay.beginSegment("LambdaHandling");
        try {

            final JsonObject inputJson = SerializationUtil.parseAsJsonElement(IOUtils.toString(inStream, Charset.defaultCharset())).getAsJsonObject();

            final AbstractApiAction apiAction = instantiateAction(inputJson.getAsJsonPrimitive("action").getAsString());

            final UserInfo userInfo = new UserInfo(inputJson.getAsJsonPrimitive("uid").getAsString(), inputJson.getAsJsonPrimitive("groups").getAsString());

            final AbstractApiResponse responseObject = apiAction.getType() != null ?
                    apiAction.handleGeneric((IntegrationRequestBody)SerializationUtil.fromJson(inputJson.getAsJsonObject("body"), apiAction.getType()), userInfo) :
                    apiAction.handleGeneric(null, userInfo);

            if (responseObject != null) {
                IOUtils.write(responseObject.toJson(), outStream, Charset.defaultCharset());
            }
        } catch (final Exception e) {
            handlingSegment.addException(e);
            ExceptionHandler.processException(e);
        } finally {
            handlingSegment.end();
        }
    }

    protected abstract AbstractApiAction instantiateAction(final String className);
}

@@ -43,87 +43,8 @@
 b;%0A%0A
-import com.amazonaws.xray.AWSXRay;%0Aimport com.amazonaws.xray.entities.Segment;%0A
 impo
@@ -74,16 +74,16 @@
 Object;%0A
+
 import d
@@ -643,88 +643,8 @@
  %7B%0A%0A
-        final Segment handlingSegment = AWSXRay.beginSegment(%22LambdaHandling%22);%0A
     
@@ -653,17 +653,16 @@
   try %7B%0A
-%0A
         
@@ -1238,16 +1238,17 @@
 estBody)
+ 
 Serializ
@@ -1588,53 +1588,8 @@
 ) %7B%0A
-            handlingSegment.addException(e);%0A
     
@@ -1638,63 +1638,8 @@
 e);%0A
-        %7D finally %7B%0A            handlingSegment.end();%0A
     

Remove X-ray from router