+ @Override
+ public Invitation findInvite(String code) {
+ if (code == null)
+ return null;
+ return dao.findInvite(code);
+ }
+
+ @Override
+ public void createLdapUser(String username, String firstname, String lastname, String email, String password) {
+ LDAPConnection lc = new LDAPConnection();
+ LDAPAttributeSet attributeSet = new LDAPAttributeSet();
+ attributeSet.add(new LDAPAttribute("objectClass", getConfiguration().getStringArray("objectClass")));
+ attributeSet.add(new LDAPAttribute("uid", username));
+ attributeSet.add(new LDAPAttribute("cn", new String[]{firstname + " " + lastname}));
+ attributeSet.add(new LDAPAttribute("sn", lastname));
+ attributeSet.add(new LDAPAttribute("givenName", firstname));
+ attributeSet.add(new LDAPAttribute("mail", email));
+ attributeSet.add(new LDAPAttribute("userPassword", password));
+ String dn = "uid=" + username + "," + getConfiguration().getString("baseDn");
+ LDAPEntry newEntry = new LDAPEntry(dn, attributeSet);
+ try {
+ lc.connect(getConfiguration().getString("ldapHost"), LDAPConnection.DEFAULT_PORT);
+ lc.bind(LDAPConnection.LDAP_V3, getConfiguration().getString("bindDn"),
+ getConfiguration().getString("bindPassword").getBytes("UTF8"));
+ lc.add(newEntry);
+ logger.info("Successfully added LDAP account: " + dn);
+ lc.disconnect();
+ } catch(LDAPException e) {
+ throw new RuntimeException(e);
+ } catch(UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
+
+ }
+
+ @Override
+ public UserClass upgradeUserClass(String username, String code) throws ObjectNotFoundException, InvitationUsedException {
+ User user = findUser(username);
+ if (user == null)
+ throw new ObjectNotFoundException("The user was not found");
+ Invitation invite = findInvite(code);
+ if (invite.getUser() != null)
+ throw new InvitationUsedException("This code has already been used");
+ invite.setUser(user);
+ UserClass couponClass = getCouponUserClass();
+ user.setUserClass(couponClass);
+ return couponClass;
+ }
+
+ @Override
+ public UserClass getCouponUserClass() {
+ return dao.findCouponUserClass();
+ }
+
+ /**
+ * Set the provided readForAll as the new readforAll value of the specified
+ * folder and sub-folders.
+ *
+ * @param user
+ * @param folder
+ * @param readForAll
+ * @throws ObjectNotFoundException
+ *
+ */
+ private void setFolderReadForAll(User user, Folder folder, Boolean readForAll){
+ if (readForAll != null && user.equals(folder.getOwner())){
+ folder.setReadForAll(readForAll);
+ dao.update(folder);
+ for (FileHeader file : folder.getFiles())
+ file.setReadForAll(readForAll);
+ if(readForAll)
+ //only update subfolders when readforall is true. otherwise all sub-folders stay untouched
+ for (Folder sub : folder.getSubfolders())
+ setFolderReadForAll(user, sub, readForAll);
+
+ }
+
+ }
+
+ /**
+ * Update the userLogin with the values from the supplied object.
+ */
+
+ public void addUserLogin(UserLogin userLogin) {
+ dao.update(userLogin);
+
+ }
+
+ /**
+ * Retrieves the current session user login and the user's last login
+ *
+ * @param userId
+ * @return a list of last two user logins
+ * @throws ObjectNotFoundException
+ */
+
+ public List<UserLogin> getLastUserLogins(Long userId) throws ObjectNotFoundException{
+ List<UserLogin> userLoginResults = new ArrayList<UserLogin>();
+ userLoginResults = dao.getLoginsForUser(userId);
+ if(userLoginResults.size() == 0)
+ throw new ObjectNotFoundException("No userlogin found for the user");
+ //if the user logins for the first time lastLoginDate = currentLoginDate
+ if(userLoginResults.size()==1)
+ userLoginResults.add(userLoginResults.get(0));
+ return userLoginResults;
+ }
+
+
+ @Override
+ public void postFileToSolr(CommonsHttpSolrServer solr, Long id) {
+ try {
+ FileHeader file = dao.getFileForIndexing(id);
+ FileBody body = file.getCurrentBody();
+ String mime = body.getMimeType();
+ boolean multipart = true;
+ if (!mime.equals("application/pdf")
+ && !mime.equals("text/plain")
+ && !mime.equals("text/html")
+ && !mime.endsWith("msword")
+ && !mime.endsWith("ms-excel")
+ && !mime.endsWith("powerpoint")
+ || (body.getFileSize() > getConfiguration().getLong("solrDocumentUploadLimitInKB") * 1024))
+ multipart = false;
+
+ if (!multipart)
+ sendMetaDataOnly(solr, file);
+ else {
+ ContentStreamUpdateRequest solrRequest = new ContentStreamUpdateRequest(getConfiguration().getString("solr.rich.update.path"));
+ solrRequest.setParam("literal.id", file.getId().toString());
+ solrRequest.setParam("literal.name", file.getName());
+ for (FileTag t : file.getFileTags()) {
+ solrRequest.getParams().add("literal.tag", t.getTag());
+ }
+ for (Permission p : file.getPermissions()) {
+ if (p.getRead()) {
+ if (p.getUser() != null)
+ solrRequest.getParams().add("literal.ureaders", p.getUser().getId().toString());
+ else if (p.getGroup() != null)
+ solrRequest.getParams().add("literal.greaders", p.getGroup().getId().toString());
+ }
+ }
+ solrRequest.setParam("literal.owner", file.getOwner().getId().toString());
+ solrRequest.setParam("literal.public", String.valueOf(file.isReadForAll()));
+ File fsFile = new File(body.getStoredFilePath());
+ solrRequest.addFile(fsFile);
+ try {
+ solr.request(solrRequest);
+ }
+ catch (SolrException e) {
+ logger.warn("File " + id + " failed with SolrException: " + e.getLocalizedMessage() + ". Retrying without the file");
+ //Let 's try without the file
+ sendMetaDataOnly(solr, file);
+ }
+ catch (NullPointerException e) {
+ logger.warn("File " + id + " failed with NullPointerException: " + e.getLocalizedMessage() + ". Retrying without the file");
+ //Let 's try without the file
+ sendMetaDataOnly(solr, file);
+ }
+ catch (SolrServerException e) {
+ logger.warn("File " + id + " failed with SolrServerException: " + e.getLocalizedMessage() + ". Retrying without the file");
+ //Let 's try without the file
+ sendMetaDataOnly(solr, file);
+ }
+ }
+ } catch (MalformedURLException e) {
+ throw new EJBException(e);
+ } catch (ObjectNotFoundException e) {
+ logger.error("Indexing of file id " + id + " failed.", e);
+ } catch (SolrServerException e) {
+ throw new EJBException(e);
+ } catch (IOException e) {
+ throw new EJBException(e);
+ }
+ }
+
+ private void sendMetaDataOnly(CommonsHttpSolrServer solr, FileHeader file) throws SolrServerException, IOException {
+ SolrInputDocument solrDoc = new SolrInputDocument();
+ solrDoc.addField("id", file.getId().toString());
+ solrDoc.addField("name", file.getName());
+ for (FileTag t : file.getFileTags()) {
+ solrDoc.addField("tag", t.getTag());
+ }
+ for (Permission p : file.getPermissions()) {
+ if (p.getRead()) {
+ if (p.getUser() != null)
+ solrDoc.addField("ureaders", p.getUser().getId());
+ else if (p.getGroup() != null)
+ solrDoc.addField("greaders", p.getGroup().getId());
+ }
+ }
+ solrDoc.addField("owner", file.getOwner().getId());
+ solrDoc.addField("public", file.isReadForAll());
+ solr.add(solrDoc);
+ }
+
+ private String tokenizeFilename(String filename){
+ StringBuffer result = new StringBuffer();
+ StringTokenizer tokenizer = new StringTokenizer(filename,"._");
+ while(tokenizer.hasMoreTokens()){
+ result.append(tokenizer.nextToken());
+ result.append(" ");
+ }
+ result.append(filename);
+ return result.toString();
+ }
+
+ private String normalizeSearchQuery(String query) {
+ if (query.contains("*"))
+ return query.toLowerCase().replace('ά', 'α').replace('έ', 'ε').replace('ί', 'ι').replace('ή', 'η').replace('ύ', 'υ')
+ .replace('ό', 'ο').replace('ς', 'σ').replace('ώ', 'ω').replace('ϊ', 'ι').replace('ϋ', 'υ');
+ else
+ return query;
+ }
+
+ private String escapeCharacters(String text) {
+ return text.replaceAll(":", "\\\\:");
+ }
+
+ /*** NEW METHODS IN ORDER TO AVOID LAZY loading exception in json render
+ ****/
+ @Override
+ public Folder expandFolder(Folder folder) throws ObjectNotFoundException{
+ Folder result = dao.getEntityById(Folder.class, folder.getId());
+ result.getSubfolders().size();
+ result.getFiles().size();
+ result.getPermissions().size();
+ return result;
+}
+
+ @Override
+ public FileHeader expandFile(FileHeader folder) throws ObjectNotFoundException{
+ FileHeader result = dao.getEntityById(FileHeader.class, folder.getId());
+ result.getFolder();
+ result.getPermissions().size();
+ result.getFileTags().size();
+ return result;
+ }
+
+ @Override
+ public Group expandGroup(Group folder) throws ObjectNotFoundException{
+ Group result = dao.getEntityById(Group.class, folder.getId());
+ result.getMembers().size();
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see gr.ebs.gss.server.ejb.ExternalAPI#getUsersByUserNameLike(java.lang.String)
+ */
+ @Override
+ public User getUserByUserName(String username) {
+ User result = dao.getUserByUserName(username);
+ return result;
+ }
+
+ /*WEBDAV CREATE EMPTY FILE*/
+ @Override
+ public FileHeader createEmptyFile(Long userId, Long folderId, String name)
+ throws DuplicateNameException, ObjectNotFoundException, GSSIOException,
+ InsufficientPermissionsException, QuotaExceededException {
+ // Validate.
+ if (userId == null)
+ throw new ObjectNotFoundException("No user specified");
+ if (folderId == null)
+ throw new ObjectNotFoundException("No folder specified");
+ String contentType = DEFAULT_MIME_TYPE;
+ if (StringUtils.isEmpty(name))
+ throw new ObjectNotFoundException("No file name specified");
+ if (dao.existsFolderOrFile(folderId, name))
+ throw new DuplicateNameException("A folder or file with the name '" + name +
+ "' already exists at this level");
+
+ // Do the actual work.
+ Folder parent = null;
+ try {
+ parent = dao.getEntityById(Folder.class, folderId);
+ } catch (final ObjectNotFoundException onfe) {
+ // Supply a more accurate problem description.
+ throw new ObjectNotFoundException("Parent folder not found");
+ }
+ final User owner = dao.getEntityById(User.class, userId);
+ if (!parent.hasWritePermission(owner))
+ throw new InsufficientPermissionsException("You don't have the permissions to write to this folder");
+ final FileHeader file = new FileHeader();
+ file.setName(name);
+ parent.addFile(file);
+ // set file owner to folder owner
+ file.setOwner(parent.getOwner());
+ //set file's readForAll value according to parent folder readForAll value
+ file.setReadForAll(parent.isReadForAll());
+
+ final Date now = new Date();
+ final AuditInfo auditInfo = new AuditInfo();
+ auditInfo.setCreatedBy(owner);
+ auditInfo.setCreationDate(now);
+ auditInfo.setModifiedBy(owner);
+ auditInfo.setModificationDate(now);
+ file.setAuditInfo(auditInfo);
+ // TODO set the proper versioning flag on creation
+ file.setVersioned(false);
+
+ for (final Permission p : parent.getPermissions()) {
+ final Permission permission = new Permission();
+ permission.setGroup(p.getGroup());
+ permission.setUser(p.getUser());
+ permission.setRead(p.getRead());
+ permission.setWrite(p.getWrite());
+ permission.setModifyACL(p.getModifyACL());
+ file.addPermission(permission);
+ }
+ // Create the file body.
+ try {
+ createEmptyFileBody(name, contentType, 0, file, auditInfo);
+ } catch (FileNotFoundException e) {
+ throw new GSSIOException(e);
+ }
+ touchParentFolders(parent, owner, new Date());
+ dao.flush();
+ return file;
+ }
+
+ private void createEmptyFileBody(String name, String mimeType, long fileSize,
+ FileHeader header, AuditInfo auditInfo)
+ throws FileNotFoundException, QuotaExceededException, ObjectNotFoundException {
+
+ long currentTotalSize = 0;
+ if (!header.isVersioned() && header.getCurrentBody() != null && header.getBodies() != null)
+ currentTotalSize = header.getTotalSize();
+ Long quotaLeft = getQuotaLeft(header.getOwner().getId());
+
+
+ FileBody body = new FileBody();
+
+ // if no mime type or the generic mime type is defined by the client, then try to identify it from the filename extension
+ if (StringUtils.isEmpty(mimeType) || "application/octet-stream".equals(mimeType)
+ || "application/download".equals(mimeType) || "application/force-download".equals(mimeType)
+ || "octet/stream".equals(mimeType) || "application/unknown".equals(mimeType))
+ body.setMimeType(identifyMimeType(name));
+ else
+ body.setMimeType(mimeType);
+ body.setAuditInfo(auditInfo);
+ body.setFileSize(fileSize);
+ body.setOriginalFilename(name);
+ body.setStoredFilePath(generateRepositoryFilePath());
+ //CLEAR OLD VERSION IF FILE IS NOT VERSIONED AND GETS UPDATED
+ if(!header.isVersioned() && header.getCurrentBody() != null){
+ header.setCurrentBody(null);
+ if (header.getBodies() != null) {
+ Iterator<FileBody> it = header.getBodies().iterator();
+ while(it.hasNext()){
+ FileBody bo = it.next();
+ deleteActualFile(bo.getStoredFilePath());
+ it.remove();
+ dao.delete(bo);
+ }
+ }
+ }
+
+ dao.flush();
+ header.addBody(body);
+ header.setAuditInfo(auditInfo);
+
+ dao.create(body);
+ }
+ /*** WEBDAV LOCK **/
+ @Override
+ public FileLock getLockById(String id) {
+ return dao.getLockById(id);
+ }
+
+ @Override
+ public FileLock getLockByToken(String tokenId) {
+ return dao.getLockByToken(tokenId);
+ }
+
+ @Override
+ public void removeLock(FileLock lock) {
+ dao.removeLock(lock);
+ }
+
+ @Override
+ public FileLock saveOrUpdateLock(FileLock lock) {
+ return dao.saveOrUpdateLock(lock);
+ }
+
+ @Override
+ public WebDavNonce getWebDavNonce(String tokenId) {
+ return dao.getWebDavNonce(tokenId);
+ }
+
+ @Override
+ public void removeWebDavNonce(WebDavNonce nonce) {
+ dao.removeWebDavNonce(nonce);
+ }
+
+ @Override
+ public WebDavNonce saveOrUpdateWebDavNonce(WebDavNonce nonce) {
+ return dao.saveOrUpdateWebDavNonce(nonce);
+ }
+
+ /* (non-Javadoc)
+ * @see gr.ebs.gss.server.ejb.ExternalAPI#getUsersByUserNameLike(java.lang.String)
+ */
+ @Override
+ public UserDTO getUserByUserName(String username) {
+ User result = dao.getUserByUserName(username);
+ return result.getDTO();
+ }
+