Subversion Repositories bacoAlunos

Rev

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

Rev Author Line No. Line
1670 jmachado 1
package pt.estgp.estgweb.services.data.repositorydocuments;
2
 
3
import com.owlike.genson.TransformationException;
1692 jmachado 4
import jomm.dao.impl.AbstractDao;
1675 jmachado 5
import org.json.JSONArray;
6
import org.json.JSONException;
7
import org.json.JSONObject;
8
import pt.estgp.estgweb.Globals;
1670 jmachado 9
import pt.estgp.estgweb.domain.*;
10
import pt.estgp.estgweb.domain.dao.DaoFactory;
1675 jmachado 11
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
12
import pt.estgp.estgweb.filters.exceptions.AccessDeniedException;
13
import pt.estgp.estgweb.services.data.RepositoryService;
1692 jmachado 14
import pt.estgp.estgweb.services.data.repositorydocuments.interfaces.RepositoryInterface;
1711 jmachado 15
import pt.estgp.estgweb.services.data.sourcemodules.RepositoryDocumentsSource;
16
import pt.estgp.estgweb.services.utils.HttpServices;
1675 jmachado 17
import pt.estgp.estgweb.web.controllers.utils.FileUploaded;
18
import pt.estgp.estgweb.web.controllers.utils.FilesUploadResult;
1711 jmachado 19
import pt.estgp.estgweb.web.exceptions.NotAuthorizedException;
1670 jmachado 20
import pt.utl.ist.berserk.logic.serviceManager.IService;
21
 
1675 jmachado 22
import java.io.FileInputStream;
1711 jmachado 23
import java.io.FileNotFoundException;
1670 jmachado 24
import java.io.IOException;
1692 jmachado 25
import java.util.ArrayList;
1675 jmachado 26
import java.util.HashSet;
27
import java.util.List;
28
import java.util.Set;
1670 jmachado 29
 
30
/**
31
 * Created by jorgemachado on 23/02/17.
32
 */
