protected void renumberProject() throws Exception {
    Session session = SessionFactory.getInstance().getSession(false);
    // renumber tasks
    Map<Long, Long> idMap = new HashMap<Long, Long>();
    for (TaskData task : (Collection<TaskData>) projectData.getTasks()) {
      long oldUniqueId = task.getUniqueId();
      long uniqueId = session.getId();
      task.setUniqueId(uniqueId);
      idMap.put(oldUniqueId, uniqueId);
      if (task.getAssignments() != null)
        for (AssignmentData assignment : (Collection<AssignmentData>) task.getAssignments()) {
          assignment.setTaskId(uniqueId);
        }
    }

    Collection<DistributionData> dists =
        (Collection<DistributionData>) projectData.getDistributions();
    if (dists != null)
      for (Iterator<DistributionData> i = dists.iterator(); i.hasNext(); ) {
        DistributionData dist = i.next();
        dist.setTaskId(idMap.get(dist.getTaskId()));
      }

    // renumber project
    projectData.setUniqueId(session.getId());
  }
  public GraphicManager instanceFromExistingSession(Container container, Map args) {
    this.args = args;

    System.gc(); // hope to avoid out of memory problems

    DebugUtils.isMemoryOk(true);

    long t = System.currentTimeMillis();
    System.out.println("---------- StartupFactory instanceFromExistingSession#1");
    final GraphicManager graphicManager = new GraphicManager(container);
    graphicManager.setStartupFactory(this);
    SessionFactory.getInstance().setJobQueue(graphicManager.getJobQueue());
    // if (Environment.isNewLook())
    graphicManager.initLookAndFeel();
    //		System.out.println("---------- StartupFactory instanceFromExistingSession#1 done in
    // "+(System.currentTimeMillis()-t)+" ms");
    final Map appletArgs = args;
    SwingUtilities.invokeLater(
        new Runnable() {

          public void run() {
            long t = System.currentTimeMillis();
            //				System.out.println("---------- StartupFactory instanceFromExistingSession#2");
            graphicManager.initView();
            //				System.out.println("---------- StartupFactory instanceFromExistingSession#2 done
            // in "+(System.currentTimeMillis()-t)+" ms");

            if (appletArgs != null) {
              String id = (String) appletArgs.get("projectId");
              if (id != null) projectId = Long.parseLong(id);
              if (id != null)
                doStartupAction(graphicManager, projectId, null, false, false, appletArgs);
            }
          }
        });
    //		graphicManager.invalidate();
    return graphicManager;
  }
  public static void clear(boolean graphic) {
    ProjectFactory.getInstance()
        .setPromptDisabled(true); // prevent remove projects job from prompting to save
    Job job =
        ProjectFactory.getInstance().getPortfolio().getRemoveAllProjectsJob(null, false, null);
    SessionFactory.getInstance().getLocalSession().schedule(job);
    try {
      job.waitResult();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if (graphic) {
      GraphicManager gm = GraphicManager.getInstance();
      if (gm != null) ((DefaultFrameManager) gm.getFrameManager()).cleanUp(false);
    }
    ProjectFactory.getInstance().getPortfolio().getObjectEventManager().removeAll();
    ProjectFactory.getInstance().setPromptDisabled(false); // enable prompting again

    // Singletons, most of them can cause problems when it re-used.
    // Other singletons shouldn't be problem but have a cleanUp method just in case
    SessionFactory.cleanUp();
    ProjectFactory.cleanUp();
    ResourcePoolFactory.cleanUp();
    UniqueIdPool.cleanUp();
    MainFrame.cleanUp();
    GraphicManager.cleanUpStatic();
    StartupFactory.cleanUpStatic();

    CalendarCatalog.cleanUp();
    CalendarDefinition.cleanUp();
    CalendarService.cleanUp();
    WorkingCalendar.cleanUp();

    AdvancedOption.cleanUp();
    CalculationOption.cleanUp();
    CalendarOption.cleanUp();
    EditOption.cleanUp();
    GanttOption.cleanUp();
    GeneralOption.cleanUp();
    ScheduleOption.cleanUp();
    TimesheetOption.cleanUp();

    FieldConverter.cleanUp();

    ActionLists.cleanUp();
    CellStyles.cleanUp();
    Configuration.cleanUp();
    Dictionary.cleanUp();

    Factory.cleanUp();
    ImportedCalendarService.cleanUp(); // remove dep
    NotAssignmentFilter.cleanUp();
    NotVoidFilter.cleanUp();
    HelpUtil.cleanUp();
    ZeroFunctor.cleanUp();
    NameCellComponent.cleanUp();
    ScheduleService.cleanUp();
    PageSizes.cleanUp();
    ContextStore.cleanUp();
    CustomFieldsMapper.cleanUp(); // remove dep
  }
  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 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 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;
  }