<commit_before>package com.devicehive.websockets.handlers;

import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import com.devicehive.configuration.Messages;
import com.devicehive.exceptions.HiveException;
import com.devicehive.json.GsonFactory;
import com.devicehive.json.strategies.JsonPolicyApply;
import com.devicehive.json.strategies.JsonPolicyDef;
import com.devicehive.util.ThreadLocalVariablesKeeper;
import com.devicehive.websockets.converters.JsonMessageBuilder;
import com.devicehive.websockets.converters.WebSocketResponse;
import com.devicehive.websockets.handlers.annotations.Action;
import com.devicehive.websockets.handlers.annotations.WebsocketController;
import com.devicehive.websockets.handlers.annotations.WsParam;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentMap;

import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.websocket.Session;

@Singleton
public class WebsocketExecutor {

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

    @Inject
    @WebsocketController
    @Any
    private Instance<WebsocketHandlers> handlers;

    private ConcurrentMap<String, Pair<WebsocketHandlers, Method>> methodsCache = Maps.newConcurrentMap();
    private ConcurrentMap<Method, List<WebsocketParameterDescriptor>> parametersCache = Maps.newConcurrentMap();


    public JsonObject execute(JsonObject request, Session session) {
        JsonObject response = null;
        try {
            ThreadLocalVariablesKeeper.setRequest(request);
            ThreadLocalVariablesKeeper.setSession(session);
            response = tryExecute(request, session);
        } catch (HiveException ex) {
            response = JsonMessageBuilder.createError(ex).build();
        } catch (ConstraintViolationException ex) {
            response =
                JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage())
                    .build();
        } catch (org.hibernate.exception.ConstraintViolationException ex) {
            response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage())
                .build();
        } catch (JsonParseException ex) {
            response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST,
                                                                     Messages.INVALID_REQUEST_PARAMETERS).build();
        } catch (OptimisticLockException ex) {
            response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT,
                                                                     Messages.CONFLICT_MESSAGE).build();
        } catch (PersistenceException ex) {
            if (ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
                response =
                    JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage())
                        .build();
            } else {
                response = JsonMessageBuilder
                    .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage())
                    .build();
            }
        } catch (Exception ex) {
            response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()).build();
        } finally {
            ThreadLocalVariablesKeeper.setRequest(null);
            ThreadLocalVariablesKeeper.setSession(null);
        }

        return new JsonMessageBuilder()
            .addAction(request.get(JsonMessageBuilder.ACTION))
            .addRequestId(request.get(JsonMessageBuilder.REQUEST_ID))
            .include(response)
            .build();
    }

    public JsonObject tryExecute(JsonObject request, Session session) {
        Pair<WebsocketHandlers, Method> methodPair = getMethod(request);
        List<Object> args = prepareArgumentValues(methodPair.getRight(), request, session);
        WebSocketResponse response = null;
        try {
            response = (WebSocketResponse) methodPair.getRight().invoke(methodPair.getLeft(), args.toArray());
        } catch (InvocationTargetException ex) {
            Throwable target = ex.getTargetException();
            Throwables.propagateIfPossible(target);
            throw new HiveException(target.getMessage(), target);
        } catch (IllegalAccessException ex) {
            throw HiveException.fatal();
        }
        if (response == null) {
            logger.error("[tryExecute]  response is null ");
            return JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();<commit_msg>Error logging is added<commit_after>package com.devicehive.websockets.handlers;

import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import com.devicehive.configuration.Messages;
import com.devicehive.exceptions.HiveException;
import com.devicehive.json.GsonFactory;
import com.devicehive.json.strategies.JsonPolicyApply;
import com.devicehive.json.strategies.JsonPolicyDef;
import com.devicehive.util.ThreadLocalVariablesKeeper;
import com.devicehive.websockets.converters.JsonMessageBuilder;
import com.devicehive.websockets.converters.WebSocketResponse;
import com.devicehive.websockets.handlers.annotations.Action;
import com.devicehive.websockets.handlers.annotations.WebsocketController;
import com.devicehive.websockets.handlers.annotations.WsParam;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentMap;

import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.websocket.Session;

@Singleton
public class WebsocketExecutor {

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

    @Inject
    @WebsocketController
    @Any
    private Instance<WebsocketHandlers> handlers;

    private ConcurrentMap<String, Pair<WebsocketHandlers, Method>> methodsCache = Maps.newConcurrentMap();
    private ConcurrentMap<Method, List<WebsocketParameterDescriptor>> parametersCache = Maps.newConcurrentMap();


    public JsonObject execute(JsonObject request, Session session) {
        JsonObject response = null;
        try {
            ThreadLocalVariablesKeeper.setRequest(request);
            ThreadLocalVariablesKeeper.setSession(session);
            response = tryExecute(request, session);
        } catch (HiveException ex) {
            logger.error("Error executing the request", ex);
            response = JsonMessageBuilder.createError(ex).build();
        } catch (ConstraintViolationException ex) {
            logger.error("Error executing the request", ex);
            response =
                JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage())
                    .build();
        } catch (org.hibernate.exception.ConstraintViolationException ex) {
            logger.error("Error executing the request", ex);
            response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage())
                .build();
        } catch (JsonParseException ex) {
            logger.error("Error executing the request", ex);
            response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST,
                                                                     Messages.INVALID_REQUEST_PARAMETERS).build();
        } catch (OptimisticLockException ex) {
            logger.error("Error executing the request", ex);
            logger.error("Data conflict", ex);
            response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT,
                                                                     Messages.CONFLICT_MESSAGE).build();
        } catch (PersistenceException ex) {
            if (ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
                response =
                    JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage())
                        .build();
            } else {
                response = JsonMessageBuilder
                    .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage())
                    .build();
            }
        } catch (Exception ex) {
            logger.error("Error executing the request", ex);
            response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()).build();
        } finally {
            ThreadLocalVariablesKeeper.setRequest(null);
            ThreadLocalVariablesKeeper.setSession(null);
        }

        return new JsonMessageBuilder()
            .addAction(request.get(JsonMessageBuilder.ACTION))
            .addRequestId(request.get(JsonMessageBuilder.REQUEST_ID))
            .include(response)
            .build();
    }

    public JsonObject tryExecute(JsonObject request, Session session) {
        Pair<WebsocketHandlers, Method> methodPair = getMethod(request);
        List<Object> args = prepareArgumentValues(methodPair.getRight(), request, session);
        WebSocketResponse response = null;
        try {
            response = (WebSocketResponse) methodPair.getRight().invoke(methodPair.getLeft(), args.toArray());
        } catch (InvocationTargetException ex) {
            Throwable target = ex.getTargetException();
            Throwables.propagateIfPossible(target);
            throw new HiveException(target.getMessage(), target);
        } catch (IllegalAccessException ex) {
            throw HiveException.fatal();
        }
        if (response == null) {
            logger.error("[tryExecute]  response is null ");
            return JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
{'fraction_non_alphanumeric': 0.08803360192010971, 'fraction_numerical': 0.0006857534716269502, 'mean_word_length': 3.2302393038433648, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6002823', 'n_tokens_mistral': 2951, 'n_tokens_neox': 2926, 'n_words': 505}