On Fri, 2003-08-15 at 11:12, Rodrigo Reyes wrote:
> Rodrigo
>     Because of your name, I suppose your native language is Spanish. So is
> mine (BTW, my name is also Rodrigo). Still, I will keep writing in English
> so everybody gets what we are talking here.

I'm Brazilian... portuguese speaker

>     So far, I haven't been able to use this method, no matter where I call
> it (in the Action or in the Screen). What am I trying to accomplish here? I
> am trying to have a different layout from the default in a group of screens.

That's what I wanted. every User pertains to a Project wich has it's own
layout.

> Is there any other way to accomplish this? How do you make this method work?
> Did you have to fix Turbine's code? Thanx

Basically I wrote my own Layout and Screens classes. See attachments.

IMHO, text generation on T2 is a mess. a PITA to customize and debug :-(



> 
> Rodrigo :)
> 
> ----- Original Message ----- 
> From: "Leandro Rodrigo Saad Cruz" <[EMAIL PROTECTED]>
> To: "Turbine Users List" <[EMAIL PROTECTED]>
> Sent: Thursday, August 14, 2003 8:25 PM
> Subject: Re: Is the data.setLayoutTemplate() method workind?
> 
> 
> > I made it work on T2.2. Not T2.3. If you want any help drop me a line
> >
> > On Thu, 14 Aug 2003 18:33:47 -0500, "Rodrigo Reyes"
> <[EMAIL PROTECTED]> escreveu:
> >
> > > De: "Rodrigo Reyes" <[EMAIL PROTECTED]>
> > > Data: Thu, 14 Aug 2003 18:33:47 -0500
> > > Para: <[EMAIL PROTECTED]>,   "turbine-dev"
> <[EMAIL PROTECTED]>
> > > Assunto: Is the data.setLayoutTemplate() method workind?
> > >
> > > Hi all
> > >     Is any one using the data.setLayoutTemplate() method? How? I am
> trying,
> > > but it doesn't seem to be working. Any help?
> > >
> > > Rodrigo Reyes
> > >
> > >
> > >
> > > ---------------------------------------------------------------------
> > > To unsubscribe, e-mail: [EMAIL PROTECTED]
> > > For additional commands, e-mail: [EMAIL PROTECTED]
> > >
> > >
> > >
> > >
> >
> > --
> > Leandro Rodrigo Saad Cruz
> > IT - Inter Business Tecnologia e
> > Servi�os (IB)
> > http://www.ibnetwork.com.br
> > http://db.apache.org/ojb
> > http://xingu.sf.net
> >
> >
> > ---------------------------------------------------------------------
> > To unsubscribe, e-mail: [EMAIL PROTECTED]
> > For additional commands, e-mail: [EMAIL PROTECTED]
> >
> 
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
> 
> 
-- 
Leandro Rodrigo Saad Cruz
IT - Inter Business Tecnologia e Servicos (IB)
http://www.ibnetwork.com.br
http://db.apache.org/ojb
http://xingu.sourceforge.net
package br.com.ibnetwork.multirc.modules.layouts;


//APP
import br.com.ibnetwork.multirc.modules.screens.BaseMultiRCScreen;

// ECS Classes
import org.apache.ecs.ConcreteElement;

// Turbine Classes
import org.apache.turbine.modules.Layout;
import org.apache.turbine.modules.Screen;
import org.apache.turbine.modules.ScreenLoader;
import org.apache.turbine.services.velocity.TurbineVelocity;
import org.apache.turbine.util.Log;
import org.apache.turbine.util.RunData;
import org.apache.turbine.util.template.TemplateNavigation;

// Velocity Stuff
import org.apache.velocity.context.Context;

/**
 * This Layout module allows Velocity templates
 * to be used as layouts.  Since dynamic content is supposed to be primarily
 * located in screens and navigations there should be relatively few reasons
 * to subclass this Layout.
 */
