--- /dev/null
+package com.pentila.entSavoie.cdt.util;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.portlet.ResourceRequest;
+
+import com.liferay.portal.kernel.exception.PortalException;
+import com.liferay.portal.kernel.exception.SystemException;
+import com.liferay.portal.kernel.json.JSONArray;
+import com.liferay.portal.kernel.json.JSONFactoryUtil;
+import com.liferay.portal.kernel.json.JSONObject;
+import com.liferay.portal.kernel.log.Log;
+import com.liferay.portal.kernel.log.LogFactoryUtil;
+import com.liferay.portal.kernel.util.HttpUtil;
+import com.liferay.portal.kernel.util.ObjectValuePair;
+import com.liferay.portal.kernel.util.ParamUtil;
+import com.liferay.portal.kernel.util.WebKeys;
+import com.liferay.portal.model.CompanyConstants;
+import com.liferay.portal.model.User;
+import com.liferay.portal.theme.ThemeDisplay;
+import com.liferay.portal.util.PortalUtil;
+import com.liferay.portlet.documentlibrary.DuplicateDirectoryException;
+import com.liferay.portlet.documentlibrary.NoSuchDirectoryException;
+import com.liferay.portlet.documentlibrary.store.DLStoreUtil;
+import com.pentila.entSavoie.cahierDeTexte.util.CDTAttachConstants;
+import com.pentila.entSavoie.cdt.model.CDTSession;
+import com.pentila.entSavoie.cdt.model.Homework;
+import com.pentila.entSavoie.cdt.service.CDTSessionLocalServiceUtil;
+import com.pentila.entSavoie.cdt.service.HomeworkLocalServiceUtil;
+import com.pentila.entSavoie.cdt.util.bean.AttachFile;
+import com.pentila.entSavoie.utils.JSPPortletUtil;
+
+public class AttachFileUtil {
+
+ private static Log logger = LogFactoryUtil.getLog(AttachFileUtil.class);
+
+ /**
+ * Get all attach file names for a given session or homework
+ * @param companyId
+ * @param sessionId
+ * @param homeworkId
+ * @return
+ * @throws PortalException
+ * @throws SystemException
+ */
+ public static List<AttachFile> getAttachFilesNames(ThemeDisplay themeDisplay, long companyId, long sessionId, long homeworkId) {
+
+ List<AttachFile> attachFiles = new ArrayList<AttachFile>();
+
+ if (sessionId == 0 && homeworkId == 0) {
+ logger.error("Error : attached files must be linked to a sessionId or a homeworkId");
+ return attachFiles;
+ }
+ if (sessionId != 0 && homeworkId != 0) {
+ logger.error("Error : attached files must be linked to either a sessionId or a homeworkId");
+ return attachFiles;
+ }
+
+ String dirName = CDTAttachConstants.ATTACH_FILE_PATH;
+ if (sessionId != 0) {
+ dirName += CDTAttachConstants.ATTACH_FILE_PATH_SESSIONS + sessionId;
+ } else {
+ dirName += CDTAttachConstants.ATTACH_FILE_PATH_HOMEWORKS + homeworkId;
+ }
+
+ try {
+ String[] fileNames = DLStoreUtil.getFileNames(companyId, CompanyConstants.SYSTEM, dirName);
+ for(String aFileName : fileNames){
+ AttachFile attachFileFromFileName = new AttachFile(themeDisplay, aFileName, companyId, sessionId, homeworkId);
+ attachFiles.add(attachFileFromFileName);
+ }
+ }
+ catch (Exception e) {
+ logger.error("Error when listing attach files for sesion or homework", e);
+ }
+
+ return attachFiles;
+ }
+
+ /**
+ * Erase the target attach file folder then copy all source attach files to new target attache file folder
+ * If there is no attach file in source, it will erase the source folder
+ * throws NoSuchDirectoryException if there is no directory to copy
+ * @param companyId
+ * @param sessionSource
+ * @param sessionTarget
+ * @throws SystemException
+ * @throws PortalException
+ */
+ public static int copyAndEraseAttachFileFromSessionToAnotherSession(long companyId, CDTSession sessionSource, CDTSession sessionTarget) throws PortalException, SystemException{
+ long repositoryId = CompanyConstants.SYSTEM;
+ String sourceDirName = CDTAttachConstants.ATTACH_FILE_PATH +
+ CDTAttachConstants.ATTACH_FILE_PATH_SESSIONS +
+ sessionSource.getSessionId();
+
+ String targetDirName = CDTAttachConstants.ATTACH_FILE_PATH +
+ CDTAttachConstants.ATTACH_FILE_PATH_SESSIONS +
+ sessionTarget.getSessionId();
+
+ if(sessionTarget.getHasAttachFile()){
+ DLStoreUtil.deleteDirectory(companyId, CompanyConstants.SYSTEM, targetDirName);
+ }
+
+ String[] sourcesAttachFilesPath = DLStoreUtil.getFileNames(companyId, repositoryId, sourceDirName);
+
+ if(sourcesAttachFilesPath == null || sourcesAttachFilesPath.length == 0){
+ return 0;
+ }
+ for(String aSourceFilePath : sourcesAttachFilesPath){
+ String[] sourceFilePathPart = aSourceFilePath.split("/");
+ DLStoreUtil.addFile(companyId,
+ repositoryId,
+ targetDirName + "/" + sourceFilePathPart[sourceFilePathPart.length-1],
+ true,
+ DLStoreUtil.getFileAsBytes(companyId, repositoryId,sourceDirName + "/" + sourceFilePathPart[sourceFilePathPart.length-1]));
+ }
+
+ return sourcesAttachFilesPath.length;
+ }
+
+ /**
+ * Copy all attache file from homeworkSource to homeworkTarget
+ * throws NoSuchDirectoryException if there is no directory to copy
+ * @param companyId
+ * @param homeworkSourceId
+ * @param homeworkTargetId
+ * @throws PortalException
+ * @throws SystemException
+ */
+ public static int copyAttachFileFromHomeworkToAnother(long companyId, long homeworkSourceId, long homeworkTargetId)
+ throws PortalException, SystemException {
+ String sourceDirName = CDTAttachConstants.ATTACH_FILE_PATH +
+ CDTAttachConstants.ATTACH_FILE_PATH_HOMEWORKS +
+ homeworkSourceId;
+
+ String targetDirName = CDTAttachConstants.ATTACH_FILE_PATH +
+ CDTAttachConstants.ATTACH_FILE_PATH_HOMEWORKS +
+ homeworkTargetId;
+ long repositoryId = CompanyConstants.SYSTEM;
+ String[] sourcesAttachFilesPath = DLStoreUtil.getFileNames(companyId, repositoryId, sourceDirName);
+ if(sourcesAttachFilesPath == null || sourcesAttachFilesPath.length == 0){
+ return 0;
+ }
+ for(String filePath : sourcesAttachFilesPath){
+ String[] filePathPart = filePath.split("/");
+ DLStoreUtil.addFile(companyId,
+ repositoryId,
+ targetDirName + "/" + filePathPart[filePathPart.length-1],
+ true,
+ DLStoreUtil.getFileAsBytes(companyId, repositoryId,sourceDirName + "/" + filePathPart[filePathPart.length-1]));
+ }
+ return sourcesAttachFilesPath.length;
+ }
+
+ /**
+ * Add 1 or more attach files to a session or a homework
+ * @param actionRequest
+ * @param actionResponse
+ * @throws PortalException
+ * @throws SystemException
+ */
+ public static JSONArray addAttachments(ThemeDisplay themeDisplay, User currentUser, long sessionId,
+ long homeworkId, Long[] attachFilesIds) {
+ long repositoryId = CompanyConstants.SYSTEM;
+
+ String dirName = CDTAttachConstants.ATTACH_FILE_PATH;
+ if (sessionId != 0) {
+ dirName += CDTAttachConstants.ATTACH_FILE_PATH_SESSIONS + sessionId;
+ } else {
+ dirName += CDTAttachConstants.ATTACH_FILE_PATH_HOMEWORKS + homeworkId;
+ }
+
+ final List<AttachFile> attachments = new ArrayList<AttachFile>();
+
+ if (attachFilesIds.length != 0) {
+
+ // Create directory on FS for given session or homework
+ try {
+ DLStoreUtil.addDirectory(currentUser.getCompanyId(), repositoryId, dirName);
+ } catch (DuplicateDirectoryException dde) {
+ } catch (Exception e) {
+ logger.error("Error when adding attach file "+dirName, e);
+ }
+
+ // Add file
+ try {
+ // => let's set the attach file boolean to true in either CDTSession or Homework
+ String[] existingAttachFiles = null;
+ try{
+ existingAttachFiles = DLStoreUtil.getFileNames(currentUser.getCompanyId(), repositoryId, dirName);
+ } catch (NoSuchDirectoryException e){
+ logger.debug("No more directory for session, there is no attach file",e);
+ }
+
+ // Loop over the attach files and add them on the file system
+ for (int j=0; j<attachFilesIds.length; j++) {
+
+ long fileId = attachFilesIds[j];
+ ObjectValuePair<String, byte[]> ovp = JSPPortletUtil.getFileAsOVP(currentUser.getCompanyId(), fileId, "");
+ String fileName = ovp.getKey();
+ byte[] bytes = ovp.getValue();
+ DLStoreUtil.addFile(currentUser.getCompanyId(), repositoryId, dirName + "/" + fileName, true, bytes);
+
+ // Generate the return JSON object
+ attachments.add(
+ new AttachFile(themeDisplay,
+ dirName + "/" + fileName,
+ currentUser.getCompanyId(),
+ sessionId,
+ homeworkId));
+ }
+
+ if (existingAttachFiles == null || existingAttachFiles.length == 0) {
+ setHasAttachFile(sessionId, homeworkId,true);
+ }
+ }
+ catch (Exception e) {
+ logger.error("Error when adding attach file "+dirName , e);
+ }
+ }
+ return JSONProxy.attachFilesJson(attachments);
+ }
+
+
+
+ /**
+ * delete an attach file
+ * @param currentUser the user
+ * @param sessionId the session ID concerned
+ * @param homeworkId the homework ID concerned
+ * @param fileName file to delete
+ * @return JSON which describe succes or error must be return directly
+ * @throws PortalException
+ * @throws SystemException
+ */
+ public static JSONObject deleteAttachment(User currentUser, long sessionId, long homeworkId, String fileName){
+ long repositoryId = CompanyConstants.SYSTEM;
+
+ String dirName = CDTAttachConstants.ATTACH_FILE_PATH;
+ if (sessionId != 0) {
+ dirName += CDTAttachConstants.ATTACH_FILE_PATH_SESSIONS + sessionId;
+ } else {
+ dirName += CDTAttachConstants.ATTACH_FILE_PATH_HOMEWORKS + homeworkId;
+ }
+
+ try {
+ DLStoreUtil.deleteFile(currentUser.getCompanyId(), repositoryId, dirName + "/" + fileName);
+
+ // Now check if there are remaining attach files for this session or homework
+ // If not => set the hasAttachFiles boolean to false in CDTSession or Homework object
+ String[] existingAttachFiles = null;
+ try{
+ existingAttachFiles = DLStoreUtil.getFileNames(currentUser.getCompanyId(), repositoryId, dirName);
+ }
+ catch(NoSuchDirectoryException e){
+ logger.debug("No more directory for session, there is no attach file",e);
+ }
+
+ if (existingAttachFiles == null || existingAttachFiles.length == 0) {
+ AttachFileUtil.setHasAttachFile(sessionId, homeworkId, false);
+ }
+ }
+ catch (PortalException e) {
+ logger.error("Error when deleting attach file " + fileName, e);
+ return JSONProxy.getJSONReturnInErrorCase("Error when deleting attach file " + fileName);
+ }
+ catch (SystemException e) {
+ logger.error("Error when deleting attach file " + fileName, e);
+ return JSONProxy.getJSONReturnInErrorCase("Error when deleting attach file " + fileName);
+ }
+
+ return JSONFactoryUtil.createJSONObject().put("success", true);
+ }
+
+
+ /**
+ * Delete all attachment in session
+ * @param currentUser
+ * @param sessionId tje is of the session
+ * @return
+ * @throws SystemException
+ * @throws PortalException
+ */
+ public static void deleteAllSessionAttachment(User currentUser, CDTSession session)
+ throws PortalException, SystemException {
+ long repositoryId = CompanyConstants.SYSTEM;
+
+ String dirName = CDTAttachConstants.ATTACH_FILE_PATH +
+ CDTAttachConstants.ATTACH_FILE_PATH_SESSIONS + session.getSessionId();
+ try{
+ DLStoreUtil.deleteDirectory(currentUser.getCompanyId(), repositoryId, dirName);
+ }
+ catch(NoSuchDirectoryException e){
+ logger.debug("No more directory for session, there is no attach file",e);
+ }
+
+ session.setHasAttachFile(false);
+ CDTSessionLocalServiceUtil.updateCDTSession(session);
+ }
+
+
+ /**
+ * Delete all attachment in homework
+ * @param currentUser
+ * @param sessionId tje is of the session
+ * @return
+ * @throws SystemException
+ * @throws PortalException
+ */
+ public static void deleteAllHomeworkAttachment(User currentUser, Homework homework)
+ throws PortalException, SystemException {
+ long repositoryId = CompanyConstants.SYSTEM;
+
+ String dirName = CDTAttachConstants.ATTACH_FILE_PATH +
+ CDTAttachConstants.ATTACH_FILE_PATH_HOMEWORKS + homework.getHomeworkId();
+
+ try{
+ DLStoreUtil.deleteDirectory(currentUser.getCompanyId(), repositoryId, dirName);
+ }
+ catch(NoSuchDirectoryException e){
+ logger.debug("No more directory for session, there is no attach file",e);
+ }
+
+ homework.setHasAttachFile(false);
+ HomeworkLocalServiceUtil.updateHomework(homework);
+ }
+
+ /**
+ * Set value to hasAttachFilevalue of session and/or homework
+ * @param sessionId session modified
+ * @param homeworkId homework modified
+ * @param valueToSet boolean which is the valeur to set to has attache file
+ * @throws PortalException
+ * @throws SystemException
+ */
+ private static void setHasAttachFile(long sessionId, long homeworkId, boolean valueToSet)
+ throws PortalException, SystemException {
+ if (sessionId != 0) {
+ CDTSession cdtSession = CDTSessionLocalServiceUtil.getCDTSession(sessionId);
+ cdtSession.setHasAttachFile(valueToSet);
+ CDTSessionLocalServiceUtil.updateCDTSession(cdtSession);
+ } else if (homeworkId != 0){
+ Homework homework = HomeworkLocalServiceUtil.getHomework(homeworkId);
+ homework.setHasAttachFile(valueToSet);
+ HomeworkLocalServiceUtil.updateHomework(homework);
+ }
+ }
+
+ /**
+ * Download an attach file, from either a CDTSession or a homework
+ * @param actionRequest
+ * @return a JSON object as a string
+ * @throws PortalException
+ * @throws SystemException
+ */
+ public static JSONObject downloadAttachFile(ResourceRequest resourceRequest) throws PortalException, SystemException {
+
+ final long companyId = PortalUtil.getCompanyId(resourceRequest);
+ final String fileId = ParamUtil.getString(resourceRequest, "fileId");
+ final String fileName = ParamUtil.getString(resourceRequest, "fileName");
+ final boolean isHomework = ParamUtil.getBoolean(resourceRequest, "isHomework", false);
+
+ String sessionOrHomeworkId = fileId.substring(15, fileId.lastIndexOf("/"));
+
+ String urlParameter = "";
+ if (isHomework) {
+ urlParameter = "homeworkId=" + sessionOrHomeworkId;
+ } else {
+ urlParameter = "sessionId=" + sessionOrHomeworkId;
+ }
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
+
+ result.put("success", true);
+ result.put("href", themeDisplay.getPathMain() + AttachFile.ATTACHEMENT_DL_STRUT_ACTION_PATH + "?" + urlParameter +"&companyId="+ companyId +"&attachment="+HttpUtil.encodeURL(fileName));
+
+ return result;
+
+ }
+
+/**
+ *
+ * @param themeDisplay
+ * @param companyId
+ * @param allHomeworkForSession
+ * @return
+ */
+ public static Map<Long, List<AttachFile>> getAttachFilesNamesFromHomeworks(
+ ThemeDisplay themeDisplay, long companyId, List<Homework> allHomeworkForSession) {
+
+ Map<Long, List<AttachFile>> mapHomeworkIdAttachFiles = new HashMap<Long, List<AttachFile>>();
+
+ for(Homework anHomework : allHomeworkForSession){
+ if(anHomework.getHasAttachFile()){
+ mapHomeworkIdAttachFiles.put(anHomework.getHomeworkId(),
+ AttachFileUtil.getAttachFilesNames(themeDisplay, companyId, 0, anHomework.getHomeworkId()));
+ }
+ else{
+ mapHomeworkIdAttachFiles.put(anHomework.getHomeworkId(), new ArrayList<AttachFile>());
+ }
+
+ }
+ return mapHomeworkIdAttachFiles;
+ }
+
+}