001/*
002 * (C) Copyright 2014 Nuxeo SA (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 *     Anahide Tchertchian
016 */
017package org.nuxeo.ecm.platform.forms.layout.facelets;
018
019import javax.faces.context.FacesContext;
020import javax.faces.event.PhaseEvent;
021import javax.faces.event.PhaseId;
022import javax.faces.event.PhaseListener;
023
024/**
025 * Phase listener that empties the map of widget ids generated by the layout system to avoid duplicate when process of
026 * facelet handlers is done twice.
027 * <p>
028 * Process is done twice on ajax requests, when performing phase restore and then phase render response => empty the map
029 * before rendering response.
030 *
031 * @since 6.0
032 */
033public class LayoutPhaseListener implements PhaseListener {
034
035    private static final long serialVersionUID = 1L;
036
037    @Override
038    public PhaseId getPhaseId() {
039        return PhaseId.RENDER_RESPONSE;
040    }
041
042    @Override
043    public void beforePhase(PhaseEvent event) {
044        FacesContext context = event.getFacesContext();
045        NuxeoLayoutIdManagerBean bean = lookupIdBean(context);
046        bean.resetIds();
047    }
048
049    protected static NuxeoLayoutIdManagerBean lookupIdBean(FacesContext ctx) {
050        String expr = "#{" + NuxeoLayoutIdManagerBean.NAME + "}";
051        NuxeoLayoutIdManagerBean bean = (NuxeoLayoutIdManagerBean) ctx.getApplication().evaluateExpressionGet(ctx,
052                expr, Object.class);
053        if (bean == null) {
054            throw new RuntimeException("Managed bean not found: " + expr);
055        }
056        return bean;
057    }
058
059    @Override
060    public void afterPhase(PhaseEvent event) {
061    }
062
063}