package pt.estgp.estgweb.services.data.repositorydocuments;
import jomm.dao.impl.AbstractDao;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import pt.estgp.estgweb.Globals;
import pt.estgp.estgweb.domain.*;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
import pt.estgp.estgweb.filters.exceptions.AccessDeniedException;
import pt.estgp.estgweb.services.data.RepositoryService;
import pt.estgp.estgweb.services.data.repositorydocuments.interfaces.InterfaceBlock;
import pt.estgp.estgweb.services.data.repositorydocuments.interfaces.InterfaceColumn;
import pt.estgp.estgweb.services.data.repositorydocuments.interfaces.InterfaceRow;
import pt.estgp.estgweb.services.data.repositorydocuments.interfaces.RepositoryInterface;
import pt.estgp.estgweb.services.data.sourcemodules.RepositoryDocumentsSource;
import pt.estgp.estgweb.services.expceptions.ServiceException;
import pt.estgp.estgweb.services.utils.HttpServices;
import pt.estgp.estgweb.web.controllers.utils.FileUploaded;
import pt.estgp.estgweb.web.controllers.utils.FilesUploadResult;
import pt.estgp.estgweb.web.exceptions.NotAuthorizedException;
import pt.utl.ist.berserk.logic.serviceManager.IService;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
/**
* Created by jorgemachado on 23/02/17.
*/
public class RepositoryDocumentService
implements IService
{
public static final 1.5.0/docs/api/java/lang/String.html">String REPOSITORY_DOCS_ROLE =
"repositoryDocs";
/**
*
* @param newCollectionId new parent Collection Id
* @param documentIds documentIds: [LONG,LONG, ...]
* @param userSession
* @throws IOException
* @throws JSONException
* @throws AccessDeniedException
*/
public void changeDocumentCollection
(1.5.0/docs/api/java/lang/Long.html">Long newCollectionId , JSONArray documentIds, UserSession userSession
) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException, AccessDeniedException
{
RepositoryDocumentCollection newCollection = DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
get(newCollectionId
);
for(int i =
0; i
< documentIds.
length();i++
)
{
long documentId = documentIds.
getLong(i
);
RepositoryDocument document = DaoFactory.
getRepositoryDocumentDaoImpl().
get(documentId
);
long old = -
1;
if(document.
getCollection() !=
null)
old = document.
getCollection().
getId();
document.
setCollection((RepositoryDocumentCollectionImpl
) newCollection
);
addHistoryLine
(userSession, document,
"Change collection by " + userSession.
getUser().
getUsername() +
" : " + userSession.
getUser().
getName() +
" : " + userSession.
getUser().
getId() +
" - at " +
new 5+0%2Fdocs%2Fapi+Date">Date().
toString() +
" from collection: " + old +
" to " + newCollectionId
);
}
}
/**
* Public service
* Uses Roles to filter collections
* @param collectionId
* @param userSession
* @return
* @throws IOException
* @throws JSONException
* @throws AccessDeniedException
*/
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, JSONException, AccessDeniedException
{
boolean onlyVisible =
!(userSession.
getUser() !=
null &&
(userSession.
getUser().
hasRole(REPOSITORY_DOCS_ROLE
)
||
userSession.
getUser().
isSuperuserOrAdmin()));
if(collectionId ==
null)
{
//finding roots
List
<RepositoryDocumentCollectionImpl
> roots = DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
findRoots(onlyVisible
);
return RepositoryDocumentCollectionImpl.
toJsonArray(roots
);
}
else
{
List
<RepositoryDocumentCollectionImpl
> childs = DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
findChilds(onlyVisible,collectionId
);
return RepositoryDocumentCollectionImpl.
toJsonArray(childs
);
}
}
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, JSONException, AccessDeniedException
{
boolean onlyVisible =
!(userSession.
getUser() !=
null &&
(userSession.
getUser().
hasRole(REPOSITORY_DOCS_ROLE
)
||
userSession.
getUser().
isSuperuserOrAdmin()));
List
<RepositoryDocumentImpl
> docs = DaoFactory.
getRepositoryDocumentDaoImpl().
findDocumentsSortPublishDateDesc(onlyVisible, collectionId
);
return RepositoryDocumentImpl.
toJsonArray(docs
);
}
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, JSONException, AccessDeniedException
{
RepositoryDocumentCollectionImpl collectionParent =
null;
if(collectionParentId
!=
null)
{
collectionParent =
(RepositoryDocumentCollectionImpl
) DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
get(collectionParentId
);
}
RepositoryDocumentCollectionImpl collectionChild = DomainObjectFactory.
createRepositoryDocumentCollectionImpl();
collectionChild.
setParent(collectionParent
);
if(collectionParent
!=
null)
collectionParent.
getChilds().
add(collectionChild
);
collectionChild.
setVisible(true);
DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
save(collectionChild
);
return collectionChild.
toJsonObject();
}
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, JSONException, AccessDeniedException
{
RepositoryDocumentCollectionImpl collectionChild =
(RepositoryDocumentCollectionImpl
) DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
get(collectionId
);
RepositoryDocumentCollectionImpl collectionNewParent = newParentId ==
null ? null :
(RepositoryDocumentCollectionImpl
) DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
get(newParentId
);
if(collectionChild.
getParent() !=
null)
{
collectionChild.
getParent().
getChilds().
remove(collectionChild
);
}
collectionChild.
setParent(collectionNewParent
);
if(collectionNewParent
!=
null)
{
collectionNewParent.
getChilds().
add(collectionChild
);
}
return collectionChild.
toJsonObject();
}
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, JSONException, AccessDeniedException
{
RepositoryDocumentCollectionImpl collectionChild = RepositoryDocumentCollectionImpl.
loadFromJson(collection
);
RepositoryDocumentCollectionImpl persistent =
(RepositoryDocumentCollectionImpl
) DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
get(collectionChild.
getId());
persistent.
setName(collectionChild.
getName());
persistent.
setDescription(collectionChild.
getDescription());
persistent.
setSortField(collectionChild.
getSortField());
persistent.
setLegacyUrl(collectionChild.
getLegacyUrl());
persistent.
setVisible(collectionChild.
isVisible());
return persistent.
toJsonObject();
}
public void deleteCollection
(long collectionId, UserSession userSession
) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException, AccessDeniedException, NotAuthorizedException
{
RepositoryDocumentCollection collection = DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
get(collectionId
);
if(collection.
getChilds().
size() > 0
)
{
throw new NotAuthorizedException
("A colecção " + collection.
getName() +
" não está vazia, tem colecções, limpe a colecção");
}
List
<RepositoryDocumentImpl
> docs = DaoFactory.
getRepositoryDocumentDaoImpl().
findDocuments(false, collectionId
);
if(docs.
size() > 0
)
{
throw new NotAuthorizedException
("A colecção " + collection.
getName() +
" não está vazia, tem documentos, limpe a colecção");
}
DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
delete(collection
);
}
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, JSONException, AccessDeniedException, NotAuthorizedException
{
JSONArray found =
new JSONArray
();
RepositoryDocumentImpl view = RepositoryDocumentImpl.
loadFromJson(docJson
);
List
<RepositoryDocumentImpl
> documents = DaoFactory.
getRepositoryDocumentDaoImpl().
findDocumentsByTitle(view.
getTitle());
if(documents.
size() > 0
)
{
for(RepositoryDocumentImpl doc: documents
)
{
found.
put(doc.
toJsonObject());
}
}
return found
;
}
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, JSONException, AccessDeniedException, NotAuthorizedException, ServiceException
{
RepositoryDocumentImpl view = RepositoryDocumentImpl.
loadFromJson(docJson
);
if(view.
getCollection() ==
null || view.
getCollection().
getId() <= 0
)
{
throw new NotAuthorizedException
("Não pode depositar documentos sem colecção");
}
RepositoryDocumentImpl persistent =
null;
if(view.
getId() <= 0
)
{
5+0%2Fdocs%2Fapi+List">List dups = DaoFactory.
getRepositoryDocumentDaoImpl().
findDocumentsByTitleAndCollection(view.
getTitle(), view.
getCollection().
getId());
if(dups.
size() > 0
)
{
throw new NotAuthorizedException
("Já existe um documento com o mesmo titulo na colecção");
}
persistent = DomainObjectFactory.
createRepositoryDocumentImpl();
DaoFactory.
getRepositoryDocumentDaoImpl().
save(persistent
);
persistent.
setOwner(userSession.
getUser());
}
else
{
persistent =
(RepositoryDocumentImpl
) DaoFactory.
getRepositoryDocumentDaoImpl().
get(view.
getId());
addHistoryLine
(userSession, persistent,
"Edited by " + userSession.
getUser().
getUsername() +
" : " + userSession.
getUser().
getName() +
" : " + userSession.
getUser().
getId() +
" - at " +
new 5+0%2Fdocs%2Fapi+Date">Date().
toString());
}
persistent.
setContributorsJson(view.
getContributorsJson());
persistent.
setAuthorsJson(view.
getAuthorsJson());
persistent.
setTitle(view.
getTitle());
persistent.
setSubtitle(view.
getSubtitle());
persistent.
setPublisher(view.
getPublisher());
persistent.
setDescription(view.
getDescription());
persistent.
setSubject(view.
getSubject());
persistent.
setPublishDate(view.
getPublishDate());
persistent.
setCloseDate(view.
getCloseDate());
persistent.
setInternalIdentifier(view.
getInternalIdentifier());
persistent.
setVisible(view.
isVisible());
if(view.
getCollection() !=
null)
{
RepositoryDocumentCollection col = DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
get(view.
getCollection().
getId());
col.
getId();
persistent.
setCollection((RepositoryDocumentCollectionImpl
) col
);
}
/**
* atualizar campos dos ficheiros já existentes
*/
if(view.
getRepositoryDocumentFiles() !=
null && view.
getRepositoryDocumentFiles().
size() > 0
)
{
for(RepositoryDocumentFileImpl ficheiroAtualizado : view.
getRepositoryDocumentFiles())
{
for(RepositoryDocumentFileImpl repoFileCandidate: persistent.
getRepositoryDocumentFiles() )
{
if(repoFileCandidate.
getId()==ficheiroAtualizado.
getId())
{
//ficheiro encontrado
repoFileCandidate.
setTitle(ficheiroAtualizado.
getTitle());
repoFileCandidate.
setDescription(ficheiroAtualizado.
getDescription());
repoFileCandidate.
setVisible(ficheiroAtualizado.
isVisible());
repoFileCandidate.
getRepositoryFileProxy().
getRepositoryFile().
setAccessControl(ficheiroAtualizado.
getRepositoryFileProxy().
getRepositoryFile().
getAccessControl());
if(!repoFileCandidate.
isVisible())
repoFileCandidate.
getRepositoryFileProxy().
getRepositoryFile().
setAccessControl(ResourceAccessControlEnum.
privateDomain.
getKey());
break;
}
}
}
}
if(uploadedFiles
!=
null)
{
//VERIFICACAO DE CONSISTENCIA DE FICHEIROS
for(FileUploaded uploadedF : uploadedFiles.
getUploadedFiles())
{
if(uploadedF.
getTmpName() ==
null || uploadedF.
getTmpName().
trim().
length() == 0
)
throw new ServiceException
("Ficheiro não definido: " + uploadedF.
getTitle());
}
RepositoryService repositoryService =
new RepositoryService
();
for(FileUploaded uploadedF : uploadedFiles.
getUploadedFiles())
{
if(uploadedF.
getAccessControl() ==
null)
uploadedF.
setAccessControl(ResourceAccessControlEnum.
publicDomain.
getKey());
ResourceAccessControlEnum controloAcesso = ResourceAccessControlEnum.
parse(uploadedF.
getAccessControl());
RepositoryDocumentFileImpl repoFile =
null;
1.5.0/docs/api/java/lang/String.html">String repositoryStream = uploadedF.
getRepositoryStream();
if(repositoryStream
!=
null)
{
for(RepositoryDocumentFileImpl repoFileCandidate: persistent.
getRepositoryDocumentFiles() )
{
if(repoFileCandidate.
getRepositoryFileProxy().
getRepositoryStream().
equals(repositoryStream
))
{
repoFile = repoFileCandidate
;
break;
}
}
if(repoFile ==
null)
throw new AccessDeniedException
("Trying to access to a repoFile not Allowded");
repositoryService.
updateRepositoryFile(
repositoryStream,
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())),
uploadedF.
getContentType(),
uploadedF.
getExtension(),
(int)uploadedF.
getFileSize(),
uploadedF.
getFileName(),
"Institutional Repository Document File",
controloAcesso
);
}
else
{
if(uploadedF.
getTmpName().
startsWith("http://") || uploadedF.
getTmpName().
startsWith("ftp://") || uploadedF.
getTmpName().
startsWith("https://"))
{
uploadedF.
setVisible(true);
FileUploaded dowloadedF = HttpServices.
downloadUrl(uploadedF.
getTmpName());
uploadedF.
setFileSize(dowloadedF.
getFileSize());
uploadedF.
setFileName(dowloadedF.
getFileName());
uploadedF.
setExtension(dowloadedF.
getExtension());
uploadedF.
setContentType(dowloadedF.
getContentType());
uploadedF.
setTmpName(dowloadedF.
getTmpName());
}
else if(!new java.
io.
1.5.0/docs/api/java/io/File.html">File(Globals.
TMP_DIR +
"/" + uploadedF.
getTmpName()).
exists())
{
throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("Ficheiro com o identificador: " + uploadedF.
getTmpName() +
" não foi encontrado");
}
repositoryStream = repositoryService.
storeRepositoryFile(
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())),
uploadedF.
getContentType(),
uploadedF.
getExtension(),
(int)uploadedF.
getFileSize(),
uploadedF.
getFileName(),
"Institutional Repository Document File",
controloAcesso,
new RepositoryDocumentsSource
(),
userSession.
getUser());
Set
<RepositoryDocumentFileImpl
> files = persistent.
getRepositoryDocumentFiles();
if(files ==
null)
{
files =
new HashSet
<RepositoryDocumentFileImpl
>();
persistent.
setRepositoryDocumentFiles(files
);
}
repoFile =
new RepositoryDocumentFileImpl
();
DaoFactory.
getRepositoryDocumentFileDaoImpl().
save(repoFile
);
files.
add(repoFile
);
RepositoryFileProxy repositoryFileProxy =
new RepositoryFileProxy
();
repositoryFileProxy.
setRepositoryStream(repositoryStream
);
repoFile.
setRepositoryFileProxy(repositoryFileProxy
);
}
repoFile.
setVisible(uploadedF.
isVisible());
if(!repoFile.
isVisible())
repoFile.
getRepositoryFileProxy().
getRepositoryFile().
setAccessControl(ResourceAccessControlEnum.
privateDomain.
getKey());
repoFile.
setTitle(uploadedF.
getTitle());
repoFile.
setDescription(uploadedF.
getDescription());
}
}
1.5.0/docs/api/java/lang/System.html">System.
out.
println(view.
toJson());
return persistent.
toJsonObject();
}
private void addHistoryLine
(UserSession userSession, RepositoryDocument persistent,
1.5.0/docs/api/java/lang/String.html">String line
) {
1.5.0/docs/api/java/lang/String.html">String history = persistent.
getHistoryEdit();
if(history ==
null)
history =
"";
else
history = history +
";\n";
history = history + line
;
persistent.
setHistoryEdit(history
);
}
public JSONArray loadCollectionsOrderedAsTree
() throws JSONException,
1.5.0/docs/api/java/io/IOException.html">IOException {
ArrayList
<RepositoryDocumentCollectionImpl
> collections =
new ArrayList
<RepositoryDocumentCollectionImpl
>();
List
<RepositoryDocumentCollection
> collectionsRoots = DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
findRoots();
for(RepositoryDocumentCollection col : collectionsRoots
)
{
col.
getName();
collections.
add((RepositoryDocumentCollectionImpl
) col
);
collections.
addAll(loadChildsOrderedAsTree
(col
));
}
return RepositoryDocumentCollectionImpl.
toJsonArraySimpleFields(collections
);
}
private ArrayList
<RepositoryDocumentCollectionImpl
> loadChildsOrderedAsTree
(RepositoryDocumentCollection rootCol
)
{
ArrayList
<RepositoryDocumentCollectionImpl
> collections =
new ArrayList
<RepositoryDocumentCollectionImpl
>();
for(RepositoryDocumentCollection col : rootCol.
getChilds())
{
col.
getName();
collections.
add((RepositoryDocumentCollectionImpl
) col
);
collections.
addAll(loadChildsOrderedAsTree
(col
));
}
return collections
;
}
public JSONObject addRepositoryInterface
(UserSession userSession
) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException, AccessDeniedException
{
RepositoryDocumentInterfaceImpl repositoryDocumentInterface = DomainObjectFactory.
createRepositoryDocumentInterfaceImpl();
repositoryDocumentInterface.
setVisible(false);
DaoFactory.
getRepositoryDocumentInterfaceDaoImpl().
save(repositoryDocumentInterface
);
return repositoryDocumentInterface.
toJsonObject();
}
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, JSONException, AccessDeniedException
{
RepositoryDocumentInterfaceImpl repositoryDocumentInterface =
RepositoryDocumentInterfaceImpl.
loadFromJson(jsonObject
);
RepositoryDocumentInterfaceImpl persistent =
(RepositoryDocumentInterfaceImpl
) DaoFactory.
getRepositoryDocumentInterfaceDaoImpl().
get(repositoryDocumentInterface.
getId());
persistent.
setVisible(repositoryDocumentInterface.
isVisible());
persistent.
setAdminDescription(repositoryDocumentInterface.
getAdminDescription());
persistent.
setSlug(repositoryDocumentInterface.
getSlug());
return persistent.
toJsonObject();
}
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, JSONException, AccessDeniedException
{
RepositoryDocumentInterfaceImpl persistent =
(RepositoryDocumentInterfaceImpl
) DaoFactory.
getRepositoryDocumentInterfaceDaoImpl().
get(id
);
DaoFactory.
getRepositoryDocumentInterfaceDaoImpl().
delete(persistent
);
}
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, JSONException, AccessDeniedException, ServiceException
{
RepositoryInterface repositoryInterface = RepositoryInterface.
loadFromJson(dataJson
);
for(InterfaceRow row: repositoryInterface.
getRows())
{
for(InterfaceColumn col : row.
getColumns())
{
for(InterfaceBlock block: col.
getBlocks())
{
if(block.
getCollectionIds() ==
null || block.
getCollectionIds().
size() == 0
)
{
throw new ServiceException
("Existem blocos sem colecção associada, corrija a situação por favor, tem de clicar no + para adicionar após escolher colecção");
}
}
}
}
RepositoryDocumentInterfaceImpl persistent =
(RepositoryDocumentInterfaceImpl
) DaoFactory.
getRepositoryDocumentInterfaceDaoImpl().
get(id
);
persistent.
setRepositoryInterface(repositoryInterface
);
}
public void addManagerToCollection
(long collectionId,
long managerId, UserSession sess
)
{
RepositoryDocumentCollection col = DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
get(collectionId
);
User u = DaoFactory.
getUserDaoImpl().
get(managerId
);
col.
getCollectionManagers().
add((UserImpl
) u
);
}
public void removeManagerInCollection
(long collectionId,
long managerId, UserSession sess
)
{
RepositoryDocumentCollection col = DaoFactory.
getRepositoryDocumentCollectionDaoImpl().
get(collectionId
);
for(User user : col.
getCollectionManagers())
{
if(user.
getId() == managerId
)
{
col.
getCollectionManagers().
remove(user
);
break;
}
}
}
public static void main
(1.5.0/docs/api/java/lang/String.html">String[] args
) throws JSONException,
1.5.0/docs/api/java/io/IOException.html">IOException
{
AbstractDao.
getCurrentSession().
beginTransaction();
JSONArray array =
new RepositoryDocumentService
().
loadCollectionsOrderedAsTree();
1.5.0/docs/api/java/lang/System.html">System.
out.
println(array.
toString());
AbstractDao.
getCurrentSession().
getTransaction().
commit();
}
}