Example usage for org.hibernate Session saveOrUpdate

List of usage examples for org.hibernate Session saveOrUpdate

Introduction

In this page you can find the example usage for org.hibernate Session saveOrUpdate.

Prototype

void saveOrUpdate(Object object);

Source Link

Document

Either #save(Object) or #update(Object) the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking).

Usage

From source file:com.cosylab.cdb.jdal.hibernate.plugin.HibernateWDALAlarmPluginImpl.java

License:Open Source License

public static void importAlarms(Session session, Configuration config, ConfigurationAccessor conf,
        Logger m_logger) throws Exception {
    // clean up whatever is in the session
    session.getTransaction().commit();//from   w ww .  j  a  v a2s .c o m
    session.clear();
    session.beginTransaction();

    // create DAOs
    ACSAlarmDAOImpl alarmDAO = new ACSAlarmDAOImpl(m_logger);
    ACSCategoryDAOImpl categoryDAO = new ACSCategoryDAOImpl(m_logger, alarmDAO);
    ACSResponsiblePersonDAOImpl responsiblePersonDAO = new ACSResponsiblePersonDAOImpl();

    // configure
    alarmDAO.setConfAccessor(conf);
    alarmDAO.setSurveillanceAlarmId("SURVEILLANCE:SOURCE:1");
    alarmDAO.setResponsiblePersonDAO(responsiblePersonDAO);

    categoryDAO.setConfAccessor(conf);
    //categoryDAO.setCategoryTreeRoot("ACS");
    categoryDAO.setCategoryTreeRoot("ROOT");
    categoryDAO.setSurveillanceCategoryPath("ACS.SURVEILLANCE");

    responsiblePersonDAO.setAlarmDAO(alarmDAO);

    // load
    final List<alma.acs.alarmsystem.generated.FaultFamily> families = alarmDAO.loadAlarms();
    final alma.acs.alarmsystem.generated.Category[] categories = categoryDAO.loadCategories();
    Map<String, ArrayList<AlarmCategory>> categoryFaultFamilyLinks = new HashMap<String, ArrayList<AlarmCategory>>();

    // store categories
    if (categories != null)
        for (alma.acs.alarmsystem.generated.Category daoCategory : categories) {
            AlarmCategory category = (AlarmCategory) session.createCriteria(AlarmCategory.class)
                    .add(Restrictions.eq("configuration", config))
                    .add(Restrictions.eq("alarmCategoryName", daoCategory.getPath())).uniqueResult();
            if (category == null) {
                category = new AlarmCategory();
                category.setAlarmCategoryName(daoCategory.getPath());
                category.setConfiguration(config);
            }
            category.setDescription(nonEmptyString(daoCategory.getDescription(), "(description)"));
            category.setPath(daoCategory.getPath());
            category.setIsDefault(daoCategory.getIsDefault());
            session.saveOrUpdate(category);

            // clear first (in case of update)
            category.getFaultFamilies().clear();

            // cache mappings
            String[] faultFamilies = daoCategory.getAlarms().getFaultFamily();
            for (String faultFamily : faultFamilies) {
                ArrayList<AlarmCategory> list = categoryFaultFamilyLinks.get(faultFamily);
                if (list == null) {
                    list = new ArrayList<AlarmCategory>();
                    categoryFaultFamilyLinks.put(faultFamily, list);
                }
                list.add(category);
            }
        }

    // store fault families and contacts, etc.
    if (families != null)
        for (alma.acs.alarmsystem.generated.FaultFamily family : families) {
            final alma.acs.alarmsystem.generated.Contact daoContact = family.getContact();
            Contact contact = (Contact) session.createCriteria(Contact.class)
                    .add(Restrictions.eq("contactName", daoContact.getName())).uniqueResult();
            if (contact == null) {
                contact = new Contact();
                contact.setContactName(nonEmptyString(daoContact.getName(), "(empty)"));
                contact.setEmail(daoContact.getEmail());
                contact.setGsm(daoContact.getGsm());
                session.persist(contact);
            }
            // If contact exist, let's check if this contact contains different information. If so,
            // issue an error
            else {
                if (!trimAndNullToEmpty(contact.getEmail()).equals(trimAndNullToEmpty(daoContact.getEmail()))
                        || !trimAndNullToEmpty(contact.getGsm())
                                .equals(trimAndNullToEmpty(daoContact.getGsm()))) {
                    throw new RuntimeException(
                            "Data stored for contact '" + contact.getContactName() + "' in TMCDB "
                                    + "does not match that comming from the 'contact' node of fault family '"
                                    + family.getName() + "'. " + "TMCDB: <" + contact.getEmail() + ", "
                                    + contact.getGsm() + ">, " + "CDB: <" + daoContact.getEmail() + ", "
                                    + daoContact.getGsm() + ">");
                }
            }

            FaultFamily faultFamily = (FaultFamily) session.createCriteria(FaultFamily.class)
                    .add(Restrictions.eq("configuration", config))
                    .add(Restrictions.eq("familyName", family.getName())).uniqueResult();
            if (faultFamily == null) {
                faultFamily = new FaultFamily();
                faultFamily.setFamilyName(family.getName());
                faultFamily.setConfiguration(config);
            }
            faultFamily.setAlarmSource(family.getAlarmSource());
            faultFamily.setHelpURL(family.getHelpUrl());
            faultFamily.setContact(contact);
            session.saveOrUpdate(faultFamily);

            // clear first (in case of update)   
            faultFamily.getAlarmCategories().clear();
            ArrayList<AlarmCategory> list = categoryFaultFamilyLinks.get(family.getName());
            if (list != null)
                for (AlarmCategory category : list) {
                    category.getFaultFamilies().add(faultFamily);
                    faultFamily.getAlarmCategories().add(category);
                    session.update(category);
                    session.update(faultFamily);
                }

            // default fault member
            if (family.getFaultMemberDefault() != null) {
                DefaultMember defaultMember = null;
                // there can be only one
                if (faultFamily.getDefaultMembers().size() != 0)
                    defaultMember = faultFamily.getDefaultMembers().iterator().next();
                if (defaultMember == null) {
                    defaultMember = new DefaultMember();
                    defaultMember.setFaultFamily(faultFamily);
                }
                defaultMember.setLocation(getLocation(session, family.getFaultMemberDefault().getLocation()));
                session.saveOrUpdate(defaultMember);
            } else {
                for (DefaultMember memberToRemove : faultFamily.getDefaultMembers()) {
                    faultFamily.getDefaultMembers().remove(memberToRemove);
                    session.delete(memberToRemove);
                }
                session.update(faultFamily);
            }

            // copy all
            Set<FaultMember> faultMembersToRemove = new HashSet<FaultMember>(faultFamily.getFaultMembers());

            // add fault members
            for (alma.acs.alarmsystem.generated.FaultMember daoFaultMember : family.getFaultMember()) {
                FaultMember faultMember = (FaultMember) session.createCriteria(FaultMember.class)
                        .add(Restrictions.eq("memberName", daoFaultMember.getName()))
                        .add(Restrictions.eq("faultFamily", faultFamily)).uniqueResult();
                faultMembersToRemove.remove(faultMember);
                if (faultMember == null) {
                    faultMember = new FaultMember();
                    faultMember.setMemberName(daoFaultMember.getName());
                    faultMember.setFaultFamily(faultFamily);
                }
                faultMember.setLocation(getLocation(session, daoFaultMember.getLocation()));
                session.saveOrUpdate(faultMember);
            }

            if (faultMembersToRemove.size() > 0) {
                for (FaultMember faultMemberToRemove : faultMembersToRemove) {
                    faultFamily.getFaultMembers().remove(faultMemberToRemove);
                    session.delete(faultMemberToRemove);
                }
                session.update(faultFamily);
            }

            // copy all
            Set<FaultCode> faultCodesToRemove = new HashSet<FaultCode>(faultFamily.getFaultCodes());

            // add fault codes
            for (alma.acs.alarmsystem.generated.FaultCode daoFaultCode : family.getFaultCode()) {
                FaultCode faultCode = (FaultCode) session.createCriteria(FaultCode.class)
                        .add(Restrictions.eq("faultFamily", faultFamily))
                        .add(Restrictions.eq("codeValue", daoFaultCode.getValue())).uniqueResult();
                faultCodesToRemove.remove(faultCode);
                if (faultCode == null) {
                    faultCode = new FaultCode();
                    faultCode.setFaultFamily(faultFamily);
                    faultCode.setCodeValue(daoFaultCode.getValue());
                }
                faultCode.setPriority(daoFaultCode.getPriority());
                faultCode.setCause(daoFaultCode.getCause());
                faultCode.setAction(daoFaultCode.getAction());
                faultCode.setConsequence(daoFaultCode.getConsequence());
                faultCode.setProblemDescription(
                        nonEmptyString(daoFaultCode.getProblemDescription(), "(description)"));
                faultCode.setIsInstant(daoFaultCode.getInstant());
                session.saveOrUpdate(faultCode);
            }

            if (faultCodesToRemove.size() > 0) {
                for (FaultCode faultCodeToRemove : faultCodesToRemove) {
                    faultFamily.getFaultCodes().remove(faultCodeToRemove);
                    session.delete(faultCodeToRemove);
                }
                session.update(faultFamily);
            }
        }

    try {
        alma.alarmsystem.alarmmessage.generated.ReductionDefinitions redDefs = alarmDAO
                .getReductionDefinitions();
        if (redDefs != null) {
            if (redDefs.getLinksToCreate() != null)
                saveReductionLinks(session, config, redDefs.getLinksToCreate().getReductionLink(),
                        ReductionLinkAction.CREATE);
            if (redDefs.getLinksToRemove() != null)
                saveReductionLinks(session, config, redDefs.getLinksToRemove().getReductionLink(),
                        ReductionLinkAction.REMOVE);

            int count = 0;
            if (redDefs.getThresholds() != null) {
                alma.alarmsystem.alarmmessage.generated.Threshold[] thresholds = redDefs.getThresholds()
                        .getThreshold();
                for (alma.alarmsystem.alarmmessage.generated.Threshold threshold : thresholds) {
                    // also commit first
                    if (count % 100 == 0) {
                        session.getTransaction().commit();
                        session.clear(); // cleanup first level cache
                        session.beginTransaction();
                        config = (Configuration) session.get(Configuration.class, config.getConfigurationId());
                    }

                    count++;

                    alma.acs.tmcdb.AlarmDefinition alarm = getAlarmDefinition(session, config,
                            threshold.getAlarmDefinition(), false);
                    alma.acs.tmcdb.ReductionThreshold t = (alma.acs.tmcdb.ReductionThreshold) session
                            .createQuery("from ReductionThreshold " + "where AlarmDefinitionId = "
                                    + alarm.getAlarmDefinitionId())
                            .uniqueResult();

                    if (t == null) {
                        t = new ReductionThreshold();
                        t.setAlarmDefinition(alarm);
                        t.setConfiguration(config);
                    }
                    t.setValue(threshold.getValue());
                    session.saveOrUpdate(t);
                }
            }
        }
    } finally {
        // clear cache (to free memory)
        adCache.clear();
    }
}

