<commit_before>package py.com.sodep.notificationserver.business;

import org.apache.log4j.Logger;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.util.Iterator;
import javapns.json.JSONException;
import javapns.notification.Payload;
import javapns.notification.PushNotificationPayload;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import py.com.sodep.notificationserver.db.dao.AplicacionDao;
import py.com.sodep.notificationserver.db.dao.DeviceRegistrationDao;
import py.com.sodep.notificationserver.db.dao.EventoDao;
import py.com.sodep.notificationserver.db.entities.Aplicacion;
import py.com.sodep.notificationserver.db.entities.Evento;
import py.com.sodep.notificationserver.db.entities.AndroidNotification;
import py.com.sodep.notificationserver.db.entities.AndroidResponse;
import py.com.sodep.notificationserver.db.entities.DeviceRegistration;
import py.com.sodep.notificationserver.db.entities.IosResponse;
import py.com.sodep.notificationserver.db.entities.Result;
import py.com.sodep.notificationserver.exceptions.handlers.BusinessException;
import py.com.sodep.notificationserver.config.GlobalCodes;
import py.com.sodep.notificationserver.facade.ApnsFacade;
import py.com.sodep.notificationserver.facade.GcmFacade;
import py.com.sodep.notificationserver.rest.entities.EventoResponse;

@ApplicationScoped
public class NotificationBusiness {

    @Inject
    AplicacionDao appDao;
    @Inject
    ApnsFacade facade;
    @Inject
    GcmFacade service;
    @Inject
    AndroidNotification notification;
    @Inject
    EventoDao eventoDao;
    @Inject
    DeviceRegistrationDao deviceDao;

    private static final Logger LOGGER = Logger.getLogger(NotificationBusiness.class);

    public EventoResponse crearEvento(Evento e, String appName) throws BusinessException {
        Aplicacion a = appDao.getByName(appName);
        if (a != null) {
            e.setAplicacion(a);
            validate(e);
            eventoDao.create(e);
            EventoResponse er = new EventoResponse(e);
            verificarNotificacionBloqueada(e);
            return er;
        } else {
            throw new BusinessException(GlobalCodes.errors.APLICACION_NOT_FOUND, "La aplicacion " + appName + " no existe.");
        }
    }

    public Evento actualizarEvento(Evento e) {
        eventoDao.update(e);
        return e;
    }

    public Evento notificar(Evento e) throws BusinessException {
        Aplicacion app = appDao.getByName(e.getAplicacion().getNombre());
        if (app != null) {
            if (e.isProductionMode()) {
                if (app.getApiKeyProd() != null) {
                    e.setAndroidResponse(notificarAndroid(app.getApiKeyProd(), e));
                }
                if (app.getCertificadoProd() != null && app.getKeyFileProd() != null) {
                    e.setIosResponse(notificarIos(app.getCertificadoProd(), app.getKeyFileProd(), e, true));
                }
            } else {
                if (app.getApiKeyDev() != null) {
                    e.setAndroidResponse(notificarAndroid(app.getApiKeyDev(), e));
                }
                if (app.getCertificadoDev() != null && app.getKeyFileDev() != null) {
                    e.setIosResponse(notificarIos(app.getCertificadoDev(), app.getKeyFileDev(), e, false));
                }
            }
        } else {
            throw new BusinessException(GlobalCodes.errors.APLICACION_NOT_FOUND, "La aplicacion " + e.getAplicacion().getNombre() + " no existe.");
        }
        e.setEstadoAndroid(GlobalCodes.ENVIADO);
        e.setEstadoIos(GlobalCodes.ENVIADO);
        return e;
    }

    @SuppressWarnings("rawtypes")
    public IosResponse notificarIos(String certifadoPath, String keyFile,
            Evento evento, Boolean productionMode) throws BusinessException {
        LOGGER.info("[Evento: " + evento + "]: Notificando iOs");
        File certificado = new File(certifadoPath);
        Payload payload = PushNotificationPayload.complex();
        ObjectNode pay = evento.getObjectNodePayLoad();
        try {
            if (evento.isSendToSync()) {
                ((PushNotificationPayload) payload).addCustomDictionary("content-available", "1");
            } else {
                ((PushNotificationPayload) payload).addAlert(evento
                        .getAlert());

                ((PushNotificationPayload) payload).addSound("default");
                if (evento.isSendToSync()) {
                    ((PushNotificationPayload) payload).addSound("default");
                }
                Iterator it = pay.fieldNames();
                while (it.hasNext()) {
                    String pair = (String) it.next();
                    LOGGER.info(pair + " = " + pay.get(pair));
                    payload.addCustomDictionary((String) pair,
                            pay.get(pair).asText());
                }
            }
        } catch (JSONException e) {
            LOGGER.error(e);
            throw new BusinessException(GlobalCodes.errors.BAD_REQUEST, "Error al parsear payload en notificacion iOs.");
        }
        IosResponse response = facade.send(payload, certificado, keyFile, productionMode, evento.getIosDevicesList());
        LOGGER.info("[IOS] Response: " + response);
        procesarErroresIos(evento, response);

        return response;

    }

