001package org.nuxeo.project.sample;
002
003import java.util.HashMap;
004import java.util.Map;
005
006import org.nuxeo.ecm.core.api.DocumentModel;
007import org.nuxeo.ecm.core.event.Event;
008import org.nuxeo.ecm.core.event.EventContext;
009import org.nuxeo.ecm.core.event.EventListener;
010import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
011import org.nuxeo.ecm.directory.Session;
012import org.nuxeo.ecm.directory.api.DirectoryService;
013import org.nuxeo.runtime.api.Framework;
014
015public class BookISBNEventListener implements EventListener {
016
017    public void handleEvent(Event event) {
018
019        EventContext ctx = event.getContext();
020
021        if (ctx instanceof DocumentEventContext) {
022
023            DocumentEventContext docCtx = (DocumentEventContext) ctx;
024            DocumentModel doc = docCtx.getSourceDocument();
025
026            if (doc != null) {
027                String type = doc.getType();
028                if ("Book".equals(type)) {
029                    process(doc);
030                }
031            }
032        }
033
034    }
035
036    public void process(DocumentModel doc) {
037        String isbn = (String) doc.getPropertyValue("book:isbn");
038        String title = (String) doc.getPropertyValue("dublincore:title");
039        if (isbn == null || title == null || isbn.trim().equals("") || title.trim().equals("")) {
040            return;
041        }
042
043        DirectoryService dirService = Framework.getService(DirectoryService.class);
044
045        try (Session dir = dirService.open("book_keywords")) {
046            DocumentModel entry = dir.getEntry(isbn);
047
048            if (entry == null) {
049                // create
050                Map<String, Object> map = new HashMap<String, Object>();
051                map.put("id", isbn);
052                map.put("label", title);
053                dir.createEntry(map);
054            } else {
055                // update
056                entry.setPropertyValue("vocabulary:label", title);
057                dir.updateEntry(entry);
058            }
059        }
060    }
061
062}