001/* 002 * (C) Copyright 2016 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 018 */ 019 020package org.nuxeo.apidoc.listener; 021 022import static org.apache.commons.lang.BooleanUtils.isFalse; 023import static org.nuxeo.apidoc.snapshot.DistributionSnapshot.PROP_LATEST_FT; 024import static org.nuxeo.apidoc.snapshot.DistributionSnapshot.PROP_LATEST_LTS; 025import static org.nuxeo.apidoc.snapshot.DistributionSnapshot.TYPE_NAME; 026 027import java.util.Arrays; 028import java.util.List; 029 030import org.nuxeo.ecm.core.api.CoreSession; 031import org.nuxeo.ecm.core.api.DocumentModel; 032import org.nuxeo.ecm.core.event.Event; 033import org.nuxeo.ecm.core.event.EventListener; 034import org.nuxeo.ecm.core.event.impl.DocumentEventContext; 035 036/** 037 * Listener used to keep only one latestLTS, or latestFT When a Distribution is 038 * created or modified with the flag; it makes it atomic. 039 * 040 * @author <a href="mailto:ak@nuxeo.com">Arnaud Kervern</a> 041 * @since 8.3 042 */ 043public class LatestDistributionsListener implements EventListener { 044 protected static final String DISTRIBUTION_QUERY = "Select * from %s where %s = 1"; 045 046 @Override 047 public void handleEvent(Event event) { 048 if (!(event.getContext() instanceof DocumentEventContext)) { 049 return; 050 } 051 052 DocumentEventContext ctx = (DocumentEventContext) event.getContext(); 053 DocumentModel srcDoc = ctx.getSourceDocument(); 054 if (!TYPE_NAME.equals(srcDoc.getType())) { 055 return; 056 } 057 058 CoreSession session = ctx.getCoreSession(); 059 List<String> flags = Arrays.asList(PROP_LATEST_FT, PROP_LATEST_LTS); 060 flags.forEach(flag -> { 061 if (isFalse((Boolean) srcDoc.getPropertyValue(flag))) { 062 return; 063 } 064 065 String query = String.format(DISTRIBUTION_QUERY, TYPE_NAME, flag); 066 session.query(query) 067 .stream() 068 .filter(doc -> srcDoc.getId() == null || !doc.getId().equals(srcDoc.getId())) 069 .forEach(doc -> { 070 doc.setPropertyValue(flag, false); 071 session.saveDocument(doc); 072 }); 073 }); 074 } 075 076}