001/* 002 * (C) Copyright 2006-2007 Nuxeo SAS (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 * Nuxeo - initial API and implementation 016 */ 017package org.nuxeo.ecm.core.uidgen; 018 019import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.DOCUMENT_CREATED; 020 021import org.apache.commons.logging.Log; 022import org.apache.commons.logging.LogFactory; 023import org.nuxeo.ecm.core.api.DocumentModel; 024import org.nuxeo.ecm.core.api.model.PropertyNotFoundException; 025import org.nuxeo.ecm.core.event.Event; 026import org.nuxeo.ecm.core.event.EventContext; 027import org.nuxeo.ecm.core.event.EventListener; 028import org.nuxeo.ecm.core.event.impl.DocumentEventContext; 029import org.nuxeo.runtime.api.Framework; 030 031public class DocUIDGeneratorListener implements EventListener { 032 033 private static final Log log = LogFactory.getLog(DocUIDGeneratorListener.class); 034 035 @Override 036 public void handleEvent(Event event) { 037 038 if (!DOCUMENT_CREATED.equals(event.getName())) { 039 return; 040 } 041 EventContext ctx = event.getContext(); 042 if (ctx instanceof DocumentEventContext) { 043 DocumentEventContext docCtx = (DocumentEventContext) ctx; 044 DocumentModel doc = docCtx.getSourceDocument(); 045 if (doc.isProxy() || doc.isVersion()) { 046 // a proxy or version keeps the uid of the document 047 // being proxied or versioned => we're not allowed 048 // to modify its field. 049 return; 050 } 051 String eventId = event.getName(); 052 log.debug("eventId : " + eventId); 053 try { 054 addUIDtoDoc(doc); 055 } catch (PropertyNotFoundException e) { 056 log.error("Error occurred while generating UID for doc: " + doc, e); 057 } 058 } 059 } 060 061 private static void addUIDtoDoc(DocumentModel doc) throws PropertyNotFoundException { 062 UIDGeneratorService service = Framework.getService(UIDGeneratorService.class); 063 if (service == null) { 064 log.error("<addUIDtoDoc> UIDGeneratorService service not found ... !"); 065 return; 066 } 067 // generate UID for our doc 068 service.setUID(doc); 069 } 070 071}