When i set cookie for user and close browser tab and open url link again it

I create the
cookie
for user if user
selected remember me
on checkbox. The cookie is created just fine. Cookie keeps information about username and password. When user successfully log into my aplication the user get redirected to specific layout (according to priority).
But when i close the browser tab and the open a tab with link to my application it returns nul pointer…
How to fix that problem, so user will be redirected to specif layout ?

The classes
LoginPanel
,
MainPanel
,
TabletUi
and
UserUi
all extends
CustomComponent
and everything is initialized in constructor.

The methods in class GymperUI :


  • showLoginFrame()
    //replace gridLayout with loginPanel,so loginPanel is shown

  • showTabletScreen()
    //replace gridLayout with tabui, -||-

  • showMainFrame()
    replace gridLayout with mainPanel, -||

I also
underline
and
boldended
text in
LoginPanel
class where i get the
null pointer
if i set the cookie for user with admin priority.

I get the
following error
, somehow the things are
null
of course…
How to fix the “damn thing” to work, so user will be redirected to specific layout for example for admin (mainpanel)?
:

java.lang.NullPointerException
    at com.gym.LoginPanel.navigateUser(LoginPanel.java:167)
    at com.gym.LoginPanel.doSomeThingIfCookieSet(LoginPanel.java:154)
    at com.gym.LoginPanel.initGui(LoginPanel.java:101)
    at com.gym.LoginPanel.<init>(LoginPanel.java:50)
    at com.gym.GymperUI.init(GymperUI.java:58)
    at com.vaadin.ui.UI.doInit(UI.java:682)
    at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:214)
    at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74)
    at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
    at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1409)
    at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:364)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

jul. 21, 2016 1:12:41 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.gym.GymperUI$Servlet]
 in context with path 
[/gymper] threw exception [com.vaadin.server.ServiceException: java.lang.NullPointerException]
 with root cause
java.lang.NullPointerException
    at com.gym.LoginPanel.navigateUser(LoginPanel.java:167)
    at com.gym.LoginPanel.doSomeThingIfCookieSet(LoginPanel.java:154)
    at com.gym.LoginPanel.initGui(LoginPanel.java:101)
    at com.gym.LoginPanel.<init>(LoginPanel.java:50)
    at com.gym.GymperUI.init(GymperUI.java:58)
    at com.vaadin.ui.UI.doInit(UI.java:682)
    at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:214)
    at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74)
    at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
    at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1409)
    at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:364)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)


Here is main class(GymperUI):

[code]
import javax.servlet.annotation.WebServlet;

import com.gym.layoutablet.TabletUi;
import com.gym.layoutuser.UserUi;
import com.vaadin.annotations.PreserveOnRefresh;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.Page;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.UI;
//preserve on refresh added
@SuppressWarnings(“serial”)
@PreserveOnRefresh
@Theme(“gymper”)
public class GymperUI extends UI {

@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = true, ui = GymperUI.class)
public static class Servlet extends VaadinServlet {
}

private GridLayout gridLayout;
private LoginPanel loginPanel;
private MainPanel mainPanel;

//screen for tablet;
private TabletUi tabui;
//screen for users
private UserUi userui;

private final String mypagetitle="Fitnes sistem";

@Override
protected void init(VaadinRequest request) {

    Page.getCurrent().setTitle(mypagetitle);
    
    CommonSessionData data = new CommonSessionData();
    GymperUI.getCurrent().setData(data);

    gridLayout = new GridLayout();
    gridLayout.setImmediate(false);
    gridLayout.setWidth("100.0%");
    gridLayout.setHeight("100.0%");
    gridLayout.setMargin(false);
    setContent(gridLayout);

    loginPanel = new LoginPanel();
    loginPanel.setWidth("100%");
    loginPanel.setHeight("100%");
    gridLayout.addComponent(loginPanel, 0, 0);

    mainPanel = new MainPanel();
     mainPanel.setWidth("100%");
    mainPanel.setHeight("100%");
    
    /*screen tablet*/
    tabui = new TabletUi();
    tabui.setWidth("100%");
    tabui.setHeight("100%");    
    
    /*screen user*/
    userui = new UserUi();
    userui.setWidth("100%");
    userui.setHeight("100%");
        
    ((CommonSessionData) GymperUI.getCurrent().getData()).setMainUi(this);
}


