001/* 002 * (C) Copyright 2013 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 * dmetzler 018 */ 019package org.nuxeo.ecm.restapi.server.jaxrs; 020 021import java.util.Map.Entry; 022 023import javax.ws.rs.DELETE; 024import javax.ws.rs.GET; 025import javax.ws.rs.PUT; 026import javax.ws.rs.core.Response; 027 028import org.nuxeo.ecm.core.api.CoreSession; 029import org.nuxeo.ecm.core.api.DataModel; 030import org.nuxeo.ecm.core.api.DocumentModel; 031import org.nuxeo.ecm.core.api.DocumentModelList; 032import org.nuxeo.ecm.webengine.model.WebObject; 033import org.nuxeo.ecm.webengine.model.impl.DefaultObject; 034 035/** 036 * Web object that allows to deal with documents list. 037 * 038 * @since 5.7.3 039 */ 040@WebObject(type = "bulk") 041public class BulkDocumentsObject extends DefaultObject { 042 043 protected DocumentModelList docs; 044 045 @Override 046 public <A> A getAdapter(Class<A> adapter) { 047 if (adapter == DocumentModel.class) { 048 return adapter.cast(docs); 049 } 050 return super.getAdapter(adapter); 051 } 052 053 @Override 054 public void initialize(Object... args) { 055 assert args != null && args.length == 1; 056 docs = (DocumentModelList) args[0]; 057 } 058 059 @GET 060 public DocumentModelList doGet() { 061 return docs; 062 } 063 064 @DELETE 065 public Response doDelete() { 066 CoreSession session = getContext().getCoreSession(); 067 for (DocumentModel doc : docs) { 068 session.removeDocument(doc.getRef()); 069 } 070 session.save(); 071 return Response.ok().build(); 072 } 073 074 @PUT 075 public DocumentModelList doUpdate(DocumentModel updateDoc) { 076 CoreSession session = getContext().getCoreSession(); 077 078 for (DocumentModel doc : docs) { 079 updateDirtyFields(updateDoc, doc); 080 session.saveDocument(doc); 081 } 082 session.save(); 083 return docs; 084 } 085 086 /** 087 * Copy the dirty fields of srcDoc to dstDoc. 088 * 089 * @param srcDoc 090 * @param dstDoc 091 * @since 5.7.3 092 */ 093 private void updateDirtyFields(DocumentModel srcDoc, DocumentModel dstDoc) { 094 for (Entry<String, DataModel> entry : srcDoc.getDataModels().entrySet()) { 095 String schemaName = entry.getKey(); 096 for (String field : entry.getValue().getDirtyFields()) { 097 Object value = srcDoc.getDataModel(schemaName).getValue(field); 098 dstDoc.getDataModel(schemaName).setValue(field, value); 099 } 100 } 101 } 102 103}