com.future.pos.util.SystemInitializer.java Source code

Java tutorial

Introduction

Here is the source code for com.future.pos.util.SystemInitializer.java

Source

package com.future.pos.util;

import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import com.future.pos.generic.GenericDAO;
import com.future.pos.licenses.License;
import com.future.pos.security.SecurityPermission;
import com.future.pos.users.User;
import com.future.sqlgateway.client.GatewayClient;

/**
 * System initializer of databases and objects.
 * 
 * @author Victorio Cebedo II
 * 
 */
public class SystemInitializer extends HttpServlet {

    private static Map<String, SystemObject> mapObjectDatabase = new HashMap<String, SystemObject>();
    private static Map<String, List<String>> mapDatabaseColumns = new HashMap<String, List<String>>();
    private static Map<Integer, List<SecurityPermission>> permissionSecurityMap = new HashMap<Integer, List<SecurityPermission>>();
    private static Map<Integer, List<SecurityPermission>> columnSecurityMap = new HashMap<Integer, List<SecurityPermission>>();

    private static final String CONFIG_JSON_DB_MAP = "/WEB-INF/dbmap";
    private static final String CONFIG_LICENSE_0 = "/WEB-INF/license0.lic";
    private static final String CONFIG_LICENSE_1 = "/WEB-INF/license1.lic";
    private static final String CONFIG_LICENSE_2 = "/WEB-INF/license2.lic";
    private static final String CONFIG_LICENSE_3 = "/WEB-INF/license3.lic";

    private static ThreadSafeCache cache = new ThreadSafeCache(1);
    private static final String CACHE_KEY_MAP_OBJ_DB = "cacheKeyMapObjectToDB";
    private static final String CACHE_KEY_MAP_DB_COLS = "cacheKeyMapDBToCols";

    private static final String JSON_ROOT_ELEMENT = "databaseMap";

    private static final long serialVersionUID = 1L;

    private static String filepathJSONDBMap;
    public static boolean configVarsInitialized = false;