From source file:com.cosylab.cdb.jdal.hibernate.plugin.HibernateWDALAlarmPluginImpl.java

License:Open Source License

private static void saveReductionLinks(Session session, Configuration config,
        alma.alarmsystem.alarmmessage.generated.ReductionLinkType[] links, ReductionLinkAction action) {
    int count = 0;

    for (alma.alarmsystem.alarmmessage.generated.ReductionLinkType link : links) {
        // also commit first
        if (count % 100 == 0) {
            session.getTransaction().commit();
            session.clear(); // cleanup first level cache
            adCache.clear();/* w  w  w  .j  av  a 2s.  c o m*/
            session.beginTransaction();
            // refresh
            config = (Configuration) session.get(Configuration.class, config.getConfigurationId());
        }

        count++;

        alma.acs.tmcdb.AlarmDefinition parent = getAlarmDefinition(session, config,
                link.getParent().getAlarmDefinition(), true);
        alma.acs.tmcdb.AlarmDefinition child = getAlarmDefinition(session, config,
                link.getChild().getAlarmDefinition(), true);

        alma.acs.tmcdb.ReductionLink remoteLink = (alma.acs.tmcdb.ReductionLink) session
                .createCriteria(alma.acs.tmcdb.ReductionLink.class)
                .add(Restrictions.eq("alarmDefinitionByParentalarmdefid", parent))
                .add(Restrictions.eq("alarmDefinitionByChildalarmdefid", child)).uniqueResult();
        if (remoteLink == null) {

            remoteLink = new alma.acs.tmcdb.ReductionLink();
            remoteLink.setAlarmDefinitionByChildalarmdefid(child);
            remoteLink.setAlarmDefinitionByParentalarmdefid(parent);
            remoteLink.setConfiguration(config);

        }
        remoteLink.setAction(action);
        remoteLink.setType(ReductionLinkType.valueOf(link.getType().toString()));
        session.saveOrUpdate(remoteLink);
    }

    // and commit
    session.getTransaction().commit();
    session.clear();
    session.beginTransaction();
}

From source file:com.cosylab.cdb.jdal.HibernateWDALImpl.java

License:Open Source License

