001/*
002 * (C) Copyright 2006 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 *     Florent Guillaume
018 */
019package org.nuxeo.project.sample;
020
021import java.util.HashMap;
022import java.util.Map;
023
024import org.nuxeo.ecm.core.api.DocumentModel;
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.ecm.directory.Session;
030import org.nuxeo.ecm.directory.api.DirectoryService;
031import org.nuxeo.runtime.api.Framework;
032
033public class BookISBNEventListener implements EventListener {
034
035    public void handleEvent(Event event) {
036
037        EventContext ctx = event.getContext();
038
039        if (ctx instanceof DocumentEventContext) {
040
041            DocumentEventContext docCtx = (DocumentEventContext) ctx;
042            DocumentModel doc = docCtx.getSourceDocument();
043
044            if (doc != null) {
045                String type = doc.getType();
046                if ("Book".equals(type)) {
047                    process(doc);
048                }
049            }
050        }
051
052    }
053
054    public void process(DocumentModel doc) {
055        String isbn = (String) doc.getPropertyValue("book:isbn");
056        String title = (String) doc.getPropertyValue("dublincore:title");
057        if (isbn == null || title == null || isbn.trim().equals("") || title.trim().equals("")) {
058            return;
059        }
060
061        DirectoryService dirService = Framework.getService(DirectoryService.class);
062
063        try (Session dir = dirService.open("book_keywords")) {
064            DocumentModel entry = dir.getEntry(isbn);
065
066            if (entry == null) {
067                // create
068                Map<String, Object> map = new HashMap<String, Object>();
069                map.put("id", isbn);
070                map.put("label", title);
071                dir.createEntry(map);
072            } else {
073                // update
074                entry.setPropertyValue("vocabulary:label", title);
075                dir.updateEntry(entry);
076            }
077        }
078    }
079
080}