Search in sources :

Example 11 with Servant

use of org.omg.PortableServer.Servant in project ACS by ACS-Community.

the class HibernateWDALImpl method loadXMLCDB.

//final Integer NULL_ID = null;
protected boolean loadXMLCDB(String[] args, ORB orb, POA poa, String configName) {
    m_logger.info("Reading configuration from XML CDB...");
    try {
        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) {
                    // Optional, but has no default!
                    manager.setServiceDaemons("");
                }
                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
                    // for Oracle
                    containerPath = "/";
                Container container = new Container();
                container.setContainerName(containerName);
                container.setPath(containerPath);
                container.setConfiguration(config);
                container.setLoggingConfig(loggingConfig);
                container.setComputer(hostComputer);
                // cpp is default, since field is required
                container.setImplLang(ImplLangEnum.valueOfForEnum(readString(containerDAO, "ImplLang", "cpp")));
                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);
                    // "/////" 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 {
                            // for Oracle
                            containerPath = "/";
                        }
                        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);
                            // cpp is default, since field is required
                            container.setImplLang(ImplLangEnum.valueOfForEnum(readString(componentDAO, "ImplLang", "cpp")));
                            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");
                    // pulled out for performance optimization, to avoid reading it twice in many cases
                    DAOProxy componentConfigurationDAO = null;
                    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") || // sadly ControlDevice does not extend CharacteristicComponent XSD
                                    (TMCDB_ACS_ONLY && xsdElementTypeResolver.doesExtend(schemaURN, "ControlDevice"));
                                    m_logger.fine(schemaURN + " does extend CharacteristicsComponent? " + isCharateristicsComponent);
                                    if (isCharateristicsComponent)
                                        characteristicsDeviceSet.add(type);
                                    processedComponentTypes.add(type);
                                }
                            } catch (Throwable th) {
                                almaBranchDoesNotExist = true;
                                // (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);
                    // TODO verify this and clean up
                    component.setContainer(tmpComponentContainer);
                    // cpp is default, since field is required
                    component.setImplLang(ImplLangEnum.valueOfForEnum(readString(componentDAO, componentName + "/ImplLang", "cpp")));
                    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
                                // this is handled by HW plugin
                                propertySet.add("Address");
                                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 {
                    // for Oracle
                    channelPath = "/";
                    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);
    }
}
Also used : EventChannelDiscardPolicy(alma.acs.tmcdb.EventChannelDiscardPolicy) EventChannelOrderPolicy(alma.acs.tmcdb.EventChannelOrderPolicy) LinkedHashSet(java.util.LinkedHashSet) Configuration(alma.acs.tmcdb.Configuration) Manager(alma.acs.tmcdb.Manager) ClientLogManager(alma.acs.logging.ClientLogManager) Servant(org.omg.PortableServer.Servant) ExtraDataFeatureUtil(com.cosylab.cdb.jdal.hibernate.ExtraDataFeatureUtil) Container(alma.acs.tmcdb.Container) AcsJCDBFieldDoesNotExistEx(alma.cdbErrType.wrappers.AcsJCDBFieldDoesNotExistEx) CDBFieldDoesNotExistEx(alma.cdbErrType.CDBFieldDoesNotExistEx) TreeSet(java.util.TreeSet) Computer(alma.acs.tmcdb.Computer) BACIProperty(alma.acs.tmcdb.BACIProperty) NotificationServiceMapping(alma.acs.tmcdb.NotificationServiceMapping) AcsJWrongCDBDataTypeEx(alma.cdbErrType.wrappers.AcsJWrongCDBDataTypeEx) WrongCDBDataTypeEx(alma.cdbErrType.WrongCDBDataTypeEx) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) DAOPOA(com.cosylab.CDB.DAOPOA) WJDALPOA(com.cosylab.CDB.WJDALPOA) WDAOPOA(com.cosylab.CDB.WDAOPOA) POA(org.omg.PortableServer.POA) DAOProxy(com.cosylab.cdb.client.DAOProxy) Schemas(alma.acs.tmcdb.Schemas) ContainerStartupOption(alma.acs.tmcdb.ContainerStartupOption) JDAL(com.cosylab.CDB.JDAL) EmptyStringHandlerBACIPropertyType(alma.TMCDB.baci.EmptyStringHandlerBACIPropertyType) BACIPropertyType(alma.TMCDB.baci.BACIPropertyType) AcsJCDBRecordDoesNotExistEx(alma.cdbErrType.wrappers.AcsJCDBRecordDoesNotExistEx) CDBRecordDoesNotExistEx(alma.cdbErrType.CDBRecordDoesNotExistEx) EventChannel(alma.acs.tmcdb.EventChannel) Iterator(java.util.Iterator) Component(alma.acs.tmcdb.Component) ContainerStartupOptionHelper(alma.acs.tmcdb.logic.ContainerStartupOptionHelper) ComponentType(alma.acs.tmcdb.ComponentType) CDBAccess(com.cosylab.cdb.client.CDBAccess) ChannelMapping(alma.acs.tmcdb.ChannelMapping) WJDALPOATie(com.cosylab.CDB.WJDALPOATie) DomainsMapping(alma.acs.tmcdb.DomainsMapping) StringTokenizer(java.util.StringTokenizer) LoggingConfig(alma.acs.tmcdb.LoggingConfig) Event(alma.acs.tmcdb.Event) Session(org.hibernate.Session)

