Subversion Repositories bacoAlunos

Rev

Rev 1211 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package pt.estgp.estgweb.services.courseunits;

import jomm.dao.impl.AbstractDao;
import jomm.utils.PdfUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.fop.apps.FOPException;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import pt.estgp.estgweb.Globals;
import pt.estgp.estgweb.domain.*;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.domain.dao.impl.CourseUnitDaoImpl;
import pt.estgp.estgweb.domain.views.CourseUnitEvaluationView;
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
import pt.estgp.estgweb.services.data.IRepositoryFile;
import pt.estgp.estgweb.services.data.RepositoryService;
import pt.estgp.estgweb.services.expceptions.ServiceException;
import pt.estgp.estgweb.utils.Dom4jUtil;
import pt.estgp.estgweb.web.FtpServer;
import pt.utl.ist.berserk.logic.serviceManager.IService;

import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
 *
 *
 * Created at 17/Out/2003 , 23:45:24
 *
 */


/**
 * @author Jorge Machado
 *
 *
 * So pode editar a avaliação da unidade o docente da unidade
 * É gerado um PDF a cada gravação do Ficheiro
 *
 * Created at 17/Out/2003 , 23:45:24
 *
 */

public class SaveCourseUnitEvaluation implements IService
{
    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(SaveCourseUnitEvaluation.class);

    RepositoryService repositoryService = new RepositoryService();