    private static void initializeLicenses() {
        try {
            if (License.isValid() && configVarsInitialized) {
                mapObjects();
                mapDatabaseColumns();
            } else {
                System.out.println("FATAL ERROR: License is not valid.");
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * Runs during initialization of the server.<br>
     * Loads on startup. Configured in web.xml.
     */
    public void init(ServletConfig config) throws ServletException {
        try {
            initializeConfigVars(config.getServletContext());
            initializeLicenses();
            initializeSecurityGroups(config.getServletContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Just in case server wasn't initialized (in the case of JBoss).<br>
     * Call this during startup.
     * 
     * @param servletContext
     */
    public static void initialize(ServletContext servletContext) {
        try {
            initializeConfigVars(servletContext);
            initializeLicenses();
            initializeSecurityGroups(servletContext);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Initialize the security groups based on<br>
     * physical files saved in the web server.
     * 
     * @param servletContext
     */
    private static void initializeSecurityGroups(ServletContext servletContext) {
        // For every account number, there's a list of column view security.
        Map<Integer, List<SecurityPermission>> viewSecurityMap = new HashMap<Integer, List<SecurityPermission>>();
        Map<Integer, List<SecurityPermission>> colSecuMap = new HashMap<Integer, List<SecurityPermission>>();
        File dir = new File(servletContext.getRealPath(User.FILEPATH_ROLES));
        File[] fileList = dir.listFiles();

        // Loop through each file in the directory.
        for (File file : fileList) {

            String fileContents = Utilities.getFileContents(file);
            List<SecurityPermission> permissions = new ArrayList<SecurityPermission>();
            List<SecurityPermission> disallowedList = new ArrayList<SecurityPermission>();

            // Loop through each line in the role file.
            boolean isFirst = true;
            boolean isAllowDone = false;
            String accountName = "";
            String[] contentsArray = fileContents.split("\n");
            for (String line : contentsArray) {
                // If now entering disallow portion.
                line = line.trim();
                if (line != null && line.equals("[Disallow]")) {
                    isAllowDone = true;
                    continue;
                }

                if (!isAllowDone) {
                    // If the first line, initialize the account name.
                    // Account name is declared in first line.
                    if (isFirst) {
                        accountName = line;
                        isFirst = false;
                        continue;
                    }

                    String tableName = line.split("=")[0];
                    String[] actionList = line.split("=")[1].split(",");
                    List<Integer> actionIDList = new ArrayList<Integer>();
                    for (String action : actionList) {
                        actionIDList.add(Integer.valueOf(action));
                    }

                    SecurityPermission permission = new SecurityPermission(accountName, tableName, actionIDList);
                    permissions.add(permission);

                }
                // Now is phase where system parses all disallowed columns.
                else {
                    String table = line.split("=")[0];
                    String[] columns = line.split("=")[1].split(",");
                    List<String> columnList = Utilities.convertArrayToList(columns);
                    SecurityPermission disallowed = new SecurityPermission(table, columnList);
                    disallowedList.add(disallowed);
                }
            }
            Integer accountType = Integer.valueOf(file.getName());
            colSecuMap.put(accountType, disallowedList);
            viewSecurityMap.put(accountType, permissions);
        }
        setColumnSecurityMap(colSecuMap);
        setPermissionSecurityMap(viewSecurityMap);
    }

    private static String getPathFromContext(ServletContext servletContext, String path) {
        String realPath = servletContext.getRealPath(path);
        if (realPath == null) {
            String hardcodedPath = "/var/lib/openshift/5478455ce0b8cde36400001e/jbossews/future/";
            System.out.println("Hardcoded Path: " + hardcodedPath);
            String[] paths = path.split("/");
            realPath = hardcodedPath + paths[paths.length - 1];
        }
        System.out.println("Real Path: " + realPath);
        return realPath;
    }

    private static void initializeConfigVars(ServletContext servletContext) {
        try {
            setFilepathJSONDBMap(getPathFromContext(servletContext, CONFIG_JSON_DB_MAP));
            License.setLicense0filepath(getPathFromContext(servletContext, CONFIG_LICENSE_0));
            License.setLicense1filepath(getPathFromContext(servletContext, CONFIG_LICENSE_1));
            License.setLicense2filepath(getPathFromContext(servletContext, CONFIG_LICENSE_2));
            License.setLicense3filepath(getPathFromContext(servletContext, CONFIG_LICENSE_3));
            configVarsInitialized = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getFilepathJSONDBMap() {
        return filepathJSONDBMap;
    }

    public static void setFilepathJSONDBMap(String filepathJSONDBMap) {
        SystemInitializer.filepathJSONDBMap = filepathJSONDBMap;
    }

    /**
     * Parse the external JSON file and parse.
     */
    private static void mapObjects() {
        try {
            // Get the external JSON file.
            String content = new Scanner(new File(getFilepathJSONDBMap())).useDelimiter("\\Z").next();
            JSONObject jsonObject = new JSONObject(content);
            JSONObject dbMap = jsonObject.getJSONObject(JSON_ROOT_ELEMENT);

            // Loop throught the JSON object.
            for (int i = 0; i < dbMap.length(); i++) {
                String tableName = String.valueOf(dbMap.names().get(i));
                JSONArray tableArray = dbMap.getJSONArray(tableName);
                String[] tableArrayValues = String.valueOf(tableArray).replaceAll("\\[", "").replaceAll("\\]", "")
                        .replaceAll("\\{", "").replaceAll("\\}", "").split(",");

                // For each detail in each table.
                Map<String, String> tempMap = new LinkedHashMap<String, String>();
                for (String value : tableArrayValues) {
                    String dbDetailKey = value.split("\":\"")[0].replaceAll("\"", "");
                    String dbDetailValue = value.split("\":\"")[1].replaceAll("\"", "");

                    // Add to a temporary map.
                    tempMap.put(dbDetailKey, dbDetailValue);
                }

                // Add to final map.
                mapObjectDatabase.put(tableName, new SystemObject(tempMap.get("DRIVER"), tempMap.get("PROTOCOL"),
                        tempMap.get("URL"), tempMap.get("PORT"), tempMap.get("DATABASE"), tempMap.get("USERNAME"),
                        tempMap.get("PASSWORD"), tempMap.get("CONTROLLER"), SystemObject.getTrueObject(tableName)));
            }
            System.out.println("Initial Object to DB mapping: " + mapObjectDatabase.toString());
            updateCachedObjectDBMap();
        } catch (Exception e) {
            System.out.println("FATAL ERROR: Failed mapping objects.");
            e.printStackTrace();
        }
    }

    /**
     * Get set of table names.
     * 
     * @return
     */
    public static Set<String> getTableSet() {
        return getCachedObjDBMap().keySet();
    }

    /**
     * Update the cached object to db map.
     */
    private static void updateCachedObjectDBMap() {
        cache.put(CACHE_KEY_MAP_OBJ_DB, getObjDBMapVariable());
    }

    /**
     * Update the cached db to cols map.
     */
    private static void updateCachedDBColsMap() {
        cache.put(CACHE_KEY_MAP_DB_COLS, getDBColsMapVariable());
    }

    /**
     * Get a value from cache.
     * 
     * @param key
     * @return
     */
    private static Object getCachedObject(String key) {
        return cache.get(key);
    }

    @SuppressWarnings("unchecked")
    public static Map<String, SystemObject> getCachedObjDBMap() {
        return getCachedObject(CACHE_KEY_MAP_OBJ_DB) != null
                ? (Map<String, SystemObject>) getCachedObject(CACHE_KEY_MAP_OBJ_DB)
                : getObjDBMapVariable();
    }

    @SuppressWarnings("unchecked")
    public static Map<String, List<String>> getCachedDBColsMap() {
        return getCachedObject(CACHE_KEY_MAP_DB_COLS) != null
                ? (Map<String, List<String>>) getCachedObject(CACHE_KEY_MAP_DB_COLS)
                : getDBColsMapVariable();
    }

    public static Map<String, SystemObject> getObjDBMapVariable() {
        return mapObjectDatabase;
    }

    public static Map<String, List<String>> getDBColsMapVariable() {
        return mapDatabaseColumns;
    }

    /**
     * Get the map of table to column list.
     * 
     * @return
     */
    public static Map<String, List<String>> mapDatabaseColumns() {
        for (String table : getCachedObjDBMap().keySet()) {
            try {
                List<String> colList = new ArrayList<String>();

                // If this deployment does not use the SQL gateway.
                if (!GenericDAO.useSQLGateway) {
                    Connection connection = DBUtilities.getConnection(table);
                    colList = DBUtilities.getDBColumnsFromConnection(connection, table);
                    connection.close();
                }
                // Handle case when using SQLGateway.
                else {
                    GatewayClient client = new GatewayClient(GenericDAO.sqlGatewayURL, GenericDAO.sqlGatewayUser,
                            GenericDAO.sqlGatewayPass);
                    colList = client.getColumnList(table);
                }
                mapDatabaseColumns.put(table, colList);
            } catch (Exception e) {
                System.out.println("FATAL ERROR: Can't connect to table " + table + ".");
                continue;
            }
        }
        updateCachedDBColsMap();
        return mapDatabaseColumns;
    }

    /**
     * Get mapped table from object.
     * 
     * @param object
     * @return
     */
    public static String getTableFromObject(Object object) {
        for (Entry<String, SystemObject> entry : getCachedObjDBMap().entrySet()) {
            String table = entry.getKey();
            Object trueObject = SystemObject.getTrueObject(table);
            if (object.getClass() == trueObject.getClass()) {
                return table;
            }
        }
        return null;
    }

    /**
     * Get mapped table from request.
     * 
     * @param object
     * @return
     */
    public static String getTableFromRequest(HttpServletRequest request) {
        String table = RequestUtilities.getSchemaTable(request);

        // If table is not passed, get it from object.
        if (table == null || table.isEmpty()) {
            Object object = RequestUtilities.getObject(request);

            for (Entry<String, SystemObject> entry : getCachedObjDBMap().entrySet()) {
                table = entry.getKey();
                Object trueObject = SystemObject.getTrueObject(table);
                if (object.getClass() == trueObject.getClass()) {
                    break;
                }
            }
        }
        return table;
    }

    /**
     * Return an empty default object given a schema table.
     * 
     * @param schemaTable
     * @return
     */
    public static Object getObject(String schemaTable) {
        return getCachedObjDBMap().get(schemaTable).getObj();
    }

    public static String getController(String schemaTable) {
        return getCachedObjDBMap().get(schemaTable).getController();
    }

    public static SystemObject getSystemObject(String schemaTable) {
        return getCachedObjDBMap().get(schemaTable);
    }

    public static Map<Integer, List<SecurityPermission>> getPermissionSecurityMap() {
        return permissionSecurityMap;
    }

    public static void setPermissionSecurityMap(Map<Integer, List<SecurityPermission>> permissionSecurityMap) {
        SystemInitializer.permissionSecurityMap = permissionSecurityMap;
    }

    public static Map<Integer, List<SecurityPermission>> getColumnSecurityMap() {
        return columnSecurityMap;
    }

    public static void setColumnSecurityMap(Map<Integer, List<SecurityPermission>> columnSecurityMap) {
        SystemInitializer.columnSecurityMap = columnSecurityMap;
    }

    public static void main(String args[]) throws Exception {
        // initializeSecurityGroups(Serv);
    }
}