protected boolean loadXMLCDB(String args[], ORB orb, POA poa, String configName) {
    m_logger.info("Reading configuration from XML CDB...");

    try {// ww  w  .j a  v  a 2 s .c om
        loadInProgress.set(true);

        /* create new poa for xmlCDB */
        org.omg.CORBA.Policy[] policies = new org.omg.CORBA.Policy[] {
                poa.create_id_assignment_policy(IdAssignmentPolicyValue.USER_ID) };

        POA xmlCDBPOA = poa.create_POA("xmlCDBPOA", poa.the_POAManager(), policies);

        for (int i = 0; i < policies.length; i++)
            policies[i].destroy();

        // disable cache for XML CDB DAL (important)
        String[] newArgs = new String[args.length + 2];
        System.arraycopy(args, 0, newArgs, 0, args.length);
        newArgs[args.length] = "-disableRecoveryFile";
        newArgs[args.length + 1] = "-disableCache";

        final WDALImpl servantDelegate = new WDALImpl(newArgs, orb, xmlCDBPOA, m_logger);
        final Servant wdalImplServant = new WJDALPOATie(servantDelegate);
        //         WDALImpl wdalImplServant = new WDALImpl(args, orb, xmlCDBPOA, m_logger);
        xmlCDBPOA.activate_object_with_id(new byte[] { 'x', 'm', 'l', 'C', 'D', 'B' }, wdalImplServant);
        org.omg.CORBA.Object ref = xmlCDBPOA.servant_to_reference(wdalImplServant);
        final JDAL xmlCDB_ = JDALHelper.narrow(ref);

        // -----

        // get set of BACI property attributes (non-extras)
        String[] baciPropertyAttributes = DOMJavaClassIntrospector.getAccessibleFields(new BACIPropertyType(),
                true);
        Set<String> baciPropertyAttributesSet = new HashSet<String>();
        for (String attribute : baciPropertyAttributes) {
            baciPropertyAttributesSet.add(attribute);
        }

        XSDElementTypeResolver xsdElementTypeResolver = new XSDElementTypeResolver(m_root, m_logger);
        Set<String> nonControlDeviceSet = new TreeSet<String>();
        Set<String> characteristicsDeviceSet = new TreeSet<String>();

        Set<String> processedComponentTypes = new HashSet<String>();
        // -----

        CDBAccess cdbAccess = new CDBAccess(orb, m_logger);
        cdbAccess.setDAL(xmlCDB_);

        try {
            hibernateUtil.beginTransaction();
            Session session = hibernateUtil.getSession();
            schemaResourceResolverLoader.setSession(session);

            // check if configuration already exists
            config = (Configuration) session.createCriteria(Configuration.class)
                    .add(Restrictions.eq("configurationName", configName)).uniqueResult();
            if (config != null) {
                m_logger.warning("Configuration with name '" + configName
                        + "' already exists. Skipping loading XML stage.");
                return false;
            }

            // create configuration
            config = new Configuration();
            config.setConfigurationName(configName);
            config.setFullName(configName);
            config.setActive(true);
            config.setCreationTime(Calendar.getInstance().getTime());
            config.setDescription("Imported from CDB by HibernateWDAL");
            session.persist(config);

            configId = config.getConfigurationId();

            // plugin importPrologue()
            if (plugin != null) {
                try {
                    plugin.importPrologue(session, config, cdbAccess);
                } catch (Throwable th) {
                    // @TODO decent exception log. Is OK to swallow th?
                    th.printStackTrace();
                }
            }

            // load all schemas            
            loadSchemas(session);

            try {
                //DAO managerDAO = xmlCDB.get_DAO_Servant("MACI/Managers/Manager");
                DAOProxy managerDAO = cdbAccess.createDAO("MACI/Managers/Manager");

                LoggingConfig managerLoggingConfig = persistLoggingConfig(session, managerDAO, false);

                Manager manager = new Manager();
                manager.setConfiguration(config);
                manager.setLoggingConfig(managerLoggingConfig);
                manager.setStartup(managerDAO.get_string("Startup"));
                manager.setServiceComponents(managerDAO.get_string("ServiceComponents"));
                try {
                    manager.setServiceDaemons(managerDAO.get_string("ServiceDaemons"));
                } catch (CDBFieldDoesNotExistEx e) {
                    manager.setServiceDaemons(""); // Optional, but has no default!
                }
                manager.setTimeout((int) managerDAO.get_double("Timeout"));
                manager.setClientPingInterval((int) managerDAO.get_double("ClientPingInterval"));
                manager.setAdministratorPingInterval((int) managerDAO.get_double("AdministratorPingInterval"));
                manager.setContainerPingInterval((int) managerDAO.get_double("ContainerPingInterval"));
                manager.setServerThreads((byte) managerDAO.get_long("ServerThreads"));
                session.persist(manager);
                m_logger.info("Imported Manager from XML.");
            } catch (Throwable e) {
                m_logger.log(Level.WARNING,
                        "MACI/Managers/Manager record does not exist or misconfigured, using defaults.", e);
            }

            /*
            String containers = xmlCDB.list_nodes("MACI/Containers");
            StringTokenizer tokenizer = new StringTokenizer(containers);
            while (tokenizer.hasMoreTokens())
            {
               String containerName = tokenizer.nextToken();
            */
            StringTokenizer tokenizer;
            String[] containerSubnodes = getSubNodes(xmlCDB_, "MACI/Containers");
            for (String containerName : containerSubnodes) {
                //DAO containerDAO = xmlCDB.get_DAO_Servant("MACI/Containers/"+containerName);
                DAOProxy containerDAO = cdbAccess.createDAO("MACI/Containers/" + containerName);

                // check if real config, otherwice skip
                if (readLong(containerDAO, "LoggingConfig/minLogLevel", -1) < 0)
                    continue;

                LoggingConfig loggingConfig = persistLoggingConfig(session, containerDAO, true);

                Computer hostComputer = null;
                String computerHostName = readString(containerDAO, "DeployInfo/Host", null);
                if (computerHostName != null) {
                    hostComputer = (Computer) session.createCriteria(Computer.class)
                            .add(Restrictions.eq("networkName", computerHostName)).uniqueResult();
                    if (hostComputer == null) {
                        // NOTE: we add some dummy data as computer name, realtime flag, CPU type here
                        String computerName = computerHostName;
                        int dotPos = computerName.indexOf('.');
                        if (dotPos > 0)
                            computerName = computerName.substring(0, dotPos);
                        hostComputer = new Computer();
                        hostComputer.setName(computerName);
                        hostComputer.setConfiguration(config);
                        hostComputer.setNetworkName(computerHostName);
                        hostComputer.setRealTime(false);
                        hostComputer.setDiskless(false);
                        hostComputer.setProcessorType(ComputerProcessorType.UNI);
                        hostComputer.setPhysicalLocation(null);
                        session.persist(hostComputer);
                    }
                }

                final String containerPath;
                int hierarchySeparatorPos = containerName.lastIndexOf('/');
                if (hierarchySeparatorPos != -1) {
                    containerPath = containerName.substring(0, hierarchySeparatorPos);
                    containerName = containerName.substring(hierarchySeparatorPos + 1);
                } else
                    containerPath = "/"; // for Oracle

                Container container = new Container();
                container.setContainerName(containerName);
                container.setPath(containerPath);
                container.setConfiguration(config);
                container.setLoggingConfig(loggingConfig);
                container.setComputer(hostComputer);

                container.setImplLang(
                        ContainerImplLang.valueOfForEnum(readString(containerDAO, "ImplLang", "cpp"))); // cpp is default, since field is required
                container.setTypeModifiers(readString(containerDAO, "DeployInfo/TypeModifiers", null));
                container.setStartOnDemand(
                        Boolean.valueOf(readString(containerDAO, "DeployInfo/StartOnDemand", "false")));

                container.setRealTime(false);
                container.setRealTimeType(null);
                container.setKernelModuleLocation(null);
                container.setKernelModule(null);

                container.setKeepAliveTime(readLong(containerDAO, "DeployInfo/KeepAliveTime", -1));
                container.setServerThreads(containerDAO.get_long("ServerThreads"));
                container.setManagerRetry(containerDAO.get_long("ManagerRetry"));
                container.setCallTimeout((int) containerDAO.get_double("Timeout"));
                container.setRecovery(Boolean.valueOf(containerDAO.get_string("Recovery")));

                int pingInterval = readLong(containerDAO, "PingInterval", Integer.MIN_VALUE);
                if (pingInterval != Integer.MIN_VALUE)
                    container.setPingInterval(pingInterval);
                container.setAutoloadSharedLibs(containerDAO.get_string("Autoload"));
                session.persist(container);
                // convert the "Flags" string of concatenated options to ContainerStartupOption 
                String containerStartFlags = readString(containerDAO, "DeployInfo/Flags", null);
                ContainerStartupOptionHelper containerStartupOptionHelper = new ContainerStartupOptionHelper(
                        m_logger);
                Collection<ContainerStartupOption> contOptions = containerStartupOptionHelper
                        .convertFlagsString(container, containerStartFlags);
                for (ContainerStartupOption containerStartupOption : contOptions) {
                    session.persist(containerStartupOption);
                }
            }
            if (containerSubnodes.length > 0) {
                m_logger.info("Imported Containers from XML.");
            } else {
                m_logger.info("No XML container data found.");
            }

            // set of all existing component names
            // used to generate *, *1, *2 names, as CDB does
            // NOTE: initial set is not filled with component names that are already in the DB
            Set<String> existingComponentNames = new HashSet<String>();

            LinkedHashSet nodes = new LinkedHashSet();

            //DAO componentDAO = xmlCDB.get_DAO_Servant("MACI/Components");
            DAOProxy componentDAO = null;

            try {
                componentDAO = cdbAccess.createDAO("MACI/Components");

                // current
                nodes.add("/");
                String[] subnodes = getSubnodes(xmlCDB_, "MACI/Components");
                if (subnodes != null)
                    for (int i = 0; i < subnodes.length; i++)
                        nodes.add(subnodes[i]);
            } catch (RuntimeException rte) {
                m_logger.warning("Failed to read MACI/Components DAO, skipping...");
            }

            Iterator iter = nodes.iterator();
            while (iter.hasNext()) {
                String path = iter.next().toString();
                String prefix;
                if (path.length() == 0 || path.equals("/"))
                    prefix = "";
                else
                    prefix = path + "/";

                String components = (String) componentDAO.get_field_data(prefix + "_elements");

                // store "original" path/prefix (it can be changed)
                final String originalPath = path;
                final String originalPrefix = prefix;

                tokenizer = new StringTokenizer(components, ",");
                while (tokenizer.hasMoreTokens()) {
                    // set original values
                    path = originalPath;
                    prefix = originalPrefix;

                    String componentName = prefix + tokenizer.nextToken();

                    String realComponentName = readString(componentDAO, componentName + "/Name", null);
                    if (realComponentName == null)
                        continue;

                    // hierarchical name fix
                    int hierarchySeparatorPos = realComponentName.lastIndexOf('/');
                    if (hierarchySeparatorPos != -1)
                        realComponentName = realComponentName.substring(hierarchySeparatorPos + 1);

                    // handle duplicate names, i.e. "*"
                    // a "trick" of adding "/" to path is being used to achieve uniques
                    // "/////" is the same as "/" for TMCDB, but not for DB
                    while (existingComponentNames.contains(prefix + realComponentName)) {
                        path = path + "/";
                        prefix = prefix + "/";
                    }
                    existingComponentNames.add(prefix + realComponentName);

                    int componentContainerId = -1;
                    Container tmpComponentContainer = null;
                    String containerName = readString(componentDAO, componentName + "/Container", null);
                    if (containerName != null && !containerName.equals("*")) {

                        String containerPath;
                        hierarchySeparatorPos = containerName.lastIndexOf('/');
                        if (hierarchySeparatorPos != -1) {
                            containerPath = containerName.substring(0, hierarchySeparatorPos);
                            containerName = containerName.substring(hierarchySeparatorPos + 1);
                        } else {
                            containerPath = "/"; // for Oracle
                        }

                        Container container = (Container) session.createCriteria(Container.class)
                                .add(Restrictions.eq("configuration", config))
                                .add(Restrictions.eq("containerName", containerName))
                                .add(Restrictions.eq("path", containerPath)).uniqueResult();
                        if (container != null) {
                            componentContainerId = container.getContainerId();
                            tmpComponentContainer = container;
                        } else {
                            LoggingConfig loggingConfig = new LoggingConfig();
                            loggingConfig.setMinLogLevelDefault((byte) 2);
                            loggingConfig.setMinLogLevelLocalDefault((byte) 2);
                            loggingConfig.setCentralizedLogger("Log");
                            loggingConfig.setDispatchPacketSize((byte) 10);
                            loggingConfig.setImmediateDispatchLevel((byte) 10);
                            loggingConfig.setFlushPeriodSeconds((byte) 10);
                            loggingConfig.setMaxLogQueueSize(1000);
                            loggingConfig.setMaxLogsPerSecond(-1);
                            session.persist(loggingConfig);

                            container = new Container();
                            container.setContainerName(containerName);
                            container.setPath(containerPath);
                            container.setConfiguration(config);
                            container.setLoggingConfig(loggingConfig);
                            container.setComputer(null);
                            container.setImplLang(ContainerImplLang
                                    .valueOfForEnum(readString(componentDAO, "ImplLang", "cpp"))); // cpp is default, since field is required
                            container.setTypeModifiers(DUMMY_CONTAINER_FLAG);
                            container.setRealTime(false);
                            container.setRealTimeType(null);
                            container.setKernelModuleLocation(null);
                            container.setKernelModule(null);
                            container.setKeepAliveTime(-1);
                            container.setServerThreads(5);
                            container.setManagerRetry(10);
                            container.setCallTimeout(2);
                            container.setRecovery(false);
                            container.setAutoloadSharedLibs(null);
                            session.persist(container);
                            componentContainerId = container.getContainerId();
                            tmpComponentContainer = container;
                        }
                    }

                    String xml = null;
                    boolean almaBranchDoesNotExist = componentName.startsWith("*");
                    boolean forceSubcomponentCheck = false;

                    int typeId;
                    String type = componentDAO.get_string(componentName + "/Type");
                    DAOProxy componentConfigurationDAO = null; // pulled out for performance optimization, to avoid reading it twice in many cases
                    Schemas schema = null;

                    {
                        String schemaURN = null;

                        // check if it is a non-control device, simply check for existence of "ControlDevice" element
                        if (!almaBranchDoesNotExist) {
                            try {
                                // @TODO: Suppress the NOTICE log (or lower its level) which we get from the CDB code if there is no component configuration under the CDB/alma/ branch.
                                //        NOTICE [CDB-RDB] Curl 'alma/SCHEDULING_MASTERSCHEDULER' does not exist.
                                componentConfigurationDAO = cdbAccess
                                        .createDAO(COMPONENT_TREE_NAME + "/" + componentName);

                                schemaURN = componentConfigurationDAO.get_string("xmlns");

                                if (!processedComponentTypes.contains(type)) {
                                    boolean isControlDevice = !TMCDB_ACS_ONLY
                                            && xsdElementTypeResolver.doesExtend(schemaURN, "ControlDevice");
                                    m_logger.fine(schemaURN + " does extend Control? " + isControlDevice);
                                    if (!isControlDevice)
                                        nonControlDeviceSet.add(type);

                                    boolean isCharateristicsComponent = xsdElementTypeResolver
                                            .doesExtend(schemaURN, "CharacteristicComponent")
                                            || (TMCDB_ACS_ONLY && xsdElementTypeResolver.doesExtend(schemaURN,
                                                    "ControlDevice")); // sadly ControlDevice does not extend CharacteristicComponent XSD
                                    m_logger.fine(schemaURN + " does extend CharacteristicsComponent? "
                                            + isCharateristicsComponent);
                                    if (isCharateristicsComponent)
                                        characteristicsDeviceSet.add(type);

                                    processedComponentTypes.add(type);
                                }
                            } catch (Throwable th) {
                                almaBranchDoesNotExist = true;

                                // obviously not a control device (no component, i.e. alma, branch)
                                // NOTE: if this device is missing alma branch data (and as control device it should have it), 
                                // this type will not be identified as control device at all, also for all devices of this type
                                // (ComponentType is filled at first occurrence of the type) 
                                if (th.getCause() instanceof CDBRecordDoesNotExistEx) {
                                    // does not exists, this is OK... do not complain
                                } else if (th instanceof CDBFieldDoesNotExistEx) {
                                    // field does not exist, but it might have sub-components
                                    forceSubcomponentCheck = true;
                                } else {
                                    m_logger.log(AcsLogLevel.WARNING, "Failed to read component configuration: "
                                            + COMPONENT_TREE_NAME + "/" + componentName, th);
                                }
                            }
                        }

                        // get the Schema identifier for the schemaURN
                        schema = (Schemas) session.createCriteria(Schemas.class)
                                .add(Restrictions.eq("URN", schemaURN))
                                .add(Restrictions.eq("configuration", config)).uniqueResult();
                        if (schema == null && !almaBranchDoesNotExist)
                            m_logger.severe("Component " + componentName + " of XSD type " + schemaURN
                                    + " has no XSD file.");

                        ComponentType componentType = (ComponentType) session
                                .createCriteria(ComponentType.class).add(Restrictions.eq("IDL", type))
                                .uniqueResult();
                        if (componentType == null) {
                            componentType = new ComponentType();
                            componentType.setIDL(type);
                            session.saveOrUpdate(componentType);
                        }

                        typeId = componentType.getComponentTypeId();
                    }

                    boolean isControlDevice = !nonControlDeviceSet.contains(type) && !almaBranchDoesNotExist;
                    boolean isCharateristicsDevice = characteristicsDeviceSet.contains(type);
                    if (!isControlDevice && !isCharateristicsDevice && xml == null && !almaBranchDoesNotExist) {
                        xml = getComponentXML(xmlCDB_, componentName, xml);
                    }

                    Component component = new Component();
                    // TODO this can be optimized!!!
                    component.setComponentType((ComponentType) session.get(ComponentType.class, typeId));
                    component.setComponentName(realComponentName);
                    component.setConfiguration(config);
                    //                   component.setContainerId(componentContainerId);
                    component.setContainer(tmpComponentContainer); // TODO verify this and clean up
                    component.setImplLang(ComponentImplLang
                            .valueOfForEnum(readString(componentDAO, componentName + "/ImplLang", "cpp"))); // cpp is default, since field is required
                    component.setRealTime(false);
                    component.setCode(componentDAO.get_string(componentName + "/Code"));
                    component.setPath(path);
                    component.setIsAutostart(
                            Boolean.parseBoolean(componentDAO.get_string(componentName + "/Autostart")));
                    component.setIsDefault(
                            Boolean.parseBoolean(componentDAO.get_string(componentName + "/Default")));
                    component.setIsStandaloneDefined(true);
                    component.setIsControl(isControlDevice);
                    component.setKeepAliveTime(componentDAO.get_long(componentName + "/KeepAliveTime"));
                    component.setMinLogLevel(
                            (byte) readLong(componentDAO, componentName + "/ComponentLogger/minLogLevel", -1));
                    component.setMinLogLevelLocal((byte) readLong(componentDAO,
                            componentName + "/ComponentLogger/minLogLevelLocal", -1));
                    component.setXMLDoc(xml);
                    component.setURN(schema == null ? null : schema.getURN());
                    session.persist(component);
                    session.flush();

                    // try to create alma branch (if available)
                    if ((isControlDevice || isCharateristicsDevice) && !almaBranchDoesNotExist) {
                        try {
                            if (componentConfigurationDAO == null) {
                                componentConfigurationDAO = cdbAccess
                                        .createDAO(COMPONENT_TREE_NAME + "/" + componentName);
                            }
                            if (plugin != null && isControlDevice) {
                                plugin.controlDeviceImportEpilogue(session, config, cdbAccess, componentName,
                                        component);
                            }

                            Set<String> propertySet = new TreeSet<String>();
                            String[] propertyCandidates = componentConfigurationDAO.get_string_seq("_elements");
                            for (String propertyName : propertyCandidates) {
                                // check if really property
                                if (readString(componentConfigurationDAO, propertyName + "/format",
                                        null) != null) {
                                    m_logger.finer("Adding property " + propertyName);
                                    propertySet.add(propertyName);
                                }
                            }

                            if (propertySet.size() > 0) {
                                String[] properties = propertySet.toArray(new String[propertySet.size()]);

                                String defaultPropertyNs = componentConfigurationDAO.get_string("xmlns");
                                String[] propertyNs = new String[properties.length];
                                for (int i = 0; i < properties.length; i++)
                                    propertyNs[i] = readString(componentConfigurationDAO,
                                            properties[i] + "/xmlns", defaultPropertyNs);

                                ExtraDataFeatureUtil extraDataFeatureUtil = new ExtraDataFeatureUtil(m_logger);

                                String[] propertyTypes = xsdElementTypeResolver.getElementTypes(
                                        componentConfigurationDAO.getElementName(), propertyNs, properties);
                                for (int i = 0; i < properties.length; i++) {
                                    String propertyName = properties[i];
                                    if (propertyTypes[i] != null && propertyTypes[i].endsWith("Seq")) {
                                        propertyTypes[i] = propertyTypes[i].substring(0,
                                                propertyTypes[i].length() - 3);
                                    }

                                    BACIProperty baciPropertyType = new BACIProperty();
                                    baciPropertyType.setComponent(component);
                                    baciPropertyType.setPropertyName(propertyName);
                                    baciPropertyType.setDescription(nonEmptyString(
                                            componentConfigurationDAO.get_string(propertyName + "/description"),
                                            "-"));
                                    baciPropertyType.setFormat(nonEmptyString(
                                            componentConfigurationDAO.get_string(propertyName + "/format"),
                                            "%s"));
                                    baciPropertyType.setUnits(nonEmptyString(
                                            componentConfigurationDAO.get_string(propertyName + "/units"),
                                            "-"));
                                    baciPropertyType.setResolution(nonEmptyString(
                                            componentConfigurationDAO.get_string(propertyName + "/resolution"),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));

                                    baciPropertyType.setArchive_priority(componentConfigurationDAO
                                            .get_long(propertyName + "/archive_priority"));
                                    baciPropertyType.setArchive_min_int(componentConfigurationDAO
                                            .get_double(propertyName + "/archive_min_int"));
                                    baciPropertyType.setArchive_max_int(componentConfigurationDAO
                                            .get_double(propertyName + "/archive_max_int"));
                                    baciPropertyType
                                            .setArchive_suppress(Boolean.parseBoolean(componentConfigurationDAO
                                                    .get_string(propertyName + "/archive_suppress")));
                                    baciPropertyType.setArchive_mechanism(
                                            BACIPropArchMech.valueOfForEnum(nonEmptyString(
                                                    componentConfigurationDAO
                                                            .get_string(propertyName + "/archive_mechanism"),
                                                    "monitor_collector")));
                                    baciPropertyType.setDefault_timer_trig(componentConfigurationDAO
                                            .get_double(propertyName + "/default_timer_trig"));
                                    baciPropertyType.setMin_timer_trig(componentConfigurationDAO
                                            .get_double(propertyName + "/min_timer_trig"));

                                    baciPropertyType
                                            .setInitialize_devio(Boolean.parseBoolean(componentConfigurationDAO
                                                    .get_string(propertyName + "/initialize_devio")));

                                    /* P<type> */
                                    baciPropertyType.setMin_delta_trig(readDouble(componentConfigurationDAO,
                                            propertyName + "/min_delta_trig", 0.0));
                                    baciPropertyType.setDefault_value(nonEmptyString(componentConfigurationDAO
                                            .get_string(propertyName + "/default_value"), "-"));

                                    baciPropertyType
                                            .setGraph_min(limitDouble(readDouble(componentConfigurationDAO,
                                                    propertyName + "/graph_min", null)));
                                    baciPropertyType
                                            .setGraph_max(limitDouble(readDouble(componentConfigurationDAO,
                                                    propertyName + "/graph_max", null)));
                                    baciPropertyType.setMin_step(readDouble(componentConfigurationDAO,
                                            propertyName + "/min_step", null));
                                    baciPropertyType.setArchive_delta(readDouble(componentConfigurationDAO,
                                            propertyName + "/archive_delta", 0.0));
                                    baciPropertyType
                                            .setArchive_delta_percent(readDouble(componentConfigurationDAO,
                                                    propertyName + "/archive_delta_percent", null));

                                    /* RO<type> */
                                    baciPropertyType.setAlarm_high_on(readDouble(componentConfigurationDAO,
                                            propertyName + "/alarm_high_on", null));
                                    baciPropertyType.setAlarm_low_on(readDouble(componentConfigurationDAO,
                                            propertyName + "/alarm_low_on", null));
                                    baciPropertyType.setAlarm_high_off(readDouble(componentConfigurationDAO,
                                            propertyName + "/alarm_high_off", null));
                                    baciPropertyType.setAlarm_low_off(readDouble(componentConfigurationDAO,
                                            propertyName + "/alarm_low_off", null));
                                    baciPropertyType.setAlarm_timer_trig(readDouble(componentConfigurationDAO,
                                            propertyName + "/alarm_timer_trig", null));

                                    /* RW<type> */
                                    baciPropertyType
                                            .setMin_value(limitDouble(readDouble(componentConfigurationDAO,
                                                    propertyName + "/min_value", null)));
                                    baciPropertyType
                                            .setMax_value(limitDouble(readDouble(componentConfigurationDAO,
                                                    propertyName + "/max_value", null)));

                                    /* ROpattern */
                                    baciPropertyType.setBitDescription(nonEmptyString(
                                            readString(componentConfigurationDAO,
                                                    propertyName + "/bitDescription", null),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));
                                    baciPropertyType.setWhenSet(nonEmptyString(
                                            readString(componentConfigurationDAO, propertyName + "/whenSet",
                                                    null),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));
                                    baciPropertyType.setWhenCleared(nonEmptyString(
                                            readString(componentConfigurationDAO, propertyName + "/whenCleared",
                                                    null),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));

                                    /* PEnum */
                                    baciPropertyType.setStatesDescription(nonEmptyString(
                                            readString(componentConfigurationDAO,
                                                    propertyName + "/statesDescription", null),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));
                                    baciPropertyType.setCondition(nonEmptyString(
                                            readString(componentConfigurationDAO, propertyName + "/condition",
                                                    null),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));
                                    baciPropertyType.setAlarm_on(nonEmptyString(
                                            readString(componentConfigurationDAO, propertyName + "/alarm_on",
                                                    null),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));
                                    baciPropertyType.setAlarm_off(nonEmptyString(
                                            readString(componentConfigurationDAO, propertyName + "/alarm_off",
                                                    null),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));

                                    /* alarms */
                                    baciPropertyType.setAlarm_fault_family(nonEmptyString(
                                            readString(componentConfigurationDAO,
                                                    propertyName + "/alarm_fault_family", null),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));
                                    baciPropertyType.setAlarm_fault_member(nonEmptyString(
                                            readString(componentConfigurationDAO,
                                                    propertyName + "/alarm_fault_member", null),
                                            EmptyStringHandlerBACIPropertyType.EMPTY_STRING_SUBSTITUTE));
                                    int level = readLong(componentConfigurationDAO,
                                            propertyName + "/alarm_level", Integer.MIN_VALUE);
                                    if (level != Integer.MIN_VALUE)
                                        baciPropertyType.setAlarm_level(level);

                                    baciPropertyType.setData(extraDataFeatureUtil.getExtraDataMap(
                                            componentConfigurationDAO, propertyName, baciPropertyAttributesSet,
                                            ExtraDataFeatureUtil.EMPTY_SET));

                                    session.persist(baciPropertyType);
                                }

                                // add non-property elements
                                propertySet.add("Address"); // this is handled by HW plugin
                                component.setXMLDoc(
                                        extraDataFeatureUtil.getExtraDataMap(componentConfigurationDAO, null,
                                                ExtraDataFeatureUtil.EMPTY_SET, propertySet));
                                session.update(component);
                            } else {
                                // no properties, add entire XML although it is a control device
                                component.setXMLDoc(
                                        xml == null ? getComponentXML(xmlCDB_, componentName, xml) : xml);
                                session.update(component);
                            }

                            // from remote, since DAO will compact it
                            if (!almaBranchDoesNotExist || forceSubcomponentCheck) {
                                String componentNodes = xmlCDB_
                                        .list_nodes(COMPONENT_TREE_NAME + "/" + componentName);
                                if (componentNodes != null) {
                                    StringTokenizer tokenizer2 = new StringTokenizer(componentNodes);
                                    while (tokenizer2.hasMoreTokens())
                                        propertySet.add(tokenizer2.nextToken());
                                }
                            }
                        } catch (RuntimeException rte) {
                            // ignore components with no configuration; this is very ugly wat of doing it...
                            if (rte.getMessage() != null && rte.getMessage().startsWith("Failed to obtain")) {
                                // noop (there is no configuration for component)
                            } else
                                rte.printStackTrace();
                        }
                    }
                }
            }
            if (nodes.size() > 0) {
                // if the preceding while loop actually did something...
                m_logger.info("Imported Components from XML.");
            }

            //
            // Channels configurations
            //
            String[] channelSubnodes = getSubNodes(xmlCDB_, "MACI/Channels");
            for (String channelName : channelSubnodes) {
                //DAO channelDAO = xmlCDB.get_DAO_Servant("MACI/Channels/"+channelName);
                DAOProxy channelDAO = cdbAccess.createDAO("MACI/Channels/" + channelName);

                final String channelPath;
                final String channelShortName;
                int hierarchySeparatorPos = channelName.lastIndexOf('/');
                if (hierarchySeparatorPos != -1) {
                    channelPath = channelName.substring(0, hierarchySeparatorPos);
                    channelShortName = channelName.substring(hierarchySeparatorPos + 1);
                } else {
                    channelPath = "/"; // for Oracle
                    channelShortName = channelName;
                }

                EventChannel eventChannel = new EventChannel();
                eventChannel.setConfiguration(config);
                eventChannel.setName(channelShortName);
                eventChannel.setPath(channelPath);
                eventChannel.setIntegrationLogs(
                        Boolean.valueOf(readString(channelDAO, "IntegrationLogs", "false")));
                eventChannel.setMaxQueueLength(readLong(channelDAO, "MaxQueueLength", 0));
                eventChannel.setMaxConsumers(readLong(channelDAO, "MaxConsumers", 0));
                eventChannel.setMaxSuppliers(readLong(channelDAO, "MaxSuppliers", 0));
                eventChannel.setRejectNewEvents(
                        Boolean.valueOf(readString(channelDAO, "RejectNewEvents", "false")));
                eventChannel.setDiscardPolicy(EventChannelDiscardPolicy
                        .valueOfForEnum(readString(channelDAO, "DiscardPolicy", "AnyOrder")));
                eventChannel.setEventReliability(EventChannelEventReliability
                        .valueOfForEnum(readString(channelDAO, "EventReliability", "BestEffort")));
                eventChannel.setConnectionReliability(EventChannelConReliability
                        .valueOfForEnum(readString(channelDAO, "ConnectionReliability", "BestEffort")));
                eventChannel.setPriority((short) readLong(channelDAO, "Priority", 0));
                eventChannel.setTimeout(readLong(channelDAO, "Timeout", 0));
                eventChannel.setOrderPolicy(EventChannelOrderPolicy
                        .valueOfForEnum(readString(channelDAO, "OrderPolicy", "AnyOrder")));
                eventChannel.setStartTimeSupported(
                        Boolean.valueOf(readString(channelDAO, "StartTimeSupported", "false")));
                eventChannel.setStopTimeSupported(
                        Boolean.valueOf(readString(channelDAO, "StopTimeSupported", "false")));
                eventChannel.setMaxEventsPerConsumer(readLong(channelDAO, "MaxEventsPerConsumer", 0));

                session.persist(eventChannel);

                Set<Event> eventSet = eventChannel.getEvents();
                String[] events = readStringSeq(channelDAO, "Events", null);
                if (events != null) {
                    for (String eventName : events) {
                        Event event = new Event();
                        event.setName(eventName);
                        event.setEventChannel(eventChannel);
                        event.setMaxProcessTime(readDouble(channelDAO, eventName + "/MaxProcessTime", 2.0));
                        eventSet.add(event);
                        session.persist(event);
                    }
                }

            }

            try {
                DAOProxy notificationServiceMappingDAO = cdbAccess
                        .createDAO("MACI/Channels/NotificationServiceMapping");

                String defaultNotSrv = notificationServiceMappingDAO.get_string("DefaultNotificationService");

                NotificationServiceMapping mappings = new NotificationServiceMapping();
                mappings.setConfiguration(config);
                mappings.setDefaultNotificationService(defaultNotSrv);
                session.persist(mappings);

                String[] domains = readStringSeq(notificationServiceMappingDAO, "Domains", null);
                if (domains != null) {
                    for (String domain : domains) {
                        String name = notificationServiceMappingDAO.get_string("Domains/" + domain + "/Name");
                        String notSrv = notificationServiceMappingDAO
                                .get_string("Domains/" + domain + "/NotificationService");
                        DomainsMapping domainsMapping = new DomainsMapping();
                        domainsMapping.setNotificationServiceMapping(mappings);
                        domainsMapping.setName(name);
                        domainsMapping.setNotificationService(notSrv);
                        mappings.getDomainsMappings().add(domainsMapping);
                        session.persist(domainsMapping);
                    }
                }

                String[] channels = readStringSeq(notificationServiceMappingDAO, "Channels_", null);
                if (channels != null) {
                    for (String channel : channels) {
                        String name = notificationServiceMappingDAO
                                .get_string("Channels_/" + channel + "/Name");
                        String notSrv = notificationServiceMappingDAO
                                .get_string("Channels_/" + channel + "/NotificationService");
                        ChannelMapping channelsMapping = new ChannelMapping();
                        channelsMapping.setNotificationServiceMapping(mappings);
                        channelsMapping.setName(name);
                        channelsMapping.setNotificationService(notSrv);
                        mappings.getChannelMappings().add(channelsMapping);
                        session.persist(channelsMapping);
                    }
                }

            } catch (RuntimeException re) {
                // no mappings
            }
            m_logger.info("Imported Notification Channels from XML.");

            // plugin importEpilogue()
            if (plugin != null) {
                try {
                    plugin.importEpilogue(session, config, cdbAccess);
                } catch (Throwable th) {
                    // @TODO: Decent exception log.
                    th.printStackTrace();
                }
            }

            hibernateUtil.commitTransaction();

            m_logger.info("Configuration from XML CDB loaded.");
        } catch (CDBFieldDoesNotExistEx ex) {
            throw AcsJCDBFieldDoesNotExistEx.fromCDBFieldDoesNotExistEx(ex);
        } catch (WrongCDBDataTypeEx ex) {
            throw AcsJWrongCDBDataTypeEx.fromWrongCDBDataTypeEx(ex);
        } catch (Throwable th) {
            throw new RuntimeException("Failed to fill-in the DB from CDB.", th);
        } finally {
            hibernateUtil.closeSession();
            cdbAccess.destroy();

            xmlCDB_._release();
            servantDelegate.shutdownEmbeddedWDALImpl();
            // destroy POA
            xmlCDBPOA.destroy(true, false);
        }

        return true;
    } catch (Throwable th) {
        m_logger.log(Level.SEVERE, "Failed to load XML CDB, exiting...", th);
        return false;
    } finally {
        loadInProgress.set(false);
    }
}

From source file:com.court.controller.BranchFxmlController.java

@FXML
private void onBranchSaveBtnAction(ActionEvent event) throws IOException {
    if (isValidationEmpty()) {
        Alert alert_error = new Alert(Alert.AlertType.ERROR);
        alert_error.setTitle("Error");
        alert_error.setHeaderText("Empty Fields !");
        alert_error.setContentText(PropHandler.getStringProperty("empty_fields"));
        alert_error.show();//w w  w .  j a  va 2 s.  co m
        return;
    }
    if (validationSupport.validationResultProperty().get().getErrors().isEmpty()) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Branch branch;
        int id = getIdByBranchCode(session, br_id_txt.getText().trim());
        if (id != 0) {
            branch = (Branch) session.load(Branch.class, id);
            parent_id = branch.getParentId();
        } else {
            branch = new Branch();
        }

        branch.setBranchCode(br_id_txt.getText().trim());
        branch.setBranchName(branch_name_txt.getText().trim());
        branch.setAddress(branch_adrs_txt.getText());
        branch.setBranchType(branch_type_combo.getSelectionModel().getSelectedItem());
        branch.setContactNo(branch_tel_txt.getText());
        branch.setDescription(branch_des_txt.getText().isEmpty() ? "No Description" : branch_des_txt.getText());
        branch.setStatus(true);
        branch.setParentId(parent_id);
        session.saveOrUpdate(branch);
        session.getTransaction().commit();
        session.close();

        Alert alert_info = new Alert(Alert.AlertType.INFORMATION);
        alert_info.setTitle("Information");
        alert_info.setHeaderText("Successfully Saved !");
        alert_info.setContentText(
                "You have successfully saved the \"" + branch_name_txt.getText() + "\" \n " + "branch.");
        Optional<ButtonType> result = alert_info.showAndWait();
        if (result.get() == ButtonType.OK) {
            FxUtilsHandler.clearFields(branch_grid_pane);
            fillBranchCodeTxt(br_id_txt);

            ObservableList<Branch> allBranches = getAllBranches();
            initBranchTable(allBranches, false);
            List<String> branchCodes = allBranches.stream().map(Branch::getBranchCode)
                    .collect(Collectors.toList());
            List<String> branchNames = allBranches.stream().map(Branch::getBranchName)
                    .collect(Collectors.toList());
            TextFields.bindAutoCompletion(branch_search_id, branchCodes);
            TextFields.bindAutoCompletion(branch_search_name, branchNames);
            btitle_pane.setContent(branch_search_grid_pane);
            parent_id = 0;

        }

    } else {
        Alert alert_error = new Alert(Alert.AlertType.ERROR);
        alert_error.setTitle("Error");
        alert_error.setHeaderText("Missing Fields !");
        alert_error.setContentText("You have some missing fields left. Move the cursor to the red \"X\""
                + " sign and find the error.");
        alert_error.show();
    }

}