    public void procesarErroresIos(Evento e, IosResponse res) {
        LOGGER.info("Procesando Errores");
        if (res.getFailure() > 0) {
            for (int i = 0; i < res.getResults().size(); i++) {
                Result r = res.getResults().get(i);
                LOGGER.info("Analizando resultado: " + r);
                if (r.getOriginalRegistrationId()!=null){
                    DeviceRegistration d = new DeviceRegistration(
                            e.getAndroidDevicesList().get(i),
                            r.getRegistrationId(),
                            GlobalCodes.NUEVO,
                            r.getError(),
                            e.getAplicacion(),
                            GlobalCodes.ELIMINAR,
                            GlobalCodes.IOS);
                    deviceDao.create(d);
                }
            }
        }
    }

    public AndroidResponse notificarAndroid(String apiKey, Evento evento) throws BusinessException {
        LOGGER.info("[Evento: " + evento.getId() + "]: notificando android");
        LOGGER.info("[Evento: " + evento.getId() + "]: Lista. Notificando android");
        notification.setRegistrationIds(evento.getAndroidDevicesList());
        notification.setData(evento.getObjectNodePayLoad().put("alert", evento.getAlert()));

        AndroidResponse ar;
        ar = service.send(apiKey, notification);
        procesarErroresAndroid(evento, ar);
        return ar;
    }

