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