//get main administrator
public MainPanel getMainPanel() {
    return mainPanel;
}

//get layout for tablet
public TabletUi getTabui() {
    return tabui;
}
//get layout for user

public UserUi getUserui() {
    return userui;
}


//get login panel
public LoginPanel getLoginPanel() {
    return loginPanel;
}

public void showMainFrame() {
    
    gridLayout.replaceComponent(loginPanel, mainPanel);
}

public void showLoginFrame() {
   
    gridLayout.replaceComponent(mainPanel, loginPanel);
}

/*tablet screen show*/

public void showTabletScreen() {
    
    gridLayout.replaceComponent(loginPanel, tabui);
}

public void showTabletLoginScreen() {
    
    gridLayout.replaceComponent(tabui, loginPanel);
}

/*show user screen*/
public void showUserScreen() {
    
    gridLayout.replaceComponent(loginPanel, userui);
}

public void showUserLoginScreen() {
    gridLayout.replaceComponent(userui, loginPanel);
}

}
[/code]
Here is my LoginPanel class:

[code]
import java.util.Date;

import javax.servlet.http.Cookie;

import com.gym.database.DBLogika;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.event.FieldEvents.FocusEvent;
import com.vaadin.event.FieldEvents.FocusListener;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Responsive;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.ValoTheme;

