Subversion Repositories bacoAlunos

Rev

Rev 1478 | Rev 1782 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
881 jmachado 1
package pt.estgp.estgweb.services.courseunits;
2
 
1103 jmachado 3
import jomm.dao.impl.AbstractDao;
881 jmachado 4
import jomm.utils.PdfUtils;
917 jmachado 5
import org.apache.commons.net.ftp.FTP;
6
import org.apache.commons.net.ftp.FTPClient;
881 jmachado 7
import org.apache.fop.apps.FOPException;
8
import org.apache.log4j.Logger;
917 jmachado 9
import org.dom4j.Document;
881 jmachado 10
import pt.estgp.estgweb.Globals;
11
import pt.estgp.estgweb.domain.*;
12
import pt.estgp.estgweb.domain.dao.DaoFactory;
1103 jmachado 13
import pt.estgp.estgweb.domain.dao.impl.CourseUnitDaoImpl;
881 jmachado 14
import pt.estgp.estgweb.domain.views.CourseUnitEvaluationView;
1312 jmachado 15
import pt.estgp.estgweb.domain.views.CourseUnitView;
881 jmachado 16
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
1103 jmachado 17
import pt.estgp.estgweb.services.data.IRepositoryFile;
881 jmachado 18
import pt.estgp.estgweb.services.data.RepositoryService;
19
import pt.estgp.estgweb.services.expceptions.ServiceException;
20
import pt.estgp.estgweb.utils.Dom4jUtil;
917 jmachado 21
import pt.estgp.estgweb.web.FtpServer;
881 jmachado 22
import pt.utl.ist.berserk.logic.serviceManager.IService;
23
 
24
import javax.xml.transform.TransformerException;
25
import javax.xml.transform.dom.DOMSource;
1103 jmachado 26
import java.io.*;
881 jmachado 27
import java.text.SimpleDateFormat;
917 jmachado 28
import java.util.*;
881 jmachado 29
 
30
/*
31
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
32
 *
33
 *
34
 * Created at 17/Out/2003 , 23:45:24
35
 *
36
 */
37
 
38
/**
39
 * @author Jorge Machado
40
 *
41
 *
917 jmachado 42
 * So pode editar a avaliação da unidade o docente da unidade
43
 * É gerado um PDF a cada gravação do Ficheiro
881 jmachado 44
 *
45
 * Created at 17/Out/2003 , 23:45:24
46
 *
47
 */
48
public class SaveCourseUnitEvaluation implements IService
49
{
50
    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);
51
 
917 jmachado 52
    RepositoryService repositoryService = new RepositoryService();
53
 