Example 12 with Servant

use of org.omg.PortableServer.Servant in project ACS by ACS-Community.

the class AcsContainer method activate_component.

/////////////////////////////////////////////////////////////
// Implementation of ContainerOperations#activate_component
/////////////////////////////////////////////////////////////
/**
     * Activates a component so that it's ready to receive functional calls
     * after returning from this method. Called by the ACS Manager.
     * <p>
     * From MACI IDL:
     * <i>
     * Activate a component whose type (class) and name (instance) are given.
     * In the process of activation, component's code-base is loaded into memory if it is not there already.
     * The code-base resides in an executable file (usually a dynamic-link library or a shared library -- DLL).
     * On platforms that do not automatically load dependent executables (e.g., VxWorks),
     * the container identifies the dependencies by querying the executable and loads them automatically.
     * Once the code is loaded, it is asked to construct a servant of a given type.
     * The servant is then initialized with the Configuration Database (CDB) and Persistance Database (PDB) data.
     * The servant is attached to the component, and a reference to it is returned.
     * </i>
     * <p>
     * @param componentHandle  handle of the component that is being activated. This handle is used
     *              by the component when it will present itself to the Manager.
     *              The component is expected to remember this handle for its entire life-time.
     * @param execution_id              
     * @param compName  name of the component to instantiate (instance name, comes from CDB)
     * @param exe   component helper implementation class; must be a subclass of
     *               {@link alma.acs.container.ComponentHelper}.
     * @param type  the type of the component to instantiate (Corba IR id).
     * @return   Returns the reference to the object that has just been activated.
     *               If the component could not the activated, a nil reference is returned.
     *
     * @see si.ijs.maci.ContainerOperations#activate_component(int, String, String, String)
     */
