Ignore:
Timestamp:
12/27/10 12:27:43 (13 years ago)
Author:
rafaelraymundo
Message:

Ticket #1430 - Mais de um certificados gravados no mesmo token.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/2.2/security/ExpressoCertLogin/src/LoginApplet.java

    r1574 r3633  
    2424 * @author Mário César Kolling - mario.kolling@serpro.gov.br 
    2525 */ 
    26 public class LoginApplet extends JApplet{ 
    27  
    28         /** 
    29          * Valor gerado aleatoriamente 
    30          */ 
    31  
    32         //TODO: Alterar a cor e fonte dos labels e das caixas de texto e senha. 
    33         private static final long serialVersionUID = -6204158613173951516L; 
    34  
    35         //private PinCodePanel pinPanel; 
    36         //private LoginPanel loginPanel; 
    37         //private PinCodePanel alreadyLoadedPanel; 
    38         //private int useCertificate = DigitalCertificate.KEYSTORE_DETECTED; 
    39 //      private String uid; 
    40         private DigitalCertificate dc; 
     26public class LoginApplet extends JApplet { 
     27 
     28    /** 
     29     * Valor gerado aleatoriamente 
     30     */ 
     31    //TODO: Alterar a cor e fonte dos labels e das caixas de texto e senha. 
     32    private static final long serialVersionUID = -6204158613173951516L; 
     33    private DigitalCertificate dc; 
    4134    private Setup setup; 
    4235 
    43         /* (non-Javadoc) 
    44         * @see java.applet.Applet#init() 
    45         */ 
    46         public void init() { 
    47                 super.init(); 
    48                 this.setSize(0, 0); 
     36    /* (non-Javadoc) 
     37    * @see java.applet.Applet#init() 
     38    */ 
     39    public void init() { 
     40        super.init(); 
     41        this.setSize(0, 0); 
    4942        this.setup = new Setup(this); 
    5043        this.setup.addLanguageResource("ExpressoCertLoginMessages"); 
    51         } 
    52  
    53         /* (non-Javadoc) 
    54          * @see java.applet.Applet#start() 
    55          */ 
    56         @Override 
    57         public void start() { 
    58                 super.start(); 
    59  
    60                 int useCertificate = DigitalCertificate.KEYSTORE_NOT_DETECTED; 
    61                 boolean tryAgain = true; 
    62  
    63                 do 
    64                 { 
    65  
    66                         // Cria uma instância de DigitalCertificate e a inicializa 
    67                         this.dc = new DigitalCertificate(this.getDocumentBase(), setup); 
    68                         useCertificate = dc.init(); 
    69                         String[] returnCode = null; 
    70  
    71                         try { 
    72                                 switch (useCertificate){ 
    73                                         case DigitalCertificate.KEYSTORE_DETECTED: 
    74                                                 // Mostra PinNeedeDialog. 
    75                                                 //tryAgain = false; 
    76                                                 String pin = DialogBuilder.showPinDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this.setup); 
    77                                                 if (pin != null) { 
    78                                                         dc.openKeyStore(pin.toCharArray()); 
    79                                                         returnCode = dc.getCredentials(pin); 
    80  
    81                                                         // se chegou aqui, keystore foi acessada e as credenciais do usuário foram recuperadas 
    82                                                         //tryAgain = false; 
    83                                                         assert (returnCode != null): "Valor de returnCode não pode ser nulo"; 
    84  
    85                                                         //this.dc.destroy(); 
    86  
    87                                                         // Faz o login 
    88  
     44    } 
     45 
     46    /* (non-Javadoc) 
     47     * @see java.applet.Applet#start() 
     48     */ 
     49    @Override 
     50    public void start() { 
     51        super.start(); 
     52 
     53        int useCertificate = DigitalCertificate.KEYSTORE_NOT_DETECTED; 
     54        boolean tryAgain = true; 
     55 
     56        do { 
     57 
     58            // Cria uma instância de DigitalCertificate e a inicializa 
     59            this.dc = new DigitalCertificate(this.getDocumentBase(), setup); 
     60            useCertificate = dc.init(); 
     61            String[] returnCode = null; 
     62 
     63            try { 
     64                switch (useCertificate) { 
     65                    case DigitalCertificate.KEYSTORE_DETECTED: 
     66                        // Mostra PinNeedeDialog. 
     67                        String pin = DialogBuilder.showPinDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this.setup); 
     68                        if (pin != null) { 
     69                            dc.openKeyStore(pin.toCharArray()); 
     70                            returnCode = dc.getCredentials(pin); 
     71 
     72                            // Faz o login 
    8973                            if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    9074                                System.out.println("Código de retorno: " + returnCode[0].trim()); 
    9175                            } 
    9276 
    93                                                         if (Integer.parseInt(returnCode[0].trim()) == 0){ 
    94  
    95                                                                 tryAgain = false; 
    96                                                                 // Pega usuário e senha de credentials[1] e credentials[2], respectivamente 
    97                                                                 // adiciona na página e faz o submit. 
    98                                                                 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 
    99                                                                 JSObject loginForm =  (JSObject) document.getMember("flogin"); 
    100                                                                 JSObject loginField = (JSObject) loginForm.getMember("user"); 
    101                                                                 loginField.setMember("value", returnCode[1].trim()); 
    102  
    103                                                                 JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 
    104                                                                 passwdField.setMember("value", returnCode[2].trim()); 
    105  
    106                                                                 loginForm.call("submit", null); 
    107                                                                 Thread.yield(); 
    108  
    109                                                         } 
    110                                                         else if (Integer.parseInt(returnCode[0].trim()) == 6){ 
    111  
    112                                                                 tryAgain = false; 
    113  
    114                                                                 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    115                                     System.out.println("Mensagem de retorno: " + returnCode[1].trim()); 
    116                                 } 
    117  
    118                                                                 //JOptionPane.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), credentials[1]); 
    119                                                                 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 
    120  
    121  
    122  
    123                                                                 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php?cd=98&ts=202"; 
    124                                                                 try { 
    125                                                                         this.getAppletContext().showDocument(new URL(redirect)); 
    126                                                                 } catch (MalformedURLException e) { 
    127                                                                         // TODO Bloco catch gerado automaticamente 
    128                                     if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 
     77                            if (returnCode == null){ // Ação cancelada 
     78                                tryAgain = false; 
     79                                String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 
     80                                try { 
     81                                    this.getAppletContext().showDocument(new URL(redirect)); 
     82                                } catch (MalformedURLException e) { 
     83                                    // TODO Bloco catch gerado automaticamente 
     84                                    if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    12985                                        e.printStackTrace(); 
    13086                                    } 
    131                                                                 } 
    132                                                         } 
    133                                                         else { 
    134                                                                 tryAgain = true; 
    135                                                                 dc.destroy(); 
    136                                                                 System.gc(); 
     87                                } 
     88                            } 
     89                            else if (Integer.parseInt(returnCode[0].trim()) == 0) { 
     90 
     91                                tryAgain = false; 
     92                                // Pega usuário e senha de credentials[1] e credentials[2], respectivamente 
     93                                // adiciona na página e faz o submit. 
     94                                JSObject document = (JSObject) JSObject.getWindow(this).getMember("document"); 
     95                                JSObject loginForm = (JSObject) document.getMember("flogin"); 
     96                                JSObject loginField = (JSObject) loginForm.getMember("user"); 
     97                                loginField.setMember("value", returnCode[1].trim()); 
     98 
     99                                JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 
     100                                passwdField.setMember("value", returnCode[2].trim()); 
     101 
     102                                loginForm.call("submit", null); 
     103                                Thread.yield(); 
     104 
     105                            } else if (Integer.parseInt(returnCode[0].trim()) == 6) { 
     106 
     107                                tryAgain = false; 
    137108 
    138109                                if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     
    140111                                } 
    141112 
    142                                                                 // Mostra mensagem de erro para o usuário 
    143                                                                 //JOptionPane.showMessageDialog(this, credentials[1]); 
    144                                                                 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 
    145                                                                 Thread.yield(); 
    146                                                         } 
    147  
    148                                                 } 
    149                                                 else { 
    150  
    151                                                         tryAgain = false; 
    152                                                         String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 
    153                                                         try { 
    154                                                                 this.getAppletContext().showDocument(new URL(redirect)); 
    155                                                         } catch (MalformedURLException e) { 
    156                                                                 // TODO Bloco catch gerado automaticamente 
     113                                DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 
     114 
     115 
     116 
     117                                String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php?cd=98&ts=202"; 
     118                                try { 
     119                                    this.getAppletContext().showDocument(new URL(redirect)); 
     120                                } catch (MalformedURLException e) { 
     121                                    // TODO Bloco catch gerado automaticamente 
     122                                    if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
     123                                        e.printStackTrace(); 
     124                                    } 
     125                                } 
     126                            } else { 
     127                                tryAgain = true; 
     128                                dc.destroy(); 
     129                                System.gc(); 
     130 
     131                                if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     132                                    System.out.println("Mensagem de retorno: " + returnCode[1].trim()); 
     133                                } 
     134 
     135                                // Mostra mensagem de erro para o usuário 
     136                                DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 
     137                                Thread.yield(); 
     138                            } 
     139 
     140                        } else { 
     141 
     142                            tryAgain = false; 
     143                            String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 
     144                            try { 
     145                                this.getAppletContext().showDocument(new URL(redirect)); 
     146                            } catch (MalformedURLException e) { 
     147                                // TODO Bloco catch gerado automaticamente 
    157148                                if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    158149                                    e.printStackTrace(); 
    159150                                } 
    160                                                         } 
    161                                                 } 
    162  
    163                                                 break; 
    164                                                 /* 
    165                                         case DigitalCertificate.KEYSTORE_ALREADY_LOADED: 
    166                                                 // Mostra PinNotNeededDialog 
    167                                                 tryAgain = false; 
    168  
    169                                                 //Verifica na página se operação anterior foi um logout 
    170                                                 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 
    171                                                 JSObject loginForm =  (JSObject) document.getMember("flogin"); 
    172                                                 JSObject loginField = (JSObject) loginForm.getMember("cd"); 
    173                                                 String cdValue = (String) loginField.getMember("value"); 
    174  
    175                                                 int cd = 0; 
    176                                                 if (cdValue.length() != 0){ 
    177                                                         cd = Integer.parseInt(cdValue); 
    178                                                 } 
    179  
    180                                                 // Se não foi logout prossegue com o login, senão pára tudo 
    181                                                 if (cd != 1 && cd != 5){ 
    182  
    183                                                         DialogBuilder.showPinNotNeededDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this)); 
    184                                                         dc.openKeyStore(null); 
    185                                                         returnCode = dc.getCredentials(""); 
    186  
    187                                                         // se chegou aqui, keystore foi acessada e as credenciais do usuário foram recuperadas 
    188                                                         assert (returnCode != null): "Valor de returnCode não pode ser nulo"; 
    189  
    190                                                         // Faz o login 
    191                                                         doLogin(returnCode); 
    192                                                 } 
    193                                                 else if (cd == 5){ 
    194                                                         JOptionPane.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    195                                                                         "Não foi possível realizar o Logon com certificado!"); 
    196                                                         // Redireciona para a tela de login 
    197                                                         String redirect = this.getCodeBase().toExternalForm() + "login.php"; 
    198                                                         try { 
    199                                                                 this.getAppletContext().showDocument(new URL(redirect)); 
    200                                                         } catch (MalformedURLException e) { 
    201                                                                 // TODO Bloco catch gerado automaticamente 
    202                                                                 e.printStackTrace(); 
    203                                                         } 
    204  
    205                                                 } 
    206  
    207                                                 //DialogBuilder.showPinNotNeededDialog(findParentframe()); 
    208  
    209                                                 break; 
    210                                                 */ 
    211                                         default: 
    212  
    213                                                 // Mostra Diálogo dizendo que token não foi encontrado 
    214                                                 // ou repositório de chaves públicas não foi configurado. 
    215                                                 // Tentar carregar token/keystore novamente? / Logon sem certificado digital? 
    216  
    217                                                 tryAgain = false; 
     151                            } 
     152                        } 
     153 
     154                        break; 
     155                    default: 
     156 
     157                        // Mostra Diálogo dizendo que token não foi encontrado 
     158                        // ou repositório de chaves públicas não foi configurado. 
     159                        // Tentar carregar token/keystore novamente? / Logon sem certificado digital? 
     160 
     161                        tryAgain = false; 
    218162                        if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    219163                            System.out.println("não achou token"); 
    220164                        } 
    221                                                  
    222                                                 dc.destroy(); 
    223                                                 System.gc(); 
    224  
    225                                                 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 
    226                                                 try { 
    227                                                         this.getAppletContext().showDocument(new URL(redirect)); 
    228                                                 } catch (MalformedURLException e) { 
    229                                                         // TODO Bloco catch gerado automaticamente 
     165 
     166                        dc.destroy(); 
     167                        System.gc(); 
     168 
     169                        String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 
     170                        try { 
     171                            this.getAppletContext().showDocument(new URL(redirect)); 
     172                        } catch (MalformedURLException e) { 
     173                            // TODO Bloco catch gerado automaticamente 
    230174                            if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    231175                                e.printStackTrace(); 
    232176                            } 
    233                                                 } 
    234  
    235                                                 //int resultado = JOptionPane.showConfirmDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    236                                                 //      "Deseja tentar novamente?", 
    237                                                 //      "Token não foi encontrado!", 
    238                                                 //      JOptionPane.OK_CANCEL_OPTION, 
    239                                                 //      JOptionPane.QUESTION_MESSAGE); 
    240  
    241                                                 //if (resultado == JOptionPane.OK_OPTION){ 
    242                                                 //      tryAgain = true; 
    243                                                 //} 
    244                                                 //else { 
    245  
    246                                                 //} 
    247  
    248                                                 // if () { 
    249                                                 //      tryAgain = true; 
    250                                                 //} 
    251                                 } 
    252  
    253                         } 
    254                         catch (SSLHandshakeException e){ 
    255                 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    256                     e.printStackTrace(); 
    257                 } 
    258                                 dc.destroy(); 
    259                                 System.gc(); 
    260                                 //JOptionPane.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), "Não foi possível validar o certificado do servidor!"); 
    261                                 //DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    262                                 //              "Não foi possível validar o certificado do servidor!", this.setup); 
     177                        } 
     178                } 
     179 
     180            } catch (SSLHandshakeException e) { 
     181                if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     182                    e.printStackTrace(); 
     183                } 
     184                dc.destroy(); 
     185                System.gc(); 
    263186                DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    264                                                 this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet001"), this.setup); 
    265  
    266                                 Thread.yield(); 
    267  
    268                                 tryAgain = true; 
    269                         } 
    270                         catch (HttpException e) { 
    271                 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    272                     e.printStackTrace(); 
    273                 } 
    274                                  
    275                                 tryAgain = true; 
    276                                 Thread.yield(); 
    277                         } 
    278                         catch (GeneralSecurityException e){ 
    279                 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    280                     e.printStackTrace(); 
    281                 } 
    282                                  
    283                                 //DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    284                                 //              "Algum erro ocorreu ao realizar o logon!", this.setup); 
     187                        this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet001"), this.setup); 
     188 
     189                Thread.yield(); 
     190 
     191                tryAgain = true; 
     192            } catch (HttpException e) { 
     193                if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     194                    e.printStackTrace(); 
     195                } 
     196 
     197                tryAgain = true; 
     198                Thread.yield(); 
     199            } catch (GeneralSecurityException e) { 
     200                if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     201                    e.printStackTrace(); 
     202                } 
     203 
    285204                DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    286                                                 this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet002"), this.setup); 
    287  
    288                                 Thread.yield(); 
    289                                 tryAgain = true; 
    290                         } 
    291                         catch (IOException e) { 
    292                                 dc.destroy(); 
    293                                 System.gc(); 
    294  
    295                 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    296                     e.printStackTrace(); 
    297                 } 
    298                 //System.out.println("Classe que originou o erro de IO: " + e.getClass().getCanonicalName());; 
     205                        this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet002"), this.setup); 
     206 
     207                Thread.yield(); 
     208                tryAgain = true; 
     209            } catch (IOException e) { 
     210                dc.destroy(); 
     211                System.gc(); 
     212 
     213                if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     214                    e.printStackTrace(); 
     215                } 
    299216 
    300217                Throwable cause = null; 
    301                 if ((cause = e.getCause()) != null){ 
    302                     if (cause instanceof javax.security.auth.login.LoginException){ 
    303                         //DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), "PIN incorreto!", this.setup); 
     218                if ((cause = e.getCause()) != null) { 
     219                    if (cause instanceof javax.security.auth.login.LoginException) { 
    304220                        DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet003"), this.setup); 
    305221                    } else { 
     
    308224                        } 
    309225                    } 
    310                 } 
    311                 else { 
    312                     if (e instanceof java.net.ConnectException){ 
    313                         //DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    314                         //        "Não foi possível fazer a conexão com o servidor do Expresso.\n" + 
    315                         //        "Verifique suas configurações de rede/proxy.", this.setup); 
     226                } else { 
     227                    if (e instanceof java.net.ConnectException) { 
    316228                        DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    317229                                this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet004"), this.setup); 
     
    323235                } 
    324236 
    325                                 Thread.yield(); 
    326                 tryAgain = true; 
    327                         } 
    328                         catch (ProviderException e) { 
    329                                 // Tentar novamente / cancel 
    330                                 //JOptionPane.showMessageDialog(this, "Token foi removido! Favor inserir seu token"); 
    331  
    332                                 dc.destroy(); 
    333                                 System.gc(); 
    334  
    335                 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    336                     e.printStackTrace(); 
    337                 } 
    338  
    339 /* 
    340                                 JOptionPane optionPane = new JOptionPane("Token foi removido\nDeseja tentar carregá-lo novamente?", 
    341                                                 JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION); 
    342                                 JDialog dialog = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), true); 
    343                                 dialog.setContentPane(optionPane); 
    344                                 //Posicionando no centro da tela. 
    345  
    346                                 Dimension mySize = dialog.getSize(); 
    347                                 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
    348                                 dialog.setLocation(screenSize.width/2 - (mySize.width/2), screenSize.height/2 - (mySize.height/2)); 
    349                                 dialog.setVisible(true); 
    350  
    351                                 Object selectedValue = optionPane.getValue(); 
    352  
    353                                 if (selectedValue == null){ 
    354  
    355                                 } 
    356                                 else { 
    357                                         if (selectedValue instanceof Integer){ 
    358                                                 Integer 
    359                                         } 
    360                                 } 
    361 */ 
    362  
    363                                 int resultado = DialogBuilder.showConfirmDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    364                                                 //"Deseja tentar carregá-lo novamente?", 
     237                Thread.yield(); 
     238                tryAgain = true; 
     239            } catch (ProviderException e) { 
     240 
     241                dc.destroy(); 
     242                System.gc(); 
     243 
     244                if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     245                    e.printStackTrace(); 
     246                } 
     247 
     248                int resultado = DialogBuilder.showConfirmDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
     249                        //"Deseja tentar carregá-lo novamente?", 
    365250                        this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet005"), 
    366                                                 JOptionPane.QUESTION_MESSAGE, 
    367                                                 JOptionPane.OK_CANCEL_OPTION, this.setup); 
    368  
    369 /*                              int resultado = JOptionPane.showConfirmDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 
    370                                                 "Deseja tentar carregá-lo novamente?", 
    371                                                 "Token foi removido!", 
    372                                                 JOptionPane.OK_CANCEL_OPTION, 
    373                                                 JOptionPane.QUESTION_MESSAGE); 
    374 */ 
    375  
    376                                 if (resultado == JOptionPane.OK_OPTION){ 
    377                                         tryAgain = true; 
    378                                 } 
    379                                 else { 
    380                                         tryAgain = false; 
    381                                 } 
    382  
    383                                 Thread.yield(); 
    384                         } 
    385  
    386                 } 
    387                 while (tryAgain); 
    388  
    389                 // chama o método que cria a interface na thread de lançamento de eventos (Event Dispatching Thread). 
    390                 //try 
    391                 //{ 
    392                 //      SwingUtilities.invokeAndWait(new Runnable(){ 
    393  
    394                                 /* (non-Javadoc) 
    395                                  * @see java.lang.Runnable#run() 
    396                                  */ 
    397                 //              public void run() { 
    398                 //                      createGUI(); 
    399                 //              } 
    400  
    401                 //      }); 
    402                 //} catch (Exception e){ 
    403                 //      System.out.println("Método createGUI não pôde ser carregado: " + e.getMessage()); 
    404                 //} 
    405  
    406         } 
    407  
    408         /* 
    409  
    410         public void doLogin(String[] credentials){ 
    411  
    412                 if (Integer.valueOf(credentials[0]) == 0){ 
    413  
    414                         // Pega usuário e senha de credentials[1] e credentials[2], respectivamente 
    415                         // adiciona na página e faz o submit. 
    416                         JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 
    417                         JSObject loginForm =  (JSObject) document.getMember("flogin"); 
    418                         JSObject loginField = (JSObject) loginForm.getMember("user"); 
    419                         loginField.setMember("value", credentials[1]); 
    420  
    421                         JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 
    422                         passwdField.setMember("value", credentials[2]); 
    423  
    424                         loginForm.call("submit", null); 
    425  
    426                 } 
    427                 else if (Integer.valueOf(credentials[0]) == 6){ 
    428  
    429                         //JOptionPane.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), credentials[1]); 
    430                         DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), credentials[1]); 
    431                         String redirect = this.getCodeBase().toExternalForm() + "login.php?cd=98&ts=202"; 
    432                         try { 
    433                                 this.getAppletContext().showDocument(new URL(redirect)); 
    434                         } catch (MalformedURLException e) { 
    435                                 // TODO Bloco catch gerado automaticamente 
    436                                 e.printStackTrace(); 
    437                         } 
    438                 } 
    439                 else { 
    440                         // Mostra mensagem de erro para o usuário 
    441                         //JOptionPane.showMessageDialog(this, credentials[1]); 
    442                         DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), credentials[1]); 
    443                 } 
    444  
    445         } 
    446  
    447         */ 
    448  
    449         /** 
    450          * Destrói a Applet, executando códigos para desregistrar tokens, keystores, etc. 
    451          */ 
    452         @Override 
    453         public void stop() { 
    454                 //super.destroy(); 
     251                        JOptionPane.QUESTION_MESSAGE, 
     252                        JOptionPane.OK_CANCEL_OPTION, this.setup); 
     253 
     254                if (resultado == JOptionPane.OK_OPTION) { 
     255                    tryAgain = true; 
     256                } else { 
     257                    tryAgain = false; 
     258                } 
     259 
     260                Thread.yield(); 
     261            } 
     262 
     263        } while (tryAgain); 
     264 
     265    } 
     266 
     267    /** 
     268     * Destrói a Applet, executando códigos para desregistrar tokens, keystores, etc. 
     269     */ 
     270    @Override 
     271    public void stop() { 
     272        //super.destroy(); 
    455273        if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    456274            System.out.println("Finalizando Applet de Login!"); 
    457275        } 
    458                  
    459                 this.dc.destroy(); 
    460                 this.dc = null; 
    461                 //Component[] components = this.getComponents(); 
    462                 //for (Component component : components){ 
    463                 //      this.remove(component); 
    464                 //      component = null; 
    465                 //} 
    466                 System.gc(); 
    467         } 
    468  
    469         /** 
    470          * Cria a interface e seleciona o Painel que será exibido de acordo com o parâmetro useCertificate 
    471          */ 
    472         /* 
    473         private void createGUI(){ 
    474  
    475                 this.setLayout(new FlowLayout()); 
    476                 this.getContentPane().setBackground(Color.WHITE); 
    477  
    478                 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 
    479                 JSObject loginForm =  (JSObject) document.getMember("flogin"); 
    480                 JSObject loginField = (JSObject) loginForm.getMember("user"); 
    481  
    482                 uid = loginField.getMember("value").toString(); 
    483  
    484                 pinPanel = new PinCodePanel(uid, true); // mostra pinCodeField 
    485                 alreadyLoadedPanel = new PinCodePanel(uid, false); // não mostra pinCodeField 
    486                 loginPanel = new LoginPanel(uid); 
    487  
    488                 switch (useCertificate){ 
    489                         case DigitalCertificate.KEYSTORE_NOT_DETECTED: 
    490                                 // Mostra interface de login com usuário e senha 
    491                                 this.getContentPane().add(loginPanel); 
    492                                 break; 
    493                         case DigitalCertificate.KEYSTORE_ALREADY_LOADED: 
    494                                 // Mostra interface de login sem pedir o pin 
    495                                 this.getContentPane().add(alreadyLoadedPanel); 
    496                                 break; 
    497                         default: 
    498                                 // Mostra interface de login pedindo o pin 
    499                                 this.getContentPane().add(pinPanel); 
    500  
    501                 } 
    502  
    503                 this.setVisible(true); 
    504  
    505         } 
    506         */ 
    507  
    508         /** 
    509          * Ação executada quando o Botão cancel de PinPanel for pressionado 
    510          * 
    511          */ 
    512         /* 
    513         private void cancelButtonActionPerformed(){ 
    514  
    515                 pinPanel.setVisible(false); 
    516                 this.remove(pinPanel); 
    517                 this.add(loginPanel); 
    518                 loginPanel.setVisible(true); 
    519                 this.setVisible(true); 
    520                 pinPanel.clearPasswordField(); 
    521  
    522         } 
    523         */ 
    524  
    525         /** 
    526          * Ação realizada quando o usuário pressiona o botão Ok ou Prossegir 
    527          * nas telas de login com pin ou sem o pin, respectivamente 
    528          * 
    529          */ 
    530         /* 
    531         private void okButtonActionPerformed(){ 
    532                 // atribui o valor da senha para o atributo Pin 
    533                 char[] pin = pinPanel.getPin(); 
    534                 String[] returnCode = null; 
    535  
    536                 // abre a keystore com o pin e recupera as credenciais do usuário 
    537                 try { 
    538                         dc.openKeyStore(pin); 
    539  
    540                         returnCode = dc.getCredentials(new String(pin)); 
    541  
    542                         assert (returnCode != null): "Valor de returnCode não pode ser nulo"; 
    543  
    544                         if (Integer.valueOf(returnCode[0]) == 0){ 
    545  
    546                                 // Pega usuário e senha de returnCode[1] e returnCode[2], respectivamente 
    547                                 // adiciona na página e faz o submit. 
    548                                 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 
    549                                 JSObject loginForm =  (JSObject) document.getMember("flogin"); 
    550                                 JSObject loginField = (JSObject) loginForm.getMember("user"); 
    551                                 loginField.setMember("value", returnCode[1]); 
    552  
    553                                 JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 
    554                                 passwdField.setMember("value", returnCode[2]); 
    555  
    556                                 this.pinPanel.clearPasswordField(); 
    557                                 loginForm.call("submit", null); 
    558  
    559                         } 
    560                         else { 
    561                                 // Mostra mensagem de erro para o usuário 
    562                                 showGetCredentialsError(returnCode[1]); 
    563                         } 
    564  
    565                 } catch (SSLHandshakeException e){ 
    566                         e.printStackTrace(); 
    567                         JOptionPane.showMessageDialog(this, "Não foi possível validar o certificado do servidor!"); 
    568                 } catch (HttpException e) { 
    569                         e.printStackTrace(); 
    570                 } catch (GeneralSecurityException e){ 
    571                         e.printStackTrace(); 
    572                 } catch (IOException e) { 
    573                         JOptionPane.showMessageDialog(this, "Senha não confere!"); 
    574                 } catch (ProviderException e) { 
    575                         JOptionPane.showMessageDialog(this, "Token foi removido!"); 
    576                 } finally { 
    577                         this.pinPanel.clearPasswordField(); 
    578                 } 
    579  
    580         } 
    581         */ 
    582  
    583         /** 
    584          * Ação realizada quando o usuário pressiona o botão acessar na 
    585          * tela de login com usuário e senha 
    586          * 
    587          */ 
    588         /* 
    589         private void acessarButtonActionPerformed(){ 
    590  
    591                 // Pega usuário e senha dos campos tfUsername e pfPasswd, respectivamente, 
    592                 // adiciona na página e faz o submit. 
    593                 String username = this.loginPanel.tfUsername.getText(); 
    594                 String passwd = String.valueOf(this.loginPanel.pfPasswd.getPassword()); 
    595  
    596                 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 
    597                 JSObject loginForm =  (JSObject) document.getMember("flogin"); 
    598                 JSObject loginField = (JSObject) loginForm.getMember("user"); 
    599                 loginField.setMember("value", username); 
    600  
    601                 JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 
    602                 passwdField.setMember("value", passwd); 
    603  
    604                 this.loginPanel.clearPasswordField(); 
    605                 loginForm.call("submit", null); 
    606  
    607         } 
    608         */ 
    609  
    610         /** 
    611          * Mostra mensagem "Campo PIN não foi preenchido!" quando o botão Ok for pressionado 
    612          *  e o campo pin estiver vazio 
    613          * 
    614          */ 
    615         /* 
    616         private void okButtonPinEmpty(){ 
    617                 JOptionPane.showMessageDialog(this, "Campo PIN não foi preenchido!"); 
    618         } 
    619         */ 
    620  
    621         /** 
    622          * Mostra mensagem de erro recebida de dc.getCredentials(); 
    623          * TODO: Mudar este método para ser mais genérico... Todas as mensagens de erro devem ser passadas para este 
    624          *              método para serem exibidas. 
    625          * @param errorMsg Mensagem de erro que deve ser exibida 
    626          */ 
    627         /* 
    628         private void showGetCredentialsError(String errorMsg){ 
    629                 JOptionPane.showMessageDialog(this, errorMsg); 
    630         } 
    631  
    632         private final class PinCodePanel extends JPanel  implements ActionListener{ 
    633 */ 
    634                 /** 
    635                  * Gerado automaticamente 
    636                  */ 
    637         /* 
    638                 private static final long serialVersionUID = 1003857725229120014L; 
    639  
    640                 JPanel pNorte, pCentro, pSul; 
    641                 JButton btOk, btCancel; 
    642                 JLabel lTitle, lPin; 
    643                 JPasswordField pfPin; 
    644  
    645                 // TODO: Implementar um construtor default (sem parâmetros); 
    646                 public PinCodePanel(String uid, boolean showPinField){ 
    647  
    648                         this.setLayout(new BorderLayout()); 
    649                         Dimension panelsDimension = new Dimension(300, 42); 
    650                         Dimension fieldsDimension = new Dimension(80, 20); 
    651  
    652                         pNorte = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
    653                         pNorte.setBackground(Color.WHITE); 
    654                         pNorte.setPreferredSize(panelsDimension); 
    655  
    656                         pCentro = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
    657                         pCentro.setBackground(Color.WHITE); 
    658                         pCentro.setPreferredSize(panelsDimension); 
    659  
    660                         pSul = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
    661                         pSul.setBackground(Color.WHITE); 
    662                         pSul.setPreferredSize(panelsDimension); 
    663  
    664                         JPanel pTitle = new JPanel(new GridLayout(2, 0)); 
    665                         pTitle.setBackground(Color.WHITE); 
    666                         JLabel lTitle2 = null; 
    667  
    668  
    669                         if (showPinField){ 
    670                                 lTitle = new JLabel("Entre com o seu PIN:"); 
    671                                 lTitle.setHorizontalTextPosition(SwingConstants.CENTER); 
    672  
    673                                 pfPin = new JPasswordField(20); 
    674                                 pfPin.setPreferredSize(fieldsDimension); 
    675                                 pfPin.addActionListener(this); 
    676                                 pfPin.setActionCommand("ok"); 
    677                                 pCentro.add(pfPin); 
    678                                 btOk = new JButton("Ok"); 
    679                                 btCancel = new JButton("Cancel"); 
    680                         } 
    681                         else { 
    682                                 lTitle = new JLabel("Token inserido e desbloqueado"); 
    683                                 lTitle.setHorizontalTextPosition(SwingConstants.CENTER); 
    684                                 lTitle2 = new JLabel(" pelo usuário " + uid + " foi detectado:"); 
    685                                 lTitle2.setHorizontalTextPosition(SwingConstants.CENTER); 
    686                                 btOk = new JButton("Prossegir"); 
    687                         } 
    688  
    689                         JPanel pTitle1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
    690                         pTitle1.setPreferredSize(new Dimension(300, 20)); 
    691                         pTitle1.setBackground(Color.WHITE); 
    692                         pTitle1.add(lTitle); 
    693                         pTitle.add(pTitle1); 
    694                         if (lTitle2 != null) { 
    695                                 JPanel pTitle2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
    696                                 pTitle2.setPreferredSize(new Dimension(300,20)); 
    697                                 pTitle2.setBackground(Color.WHITE); 
    698                                 pTitle.add(pTitle2); 
    699                                 pTitle2.add(lTitle2); 
    700                         } 
    701  
    702                         pNorte.add(pTitle); 
    703  
    704                         btOk.setMnemonic(KeyEvent.VK_ENTER); 
    705                         btOk.setActionCommand("ok"); 
    706                         btOk.addActionListener(this); 
    707                         pSul.add(btOk); 
    708  
    709                         if (btCancel != null){ 
    710                                 btCancel.setActionCommand("cancel"); 
    711                                 btCancel.addActionListener(this); 
    712                                 pSul.add(btCancel); 
    713                         } 
    714  
    715                         this.add(pNorte, BorderLayout.NORTH); 
    716                         this.add(pCentro, BorderLayout.CENTER); 
    717                         this.add(pSul, BorderLayout.SOUTH); 
    718                 } 
    719  
    720                 // design ruim!!! azar :-S 
    721                 public char[] getPin() { 
    722                         if (pfPin == null){ 
    723                                 return null; 
    724                         } 
    725                         return pfPin.getPassword(); 
    726                 } 
    727  
    728                 void clearPasswordField(){ 
    729                         if (pfPin != null){ 
    730                                 pfPin.setText(""); 
    731                         } 
    732                 } 
    733  
    734                 public void actionPerformed(ActionEvent evt) { 
    735  
    736                         String command = evt.getActionCommand(); 
    737  
    738                         // Atribui o valor digitado para o campo 
    739                         // senha e esconde a interface e assina o certificado 
    740                         if (command.equals("ok")){ 
    741  
    742                                 if (pfPin != null && pfPin.getPassword().length <= 0){ 
    743                                         // Mostra um aviso de que o campo PIN não foi preenchido 
    744                                         okButtonPinEmpty(); 
    745                                 } 
    746                                 else { 
    747                                         okButtonActionPerformed(); 
    748                                 } 
    749  
    750                         } 
    751                         else if (command.equals("cancel")){ 
    752                                 cancelButtonActionPerformed(); 
    753                         } 
    754                 } 
    755  
    756  
    757         } 
    758  
    759         private final class LoginPanel extends JPanel implements ActionListener{ 
    760 */ 
    761                 /** 
    762                  * 
    763                  */ 
    764         /* 
    765                 private static final long serialVersionUID = -8604718192554937222L; 
    766                 JButton btAcessar; 
    767                 JTextField tfUsername; 
    768                 JPasswordField pfPasswd; 
    769  
    770                 public LoginPanel(String uid){ 
    771  
    772                         this.setLayout(new BorderLayout()); 
    773  
    774                         JPanel panelCredentials = new JPanel(new GridLayout(2, 0)); 
    775                         panelCredentials.setBackground(Color.WHITE); 
    776                         panelCredentials.setPreferredSize(new Dimension(280, 84)); 
    777  
    778                         JPanel panelUsername = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
    779                         panelUsername.setBackground(Color.WHITE); 
    780                         panelUsername.setPreferredSize(new Dimension(300, 42)); 
    781  
    782                         JLabel labelUsername = new JLabel("Usuário"); 
    783                         panelUsername.add(labelUsername); 
    784                         labelUsername.setPreferredSize(new Dimension(100, 40)); 
    785  
    786                         tfUsername = new JTextField(15); 
    787                         tfUsername.setText(uid); 
    788                         panelUsername.add(tfUsername); 
    789  
    790                         JPanel panelPasswd = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
    791                         panelPasswd.setPreferredSize(new Dimension(300, 42)); 
    792                         JLabel labelPasswd = new JLabel("Senha"); 
    793                         panelPasswd.add(labelPasswd); 
    794                         panelPasswd.setBackground(Color.WHITE); 
    795                         labelPasswd.setPreferredSize(new Dimension(100, 20)); 
    796  
    797                         pfPasswd = new JPasswordField(15); 
    798                         panelPasswd.add(pfPasswd); 
    799  
    800                         panelCredentials.add(panelUsername); 
    801                         panelCredentials.add(panelPasswd); 
    802                         this.add(panelCredentials, BorderLayout.CENTER); 
    803  
    804                         btAcessar = new JButton("Acessar"); 
    805                         btAcessar.setActionCommand("acessar"); 
    806                         btAcessar.addActionListener(this); 
    807                         JPanel panelBtAcessar = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
    808                         panelBtAcessar.setBackground(Color.WHITE); 
    809                         panelBtAcessar.setPreferredSize(new Dimension(300, 42)); 
    810                         panelBtAcessar.add(btAcessar); 
    811  
    812                         this.add(panelBtAcessar, BorderLayout.SOUTH); 
    813                         this.setVisible(true); 
    814  
    815                 } 
    816  
    817                 public void actionPerformed(ActionEvent e) { 
    818                         if (e.getActionCommand().equals("acessar")){ 
    819                                 acessarButtonActionPerformed(); 
    820                         } 
    821  
    822                 } 
    823  
    824                 void clearPasswordField(){ 
    825                         pfPasswd.setText(""); 
    826                 } 
    827  
    828         } 
    829         */ 
    830  
     276 
     277        this.dc.destroy(); 
     278        this.dc = null; 
     279        System.gc(); 
     280    } 
    831281} 
Note: See TracChangeset for help on using the changeset viewer.