public class LoginPanel extends CustomComponent {

private Panel panellogin;
private VerticalLayout mainLayout;
private Button bLogin;
private TextField tfUsername;
private PasswordField tfPassword;
private CheckBox cbrm;
private Label lerror;
private final String MY_COOKIE_NAME="gymperuser";
private final String MY_COOKIE_SPLITER="~";
private AbsoluteLayout allog;

public LoginPanel() {
    
    buildMainLayout();
    setCompositionRoot(mainLayout);

    Responsive.makeResponsive(this);
    initGui();
    
}

public void initGui(){
     
    
    bLogin.setClickShortcut(KeyCode.ENTER);
    bLogin.addClickListener(new Button.ClickListener() {


         public void buttonClick(Button.ClickEvent event) {

             
             if(tfUsername.getValue().isEmpty() && tfPassword.getValue().isEmpty()){
                 
                 lerror.setValue("Vnosna polja sta prazna.");
             }else if(tfUsername.getValue().isEmpty() && !tfPassword.getValue().isEmpty()){
                 
                 lerror.setValue("Vnesi uporabniško ime.");
             }else if(!tfUsername.getValue().isEmpty() && tfPassword.getValue().isEmpty()){
                 
                 lerror.setValue("Vnesi geslo.");
             }else{
                  
                  login(tfUsername.getValue(), tfPassword.getValue());
             }
             
         }
         

     });
   
    tfPassword.addFocusListener(new FocusListener() {
         
         @Override
         public void focus(FocusEvent event) {
             // TODO Auto-generated method stub
             lerror.setValue("");
         }
     });
     
     tfUsername.addFocusListener(new FocusListener() {
         
         @Override
         public void focus(FocusEvent event) {
             // TODO Auto-generated method stub
             lerror.setValue("");
         }
     });
    
       doSomeThingIfCookieSet();
}

private void login(String username, String password) {
    
    boolean result = DBLogika.loginUser(username, password);
    
    if (result == true) {
        
        FunctionCreateMyCookie(username,password);
        lerror.setValue("");
        navigateUser(DBLogika.getUserPriority(username, password));
        
    } else {
        lerror.setValue("Napačna prijava.");
    }
}

private void FunctionCreateMyCookie(String un,String mypasword){
    
    if(cbrm.getValue()){
    
        Cookie piskot=getCookieByName(MY_COOKIE_NAME);
        
        if(piskot==null){
            piskot=new Cookie(MY_COOKIE_NAME, un+MY_COOKIE_SPLITER+mypasword);
            int myCookieAge=3600*24;
            piskot.setMaxAge(myCookieAge);
            piskot.setPath(VaadinService.getCurrentRequest() .getContextPath());
            VaadinService.getCurrentResponse().addCookie(piskot); 
        }
        
    }
    
}

private Cookie getCookieByName(String name) { 
      
     Cookie[] cookies = VaadinService.getCurrentRequest().getCookies();
      for (Cookie cookie : cookies) { 
        if (name.equals(cookie.getName())) { 
          return cookie; 
        } 
      }
      return null; 
      
}

private void doSomeThingIfCookieSet(){
    Cookie piskotek=getCookieByName(MY_COOKIE_NAME);
    
    if(piskotek!=null){
        String val[]=piskotek.getValue().split(MY_COOKIE_SPLITER);
        navigateUser(DBLogika.getUserPriority(val[0]

,val[1]
));
}

}

private void navigateUser(int userpriority){
    
//    System.out.println("user priority: "+userpriority);
    
    switch(userpriority){
    
        case 1:
            //for admin [b]


//HERE I GET THE NULL POINTER if i login as user that have admin priority

[/b]
((CommonSessionData) GymperUI.getCurrent().getData()).getMainUi().showMainFrame();

            break;
        case 2:
            //for tablet
            ((CommonSessionData) GymperUI.getCurrent().getData()).setUsername(tfUsername.getValue());
            ((CommonSessionData) GymperUI.getCurrent().getData()).getMainUi().getTabui().setGuiData();
            
            
            ((CommonSessionData) GymperUI.getCurrent().getData()).getMainUi().getTabui()
                .refreshTable(new java.sql.Timestamp((new Date()).getTime()));
            
            //osveži telovadnice
            ((CommonSessionData) GymperUI.getCurrent().getData()).getMainUi().getTabui().fillMyCombox();
            
            ((CommonSessionData) GymperUI.getCurrent().getData()).getMainUi().showTabletScreen();
            
            
            break;
        case 3:
             //for user
            ((CommonSessionData) GymperUI.getCurrent().getData()).setUsername(tfUsername.getValue());
            ((CommonSessionData) GymperUI.getCurrent().getData()).getMainUi().getUserui().setGuiData();  
            ((CommonSessionData) GymperUI.getCurrent().getData()).getMainUi().showUserScreen();
              
            break;
    }
    
    tfUsername.setValue("");
    tfPassword.setValue("");
  
}

private void buildMainLayout(){
    
    mainLayout=new VerticalLayout();
    mainLayout.setSizeFull();
    
    buildAbsoluteLayout();
    buildMainPanel();
    
    mainLayout.addComponent(panellogin);
    mainLayout.setComponentAlignment(panellogin, Alignment.MIDDLE_CENTER);
    
}

private void buildMainPanel(){
    
    panellogin = new Panel("Prijava");
    panellogin.setWidth("355px");
    panellogin.setHeight("270px");
    
    panellogin.setContent(allog);
    
}

private void buildAbsoluteLayout() {

    allog=new AbsoluteLayout();
    allog.setHeight("100%");
    allog.setWidth("100%");
    
    
    tfUsername = new TextField();
    
    tfUsername.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);
    tfUsername.setIcon(FontAwesome.USER);
    tfUsername.setImmediate(false);

    
    tfPassword = new PasswordField();
    tfPassword.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);
    tfPassword.setIcon(FontAwesome.LOCK);
    tfPassword.setImmediate(false);
    
    HorizontalLayout hlo=new HorizontalLayout();
    hlo.addStyleName(ValoTheme.LAYOUT_HORIZONTAL_WRAPPING);
    hlo.addComponent(tfUsername);

    HorizontalLayout hlt=new HorizontalLayout();
    hlt.addStyleName(ValoTheme.LAYOUT_HORIZONTAL_WRAPPING);
    hlt.addComponent(tfPassword);

    Label lus=new Label("Uporabniško ime:");
    lus.setHeight("25px");
    lus.setWidth("135px");
    
    Label lp=new Label("Geslo:");
    lp.setHeight("25px");
    lp.setWidth("135px");
    
    bLogin = new Button();
    bLogin.setCaption("Prijava");
    bLogin.setIcon(FontAwesome.SIGN_IN);
    bLogin.addStyleName("primary");
    
    lerror=new Label();
    lerror.setHeight("25px");
    lerror.setWidth("180px");
    lerror.addStyleName("mylbsty");
    
    Label lempty=new Label(" ");
    lempty.setHeight("25");
    lempty.setWidth("180px");
    
    cbrm=new CheckBox("Zapomni si me");

    allog.addComponent(lempty, "top:10px;left:10px;");
    allog.addComponent(lus, "top:46px;left:10px;");
    allog.addComponent(hlo, "top:40px;left:150px;");
    allog.addComponent(lp, "top:105px;left:10px;");
    allog.addComponent(hlt, "top:90px;left:150px;");
    allog.addComponent(bLogin, "top:140px;left:150px;");
    allog.addComponent(lerror, "bottom:10px;left:150px;");
   
    allog.addComponent(cbrm, "left:10px;top:150px;");
    
}

}
[/code]
CommenSessionData class:

import java.io.Serializable;

import com.gym.Dialogs.AddAbonma;
import com.gym.layoutablet.TabletUi;
import com.vaadin.ui.GridLayout;

public class CommonSessionData implements Serializable{

    private GymperUI mainUi;
    private String usernametablet;
    private AddAbonma adabonma;
    private boolean SomethingDoneInPaymentToPayReview;
    private boolean fromShowPaymentToPayReview;
    
    private boolean fromTableUiToReviewPartnerInfoTab;
    private boolean SomethingDoneReviewPartnerInfoTab;
    
        
    public boolean isFromTableUiToReviewPartnerInfoTab() {
        return fromTableUiToReviewPartnerInfoTab;
    }

    public void setFromTableUiToReviewPartnerInfoTab(
            boolean fromTableUiToReviewPartnerInfoTab) {
        this.fromTableUiToReviewPartnerInfoTab = fromTableUiToReviewPartnerInfoTab;
    }

    public boolean isSomethingDoneReviewPartnerInfoTab() {
        return SomethingDoneReviewPartnerInfoTab;
    }

    public void setSomethingDoneReviewPartnerInfoTab(
            boolean somethingDoneReviewPartnerInfoTab) {
        SomethingDoneReviewPartnerInfoTab = somethingDoneReviewPartnerInfoTab;
    }

    public boolean isFromShowPaymentToPayReview() {
        return fromShowPaymentToPayReview;
    }

    public void setFromShowPaymentToPayReview(boolean fromShowPaymentToPayReview) {
        this.fromShowPaymentToPayReview = fromShowPaymentToPayReview;
    }

    public boolean isSomethingDoneInPaymentToPayReview() {
        return SomethingDoneInPaymentToPayReview;
    }

    public void setSomethingDoneInPaymentToPayReview(
            boolean somethingDoneInPaymentToPayReview) {
        SomethingDoneInPaymentToPayReview = somethingDoneInPaymentToPayReview;
    }

    public GymperUI getMainUi() {
        return mainUi;
    }

    
    public void setAdabonma(AddAbonma adabonma) {
        this.adabonma = adabonma;
    }
    
    public AddAbonma getAdabonma() {
        return adabonma;
    }
    
    public void setMainUi(GymperUI mainUi) {
        this.mainUi = mainUi;
    }
    
    public void setUsername(String username) {
        this.usernametablet= username;
    }

    public String getUsername() {
        return usernametablet;
    }
  
}

I think the problem is that you call initGui() (and therefore doSomeThingIfCookieSet) in LoginPanel constructor and in your UI.init you instantiate LoginPanel before calling ((CommonSessionData) GymperUI.getCurrent().getData()).setMainUi(this)

Tnx you.
I fix the problem like this in extend UI class:

if(loginPanel!=null){ loginPanel.doSomeThingIfCookieSet(); } Now it work fine.