public class MultiRCLayout extends Layout
{
    /**
     * Method called by LayoutLoader.
     *
     * @param RunData
     * @return processed template in a String
     */
    public void doBuild( RunData data ) throws Exception
    {
        /* Get the context needed by WebMacro */
        Context context = TurbineVelocity.getContext( data );
        /* Screen results */
        String returnValue = "";

        /*
         * First, generate the screen and put it in the context so
         * we can grab it the layout template.
         */
        ConcreteElement results = ScreenLoader.getInstance()
            .eval(data, data.getScreen());
        if (results != null)
            returnValue = results.toString();

        /* variable for the screen in the layout template */
        context.put("screen_placeholder", returnValue);

        /* variable to reference the navigation screen in the layout template */
        context.put("navigation", new TemplateNavigation( data ));

        /* pega o nome do template de layout */
        Screen screen = ScreenLoader.getInstance().getInstance(data.getScreen());
        String templateName;
        if(screen instanceof BaseMultiRCScreen)
        {
            templateName = ((BaseMultiRCScreen)screen).getLayoutTemplateName(data);
        }
        else
        {
            templateName = data.getTemplateInfo().getLayoutTemplate();
        }

        //Log.debug("debug","MultiRCLayout: layout template name = "+ templateName + " do screen : "+screen.getClass().getName());

        /* Set the locale and content type */
        data.getResponse().setLocale(data.getLocale());
        data.getResponse().setContentType(data.getContentType());

        /* Finally, generate the layout template and send it to the browser */
        data.getOut().print(TurbineVelocity.handleRequest(context, "layouts" + templateName));
    }
}
package br.com.ibnetwork.multirc.modules.screens;

//APP
import br.com.ibnetwork.multirc.om.Usuario;

//T2
import org.apache.turbine.util.RunData;
import org.apache.turbine.util.Log;
import org.apache.turbine.util.StringUtils;
import org.apache.turbine.util.security.AccessControlList;
import org.apache.turbine.modules.screens.VelocitySecureScreen;
import org.apache.velocity.context.Context;
import org.apache.turbine.services.velocity.TurbineVelocity;
import org.apache.turbine.services.resources.TurbineResources;

/**
 * <b>TODO</b> : Fazer com que o m�dulo aceite + de um role, grupo ou perm como
 * Este � o m�dulo b�sico para o screens do site. Ele gerencia duas fun��es b�sicas :
 * <ul type="square">
 * <li>
 * <b>Restri��es de execu��o do m�dulo</b> : antes de executar o screen, as permiss�es/roles do usu�rio em seu ACL s�o comparados 
 * com as configura��es em multirc.conf, exemplo :
 * <br>
 * <b>services.SecuritySevice.screen.perm.&lt;fully qualified class name&gt;=&lt;perm name&gt;</b> e/ou <br>
 * <b>services.SecuritySevice.screen.group.&lt;fully qualified class name&gt;=&lt;group name&gt;</b> e/ou <br>
 * <b>services.SecuritySevice.screen.role.&lt;fully qualified class name&gt;=&lt;role name&gt;</b> e/ou <br>
 * <br>
 * Cada restri��o ser� adicionada a pr�xima com AND, se nenhuma restri��o for imposta a execu��o do m�dulo o m�dulo ser� executado normalmente.<br>
 * Caso o usu�rio n�o esteja logado, ou n�o pertenca a nenhum grupo, ou ainda, algum dos testes acima falhe, o execu��o do m�dulo ser� proibida e o usu�rio redirecionado para
 * <b>template.access.denied</b>(multirc.conf) com a mensagem "Acesso Negado"
 * </li>
 *
 * <li>
 * <b>Template branding</b> : este m�dulo � respons�vel por encontrar qual template de layout esta associado ao screen.
 * Para isso, o layout em RunData � pesquisado, caso seja uma parametro inv�lido, o layout do projeto 
 * relacionado ao usuario que executa o modulo ser� pesquisado, caso n�o exista, o layout default sera usado.
 * </li>
 * </ul>
 * @author <a href="mailto:[EMAIL PROTECTED]">Leandro Rodrigo Saad Cruz</a>
 */