From source file:com.court.controller.LoanFxmlController.java

@FXML
private void onSaveBtnAction(ActionEvent event) throws IOException {
    if (isValidationEmpty()) {
        Alert alert_error = new Alert(Alert.AlertType.ERROR);
        alert_error.setTitle("Error");
        alert_error.setHeaderText("Empty Fields !");
        alert_error.setContentText(PropHandler.getStringProperty("empty_fields"));
        alert_error.show();// ww  w  .  jav a2  s. c o  m
        return;
    }
    if (validationSupport.validationResultProperty().get().getErrors().isEmpty()) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Loan loan;
        int id = getIdByLoanCode(session, loan_id_txt.getText().trim());
        if (id != 0) {
            loan = (Loan) session.load(Loan.class, id);
        } else {
            loan = new Loan();
        }

        autoDetectRepayCycle();
        loan.setLoanId(loan_id_txt.getText().trim());
        loan.setLoanName(loan_name_txt.getText());
        loan.setInterestMethod(int_method_combo.getSelectionModel().getSelectedItem());
        loan.setLoanInterest(TextFormatHandler.getPercentageFieldValue(loan_int_txt));
        loan.setInterestPer(loan_int_combo.getSelectionModel().getSelectedItem());
        loan.setLoanDuration(Integer.parseInt(loan_due_txt.getText().trim()));
        loan.setDurationPer(loan_due_combo.getSelectionModel().getSelectedItem());
        loan.setRepaymentCycle("Monthly");
        loan.setNoOfRepay(Integer.parseInt(repay_txt.getText().trim()));
        loan.setStatus(true);
        session.saveOrUpdate(loan);
        session.getTransaction().commit();
        session.close();

        Alert alert_info = new Alert(Alert.AlertType.INFORMATION);
        alert_info.setTitle("Information");
        alert_info.setHeaderText("Successfully Saved !");
        alert_info.setContentText("You have successfully saved \"" + loan_name_txt.getText() + "\"");
        Optional<ButtonType> result = alert_info.showAndWait();
        if (result.get() == ButtonType.OK) {
            FxUtilsHandler.clearFields(save_grid, loan_int_hbox, loan_due_hbox, loan_repay_hbox);
            fillLoanCodeTxt(loan_id_txt);

            ObservableList<Loan> allLoans = getAllLoans();
            initLoanTable(allLoans);
            List<String> loanCodes = allLoans.stream().map(Loan::getLoanId).collect(Collectors.toList());
            List<String> loanNames = allLoans.stream().map(Loan::getLoanName).collect(Collectors.toList());
            TextFields.bindAutoCompletion(loan_search_id_txt, loanCodes);
            TextFields.bindAutoCompletion(loan_search_name_txt, loanNames);
        }
    } else {
        Alert alert_error = new Alert(Alert.AlertType.ERROR);
        alert_error.setTitle("Error");
        alert_error.setHeaderText("Missing Fields !");
        alert_error.setContentText("You have some missing fields left. Move the cursor to the red \"X\""
                + " sign and find the error.");
        alert_error.show();
    }
}

