001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Thomas Roger
018 */
019
020package org.nuxeo.ecm.webapp.action;
021
022import static org.apache.commons.logging.LogFactory.getLog;
023import static org.jboss.seam.ScopeType.CONVERSATION;
024import static org.jboss.seam.annotations.Install.FRAMEWORK;
025import static org.nuxeo.ecm.webapp.helpers.EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED;
026
027import java.io.IOException;
028import java.io.Serializable;
029import java.util.ArrayList;
030import java.util.Collection;
031import java.util.Collections;
032import java.util.HashMap;
033import java.util.List;
034import java.util.Map;
035
036import javax.faces.application.FacesMessage;
037import javax.faces.context.FacesContext;
038import javax.servlet.http.HttpServletRequest;
039
040import org.apache.commons.logging.Log;
041import org.jboss.seam.annotations.In;
042import org.jboss.seam.annotations.Install;
043import org.jboss.seam.annotations.Name;
044import org.jboss.seam.annotations.Observer;
045import org.jboss.seam.annotations.Scope;
046import org.jboss.seam.annotations.web.RequestParameter;
047import org.jboss.seam.core.Events;
048import org.jboss.seam.faces.FacesMessages;
049import org.jboss.seam.international.Messages;
050import org.jboss.seam.international.StatusMessage;
051import org.nuxeo.ecm.automation.AutomationService;
052import org.nuxeo.ecm.automation.OperationChain;
053import org.nuxeo.ecm.automation.OperationContext;
054import org.nuxeo.ecm.automation.OperationException;
055import org.nuxeo.ecm.automation.OperationParameters;
056import org.nuxeo.ecm.automation.core.util.BlobList;
057import org.nuxeo.ecm.automation.core.util.DataModelProperties;
058import org.nuxeo.ecm.automation.server.jaxrs.batch.BatchManager;
059import org.nuxeo.ecm.core.api.Blob;
060import org.nuxeo.ecm.core.api.CoreSession;
061import org.nuxeo.ecm.core.api.DataModel;
062import org.nuxeo.ecm.core.api.DocumentModel;
063import org.nuxeo.ecm.core.api.IdRef;
064import org.nuxeo.ecm.core.api.NuxeoException;
065import org.nuxeo.ecm.core.api.impl.SimpleDocumentModel;
066import org.nuxeo.ecm.core.api.security.SecurityConstants;
067import org.nuxeo.ecm.platform.actions.Action;
068import org.nuxeo.ecm.platform.ui.web.api.NavigationContext;
069import org.nuxeo.ecm.platform.ui.web.api.WebActions;
070import org.nuxeo.ecm.platform.ui.web.rest.FancyNavigationHandler;
071import org.nuxeo.ecm.platform.ui.web.util.files.FileUtils;
072import org.nuxeo.ecm.platform.web.common.exceptionhandling.ExceptionHelper;
073import org.nuxeo.ecm.webapp.dnd.DndConfigurationHelper;
074import org.nuxeo.ecm.webapp.filemanager.FileManageActionsBean;
075import org.nuxeo.ecm.webapp.filemanager.NxUploadedFile;
076import org.nuxeo.runtime.api.Framework;
077import org.richfaces.event.FileUploadEvent;
078
079/**
080 * @since 6.0
081 */
082@Name("importActions")
083@Scope(CONVERSATION)
084@Install(precedence = FRAMEWORK)
085public class ImportActions implements Serializable {
086
087    private static final long serialVersionUID = 1L;
088
089    private static final Log log = getLog(ImportActions.class);
090
091    public static final String LABEL_IMPORT_PROBLEM = "label.bulk.import.documents.error";
092
093    public static final String LABEL_IMPORT_CANNOT_CREATE_ERROR = "label.bulk.import.documents.cannotCreateError";
094
095    public static final String DOCUMENTS_IMPORTED = "documentImported";
096
097    @In(create = true, required = false)
098    protected transient CoreSession documentManager;
099
100    @In(create = true)
101    protected NavigationContext navigationContext;
102
103    @In(create = true)
104    protected transient WebActions webActions;
105
106    @In(create = true)
107    protected transient DndConfigurationHelper dndConfigHelper;
108
109    @In(create = true, required = false)
110    protected FacesMessages facesMessages;
111
112    @In(create = true)
113    protected Map<String, String> messages;
114
115    @RequestParameter
116    protected String fancyboxFormId;
117
118    protected DocumentModel importDocumentModel;
119
120    protected Action selectedImportOption;
121
122    protected List<Action> importOptions;
123
124    protected String selectedImportFolderId;
125
126    protected String currentBatchId;
127
128    protected Collection<NxUploadedFile> uploadedFiles = null;
129
130    public DocumentModel getImportDocumentModel() {
131        if (importDocumentModel == null) {
132            importDocumentModel = new SimpleDocumentModel();
133        }
134        return importDocumentModel;
135    }
136
137    public String getSelectedImportOptionId() {
138        if (selectedImportOption == null) {
139            selectedImportOption = importOptions != null && importOptions.size() > 0 ? importOptions.get(0) : null;
140        }
141        return selectedImportOption != null ? selectedImportOption.getId() : null;
142    }
143
144    public void setSelectedImportOptionId(String id) {
145        for (Action importOption : importOptions) {
146            if (importOption.getId().equals(id)) {
147                selectedImportOption = importOption;
148                break;
149            }
150        }
151    }
152
153    public Action getSelectedImportOption() {
154        if (selectedImportOption == null) {
155            selectedImportOption = importOptions != null && importOptions.size() > 0 ? importOptions.get(0) : null;
156        }
157        return selectedImportOption;
158    }
159
160    public List<Action> getImportOptions(String dropContext) {
161        if (importOptions == null) {
162            importOptions = new ArrayList<>();
163            importOptions.addAll(webActions.getActionsList(dropContext));
164        }
165        return importOptions;
166    }
167
168    public String getSelectedImportFolderId() {
169        if (selectedImportFolderId == null) {
170            DocumentModel currentDocument = navigationContext.getCurrentDocument();
171            if (currentDocument == null) {
172                return null;
173            }
174            if (currentDocument.isFolder() && !"/".equals(currentDocument.getPathAsString())
175                    && documentManager.hasPermission(currentDocument.getRef(), SecurityConstants.ADD_CHILDREN)) {
176                selectedImportFolderId = currentDocument.getId();
177            } else {
178                // try to find the first folderish parent
179                List<DocumentModel> parents = documentManager.getParentDocuments(currentDocument.getRef());
180                Collections.reverse(parents);
181
182                for (DocumentModel parent : parents) {
183                    if (parent.isFolder()
184                            && documentManager.hasPermission(parent.getRef(), SecurityConstants.ADD_CHILDREN)) {
185                        selectedImportFolderId = parent.getId();
186                        break;
187                    }
188                }
189            }
190        }
191        return selectedImportFolderId;
192    }
193
194    public void setSelectedImportFolderId(String selectedImportFolderId) {
195        this.selectedImportFolderId = selectedImportFolderId;
196    }
197
198    /*
199     * ----- Document bulk import -----
200     */
201
202    public String generateBatchId() {
203        if (currentBatchId == null) {
204            BatchManager batchManager = Framework.getService(BatchManager.class);
205            currentBatchId = batchManager.initBatch();
206        }
207        return currentBatchId;
208    }
209
210    public boolean hasUploadedFiles() {
211        if (currentBatchId != null) {
212            BatchManager batchManager = Framework.getService(BatchManager.class);
213            return batchManager.hasBatch(currentBatchId);
214        }
215        return false;
216    }
217
218    public String importDocuments() {
219        Map<String, Serializable> importOptionProperties = selectedImportOption.getProperties();
220        String chainOrOperationId = null;
221        if (importOptionProperties.containsKey("chainId")) {
222            chainOrOperationId = (String) importOptionProperties.get("chainId");
223        } else if (importOptionProperties.containsKey("operationId")) {
224            chainOrOperationId = (String) importOptionProperties.get("operationId");
225        } else {
226            // fallback on action id
227            chainOrOperationId = selectedImportOption.getId();
228        }
229
230        List<DataModel> dms = new ArrayList<>();
231        for (String schema : importDocumentModel.getSchemas()) {
232            dms.add(importDocumentModel.getDataModel(schema));
233        }
234        DataModelProperties properties = new DataModelProperties(dms, true);
235
236        Map<String, Object> contextParams = new HashMap<>();
237        contextParams.put("docMetaData", properties);
238        contextParams.put("currentDocument", selectedImportFolderId);
239
240        boolean resetBatchState = true;
241        try {
242            List<DocumentModel> importedDocuments;
243            if (dndConfigHelper.useHtml5DragAndDrop()) {
244                importedDocuments = importDocumentsThroughBatchManager(chainOrOperationId, contextParams);
245
246            } else {
247                importedDocuments = importDocumentsThroughUploadItems(chainOrOperationId, contextParams);
248            }
249
250            Events.instance().raiseEvent(DOCUMENTS_IMPORTED, importedDocuments, importDocumentModel);
251
252            if (selectedImportFolderId != null) {
253                return navigationContext.navigateToRef(new IdRef(selectedImportFolderId));
254            }
255        } catch (NuxeoException e) {
256            log.debug(e, e);
257            Throwable t = ExceptionHelper.unwrapException(e);
258            // FIXME NXP-XXXXX
259            if (t.getMessage().contains("Cannot create")) {
260                // do not reset state
261                resetBatchState = false;
262                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Messages.instance().get(
263                        LABEL_IMPORT_CANNOT_CREATE_ERROR), null);
264                FacesContext faces = FacesContext.getCurrentInstance();
265                if (fancyboxFormId != null && fancyboxFormId.startsWith(":")) {
266                    faces.addMessage(fancyboxFormId.substring(1), message);
267                } else {
268                    faces.addMessage(fancyboxFormId, message);
269                }
270                HttpServletRequest httpRequest = (HttpServletRequest) faces.getExternalContext().getRequest();
271                // avoid redirect for message to be displayed (and fancybox to
272                // be reopened)
273                httpRequest.setAttribute(FancyNavigationHandler.DISABLE_REDIRECT_FOR_URL_REWRITE, Boolean.TRUE);
274            } else {
275                facesMessages.addFromResourceBundle(StatusMessage.Severity.ERROR,
276                        Messages.instance().get(LABEL_IMPORT_PROBLEM));
277            }
278        } finally {
279            if (resetBatchState) {
280                // reset batch state
281                cancel();
282            }
283        }
284
285        return null;
286    }
287
288    @SuppressWarnings("unchecked")
289    protected List<DocumentModel> importDocumentsThroughBatchManager(String chainOrOperationId,
290            Map<String, Object> contextParams) {
291        BatchManager bm = Framework.getService(BatchManager.class);
292        return (List<DocumentModel>) bm.execute(currentBatchId, chainOrOperationId, documentManager, contextParams,
293                null);
294    }
295
296    @SuppressWarnings("unchecked")
297    protected List<DocumentModel> importDocumentsThroughUploadItems(String chainOrOperationId,
298            Map<String, Object> contextParams) {
299        if (uploadedFiles == null) {
300            return Collections.emptyList();
301        }
302
303        try (OperationContext ctx = new OperationContext(documentManager)) {
304            List<Blob> blobs = new ArrayList<>();
305            for (NxUploadedFile uploadItem : uploadedFiles) {
306                Blob blob = uploadItem.getBlob();
307                FileUtils.configureFileBlob(blob);
308                blobs.add(blob);
309            }
310
311            ctx.setInput(new BlobList(blobs));
312            ctx.putAll(contextParams);
313
314            AutomationService as = Framework.getService(AutomationService.class);
315            if (chainOrOperationId.startsWith("Chain.")) {
316                return (List<DocumentModel>) as.run(ctx, chainOrOperationId.substring(6));
317            } else {
318                OperationChain chain = new OperationChain("operation");
319                OperationParameters params = new OperationParameters(chainOrOperationId, new HashMap<String, Object>());
320                chain.add(params);
321                return (List<DocumentModel>) as.run(ctx, chain);
322            }
323        } catch (OperationException e) {
324            log.error("Error while executing automation batch ", e);
325            throw new NuxeoException(e);
326        } finally {
327            for (NxUploadedFile uploadItem : getUploadedFiles()) {
328                // FIXME: check if a temp file needs to be tracked for
329                // deletion
330                // File tempFile = uploadItem.getFile();
331                // if (tempFile != null && tempFile.exists()) {
332                // Framework.trackFile(tempFile, tempFile);
333                // }
334            }
335            uploadedFiles = null;
336        }
337
338    }
339
340    public void cancel() {
341        if (currentBatchId != null) {
342            BatchManager bm = Framework.getService(BatchManager.class);
343            bm.clean(currentBatchId);
344        }
345        importDocumentModel = null;
346        selectedImportFolderId = null;
347        uploadedFiles = null;
348        currentBatchId = null;
349    }
350
351    public Collection<NxUploadedFile> getUploadedFiles() {
352        if (uploadedFiles == null) {
353            uploadedFiles = new ArrayList<>();
354        }
355        return uploadedFiles;
356    }
357
358    public void setUploadedFiles(Collection<NxUploadedFile> uploadedFiles) {
359        this.uploadedFiles = uploadedFiles;
360    }
361
362    @Observer(value = USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED)
363    public void invalidateSelectedImportFolder() {
364        selectedImportFolderId = null;
365    }
366
367    /**
368     * @since 6.0
369     */
370    public void processUpload(FileUploadEvent uploadEvent) {
371        try {
372            if (uploadedFiles == null) {
373                uploadedFiles = new ArrayList<NxUploadedFile>();
374            }
375            Blob blob = FileManageActionsBean.getBlob(uploadEvent);
376            uploadedFiles.add(new NxUploadedFile(blob));
377        } catch (IOException e) {
378            log.error(e, e);
379        }
380    }
381
382}