public abstract class BaseMultiRCScreen 
    extends VelocitySecureScreen
{
    public static final String AUTHORIZATION_KEY = "services.SecurityService.screen.";
    public static final String DEFAULT_LAYOUT_TEMPLATE_KEY = "layout.projeto.default";
    /**
     * Este m�todo sobrescreve VelocityScreen para for�ar as restri��es de seguran�a : isAuthorized() e isPublicModule()
     *
     * @param data Turbine information.
     * @exception Exception, a generic exception.
     */
    protected void doBuildTemplate( RunData data ) 
        throws Exception
    {
        String username = data.getUser().getUserName();
        String modulo = data.getScreen();
        //Log.debug("security","BasemultiRCScreen - Executing doBuildTemplate(data)");
        if ( isAclOk(data) && isAuthorized(data))
        {
            //Log.debug("security","BaseMultiRCScreen: usuario ["+username+"] pode processar ["+modulo+"]");
            doBuildTemplate( data, TurbineVelocity.getContext( data ) );

        }
        else
        {
            Log.info("security","BaseMultiRCScreen: usuario ["+username+"] NAO pode processar ["+modulo+"]");
            data.getVarDebug().put("message_type","error");
            data.setScreenTemplate("AccessDenied.vm");
            data.setMessage("Acesso negado");
        }
    }

    public void doBuildTemplate(RunData data,Context ctx)
    {

    }

    /**
     * Este m�todo � executado antes de <b>doBuildTemplate(data,context)</b> 
     * para refor�ar a seguran�a do sistema de acordo com as configura��o em multirc.conf
     */
    protected boolean isAclOk( RunData data )
    {
        try
        {
            AccessControlList acl = data.getACL();
            String groupName = ((Usuario)data.getUser()).getGrupo().getName();

            String requiredPerm  = TurbineResources.getString(AUTHORIZATION_KEY+"perm."+this.getClass().getName(),null);
            String requiredRole  = TurbineResources.getString(AUTHORIZATION_KEY+"role."+this.getClass().getName(),null);
            String requiredGroup = TurbineResources.getString(AUTHORIZATION_KEY+"group."+this.getClass().getName(),null);

            //Log.debug("security","BaseMultiRCScreen: Credenciais para ["+this.getClass().getName()+"] -> role["+ requiredRole +"] perm["+ requiredPerm +"] group["+ requiredGroup +"]");
           
            boolean allowed = true;
            if (acl != null && data.getUser().hasLoggedIn())
            {
                allowed = (requiredPerm != null) ? acl.hasPermission(requiredPerm,groupName) : allowed ;
                //Log.debug("security","BaseMultiRCScreen: Has Perm ??["+allowed+"]");
                allowed = allowed && (requiredRole != null) ? acl.hasRole(requiredRole,groupName) : allowed ;
                //Log.debug("security","BaseMultiRCScreen: Has Role and Perm ??["+allowed+"]");
                allowed = allowed && (requiredGroup != null) ? requiredGroup.equals(groupName) : allowed ;
                //Log.debug("security","BaseMultiRCScreen: Has Role and Perm and Group ??["+allowed+"]");
            }
            return allowed;
        }            
        catch(NullPointerException e)
        {
            //pode ocorrer se o usuario na tiver grupo, ou nao estiver loggado
            Log.info("security","Usuario nao pode processar este modulo:"+this.getClass().getName()+" pois nao esta logado ou nao esta associado a nenhum grupo",e);
        }
        catch(Exception e)
        {
            //ocorre quando existe algum erro de persistencia ao pegar o grupo do usuario
            Log.info("security","Usu�rio n�o pode processar este m�dulo:"+this.getClass().getName()+" pois n�o foi poss�vel determinar seu grupo",e);
        }
        return false;
    }

    /**
     * M�todo chamado por MultiRCLayout para descobrir qual o template de layout que dever ser executado.
     * O template a ser usado no layout depende fudamentalmente do projeto relacionado ao usu�rio que executa o m�dulo.
     * Se o template proposto pelo projeto nao existir, o template encontrado em TemplateInfo sera usado
     */
    public String getLayoutTemplateName(RunData data)
    {
        String layoutFromTemplateInfo = data.getTemplateInfo().getLayoutTemplate();
        String layoutFromURL  = data.getParameters().get("layout");
        String layoutFromConfiguration = TurbineResources.getString(DEFAULT_LAYOUT_TEMPLATE_KEY,"Default.vm");
        String choosenLayout = null;

//         Log.debug("security","BaseMultiRCScreen: layout from :TemplateInfo["+layoutFromTemplateInfo
//                   +"] URL["+ layoutFromURL
//                   +"] Configuration["+layoutFromConfiguration
//                   +"]");

        if(tryLayout(layoutFromURL))
        {
            choosenLayout = buildTemplateName(layoutFromURL);
        }
        else if(tryLayout(layoutFromTemplateInfo))
        {
            choosenLayout = layoutFromTemplateInfo;
        }
        else
        {
            choosenLayout = layoutFromConfiguration;
        }

        //Log.debug("security","BaseMultiRCScreen: novo layout template ["+choosenLayout+"]");
        data.getTemplateInfo().setLayoutTemplate(choosenLayout);

        return choosenLayout;
    }

    public static boolean tryLayout(String layoutToTry)
    {
        String temp = StringUtils.isValid(layoutToTry) ? buildTemplateName(layoutToTry) : null ;
        return TurbineVelocity.templateExists("/layouts"+temp);
    }

    public static String buildTemplateName(String withCommas)
    {
        return ("/".concat(withCommas)).replace(',','/');
    }

}

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to