    public CourseUnitEvaluationView save(CourseUnitEvaluationView cupv, 1.5.0/docs/api/java/lang/Long.html">Long coursUnitId, UserSession usession) throws ServiceException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, 1.5.0/docs/api/java/io/IOException.html">IOException, FOPException {

        CourseUnit c = DaoFactory.getCourseUnitDaoImpl().get(coursUnitId);


        CourseUnitEvaluation evaluation = c.getCourseUnitEvaluation();
        if(evaluation == null)
        {
            evaluation = new CourseUnitEvaluationImpl();
            DaoFactory.getCourseUnitEvaluationDaoImpl().save(evaluation);
            c.setCourseUnitEvaluation(evaluation);
        }
//

        if(usession.getUser() instanceof Teacher &&
                ((((Teacher)(usession.getUser())).isTeacherOfCourseUnit(c.getId(),true))
                        ||
                        (c.getResponsableTeacher()!=null && usession.getUser().getId() == c.getResponsableTeacher().getId())
        ))
        {
            //PROF OU RESPONSAVEL
            cupv.persistViewInObjectTeacher(evaluation);
        }
        else if(usession.getUser() instanceof Teacher
                && (((usession.getUser())).hasRole(c.getCourse().getValidationRole())
                ||
                ((usession.getUser()) == c.getCourse().getCoordinator()))
                )
        {
            //COMISSAO DE CURSO
            cupv.persistViewInObjectTeacher(evaluation);
        }
        List<String> errors = new ArrayList<String>();
        1.5.0/docs/api/java/lang/String.html">String estado = "POR ENTREGAR";
        if(cupv.isFechar())
        {
            evaluation.setClosed(true);
            evaluation.setTeacherComplete(true);
            estado = "Aceite pela Comissão de Curso";
        }
        else if(cupv.isTeacherComplete())
        {
            estado = "Entregue à Comissão de Curso pelo docente";
            evaluation.setTeacherComplete(true);
        }
        else if(!cupv.isAutosave())
        {
            estado = "Alterado pelo docente";
            evaluation.setClosed(false);
            //TODO novo
            evaluation.setTeacherComplete(false);
        }



        if(!cupv.isAutosave())
        {
            createPdf(evaluation,c,usession,errors);
            if(usession != null && usession.getUser() != null && usession.getUser() instanceof Teacher)
                DirectedCoordinatedUnitsService.sendNotificationsCourseUnitEvaluationEditedInterestedPeople(c, estado, usession);
            else
            {
                logger.info("Nao vai informar docentes");
            }
        }
        //passou para aqui para não afetar a persistencia
        //estava em cima no create do new e depois o evaluation interno ficava a nulo
        // e no persist ja nao havia nada para persistir
        cupv.setCourseUnitEvaluation(evaluation);
        return cupv;
    }

    public CourseUnitEvaluationView open(1.5.0/docs/api/java/lang/Long.html">Long coursUnitId, UserSession usession) throws ServiceException {

        CourseUnit c = DaoFactory.getCourseUnitDaoImpl().get(coursUnitId);
        CourseUnitEvaluation evaluation = c.getCourseUnitEvaluation();
        if(usession.getUser() instanceof Teacher &&
                (((Teacher)usession.getUser()).isTeacherOfCourseUnit(c.getId(),true)
                ||
                c.getResponsableTeacher()!=null && usession.getUser().getId() == c.getResponsableTeacher().getId()
                ||
                usession.getUser().hasRole(c.getCourse().getValidationRole())
                ||
                ((usession.getUser()) == c.getCourse().getCoordinator())
                ))
        {
            evaluation.setClosed(false);
            evaluation.setTeacherComplete(false);
        }
        CourseUnitEvaluationView cupv = new CourseUnitEvaluationView(evaluation);
        if(usession != null && usession.getUser() != null && usession.getUser() instanceof Teacher)
            DirectedCoordinatedUnitsService.sendNotificationsCourseUnitEvaluationEditedInterestedPeople(c, "Aberto pela Comissão de Curso", usession);

        return cupv;
    }

    //TODO TEACHER COMPLETE OPEN not in use coordinatores open and close every fields
    public CourseUnitEvaluationView setTeacherIncomplete(1.5.0/docs/api/java/lang/Long.html">Long coursUnitId, UserSession usession) throws ServiceException {

        CourseUnit c = DaoFactory.getCourseUnitDaoImpl().get(coursUnitId);
        CourseUnitEvaluation evaluation = c.getCourseUnitEvaluation();
        //So responsaveis e profs desdemente que a avaliação nao esteja fechada
        //caso contrario so coordenadores
        boolean isTeacherOfCourseUnitAndEvaluationNotClosed =
                usession.getUser() instanceof Teacher
                &&
                (
                    ((Teacher)usession.getUser()).isTeacherOfCourseUnit(c.getId(),true)
                        ||
                    c.getResponsableTeacher()!=null && usession.getUser().getId() == c.getResponsableTeacher().getId()
                )
                && !evaluation.isClosed();

        boolean isCoordinatorOrCourseCommission =
                usession.getUser() instanceof Teacher
                        &&
                        (
                            usession.getUser().hasRole(c.getCourse().getValidationRole())
                                ||
                            ((usession.getUser()) == c.getCourse().getCoordinator())
                        );


        if(isTeacherOfCourseUnitAndEvaluationNotClosed || isCoordinatorOrCourseCommission)
        {
            evaluation.setTeacherComplete(false);
        }
        CourseUnitEvaluationView cupv = new CourseUnitEvaluationView(evaluation);
        return cupv;
    }

    public void createPdf(CourseUnitEvaluation cuv, CourseUnit cu, UserSession userSession,List<String> errors) throws 1.5.0/docs/api/java/io/IOException.html">IOException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, FOPException {


        1.5.0/docs/api/java/lang/String.html">String path = generatePdf(cuv, cu);



        RepositoryService repositoryService = new RepositoryService();
        User owner = userSession.getUser();

        if(cu.getEvaluationStreamId() == null)
        {
            1.5.0/docs/api/java/lang/String.html">String identifier = repositoryService.storeRepositoryFile(new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(path), "application/pdf", "pdf",((int) new 1.5.0/docs/api/java/io/File.html">File(path).length()), cu.getCode() + "-evaluation.pdf", "courseunit.evaluation.description" + cu.getName(), ResourceAccessControlEnum.courseunitEvaluationDomain,owner);
            cu.setEvaluationStreamId(identifier);
        }
        else
        {
            repositoryService.updateRepositoryFile(cu.getEvaluationStreamId(), new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(path),  "application/pdf", "pdf", ((int)new 1.5.0/docs/api/java/io/File.html">File(path).length()),cu.getCode() + "-evaluation.pdf", "evaluation.evaluation.description " + cu.getName(), ResourceAccessControlEnum.privateDomain);
        }

        //Obrigar a ser falso

        //NOVO


        if(cuv.isClosed())
        {
            RepositoryFileImpl repoFile = repositoryService.loadView(cu.getEvaluationStreamId());
            sendPdfFtpIonline(cu,errors,userSession,new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(path),repoFile.getLastVersion().getSaveDate(),null);
        }

    }

    public 1.5.0/docs/api/java/lang/String.html">String generatePdf(CourseUnitEvaluation cuv, CourseUnit c) throws 1.5.0/docs/api/java/io/IOException.html">IOException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, FOPException {

        CourseUnitEvaluationImpl cuvImpl = (CourseUnitEvaluationImpl) DaoFactory.getCourseUnitEvaluationDaoImpl().narrow(cuv);
        5+0%2Fdocs%2Fapi+Document">Document  responseDoc = cuvImpl.getDom(c);
        responseDoc.setXMLEncoding("ISO-8859-1");

        1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat sdf = new 1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat("dd-MM-yyyy");

        responseDoc.getRootElement().addAttribute("data", sdf.format(new java.util.5+0%2Fdocs%2Fapi+Date">Date()));




        1.5.0/docs/api/java/lang/String.html">String path = Globals.TMP_DIR + 1.5.0/docs/api/java/io/File.html">File.separator + c.getCode() + "-" + c.getNormalizedName() + "-eval.pdf";

        1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream out = new 1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream(path);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("site", Globals.SITE_URL);


        org.w3c.dom.5+0%2Fdocs%2Fapi+Document">Document dd = Dom4jUtil.toW3c(responseDoc);

        PdfUtils.createPdfFromXml(new 1.5.0/docs/api/javax/xml/transform/dom/DOMSource.html">DOMSource(dd), "pt/estgp/estgweb/services/courseunits/courseunitevaluation.fo.xsl", out, params);
        out.flush();
        out.close();
        return path;
    }



   /* public boolean sendPdfFtpIonline(CourseUnit cu, List<String> errors, UserSession u, FTPClient client) throws IOException, TransformerException, FOPException
    {
        RepositoryService repositoryService = new RepositoryService();
        if(cu.getProgramStreamId() != null && cu.getProgramStreamId().length()> 0)
        {
            RepositoryFileImpl repoFile = repositoryService.loadView(cu.getProgramStreamId());
            String path = generatePdfFile(cu, errors, u);
            sendPdfFtpIonline(cu,errors,u,path,repoFile.getLastVersion().getSaveDate(),client);
            return true;
        }
        return false;
    }*/


    1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat sdf = new 1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat("yyyy_MM_dd.HH_mm_ss");
    private boolean sendPdfFtpIonline(CourseUnit cu, List<String> errors, UserSession u,5+0%2Fdocs%2Fapi+InputStream">InputStream input,5+0%2Fdocs%2Fapi+Date">Date versionDate,FTPClient client) throws 1.5.0/docs/api/java/io/IOException.html">IOException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, FOPException {

        FtpServer server = null;
        if(client == null)
        {
            server = FtpServer.getNewServer(Globals.FTP_IONLINE_URL,Globals.FTP_IONLINE_USER,Globals.FTP_IONLINE_PASS);
            client = server.getClient();
            if(client == null)
            {
                logger.warn("###################");
                logger.warn("################### > CANT CONNECT FTP");
                return false;
            }
        }
        client.setFileType(FTP.BINARY_FILE_TYPE);

        1.5.0/docs/api/java/lang/String.html">String pastaFichaCurricular = Globals.FTP_IONLINE_START_PATH + cu.getPathIntranet() + "/" + Globals.INTRANET_DTP + "/" + Globals.INTRANET_DTP_FichaAvaliacao;
        if(!client.changeWorkingDirectory(pastaFichaCurricular))
        {
            logger.error("FTP CANT CHANGE TO PATH: " + pastaFichaCurricular);
            return false;
        }
        else
        {
            client.storeFile(cu.getCode() + "_" + cu.getNormalizedName() + "_v" + sdf.format(versionDate) + ".pdf",input);

            if(server != null)
            {
                client.quit();
                client.disconnect();
            }
            return true;
        }

        //
    }

    public void storeAllClosedEvaluationsInActivePeriod() throws 1.5.0/docs/api/java/io/IOException.html">IOException
    {
        CourseUnitDaoImpl dao = DaoFactory.getCourseUnitDaoImpl();
        List<Long> unitsIds = dao.loadClosedCourseUnitsEvaluations();

        List<String> errors = new ArrayList<String>();
        for (1.5.0/docs/api/java/lang/Long.html">Long unitId: unitsIds) {
            CourseUnit next = DaoFactory.getCourseUnitDaoImpl().load(unitId);

            try {
                if(next.getEvaluationStreamId() == null)
                {
                    1.5.0/docs/api/java/lang/System.html">System.out.print("Generating PDF for evaluation report for: " + next.getCourse().getName() + " - " + next.getSemestre() + " - " + next.getNormalizedName());
                    createPdf(next.getCourseUnitEvaluation(),next,null,errors);
                }

                1.5.0/docs/api/java/lang/System.html">System.out.print("Sending evaluation report for: " + next.getCourse().getName() + " - " + next.getSemestre() + " - " + next.getNormalizedName());

                RepositoryFileImpl repoFile = repositoryService.loadView(next.getEvaluationStreamId());
                IRepositoryFile iRepoFile = repositoryService.loadByIdentifier(next.getEvaluationStreamId());


                if(sendPdfFtpIonline(next,errors,null,iRepoFile.getInput(),repoFile.getLastVersion().getSaveDate(),null))
                    1.5.0/docs/api/java/lang/System.html">System.out.print(" ... OK");
                else
                    1.5.0/docs/api/java/lang/System.html">System.out.print(" ... FAIL probably no StreamID");
                1.5.0/docs/api/java/lang/System.html">System.out.print("\n");
                if(errors.size()>0)
                    for(1.5.0/docs/api/java/lang/String.html">String error:errors)
                        logger.warn(error);
            } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
                logger.error(e,e);
            } catch (1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException e) {
                logger.error(e, e);
            } catch (FOPException e) {
                e.printStackTrace();
            }

            AbstractDao.getCurrentSession().evict(next);
        }
    }

    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws 1.5.0/docs/api/java/io/IOException.html">IOException {

        AbstractDao.getCurrentSession().beginTransaction();
        new SaveCourseUnitEvaluation().storeAllClosedEvaluationsInActivePeriod();
        AbstractDao.getCurrentSession().flush();
        AbstractDao.getCurrentSession().getTransaction().commit();
    }
}