1312 jmachado 54
    public CourseUnitEvaluationView save(CourseUnitEvaluationView cupv, 1.5.0/docs/api/java/lang/Long.html">Long coursUnitId, UserSession usession, CourseUnitImpl c) throws ServiceException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, 1.5.0/docs/api/java/io/IOException.html">IOException, FOPException {
881 jmachado 55
 
56
 
949 jmachado 57
 
1312 jmachado 58
 
881 jmachado 59
        CourseUnitEvaluation evaluation = c.getCourseUnitEvaluation();
60
        if(evaluation == null)
61
        {
62
            evaluation = new CourseUnitEvaluationImpl();
63
            DaoFactory.getCourseUnitEvaluationDaoImpl().save(evaluation);
1029 jmachado 64
            c.setCourseUnitEvaluation(evaluation);
881 jmachado 65
        }
66
//
1312 jmachado 67
        //O form tem de vir sempre completo com todos os campos
68
        //Caso isto mude de futuro teremos de usar um novo metodo para
69
        //comutar o estado e nao o save.
70
        //Apenas o open muda somente o estado
881 jmachado 71
 
1312 jmachado 72
        /*if(usession.getUser() instanceof Teacher &&
881 jmachado 73
                ((((Teacher)(usession.getUser())).isTeacherOfCourseUnit(c.getId(),true))
74
                        ||
75
                        (c.getResponsableTeacher()!=null && usession.getUser().getId() == c.getResponsableTeacher().getId())
76
        ))
77
        {
1312 jmachado 78
            //PROF OU RESPONSAVEL*/
79
 
80
        cupv.persistViewInObjectTeacher(evaluation);
81
 
82
        /*}
1171 jmachado 83
        else if(usession.getUser() instanceof Teacher
881 jmachado 84
                && (((usession.getUser())).hasRole(c.getCourse().getValidationRole())
85
                ||
86
                ((usession.getUser()) == c.getCourse().getCoordinator()))
87
                )
88
        {
1171 jmachado 89
            //COMISSAO DE CURSO
881 jmachado 90
            cupv.persistViewInObjectTeacher(evaluation);
1312 jmachado 91
        }*/
92
 
881 jmachado 93
        List<String> errors = new ArrayList<String>();
1033 jmachado 94
        1.5.0/docs/api/java/lang/String.html">String estado = "POR ENTREGAR";
917 jmachado 95
        if(cupv.isFechar())
96
        {
97
            evaluation.setClosed(true);
1017 jmachado 98
            evaluation.setTeacherComplete(true);
1037 jmachado 99
            estado = "Aceite pela Comissão de Curso";
917 jmachado 100
        }
1017 jmachado 101
        else if(cupv.isTeacherComplete())
102
        {
1037 jmachado 103
            estado = "Entregue à Comissão de Curso pelo docente";
1017 jmachado 104
            evaluation.setTeacherComplete(true);
105
        }
1153 jmachado 106
        else if(!cupv.isAutosave())
917 jmachado 107
        {
1033 jmachado 108
            estado = "Alterado pelo docente";
917 jmachado 109
            evaluation.setClosed(false);
1031 jmachado 110
            //TODO novo
111
            evaluation.setTeacherComplete(false);
917 jmachado 112
        }
881 jmachado 113
 
1033 jmachado 114
 
1210 jmachado 115
 
1153 jmachado 116
        if(!cupv.isAutosave())
881 jmachado 117
        {
1153 jmachado 118
            createPdf(evaluation,c,usession,errors);
119
            if(usession != null && usession.getUser() != null && usession.getUser() instanceof Teacher)
120
                DirectedCoordinatedUnitsService.sendNotificationsCourseUnitEvaluationEditedInterestedPeople(c, estado, usession);
121
            else
122
            {
123
                logger.info("Nao vai informar docentes");
124
            }
881 jmachado 125
        }
1210 jmachado 126
        //passou para aqui para não afetar a persistencia
127
        //estava em cima no create do new e depois o evaluation interno ficava a nulo
128
        // e no persist ja nao havia nada para persistir
129
        cupv.setCourseUnitEvaluation(evaluation);
881 jmachado 130
        return cupv;
131
    }
132
 
1312 jmachado 133
    public CourseUnitEvaluationView open(1.5.0/docs/api/java/lang/Long.html">Long coursUnitId, UserSession usession,CourseUnitImpl c) throws ServiceException {
987 jmachado 134
 
135
        CourseUnitEvaluation evaluation = c.getCourseUnitEvaluation();
1312 jmachado 136
 
137
        evaluation.setClosed(false);
138
        evaluation.setTeacherComplete(false);
987 jmachado 139
        CourseUnitEvaluationView cupv = new CourseUnitEvaluationView(evaluation);
1033 jmachado 140
        if(usession != null && usession.getUser() != null && usession.getUser() instanceof Teacher)
1037 jmachado 141
            DirectedCoordinatedUnitsService.sendNotificationsCourseUnitEvaluationEditedInterestedPeople(c, "Aberto pela Comissão de Curso", usession);
1033 jmachado 142
 
987 jmachado 143
        return cupv;
144
    }
145
 
1312 jmachado 146
    /**
147
     * Get the clearances from courseunit loaded by filter and put them in courseUnitView in service paramenter
148
     * returning the view fullfilled with clearances
149
     * @param cuv
150
     * @param courseUnitId
151
     * @param usession
152
     * @param c
153
     * @return
154
     * @throws ServiceException
155
     * @throws TransformerException
156
     * @throws IOException
157
     * @throws FOPException
158
     */
159
    public CourseUnitView initClearances(CourseUnitView cuv, 1.5.0/docs/api/java/lang/Long.html">Long courseUnitId, UserSession usession, CourseUnitImpl c) throws ServiceException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, 1.5.0/docs/api/java/io/IOException.html">IOException, FOPException {
160
        ((CourseUnitImpl)cuv.getCourseUnit()).setClearanceRuledSupport(c.getClearanceRuledSupport());
161
        return cuv;
162
    }
1017 jmachado 163
 
1312 jmachado 164
 
165
 
166
        //TODO TEACHER COMPLETE OPEN not in use coordinatores open and close every fields
167
    /*public CourseUnitEvaluationView setTeacherIncomplete(Long coursUnitId, UserSession usession) throws ServiceException {
168
 
1017 jmachado 169
        CourseUnit c = DaoFactory.getCourseUnitDaoImpl().get(coursUnitId);
170
        CourseUnitEvaluation evaluation = c.getCourseUnitEvaluation();
171
        //So responsaveis e profs desdemente que a avaliação nao esteja fechada
172
        //caso contrario so coordenadores
173
        boolean isTeacherOfCourseUnitAndEvaluationNotClosed =
174
                usession.getUser() instanceof Teacher
175
                &&
176
                (
177
                    ((Teacher)usession.getUser()).isTeacherOfCourseUnit(c.getId(),true)
178
                        ||
179
                    c.getResponsableTeacher()!=null && usession.getUser().getId() == c.getResponsableTeacher().getId()
180
                )
181
                && !evaluation.isClosed();
182
 
183
        boolean isCoordinatorOrCourseCommission =
184
                usession.getUser() instanceof Teacher
185
                        &&
186
                        (
187
                            usession.getUser().hasRole(c.getCourse().getValidationRole())
188
                                ||
189
                            ((usession.getUser()) == c.getCourse().getCoordinator())
190
                        );
191
 
192
 
193
        if(isTeacherOfCourseUnitAndEvaluationNotClosed || isCoordinatorOrCourseCommission)
194
        {
195
            evaluation.setTeacherComplete(false);
196
        }
197
        CourseUnitEvaluationView cupv = new CourseUnitEvaluationView(evaluation);
198
        return cupv;
1312 jmachado 199
    }*/
1017 jmachado 200
 
917 jmachado 201
    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 {
881 jmachado 202
 
917 jmachado 203
 
204
        1.5.0/docs/api/java/lang/String.html">String path = generatePdf(cuv, cu);
205
 
206
 
207
 
208
        RepositoryService repositoryService = new RepositoryService();
209
        User owner = userSession.getUser();
210
 
211
        if(cu.getEvaluationStreamId() == null)
212
        {
1703 jmachado 213
            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, null, owner);
917 jmachado 214
            cu.setEvaluationStreamId(identifier);
215
        }
216
        else
217
        {
1478 jmachado 218
            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.courseunitEvaluationDomain);
917 jmachado 219
        }
220
 
221
        //Obrigar a ser falso
222
 
223
        //NOVO
224
 
1103 jmachado 225
 
917 jmachado 226
        if(cuv.isClosed())
227
        {
228
            RepositoryFileImpl repoFile = repositoryService.loadView(cu.getEvaluationStreamId());
1103 jmachado 229
            sendPdfFtpIonline(cu,errors,userSession,new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(path),repoFile.getLastVersion().getSaveDate(),null);
917 jmachado 230
        }
1103 jmachado 231
 
917 jmachado 232
    }