1675 jmachado 33
public class RepositoryDocumentService implements IService
34
{
1670 jmachado 35
 
1675 jmachado 36
    public static final 1.5.0/docs/api/java/lang/String.html">String REPOSITORY_DOCS_ROLE = "repositoryDocs";
1670 jmachado 37
 
1675 jmachado 38
 
39
    /**
40
     * Public service
41
     * Uses Roles to filter collections
42
     * @param collectionId
43
     * @param userSession
44
     * @return
45
     * @throws IOException
46
     * @throws TransformationException
47
     * @throws JSONException
48
     * @throws AccessDeniedException
49
     */
50
    public JSONArray openRepositoryCollection(1.5.0/docs/api/java/lang/Long.html">Long collectionId, UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException {
51
 
1679 jmachado 52
        boolean onlyVisible = !(userSession.getUser() != null &&
1675 jmachado 53
                (userSession.getUser().hasRole(REPOSITORY_DOCS_ROLE)
54
                        ||
1679 jmachado 55
                        userSession.getUser().isSuperuserOrAdmin()));
1675 jmachado 56
        if(collectionId == null)
57
        {
58
            //finding roots
1679 jmachado 59
            List<RepositoryDocumentCollectionImpl> roots = DaoFactory.getRepositoryDocumentCollectionDaoImpl().findRoots(onlyVisible);
1675 jmachado 60
            return RepositoryDocumentCollectionImpl.toJsonArray(roots);
61
        }
62
        else
63
        {
1679 jmachado 64
            List<RepositoryDocumentCollectionImpl> childs = DaoFactory.getRepositoryDocumentCollectionDaoImpl().findChilds(onlyVisible,collectionId);
1675 jmachado 65
            return RepositoryDocumentCollectionImpl.toJsonArray(childs);
66
        }
67
    }
68
 
69
 
70
    public JSONArray openRepositoryCollectionDocuments(1.5.0/docs/api/java/lang/Long.html">Long collectionId, UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException {
71
 
1679 jmachado 72
        boolean onlyVisible = !(userSession.getUser() != null &&
1675 jmachado 73
                (userSession.getUser().hasRole(REPOSITORY_DOCS_ROLE)
74
                        ||
1679 jmachado 75
                        userSession.getUser().isSuperuserOrAdmin()));
1675 jmachado 76
 
1679 jmachado 77
        List<RepositoryDocumentImpl> docs = DaoFactory.getRepositoryDocumentDaoImpl().findDocumentsSortPublishDateDesc(onlyVisible, collectionId);
1675 jmachado 78
        return RepositoryDocumentImpl.toJsonArray(docs);
79
    }
80
 
81
    public JSONObject addRepositoryCollection(1.5.0/docs/api/java/lang/Long.html">Long collectionParentId, UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException {
82
        RepositoryDocumentCollectionImpl collectionParent = null;
83
        if(collectionParentId != null)
84
        {
85
             collectionParent = (RepositoryDocumentCollectionImpl) DaoFactory.getRepositoryDocumentCollectionDaoImpl().get(collectionParentId);
86
        }
87
        RepositoryDocumentCollectionImpl collectionChild = DomainObjectFactory.createRepositoryDocumentCollectionImpl();
88
        collectionChild.setParent(collectionParent);
89
 
90
        if(collectionParent != null)
91
            collectionParent.getChilds().add(collectionChild);
92
 
93
        collectionChild.setVisible(true);
94
        DaoFactory.getRepositoryDocumentCollectionDaoImpl().save(collectionChild);
95
        return collectionChild.toJsonObject();
96
    }
97
 
98
    public JSONObject changeParentRepositoryDocumentCollection(1.5.0/docs/api/java/lang/Long.html">Long collectionId,1.5.0/docs/api/java/lang/Long.html">Long newParentId, UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException {
99
        RepositoryDocumentCollectionImpl collectionChild = (RepositoryDocumentCollectionImpl) DaoFactory.getRepositoryDocumentCollectionDaoImpl().get(collectionId);
100
        RepositoryDocumentCollectionImpl collectionNewParent = newParentId == null ? null : (RepositoryDocumentCollectionImpl) DaoFactory.getRepositoryDocumentCollectionDaoImpl().get(newParentId);
101
 
102
        if(collectionChild.getParent() != null)
103
        {
104
            collectionChild.getParent().getChilds().remove(collectionChild);
105
        }
106
        collectionChild.setParent(collectionNewParent);
107
        if(collectionNewParent != null)
108
        {
109
            collectionNewParent.getChilds().add(collectionChild);
110
        }
111
 
112
 
113
        return collectionChild.toJsonObject();
114
    }
115
 
116
 
117
 
118
    public JSONObject updateRepositoryCollection(1.5.0/docs/api/java/lang/String.html">String collection, UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException {
119
 
120
        RepositoryDocumentCollectionImpl collectionChild = RepositoryDocumentCollectionImpl.loadFromJson(collection);
121
 
122
 
123
        RepositoryDocumentCollectionImpl persistent = (RepositoryDocumentCollectionImpl) DaoFactory.getRepositoryDocumentCollectionDaoImpl().get(collectionChild.getId());
124
        persistent.setName(collectionChild.getName());
125
        persistent.setDescription(collectionChild.getDescription());
126
        persistent.setLegacyUrl(collectionChild.getLegacyUrl());
127
        persistent.setVisible(collectionChild.isVisible());
128
 
129
        return persistent.toJsonObject();
130
    }
131
 
132
 
1719 jmachado 133
    public JSONArray checkRepositoryDocumentExistence(1.5.0/docs/api/java/lang/String.html">String docJson, UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException, NotAuthorizedException
134
    {
135
        JSONArray found = new JSONArray();
136
        RepositoryDocumentImpl view = RepositoryDocumentImpl.loadFromJson(docJson);
137
        List<RepositoryDocumentImpl> documents = DaoFactory.getRepositoryDocumentDaoImpl().findDocumentsByTitle(view.getTitle());
138
        if(documents.size() > 0)
139
        {
140
            for(RepositoryDocumentImpl doc: documents)
141
            {
142
                found.put(doc.toJsonObject());
143
            }
144
        }
145
        return found;
146
    }
147
 
1711 jmachado 148
    public JSONObject saveRepositoryDocument(1.5.0/docs/api/java/lang/String.html">String docJson, FilesUploadResult uploadedFiles, UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException, NotAuthorizedException {
1675 jmachado 149
 
1670 jmachado 150
        RepositoryDocumentImpl view = RepositoryDocumentImpl.loadFromJson(docJson);
1711 jmachado 151
 
152
        if(view.getCollection() == null || view.getCollection().getId() <= 0)
153
        {
154
            throw new NotAuthorizedException("Não pode depositar documentos sem colecção");
155
        }
156
 
1670 jmachado 157
        RepositoryDocumentImpl persistent = null;
158
        if(view.getId() <= 0)
159
        {
1711 jmachado 160
            5+0%2Fdocs%2Fapi+List">List dups = DaoFactory.getRepositoryDocumentDaoImpl().findDocumentsByTitleAndCollection(view.getTitle(), view.getCollection().getId());
161
            if(dups.size() > 0)
162
            {
163
                throw new NotAuthorizedException("Já existe um documento com o mesmo titulo na colecção");
164
            }
1670 jmachado 165
            persistent = DomainObjectFactory.createRepositoryDocumentImpl();
166
            DaoFactory.getRepositoryDocumentDaoImpl().save(persistent);
167
        }
1675 jmachado 168
        else
169
        {
170
            persistent = (RepositoryDocumentImpl) DaoFactory.getRepositoryDocumentDaoImpl().get(view.getId());
171
        }
1670 jmachado 172
 
173
        persistent.setContributorsJson(view.getContributorsJson());
174
        persistent.setAuthorsJson(view.getAuthorsJson());
175
        persistent.setTitle(view.getTitle());
176
        persistent.setSubtitle(view.getSubtitle());
177
        persistent.setPublisher(view.getPublisher());
178
        persistent.setDescription(view.getDescription());
179
        persistent.setPublishDate(view.getPublishDate());
180
        persistent.setCloseDate(view.getCloseDate());
181
        persistent.setInternalIdentifier(view.getInternalIdentifier());
182
        persistent.setVisible(view.isVisible());
183
 
184
        if(view.getCollection() != null)
185
        {
186
            RepositoryDocumentCollection col = DaoFactory.getRepositoryDocumentCollectionDaoImpl().get(view.getCollection().getId());
187
            col.getId();
188
            persistent.setCollection((RepositoryDocumentCollectionImpl) col);
189
        }
190
 
1675 jmachado 191
        /**
192
         * atualizar campos dos ficheiros já existentes
193
         */
194
        if(view.getRepositoryDocumentFiles() != null && view.getRepositoryDocumentFiles().size() > 0)
195
        {
196
            for(RepositoryDocumentFileImpl ficheiroAtualizado : view.getRepositoryDocumentFiles())
197
            {
198
                for(RepositoryDocumentFileImpl repoFileCandidate: persistent.getRepositoryDocumentFiles() )
199
                {
200
                    if(repoFileCandidate.getId()==ficheiroAtualizado.getId())
201
                    {
202
                        //ficheiro encontrado
203
                        repoFileCandidate.setTitle(ficheiroAtualizado.getTitle());
204
                        repoFileCandidate.setDescription(ficheiroAtualizado.getDescription());
205
                        repoFileCandidate.setVisible(ficheiroAtualizado.isVisible());
206
                        repoFileCandidate.getRepositoryFileProxy().getRepositoryFile().setAccessControl(ficheiroAtualizado.getRepositoryFileProxy().getRepositoryFile().getAccessControl());
1679 jmachado 207
                        if(!repoFileCandidate.isVisible())
208
                            repoFileCandidate.getRepositoryFileProxy().getRepositoryFile().setAccessControl(ResourceAccessControlEnum.privateDomain.getKey());
1675 jmachado 209
                        break;
210
                    }
211
                }
212
            }
213
        }
214
        if(uploadedFiles != null)
215
        {
216
            RepositoryService repositoryService = new RepositoryService();
217
            for(FileUploaded uploadedF : uploadedFiles.getUploadedFiles())
218
            {
1711 jmachado 219
                if(uploadedF.getAccessControl() == null)
220
                    uploadedF.setAccessControl(ResourceAccessControlEnum.publicDomain.getKey());
1675 jmachado 221
 
222
                ResourceAccessControlEnum controloAcesso = ResourceAccessControlEnum.parse(uploadedF.getAccessControl());
223
 
224
                RepositoryDocumentFileImpl repoFile = null;
225
                1.5.0/docs/api/java/lang/String.html">String repositoryStream = uploadedF.getRepositoryStream();
226
                if(repositoryStream != null)
227
                {
228
                    for(RepositoryDocumentFileImpl repoFileCandidate: persistent.getRepositoryDocumentFiles() )
229
                    {
230
                        if(repoFileCandidate.getRepositoryFileProxy().getRepositoryStream().equals(repositoryStream))
231
                        {
232
                            repoFile = repoFileCandidate;
233
                            break;
234
                        }
235
                    }
236
                    if(repoFile == null)
237
                        throw new AccessDeniedException("Trying to access to a repoFile not Allowded");
238
 
239
                    repositoryService.updateRepositoryFile(
240
                            repositoryStream,
241
                            new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(new java.io.1.5.0/docs/api/java/io/File.html">File(Globals.TMP_DIR + "/" + uploadedF.getTmpName())),
242
                            uploadedF.getContentType(),
243
                            uploadedF.getExtension(),
244
                            (int)uploadedF.getFileSize(),
245
                            uploadedF.getFileName(),
246
                            "Institutional Repository Document File",
247
                            controloAcesso);
248
                }
249
                else
250
                {
1711 jmachado 251
                    if(uploadedF.getTmpName().startsWith("http://") || uploadedF.getTmpName().startsWith("ftp://") || uploadedF.getTmpName().startsWith("https://"))
252
                    {
253
                        uploadedF.setVisible(true);
254
 
255
                        FileUploaded dowloadedF = HttpServices.downloadUrl(uploadedF.getTmpName());
256
                        uploadedF.setFileSize(dowloadedF.getFileSize());
257
                        uploadedF.setFileName(dowloadedF.getFileName());
258
                        uploadedF.setExtension(dowloadedF.getExtension());
259
                        uploadedF.setContentType(dowloadedF.getContentType());
260
                        uploadedF.setTmpName(dowloadedF.getTmpName());
261
 
262
                    }
263
                    else if(!new java.io.1.5.0/docs/api/java/io/File.html">File(Globals.TMP_DIR + "/" + uploadedF.getTmpName()).exists())
264
                    {
265
                        throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("Ficheiro com o identificador: " + uploadedF.getTmpName() + " não foi encontrado");
266
                    }
267
 
1675 jmachado 268
                    repositoryStream = repositoryService.storeRepositoryFile(
269
                            new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(new java.io.1.5.0/docs/api/java/io/File.html">File(Globals.TMP_DIR + "/" + uploadedF.getTmpName())),
270
                            uploadedF.getContentType(),
271
                            uploadedF.getExtension(),
272
                            (int)uploadedF.getFileSize(),
273
                            uploadedF.getFileName(),
274
                            "Institutional Repository Document File",
275
                            controloAcesso,
1711 jmachado 276
                            new RepositoryDocumentsSource(),
277
                            userSession.getUser());
1675 jmachado 278
                    Set<RepositoryDocumentFileImpl> files = persistent.getRepositoryDocumentFiles();
279
                    if(files == null)
280
                    {
281
                        files = new HashSet<RepositoryDocumentFileImpl>();
282
                        persistent.setRepositoryDocumentFiles(files);
283
                    }
284
                    repoFile = new RepositoryDocumentFileImpl();
285
                    DaoFactory.getRepositoryDocumentFileDaoImpl().save(repoFile);
286
                    files.add(repoFile);
287
                    RepositoryFileProxy repositoryFileProxy = new RepositoryFileProxy();
288
                    repositoryFileProxy.setRepositoryStream(repositoryStream);
289
                    repoFile.setRepositoryFileProxy(repositoryFileProxy);
290
                }
291
 
292
                repoFile.setVisible(uploadedF.isVisible());
1679 jmachado 293
                if(!repoFile.isVisible())
294
                    repoFile.getRepositoryFileProxy().getRepositoryFile().setAccessControl(ResourceAccessControlEnum.privateDomain.getKey());
1675 jmachado 295
                repoFile.setTitle(uploadedF.getTitle());
296
                repoFile.setDescription(uploadedF.getDescription());
297
 
298
            }
299
 
300
        }
301
 
1670 jmachado 302
        1.5.0/docs/api/java/lang/System.html">System.out.println(view.toJson());
1675 jmachado 303
        return persistent.toJsonObject();
1670 jmachado 304
    }
1692 jmachado 305
 
306
 
307
    public JSONArray loadCollectionsOrderedAsTree() throws JSONException, TransformationException, 1.5.0/docs/api/java/io/IOException.html">IOException {
308
        ArrayList<RepositoryDocumentCollectionImpl> collections = new ArrayList<RepositoryDocumentCollectionImpl>();
309
        List<RepositoryDocumentCollection> collectionsRoots = DaoFactory.getRepositoryDocumentCollectionDaoImpl().findRoots();
310
        for(RepositoryDocumentCollection col : collectionsRoots)
311
        {
312
            col.getName();
313
            collections.add((RepositoryDocumentCollectionImpl) col);
314
            collections.addAll(loadChildsOrderedAsTree(col));
315
        }
316
        return RepositoryDocumentCollectionImpl.toJsonArray(collections);
317
    }
318
 
319
    private ArrayList<RepositoryDocumentCollectionImpl> loadChildsOrderedAsTree(RepositoryDocumentCollection rootCol)
320
    {
321
        ArrayList<RepositoryDocumentCollectionImpl> collections = new ArrayList<RepositoryDocumentCollectionImpl>();
322
        for(RepositoryDocumentCollection col : rootCol.getChilds())
323
        {
324
            col.getName();
325
            collections.add((RepositoryDocumentCollectionImpl) col);
326
            collections.addAll(loadChildsOrderedAsTree(col));
327
        }
328
        return collections;
329
    }
330
 
331
 
332
 
333
 
334
    public JSONObject addRepositoryInterface(UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException {
335
        RepositoryDocumentInterfaceImpl repositoryDocumentInterface = DomainObjectFactory.createRepositoryDocumentInterfaceImpl();
336
        repositoryDocumentInterface.setVisible(false);
337
        DaoFactory.getRepositoryDocumentInterfaceDaoImpl().save(repositoryDocumentInterface);
338
        return repositoryDocumentInterface.toJsonObject();
339
    }
340
    public JSONObject updateRepositoryInterface(1.5.0/docs/api/java/lang/String.html">String jsonObject,UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException {
341
 
342
        RepositoryDocumentInterfaceImpl repositoryDocumentInterface =
343
                RepositoryDocumentInterfaceImpl.loadFromJson(jsonObject);
344
 
345
        RepositoryDocumentInterfaceImpl persistent = (RepositoryDocumentInterfaceImpl) DaoFactory.getRepositoryDocumentInterfaceDaoImpl().get(repositoryDocumentInterface.getId());
346
        persistent.setVisible(repositoryDocumentInterface.isVisible());
347
        persistent.setAdminDescription(repositoryDocumentInterface.getAdminDescription());
348
        persistent.setSlug(repositoryDocumentInterface.getSlug());
349
 
350
        return persistent.toJsonObject();
351
    }
352
 
353
    public void removeRepositoryInterface(1.5.0/docs/api/java/lang/Long.html">Long id,UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException {
354
 
355
        RepositoryDocumentInterfaceImpl persistent = (RepositoryDocumentInterfaceImpl) DaoFactory.getRepositoryDocumentInterfaceDaoImpl().get(id);
356
        DaoFactory.getRepositoryDocumentInterfaceDaoImpl().delete(persistent);
357
    }
358
 
359
 
360
    public void saveRepositoryInterfaceData(1.5.0/docs/api/java/lang/Long.html">Long id,1.5.0/docs/api/java/lang/String.html">String dataJson, UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JSONException, AccessDeniedException {
361
 
362
        RepositoryInterface repositoryInterface = RepositoryInterface.loadFromJson(dataJson);
363
        RepositoryDocumentInterfaceImpl persistent = (RepositoryDocumentInterfaceImpl) DaoFactory.getRepositoryDocumentInterfaceDaoImpl().get(id);
364
        persistent.setRepositoryInterface(repositoryInterface);
365
    }
366
 
367
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws TransformationException, JSONException, 1.5.0/docs/api/java/io/IOException.html">IOException
368
    {
369
        AbstractDao.getCurrentSession().beginTransaction();
370
        JSONArray array = new RepositoryDocumentService().loadCollectionsOrderedAsTree();
371
        1.5.0/docs/api/java/lang/System.html">System.out.println(array.toString());
372
        AbstractDao.getCurrentSession().getTransaction().commit();
373
    }
374
 
1670 jmachado 375
}