All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jk.application.api.AbstractApplicationManager Maven / Gradle / Ivy

/*
 * Copyright 2002-2016 Jalal Kiswani.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jk.application.api;
/*

 * Copyright 2002-2016 Jalal Kiswani.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.List;

import com.jk.application.exceptions.ApplicationException;
import com.jk.application.listener.ApplicationListener;
import com.jk.application.parsers.ApplicationXmlParser;
import com.jk.application.parsers.EntityMetaXmlParser;
import com.jk.application.ui.UIApplicationFrame;
import com.jk.application.ui.UIWidgetFactory;
import com.jk.db.dataaccess.plain.JKPlainDataAccess;
import com.jk.db.datasource.JKDataSource;
import com.jk.db.datasource.JKDataSourceFactory;
import com.jk.db.datasource.JKDatabaseType;
import com.jk.db.dynamic.meta.AbstractEntityMetaFactory;
import com.jk.exceptions.handler.JKExceptionUtil;
import com.jk.logging.JKLogger;
import com.jk.logging.JKLoggerFactory;
import com.jk.metadata.db.meta.EntityMeta;
import com.jk.security.JKSecurityManager;
import com.jk.security.JKUser;
import com.jk.util.JK;
import com.jk.util.JKIOUtil;

/**
 * The Class ApplicationManager.
 *
 * @author Jalal Kiswani
 */
public abstract class AbstractApplicationManager implements ApplicationManager {
	JKLogger logger = JKLoggerFactory.getLogger(getClass());
	private static final String[] DEFAULT_SYSTEM_FILES = { "/jk/application.xml", "/jk/system.xml", "/jk/default.system.xml" };
	private static final String DEFAULT_METADATA_ENTITIES_XML = "/jk/metadata/entities.xml";
	private static final int LOGIN_RETRIES = 3;

	private Application application;

	/**
	 * Gets the single instance of ApplicationManager.
	 *
	 * @return single instance of ApplicationManager
	 */
	public AbstractApplicationManager() {
		System.out.println(JKIOUtil.readFile("/jk/banner.txt"));
		logger.info("Starting Smart-EIS framework....");
		logger.debug("set default exception handler");
		logger.info("Set data-sources...");
		JKDataSourceFactory.getDefaultDataSource();
		logger.debug("Check if default database script installed...");
		checkScriptsInstalled();
		logger.info("Initialize Application-Manager...");
		init();
	}

	protected void checkScriptsInstalled() {
		
		// TODO : add generic way to apply db-scripts
		JKDataSource source = JKDataSourceFactory.getDefaultDataSource();
		if (source.getDatabaseType() == JKDatabaseType.MYSQL) {
			JKPlainDataAccess dao = JKDataSourceFactory.getPlainDataAccess();
			if (!dao.isTableExists("sec_users")) {
				if (getUIWidgetFactory().showConfirmation("It looks like a first usage, execute base script on DB?")) {
					dao.runScript("/scripts/mysql/base.sql");
				}
			}
		} else {
			getUIWidgetFactory().showWarning("Initialization script for your DBMS is not supported, please execute script manually");
		}
	}

	protected UIWidgetFactory getUIWidgetFactory() {
		return ApplicationSuperFactory.getInstance().getUIWidgetFactory();
	}

	/**
	 * Close main frame.
	 */
	public void closeMainFrame() {
		logger.debug("close main frame");
		JK.validateNull("Application", application);
		JK.validateNull("Application Frame", application.getApplicationFrame());
		application.getApplicationFrame().close();
	}

	protected void fireAfterApplicationInit() {
		final List listeners = this.application.getApplicationListeners();
		for (int i = 0; i < listeners.size(); i++) {
			listeners.get(i).afterInit(this.application);
		}
	}

	protected void fireAfterApplicationStart() {
		final List listeners = this.application.getApplicationListeners();
		for (int i = 0; i < listeners.size(); i++) {
			listeners.get(i).afterStart(this.application);
		}
	}

	/**
	 *
	 */
	protected void fireBeforeApplicationInit() {
		final List listeners = this.application.getApplicationListeners();
		for (int i = 0; i < listeners.size(); i++) {
			listeners.get(i).beforeInit(this.application);
		}
	}

	protected void fireBeforeApplicationStart() {
		final List listeners = this.application.getApplicationListeners();
		for (int i = 0; i < listeners.size(); i++) {
			listeners.get(i).beforeStart(this.application);
		}
	}

	/**
	 *
	 * @param e
	 */
	protected void fireException(final Exception e) {
		final List listeners = this.application.getApplicationListeners();
		for (int i = 0; i < listeners.size(); i++) {
			listeners.get(i).onException(this.application, e);
		}
	}

	/**
	 * Gets the application.
	 *
	 * @return the application
	 */
	public Application getApplication() {
		JK.notNull(this.application);
		return this.application;
	}

	/**
	 * Inits the.
	 *
	 * @return the application
	 * @throws FileNotFoundException
	 *             the file not found exception
	 * @throws ApplicationException
	 *             the application exception
	 */
	public void init() {
		for (String fileName : DEFAULT_SYSTEM_FILES) {
			logger.debug("trying to init application with file :", fileName);
			InputStream fileInputStream = JK.getInputStream(fileName);
			if (fileInputStream != null) {
				init(fileInputStream);
			}
		}
		logger.info(" config files doesnot exist, init with defaults");
		init(null);

	}

