com.cerebro.provevaadin.Secure.java Source code

Java tutorial

Introduction

Here is the source code for com.cerebro.provevaadin.Secure.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cerebro.provevaadin;

import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author matteo
 */
class Secure extends VerticalLayout {

    public Secure() {

        HorizontalLayout top = new HorizontalLayout();
        this.addComponent(top);
        top.addComponent(new Label("Area sicura"));

        VerticalLayout content = new VerticalLayout();
        this.addComponent(content);

        Navigator nav = new Navigator(UI.getCurrent(), content);
        nav.setErrorView(new ErrorView());
        nav.addView("", new HomeView());
        nav.navigateTo("");

        Button logout = new Button("Logout");
        logout.addClickListener((Button.ClickEvent event) -> {
            System.out.println("Esco dalla sessione");
            SecurityUtils.getSubject().logout();
            UI.getCurrent().getSession().close();
            UI.getCurrent().getPage().setLocation("");
        });
        top.addComponent(logout);
    }

    private static class ErrorView extends VerticalLayout implements View {

        public ErrorView() {
            this.addComponent(
                    new Label("La pagina che stai cercando non esiste oppure non hai i permessi per accederci"));

        }

        @Override
        public void enter(ViewChangeListener.ViewChangeEvent event) {
            System.out.println("View di errore");
        }
    }

    private static class HomeView extends VerticalLayout implements View {

        Logger log = LoggerFactory.getLogger(MyUI.class);

        public HomeView() {
            this.addComponent(new Label("Homepage"));
            this.addComponent(addLabelAdmin());
        }

        @Override
        public void enter(ViewChangeListener.ViewChangeEvent event) {
            log.info("View Home page");
        }

        @RequiresRoles("admin")
        private Label addLabelAdmin() {
            Label l = new Label("Etichetta");
            if (SecurityUtils.getSubject().hasRole("admin")) {
                l.setValue("Etichetta come amministratore");
            }
            return l;
        }
    }

}