001/* 002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * dmetzler 016 */ 017package org.nuxeo.ecm.restapi.server.jaxrs; 018 019import java.util.Map.Entry; 020 021import javax.ws.rs.DELETE; 022import javax.ws.rs.GET; 023import javax.ws.rs.PUT; 024import javax.ws.rs.core.Response; 025 026import org.nuxeo.ecm.core.api.CoreSession; 027import org.nuxeo.ecm.core.api.DataModel; 028import org.nuxeo.ecm.core.api.DocumentModel; 029import org.nuxeo.ecm.core.api.DocumentModelList; 030import org.nuxeo.ecm.webengine.model.WebObject; 031import org.nuxeo.ecm.webengine.model.impl.DefaultObject; 032 033/** 034 * Web object that allows to deal with documents list. 035 * 036 * @since 5.7.3 037 */ 038@WebObject(type = "bulk") 039public class BulkDocumentsObject extends DefaultObject { 040 041 protected DocumentModelList docs; 042 043 @Override 044 public <A> A getAdapter(Class<A> adapter) { 045 if (adapter == DocumentModel.class) { 046 return adapter.cast(docs); 047 } 048 return super.getAdapter(adapter); 049 } 050 051 @Override 052 public void initialize(Object... args) { 053 assert args != null && args.length == 1; 054 docs = (DocumentModelList) args[0]; 055 } 056 057 @GET 058 public DocumentModelList doGet() { 059 return docs; 060 } 061 062 @DELETE 063 public Response doDelete() { 064 CoreSession session = getContext().getCoreSession(); 065 for (DocumentModel doc : docs) { 066 session.removeDocument(doc.getRef()); 067 } 068 session.save(); 069 return Response.ok().build(); 070 } 071 072 @PUT 073 public DocumentModelList doUpdate(DocumentModel updateDoc) { 074 CoreSession session = getContext().getCoreSession(); 075 076 for (DocumentModel doc : docs) { 077 updateDirtyFields(updateDoc, doc); 078 session.saveDocument(doc); 079 } 080 session.save(); 081 return docs; 082 } 083 084 /** 085 * Copy the dirty fields of srcDoc to dstDoc. 086 * 087 * @param srcDoc 088 * @param dstDoc 089 * @since 5.7.3 090 */ 091 private void updateDirtyFields(DocumentModel srcDoc, DocumentModel dstDoc) { 092 for (Entry<String, DataModel> entry : srcDoc.getDataModels().entrySet()) { 093 String schemaName = entry.getKey(); 094 for (String field : entry.getValue().getDirtyFields()) { 095 Object value = srcDoc.getDataModel(schemaName).getValue(field); 096 dstDoc.getDataModel(schemaName).setValue(field, value); 097 } 098 } 099 } 100 101}