233
 
234
    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 {
235
 
940 jmachado 236
        CourseUnitEvaluationImpl cuvImpl = (CourseUnitEvaluationImpl) DaoFactory.getCourseUnitEvaluationDaoImpl().narrow(cuv);
953 jmachado 237
        5+0%2Fdocs%2Fapi+Document">Document  responseDoc = cuvImpl.getDom(c);
917 jmachado 238
        responseDoc.setXMLEncoding("ISO-8859-1");
239
 
240
        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");
241
 
242
        responseDoc.getRootElement().addAttribute("data", sdf.format(new java.util.5+0%2Fdocs%2Fapi+Date">Date()));
243
 
244
 
245
 
246
 
247
        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";
248
 
249
        1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream out = new 1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream(path);
250
        Map<String,Object> params = new HashMap<String,Object>();
251
        params.put("site", Globals.SITE_URL);
252
 
253
 
254
        org.w3c.dom.5+0%2Fdocs%2Fapi+Document">Document dd = Dom4jUtil.toW3c(responseDoc);
255
 
256
        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);
257
        out.flush();
258
        out.close();
259
        return path;
260
    }
261
 
262
 
263
 
264
   /* public boolean sendPdfFtpIonline(CourseUnit cu, List<String> errors, UserSession u, FTPClient client) throws IOException, TransformerException, FOPException
265
    {
266
        RepositoryService repositoryService = new RepositoryService();
267
        if(cu.getProgramStreamId() != null && cu.getProgramStreamId().length()> 0)
268
        {
269
            RepositoryFileImpl repoFile = repositoryService.loadView(cu.getProgramStreamId());
270
            String path = generatePdfFile(cu, errors, u);
271
            sendPdfFtpIonline(cu,errors,u,path,repoFile.getLastVersion().getSaveDate(),client);
272
            return true;
273
        }
274
        return false;
275
    }*/
276
 
277
    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");
1103 jmachado 278
    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 {
917 jmachado 279
 
1312 jmachado 280
        if(Globals.TEST_ENVIRONEMENT)
281
        {
282
            1.5.0/docs/api/java/lang/String.html">String warn = "System in TEST Environement - will NOT send file to ionline test.control.var.DontSendIonlineFiles = true";
283
            logger.warn(warn);
284
            return false;
285
        }
917 jmachado 286
        FtpServer server = null;
287
        if(client == null)
288
        {
289
            server = FtpServer.getNewServer(Globals.FTP_IONLINE_URL,Globals.FTP_IONLINE_USER,Globals.FTP_IONLINE_PASS);
290
            client = server.getClient();
1005 jmachado 291
            if(client == null)
292
            {
293
                logger.warn("###################");
294
                logger.warn("################### > CANT CONNECT FTP");
1103 jmachado 295
                return false;
1005 jmachado 296
            }
917 jmachado 297
        }
298
        client.setFileType(FTP.BINARY_FILE_TYPE);
299
 
300
        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;
301
        if(!client.changeWorkingDirectory(pastaFichaCurricular))
302
        {
303
            logger.error("FTP CANT CHANGE TO PATH: " + pastaFichaCurricular);
1103 jmachado 304
            return false;
917 jmachado 305
        }
306
        else
307
        {
1103 jmachado 308
            client.storeFile(cu.getCode() + "_" + cu.getNormalizedName() + "_v" + sdf.format(versionDate) + ".pdf",input);
917 jmachado 309
 
310
            if(server != null)
311
            {
312
                client.quit();
313
                client.disconnect();
314
            }
1103 jmachado 315
            return true;
917 jmachado 316
        }
1103 jmachado 317
 
917 jmachado 318
        //
319
    }
320
 
1103 jmachado 321
    public void storeAllClosedEvaluationsInActivePeriod() throws 1.5.0/docs/api/java/io/IOException.html">IOException
322
    {
323
        CourseUnitDaoImpl dao = DaoFactory.getCourseUnitDaoImpl();
324
        List<Long> unitsIds = dao.loadClosedCourseUnitsEvaluations();
325
 
326
        List<String> errors = new ArrayList<String>();
327
        for (1.5.0/docs/api/java/lang/Long.html">Long unitId: unitsIds) {
328
            CourseUnit next = DaoFactory.getCourseUnitDaoImpl().load(unitId);
329
 
330
            try {
331
                if(next.getEvaluationStreamId() == null)
332
                {
333
                    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());
334
                    createPdf(next.getCourseUnitEvaluation(),next,null,errors);
335
                }
336
 
337
                1.5.0/docs/api/java/lang/System.html">System.out.print("Sending evaluation report for: " + next.getCourse().getName() + " - " + next.getSemestre() + " - " + next.getNormalizedName());
338
 
339
                RepositoryFileImpl repoFile = repositoryService.loadView(next.getEvaluationStreamId());
1106 jmachado 340
                IRepositoryFile iRepoFile = repositoryService.loadByIdentifier(next.getEvaluationStreamId());
1103 jmachado 341
 
342
 
343
                if(sendPdfFtpIonline(next,errors,null,iRepoFile.getInput(),repoFile.getLastVersion().getSaveDate(),null))
344
                    1.5.0/docs/api/java/lang/System.html">System.out.print(" ... OK");
345
                else
346
                    1.5.0/docs/api/java/lang/System.html">System.out.print(" ... FAIL probably no StreamID");
347
                1.5.0/docs/api/java/lang/System.html">System.out.print("\n");
348
                if(errors.size()>0)
349
                    for(1.5.0/docs/api/java/lang/String.html">String error:errors)
350
                        logger.warn(error);
351
            } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
352
                logger.error(e,e);
353
            } catch (1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException e) {
354
                logger.error(e, e);
355
            } catch (FOPException e) {
356
                e.printStackTrace();
357
            }
358
 
359
            AbstractDao.getCurrentSession().evict(next);
360
        }
361
    }
362
 
363
    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 {
364
 
365
        AbstractDao.getCurrentSession().beginTransaction();
366
        new SaveCourseUnitEvaluation().storeAllClosedEvaluationsInActivePeriod();
367
        AbstractDao.getCurrentSession().flush();
368
        AbstractDao.getCurrentSession().getTransaction().commit();
369
    }
881 jmachado 370
}