package org.wisdom.content.bodyparsers;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Provides;
import org.wisdom.api.content.BodyParser;
import org.wisdom.api.http.Context;
import org.wisdom.api.http.MimeTypes;
import org.wisdom.content.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@Component
@Provides
@Instantiate
public class BodyParserJson implements BodyParser {

    private final Logger logger = LoggerFactory.getLogger(BodyParserJson.class);

    public <T> T invoke(Context context, Class<T> classOfT) {
        T t = null;
        try {
            t = Json.mapper().readValue(context.getReader(), classOfT);
        } catch (IOException e) {
            logger.error("Error parsing incoming Json", e);
        }

        return t;
    }

    @Override
    public <T> T invoke(byte[] bytes, Class<T> classOfT) {
        T t = null;
        try {
            t = Json.mapper().readValue(bytes, classOfT);
        } catch (IOException e) {
            logger.error("Error parsing incoming Json", e);
        }

        return t;
    }

    public String getContentType() {
        return MimeTypes.JSON;
    }

}

package org.wisdom.content.bodyparsers;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Provides;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wisdom.api.content.BodyParser;
import org.wisdom.api.http.Context;
import org.wisdom.api.http.MimeTypes;
import org.wisdom.content.json.Json;

import java.io.IOException;

@Component
@Provides
@Instantiate
public class BodyParserJson implements BodyParser {

    private final Logger logger = LoggerFactory.getLogger(BodyParserJson.class);

    public <T> T invoke(Context context, Class<T> classOfT) {
        T t = null;
        try {
            final String content = context.body();
            if (content == null  || content.length() == 0) {
                return null;
            }
            t = Json.mapper().readValue(content, classOfT);
        } catch (IOException e) {
            logger.error("Error parsing incoming Json", e);
        }

        return t;
    }

    @Override
    public <T> T invoke(byte[] bytes, Class<T> classOfT) {
        T t = null;
        try {
            t = Json.mapper().readValue(bytes, classOfT);
        } catch (IOException e) {
            logger.error("Error parsing incoming Json", e);
        }

        return t;
    }

    public String getContentType() {
        return MimeTypes.JSON;
    }

}

Check for null and empty body before trying to map a json string to an object.
Check for null and empty body before trying to map a json string to an object.

Signed-off-by: Clement Escoffier <6397137e57d1f87002962a37058f2a1c76fca9db@gmail.com>