public ComponentInfo activate_component(int componentHandle, long execution_id, String compName, String exe, String type) throws CannotActivateComponentEx {
    // reject the call if container is shutting down
    if (shuttingDown.get()) {
        String msg = "activate_component() rejected because of container shutdown.";
        m_logger.fine(msg);
        AcsJCannotActivateComponentEx ex = new AcsJCannotActivateComponentEx();
        ex.setCURL(compName);
        ex.setDetailedReason(msg);
        throw ex.toCannotActivateComponentEx();
    }
    ComponentInfo componentInfo = null;
    StopWatch activationWatch = new StopWatch(m_logger);
    // to make component activations stick out in the log list
    m_logger.finer("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
    m_logger.fine("activate_component: handle=" + componentHandle + " name=" + compName + " helperClass=" + exe + " type=" + type);
    // if the container is still starting up, then hold the request until the container is ready
    boolean contInitWaitSuccess = false;
    try {
        contInitWaitSuccess = containerStartOrbThreadGate.await(30, TimeUnit.SECONDS);
    } catch (InterruptedException ex1) {
    // just leave contInitWaitSuccess == false
    }
    if (!contInitWaitSuccess) {
        String msg = "Activation of component " + compName + " timed out after 30 s waiting for the container to finish its initialization.";
        m_logger.warning(msg);
        AcsJCannotActivateComponentEx ex = new AcsJCannotActivateComponentEx();
        ex.setCURL(compName);
        ex.setDetailedReason(msg);
        throw ex.toCannotActivateComponentEx();
    }
    ComponentAdapter compAdapter = null;
    try {
        synchronized (m_activeComponentMap) {
            ComponentAdapter existingCompAdapter = getExistingComponent(componentHandle, compName, type);
            if (existingCompAdapter != null) {
                return existingCompAdapter.getComponentInfo();
            } else if (!m_activeComponentMap.reserveComponent(componentHandle)) {
                AcsJContainerEx ex = new AcsJContainerEx();
                ex.setContextInfo("Component with handle '" + componentHandle + "' is already being activated by this container. Manager should have prevented double activation.");
                throw ex;
            }
        }
        ClassLoader compCL = null;
        // the property 'acs.components.classpath.jardirs' is set by the script acsStartContainer
        // to a list of all relevant 'lib/ACScomponents/' directories
        String compJarDirs = System.getProperty(AcsComponentClassLoader.PROPERTY_JARDIRS);
        if (compJarDirs != null) {
            compCL = new AcsComponentClassLoader(Thread.currentThread().getContextClassLoader(), m_logger, compName);
        } else {
            // fallback: load component impl classes in the global class loader
            compCL = Thread.currentThread().getContextClassLoader();
        }
        // Create component helper using component classloader.
        // Note that the base class alma.acs.container.ComponentHelper will still be loaded by the container CL,
        // although the current subclassing design is a bit dirtier than it could be in the sense that a mean
        // component could deploy modified container classes (e.g. in method getInterfaceTranslator).
        // Nothing big to worry about though...
        ComponentHelper compHelper = createComponentHelper(compName, exe, compCL);
        // Creates component implementation and connects it with the Corba-generated POATie object.
        // Objects for container interception ("tight container") and for automatic xml binding class
        // de-/serialization are chained up and inserted here. End-to-end they have to translate between the
        // operations interface derived from corba IDL and the component's declared internalInterface.
        StopWatch compStopWatch = new StopWatch();
        ComponentLifecycle compImpl = compHelper.getComponentImpl();
        LOG_CompAct_Instance_OK.log(m_logger, compName, compStopWatch.getLapTimeMillis());
        //m_logger.finest(compName + " component impl created, with classloader " + compImpl.getClass().getClassLoader().getClass().getName());
        Class<? extends ACSComponentOperations> operationsIFClass = compHelper.getOperationsInterface();
        Constructor<? extends Servant> poaTieCtor = compHelper.getPOATieClass().getConstructor(new Class[] { operationsIFClass });
        Object operationsIFImpl = null;
        // translations for some methods only...
        if (operationsIFClass.isInstance(compImpl)) {
            m_logger.finer("component " + compName + " implements operations interface directly; no dynamic translator proxy used.");
            operationsIFImpl = compImpl;
        } else {
            m_logger.finer("creating dynamic proxy to map corba interface calls to component " + compName + ".");
            operationsIFImpl = compHelper.getInterfaceTranslator();
            if (!Proxy.isProxyClass(operationsIFImpl.getClass()) && !(operationsIFImpl instanceof ExternalInterfaceTranslator))
                m_logger.log(AcsLogLevel.NOTICE, "interface translator proxy for component " + compName + " isn't " + "the default one, and doesn't expose the default as one either. This may cause problem when invoking " + "xml-aware offshoot getters");
        }
        // make it a tight container (one that intercepts functional method calls)
        String[] methodsExcludedFromInvocationLogging = compHelper.getComponentMethodsExcludedFromInvocationLogging();
        Object poaDelegate = ContainerSealant.createContainerSealant(operationsIFClass, operationsIFImpl, compName, false, m_logger, compCL, methodsExcludedFromInvocationLogging);
        // construct the POATie skeleton with operationsIFImpl as the delegate object
        Servant servant = null;
        try {
            servant = poaTieCtor.newInstance(new Object[] { poaDelegate });
        } catch (Throwable thr) {
            AcsJContainerEx ex = new AcsJContainerEx(thr);
            ex.setContextInfo("failed to instantiate the servant object for component " + compName + " of type " + compImpl.getClass().getName());
            throw ex;
        }
        //
        // administrate the new component
        //
        compAdapter = new ComponentAdapter(compName, type, exe, componentHandle, m_containerName, compImpl, m_managerProxy, sharedCdbRef, compCL, m_logger, m_acsCorba);
        // to support automatic offshoot translation for xml-binded offshoots, we need to pass the dynamic adaptor
        if (!operationsIFClass.isInstance(compImpl)) {
            // if an external interface translator was given by the user, get the default interface translator
            if (operationsIFImpl instanceof ExternalInterfaceTranslator)
                operationsIFImpl = ((ExternalInterfaceTranslator) operationsIFImpl).getDefaultInterfaceTranslator();
            compAdapter.setComponentXmlTranslatorProxy(operationsIFImpl);
        }
        // for future offshoots created by this component we must pass on the no-auto-logging info
        compAdapter.setMethodsExcludedFromInvocationLogging(methodsExcludedFromInvocationLogging);
        compStopWatch.reset();
        compAdapter.activateComponent(servant);
        LOG_CompAct_Corba_OK.log(m_logger, compName, compStopWatch.getLapTimeMillis());
        // now it's time to turn off ORB logging if the new component is requesting this
        if (compHelper.requiresOrbCentralLogSuppression()) {
            ClientLogManager.getAcsLogManager().suppressCorbaRemoteLogging();
        }
        // even though the component is now an activated Corba object already,
        // it won't be called yet since the maciManager will only pass around
        // access information after we've returned from this activate_component method.
        // Therefore it's not too late to call initialize and execute, which are
        // guaranteed to be called before incoming functional calls must be expected.
        // At the moment we have to call these two methods one after the other;
        // if the Manager supports new calling semantics, we could separate the two
        // as described in ComponentLifecycle
        m_logger.fine("about to initialize component " + compName);
        compStopWatch.reset();
        compAdapter.initializeComponent();
        compAdapter.executeComponent();
        LOG_CompAct_Init_OK.log(m_logger, compName, compStopWatch.getLapTimeMillis());
        // we've deferred storing the component in the map until after it's been initialized successfully
        m_activeComponentMap.put(componentHandle, compAdapter);
        long activTime = activationWatch.getLapTimeMillis();
        m_logger.info("component " + compName + " activated and initialized in " + activTime + " ms.");
        componentInfo = compAdapter.getComponentInfo();
    } catch (Throwable thr) {
        m_logger.log(Level.SEVERE, "Failed to activate component " + compName + ", problem was: ", thr);
        if (compAdapter != null) {
            try {
                compAdapter.deactivateComponent();
            } catch (Exception ex) {
                m_logger.log(Level.FINE, ex.getMessage(), ex);
            }
        }
        m_activeComponentMap.remove(componentHandle);
        AcsJCannotActivateComponentEx ex = new AcsJCannotActivateComponentEx(thr);
        throw ex.toCannotActivateComponentEx();
    } finally {
        // to make (possibly nested) component activations stick out in the log list
        m_logger.finer(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    }
    return componentInfo;
}
Also used : AcsJContainerEx(alma.JavaContainerError.wrappers.AcsJContainerEx) AcsJCannotActivateComponentEx(alma.maciErrType.wrappers.AcsJCannotActivateComponentEx) AcsComponentClassLoader(alma.acs.classloading.AcsComponentClassLoader) Servant(org.omg.PortableServer.Servant) AcsJException(alma.acs.exceptions.AcsJException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) LogConfigException(alma.acs.logging.config.LogConfigException) StopWatch(alma.acs.util.StopWatch) ComponentLifecycle(alma.acs.component.ComponentLifecycle) AcsComponentClassLoader(alma.acs.classloading.AcsComponentClassLoader) ComponentInfo(si.ijs.maci.ComponentInfo) CBComponentInfo(si.ijs.maci.CBComponentInfo)

Example 13 with Servant

use of org.omg.PortableServer.Servant in project ACS by ACS-Community.

the class ComponentHelper method getPOATieClass.

/**
	 * Gets the <code>Class</code> object for the POA tie skeleton class.
	 * The POA tie class is generated by the IDL compiler and must have
	 * a constructor that takes the operations interface as its only parameter.
	 * 
	 * @return the tie class.
	 */
final Class<? extends Servant> getPOATieClass() throws AcsJJavaComponentHelperEx {
    Class<? extends Servant> poaTieClass = null;
    try {
        poaTieClass = _getPOATieClass();
    } catch (Throwable thr) {
        AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx(thr);
        ex.setContextInfo("failed to obtain the POATie class from component helper.");
        throw ex;
    }
    if (poaTieClass == null) {
        AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx();
        ex.setContextInfo("received null as the POATie class from the component helper.");
        throw ex;
    }
    // check inheritance stuff (Servant should be checked by compiler under JDK 1.5, but operations IF is unknown at ACS compile time)
    if (!Servant.class.isAssignableFrom(poaTieClass)) {
        AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx();
        ex.setContextInfo("received invalid POATie class that is not a subclass of org.omg.PortableServer.Servant");
        throw ex;
    }
    if (!getOperationsInterface().isAssignableFrom(poaTieClass)) {
        AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx();
        ex.setContextInfo("POATie class '" + poaTieClass + "' does not implement the declared operations interface '" + getOperationsInterface().getName() + "'.");
        throw ex;
    }
    return poaTieClass;
}
Also used : AcsJJavaComponentHelperEx(alma.JavaContainerError.wrappers.AcsJJavaComponentHelperEx) Servant(org.omg.PortableServer.Servant)

Example 14 with Servant

use of org.omg.PortableServer.Servant in project kernel by cristal-ise.

the class CorbaServer method getItem.

/**
 * Returns a CORBA servant for a pre-existing entity
 *
 * @param itemPath the ItemPath representing the Item
 * @return the servant
 * @throws ObjectNotFoundException itemPath was not found
 */
public TraceableEntity getItem(ItemPath itemPath) throws ObjectNotFoundException {
    Servant item = null;
    if (!itemPath.exists())
        throw new ObjectNotFoundException(itemPath + " does not exist");
    synchronized (mItemCache) {
        item = mItemCache.get(itemPath);
        if (item == null) {
            Logger.msg(7, "Creating new servant for " + itemPath);
            item = new TraceableEntity(itemPath, mItemPOA);
            mItemCache.put(itemPath, item);
        }
    }
    return (TraceableEntity) item;
}
Also used : ObjectNotFoundException(org.cristalise.kernel.common.ObjectNotFoundException) Servant(org.omg.PortableServer.Servant)

Example 15 with Servant

use of org.omg.PortableServer.Servant in project kernel by cristal-ise.

the class CorbaServer method getAgent.

/**
 * Returns a CORBA servant for a pre-existing entity
 *
 * @param agentPath the AgentPath representing the Agent
 * @return the servant
 * @throws InvalidAgentPathException agentPath was not Agent
 * @throws ObjectNotFoundException agentPath was not found
 */
public ActiveEntity getAgent(AgentPath agentPath) throws InvalidAgentPathException, ObjectNotFoundException {
    Servant agent = null;
    if (!agentPath.exists())
        throw new ObjectNotFoundException(agentPath + " does not exist");
    synchronized (mItemCache) {
        agent = mItemCache.get(agentPath);
        if (agent == null) {
            Logger.msg(7, "Creating new servant for " + agentPath);
            agent = new ActiveEntity(agentPath, mAgentPOA);
            mItemCache.put(agentPath, agent);
        } else if (!(agent instanceof ActiveEntity))
            throw new InvalidAgentPathException("Item " + agentPath + " was not an agent");
    }
    return (ActiveEntity) agent;
}
Also used : ObjectNotFoundException(org.cristalise.kernel.common.ObjectNotFoundException) Servant(org.omg.PortableServer.Servant) InvalidAgentPathException(org.cristalise.kernel.lookup.InvalidAgentPathException) ActiveEntity(org.cristalise.kernel.entity.agent.ActiveEntity)

Aggregations

Servant (org.omg.PortableServer.Servant)16 POA (org.omg.PortableServer.POA)5 AcsJContainerServicesEx (alma.JavaContainerError.wrappers.AcsJContainerServicesEx)4 AcsJContainerEx (alma.JavaContainerError.wrappers.AcsJContainerEx)2 AcsJException (alma.acs.exceptions.AcsJException)2 AcsJCDBRecordDoesNotExistEx (alma.cdbErrType.wrappers.AcsJCDBRecordDoesNotExistEx)2 DummyComponent (alma.jconttest.DummyComponent)2 DummyComponentPOATie (alma.jconttest.DummyComponentPOATie)2 ObjectNotFoundException (org.cristalise.kernel.common.ObjectNotFoundException)2 OffShoot (alma.ACS.OffShoot)1 PropertyOperations (alma.ACS.PropertyOperations)1 AcsJJavaComponentHelperEx (alma.JavaContainerError.wrappers.AcsJJavaComponentHelperEx)1 BACIPropertyType (alma.TMCDB.baci.BACIPropertyType)1 EmptyStringHandlerBACIPropertyType (alma.TMCDB.baci.EmptyStringHandlerBACIPropertyType)1 AcsComponentClassLoader (alma.acs.classloading.AcsComponentClassLoader)1 ComponentLifecycle (alma.acs.component.ComponentLifecycle)1 ComponentLifecycleException (alma.acs.component.ComponentLifecycleException)1 ComponentInvocationHandler (alma.acs.component.dynwrapper.ComponentInvocationHandler)1 ComponentServantManager (alma.acs.container.ComponentServantManager)1 ClientLogManager (alma.acs.logging.ClientLogManager)1