From source file:com.court.controller.MemberfxmlController.java

@FXML
private void onMemberSaveBtnAction(ActionEvent event) throws IOException {
    if (isValidationEmpty(validationSupport)) {
        Alert alert_error = new Alert(Alert.AlertType.ERROR);
        alert_error.setTitle("Error");
        alert_error.setHeaderText("Empty Fields !");
        alert_error.setContentText(PropHandler.getStringProperty("empty_fields"));
        alert_error.show();/*  ww  w  .j ava 2  s .  c o  m*/
        return;
    }

    Predicate<String> predicate = (t) -> {
        return memberCodes.contains(t);
    };

    if (!isSearch && predicate.test(member_code_txt.getText())) {
        Alert alert_error = new Alert(Alert.AlertType.ERROR);
        alert_error.setTitle("Error");
        alert_error.setHeaderText("Member already exist.");
        alert_error.setContentText("You have already saved this member " + member_code_txt.getText());
        alert_error.show();
        return;
    }

    if (validationSupport.validationResultProperty().get().getErrors().isEmpty()) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            Member member;
            int id = getIdByMemberCode(session, member_code_txt.getText().trim());
            if (id != 0) {
                member = (Member) session.load(Member.class, id);
                updateMemberStatus(member_status_combo.getSelectionModel().getSelectedItem(), member,
                        hndler.loggedUser(), session);
            } else {
                member = new Member();
                member.setMemberId(member_code_txt.getText().trim());
                member.setNic(nic_no.getText());
            }

            member.setEmpId(emp_id_txt.getText());
            member.setJobStatus(job_status_combo.getSelectionModel().getSelectedItem());
            //member.setPaymentOfficer(payment_officer_txt.getText());
            member.setFullName(member_full_name_txt.getText());
            member.setNameWithIns(member_namins_txt.getText());
            member.setAddress(member_adrs_txt.getText());
            member.setJobTitle(member_job_txt.getText());
            member.setBranch(getBranchByName(session, member_brch_txt.getText().trim()));
            member.setTel1(member_tel1_txt.getText());
            member.setTel2(member_tel2_txt.getText());
            member.setEmail(member_email_txt.getText());
            member.setSex(member_sex_combo.getSelectionModel().getSelectedItem());
            member.setCurStatus(member_status_combo.getSelectionModel().getSelectedItem());
            member.setMaritalStatus(member_maritial_combo.getSelectionModel().getSelectedItem());
            member.setDob(FxUtilsHandler.getDateFrom(member_bday_chooser.getValue()));
            member.setAppintedDate(Date.valueOf(member_apo_chooser.getValue()));
            member.setJoinedDate(FxUtilsHandler.getDateFrom(member_join_chooser.getValue()));
            member.setOverpay(0.0);
            member.setZeroOverpay(0.0);
            member.setStatus(member.getCurStatus().equalsIgnoreCase("Active"));
            member.setDescription(
                    member_des_txt.getText().isEmpty() ? "No Description" : member_des_txt.getText());
            //  member.setImgPath(imgString == null ? "" : imgString.getImg_path().toString());
            //   member.setStatus(true);
            if (payBranch != null) {
                member.setPayOffice(payBranch);
            }
            session.saveOrUpdate(member);
            session.getTransaction().commit();
        } catch (Exception e) {
            if (session.getTransaction() != null) {
                session.getTransaction().rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }

        Alert alert_info = new Alert(Alert.AlertType.INFORMATION);
        alert_info.setTitle("Information");
        alert_info.setHeaderText("Successfully Saved !");
        alert_info.setContentText("You have successfully saved member \"" + member_namins_txt.getText() + "\"");
        Optional<ButtonType> result = alert_info.showAndWait();
        if (result.get() == ButtonType.OK) {
            FxUtilsHandler.clearFields(main_grid_pane, date_hbox, tel_hbox, nic_col_id, working_box,
                    job_title_box);
            fillMemberCodeTxt(member_code_txt);
            imgString = null;
            member_img.setImage(new Image(getClass().getResourceAsStream(FileHandler.MEMBER_DEFAULT_IMG)));

            ObservableList<Member> allMembers = getAllMembers();
            List<String> memberCodes = allMembers.stream().map(Member::getMemberId)
                    .collect(Collectors.toList());
            List<String> memberNames = allMembers.stream().map(Member::getFullName)
                    .collect(Collectors.toList());
            List<String> memberJobs = allMembers.stream()
                    .filter(FxUtilsHandler.distinctByKey(p -> p.getJobTitle())).map(Member::getJobTitle)
                    .collect(Collectors.toList());
            p1.clearSuggestions();
            p1.addPossibleSuggestions(memberCodes);
            p2.clearSuggestions();
            p2.addPossibleSuggestions(memberNames);
            p3.clearSuggestions();
            p3.addPossibleSuggestions(memberJobs);
            identifyCodesEditable(true);
            isSearch = false;
            disableTabs(true);
            FxUtilsHandler.activeDeactiveChildrenControls(true, main_grid_pane, date_hbox, tel_hbox);
            FxUtilsHandler.activeBtnAppearanceChange(member_deactive_btn, true, true);
            deactive_label.setText("");

        }
    } else {
        Alert alert_error = new Alert(Alert.AlertType.ERROR);
        alert_error.setTitle("Error");
        alert_error.setHeaderText("Missing Fields !");
        alert_error.setContentText(PropHandler.getStringProperty("missing_fields"));
        alert_error.show();
    }
}

