public boolean doLogin(GraphicManager graphicManager) {

    if (Environment.isNoPodServer()) {
      Environment.setNewLook(true);
      log.info("Login POD Server.");
    }
    if (Environment.getStandAlone() || Environment.isNoPodServer()) {
      if (!Environment.isNoPodServer()) {
        Environment.setUser(new DefaultUser());
        log.info("Locale user.");
      }
      return true;
    }
    credentials.put("serverUrl", serverUrl);
    getCredentials();
    Environment.setNewLook(true);

    int badLoginCount = 0;
    while (true) { // until a good login or exit because of too many bad
      //			graphicManager.getFrame().setVisible(true);
      if (login == null || password == null || badLoginCount > 0) {
        URL loginUrl = null;
        if (login == null || password == null) {
          try {
            loginUrl = new URL(serverUrl + "/login");
            System.out.println("trying login at " + serverUrl + "/login");
          } catch (MalformedURLException e) {
          }
        }
        LoginForm form =
            LoginDialog.doLogin(graphicManager.getFrame(), loginUrl); // it's actually a singleton
        if (form.isCancelled()) System.exit(-1);
        if (form.isUseMenus()) Environment.setNewLook(false);

        login = form.getLogin();
        password = form.getPassword();
      }

      if ("_SA".equals(login) || Environment.getStandAlone()) { // for testing purposes!
        Environment.setStandAlone(true);
        Environment.setUser(new DefaultUser());
        break;
      } else {
        credentials.put("login", login);
        credentials.put("password", password);

        SessionFactory.getInstance().setCredentials(credentials);
        try {
          Session session = SessionFactory.getInstance().getSession(false);
          System.out.println("logging in");
          final GraphicManager gm = graphicManager;
          SessionFactory.callNoEx(
              session,
              "login",
              new Class[] {Closure.class},
              new Object[] {
                new Closure() {
                  public void execute(Object arg0) {
                    Map<String, String> env = (Map<String, String>) arg0;
                    if (env != null) {
                      String serverVersion = env.get("serverVersion");
                      checkServerVersion(serverVersion);
                    }
                    if (gm != null) gm.setConnected(true);
                  }
                }
              });
          if (!((Boolean) SessionFactory.callNoEx(session, "isLicensedToRunClient", null, null))
              .booleanValue()) {
            Alert.error(Messages.getString("Error.roleCantRunClient"));
            abort();
            return false;
          }

          //					System.out.println("Application started with args: credentials=" +
          // credentials.get("login") + " name " + session.getUser().getName() + " Roles " +
          // session.getUser().getServerRoles());
          break;
          //			TODO test if login is valid.  If not, reshow login dialog
        } catch (Exception e) {
          if (Session.EXPIRED.equals(e.getMessage())) {
            Alert.error(Messages.getString("Error.accountExpired"));
            abort();
            return false;
          }
          System.out.println("failure " + e);
          badLoginCount++;
          SessionFactory.getInstance().clearSessions();

          if (badLoginCount == NUM_INVALID_LOGINS) {
            Alert.error(Messages.getString("Login.tooManyBad"));
            abort();
            return false;
          } else {
            Alert.error(Messages.getString("Login.error"));
          }
        }
      }
    }
    return true;
  }
  public void doStartupAction(
      final GraphicManager gm,
      final long projectId,
      final String[] projectUrls,
      final boolean welcome,
      boolean readOnly,
      final Map<String, String> args) {
    this.args = args;
    log.debug("Start up action: " + projectId);
    if (Environment.isClientSide() && !Environment.isTesting()) {
      log.debug("Start up action: A");
      if (projectId > 0) {
        log.debug("Start up action: B");

        Boolean writable = null;
        if (readOnly) writable = Boolean.FALSE;
        else writable = verifyOpenWritable(projectId);
        if (writable == null) return;
        AssignmentService.getInstance().setSubstituting(args.get("oldResourceId") != null);
        log.info("Load document: " + projectUrls);
        gm.loadDocument(
            projectId,
            true,
            !writable,
            new Closure() {
              public void execute(Object arg0) {
                log.debug("Start up action: D");
                Project project = (Project) arg0;
                DocumentFrame frame = gm.getCurrentFrame();
                if (frame != null && frame.getProject().getUniqueId() != projectId) {
                  log.debug("Start up action: E");

                  gm.switchToProject(projectId);
                }
                log.debug("Start up action: F");
                if (args.get("oldResourceId") != null) { // see if need to substitute
                  // JGao 6/3/2009 Need to set initial ids to make sure before doing resource
                  // substitution
                  if (project.getInitialTaskIds() == null) project.setInitialIds();
                  final long oldResourceId = Long.parseLong(args.get("oldResourceId"));
                  final long newResourceId = Long.parseLong(args.get("newResourceId"));
                  final Date startingFrom = DateTime.parseZulu(args.get("startingFrom"));
                  final int[] taskIds =
                      StringList.parseAsIntArray(args.get("commaSeparatedTaskIds"));
                  AssignmentService.getInstance()
                      .replaceResource(
                          projectId, oldResourceId, newResourceId, startingFrom, taskIds);
                  if (GraphicManager.getInstance() != null)
                    GraphicManager.getInstance().setEnabledDocumentMenuActions(true);
                  args.put("oldResourceId", null); // avoid doing again
                  AssignmentService.getInstance().setSubstituting(false);
                  log.debug("Start up action: G");
                }
              }
            });
      } else if (projectUrls != null && projectUrls.length > 0) {
        log.info("Load document: " + projectUrls[0]);
        gm.loadLocalDocument(projectUrls[0], !Environment.getStandAlone(), true);
      }
    }
    if (serverUrl != null) {
      if (opts.get("auth") != null) {
        String username = (String) ((LinkedList) opts.get("auth")).get(1);
        String password = (String) ((LinkedList) opts.get("auth")).get(2);
        TracImporter importer = new TracImporter(serverUrl, username, password);
        String msg = importer.checkConnection();
        if (msg != null) {}

        try {
          importer.importByQuery("status!=close");
        } catch (XmlRpcException e) {
          e.printStackTrace();
        }
        Project project = importer.getProject();
        String HTTP_PREFIX = "http://";

        project.setFileName(
            HTTP_PREFIX
                + username
                + ":"
                + password
                + "@"
                + serverUrl.substring(HTTP_PREFIX.length()));

        project.initialize(false, false);
        project.setBoundsAfterReadProject();

        Environment.setImporting(false);
        project.setWasImported(true);

        final Session session = SessionFactory.getInstance().getSession(true);
        session.refreshMetadata(project);
        session.readCurrencyData(project);
        return;

      } else {
        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                if (Environment.isOpenProj() && !Environment.isPlugin()) {
                  //							LicenseDialog.showDialog(gm.getFrame(),false);
                  UserInfoDialog.showDialog(gm.getFrame(), false);
                  //							TryPODDialog.maybeShow(gm.getFrame(),false);
                  //							UpdateChecker.checkForUpdateInBackground();
                }
                if (welcome && !Environment.isPlugin()) {
                  if (Environment.isOpenProj()) {
                    // LicenseDialog.showDialog(gm.getFrame(),false);
                    // TipOfTheDay.showDialog(gm.getFrame(), false);
                  } else {
                    if (Environment.isNeedToRestart()) return;
                    if (!LafManagerImpl
                        .isLafOk()) // for startup glitch - we don't want people to work until
                                    // restarting.
                    return;

                    //
                    //								String lastVersion =
                    // Preferences.userNodeForPackage(StartupFactory.class).get("lastVersion","0");
                    //								String thisVersion = VersionUtils.getVersion();
                    //								System.out.println("last version " + lastVersion + " this version " +
                    // thisVersion);
                    //								if (!lastVersion.equals(thisVersion)) {
                    //
                    //	Preferences.userNodeForPackage(StartupFactory.class).put("lastVersion",thisVersion);
                    //									String javaVersion = System.getProperty("java.version");
                    //									if (javaVersion.equals("1.6.0_04") || javaVersion.equals("1.6.0_05"))
                    //										Alert.warn("Project-ON-Demand has been updated.  Please close your
                    // browser completely and restart it to complete the upgrade process.");
                    //									return;
                    //								}

                  }
                  gm.doWelcomeDialog();
                }
                if (Environment.isPlugin()) gm.doNewProjectNoDialog(opts);
              }
            });
      }
    }
  }
  public GraphicManager instanceFromNewSession(Container container, boolean doWelcome) {

    //		DebugUtils.dumpStack("instanceFromNewSession being called ");
    VersionUtils.versionCheck(true);
    if (!VersionUtils.isJnlpUpToDate())
      System.out.println(
          "Jnlp isn't up to date, current version is: " + VersionUtils.getJnlpVersion());
    long t = System.currentTimeMillis();
    log.info("New session");
    Environment.setClientSide(true);

    System.setSecurityManager(null);
    Thread loadConfigThread =
        new Thread("loadConfig") {
          public void run() {
            long t = System.currentTimeMillis();
            doLoadConfig();
          }
        };
    loadConfigThread.start();

    GraphicManager graphicManager = GraphicManager.getInstance(); // normally null, unless reinit
    boolean recycling = graphicManager != null;
    // String projectUrl[]=null;
    try {
      if (Environment.isNoPodServer() || graphicManager == null) {
        graphicManager = new GraphicManager(/*projectUrl,*/ serverUrl, container);
        graphicManager.setStartupFactory(this);
      } else {
        reinitialize();
      }
    } catch (HeadlessException e) {
      e.printStackTrace();
    }
    graphicManager.setConnected(false);

    if (!doLogin(graphicManager)) return null;
    // if (Environment.isNewLook())
    if (Environment.isNoPodServer() || !recycling) graphicManager.initLookAndFeel();

    SessionFactory.getInstance().setJobQueue(graphicManager.getJobQueue());

    PartnerInfo partnerInfo = null;
    if (!Environment.getStandAlone() && !Environment.isNoPodServer()) {
      Session session = SessionFactory.getInstance().getSession(false);
      try {
        partnerInfo = (PartnerInfo) SessionFactory.call(session, "retrievePartnerInfo", null, null);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    //		System.out.println("---------- StartupFactory instanceFromNewSession#1 main done in
    // "+(System.currentTimeMillis()-t)+" ms");
    try {
      loadConfigThread.join();
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    }

    t = System.currentTimeMillis();
    //		System.out.println("---------- StartupFactory instanceFromNewSession#2");

    // graphicManager.showWaitCursor(true); //TODO use a progress bar - maybe a Job
    if (partnerInfo != null) {

      if (partnerInfo.getConfigurationXML() != null) {
        ConfigurationReader.readString(
            partnerInfo.getConfigurationXML(), Configuration.getInstance());
        Configuration.getInstance().setDonePopulating();
      }
      if (partnerInfo.getViewXML() != null) {
        ConfigurationReader.readString(partnerInfo.getViewXML(), Dictionary.getInstance());
      }
    }

    final GraphicManager gm = graphicManager;
    graphicManager.beginInitialization();
    try {

      graphicManager.initView();

      doStartupAction(
          graphicManager,
          projectId,
          (projectUrls == null && gm.getLastFileName() != null)
              ? new String[] {gm.getLastFileName()}
              : projectUrls,
          doWelcome,
          false,
          args);

      doPostInitView(graphicManager.getContainer());
      // graphicManager.getContainer().applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    } finally {
      graphicManager.finishInitialization();
    }
    instanceFromNewSessionDone = true;
    return graphicManager;
  }