001/*
002 * CDDL HEADER START
003 *
004 * The contents of this file are subject to the terms of the
005 * Common Development and Distribution License, Version 1.0 only
006 * (the "License").  You may not use this file except in compliance
007 * with the License.
008 *
009 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
010 * or http://forgerock.org/license/CDDLv1.0.html.
011 * See the License for the specific language governing permissions
012 * and limitations under the License.
013 *
014 * When distributing Covered Code, include this CDDL HEADER in each
015 * file and include the License file at legal-notices/CDDLv1_0.txt.
016 * If applicable, add the following below this CDDL HEADER, with the
017 * fields enclosed by brackets "[]" replaced with your own identifying
018 * information:
019 *      Portions Copyright [yyyy] [name of copyright owner]
020 *
021 * CDDL HEADER END
022 *
023 *
024 *      Copyright 2008-2010 Sun Microsystems, Inc.
025 *      Portions Copyright 2014-2015 ForgeRock AS
026 */
027
028package org.opends.guitools.uninstaller.ui;
029
030import java.awt.Dimension;
031import java.awt.GridBagConstraints;
032import java.awt.GridBagLayout;
033import java.awt.event.ActionEvent;
034import java.awt.event.ActionListener;
035import java.net.URI;
036import java.security.cert.X509Certificate;
037import java.util.ArrayList;
038
039import javax.naming.NamingException;
040import javax.naming.ldap.InitialLdapContext;
041import javax.swing.Box;
042import javax.swing.JButton;
043import javax.swing.JDialog;
044import javax.swing.JFrame;
045import javax.swing.JLabel;
046import javax.swing.JPanel;
047import javax.swing.JTextField;
048import javax.swing.SwingUtilities;
049import javax.swing.text.JTextComponent;
050
051import org.forgerock.i18n.LocalizableMessage;
052import org.forgerock.i18n.slf4j.LocalizedLogger;
053import org.opends.admin.ads.ADSContext;
054import org.opends.admin.ads.util.ApplicationTrustManager;
055import org.opends.guitools.controlpanel.datamodel.ConnectionProtocolPolicy;
056import org.opends.guitools.controlpanel.datamodel.ControlPanelInfo;
057import org.opends.guitools.controlpanel.util.ConfigFromFile;
058import org.opends.quicksetup.ApplicationException;
059import org.opends.quicksetup.Constants;
060import org.opends.quicksetup.Installation;
061import org.opends.quicksetup.ReturnCode;
062import org.opends.quicksetup.Step;
063import org.opends.quicksetup.UserData;
064import org.opends.quicksetup.UserDataCertificateException;
065import org.opends.quicksetup.event.MinimumSizeComponentListener;
066import org.opends.quicksetup.ui.CertificateDialog;
067import org.opends.quicksetup.ui.UIFactory;
068import org.opends.quicksetup.ui.Utilities;
069import org.opends.quicksetup.util.BackgroundTask;
070import org.opends.quicksetup.util.UIKeyStore;
071import org.opends.quicksetup.util.Utils;
072
073import static com.forgerock.opendj.cli.Utils.*;
074
075import static org.opends.messages.AdminToolMessages.*;
076import static org.opends.messages.QuickSetupMessages.*;
077
078/**
079 * This class is a dialog that appears when the user must provide authentication
080 * to connect to the Directory Server in order to be able to display
081 * information.
082 */
083public class LoginDialog extends JDialog
084{
085  private static final long serialVersionUID = 9049409381101152000L;
086
087  private JFrame parent;
088
089  private JLabel lHostName;
090  private JLabel lUid;
091  private JLabel lPwd;
092
093  private JTextField tfHostName;
094  private JTextField tfUid;
095  private JTextField tfPwd;
096
097  private JButton cancelButton;
098  private JButton okButton;
099
100  private boolean isCanceled = true;
101
102  private ApplicationTrustManager trustManager;
103  private int timeout;
104
105  private InitialLdapContext ctx;
106
107  private String usedUrl;
108
109  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
110
111  /**
112   * Constructor of the LoginDialog.
113   * @param parent the parent frame for this dialog.
114   * @param trustManager the trust manager to be used for the secure
115   * connections.
116   * @param timeout the timeout to establish the connection in milliseconds.
117   * Use {@code 0} to express no timeout.
118   */
119  public LoginDialog(JFrame parent, ApplicationTrustManager trustManager,
120      int timeout)
121  {
122    super(parent);
123    setTitle(INFO_LOGIN_DIALOG_TITLE.get().toString());
124    this.parent = parent;
125    getContentPane().add(createPanel());
126    if (trustManager == null)
127    {
128      throw new IllegalArgumentException("The trustmanager cannot be null.");
129    }
130    this.trustManager = trustManager;
131    this.timeout = timeout;
132    /*
133     * TODO: find a way to calculate this dynamically.  This is done to avoid
134     * all the text in a single line.
135     */
136    setPreferredSize(new Dimension(500, 250));
137    addComponentListener(new MinimumSizeComponentListener(this, 500, 250));
138    getRootPane().setDefaultButton(okButton);
139  }
140
141  /**
142   * Returns <CODE>true</CODE> if the user clicked on cancel and
143   * <CODE>false</CODE> otherwise.
144   * @return <CODE>true</CODE> if the user clicked on cancel and
145   * <CODE>false</CODE> otherwise.
146   */
147  public boolean isCanceled()
148  {
149    return isCanceled;
150  }
151
152  /** {@inheritDoc} */
153  @Override
154  public void setVisible(boolean visible)
155  {
156    cancelButton.setEnabled(true);
157    okButton.setEnabled(true);
158    if (visible)
159    {
160      tfPwd.setText("");
161      tfPwd.requestFocusInWindow();
162      UIFactory.setTextStyle(lHostName,
163          UIFactory.TextStyle.PRIMARY_FIELD_VALID);
164      UIFactory.setTextStyle(lUid,
165          UIFactory.TextStyle.PRIMARY_FIELD_VALID);
166      UIFactory.setTextStyle(lPwd,
167          UIFactory.TextStyle.PRIMARY_FIELD_VALID);
168      getRootPane().setDefaultButton(okButton);
169    }
170    super.setVisible(visible);
171  }
172
173  /**
174   * Returns the Host Name as is referenced in other servers.
175   * @return the Host Name as is referenced in other servers.
176   */
177  public String getHostName()
178  {
179    return tfHostName.getText();
180  }
181
182  /**
183   * Returns the Administrator UID provided by the user.
184   * @return the Administrator UID provided by the user.
185   */
186  public String getAdministratorUid()
187  {
188    return tfUid.getText();
189  }
190
191  /**
192   * Returns the Administrator password provided by the user.
193   * @return the Administrator password provided by the user.
194   */
195  public String getAdministratorPwd()
196  {
197    return tfPwd.getText();
198  }
199
200  /**
201   * Returns the connection we got with the provided authentication.
202   * @return the connection we got with the provided authentication.
203   */
204  public InitialLdapContext getContext()
205  {
206    return ctx;
207  }
208
209  /**
210   * Creates and returns the panel of the dialog.
211   * @return the panel of the dialog.
212   */
213  private JPanel createPanel()
214  {
215    JPanel p1 = new JPanel(new GridBagLayout());
216    p1.setBackground(UIFactory.CURRENT_STEP_PANEL_BACKGROUND);
217    p1.setBorder(UIFactory.DIALOG_PANEL_BORDER);
218    GridBagConstraints gbc = new GridBagConstraints();
219    gbc.gridwidth = GridBagConstraints.RELATIVE;
220    gbc.anchor = GridBagConstraints.NORTHWEST;
221    gbc.insets = UIFactory.getCurrentStepPanelInsets();
222    p1.add(UIFactory.makeJLabel(UIFactory.IconType.INFORMATION_LARGE, null,
223        UIFactory.TextStyle.NO_STYLE), gbc);
224    gbc.weightx = 1.0;
225    gbc.fill = GridBagConstraints.BOTH;
226    gbc.gridwidth = GridBagConstraints.REMAINDER;
227    gbc.insets.left = 0;
228    LocalizableMessage msg = INFO_UNINSTALL_LOGIN_DIALOG_MSG.get();
229
230    JTextComponent textPane =
231      UIFactory.makeHtmlPane(msg, UIFactory.INSTRUCTIONS_FONT);
232    textPane.setOpaque(false);
233    textPane.setEditable(false);
234    p1.add(textPane, gbc);
235
236    JPanel p2 = new JPanel(new GridBagLayout());
237    p2.setOpaque(false);
238
239    gbc.gridwidth = GridBagConstraints.RELATIVE;
240    gbc.weightx = 0.0;
241    gbc.insets = UIFactory.getEmptyInsets();
242    gbc.anchor = GridBagConstraints.WEST;
243    gbc.fill = GridBagConstraints.HORIZONTAL;
244    lHostName = UIFactory.makeJLabel(UIFactory.IconType.NO_ICON,
245        INFO_UNINSTALL_LOGIN_HOST_NAME_LABEL.get(),
246        UIFactory.TextStyle.PRIMARY_FIELD_VALID);
247    p2.add(lHostName, gbc);
248    gbc.weightx = 1.0;
249    gbc.insets.left = UIFactory.LEFT_INSET_PRIMARY_FIELD;
250    gbc.gridwidth = GridBagConstraints.REMAINDER;
251    tfHostName = UIFactory.makeJTextField(
252        LocalizableMessage.raw(UserData.getDefaultHostName()),
253        INFO_UNINSTALL_LOGIN_HOST_NAME_TOOLTIP.get(),
254        UIFactory.HOST_FIELD_SIZE, UIFactory.TextStyle.TEXTFIELD);
255    p2.add(tfHostName, gbc);
256
257    gbc.gridwidth = GridBagConstraints.RELATIVE;
258    gbc.weightx = 0.0;
259    gbc.insets.left = 0;
260    gbc.insets.top = UIFactory.TOP_INSET_PRIMARY_FIELD;
261    gbc.anchor = GridBagConstraints.WEST;
262    gbc.fill = GridBagConstraints.HORIZONTAL;
263    lUid = UIFactory.makeJLabel(UIFactory.IconType.NO_ICON,
264        INFO_GLOBAL_ADMINISTRATOR_UID_LABEL.get(),
265        UIFactory.TextStyle.PRIMARY_FIELD_VALID);
266    p2.add(lUid, gbc);
267    gbc.weightx = 1.0;
268    gbc.insets.left = UIFactory.LEFT_INSET_PRIMARY_FIELD;
269    gbc.gridwidth = GridBagConstraints.REMAINDER;
270    tfUid = UIFactory.makeJTextField(LocalizableMessage.raw(Constants.GLOBAL_ADMIN_UID),
271        INFO_UNINSTALL_LOGIN_UID_TOOLTIP.get(),
272        UIFactory.DN_FIELD_SIZE, UIFactory.TextStyle.TEXTFIELD);
273    p2.add(tfUid, gbc);
274
275    gbc.gridwidth = GridBagConstraints.RELATIVE;
276    gbc.weightx = 0.0;
277    gbc.insets.left = 0;
278    lPwd = UIFactory.makeJLabel(UIFactory.IconType.NO_ICON,
279        INFO_GLOBAL_ADMINISTRATOR_PWD_LABEL.get(),
280        UIFactory.TextStyle.PRIMARY_FIELD_VALID);
281    p2.add(lPwd, gbc);
282    gbc.insets.left = UIFactory.LEFT_INSET_PRIMARY_FIELD;
283    gbc.fill = GridBagConstraints.HORIZONTAL;
284    gbc.gridwidth = GridBagConstraints.REMAINDER;
285    JPanel p3 = new JPanel(new GridBagLayout());
286    p3.setOpaque(false);
287    tfPwd = UIFactory.makeJPasswordField(null,
288        INFO_UNINSTALL_LOGIN_PWD_TOOLTIP.get(),
289        UIFactory.PASSWORD_FIELD_SIZE, UIFactory.TextStyle.PASSWORD_FIELD);
290    p2.add(p3, gbc);
291    gbc.insets = UIFactory.getEmptyInsets();
292    gbc.gridwidth = GridBagConstraints.RELATIVE;
293    gbc.weightx = 0.0;
294    p3.add(tfPwd, gbc);
295    gbc.gridwidth = GridBagConstraints.REMAINDER;
296    gbc.weightx = 1.0;
297    p3.add(Box.createHorizontalGlue(), gbc);
298
299
300    gbc.fill = GridBagConstraints.HORIZONTAL;
301    gbc.insets = UIFactory.getEmptyInsets();
302    gbc.gridwidth = GridBagConstraints.RELATIVE;
303    gbc.weightx = 0.0;
304    gbc.insets.top = 0;
305    p1.add(Box.createHorizontalGlue(), gbc);
306    gbc.weightx = 1.0;
307    gbc.gridwidth = GridBagConstraints.REMAINDER;
308    gbc.insets.right = UIFactory.getCurrentStepPanelInsets().right;
309    p1.add(p2, gbc);
310    gbc.weighty = 1.0;
311    gbc.fill = GridBagConstraints.VERTICAL;
312    gbc.insets.bottom = UIFactory.getCurrentStepPanelInsets().bottom;
313    p1.add(Box.createVerticalGlue(), gbc);
314
315
316    JPanel buttonPanel = new JPanel(new GridBagLayout());
317    buttonPanel.setOpaque(false);
318    gbc.fill = GridBagConstraints.HORIZONTAL;
319    gbc.weightx = 1.0;
320    gbc.insets = UIFactory.getEmptyInsets();
321    gbc.gridwidth = 3;
322    buttonPanel.add(Box.createHorizontalGlue(), gbc);
323    gbc.gridwidth = GridBagConstraints.RELATIVE;
324    gbc.fill = GridBagConstraints.NONE;
325    gbc.weightx = 0.0;
326    okButton =
327      UIFactory.makeJButton(INFO_OK_BUTTON_LABEL.get(),
328          INFO_UNINSTALL_LOGIN_OK_BUTTON_TOOLTIP.get());
329    buttonPanel.add(okButton, gbc);
330    okButton.addActionListener(new ActionListener()
331    {
332      @Override
333      public void actionPerformed(ActionEvent ev)
334      {
335        okClicked();
336      }
337    });
338
339    gbc.gridwidth = GridBagConstraints.REMAINDER;
340    gbc.insets.left = UIFactory.HORIZONTAL_INSET_BETWEEN_BUTTONS;
341    cancelButton =
342      UIFactory.makeJButton(INFO_CANCEL_BUTTON_LABEL.get(),
343          INFO_UNINSTALL_LOGIN_CANCEL_BUTTON_TOOLTIP.get());
344    buttonPanel.add(cancelButton, gbc);
345    cancelButton.addActionListener(new ActionListener()
346    {
347      @Override
348      public void actionPerformed(ActionEvent ev)
349      {
350        cancelClicked();
351      }
352    });
353
354    JPanel p = new JPanel(new GridBagLayout());
355    p.setBackground(UIFactory.DEFAULT_BACKGROUND);
356    gbc.insets = UIFactory.getEmptyInsets();
357    gbc.fill = GridBagConstraints.BOTH;
358    gbc.gridwidth = GridBagConstraints.REMAINDER;
359    gbc.weightx = 1.0;
360    gbc.weighty = 1.0;
361    p.add(p1, gbc);
362    gbc.weighty = 0.0;
363    gbc.insets = UIFactory.getButtonsPanelInsets();
364    p.add(buttonPanel, gbc);
365
366    return p;
367  }
368
369  /**
370   * Method called when user clicks on cancel.
371   *
372   */
373  private void cancelClicked()
374  {
375    isCanceled = true;
376    dispose();
377  }
378
379  /**
380   * Method called when user clicks on OK.
381   *
382   */
383  private void okClicked()
384  {
385    BackgroundTask<Boolean> worker = new BackgroundTask<Boolean>()
386    {
387      @Override
388      public Boolean processBackgroundTask() throws NamingException,
389      ApplicationException
390      {
391        Boolean isServerRunning = Boolean.TRUE;
392        ctx = null;
393        try
394        {
395          ControlPanelInfo info = ControlPanelInfo.getInstance();
396          info.setTrustManager(getTrustManager());
397          info.setConnectTimeout(timeout);
398          info.regenerateDescriptor();
399          ConfigFromFile conf = new ConfigFromFile();
400          conf.readConfiguration();
401          String dn = ADSContext.getAdministratorDN(tfUid.getText());
402          String pwd = tfPwd.getText();
403          info.setConnectionPolicy(ConnectionProtocolPolicy.USE_ADMIN);
404          usedUrl = info.getAdminConnectorURL();
405          if (usedUrl == null)
406          {
407            throw new ApplicationException(ReturnCode.APPLICATION_ERROR,
408                ERR_COULD_NOT_FIND_VALID_LDAPURL.get(), null);
409          }
410          ctx =
411            org.opends.guitools.controlpanel.util.Utilities.getAdminDirContext(
412              info, dn, pwd);
413
414
415        } catch (NamingException ne)
416        {
417          if (isServerRunning())
418          {
419            throw ne;
420          }
421          isServerRunning = Boolean.FALSE;
422        } catch (ApplicationException | IllegalStateException e)
423        {
424          throw e;
425        } catch (Throwable t)
426        {
427          throw new IllegalStateException("Unexpected throwable.", t);
428        }
429        return isServerRunning;
430      }
431
432      @Override
433      public void backgroundTaskCompleted(Boolean returnValue,
434          Throwable throwable)
435      {
436        if (throwable != null)
437        {
438          logger.info(LocalizableMessage.raw("Error connecting: " + throwable, throwable));
439          if (isCertificateException(throwable))
440          {
441            ApplicationTrustManager.Cause cause =
442              trustManager.getLastRefusedCause();
443
444            logger.info(LocalizableMessage.raw("Certificate exception cause: "+cause));
445            UserDataCertificateException.Type excType = null;
446            if (cause == ApplicationTrustManager.Cause.NOT_TRUSTED)
447            {
448              excType = UserDataCertificateException.Type.NOT_TRUSTED;
449            }
450            else if (cause ==
451              ApplicationTrustManager.Cause.HOST_NAME_MISMATCH)
452            {
453              excType = UserDataCertificateException.Type.HOST_NAME_MISMATCH;
454            }
455            else
456            {
457              LocalizableMessage msg = getThrowableMsg(
458                  INFO_ERROR_CONNECTING_TO_LOCAL.get(), throwable);
459              displayError(msg, INFO_ERROR_TITLE.get());
460            }
461
462            if (excType != null)
463            {
464              String h;
465              int p;
466              try
467              {
468                URI uri = new URI(usedUrl);
469                h = uri.getHost();
470                p = uri.getPort();
471              }
472              catch (Throwable t)
473              {
474                logger.warn(LocalizableMessage.raw(
475                    "Error parsing ldap url of ldap url.", t));
476                h = INFO_NOT_AVAILABLE_LABEL.get().toString();
477                p = -1;
478              }
479              UserDataCertificateException udce =
480              new UserDataCertificateException(Step.REPLICATION_OPTIONS,
481                  INFO_CERTIFICATE_EXCEPTION.get(h, p),
482                  throwable, h, p,
483                  getTrustManager().getLastRefusedChain(),
484                  getTrustManager().getLastRefusedAuthType(), excType);
485
486              handleCertificateException(udce);
487            }
488          }
489          else if (throwable instanceof NamingException)
490          {
491            boolean uidInvalid = false;
492            boolean pwdInvalid = false;
493
494            String uid = tfUid.getText();
495            ArrayList<LocalizableMessage> possibleCauses = new ArrayList<>();
496            if ("".equals(uid.trim()))
497            {
498              uidInvalid = true;
499              possibleCauses.add(INFO_EMPTY_ADMINISTRATOR_UID.get());
500            }
501
502            if ("".equals(tfPwd.getText()))
503            {
504              pwdInvalid = true;
505              possibleCauses.add(INFO_EMPTY_PWD.get());
506            }
507            if (uidInvalid)
508            {
509              UIFactory.setTextStyle(lUid,
510                UIFactory.TextStyle.PRIMARY_FIELD_INVALID);
511            }
512            else
513            {
514              UIFactory.setTextStyle(lUid,
515                  UIFactory.TextStyle.PRIMARY_FIELD_VALID);
516              pwdInvalid = true;
517            }
518            if (pwdInvalid)
519            {
520              UIFactory.setTextStyle(lPwd,
521                UIFactory.TextStyle.PRIMARY_FIELD_INVALID);
522            }
523            else
524            {
525              UIFactory.setTextStyle(lPwd,
526                  UIFactory.TextStyle.PRIMARY_FIELD_VALID);
527            }
528            if (possibleCauses.size() > 0)
529            {
530              // LocalizableMessage with causes
531              displayError(
532                  ERR_CANNOT_CONNECT_TO_LOGIN_WITH_CAUSE.get(
533                          Utils.getMessageFromCollection(possibleCauses, "\n")),
534                  INFO_ERROR_TITLE.get());
535            }
536            else
537            {
538              // Generic message
539              displayError(
540                  Utils.getMessageForException((NamingException)throwable),
541                  INFO_ERROR_TITLE.get());
542            }
543          }
544          else if (throwable instanceof ApplicationException)
545          {
546            displayError(((ApplicationException)throwable).getMessageObject(),
547                    INFO_ERROR_TITLE.get());
548          }
549          else
550          {
551            // This is a bug
552            logger.error(LocalizableMessage.raw("Unexpected throwable: "+throwable,
553                throwable));
554            displayError(
555                getThrowableMsg(INFO_BUG_MSG.get(), throwable),
556                INFO_ERROR_TITLE.get());
557          }
558          cancelButton.setEnabled(true);
559          okButton.setEnabled(true);
560        } else
561        {
562          if (Boolean.FALSE.equals(returnValue))
563          {
564            displayInformationMessage(
565                INFO_LOGIN_DIALOG_SERVER_NOT_RUNNING_MSG.get(),
566                INFO_LOGIN_DIALOG_SERVER_NOT_RUNNING_TITLE.get());
567          }
568          else
569          {
570            String hostName = tfHostName.getText();
571            if (hostName == null || hostName.trim().length() == 0)
572            {
573              displayError(INFO_EMPTY_REMOTE_HOST.get(),
574                  INFO_ERROR_TITLE.get());
575              UIFactory.setTextStyle(lHostName,
576                  UIFactory.TextStyle.PRIMARY_FIELD_INVALID);
577            }
578            else
579            {
580              UIFactory.setTextStyle(lHostName,
581                UIFactory.TextStyle.PRIMARY_FIELD_VALID);
582            }
583          }
584          UIFactory.setTextStyle(lUid,
585              UIFactory.TextStyle.PRIMARY_FIELD_VALID);
586          UIFactory.setTextStyle(lPwd,
587              UIFactory.TextStyle.PRIMARY_FIELD_VALID);
588
589          isCanceled = false;
590          cancelButton.setEnabled(true);
591          okButton.setEnabled(true);
592          dispose();
593        }
594      }
595    };
596    cancelButton.setEnabled(false);
597    okButton.setEnabled(false);
598    worker.startBackgroundTask();
599  }
600
601  /**
602   * Displays an error message dialog.
603   *
604   * @param msg
605   *          the error message.
606   * @param title
607   *          the title for the dialog.
608   */
609  private void displayError(LocalizableMessage msg, LocalizableMessage title)
610  {
611    Utilities.displayError(parent, msg, title);
612    toFront();
613
614  }
615
616  /**
617   * Displays an information message dialog.
618   *
619   * @param msg
620   *          the information message.
621   * @param title
622   *          the title for the dialog.
623   */
624  private void displayInformationMessage(LocalizableMessage msg, LocalizableMessage title)
625  {
626    Utilities.displayInformationMessage(parent, msg, title);
627    toFront();
628  }
629
630  /**
631   * Returns whether the server is running or not.
632   * @return <CODE>true</CODE> if the server is running and <CODE>false</CODE>
633   * otherwise.
634   */
635  private boolean isServerRunning()
636  {
637    return Installation.getLocal().getStatus().isServerRunning();
638  }
639
640  /**
641   * Returns the trust manager that can be used to establish secure connections.
642   * @return the trust manager that can be used to establish secure connections.
643   */
644  private ApplicationTrustManager getTrustManager()
645  {
646    return trustManager;
647  }
648
649  /**
650   * Displays a dialog asking the user to accept a certificate if the user
651   * accepts it, we update the trust manager and simulate a click on "OK" to
652   * re-check the authentication.
653   * This method assumes that we are being called from the event thread.
654   */
655  private void handleCertificateException(UserDataCertificateException ce)
656  {
657    CertificateDialog dlg = new CertificateDialog(parent, ce);
658    dlg.pack();
659    dlg.setVisible(true);
660    if (dlg.getUserAnswer() != CertificateDialog.ReturnType.NOT_ACCEPTED)
661    {
662      X509Certificate[] chain = ce.getChain();
663      String authType = ce.getAuthType();
664      String host = ce.getHost();
665
666      if (chain != null && authType != null && host != null)
667      {
668        logger.info(LocalizableMessage.raw("Accepting certificate presented by host "+host));
669        getTrustManager().acceptCertificate(chain, authType, host);
670        /* Simulate a click on the OK by calling in the okClicked method. */
671        SwingUtilities.invokeLater(new Runnable()
672        {
673          @Override
674          public void run()
675          {
676            okClicked();
677          }
678        });
679      }
680      else
681      {
682        if (chain == null)
683        {
684          logger.warn(LocalizableMessage.raw(
685              "The chain is null for the UserDataCertificateException"));
686        }
687        if (authType == null)
688        {
689          logger.warn(LocalizableMessage.raw(
690              "The auth type is null for the UserDataCertificateException"));
691        }
692        if (host == null)
693        {
694          logger.warn(LocalizableMessage.raw(
695              "The host is null for the UserDataCertificateException"));
696        }
697      }
698    }
699    if (dlg.getUserAnswer() ==
700      CertificateDialog.ReturnType.ACCEPTED_PERMANENTLY)
701    {
702      X509Certificate[] chain = ce.getChain();
703      if (chain != null)
704      {
705        try
706        {
707          UIKeyStore.acceptCertificate(chain);
708        }
709        catch (Throwable t)
710        {
711          logger.warn(LocalizableMessage.raw("Error accepting certificate: "+t, t));
712        }
713      }
714    }
715  }
716
717  /**
718   * Method written for testing purposes.
719   * @param args the arguments to be passed to the test program.
720   */
721  public static void main(String[] args)
722  {
723    try
724    {
725      LoginDialog dlg = new LoginDialog(
726          org.opends.guitools.controlpanel.util.Utilities.createFrame(),
727          new ApplicationTrustManager(null),
728          5000);
729      dlg.pack();
730      dlg.setVisible(true);
731    } catch (Exception ex)
732    {
733      ex.printStackTrace();
734    }
735  }
736}