From source file:com.court.controller.MemberfxmlController.java

private void formChildrenInputDesign(String titleS, MemChild mc) {

    ValidationSupport va = new ValidationSupport();
    GridPane gpane = new GridPane();
    ColumnConstraints c1 = new ColumnConstraints();
    c1.setHgrow(Priority.SOMETIMES);/*  ww w. j a  v a 2  s  . c o  m*/
    c1.setPrefWidth(100.0);
    c1.setMinWidth(10.0);

    ColumnConstraints c2 = new ColumnConstraints();
    c2.setHgrow(Priority.ALWAYS);
    c2.setPrefWidth(100.0);
    c2.setMinWidth(10.0);

    RowConstraints r1 = new RowConstraints();
    r1.setMinHeight(10.0);
    r1.setPrefHeight(30.0);
    r1.setVgrow(Priority.SOMETIMES);

    RowConstraints r2 = new RowConstraints();
    r2.setMinHeight(10.0);
    r2.setPrefHeight(30.0);
    r2.setVgrow(Priority.SOMETIMES);

    RowConstraints r3 = new RowConstraints();
    r3.setMinHeight(10.0);
    r3.setPrefHeight(30.0);
    r3.setVgrow(Priority.SOMETIMES);

    RowConstraints r4 = new RowConstraints();
    r4.setMinHeight(10.0);
    r4.setPrefHeight(30.0);
    r4.setVgrow(Priority.SOMETIMES);

    RowConstraints r5 = new RowConstraints();
    r5.setMinHeight(10.0);
    r5.setPrefHeight(30.0);
    r5.setVgrow(Priority.SOMETIMES);

    RowConstraints r6 = new RowConstraints();
    r6.setMinHeight(20.0);
    r6.setPrefHeight(40.0);
    r6.setVgrow(Priority.SOMETIMES);

    gpane.setStyle("-fx-border-color: #ffff; -fx-border-width: 2px;");
    gpane.getColumnConstraints().addAll(c1, c2);
    gpane.getRowConstraints().addAll(r1, r2, r3, r4, r5, r6);

    Label title = new Label(titleS.toUpperCase());
    title.setFont(new Font(18.0));
    title.setUnderline(true);
    GridPane.setColumnSpan(title, 2);
    GridPane.setRowIndex(title, 0);

    Label cname = new Label("Child Name");
    GridPane.setRowIndex(cname, 1);
    GridPane.setColumnIndex(cname, 0);

    Label dob = new Label("Date of Birth");
    GridPane.setRowIndex(dob, 2);
    GridPane.setColumnIndex(dob, 0);

    Label sex = new Label("Sex");
    GridPane.setRowIndex(sex, 3);
    GridPane.setColumnIndex(sex, 0);

    Label hoi = new Label("HOI");
    GridPane.setRowIndex(hoi, 4);
    GridPane.setColumnIndex(hoi, 0);

    Label aci = new Label("ACI");
    GridPane.setRowIndex(aci, 5);
    GridPane.setColumnIndex(aci, 0);

    TextField cname_txt = new TextField();
    GridPane.setRowIndex(cname_txt, 1);
    GridPane.setColumnIndex(cname_txt, 1);
    va.registerValidator(cname_txt, Validator.createEmptyValidator("This field is not optional !"));
    cname_txt.setText(mc != null ? mc.getName() : "");

    DatePicker dob_p = new DatePicker();
    FxUtilsHandler.setDatePickerTimeFormat(dob_p);
    GridPane.setRowIndex(dob_p, 2);
    GridPane.setColumnIndex(dob_p, 1);
    va.registerValidator(dob_p, Validator.createEmptyValidator("Please select the date of birth !"));
    dob_p.setValue(mc != null ? FxUtilsHandler.getLocalDateFrom(mc.getDob()) : null);

    ComboBox<String> sex_box = new ComboBox();
    sex_box.setPromptText("-- SELECT --");
    sex_box.setItems(FXCollections.observableArrayList("Male", "Female"));
    va.registerValidator(sex_box, Validator.createEmptyValidator("Sex cannot be empty !"));
    GridPane.setRowIndex(sex_box, 3);
    GridPane.setColumnIndex(sex_box, 1);
    if (mc != null) {
        sex_box.getSelectionModel().select(mc.getSex());
    }

    CheckBox hoi_chk = new CheckBox();
    GridPane.setRowIndex(hoi_chk, 4);
    GridPane.setColumnIndex(hoi_chk, 1);
    hoi_chk.setSelected(mc != null ? mc.isHoi() : false);

    CheckBox aci_chk = new CheckBox();
    GridPane.setRowIndex(aci_chk, 5);
    GridPane.setColumnIndex(aci_chk, 1);
    aci_chk.setSelected(mc != null ? mc.isAci() : false);

    Button sav_btn = new Button("Save");
    sav_btn.setStyle("-fx-text-fill: #ffff;");
    sav_btn.getStyleClass().add("btn");
    sav_btn.getStyleClass().add("btn-primary");
    sav_btn.setOnAction(((event) -> {
        if (isValidationEmpty(va)) {
            Alert alert_error = new Alert(Alert.AlertType.ERROR);
            alert_error.setTitle("Error");
            alert_error.setHeaderText("Empty Fields !");
            alert_error.setContentText("You have some empty fields left !.");
            alert_error.show();
            return;
        }
        if (va.validationResultProperty().get().getErrors().isEmpty()) {
            MemChild mchild;
            if (mc != null) {
                mchild = mc;
                mchild.setAci(aci_chk.isSelected());
                mchild.setHoi(hoi_chk.isSelected());
                mchild.setName(cname_txt.getText());
                mchild.setSex(sex_box.getSelectionModel().getSelectedItem());
                mchild.setDob(FxUtilsHandler.getDateFrom(dob_p.getValue()));
            } else {
                mchild = new MemChild();
                mchild.setAci(aci_chk.isSelected());
                mchild.setHoi(hoi_chk.isSelected());
                mchild.setName(cname_txt.getText());
                mchild.setSex(sex_box.getSelectionModel().getSelectedItem());
                mchild.setDob(FxUtilsHandler.getDateFrom(dob_p.getValue()));
                mchild.setMember(getMemberByCode(member_code_txt.getText()));
            }
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            session.saveOrUpdate(mchild);
            session.getTransaction().commit();
            session.close();
            Alert alert_success = new Alert(Alert.AlertType.INFORMATION);
            alert_success.setTitle("Success");
            alert_success.setHeaderText("Successfully Saved");
            alert_success.setContentText("You have successfully save the child.");
            Optional<ButtonType> result = alert_success.showAndWait();
            if (result.get() == ButtonType.OK) {
                initMemChildTable(getChildrenOfMember(member_code_txt.getText()));
                family_info_vbox.getChildren().clear();
                family_info_vbox.getChildren().add(family_gridbox);
            }
        }

    }));

    Button cancel_btn = new Button("Cancel");
    cancel_btn.setStyle("-fx-text-fill: #ffff;");
    cancel_btn.getStyleClass().add("btn");
    cancel_btn.getStyleClass().add("btn-warning");
    cancel_btn.setOnAction((ActionEvent event) -> {
        family_info_vbox.getChildren().clear();
        family_info_vbox.getChildren().add(family_gridbox);

    });

    HBox btn_box = new HBox(sav_btn, cancel_btn);
    btn_box.setAlignment(Pos.CENTER_RIGHT);
    btn_box.setSpacing(5.0);
    GridPane.setRowIndex(btn_box, 6);
    GridPane.setColumnIndex(btn_box, 1);

    gpane.getChildren().addAll(title, cname, dob, sex, hoi, aci, cname_txt, dob_p, sex_box, hoi_chk, aci_chk,
            btn_box);
    family_info_vbox.getChildren().clear();
    family_info_vbox.getChildren().add(gpane);
}

