PageRenderTime 384ms CodeModel.GetById 71ms app.highlight 222ms RepoModel.GetById 79ms app.codeStats 0ms

/src/mpv5/Main.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 1131 lines | 876 code | 129 blank | 126 comment | 127 complexity | 0599650cc5fb32530f702b9c42bd224c MD5 | raw file
   1/*
   2 *  This file is part of YaBS.
   3 *
   4 *      YaBS is free software: you can redistribute it and/or modify
   5 *      it under the terms of the GNU General Public License as published by
   6 *      the Free Software Foundation, either version 3 of the License, or
   7 *      (at your option) any later version.
   8 *
   9 *      YaBS is distributed in the hope that it will be useful,
  10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
  11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12 *      GNU General Public License for more details.
  13 *
  14 *      You should have received a copy of the GNU General Public License
  15 *      along with YaBS.  If not, see <http://www.gnu.org/licenses/>.
  16 */
  17package mpv5;
  18
  19import java.io.IOException;
  20import java.util.logging.Level;
  21import java.util.logging.Logger;
  22import mpv5.db.common.NodataFoundException;
  23import mpv5.db.common.ReturnValue;
  24import mpv5.logging.*;
  25import org.jdesktop.application.SingleFrameApplication;
  26import com.l2fprod.common.swing.plaf.LookAndFeelAddons;
  27import enoa.connection.NoaConnection;
  28import enoa.connection.NoaConnectionLocalServer;
  29import enoa.handler.TemplateHandler;
  30import java.awt.Color;
  31import java.awt.Cursor;
  32import java.awt.Font;
  33import java.io.File;
  34import java.net.HttpURLConnection;
  35import java.net.ServerSocket;
  36import java.net.Socket;
  37import java.net.URL;
  38import java.util.ArrayList;
  39import java.util.Date;
  40import java.util.Enumeration;
  41import java.util.List;
  42import java.util.Properties;
  43import javax.swing.ImageIcon;
  44import javax.swing.SwingUtilities;
  45import javax.swing.UIManager;
  46import mpv5.db.common.Context;
  47import mpv5.db.common.DatabaseConnection;
  48import mpv5.db.common.DatabaseObject;
  49import mpv5.db.common.DatabaseObjectLock;
  50import mpv5.db.common.QueryHandler;
  51import mpv5.db.objects.Template;
  52import mpv5.globals.Constants;
  53import mpv5.globals.LocalSettings;
  54import mpv5.globals.Messages;
  55import mpv5.pluginhandling.YabsPluginLoader;
  56import mpv5.ui.dialogs.Popup;
  57import mpv5.ui.dialogs.SplashScreen;
  58import mpv5.ui.dialogs.Wizard;
  59
  60import mpv5.db.objects.User;
  61import mpv5.db.objects.ValueProperty;
  62import mpv5.globals.GlobalSettings;
  63import mpv5.handler.Scheduler;
  64import mpv5.i18n.LanguageManager;
  65import mpv5.pluginhandling.UserPlugin;
  66import mpv5.server.MPServer;
  67import mpv5.ui.dialogs.LoginToInstanceScreen;
  68import mpv5.ui.dialogs.Notificator;
  69import mpv5.ui.dialogs.Search2;
  70import mpv5.ui.dialogs.subcomponents.ControlPanel_Fonts;
  71import mpv5.ui.dialogs.subcomponents.wizard_DBSettings_simple_1;
  72import mpv5.ui.frames.MPView;
  73import mpv5.usermanagement.MPSecurityManager;
  74import mpv5.utils.files.FileDirectoryHandler;
  75import mpv5.utils.files.FileExecutor;
  76import mpv5.utils.files.FileMonitor;
  77import mpv5.utils.files.FileReaderWriter;
  78import mpv5.utils.print.PrintJob2;
  79import mpv5.utils.reflection.ClasspathTools;
  80import mpv5.utils.text.RandomText;
  81import mpv5.webshopinterface.WSIManager;
  82import org.jdesktop.application.FrameView;
  83
  84/**
  85 * The main class of the application.
  86 */
  87public class Main implements Runnable {
  88
  89    public static SplashScreen splash;
  90    private static boolean removeplugs = false;
  91    /**
  92     * Is true if the application is running, false if in editor
  93     */
  94    public static boolean INSTANTIATED = false;
  95    private static Integer FORCE_INSTALLER;
  96    public static boolean HEADLESS = false;
  97    public static String WINDOW_TITLE = Constants.VERSION;
  98    public static int SINGLE_PORT = 65531;
  99
 100    /**
 101     * Use this method to (re) cache data from the database to avoid unnecessary
 102     * db queries
 103     */
 104    public static void cache() {
 105        Runnable runnable = new Runnable() {
 106
 107            @Override
 108            public void run() {
 109                Log.Debug(Main.class, Messages.CACHE);
 110                User.cacheUser();
 111                Log.Debug(Main.class, Messages.CACHED_OBJECTS + ": " + Context.getUser());
 112                LanguageManager.getCountriesAsComboBoxModel();
 113                Log.Debug(Main.class, Messages.CACHED_OBJECTS + ": " + Context.getCountries());
 114            }
 115        };
 116        new Thread(runnable).start();
 117//        Account.cacheAccounts();//pre cache accounts
 118//        YabsView.addMessage(Messages.CACHED_OBJECTS + ": " + Context.getAccounts());
 119//        DatabaseObject.cacheObjects();//Is called by User.login() later
 120    }
 121
 122    /**
 123     * Add the processes to close on exit
 124     *
 125     * @param officeApplication
 126     */
 127    public static void addProcessToClose(Process application) {
 128        oap.add(application);
 129    }
 130    private static List<Process> oap = new ArrayList<Process>();
 131
 132    private static boolean readLocalSettings() throws Exception {
 133        splash.nextStep(Messages.LOCAL_SETTINGS.toString());
 134        try {
 135            LocalSettings.read();
 136            LocalSettings.apply();
 137            Log.Print("Done with local settings file: " + LocalSettings.getLocalFile());
 138            return true;
 139        } catch (Exception ex) {
 140            Log.Print(ex.getMessage());
 141            Log.Print("Local settings file not readable: " + LocalSettings.getLocalFile());
 142            return false;
 143        }
 144    }
 145
 146    private static void readGlobalSettings() {
 147        try {
 148            GlobalSettings.read();
 149        } catch (Exception ex) {
 150            Log.Debug(Main.class, ex);
 151        }
 152    }
 153
 154    public static void readImports() {
 155        splash.nextStep(Messages.IMPORT_LANGUAGES.toString());
 156        File ilang = new File(Constants.LANGUAGES_DIR);
 157        try {
 158            Log.Debug(Main.class, "Checking: " + ilang.getPath());
 159            if (ilang.isDirectory() && ilang.canRead()) {
 160                File[] languages = FileDirectoryHandler.getFilesOfDirectory(ilang);
 161                for (int i = 0; i < languages.length; i++) {
 162                    File file = languages[i];
 163                    if (QueryHandler.instanceOf().clone(Context.getLanguage()).checkUniqueness("longname", file.getName())) {
 164                        try {
 165                            Log.Debug(Main.class, "Importing: " + file.getPath());
 166                            String lang = LanguageManager.importLanguage(file.getName(), file);
 167                            if (lang != null && Popup.Y_N_dialog(Messages.IMPORT_LANGUAGES_DONE)) {//TODO: l10n
 168                                User u = (User) Search2.showSearchFor(Context.getUser());
 169                                if (u != null) {
 170                                    u.setLanguage(lang);
 171                                    u.save();
 172                                    Popup.notice(Messages.DONE);
 173                                }
 174                            }
 175                        } catch (Exception exception) {
 176                            Log.Debug(exception);
 177                        }
 178                    }
 179                    file.deleteOnExit();
 180                }
 181            }
 182        } catch (Exception e) {
 183            Log.Debug(e);
 184            Popup.error(e);
 185        }
 186
 187        splash.nextStep(Messages.IMPORT_TEMPLATES.toString());
 188        File itemp = new File(Constants.TEMPLATES_DIR);
 189        try {
 190            Log.Debug(Main.class, "Checking: " + itemp.getPath());
 191            boolean imp = false;
 192            if (itemp.isDirectory() && itemp.canRead()) {
 193                File[] templates = FileDirectoryHandler.getFilesOfDirectory(itemp);
 194                for (int i = 0; i < templates.length; i++) {
 195                    File file = templates[i];
 196                    Log.Debug(Main.class, "Importing: " + file.getPath());
 197                    if (TemplateHandler.importTemplate(file)) {
 198                        imp = true;
 199                    }
 200                    file.deleteOnExit();
 201                }
 202                if (imp) {
 203                    Popup.notice(Messages.IMPORT_TEMPLATES_DONE);
 204                }
 205            }
 206        } catch (Exception e) {
 207            Log.Debug(e);
 208            Popup.error(e);
 209        }
 210
 211        splash.nextStep(Messages.IMPORT_PLUGINS.toString());
 212        File iplug = new File(Constants.PLUGINS_DIR);
 213        try {
 214            Log.Debug(Main.class, "Checking: " + iplug.getPath());
 215            if (iplug.isDirectory() && iplug.canRead()) {
 216                File[] plugins = FileDirectoryHandler.getFilesOfDirectory(iplug);
 217                for (int i = 0; i < plugins.length; i++) {
 218                    File file = plugins[i];
 219                    Log.Debug(Main.class, "Importing: " + file.getPath());
 220                    YabsPluginLoader.importPlugin(file.getName(), file);
 221                    Popup.notice(Messages.IMPORT_PLUGINS_DONE);//TODO: l10n
 222
 223                    file.deleteOnExit();
 224                }
 225            }
 226        } catch (Exception e) {
 227            Log.Debug(e);
 228            Popup.error(e);
 229        }
 230
 231    }
 232
 233    private static void runStartScripts() {
 234        if (User.PROPERTIES_OVERRIDE.hasProperty("startupcommand")) {
 235            try {
 236                FileExecutor.run(User.PROPERTIES_OVERRIDE.getProperty("startupcommand"));
 237            } catch (Exception e) {
 238                Log.Debug(e);
 239            }
 240        }
 241    }
 242
 243    public static void extStart(Class<YabsApplication> app, Class<MPView> view, String... args) throws Exception {
 244        APPLICATION_CLASS = app;
 245        VIEW_CLASS = view;
 246        main(args);
 247    }
 248
 249    /**
 250     * Launch the application
 251     */
 252    public static void start() {
 253
 254//        splash.nextStep(Messages.LAUNCH.toString());
 255        splash.nextStep(Messages.DBCONN_UPDATE_BEPATIENT.toString());
 256        Log.Debug(Main.class, "Trying to launch application now..");
 257        Runnable runnable = new Runnable() {
 258
 259            @Override
 260            @SuppressWarnings("unchecked")
 261            public void run() {
 262                try {
 263                    SingleFrameApplication.launch(APPLICATION_CLASS, new String[]{});
 264                } catch (Exception e) {
 265                    Log.Debug(e);
 266                }
 267            }
 268        };
 269        SwingUtilities.invokeLater(runnable);
 270    }
 271    /**
 272     * Indicates whether this is the first start of the application
 273     */
 274    public static boolean firstStart;
 275    /**
 276     * Sometimes it is nice to have a good goodbye message at hand ;-)<br/><br/>
 277     * <b>"So Long, and Thanks for All the Fish."</b>
 278     */
 279    public static final String GOODBYE_MESSAGE = "So Long, and Thanks for All the Fish.";
 280    /**
 281     * Indicates whether the server component shall start
 282     */
 283    public static boolean START_SERVER = false;
 284    /**
 285     * Indicates whether lib check shall be skipped
 286     */
 287    public static boolean SKIP_LIBCHECK = false;
 288    /**
 289     * Indicates whether template check shall be skipped
 290     */
 291    public static boolean SKIP_TPLCHECK = false;
 292    /**
 293     * The Yabs Application (JSAF)
 294     */
 295    public static Class<YabsApplication> APPLICATION_CLASS;
 296    /**
 297     * The Yabs View (JSAF FrameView)
 298     */
 299    public static Class<MPView> VIEW_CLASS;
 300
 301    /**
 302     * At startup create and show the main frame of the application.
 303     */
 304    public void startup() {
 305
 306        checkLibs();
 307        checkSingleInstance();
 308
 309        Log.Debug(this, "Startup procedure... ");
 310        getApplication().getContext().getLocalStorage().setDirectory(new File(LocalSettings.getProperty(LocalSettings.CACHE_DIR)));
 311
 312        splash.nextStep(Messages.FIRST_INSTANCE.toString());
 313        splash.nextStep(Messages.DB_CHECK.toString());
 314
 315        ControlPanel_Fonts.applyFont(Font.decode(LocalSettings.getProperty(LocalSettings.DEFAULT_FONT)));
 316        if (FORCE_INSTALLER == null) {
 317            Log.Debug(this, "Probing database connection... ");
 318            if (probeDatabaseConnection()) {
 319
 320                splash.nextStep(Messages.DBCONN_UPDATE_BEPATIENT.toString());
 321                QueryHandler.instanceOf();
 322
 323                readGlobalSettings();
 324                Log.Debug(this, "Loading Yabs... ");
 325                readImports();
 326
 327                Main.splash.nextStep(Messages.INIT_LOGIN.toString());
 328                try {
 329                    login();
 330                } catch (NodataFoundException nodataFoundException) {
 331                    Log.Debug(nodataFoundException);
 332                }
 333                Main.splash.nextStep(Messages.INIT_GUI.toString());
 334                if (!HEADLESS) {
 335                    try {
 336                        @SuppressWarnings("unchecked")
 337                        FrameView view = (FrameView) VIEW_CLASS.getDeclaredConstructor(SingleFrameApplication.class).newInstance(getApplication());
 338                        getApplication().setMainView(view);
 339                        getApplication().show(view);
 340
 341//                        Log.Print(Arrays.asList(getApplication().getMainView().getClass().getInterfaces()));
 342                    } catch (Exception ex) {
 343                        Log.Debug(ex);
 344                        System.exit(1);
 345                    }
 346                    YabsViewProxy.instance().register((YabsView) getApplication().getMainView());
 347                }
 348                go(false);
 349
 350                if (LocalSettings.getBooleanProperty(LocalSettings.OFFICE_LOCALSERVER)) {
 351                    final Thread startServerThread;
 352
 353                    Runnable runnable2 = new Runnable() {
 354
 355                        @Override
 356                        public void run() {
 357                            try {
 358                                Log.Debug(Main.class, "Starting OpenOffice as background service..");
 359                                NoaConnectionLocalServer.startOOServerIfNotRunning(LocalSettings.getProperty(LocalSettings.OFFICE_HOME), LocalSettings.getIntegerProperty(LocalSettings.OFFICE_PORT));
 360                            } catch (Exception n) {
 361                                Log.Debug(Main.class, n.getMessage());
 362                            }
 363                        }
 364                    };
 365                    startServerThread = new Thread(runnable2);
 366                    startServerThread.start();
 367                }
 368
 369            } else if (Popup.Y_N_dialog(splash, Messages.NO_DB_CONNECTION, Messages.FIRST_START.toString())) {
 370                Log.Debug(this, "Loading database config wizard...");
 371                if (!HEADLESS) {
 372                    splash.dispose();
 373                }
 374                showDbWiz(null);
 375            } else {
 376                Log.Debug(this, "Cancelled by user.");
 377                System.exit(1);
 378            }
 379        } else {
 380            Log.Debug(this, "Forced to start the database config wiz... ");
 381            showDbWiz(FORCE_INSTALLER);
 382        }
 383    }
 384
 385    public void shutdown() {
 386        if (Log.isDebugging()) {
 387            Log.Print(Messages.getMissing());
 388        }
 389
 390        if (!HEADLESS) {
 391            getApplication().getMainFrame().setCursor(new Cursor(Cursor.WAIT_CURSOR));
 392        }
 393
 394        DatabaseObjectLock.releaseAllObjectsFor(mpv5.db.objects.User.getCurrentUser());
 395        try {
 396            GlobalSettings.save();
 397            LocalSettings.save();
 398
 399            if (!mpv5.db.objects.User.getCurrentUser().isDefault()) {
 400
 401                try {
 402                    ValueProperty.addOrUpdateProperty("layoutinfo", User.getCurrentUser().getLayoutProperties(), User.getCurrentUser());
 403                } catch (Exception ex) {
 404                    Log.Debug(ex);
 405                }
 406
 407                try {
 408                    if (User.getCurrentUser().getProperties().hasProperty("shutdowncommand")) {
 409                        String commands = User.getCurrentUser().getProperties().getProperty("shutdowncommand");
 410                        FileExecutor.run(commands);
 411                    }
 412                } catch (Exception ex) {
 413                    Log.Debug(ex);
 414                }
 415                mpv5.db.objects.User.getCurrentUser().logout();
 416            }
 417            NoaConnection.killConnection();
 418            for (int i = 0; i < oap.size(); i++) {
 419                Process p = oap.get(i);
 420                try {
 421                    Log.Debug(this, "Killing process: " + p);
 422                    p.destroy();
 423                    p.waitFor();
 424                } catch (Exception n) {
 425                    Log.Debug(this, n);
 426                }
 427            }
 428        } catch (Exception e) {
 429            Log.Debug(e);
 430        }
 431
 432        if (Log.getLoglevel() == Log.LOGLEVEL_DEBUG) {
 433//            Log.Debug(Main.class, QueryHandler.instanceOf().getStatistics());
 434        }
 435        Log.Print(GOODBYE_MESSAGE);
 436
 437        try {
 438            //Cleanup
 439            FileDirectoryHandler.deleteDirectoryContent2(new File(FileDirectoryHandler.getTempDir2()), ".properties", ".xml");
 440        } catch (IOException ex) {
 441        }
 442    }
 443
 444    /**
 445     * Main method launching the application.
 446     *
 447     * @param args
 448     * @throws Exception
 449     */
 450    public static void main(String[] args) throws Exception {
 451
 452        INSTANTIATED = true;
 453        if (APPLICATION_CLASS == null) {//fallback
 454            APPLICATION_CLASS = YabsApplication.class;
 455        }
 456        if (VIEW_CLASS == null) {//fallback
 457            VIEW_CLASS = MPView.class;
 458        }
 459
 460        try {
 461            splash = new SplashScreen(new ImageIcon(Main.class.getResource(mpv5.globals.Constants.SPLASH_IMAGE)));
 462            splash.init(12);
 463            Log.Print(Messages.START_MESSAGE);
 464            splash.nextStep(Messages.INIT.toString());
 465
 466            getOS();
 467            setEnv(null);
 468            parseArgs(args);
 469            runStartScripts();
 470            if (readLocalSettings()) {
 471                LanguageManager.preLoadCachedLanguage();
 472            }
 473            setDerbyLog();
 474            start();
 475        } catch (Exception e) {
 476            Popup.error(null, e);
 477            System.exit(1);
 478        }
 479    }
 480    /**
 481     * The path for db, cache, session files
 482     */
 483    public static String MPPATH = null;
 484    /**
 485     * The local settings file
 486     */
 487    public static String SETTINGS_FILE = null;
 488    /**
 489     * The user home directory
 490     */
 491    public static String USER_HOME = null;
 492    /**
 493     * A shortcut to the user desktop
 494     */
 495    public static String DESKTOP = null;
 496    private static boolean nolf = false;
 497    /**
 498     * True if MacOS X has been detected
 499     */
 500    public static boolean osIsMacOsX = false;
 501    /**
 502     * True if a Windows version has been detected
 503     */
 504    public static boolean osIsWindows = false;
 505    /**
 506     * True if a Linux distribution has been detected
 507     */
 508    public static boolean osIsLinux = false;
 509    /**
 510     * True if a Solaris distribution has been detected
 511     */
 512    public static boolean osIsSolaris = false;
 513
 514    private static void getOS() {
 515        String os = System.getProperty("os.name").toLowerCase();
 516        osIsMacOsX = "mac os x".equals(os);
 517        osIsWindows = os != null && os.indexOf("windows") != -1;
 518        osIsLinux = os != null && os.indexOf("linux") != -1;
 519        osIsSolaris = os != null && os.indexOf("solaris") != -1;
 520    }
 521
 522    /**
 523     * Set the dirs
 524     *
 525     * @param rootDir The root dir or null, defaults to: USER_HOME +
 526     * File.separator + ".yabs"
 527     */
 528    public static void setEnv(String rootDir) {
 529
 530        if (osIsWindows) {
 531            USER_HOME = System.getenv("USERPROFILE");
 532        } else {
 533            USER_HOME = System.getProperty("user.home");
 534        }
 535
 536        DESKTOP = USER_HOME + File.separator + "Desktop";
 537        if (rootDir == null) {
 538            MPPATH = USER_HOME + File.separator + ".yabs";
 539        } else {
 540            MPPATH = rootDir;
 541        }
 542        SETTINGS_FILE = Main.MPPATH + File.separator + "settings" + Constants.RELEASE_VERSION + ".yabs";
 543    }
 544
 545    private static void parseArgs(String[] args) {
 546
 547        org.apache.commons.cli2.builder.DefaultOptionBuilder obuilder = new org.apache.commons.cli2.builder.DefaultOptionBuilder();
 548        org.apache.commons.cli2.builder.ArgumentBuilder abuilder = new org.apache.commons.cli2.builder.ArgumentBuilder();
 549        org.apache.commons.cli2.builder.GroupBuilder gbuilder = new org.apache.commons.cli2.builder.GroupBuilder();
 550
 551        org.apache.commons.cli2.Argument option = abuilder.withName("option").withMinimum(1).withMaximum(1).create();
 552        org.apache.commons.cli2.Argument filearg = abuilder.withName("=file").withMinimum(1).withMaximum(1).create();
 553        org.apache.commons.cli2.Argument dirarg = abuilder.withName("directory").withMinimum(1).withMaximum(1).create();
 554        org.apache.commons.cli2.Argument number = abuilder.withName("number").withMinimum(1).withMaximum(1).create();
 555
 556        org.apache.commons.cli2.Option server = obuilder.withShortName("server").withShortName("serv").withDescription("start built-in server component").create();
 557        org.apache.commons.cli2.Option ignoreLibs = obuilder.withShortName("ignorelibs").withShortName("il").withDescription("ignore Libs checking").create();
 558        org.apache.commons.cli2.Option ignoreTpls = obuilder.withShortName("ignoretpls").withShortName("it").withDescription("ignore Templateupdate checking").create();
 559        org.apache.commons.cli2.Option showenv = obuilder.withShortName("showenv").withShortName("se").withDescription("show environmental variables").create();
 560        org.apache.commons.cli2.Option help = obuilder.withShortName("help").withShortName("h").withDescription("print this message").create();
 561        org.apache.commons.cli2.Option license = obuilder.withShortName("license").withShortName("li").withDescription("print license").create();
 562        org.apache.commons.cli2.Option version = obuilder.withShortName("version").withDescription("print the version information and exit").create();
 563        org.apache.commons.cli2.Option verbose = obuilder.withShortName("verbose").withDescription("be extra verbose").create();
 564        org.apache.commons.cli2.Option nolfs = obuilder.withShortName("nolf").withDescription("use java native metal L&F").create();
 565        org.apache.commons.cli2.Option debug = obuilder.withShortName("debug").withDescription("enable debug logging").create();
 566        org.apache.commons.cli2.Option removeplugins = obuilder.withShortName("removeplugins").withDescription("remove all plugins which would be loaded").create();
 567        org.apache.commons.cli2.Option removelangs = obuilder.withShortName("noi18n").withDescription("remove all languages which would be loaded").create();
 568        org.apache.commons.cli2.Option forceinstall = obuilder.withShortName("finstall").withDescription("force-install").create();
 569        org.apache.commons.cli2.Option logfile = obuilder.withShortName("logfile").withShortName("l").withDescription("use file for log").withArgument(filearg).create();
 570        org.apache.commons.cli2.Option mpdir = obuilder.withShortName("appdir").withShortName("dir").withShortName("path").withDescription("set the application main dir (used for caching, settings, temp files)").withArgument(dirarg).create();
 571        org.apache.commons.cli2.Option connectionInstance = obuilder.withShortName("connectionInstance").withShortName("conn").withDescription("use stored connection with this ID").withArgument(number).create();
 572        org.apache.commons.cli2.Option windowlog = obuilder.withShortName("windowlog").withDescription("enables logging to the MP Log Console").create();
 573        org.apache.commons.cli2.Option consolelog = obuilder.withShortName("consolelog").withDescription("enables logging to STDOUT").create();
 574        org.apache.commons.cli2.Option printtest = obuilder.withShortName("printtest").withDescription("test PDF printing").create();
 575        org.apache.commons.cli2.Option params = obuilder.withShortName("params").withDescription("optional parameters \"param1:value1;param2:value2..\"").withArgument(option).create();
 576
 577
 578        org.apache.commons.cli2.Group options = gbuilder.withName("options").
 579                withOption(help).
 580                withOption(version).
 581                withOption(verbose).
 582                withOption(debug).
 583                withOption(license).
 584                withOption(nolfs).
 585                withOption(showenv).
 586                withOption(removeplugins).
 587                withOption(removelangs).
 588                withOption(connectionInstance).
 589                withOption(logfile).
 590                withOption(server).
 591                withOption(windowlog).
 592                withOption(consolelog).
 593                withOption(mpdir).
 594                withOption(printtest).
 595                withOption(params).
 596                withOption(forceinstall).
 597                withOption(ignoreLibs).
 598                withOption(ignoreTpls).
 599                create();
 600
 601        org.apache.commons.cli2.util.HelpFormatter hf = new org.apache.commons.cli2.util.HelpFormatter();
 602        org.apache.commons.cli2.commandline.Parser p = new org.apache.commons.cli2.commandline.Parser();
 603        p.setGroup(options);
 604        p.setHelpFormatter(hf);
 605
 606        org.apache.commons.cli2.CommandLine cl = p.parseAndHelp(args);
 607
 608
 609
 610        if (cl == null) {
 611            Log.Print("Cannot parse arguments");
 612        } else {
 613            if (cl.hasOption(mpdir)) {
 614                setEnv(cl.getValue(mpdir).toString());
 615            }
 616
 617            if (cl.hasOption(connectionInstance)) {
 618                try {
 619                    if (!LocalSettings.hasConnectionID(Integer.valueOf(String.valueOf(cl.getValue(connectionInstance))))) {
 620                        FORCE_INSTALLER = Integer.valueOf(String.valueOf(cl.getValue(connectionInstance)));
 621                    }
 622                    Log.Debug(Main.class, "Switching connection id to: " + Integer.valueOf(String.valueOf(cl.getValue(connectionInstance))));
 623                    LocalSettings.setConnectionID(Integer.valueOf(String.valueOf(cl.getValue(connectionInstance))));
 624                } catch (Exception ex) {
 625                    Log.Debug(ex);
 626                }
 627            }
 628
 629            if (cl.hasOption(forceinstall)) {
 630                FORCE_INSTALLER = RandomText.getInteger();
 631            }
 632
 633            if (cl.hasOption(help)) {
 634                hf.print();
 635                System.exit(0);
 636            }
 637
 638            if (cl.hasOption(license)) {
 639                try {
 640                    System.out.print(new FileReaderWriter(new File(Main.class.getResource("/mpv5/resources/license/gpl-3").toURI())).read());
 641                } catch (Exception ex) {
 642                    Log.Debug(ex);
 643                }
 644            }
 645
 646            if (cl.hasOption(version)) {
 647                System.out.println("YABS Version: " + Constants.VERSION);
 648            }
 649
 650            if (cl.hasOption(verbose)) {
 651                Log.setLogLevel(Log.LOGLEVEL_NORMAL);
 652
 653            }
 654
 655            if (cl.hasOption(debug)) {
 656                Log.setLogLevel(Log.LOGLEVEL_DEBUG);
 657            }
 658
 659            if (cl.hasOption(logfile)) {
 660                if (String.valueOf(cl.getValue(logfile)).split("=").length != 2) {
 661                    Log.Debug(Main.class, "logfile must be specified (-logfile=file.log)!");
 662                } else {
 663                    try {
 664                        YConsole.setLogFile(((String) cl.getValue(logfile)).split("=")[1]);
 665                    } catch (Exception e) {
 666                        Log.Debug(Main.class, "Error while writing to: " + e.getMessage());
 667                    }
 668                }
 669            }
 670
 671            if (cl.hasOption(nolfs)) {
 672                Main.nolf = true;
 673            }
 674
 675            if (cl.hasOption(removeplugins)) {
 676                removeplugs = true;
 677            }
 678
 679            if (cl.hasOption(removelangs)) {
 680                LanguageManager.disableLanguages();
 681            }
 682
 683            if (cl.hasOption(showenv)) {
 684                printEnv();
 685            }
 686
 687            if (cl.hasOption(server)) {
 688                START_SERVER = true;
 689            }
 690
 691            if (cl.hasOption(ignoreLibs)) {
 692                SKIP_LIBCHECK = true;
 693            }
 694
 695            if (cl.hasOption(ignoreTpls)) {
 696                SKIP_TPLCHECK = true;
 697            }
 698
 699            YConsole.setLogStreams(cl.hasOption(logfile), cl.hasOption(consolelog), cl.hasOption(windowlog));
 700
 701            if (cl.hasOption(params)) {
 702                try {
 703                    String[] parameters = String.valueOf(cl.getValue(params)).replace("\"", "").split(";");
 704
 705                    for (int i = 0; i < parameters.length; i++) {
 706                        String[] opt = parameters[i].split(":");
 707                        String key = opt[0];
 708                        String val = opt[1];
 709                        User.PROPERTIES_OVERRIDE.addProperty(key, val);
 710                    }
 711                } catch (Exception exception) {
 712                    Log.Debug(exception);
 713                }
 714            }
 715
 716            if (cl.hasOption(printtest)) {
 717                try {
 718                    PrintJob2 printJob2 = new PrintJob2(new File("printer_test.pdf"), "pdf");
 719                    System.exit(0);
 720                } catch (Exception ex) {
 721                    Log.Debug(ex);
 722                    System.exit(0);
 723                }
 724            }
 725        }
 726
 727        if (cl != null) {
 728            Log.Print("\nOptions used:");
 729
 730            for (int idx = 0; idx
 731                    < cl.getOptions().size(); idx++) {
 732                Log.Print(cl.getOptions().get(idx));
 733            }
 734            Log.Print("\n");
 735        }
 736    }
 737
 738    /**
 739     * Redirect derby log file
 740     */
 741    public static void setDerbyLog() {
 742        Properties p = System.getProperties();
 743        try {
 744            File d = FileDirectoryHandler.getTempFile("derby");
 745            d.createNewFile();
 746            Log.Debug(Main.class, "Setting derby log to " + d.getPath());
 747            p.put("derby.stream.error.file", d.getPath());
 748//            p.setProperty("derby.drda.startNetworkServer", "true");
 749
 750        } catch (Exception ex) {
 751            Log.Debug(ex);
 752        }
 753    }
 754
 755    /**
 756     *
 757     * @param lafname
 758     */
 759    public static void setLaF(final String lafname) {
 760        if (!Main.nolf && !HEADLESS) {
 761            Runnable runnable = new Runnable() {
 762
 763                @Override
 764                public void run() {
 765                    try {
 766                        if (lafname != null) {
 767                            try {
 768                                Class.forName(lafname);
 769                            } catch (ClassNotFoundException ex) {
 770                                Log.Debug(Main.class, "Laf not valid here: " + lafname);
 771                                return;
 772                            }
 773                            UIManager.setLookAndFeel(lafname);
 774                        } else {
 775                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
 776                        }
 777                        LookAndFeelAddons.setAddon(LookAndFeelAddons.getBestMatchAddonClassName());
 778
 779                    } catch (Exception exe) {
 780                        try {
 781                            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
 782
 783                        } catch (Exception ex) {
 784                            Log.Debug(Main.class, ex);
 785                        }
 786                        Log.Debug(Main.class, exe);
 787                    }
 788                    try {
 789                        if (getApplication().isReady() && getApplication().getMainView().getFrame() != null && (getApplication().getMainView()).getFrame().isShowing()) {
 790                            SwingUtilities.updateComponentTreeUI((getApplication().getMainView()).getFrame());
 791                            ((YabsView) getApplication().getMainView()).getIdentifierFrame().validate();
 792                        }
 793                    } catch (Exception e) {
 794                        Log.Debug(Main.class, e.getMessage());
 795                    }
 796                }
 797            };
 798            SwingUtilities.invokeLater(runnable);
 799        }
 800    }
 801
 802    /**
 803     *
 804     */
 805    public static void printEnv() {
 806        Properties sysprops = System.getProperties();
 807        Enumeration propnames = sysprops.propertyNames();
 808
 809        while (propnames.hasMoreElements()) {
 810            String propname = (String) propnames.nextElement();
 811            Log.Debug(Main.class, "System env: " + propname.toUpperCase() + " : " + System.getProperty(propname));
 812        }
 813    }
 814
 815    /**
 816     *
 817     * @param firststart
 818     */
 819    public void go(boolean firststart) {
 820
 821        splash.nextStep(Messages.CACHE.toString());
 822        cache();
 823
 824        Main.splash.nextStep(Messages.INIT_PLUGINS.toString());
 825
 826        Runnable runnable = new Runnable() {
 827
 828            @Override
 829            public void run() {
 830                try {
 831                    loadPlugins();
 832                } catch (Exception e) {
 833                    Popup.error(e);
 834                }
 835            }
 836        };
 837        new Thread(runnable).start();
 838        splash.dispose();
 839
 840        if (!HEADLESS) {
 841            if (START_SERVER) {
 842                MPServer.runServer();
 843            }
 844        }
 845
 846        Runnable runnable3 = new Runnable() {
 847
 848            public void run() {
 849                WSIManager.instanceOf().start();
 850            }
 851        };
 852
 853        new Thread(runnable3).start();
 854
 855        if (!HEADLESS) {
 856            try {
 857                (new Scheduler()).start();
 858            } catch (Exception e) {
 859                Log.Debug(e);
 860            }
 861        }
 862
 863        if (!HEADLESS) {
 864            if (!LocalSettings.getBooleanProperty(LocalSettings.SUPPRESS_UPDATE_CHECK)) {
 865                Runnable runnable1 = new Runnable() {
 866
 867                    @Override
 868                    public void run() {
 869                        if (checkUpdates()) {
 870                            Notificator.raiseNotification(Messages.UPDATE_AVAILABLE, false);
 871                        }
 872                    }
 873                };
 874
 875                new Thread(runnable1).start();
 876            }
 877        }
 878
 879        if (!HEADLESS) {
 880            checkTpls();
 881        }
 882
 883    }
 884
 885    private void loadPlugins() {
 886        if (!HEADLESS) {
 887            if (!removeplugs) {
 888                try {
 889                    YabsPluginLoader.queuePlugins();
 890                    YabsPluginLoader.loadPlugins();
 891                } catch (Throwable e) {
 892                    Log.Debug(e);
 893                    Popup.notice("Plugin ERROR " + e);
 894                }
 895            } else {
 896                try {
 897                    List data = DatabaseObject.getReferencedObjects(mpv5.db.objects.User.getCurrentUser(), Context.getPluginsToUsers());
 898                    for (int i = 0; i < data.size(); i++) {
 899                        try {
 900                            ((UserPlugin) data.get(i)).delete();
 901                        } catch (Exception e) {
 902                            Log.Debug(e);
 903                        }
 904                    }
 905                } catch (NodataFoundException ex) {
 906                    Log.Debug(Main.class, ex.getMessage());
 907                }
 908            }
 909        }
 910    }
 911
 912    private void login() throws NodataFoundException {
 913        if (!LocalSettings.getProperty("lastuser").equals("INSTANCE")) {
 914            User usern1 = new User();
 915            Log.Debug(this, "Checking for auto login.. ");
 916
 917            try {
 918                if (usern1.fetchDataOf(Integer.valueOf(LocalSettings.getProperty("lastuser")))) {
 919                    Log.Debug(this, "Trying to login user: " + usern1);
 920                    User user = mpv5.usermanagement.MPSecurityManager.checkAuthInternal(usern1, LocalSettings.getProperty("lastuserpw"));
 921                    Log.Debug(this, "Found user: " + user);
 922                    if (user != null) {
 923                        user.login();
 924                    } else {
 925                        LoginToInstanceScreen.load();
 926                    }
 927                }
 928            } catch (Exception nodataFoundException) {
 929                LoginToInstanceScreen.load();
 930            }
 931        } else {
 932            LoginToInstanceScreen.load();
 933        }
 934    }
 935
 936    private boolean probeDatabaseConnection() {
 937        try {
 938            DatabaseConnection.instanceOf();
 939            Log.Debug(this, "Connected to database: " + DatabaseConnection.instanceOf().getCtype().getURL());
 940            return true;
 941        } catch (Exception ex) {
 942            Log.Debug(this, "Could not connect to database: " + ex);
 943            return false;
 944        }
 945    }
 946
 947    private boolean firstInstance() {
 948        return true;
 949    }
 950
 951    private void showDbWiz(Integer forConnId) {
 952        try {
 953            Log.setLogLevel(Log.LOGLEVEL_DEBUG);
 954            YConsole.setLogFile("install.log");
 955            Log.Debug(this, new Date());
 956
 957        } catch (Exception ex) {
 958            mpv5.logging.Log.Debug(ex);//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
 959        }
 960        try {
 961            User u = User.DEFAULT;
 962            u.setInthighestright(MPSecurityManager.RIGHT_TO_CREATE_OR_DELETE);
 963            User._setUser(User.DEFAULT);
 964        } catch (Exception e) {
 965            Log.Debug(e);
 966        }
 967
 968        Wizard w = new Wizard(true);
 969        w.addPanel(new wizard_DBSettings_simple_1(w, forConnId));
 970        w.showWiz();
 971    }
 972
 973    /**
 974     * Checks if updates are available
 975     */
 976    private boolean checkUpdates() {
 977
 978        try {
 979            //Just a basic check
 980            HttpURLConnection.setFollowRedirects(true);
 981            HttpURLConnection con =
 982                    (HttpURLConnection) new URL(Constants.CURRENT_VERSION_URL).openConnection();
 983            con.setRequestMethod("GET");
 984            // When the available version is not the current version, we assume there is an update available
 985            Log.Debug(Main.class, Constants.CURRENT_VERSION_URL + " " + con.getResponseMessage());
 986
 987            return (con.getResponseCode() != HttpURLConnection.HTTP_OK);
 988        } catch (Exception e) {
 989            Log.Debug(Main.class, e.getMessage());
 990            //When we cant reach it at all, no update presumably
 991            return false;
 992        }
 993    }
 994
 995    @SuppressWarnings("unchecked")
 996    public static SingleFrameApplication getApplication() {
 997        return (SingleFrameApplication) SingleFrameApplication.getInstance(APPLICATION_CLASS);
 998    }
 999
1000    private void checkSingleInstance() {
1001        if (LocalSettings.hasProperty(LocalSettings.DBTYPE)
1002                && LocalSettings.getProperty(LocalSettings.DBTYPE).equals("single")) {
1003            try {
1004                Socket test = new Socket("localhost", Main.SINGLE_PORT);
1005                Log.Print("*** Already running!");
1006                System.exit(1);
1007            } catch (Exception e) {
1008                Log.Print("*** First instance.. running!");
1009                new Thread(this).start();
1010            }
1011        }
1012    }
1013
1014    @Override
1015    public void run() {
1016        Socket clientSocket;
1017        try {
1018            // Create the server socket
1019            ServerSocket serverSocket = new ServerSocket(Main.SINGLE_PORT, 10);
1020            while (true) {
1021                // Wait for a connection
1022                clientSocket = serverSocket.accept();
1023                java.awt.EventQueue.invokeLater(new Runnable() {
1024
1025                    @Override
1026                    public void run() {
1027                        getApplication().getMainFrame().setVisible(true);
1028                        getApplication().getMainFrame().requestFocus();
1029                    }
1030                });
1031
1032                clientSocket.close();
1033            }
1034        } catch (IOException ioe) {
1035            Log.Debug(ioe);
1036        }
1037    }
1038
1039    @SuppressWarnings("unchecked")
1040    private void checkLibs() {
1041        splash.nextStep(Messages.CHECK_LIBS.toString());
1042        if (!SKIP_LIBCHECK) {
1043            final String[] libs;
1044            try {
1045                libs = ClasspathTools.findLibsFromManifest(Main.class);
1046                if (libs != null) {
1047                    Runnable runnable1 = new Runnable() {
1048
1049                        @Override
1050                        public void run() {
1051                            File libdir = new File(Constants.LIBS_DIR);
1052                            if (!libdir.exists()) {
1053                                Log.Debug(Main.class,
1054                                        "Libcheck failed in " + Constants.LIBS_DIR);
1055                                return;
1056                            }
1057
1058                            boolean failed = false;
1059                            for (int i = 0; i < libs.length; i++) {
1060                                Log.Debug(Main.class, "Checking: " + libs[i]);
1061                                File lib = new File(libs[i]);
1062                                failed = !lib.canRead();
1063                            }
1064                            if (failed == true) {
1065                                Popup.notice(Messages.MISSING_LIBS.toString());
1066                                //YabsApplication.getInstance().exit();
1067                            }
1068                        }
1069                    };
1070
1071                    new Thread(runnable1).start();
1072                }
1073            } catch (Exception e) {
1074                Log.Debug(e);
1075            }
1076        }
1077    }
1078
1079    @SuppressWarnings("unchecked")
1080    private void checkTpls() {
1081        splash.nextStep(Messages.CHECK_TPLUPDATE.toString());
1082        if (!SKIP_TPLCHECK) {
1083            Runnable runnable1 = new Runnable() {
1084
1085                Object[][] data = null;
1086
1087                @Override
1088                public void run() {
1089                    try {
1090                        ReturnValue rv = QueryHandler.instanceOf().clone(Context.getTemplate()).select(false);
1091                        data = rv.getData();
1092                        for (int i = 0; i < data.length; i++) {
1093                            final Template tpl = (Template) Template.getObject(Context.getTemplate(), Integer.parseInt(data[i][0].toString()));
1094                            FileMonitor.FileChangeListener filecl = new FileMonitor.FileChangeListener() {
1095
1096                                public void fileChanged(String fileName) {
1097                                    QueryHandler.instanceOf().clone(Context.getFiles()).updateFile(new File(fileName), tpl.__getFilename());
1098                                    tpl.setDescription(tpl.__getDescription() + "\n - Updated: " + new Date());
1099                                    tpl.save(true);
1100                                    TemplateHandler.clearCache();
1101                                }
1102                            };
1103
1104                            if (!tpl.__getPathtofile().equals("")) {
1105                                if (tpl.__getisupdateenabled()) {
1106                                    File file = new File(tpl.__getPathtofile());
1107                                    if (file.exists()) {
1108                                        Log.Debug(this, tpl.__getLastmodified());
1109                                        Log.Debug(this, file.lastModified());
1110                                        if (tpl.__getLastmodified() < file.lastModified()) {
1111                                            QueryHandler.instanceOf().clone(Context.getFiles()).updateFile(file, tpl.__getFilename());
1112                                            tpl.setDescription(tpl.__getDescription() + "\n - Updated: " + new Date());
1113                                            tpl.setLastmodified(file.lastModified());
1114                                            tpl.save(true);
1115                                            TemplateHandler.clearCache();
1116                                        }
1117                                    }
1118                                    FileMonitor.getInstance().addFileChangeListener(filecl, tpl.__getPathtofile(), 1000l);
1119                                }
1120                            }
1121                        }
1122                    } catch (NodataFoundException ex) {
1123                        Log.Debug(this, ex.getMessage());
1124                        YabsViewProxy.instance().addMessage(Messages.NO_TEMPLATE_DEFINDED, Color.YELLOW);
1125                    }
1126                }
1127            };
1128            new Thread(runnable1).start();
1129        }
1130    }
1131}