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