From source file:com.court.controller.MemberfxmlController.java

private void hibernateSaveMemberSubscriptions(MemberSubscription ms, MemberSubscriptions mm, Session session,
        Member member) {/*from  ww  w.j  a v a  2  s. co m*/
    switch (ms.getFeeName()) {

    case "Membership Fee":
        mm.setMemberSubscription(ms);
        mm.setMember(member);
        mm.setAmount(TextFormatHandler.getCurrencyFieldValue(mem_fee_txt));
        mm.setRepaymentType(mem_fee_repay_combo.getSelectionModel().getSelectedItem());
        session.saveOrUpdate(mm);
        break;
    case "Savings Fee":
        mm.setMemberSubscription(ms);
        mm.setMember(member);
        mm.setAmount(TextFormatHandler.getCurrencyFieldValue(sav_fee_txt));
        mm.setRepaymentType(sav_fee_repay_combo.getSelectionModel().getSelectedItem());
        session.saveOrUpdate(mm);
        break;
    case "HOI Fee":
        mm.setMemberSubscription(ms);
        mm.setMember(member);
        mm.setAmount(TextFormatHandler.getCurrencyFieldValue(hoi_fee_txt));
        mm.setRepaymentType(hoi_fee_repay_combo.getSelectionModel().getSelectedItem());
        session.saveOrUpdate(mm);
        break;
    case "ACI Fee":
        mm.setMemberSubscription(ms);
        mm.setMember(member);
        mm.setAmount(TextFormatHandler.getCurrencyFieldValue(aci_fee_txt));
        mm.setRepaymentType(aci_fee_repay_combo.getSelectionModel().getSelectedItem());
        session.saveOrUpdate(mm);
        break;
    case "Optional":
        mm.setMemberSubscription(ms);
        mm.setMember(member);
        mm.setAmount(TextFormatHandler.getCurrencyFieldValue(optional_txt));
        mm.setRepaymentType(opt_fee_repay_combo.getSelectionModel().getSelectedItem());
        session.saveOrUpdate(mm);
        break;
    case "Admission Fee":
        mm.setMemberSubscription(ms);
        mm.setMember(member);
        mm.setAmount(TextFormatHandler.getCurrencyFieldValue(adm_fee_txt));
        mm.setRepaymentType(adm_fee_repay_combo.getSelectionModel().getSelectedItem());
        session.saveOrUpdate(mm);
        break;
    }
}

From source file:com.court.controller.UserManageFxmlController.java

@FXML
private void saveBtnAction(ActionEvent event) throws IOException {
    //user save validation problem :(---------
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();/*from   w w w  .  ja va2s . com*/
    UserHasUserRole uhur;
    int id = getUHasRoleIdByUserName(session, user_name_txt.getText());
    if (id != 0) {
        uhur = (UserHasUserRole) session.load(UserHasUserRole.class, id);
        //  ValidationSupport.setRequired(user_name_txt, true);
    } else {
        uhur = new UserHasUserRole();
    }

    if (isValidationEmpty()) {
        Alert alert_error = new Alert(Alert.AlertType.ERROR);
        alert_error.setTitle("Error");
        alert_error.setHeaderText("Empty Fields !");
        alert_error.setContentText(PropHandler.getStringProperty("empty_fields"));
        alert_error.show();
        return;
    }
    if (validationSupport.validationResultProperty().get().getErrors().isEmpty()) {

        User u = new User();
        u.setFullName(full_name_txt.getText());
        u.setUserName(user_name_txt.getText());
        u.setEmail(email_txt.getText());
        u.setAddress(address_txt.getText());
        u.setTel(tele_txt.getText());
        u.setImgPath(imgString == null ? "" : imgString.getImg_path().toString());
        u.setStatus(true);

        uhur.setUser(u);
        uhur.setUserRole(getUserRoleFrom(usr_role_combo.getSelectionModel().getSelectedItem(), session));
        session.saveOrUpdate(uhur);
        session.getTransaction().commit();
        session.close();

        Alert alert_success = new Alert(Alert.AlertType.INFORMATION);
        alert_success.setTitle("Success");
        alert_success.setHeaderText("Successfully Saved !");
        alert_success.setContentText("You have successfully saved" + " \"" + full_name_txt.getText() + "\".");
        Optional<ButtonType> result = alert_success.showAndWait();
        if (result.get() == ButtonType.OK) {
            initUserRoleTable(getAllUserRoles());
            //if logged user changes his own details......
            if (loggedSession.getUrole().getId() == id) {
                loggedSession.setUrole(uhur);
                DashBoardFxmlController.controller.setLoggedSession(loggedSession.getUrole());
            }
        }
    }
}

From source file:com.court.controller.UserManageFxmlController.java

@FXML
private void onSaveRoleBtnAction(ActionEvent event) {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();/*from  w  w  w.  j  a v a 2s .co  m*/
    UserRole uuRole;
    int id = getIdByUserRole(session, usr_role_name_txt.getText().trim().toLowerCase());
    if (id != 0) {
        uuRole = (UserRole) session.load(UserRole.class, id);
    } else {
        uuRole = new UserRole();
    }

    uuRole.setRoleName(usr_role_name_txt.getText().trim().toLowerCase());
    uuRole.setStatus(true);

    if (checkedItems != null) {
        //first have to delete already exist privileges
        deleteAllDBExitsPrivilages(session, uuRole.getId());
        Set<PrivCat> pCats = new HashSet<>();
        checkedItems.forEach(e -> {
            PrivCat pc = new PrivCat();
            pc.setUserRole(uuRole);
            pc.setUsrRolePrivilage(getPrivilegeByPrivId(session, e.getValue().getId()));
            pCats.add(pc);
        });
        uuRole.setPrivCats(pCats);
    }

    session.saveOrUpdate(uuRole);
    session.getTransaction().commit();
    session.close();

    Alert alert_success = new Alert(Alert.AlertType.INFORMATION);
    alert_success.setTitle("Success");
    alert_success.setHeaderText("Successfully Saved !");
    alert_success
            .setContentText("You have successfully save the \"" + usr_role_name_txt.getText() + " user Role\"");
    Optional<ButtonType> showAndWait = alert_success.showAndWait();
    if (showAndWait.get() == ButtonType.OK) {
        initUserRoleTable(getAllUserRoles());
        FxUtilsHandler.clearFields(main_grid);
        imgString = null;
        usr_img_view.setImage(new Image(getClass().getResourceAsStream(FileHandler.MEMBER_DEFAULT_IMG)));
        FxUtilsHandler.activeDeactiveChildrenControls(true, main_grid);
    }

}