    public void procesarErroresAndroid(Evento evento, AndroidResponse ar) {
        if (ar.getFailure() > 0) {
            for (int i = 0; i < ar.getResults().size(); i++) {
                Result r = ar.getResults().get(i);
                LOGGER.info("Analizando resultado: " + r);
                if (r.getError() != null && (r.getError().equals(GlobalCodes.NotRegistered)
                        || r.getError().equals(GlobalCodes.InvalidRegistration)
                        || r.getError().equals(GlobalCodes.MissingRegistration))) {
                    DeviceRegistration d = new DeviceRegistration(
                            evento.getAndroidDevicesList().get(i),
                            r.getRegistrationId(),
                            GlobalCodes.NUEVO,
                            r.getError(),
                            evento.getAplicacion(),
                            GlobalCodes.getAccion(r.getError()),
                            GlobalCodes.ANDROID);
                    deviceDao.create(d);
                }
                if (r.getError() != null && (r.getError().equals(GlobalCodes.InvalidPackageName)
                        || r.getError().equals(GlobalCodes.MismatchSenderId))) {<commit_msg>Se ignora MismatchSenderId para el bloqueo de la aplicación<commit_after>package py.com.sodep.notificationserver.business;

import org.apache.log4j.Logger;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.util.Iterator;
import javapns.json.JSONException;
import javapns.notification.Payload;
import javapns.notification.PushNotificationPayload;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import py.com.sodep.notificationserver.db.dao.AplicacionDao;
import py.com.sodep.notificationserver.db.dao.DeviceRegistrationDao;
import py.com.sodep.notificationserver.db.dao.EventoDao;
import py.com.sodep.notificationserver.db.entities.Aplicacion;
import py.com.sodep.notificationserver.db.entities.Evento;
import py.com.sodep.notificationserver.db.entities.AndroidNotification;
import py.com.sodep.notificationserver.db.entities.AndroidResponse;
import py.com.sodep.notificationserver.db.entities.DeviceRegistration;
import py.com.sodep.notificationserver.db.entities.IosResponse;
import py.com.sodep.notificationserver.db.entities.Result;
import py.com.sodep.notificationserver.exceptions.handlers.BusinessException;
import py.com.sodep.notificationserver.config.GlobalCodes;
import py.com.sodep.notificationserver.facade.ApnsFacade;
import py.com.sodep.notificationserver.facade.GcmFacade;
import py.com.sodep.notificationserver.rest.entities.EventoResponse;

@ApplicationScoped
public class NotificationBusiness {

    @Inject
    AplicacionDao appDao;
    @Inject
    ApnsFacade facade;
    @Inject
    GcmFacade service;
    @Inject
    AndroidNotification notification;
    @Inject
    EventoDao eventoDao;
    @Inject
    DeviceRegistrationDao deviceDao;

    private static final Logger LOGGER = Logger.getLogger(NotificationBusiness.class);

    public EventoResponse crearEvento(Evento e, String appName) throws BusinessException {
        Aplicacion a = appDao.getByName(appName);
        if (a != null) {
            e.setAplicacion(a);
            validate(e);
            eventoDao.create(e);
            EventoResponse er = new EventoResponse(e);
            verificarNotificacionBloqueada(e);
            return er;
        } else {
            throw new BusinessException(GlobalCodes.errors.APLICACION_NOT_FOUND, "La aplicacion " + appName + " no existe.");
        }
    }

    public Evento actualizarEvento(Evento e) {
        eventoDao.update(e);
        return e;
    }

    public Evento notificar(Evento e) throws BusinessException {
        Aplicacion app = appDao.getByName(e.getAplicacion().getNombre());
        if (app != null) {
            if (e.isProductionMode()) {
                if (app.getApiKeyProd() != null) {
                    e.setAndroidResponse(notificarAndroid(app.getApiKeyProd(), e));
                }
                if (app.getCertificadoProd() != null && app.getKeyFileProd() != null) {
                    e.setIosResponse(notificarIos(app.getCertificadoProd(), app.getKeyFileProd(), e, true));
                }
            } else {
                if (app.getApiKeyDev() != null) {
                    e.setAndroidResponse(notificarAndroid(app.getApiKeyDev(), e));
                }
                if (app.getCertificadoDev() != null && app.getKeyFileDev() != null) {
                    e.setIosResponse(notificarIos(app.getCertificadoDev(), app.getKeyFileDev(), e, false));
                }
            }
        } else {
            throw new BusinessException(GlobalCodes.errors.APLICACION_NOT_FOUND, "La aplicacion " + e.getAplicacion().getNombre() + " no existe.");
        }
        e.setEstadoAndroid(GlobalCodes.ENVIADO);
        e.setEstadoIos(GlobalCodes.ENVIADO);
        return e;
    }

    @SuppressWarnings("rawtypes")
    public IosResponse notificarIos(String certifadoPath, String keyFile,
            Evento evento, Boolean productionMode) throws BusinessException {
        LOGGER.info("[Evento: " + evento + "]: Notificando iOs");
        File certificado = new File(certifadoPath);
        Payload payload = PushNotificationPayload.complex();
        ObjectNode pay = evento.getObjectNodePayLoad();
        try {
            if (evento.isSendToSync()) {
                ((PushNotificationPayload) payload).addCustomDictionary("content-available", "1");
            } else {
                ((PushNotificationPayload) payload).addAlert(evento
                        .getAlert());

                ((PushNotificationPayload) payload).addSound("default");
                if (evento.isSendToSync()) {
                    ((PushNotificationPayload) payload).addSound("default");
                }
                Iterator it = pay.fieldNames();
                while (it.hasNext()) {
                    String pair = (String) it.next();
                    LOGGER.info(pair + " = " + pay.get(pair));
                    payload.addCustomDictionary((String) pair,
                            pay.get(pair).asText());
                }
            }
        } catch (JSONException e) {
            LOGGER.error(e);
            throw new BusinessException(GlobalCodes.errors.BAD_REQUEST, "Error al parsear payload en notificacion iOs.");
        }
        IosResponse response = facade.send(payload, certificado, keyFile, productionMode, evento.getIosDevicesList());
        LOGGER.info("[IOS] Response: " + response);
        procesarErroresIos(evento, response);

        return response;

    }

    public void procesarErroresIos(Evento e, IosResponse res) {
        LOGGER.info("Procesando Errores");
        if (res.getFailure() > 0) {
            for (int i = 0; i < res.getResults().size(); i++) {
                Result r = res.getResults().get(i);
                LOGGER.info("Analizando resultado: " + r);
                if (r.getOriginalRegistrationId()!=null){
                    DeviceRegistration d = new DeviceRegistration(
                            e.getAndroidDevicesList().get(i),
                            r.getRegistrationId(),
                            GlobalCodes.NUEVO,
                            r.getError(),
                            e.getAplicacion(),
                            GlobalCodes.ELIMINAR,
                            GlobalCodes.IOS);
                    deviceDao.create(d);
                }
            }
        }
    }

    public AndroidResponse notificarAndroid(String apiKey, Evento evento) throws BusinessException {
        LOGGER.info("[Evento: " + evento.getId() + "]: notificando android");
        LOGGER.info("[Evento: " + evento.getId() + "]: Lista. Notificando android");
        notification.setRegistrationIds(evento.getAndroidDevicesList());
        notification.setData(evento.getObjectNodePayLoad().put("alert", evento.getAlert()));

        AndroidResponse ar;
        ar = service.send(apiKey, notification);
        procesarErroresAndroid(evento, ar);
        return ar;
    }

    public void procesarErroresAndroid(Evento evento, AndroidResponse ar) {
        if (ar.getFailure() > 0) {
            for (int i = 0; i < ar.getResults().size(); i++) {
                Result r = ar.getResults().get(i);
                LOGGER.info("Analizando resultado: " + r);
                if (r.getError() != null && (r.getError().equals(GlobalCodes.NotRegistered)
                        || r.getError().equals(GlobalCodes.InvalidRegistration)
                        || r.getError().equals(GlobalCodes.MissingRegistration))) {
                    DeviceRegistration d = new DeviceRegistration(
                            evento.getAndroidDevicesList().get(i),
                            r.getRegistrationId(),
                            GlobalCodes.NUEVO,
                            r.getError(),
                            evento.getAplicacion(),
                            GlobalCodes.getAccion(r.getError()),
                            GlobalCodes.ANDROID);
                    deviceDao.create(d);
                }
                if (r.getError() != null && r.getError().equals(GlobalCodes.InvalidPackageName)) {
{'fraction_non_alphanumeric': 0.10935850462646712, 'fraction_numerical': 0.0007452027572502018, 'mean_word_length': 2.1800947867298577, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2408186', 'n_tokens_mistral': 4521, 'n_tokens_neox': 4551, 'n_words': 749}