	/**
	 * Inits the.
	 *
	 * @param in
	 *            the in
	 * @return the application
	 * @throws ApplicationException
	 *             the application exception
	 */
	public void init(final InputStream in) {
		try {
			logger.info("Load default Metadata...");
			loadDefaultEntitiesMeta();
			if (in != null) {
				logger.info("Parse application....");
				final ApplicationXmlParser parser = new ApplicationXmlParser();
				this.application = parser.parseApplication(in);
			} else {
				logger.debug("Create default application...");
				this.application = ApplicationSuperFactory.getInstance().getDefaultApplication();
			}
			if (this.application.getSplashImage() != null) {
				logger.debug("show splash");
				getUIWidgetFactory().showSplash(this.application.getSplashImage());
			}
			logger.debug("Validate license...");
			fireBeforeApplicationInit();
			// ExceptionUtil.initExceptionLogging();
			logger.debug("Init application instance...");
			this.application.init();
			// WE DELAY THE CHECK UNTIL NOW TO BE SURE THAT WE HAVE LOADED THE
			// LABLES
			// if (firstRun && isAllowSingleInstanceOnly()) {
			// logger.debug("Set single instance only...");
			// // to avoid any issues with swicthLocale or restart
			// InstanceManager.registerInstance(this.application.getApplicationId());
			// firstRun = false;
			// }
			logger.debug("Check database base script executed...");
			getUIWidgetFactory().disposeSplash();
			// checkScriptsInstalled();
			fireAfterApplicationInit();
		} catch (final Exception e) {
			fireException(e);
			throw new ApplicationException(e);
		} finally {
			getUIWidgetFactory().disposeSplash();
		}
	}

	// //
	// ////////////////////////////////////////////////////////////////////////////////////
	// private void initConfig() throws FileNotFoundException, IOException {
	// final DefaultConfigManager manager =
	// ConfigManagerFactory.getDefaultConfigManager();
	// // Properties prop = new Properties();
	// // prop.loadFromXML(new FileInputStream("system.config"));
	// System.getProperties().putAll(manager.getProperties());
	// logger.debug(manager.getProperties());
	// }

	// //
	// ////////////////////////////////////////////////////////////////////////////////////
	// private boolean isAllowSingleInstanceOnly() {
	// return System.getProperty("SINGLE_INSTANCE",
	// "false").toLowerCase().equals("true");
	// }

	// ////////////////////////////////////////////////////////////////////////////////////
	private void loadDefaultEntitiesMeta() {
		logger.debug("start loading default meta");
		final EntityMetaXmlParser parser = new EntityMetaXmlParser();
		String resourceName = DEFAULT_METADATA_ENTITIES_XML;
		logger.debug("Load default meta from:" + resourceName);
		final InputStream in = JK.getInputStream(resourceName);
		if (in != null) {
			logger.debug("Parsing default meta");
			final Hashtable meta = parser.parse(in, "default");
			logger.debug("Adding meta to abstract table meta factory : " + meta);
			AbstractEntityMetaFactory.getInstance().addEntitiesMeta(JKDataSourceFactory.getDefaultDataSource(), meta);
		}else {
			logger.debug("Default entities metadata file not found!");
		}
	}

	/**
	 * Logout.
	 *
	 * @throws ApplicationException
	 *             the application exception
	 */
	public void logout() throws ApplicationException {
		// SecurityFacade facade=new SecurityFacade();
		// try {
		// facade.addLogoutAudit();
		// } catch (DaoException e) {
		// throw new ApplicationException(e);
		// }
		closeMainFrame();
		JKSecurityManager.setCurrentUser(null);
		start();
	}

	/**
	 * Restart frame.
	 */
	public void restartFrame() {
		try {
			this.application.getApplicationFrame().dispose();
			init();
			start();
		} catch (final Exception e) {
			JKExceptionUtil.handle(e);
		}
	}

	/**
	 * Start.
	 *
	 * @throws ApplicationException
	 *             the application exception
	 */
	public void start() throws ApplicationException {
		fireBeforeApplicationStart();
		try {
			if (!JKSecurityManager.isUserLoggedIn()) {
				final JKUser user = JKSecurityManager.getAuthenticaor().authenticate(this.application.getApplicationName(), LOGIN_RETRIES);
				JKSecurityManager.setCurrentUser(user);
				// AutomaticDBBackup.processDatabaseAutobackup();
			}
			if (this.application.getSplashImage() != null) {
				getUIWidgetFactory().showSplash(application.getApplicationName(), this.application.getSplashImage());
			}
			UIApplicationFrame applicationFrame = getUIWidgetFactory().createApplicationFrame(this.application);
			this.application.setApplicationFrame(applicationFrame);
			applicationFrame.setTitle(this.application.getApplicationName());
			getUIWidgetFactory().setDefaultMainFrame(applicationFrame);
			// applicationFrame.setExtendedState(ApplicationFrame.MAXIMIZED_BOTH);

			applicationFrame.setVisible(true);
			fireAfterApplicationStart();
		} catch (final Exception e) {
			fireException(e);
			throw new ApplicationException(e);
		} finally {
			getUIWidgetFactory().disposeSplash();
		}
	}

	@Override
	public void reset() {
	}

	@Override
	public void restart() {
		if (getUIWidgetFactory().showConfirmation("WE_NEED_TO_RESTART_THE_SYSTEM,RESTART_NOW?")) {
			JK.restart();
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy