Example usage for javax.activation DataHandler toString

List of usage examples for javax.activation DataHandler toString

Introduction

In this page you can find the example usage for javax.activation DataHandler toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:es.pode.planificador.negocio.trabajos.CargaODEs.java

/**
 * Mtodo de ejecucin de la tarea./*from  w w  w. j a  v a  2s  . c o  m*/
 * Publicacin de los ODEs en la plataforma de manera automtica.
 */
public void execute(JobExecutionContext context) throws JobExecutionException {
    Long idTarea = null;
    String usuario = (String) context.getJobDetail().getJobDataMap().get(CtesPlanificador.USUARIO);
    boolean ejecucionIncorrecta = false;

    /* Aadimos la seguridad al proceso */
    log("Usuario que lanza la tarea: " + usuario);
    boolean contextoCargado = Autenticar.cargarContextoSeguridad(usuario);

    if (!contextoCargado) {
        log.error("ERROR: No han cargado los datos en el contexto de seguridad");
        return;
    }

    /*
     *   Parmetros propios del trabajo:
     *       pathODEs, pathODEsCargados, pathODEsNoCargados
     *       msgPublicado, msgNoPublicado y msgDescTrabajo
     *       
    */
    ArrayList parametros = (ArrayList) context.getJobDetail().getJobDataMap().get(CtesPlanificador.PARAMETROS);
    String pathODEs = (String) parametros.get(0);
    String pathODEsCargados = (String) parametros.get(1);
    String pathODEsNoCargados = (String) parametros.get(2);
    String msgPublicado = (String) parametros.get(3);
    String msgNoPublicado = (String) parametros.get(4);
    String msgDescTrabajo = (String) parametros.get(5);
    String sobrescribir = (String) parametros.get(6);

    log("CargaODEs: " + context.getJobDetail().getFullName() + " ejecutandose a las " + new Date());

    /* Comprobamos si existen los directorios de trabajo de la carga de ODEs */
    File fPathODEs = new File(pathODEs);
    if (!fPathODEs.exists()) {
        log.error("Error: El directorio donde se deben encontrar los ODEs no existe o no se puede acceder a l "
                + fPathODEs.getAbsolutePath());
        JobExecutionException excepcion = new JobExecutionException(
                "Error: No se ha podido registrar. El directorio de los ODEs no existe: "
                        + fPathODEs.getAbsolutePath());
        throw excepcion;
    }

    File fpathODEsCargados = new File(pathODEsCargados);
    if (!fpathODEsCargados.exists()) {
        log.error(
                "Error: El directorio donde se deben mover los ODEs cargados no existe o no se puede acceder a l "
                        + fPathODEs.getAbsolutePath());
        JobExecutionException excepcion = new JobExecutionException(
                "Error: No se ha podido registrar. No exste el directorio donde se deben moven los ODEs publicados: "
                        + fpathODEsCargados.getAbsolutePath());
        throw excepcion;
    }

    File fpathODEsNoCargados = new File(pathODEsNoCargados);
    if (!fpathODEsNoCargados.exists()) {
        log.error(
                "Error: El directorio donde se deben mover los ODEs no cargados no existe o no se puede acceder a l "
                        + fpathODEsNoCargados.getAbsolutePath());
        JobExecutionException excepcion = new JobExecutionException(
                "Error: El directorio donde se deben mover los ODEs no cargados no existe o no se puede acceder a l "
                        + fpathODEsNoCargados.getAbsolutePath());
        throw excepcion;
    }

    /* Registramos el inicio del trabajo */
    idTarea = Planificador.registrarInicioTarea(context.getJobDetail().getName(),
            context.getJobDetail().getGroup(), msgDescTrabajo, usuario);

    log("Identificador de la tarea: " + idTarea);

    /* Recorremos el directorio donde estan los ficheros(ODEs) a publicar */

    /* Antiguamente:: Se recogian los odes de una direccion en concreto
       File ODEs = new File(pathODEs);
       File[] arrayList = ODEs.listFiles();
     */

    File fileOde = null;

    String[] odes = UtilesFicheros.obtenerOdesDePath(pathODEs, true, true);

    //recorremos todos los odes
    for (int i = 0; i < odes.length; i++) {
        try {
            log("Carga del ODE: " + odes[i]);

            /* Se comprueba si la tarea ha sido interrumpida */
            if (interrupcion) {
                log("Se para la tarea por peticin del cliente");
                break;
            }

            /* Antes se ignoraba los directorios, ahora obtenermos una lista de los path de los odes
             * que esten dentro de una carpeta o de subcarpetas. no hace falta ignorar los directorios
             * Los directorios no se cargan en el nodo 
                    
            if (arrayList[i].isDirectory()) {
               log("Directorio: " + arrayList[i].getAbsolutePath());
               continue;
            }
                    
            //Nos aseguramos que siga existiendo el fichero a cargar
            if (!arrayList[i].exists()) {
               log("El fichero " + arrayList[i].getAbsolutePath() + " ha sido borrado o movido");
               continue;
            }
                    
            */

            //recogemos el ode correspondiente en un FILE para tratarlo
            fileOde = new File(odes[i]);

            //comprobamos que el ode existe todavia
            if (!fileOde.exists()) {
                log("El fichero " + odes[i] + " ha sido borrado o movido");
                continue;
            }

            FileDataSource fileDS = new FileDataSource(odes[i]);
            log("FileDataSource: " + fileDS.toString());

            /* Llamada al servicio de publicacin con el ODE */
            DataHandler pif = new DataHandler(fileDS);
            log("DataHandler: " + pif.toString());

            String codPublicacion = ServiceLocator.instance().getSrvPlanificadorService().publicarPIF(pif,
                    usuario.toString(), msgDescTrabajo + " " + fileOde.getName(), sobrescribir,
                    fileOde.getName());

            //Tratamos el codigo para que solo contenga el primero si tuviera mas de uno
            String codigoCapado = null;

            if (codPublicacion == null || codPublicacion.equals(""))
                codigoCapado = "20.1";
            else {
                int posicion = codPublicacion.indexOf(";");
                if (posicion == -1)
                    codigoCapado = codPublicacion;
                else
                    codigoCapado = codPublicacion.substring(0, posicion);
            }

            log("PublicarPIF: " + codigoCapado);

            /* Preparacin del registro del resultado de la publicacin */
            TareaEjecutadaVO tarea = new TareaEjecutadaVO();
            tarea.setId(idTarea);
            RegistroTareaEjecutadaVO registro = new RegistroTareaEjecutadaVO();
            registro.setTarea_ejecutada(tarea);
            registro.setFecha(new GregorianCalendar());
            registro.setCodigo(codigoCapado);

            /* Publicacin correcta */
            if (codigoCapado.equals(PUBLICACION_CORRECTA)) {
                log.debug("Registramos que la publicacin ha sido correcta. ODE: " + fileOde.getName());
                registro.setEstado(ConstantesAgrega.TRABAJO_CORRECTO);
                registro.setDescripcion(msgPublicado + ". " + fileOde.getName());

                /* Se mueve el ODE publicado al directorio correspondiente */
                try {
                    log.debug("Fichero: " + pathODEsCargados + File.separator + fileOde.getName());

                    File ficheroCargado = new File(pathODEsCargados + File.separator + fileOde.getName());

                    if (ficheroCargado.exists()) {
                        log.warn("Ya existe un fichero con ese nombre: " + ficheroCargado.getAbsolutePath()
                                + " en la carpeta de cargados. Se elimina para mover el nuevo fichero");
                        ficheroCargado.delete();
                    }

                    boolean mov = fileOde.renameTo(ficheroCargado);
                    if (!mov)
                        log.error("El fichero no se ha podido mover: " + fileOde.getAbsolutePath());
                } catch (Exception e2) {
                    RegistrarTrabajoException excepcion = new RegistrarTrabajoException(
                            "Error: No se ha podido mover el ODE cargado al directorio de ODEs publicados "
                                    + fileOde.getAbsolutePath(),
                            e2);
                    log.error(excepcion);
                }
            } else { // Publicacin incorrecta. El ODE no pasa la validacin
                log.info("El ODE: " + fileOde.getName() + " no es vlido. Cdigo de error: " + codPublicacion);
                registro.setEstado(ConstantesAgrega.TRABAJO_ERRONEO);
                // vamos a recoger el error de publicacion
                if (codPublicacion.indexOf(";") != -1)
                    msgNoPublicado = codPublicacion.substring(codPublicacion.indexOf(";") + 1);
                registro.setDescripcion(msgNoPublicado + ". " + fileOde.getName());
                registro.setCodigo(codigoCapado);
                ejecucionIncorrecta = true;

                /* Se mueve el ODE no publicado al directorio correspondiente */
                try {
                    log.debug(
                            "Fichero no publicado: " + pathODEsNoCargados + File.separator + fileOde.getName());

                    File ficheroNoCargado = new File(pathODEsNoCargados + File.separator + fileOde.getName());

                    if (ficheroNoCargado.exists()) {
                        log.warn("Ya existe un fichero con ese nombre: " + ficheroNoCargado.getAbsolutePath()
                                + " en la carpeta de no cargados. Se elimina para mover el nuevo fichero");
                        ficheroNoCargado.delete();
                    }

                    boolean mov = fileOde.renameTo(ficheroNoCargado);

                    if (!mov)
                        log.error("El fichero no se ha podido mover: " + fileOde.getAbsolutePath());
                } catch (Exception e2) {
                    RegistrarTrabajoException excepcion = new RegistrarTrabajoException(
                            "Error: No se ha podido mover el ODE no publicado " + fileOde.getAbsolutePath(),
                            e2);
                    log.error(excepcion);
                }
            }

            // Se registra en la tabla derivada como ha ido la carga de ese ODE
            try {
                ServiceLocator.instance().getSrvRegistroPlanificadorService().registrarTrabajoHijo(registro);
            } catch (Exception e1) {
                RegistrarTrabajoException excepcion = new RegistrarTrabajoException(
                        "Error: No se ha podido registrar la tarea derivada " + e1.getMessage(), e1);
                log.error(excepcion);
            }
        } catch (Exception e) { // Deberan ser excepciones enviadas del servicio de publicacin de ODEs

            String path = "";

            if (fileOde != null || fileOde.getAbsolutePath() != null)
                path = fileOde.getAbsolutePath();

            log.error("Error publicando ODE: " + path + " " + e);
            ejecucionIncorrecta = true;

            TareaEjecutadaVO tarea = new TareaEjecutadaVO();
            tarea.setId(idTarea);
            RegistroTareaEjecutadaVO registro = new RegistroTareaEjecutadaVO();
            registro.setTarea_ejecutada(tarea);
            registro.setDescripcion(msgNoPublicado + ". " + fileOde.getName() + " " + e.getMessage());
            registro.setEstado(ConstantesAgrega.TRABAJO_ERRONEO);
            registro.setCodigo(EXCEPCION_NO_CONTROLADA);
            registro.setFecha(new GregorianCalendar());

            /* Registramos la no publicacin del ODE */
            try {
                ServiceLocator.instance().getSrvRegistroPlanificadorService().registrarTrabajoHijo(registro);
            } catch (Exception e1) {
                RegistrarTrabajoException excepcion = new RegistrarTrabajoException(
                        "Error: No se ha podido registrar", e1);
                log.error(excepcion);
            }

            /* Se mueve el ODE no publicado al directorio correspondiente */
            try {
                log("Fichero no publicado: " + pathODEsNoCargados + File.separator + fileOde.getName());
                File ficheroNoCargado = new File(pathODEsNoCargados + File.separator + fileOde.getName());

                if (ficheroNoCargado.exists()) {
                    log.warn("Ya existe un fichero con ese nombre: " + ficheroNoCargado.getAbsolutePath()
                            + " en la carpeta de no cargados. Se elimina para mover el nuevo fichero");
                    ficheroNoCargado.delete();
                }

                boolean mov = fileOde.renameTo(ficheroNoCargado);

                if (!mov)
                    log.error("El fichero no se ha podido mover: " + fileOde.getAbsolutePath());
            } catch (Exception e2) {
                RegistrarTrabajoException excepcion = new RegistrarTrabajoException(
                        "Error: No se ha podido mover el ODE no publicado " + fileOde.getAbsolutePath(), e2);
                log.error(excepcion);
            }
        }
    }

    //TODO: De este registro se deber encargar la tarea ejecutada
    /* Registramos la hora de finalizacin de la tarea y si ha sido correcta/incorrecta la publicacin */
    try {
        TareaEjecutadaVO trabajoEjecutado = new TareaEjecutadaVO();
        trabajoEjecutado.setId(idTarea);
        trabajoEjecutado.setFechaFin(new GregorianCalendar());

        if (interrupcion)
            trabajoEjecutado.setEstado(ConstantesAgrega.TRABAJO_INTERRUMPIDO);
        else if (ejecucionIncorrecta)
            trabajoEjecutado.setEstado(ConstantesAgrega.TRABAJO_ERRONEO);
        else
            trabajoEjecutado.setEstado(ConstantesAgrega.TRABAJO_CORRECTO);

        ServiceLocator.instance().getSrvRegistroPlanificadorService()
                .registrarTrabajoFechaFin(trabajoEjecutado);
    } catch (Exception e1) {
        RegistrarTrabajoException excepcion = new RegistrarTrabajoException(
                "Error: No se ha podido registrar el fin del trabajo", e1);
        log.error(excepcion);
    }
}