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