Subversion Repositories linshare

[/] [branches/] [ui-work-linshare-0.9/] [src/] [main/] [java/] [org/] [linagora/] [linShare/] [view/] [tapestry/] [pages/] [share/] [Index.java] - Rev 480

Go to most recent revision | Compare with Previous | Blame | View Log

package org.linagora.linShare.view.tapestry.pages.share;
 
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
 
import org.apache.tapestry5.ajax.MultiZoneUpdate;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.linagora.linShare.core.Facade.DocumentFacade;
import org.linagora.linShare.core.Facade.ParameterFacade;
import org.linagora.linShare.core.Facade.RecipientFavouriteFacade;
import org.linagora.linShare.core.Facade.ShareFacade;
import org.linagora.linShare.core.Facade.UserFacade;
import org.linagora.linShare.core.domain.entities.MailContainer;
import org.linagora.linShare.core.domain.objects.SuccessesAndFailsItems;
import org.linagora.linShare.core.domain.vo.DocumentVo;
import org.linagora.linShare.core.domain.vo.ShareDocumentVo;
import org.linagora.linShare.core.domain.vo.UserVo;
import org.linagora.linShare.core.exception.BusinessException;
import org.linagora.linShare.core.utils.FileUtils;
import org.linagora.linShare.view.tapestry.beans.ShareSessionObjects;
import org.linagora.linShare.view.tapestry.enums.BusinessUserMessageType;
import org.linagora.linShare.view.tapestry.objects.BusinessUserMessage;
import org.linagora.linShare.view.tapestry.objects.MessageSeverity;
import org.linagora.linShare.view.tapestry.services.BusinessMessagesManagementService;
import org.linagora.linShare.view.tapestry.services.impl.MailCompletionService;
import org.linagora.linShare.view.tapestry.services.impl.MailContainerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class Index {
	private static final Logger logger = LoggerFactory.getLogger(Index.class);
 
	@SessionState
	@Property
	private ShareSessionObjects shareSessionObjects;
 
	@Property
	@Persist
	private List<String> recipients;
 
	@Property
	@Persist
	private List<DocumentVo> documents;
 
	@Property
	private DocumentVo document;
 
	@Property
	private String recipient;
 
	@Inject
	private UserFacade userFacade;
 
	@Inject
	private RecipientFavouriteFacade recipientFavouriteFacade;
 
	@SessionState
	private UserVo userVo;
 
	@InjectComponent
	private Zone recipientsZone;
 
	@InjectComponent
	private Zone documentsZone;
 
	@Property
	@Persist
	private Date dateExpirationShare;
 
	@Property
	@Persist
	private String textAreaValue;
 
	@Property
	@Persist
	private String textAreaSubjectValue;
 
	@Property
	private String recipientsSearch;
 
	@Inject
	private Request request; 
 
	@Inject
	private DocumentFacade documentFacade;
	@Inject
	private ShareFacade shareFacade;
 
    @Inject
    private BusinessMessagesManagementService messagesManagementService;
 
	@Inject
	private MailContainerBuilder mailContainerBuilder;
 
    @Inject
    private ParameterFacade parameterFacade;
 
    @InjectComponent
    private Form documentUploadForm;
 
    @InjectComponent
    private Form shareForm;
 
	@Property
	@Persist
    private UploadedFile documentUpload;
 
	@Inject
	private Messages messages;
 
    private static final long DEFAULT_MAX_FILE_SIZE = 52428800;
 
    private boolean reset;
 
	@SetupRender
	public void init() {
		if (recipients == null) {
			recipients = new ArrayList<String>();
		}
		for (UserVo recipientU : shareSessionObjects.getUsers()) {
			if (!recipients.contains(recipientU.getMail())) {
				recipients.add(recipientU.getMail());
			}
		}
		Collections.sort(recipients);
 
		if (documents == null) {
			documents = new ArrayList<DocumentVo>();
		}
		for (DocumentVo documentVo : shareSessionObjects.getDocuments()) {
			if (!documents.contains(documentVo)) {
				documents.add(documentVo);
			}
		}
	}
 
 
    public Object onSuccessFromShareForm() throws BusinessException {
		Calendar dateExpiry = null;
 
    	if (reset) {
    		clearShareForm();
    		return this;
    	}
 
    	if (shareForm.getHasErrors()) {
    		return this;
    	}
 
		if (dateExpirationShare != null) {
			dateExpiry = Calendar.getInstance();
			dateExpiry.setTime(dateExpirationShare);
		}
 
		SuccessesAndFailsItems<ShareDocumentVo> sharing = new SuccessesAndFailsItems<ShareDocumentVo>();
		try {
			MailContainer mailContainer = mailContainerBuilder.buildMailContainer(userVo, textAreaValue);
			mailContainer.setSubject(textAreaSubjectValue); //retrieve the subject of the mail defined by the user
			sharing = shareFacade.createSharingWithMailUsingRecipientsEmailAndExpiryDate(userVo, 
					documents, recipients, true, mailContainer, dateExpiry);
 
 
		} catch (BusinessException e1) {
			logger.error("Could not create sharing", e1);
			throw e1;
		}
 
 
		shareSessionObjects=new ShareSessionObjects();
		if (sharing.getFailsItem().size()>0) {
			shareSessionObjects.addError(messages.get("components.confirmSharePopup.fail"));
		} else {
			recipientFavouriteFacade.increment(userVo, recipients);
			shareSessionObjects.addMessage(messages.get("components.confirmSharePopup.success"));
			clearShareForm();
		}
 
		return org.linagora.linShare.view.tapestry.pages.files.Index.class;
 
	}
 
 
	private void clearShareForm() {
		documents.clear();
		recipients.clear();
		shareSessionObjects.getDocuments().clear();
		shareSessionObjects.getUsers().clear();
		textAreaSubjectValue=null;
		textAreaValue=null;
		dateExpirationShare=null;
	}
 
	public void onValidateFormFromShareForm() throws BusinessException {
    	if (reset) return;
 
		if (recipients == null || recipients.isEmpty()) {
			shareForm.recordError("Vous devez spécifier au moins un destinataire");
		}
		if (documents == null || documents.isEmpty()) {
			shareForm.recordError("Vous devez spécifier au moins un document à partager");
		}
	}
 
    public void onValidateFormFromDocumentUploadForm() {
    	if (documentUpload == null) {
    		documentUploadForm.recordError("Spécifiez un fichier");
    	}
    }
 
    void onSelectedFromReset()  { reset = true; }
 
    public Object onSuccessFromDocumentUploadForm() throws BusinessException {
 
        if (documentUpload != null) {
        	if (documentUpload.getSize() > getMaxFileSize()) {
        		messagesManagementService.notify(new BusinessUserMessage(BusinessUserMessageType.UPLOAD_WITH_FILE_TOO_LARGE,
                        MessageSeverity.ERROR, 
                        documentUpload.getFileName(), 
                        FileUtils.getFriendlySize(documentUpload.getSize(),messages),
                        FileUtils.getFriendlySize(getMaxFileSize(),messages)));
        	}
        	if (documentUpload.getSize() > getUserFreeSpace()) {
        		messagesManagementService.notify(new BusinessUserMessage(BusinessUserMessageType.UPLOAD_NOT_ENOUGH_SPACE,
                        MessageSeverity.ERROR, 
                        documentUpload.getFileName(), 
                        FileUtils.getFriendlySize(documentUpload.getSize(),messages),
                        FileUtils.getFriendlySize(getUserFreeSpace(),messages)));
        	}
 
            String mimeType;
            try {
                mimeType = documentFacade.getMimeType(documentUpload.getStream(), documentUpload.getFilePath());
                if (null == mimeType) {
                    mimeType = documentUpload.getContentType();
                }
            } catch (BusinessException e) {
                mimeType = documentUpload.getContentType();
            }
 
            try {
                DocumentVo document = documentFacade.insertFile(documentUpload.getStream(), documentUpload.getSize(),
                    documentUpload.getFileName(), mimeType, userVo);
                messagesManagementService.notify(new BusinessUserMessage(BusinessUserMessageType.UPLOAD_OK,
                    MessageSeverity.INFO, documentUpload.getFileName()));
                documents.add(document);
 
            } catch (BusinessException e) {
                messagesManagementService.notify(e);
            }
        }
 
		return updateDocumentDisplay();
    }
 
	public Object onActionFromRemoveDocument(String identifier) {
		for (DocumentVo documentVo : documents) {
			if (documentVo.getIdentifier().equals(identifier)) {
				documents.remove(documentVo);
				break;
			}
		}
		for (DocumentVo documentVo : shareSessionObjects.getDocuments()) {
			if (documentVo.getIdentifier().equals(identifier)) {
				documents.remove(documentVo);
				break;
			}
		}
 
		return updateDocumentDisplay();
	}
 
 
	private Object updateDocumentDisplay() {
		if (request.isXHR()) {
			return new MultiZoneUpdate("documentsZone", documentsZone.getBody());
		}
		return this;
	}
 
 
    public long getUserFreeSpace() {
        return documentFacade.getUserAvailableQuota(userVo);
    }
 
    public long getMaxFileSize() {
        long maxFileSize = DEFAULT_MAX_FILE_SIZE;
        try {
            maxFileSize = parameterFacade.loadConfig().getFileSizeMax();
        } catch (BusinessException e) {
            // value has not been defined. We use the default value.
        }
        return maxFileSize;
    }
 
 
	public List<String> onProvideCompletionsFromRecipientsPattern(String input) {
		List<UserVo> searchResults = performSearch(input);
 
		List<String> elements = new ArrayList<String>();
		for (UserVo user : searchResults) {
			 String completeName = MailCompletionService.formatLabel(user);
            if (!elements.contains(completeName)) {
                elements.add(completeName);
            }
		}
 
		return elements;
	}
 
 
	/** Perform a user search using the user search pattern.
	 * @param input user search pattern.
	 * @return list of users.
	 */
	private List<UserVo> performSearch(String input) {
 
 
		Set<UserVo> userSet = new HashSet<UserVo>();
 
		String firstName_ = null;
		String lastName_ = null;
 
		if (input != null && input.length() > 0) {
			StringTokenizer stringTokenizer = new StringTokenizer(input, " ");
			if (stringTokenizer.hasMoreTokens()) {
				firstName_ = stringTokenizer.nextToken();
				if (stringTokenizer.hasMoreTokens()) {
					lastName_ = stringTokenizer.nextToken();
				}
			}
		}
 
        if (input != null) {
            userSet.addAll(userFacade.searchUser(input.trim(), null, null,userVo));
        }
		userSet.addAll(userFacade.searchUser(null, firstName_, lastName_, userVo));
		userSet.addAll(userFacade.searchUser(null, lastName_, firstName_,  userVo));
		userSet.addAll(recipientFavouriteFacade.findRecipientFavorite(input.trim(), userVo));
 
		return recipientFavouriteFacade.recipientsOrderedByWeightDesc(new ArrayList<UserVo>(userSet), userVo);
	}
 
	public Object onSuccessFromRecipientsForm() {
		List<String> mails = MailCompletionService.parseEmails(recipientsSearch);
 
		if (recipients == null) {
			recipients = new ArrayList<String>();
		}
 
		for (String string : mails) {
			if (!recipients.contains(string.trim())) {
				recipients.add(string.trim());
			}
		}
 
		recipientsSearch = null;
 
		return updateRecipientDisplay();
	}
 
 
	private Object updateRecipientDisplay() {
		Collections.sort(recipients);
		if (request.isXHR()) {
			return new MultiZoneUpdate("recipientsZone", recipientsZone.getBody());
		}
		return this;
	}
 
	public Object onActionFromRemoveRecipient(String recipient) {
		if (recipients.contains(recipient)) {
			recipients.remove(recipient);
		}
		for (UserVo recipientU : shareSessionObjects.getUsers()) {
			if (recipientU.getMail().equals(recipient)) {
				shareSessionObjects.removeUser(recipientU);
				break;
			}
		}
 
		return updateRecipientDisplay();
	}
 
}
 

Go to most recent revision | Compare with Previous | Blame | View Log