Ejemplo n.º 1
0
def intialize():
        global domainProps;
        global userConfigFile;
        global userKeyFile;

        # test arguments
        if len(sys.argv) != 3:
                print 'Usage:  stopDomain.sh  <default.properties_file> <property_file>';
                exit();

				
		print 'Starting the initialization process';                                                                                                                                                    

    	try:
    		domainProps = Properties()

		# load DEFAULT properties                                                                                                                                                                               
		input = FileInputStream(sys.argv[1])
		domainProps.load(input)
		input.close()
			
		
		# load properties and overwrite defaults
		input = FileInputStream(sys.argv[2])
		domainProps.load(input)
		input.close()

                userConfigFile = File(sys.argv[2]).getParent()+'/'+domainProps.getProperty('domainName')+'.userconfig'
                userKeyFile = File(sys.argv[2]).getParent()+'/'+domainProps.getProperty('domainName')+'.userkey'

        except:
                print 'Cannot load properties  !';
                exit();

        print 'Initialization completed';
def addPropertiesFromFile(props, filename, site_home):
    addProps = Properties()
    input = FileInputStream(filename)
    addProps.load(input)
    input.close()

    baseFileList = addProps.getProperty('base')
    
    if not baseFileList is None:
        baseFiles = baseFileList.split(",")
        for baseFile in baseFiles:
            baseFileResolved=getBaseFile(baseFile, site_home)
            if baseFileResolved=='':
                log.error('Configuration inherits from properties file that does not exist: ' + baseFile)
                log.info('Suggested Fix: Update the base property within ' + filename + ' to the correct file path')
                sys.exit()
            log.debug('Attempting to load properties from ' + baseFile)
            addPropertiesFromFile(addProps, baseFileResolved, site_home)
            addProps.remove('base')

    enum = addProps.keys()
    while enum.hasMoreElements():
        key = enum.nextElement()
        if props.getProperty(key) is None:
            props.setProperty(key, addProps.getProperty(key))
            addDataLinage(key,filename,addProps.getProperty(key))
def loadProperties(fileName):
	properties = Properties()
	input = FileInputStream(fileName)
	properties.load(input)
	input.close()
	result= {}
	for entry in properties.entrySet(): result[entry.key] = entry.value
	return result
Ejemplo n.º 4
0
 def read_versions(self):
     versionsProperties = Properties()
     fin = FileInputStream(self.versionsFileName)
     versionsProperties.load(fin)
     scriptVersion = versionsProperties.getProperty("script")
     toolsVersion = versionsProperties.getProperty("tools")
     fin.close()
     return scriptVersion, toolsVersion
Ejemplo n.º 5
0
 def read_versions(self):
     versionsProperties = Properties()
     fin = FileInputStream(self.versionsFileName)
     versionsProperties.load(fin)
     scriptVersion = versionsProperties.getProperty("script")
     toolsVersion = versionsProperties.getProperty("tools")
     fin.close()
     return scriptVersion, toolsVersion
def load_redback_registry():
    reg = Properties()
    reg_file = 'redback.properties'
    if os.path.isfile(reg_file):
        reg_fd = FileInputStream(reg_file)
        reg.load(reg_fd)
        reg_fd.close()
    return reg
def load_redback_registry():
    reg = Properties()
    reg_file = 'redback.properties'
    if os.path.isfile(reg_file):
        reg_fd = FileInputStream(reg_file)
        reg.load(reg_fd)
        reg_fd.close()
    return reg
Ejemplo n.º 8
0
def load_global_registry():
    reg = Properties()
    reg_file = 'global_platform.properties'
    if os.path.isfile(reg_file):
        reg_fd = FileInputStream(reg_file)
        reg.load(reg_fd)
        reg_fd.close()
    return reg
Ejemplo n.º 9
0
def getPushProperties():
    pushProperties          = HashMap()
    pushPropertiesFileStr   = "%s%s%s" % (adapterConfigBaseDir, FILE_SEPARATOR, PUSH_PROPERTIES_FILE)
    properties              = Properties()
    debugMode               = 0
    sortCSVFields           = ""
    smartUpdateIgnoreFields = ""
    testConnNameSpace       = "BMC.CORE"
    testConnClass           = "BMC_ComputerSystem"
    try:
        logger.debug("Checking push properties file for debugMode [%s]" % pushPropertiesFileStr)
        fileInputStream = FileInputStream(pushPropertiesFileStr)
        properties.load(fileInputStream)

        # Property: debugMode
        try:
            debugModeStr    = properties.getProperty("debugMode")
            if isNoneOrEmpty(debugModeStr) or string.lower(string.strip(debugModeStr)) == 'false':
                debugMode   = 0
            elif string.lower(string.strip(debugModeStr)) == 'true':
                debugMode   = 1
        except:
            logger.debugException("Unable to read debugMode property from push.properties")

        if debugMode:
            logger.debug("Debug mode = TRUE. XML data pushed to Remedy/Atrium will be persisted in the directory: %s" % adapterResBaseDir)
        else:
            logger.debug("Debug mode = FALSE")

        # Property: smartUpdateIgnoreFields
        try:
            smartUpdateIgnoreFields = properties.getProperty("smartUpdateIgnoreFields")
        except:
            logger.debugException("Unable to read smartUpdateIgnoreFields property from push.properties")

        # Property: sortCSVFields
        try:
            sortCSVFields = properties.getProperty("sortCSVFields")
        except:
            logger.debugException("Unable to read sortCSVFields property from push.properties")

        # Property: testConnNameSpace
        try:
            testConnNameSpace = properties.getProperty("testConnNameSpace")
        except:
            logger.debugException("Unable to read testConnNameSpace property from push.properties")

        # Property: testConnClass
        try:
            testConnClass = properties.getProperty("testConnClass")
        except:
            logger.debugException("Unable to read testConnClass property from push.properties")

        fileInputStream.close()
    except:
        logger.debugException("Unable to process %s file." % PUSH_PROPERTIES_FILE)

    return debugMode, smartUpdateIgnoreFields, sortCSVFields, testConnNameSpace, testConnClass
Ejemplo n.º 10
0
def loadProperties(propFileName):
    from java.io import FileInputStream
    from java.util import Properties

    fileprop = Properties()
    fileStream = FileInputStream(propFileName)
    fileprop.load(fileStream)

    return fileprop
Ejemplo n.º 11
0
def intialize():
        global domainLocation;
        global jvmLocation;
        global domainTemplate;
        global domainProps;
        global adminUserName;
        global adminPassword;
        global userConfigFile;
        global userKeyFile;

        # test arguments
        if len(sys.argv) != 6:
                print 'Usage:  createDomain.sh <template-file> <default.properties_file> <property_file> <wls_username> <wls_password>';
                exit();

        print 'Starting the initialization process';

        domainTemplate = sys.argv[1];
        print 'Using Domain Template: ' + domainTemplate;
        try:
                domainProps = Properties()

                # load DEFAULT properties
                # print 'Reading default properties from '+sys.argv[2];
                input = FileInputStream(sys.argv[2])
                domainProps.load(input)
                input.close()


                # load properties and overwrite defaults
                input = FileInputStream(sys.argv[3])
                domainProps.load(input)
                input.close()

                adminUserName = sys.argv[4];
                adminPassword = sys.argv[5];

		# Files for generating secret key

		userConfigFile = File(sys.argv[3]).getParent()+'/'+domainProps.getProperty('domainName')+'.userconfig'
                print userConfigFile
		userKeyFile = File(sys.argv[3]).getParent()+'/'+domainProps.getProperty('domainName')+'.userkey'
	        print userKeyFile			

                domainLocation = domainProps.getProperty('domainsDirectory') + pathSeparator + domainProps.getProperty('domainName');
                print 'Domain Location: ' + domainLocation;
                if len(domainProps.getProperty('jvmLocation')) == 0:
                        print 'JVM location property not defined - cancel creation !';
                        exit();
                print 'JVM Location: ' + domainProps.getProperty('jvmLocation');

        except:
                dumpStack()
                print 'Cannot initialize creation process !';
                exit();

        print 'Initialization completed';
def loadMyProperties(fileName):
    properties = Properties()
    input = FileInputStream(fileName)
    properties.load(input)
    input.close()
    result = {}
    for entry in properties.entrySet():
        result[entry.key] = entry.value
    return result
Ejemplo n.º 13
0
def get_file_properties(filename):
    if filename not in deploy_files_properties:
        data = get_file_data(filename)
        input_stream = ByteArrayInputStream(data)
        properties = Properties()
        properties.load(input_stream)
        
        deploy_files_properties[filename] = properties
    return deploy_files_properties[filename]
Ejemplo n.º 14
0
def read_tools_list(tmpToolsListFile):
    """Read the tools names and tools data urls
       from the downlaoded tools list
    """
    properties = Properties()
    fin = FileInputStream(tmpToolsListFile)
    properties.load(fin)
    toolsRefs = properties.getProperty("tools.list").split("|")
    fin.close()
    return toolsRefs
Ejemplo n.º 15
0
def read_tools_list(tmpToolsListFile):
    """Read the tools names and tools data urls
       from the downlaoded tools list
    """
    properties = Properties()
    fin = FileInputStream(tmpToolsListFile)
    properties.load(fin)
    toolsRefs = properties.getProperty("tools.list").split("|")
    fin.close()
    return toolsRefs
def loadPropertiesFromFile(filename,props):
    newprops=Properties()
    inputstr = FileInputStream(filename)
    newprops.load(inputstr)
    inputstr.close()
    enum = newprops.keys()
    while enum.hasMoreElements():
        key = enum.nextElement()
        if props.getProperty(key) is None:
            props.setProperty(key, newprops.getProperty(key))
    return props
Ejemplo n.º 17
0
  def loadProperties(self, filename):
    f = File("%s" % filename)
    props = Properties()

    if f.exists():
      print 'Chargement de la configuration depuis ' + filename
      fis = FileInputStream( f )
      props.load( fis )
    else:
      print 'ERROR: Impossible de charger le fichier de configuration ' + filename
    return props
def loadProps(path):
    props = Properties()
    try:
        propReader = FileReader(path)
        props.load(propReader)
        propReader.close()
    except:
        type, value, traceback = sys.exc_info()
        print "Error loading properties from file:" + path + ":" + ` value `

    return props
Ejemplo n.º 19
0
def load_common_properties():
    """Loads common test properties into grinder properties."""

    current_dir = os.path.dirname(os.path.abspath(__file__))
    file_name = os.path.join(current_dir, PROPERTIES)
    source = BufferedInputStream(FileInputStream(file_name))
    props = Properties()
    props.load(source)
    source.close()

    for key in props.keySet().iterator():
        grinder.properties[key] = props.get(key)
def run():
    versionFile = File(os.getcwd(), 'core/resources/version.properties')
    log.debug('Checking if ' + str(versionFile) + ' exists')
    if os.path.exists(str(versionFile)):
        versionProperties = Properties()
        input = FileInputStream(versionFile)
        versionProperties.load(input)
        input.close()
        versionInfo=getVersionInfo(versionProperties)
    else:
    	versionInfo=getVersionInfo(None)
    log.info('this')
    log.info(versionInfo)
Ejemplo n.º 21
0
def descryptPropsFile(filepath):
	print
	print '----- Decrypting %s -----' % filepath
	try:
		properties = Properties()
		file = FileInputStream(filepath)
		properties.load(file)
		file.close()
		for entry in properties.entrySet():
			print '%s = %s' % (entry.key.strip(), java.lang.String(decrypt(entry.value.strip())))
	except IOError:
		print "Error: Unable to read file '%s' - check file permissions" % filepath
		print
def run():
    versionFile = File(os.getcwd(), 'core/resources/version.properties')
    log.debug('Checking if ' + str(versionFile) + ' exists')
    if os.path.exists(str(versionFile)):
        versionProperties = Properties()
        input = FileInputStream(versionFile)
        versionProperties.load(input)
        input.close()
        versionInfo = getVersionInfo(versionProperties)
    else:
        versionInfo = getVersionInfo(None)
    log.info('this')
    log.info(versionInfo)
Ejemplo n.º 23
0
def read_tools_list(tmpToolsListFile):
    """Read the tools names and tools data urls
       from the downlaoded tools list
    """
    toolsInfo = []
    properties = Properties()
    fin = FileInputStream(tmpToolsListFile)
    properties.load(fin)
    toolsRefs = properties.getProperty("tools.list").split("|")
    for toolRef in toolsRefs:
        jarUrl = properties.getProperty(toolRef)
        toolsInfo.append([toolRef, jarUrl.replace("\n", "")])
    fin.close()
    return toolsInfo
Ejemplo n.º 24
0
 def _areUserFilesValid(self):
   if not (self._userConfigFile and self._userKeyFile):
     return False
   if not (self._is_non_zero_file(self._userConfigFile) and self._is_non_zero_file(self._userKeyFile)):
     return False
   try:
     inStream=FileInputStream(self._userConfigFile)
     userConfigs=Properties()
     userConfigs.load(inStream)
   except NullPointerException:
     return False
   if not (userConfigs.getProperty('weblogic.management.username') and userConfigs.getProperty('weblogic.management.password')):
     return False
   return True
Ejemplo n.º 25
0
def initLogger(prefix, project, debug):
	log4JPropertiesFile = "properties" + File.separator + "log4j.properties"
	if not os.path.exists(log4JPropertiesFile):	
		print "******* log4J properties file %s not available *******" % log4JPropertiesFile 		
		sys.exit(1)
	propertyFile = open(log4JPropertiesFile, "r")	
	props = Properties()
	props.load(propertyFile)
	propertyFile.close()	
	if debug:
		props.setProperty("log4j.rootCategory", "DEBUG, console, file")
	logFileName = LOGDIRNAME + File.separator + prefix + "_" + project + "_" + h2hprops.get(KYUNIQUEPACKAGEID) + ".log"
	props.setProperty("log4j.appender.file.File", logFileName)		
	PropertyConfigurator.configure(props)
Ejemplo n.º 26
0
def load_property_file(filename):

    propfile = Properties()

    try:
        fin = FileInputStream(filename)
        propfile.load(fin)
        fin.close()
        return propfile
    except FileNotFoundException:
        LogError("File Not Found" + filename)
        sys.exit(1)
    except:
        LogError("Could not open Properties File" + filename)
        sys.exit(1)
Ejemplo n.º 27
0
def init(trace=False, debug=False):

    global log, logfileName, prog, ext

    coll_home = getCollHome()
    prog, ext = getProgramName()
    #Load properties file in java.util.Properties
    propsFileName = coll_home + "/etc/collation.properties"
    inStream = FileInputStream(propsFileName)
    propFile = Properties()
    propFile.load(inStream)

    log, logfileName = setupLog4jLogging(trace, debug)

    return log, logfileName, prog
 def login(self, domain, userid, password):
     fis = None
     userinfo = getResource(__file__, "users_db", userid + ".properties")
     if not os.path.exists(userinfo):
         raise UnauthorizedException("login", userid, userid)
     props = Properties()
     try:
         fis = FileInputStream(File(userinfo))
         props.load(fis)
     finally:
         fis.close()
     DumbIdentityManager.login(self, domain, userid, password)
     user = SimpleUser(userid, props)
     if user.getPassword() != password:
         raise UnauthorizedException("login", userid, userid)
     self.current = user
Ejemplo n.º 29
0
def init(context):
    if not File("storage/python_console.props").exists():
        context.log("storage/python_console.props does not exist")
        return
    context.log("storage/python_console.props exists; proceeding with load")
    props = Properties()
    props.load(FileInputStream(File("storage/python_console.props"))) 
    server = ServerSocket(int(props["port"]), 20,
                          InetAddress.getByName(props["host"])
                          if "host" in props else None)
    class ServerThread(Thread):
        def run(self):
            while not server.isClosed():
                socket = server.accept()
                HandlerThread(socket).start()
    ServerThread().start()
Ejemplo n.º 30
0
def intialize():
	global props
	
	if len(sys.argv) != 2:
		print 'Usage:  domain.py  <property_file>';
		exit();
	try:
		props = Properties()
		input = FileInputStream(sys.argv[1])
		props.load(input)
		input.close()
	except:

		print 'Cannot load properties  !';
		exit();
	
	print 'initialization completed';
Ejemplo n.º 31
0
def intialize():
    global props

    if len(sys.argv) != 2:
        print 'Usage:  domain.py  <property_file>'
        exit()
    try:
        props = Properties()
        input = FileInputStream(sys.argv[1])
        props.load(input)
        input.close()
    except:

        print 'Cannot load properties  !'
        exit()

    print 'initialization completed'
Ejemplo n.º 32
0
def intialize():
    global domainProps
    global userConfigFile
    global userKeyFile
    global overwrittenServerURL
    global levelToPrint

    # test arguments
    if ((len(sys.argv) != 4) and (len(sys.argv) != 5)):
        print 'Usage:  printStatusInformation.sh  <default.properties_file> <property_file> <SUMMARY / ALL>'
        print 'OR'
        print 'Usage:  printStatusInformation.sh  <default.properties_file> <property_file> <SUMMARY / ALL> <ADMIN-URL overwrite>'
        exit()

    print 'Starting the initialization process'

    try:
        domainProps = Properties()

        # load DEFAULT properties
        input = FileInputStream(sys.argv[1])
        domainProps.load(input)
        input.close()

        # load properties and overwrite defaults
        input = FileInputStream(sys.argv[2])
        domainProps.load(input)
        input.close()

        userConfigFile = File(sys.argv[2]).getParent(
        ) + '/' + domainProps.getProperty('domainName') + '.userconfig'
        userKeyFile = File(sys.argv[2]).getParent(
        ) + '/' + domainProps.getProperty('domainName') + '.userkey'

        levelToPrint = sys.argv[3]

        if (len(sys.argv) == 5):
            overwrittenServerURL = sys.argv[4]

    except:
        dumpStack()
        print 'Cannot load properties  !'
        exit()

    print 'Initialization completed'
Ejemplo n.º 33
0
def intialize():
        global domainProps;
        global userConfigFile;
        global userKeyFile;
        global overwrittenServerURL;
        global levelToPrint;

        # test arguments
        if ((len(sys.argv) != 3) and (len(sys.argv) != 4)):
                print 'Usage:  threaddump.py <default.properties_file> <property_file>';
                print 'OR'
                print 'Usage:  threaddump.py <default.properties_file> <property_file> <ADMIN-URL overwrite>';
                exit();


        print 'Starting the initialization process';

        try:
                domainProps = Properties()

                # load DEFAULT properties
                input = FileInputStream(sys.argv[1])
                domainProps.load(input)
                input.close()

                # load properties and overwrite defaults
                input = FileInputStream(sys.argv[2])
                domainProps.load(input)
                input.close()

                userConfigFile = File(sys.argv[2]).getParent()+'/'+domainProps.getProperty('domainName')+'.userconfig'
                userKeyFile = File(sys.argv[2]).getParent()+'/'+domainProps.getProperty('domainName')+'.userkey'

                if (len(sys.argv) == 4):
                    overwrittenServerURL = sys.argv[3];


        except:
                dumpStack()
                print 'Cannot load properties  !';
                exit();

        print 'Initialization completed';
Ejemplo n.º 34
0
def parseNlbProps(output, resultVector, hostOSH, framework, ip):
    clusterNameAndProps = output.split('\n', 1)
    #the name of the cluster; also reflected in props that's why commented
    #clusterName = clusterNameAndProps[0]

    clusterPropsAndPortRules = re.split(PROP_RULE_SEPARATOR, clusterNameAndProps[1])

    #cut the statistics from output
    portRulesPropsString = re.split('\\s\\sStatistics:', clusterPropsAndPortRules[2])[0]
    props = Properties()

    propsString = String(clusterPropsAndPortRules[0])
    props.load(ByteArrayInputStream(propsString.getBytes('UTF-8')))

    parseRulesConfigOsh = parsePortRules(portRulesPropsString)
    nlbCluster = NlbClusterBuilder(props, parseRulesConfigOsh, hostOSH, framework, ip)
    nlbCluster.addOshToVector(resultVector)
    nlbNode = NlbSwBuilder(props, nlbCluster.getNlbClusterOSH(), hostOSH, framework)
    nlbNode.addOshToVector(resultVector)
Ejemplo n.º 35
0
def init(trace=False, debug=False):
    global jython_home
    global python_home
    global log
    global prog

    coll_home = getCollHome()
    prog, ext = getProgramName()
    #Load properties file in java.util.Properties
    propsFileName = coll_home + "/etc/collation.properties"
    inStream = FileInputStream(propsFileName)
    propFile = Properties()
    propFile.load(inStream)

    System.setProperty("jython.home", coll_home + "/external/jython-2.1")
    System.setProperty("python.home", coll_home + "/external/jython-2.1")
    jython_home = System.getProperty("jython.home")

    log = setupLog4jLogging(trace, debug)

    return log, prog
Ejemplo n.º 36
0
def getDebugMode():
    pushPropertiesFileStr = "%s%s%s" % (adapterConfigBaseDir, FILE_SEPARATOR, PUSH_PROPERTIES_FILE)
    properties = Properties()
    debugMode = 0
    try:
        logger.debug("Checking push properties file for debugMode [%s]" % pushPropertiesFileStr)
        fileInputStream = FileInputStream(pushPropertiesFileStr)
        properties.load(fileInputStream)
        debugModeStr = properties.getProperty("debugMode")
        if isNoneOrEmpty(debugModeStr) or string.lower(string.strip(debugModeStr)) == 'false':
            debugMode = 0
        elif string.lower(string.strip(debugModeStr)) == 'true':
            debugMode = 1
        fileInputStream.close()
    except:
        debugMode = 0 # ignore and continue with debugMode=0
        logger.debugException("Unable to process %s file." % PUSH_PROPERTIES_FILE)
    if debugMode:
        logger.debug("Debug mode = TRUE. XML data pushed to CA CMDB will be persisted in the directory: %s" % adapterResBaseDir)
    else:
        logger.debug("Debug mode = FALSE")
    return debugMode
Ejemplo n.º 37
0
def load_variables(file_path):
    """
    Load a dictionary of variables from the specified file.
    :param file_path: the file from which to load properties
    :return the dictionary of variables
    :raises VariableException if an I/O error occurs while loading the variables from the file
    """
    method_name = "load_variables"

    variable_map = {}
    props = Properties()
    input_stream = None
    try:
        input_stream = FileInputStream(file_path)
        props.load(input_stream)
        input_stream.close()
    except IOException, ioe:
        ex = exception_helper.create_variable_exception(
            'WLSDPLY-01730', file_path, ioe.getLocalizedMessage(), error=ioe)
        _logger.throwing(ex, class_name=_class_name, method_name=method_name)
        if input_stream is not None:
            input_stream.close()
        raise ex
Ejemplo n.º 38
0
def parseNlbProps(output, resultVector, hostOSH, framework, ip):
    clusterNameAndProps = output.split('\n', 1)
    #the name of the cluster; also reflected in props that's why commented
    #clusterName = clusterNameAndProps[0]

    clusterPropsAndPortRules = re.split(PROP_RULE_SEPARATOR,
                                        clusterNameAndProps[1])

    #cut the statistics from output
    portRulesPropsString = re.split('\\s\\sStatistics:',
                                    clusterPropsAndPortRules[2])[0]
    props = Properties()

    propsString = String(clusterPropsAndPortRules[0])
    props.load(ByteArrayInputStream(propsString.getBytes('UTF-8')))

    parseRulesConfigOsh = parsePortRules(portRulesPropsString)
    nlbCluster = NlbClusterBuilder(props, parseRulesConfigOsh, hostOSH,
                                   framework, ip)
    nlbCluster.addOshToVector(resultVector)
    nlbNode = NlbSwBuilder(props, nlbCluster.getNlbClusterOSH(), hostOSH,
                           framework)
    nlbNode.addOshToVector(resultVector)
 def __getEc2PrivateIpv4s(self, additionalVariables):
     try:
         dir = File(self.__basedir)
         dir = dir.getParentFile().getParentFile().getParentFile()
         fileReader = FileReader(File(dir, "engine-session.properties" ))
         props = Properties()
         props.load(fileReader)
         ec2PrivateIpv4s = props.getProperty("ec2PrivateIpv4s")
         if ec2PrivateIpv4s:
             ipList = ec2PrivateIpv4s.split()
             logger.info("Ec2 Private IPv4s:" + list2str(ipList))
             engineInstance = getVariableValue("ENGINE_INSTANCE")
             engineInstance = int(engineInstance)
             if len(ipList) > engineInstance:
                 self.__dockerHostIp = ipList[engineInstance]
                 logger.info("Setting DOCKER_HOST_IP:" +self.__dockerHostIp)
                 additionalVariables.add(RuntimeContextVariable("DOCKER_HOST_IP", self.__dockerHostIp, RuntimeContextVariable.STRING_TYPE, "Docker Host IP", False, RuntimeContextVariable.NO_INCREMENT))
             else:
                 self.__dockerHostIp  = getVariableValue("LISTEN_ADDRESS")
                 additionalVariables.add(RuntimeContextVariable("DOCKER_HOST_IP", self.__dockerHostIp , RuntimeContextVariable.STRING_TYPE, "Docker Host IP", False, RuntimeContextVariable.NO_INCREMENT))
     except:
         type, value, traceback = sys.exc_info()
         logger.warning("read engine session properties error:" + `value`)
Ejemplo n.º 40
0
def intialize():
    global domainProps
    global userConfigFile
    global userKeyFile
    global consoleAction

    # test arguments
    if len(sys.argv) != 4:
        print 'Usage:  adminConsole.sh  <default.properties_file> <property_file>  ON/OFF'
        exit()

    print 'Starting the initialization process'

    try:
        domainProps = Properties()

        # load DEFAULT properties
        input = FileInputStream(sys.argv[1])
        domainProps.load(input)
        input.close()

        # load properties and overwrite defaults
        input = FileInputStream(sys.argv[2])
        domainProps.load(input)
        input.close()

        userConfigFile = File(sys.argv[2]).getParent(
        ) + '/' + domainProps.getProperty('domainName') + '.userconfig'
        userKeyFile = File(sys.argv[2]).getParent(
        ) + '/' + domainProps.getProperty('domainName') + '.userkey'

        consoleAction = sys.argv[3]
    except:
        print 'Cannot load properties  !'
        exit()

    print 'Initialization completed'
Ejemplo n.º 41
0
def load_variables(file_path, allow_multiple_files=False):
    """
    Load a dictionary of variables from the specified file(s).
    :param file_path: the file from which to load properties
    :param allow_multiple_files: if True, allow a comma-separated list of variable files
    :return the dictionary of variables
    :raises VariableException if an I/O error occurs while loading the variables from the file
    """
    method_name = "load_variables"

    if allow_multiple_files:
        paths = file_path.split(CommandLineArgUtil.MODEL_FILES_SEPARATOR)
    else:
        paths = [file_path]

    variable_map = {}

    for path in paths:
        props = Properties()
        input_stream = None
        try:
            input_stream = FileInputStream(path)
            props.load(input_stream)
            input_stream.close()
        except IOException, ioe:
            ex = exception_helper.create_variable_exception(
                'WLSDPLY-01730', path, ioe.getLocalizedMessage(), error=ioe)
            _logger.throwing(ex,
                             class_name=_class_name,
                             method_name=method_name)
            if input_stream is not None:
                input_stream.close()
            raise ex

        for key in props.keySet():
            value = props.getProperty(key)
            variable_map[key] = value
Ejemplo n.º 42
0
    def doInBackground(self):
        #print "\n- Checking for the latest version..."
        try:
            url = URL(self.app.scriptVersionUrl)
            uc = url.openConnection()
            ins = uc.getInputStream()
            p = Properties()
            p.load(ins)
            latestScriptVersion = p.getProperty("script")
            self.app.latestToolsVersion = p.getProperty("tools")
        except (UnknownHostException, SocketException):
            print "I can't connect to:\n%s" % url
            ins.close()
            return

        if latestScriptVersion == self.app.SCRIPTVERSION:
            #using latest script
            print "  already using the latest script version:", self.app.SCRIPTVERSION
            if self.app.latestToolsVersion == self.app.TOOLSVERSION:
                #using latest tools
                print "  already using the latest tools version:", self.app.TOOLSVERSION
                if self.mode != "auto":
                    JOptionPane.showMessageDialog(self.app.preferencesFrame,
                                                  self.app.strings.getString("using_latest"))
                    return
            else:
                #not using latest tools
                print "  tools can be updated: %s -> %s" % (self.app.TOOLSVERSION,
                                                           self.app.latestToolsVersion)
                answer = JOptionPane.showConfirmDialog(Main.parent,
                    self.app.strings.getString("update_tools_question"),
                    self.app.strings.getString("updates_available"),
                    JOptionPane.YES_NO_OPTION)
                if answer == 0:
                    #Download the updated tools data
                    print "\n- Update tools data"
                    try:
                        self.app.toolsProgressDialog
                    except AttributeError:
                        from java.awt import Dialog
                        self.app.toolsProgressDialog = ToolsProgressDialog(Main.parent,
                                                           self.app.strings.getString("download_tools_updates"),
                                                           Dialog.ModalityType.APPLICATION_MODAL,
                                                           self.app)
                    self.app.toolsProgressDialog.show()
        else:
            #not using latest script
            print "a new script version is available:\n%s -> %s" % (self.app.SCRIPTVERSION,
                                                                    latestScriptVersion)
            messageArguments = array([self.app.SCRIPTVERSION, latestScriptVersion], String)
            formatter = MessageFormat("")
            formatter.applyPattern(self.app.strings.getString("updates_warning"))
            msg = formatter.format(messageArguments)
            options = [
                self.app.strings.getString("Do_not_check_for_updates"),
                self.app.strings.getString("Visit_Wiki"),
                self.app.strings.getString("cancel")]
            answer = JOptionPane.showOptionDialog(Main.parent,
                msg,
                self.app.strings.getString("updates_available"),
                JOptionPane.YES_NO_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                None,
                options,
                options[1])
            if answer == 0:
                self.app.properties.setProperty("check_for_update", "off")
                self.app.save_config(self)
            elif answer == 1:
                OpenBrowser.displayUrl(self.app.SCRIPTWEBSITE)
Ejemplo n.º 43
0
def loadPropsFil(propsFil):
    properties = {}
    propFil = Properties()
    propFil.load(FileInputStream(propsFil))
    properties.update(propFil)
    return properties
Ejemplo n.º 44
0
    elif opt == "-p":
        properties = arg
    elif opt == "-t":
        domainDir = arg

if domain == "":
    print "Missing \"-d domain\" parameter."
    usage()
    sys.exit(2)

if domainDir == "":
    print "Missing \"-t domainDir\" parameter."
    usage()
    sys.exit(2)

if properties == "":
    print "Missing \"-p Property File\" parameter."
    usage()
    sys.exit(2)

propsInputStream = FileInputStream(properties)
props.load(propsInputStream)

print "ConfigureIAMDomain started"

iam_home_dir = props.get("IAM_HOME")

print "IAM_HOME=" + iam_home_dir

sys.exit()
Ejemplo n.º 45
0
from java import io
from java.lang import Exception
from java.lang import Throwable
import os.path
import sys

envproperty = ""
if (len(sys.argv) > 1):
    envproperty = sys.argv[1]
else:
    print "Environment Property file not specified"
    sys.exit(2)

propInputStream = FileInputStream(envproperty)
configProps = Properties()
configProps.load(propInputStream)


def createJDBCDS(ds_name, ds_jndi, ds_url, ds_user, ds_pwd, target_name):
    try:
        cd('/')
        print "Deleting datasource: " + ds_jndi
        delete(ds_jndi, 'JDBCSystemResource')
        print ds_jndi + " deleted!"
    except:
        print ds_jndi + " does not exist!"

    jdbcds = create(ds_name, "JDBCSystemResource")
    jdbcResource = jdbcds.getJDBCResource()
    jdbcResource.setName(ds_name)
    jdbcds.addTarget(getMBean("/Servers/" + target_name))
Ejemplo n.º 46
0
from java import io
from java.lang import Exception
from java.lang import Throwable
import os.path
import sys
 
envproperty=""
if (len(sys.argv) > 1):
        envproperty=sys.argv[1]
else:
        print "Environment Property file not specified"
        sys.exit(2)
 
propInputStream=FileInputStream(envproperty)
configProps=Properties()
configProps.load(propInputStream)
 
##########################################
# Create JMS Moudle will take the 
# arguments as name, subdeployment name
# target can be on admin or managed server or cluster
##########################################
def createJMSModule(jms_module_name, adm_name, subdeployment_name):
        cd('/JMSServers')
        jmssrvlist=ls(returnMap='true')
        print jmssrvlist
        cd('/')
        module = create(jms_module_name, "JMSSystemResource")
        #cluster = getMBean("Clusters/"+cluster_target_name)
        #module.addTarget(cluster)
        #adm_name=get('AdminServerName')
#!/usr/bin/env /oracle/product/middleware/Oracle_OSB1/common/bin/wlst.sh
from java.util import Properties
from java.io import FileInputStream

# ===============
#  Variable Defs
# ===============
# relativo estar na mesma pasta . 
prop = Properties()
prop.load(FileInputStream("osb.properties"))

ADMIN_SERVER 				= prop.getProperty('ADMIN_SERVER')
ADMIN_SERVER_PORT		 	= int(prop.getProperty('ADMIN_SERVER_PORT'))
DATABASE 					= prop.getProperty('DATABASE')
DOMAIN 						= prop.getProperty('DOMAIN')
DOMAIN_HOME 				= prop.getProperty('DOMAIN_HOME')
LISTEN_ADDRESS 				= prop.getProperty('LISTEN_ADDRESS')
MACHINE 					= prop.getProperty('MACHINE')
MANAGED_SERVER 				= prop.getProperty('MANAGED_SERVER')
MANAGED_SERVER_PORT			= int(prop.getProperty('MANAGED_SERVER_PORT'))
MDS_USER 					= prop.getProperty('MDS_USER')
MDS_PASSWORD 				= prop.getProperty('MDS_PASSWORD')
MW_HOME						= prop.getProperty('MW_HOME')
NODE_MANAGER 				= prop.getProperty('NODE_MANAGER')
NODE_MANAGER_LISTEN_ADDRESS = prop.getProperty('NODE_MANAGER_LISTEN_ADDRESS')
NODE_MANAGER_PASSWORD		= prop.getProperty('NODE_MANAGER_PASSWORD')
NODE_MANAGER_PORT 			= int(prop.getProperty('NODE_MANAGER_PORT'))
OSB_HOME					= prop.getProperty('OSB_HOME')
SOAINFRA_USER 				= prop.getProperty('SOAINFRA_USER')
SOAINFRA_PASSWORD 			= prop.getProperty('SOAINFRA_PASSWORD')
WEBLOGIC_PASSWORD			= prop.getProperty('WEBLOGIC_PASSWORD')
Ejemplo n.º 48
0
        rb_config.setProperty('validation',validation)
    if validation=='on':
        run_validators()
    else:
        main_logger.warn('Ignoring validation due to property validation=off')
    
try:
    customLog = rb_config.getProperty('confignow.commandlog')
    # @todo - consider moving off to separate function 
    if customLog is not None and len(customLog) > 0:
        if customLog == 'true':
            customLog = 'ConfigNOW_' + command_name + "_" + datetime.now().strftime("%Y%m%d_%H%M%S.log")
        main_logger.info('Setting custom log file for command: "' + customLog + '"')
        inStream = FileInputStream('log4j.properties')
        logProperties = Properties()
        logProperties.load(inStream)
        logProperties.setProperty('log4j.appender.filelog.File', customLog)
        PropertyConfigurator.configure(logProperties)

    log = setup_command_logger()
	

    main_logger.info('WLST support: ' + bool_str(wlst_support))

    command_file = find_command_file()
    if command_file:
        validate_plugins()
        run_command_plugins('pre')
        if is_jython(command_file):
            main_logger.info('Running command from jython file: ' + command_file)
            # todo: investigate changing this to use call_extension(), done like this to work with wlst
Ejemplo n.º 49
0
        run_validators()
    else:
        main_logger.warn('Ignoring validation due to property validation=off')

try:
    customLog = rb_config.getProperty('confignow.commandlog')
    # @todo - consider moving off to separate function
    if customLog is not None and len(customLog) > 0:
        if customLog == 'true':
            customLog = 'ConfigNOW_' + command_name + "_" + datetime.now(
            ).strftime("%Y%m%d_%H%M%S.log")
        main_logger.info('Setting custom log file for command: "' + customLog +
                         '"')
        inStream = FileInputStream('log4j.properties')
        logProperties = Properties()
        logProperties.load(inStream)
        logProperties.setProperty('log4j.appender.filelog.File', customLog)
        PropertyConfigurator.configure(logProperties)

    log = setup_command_logger()

    main_logger.info('WLST support: ' + bool_str(wlst_support))

    command_file = find_command_file()
    if command_file:
        validate_plugins()
        run_command_plugins('pre')
        if is_jython(command_file):
            main_logger.info('Running command from jython file: ' +
                             command_file)
            # todo: investigate changing this to use call_extension(), done like this to work with wlst
Ejemplo n.º 50
0
from java.sql import DriverManager
from java.util import Properties
from java.util import Random
from java.io import FileInputStream
from java.lang import System
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test

testname = System.getProperty("sql.testname")
test = Test(0, testname)

testConfig = "./src/test/use-cases/"
sqlQueryFilename = testConfig + testname + ".sql"
connectionSettingsFile = testConfig + testname
jdbcConnectionSettings = Properties()
jdbcConnectionSettings.load(FileInputStream(connectionSettingsFile))

sqlQuery = open(sqlQueryFilename, "r").readline()

# Load the JDBC drivers.
DriverManager.registerDriver(OracleDriver())


def getConnection():
    return DriverManager.getConnection(
        jdbcConnectionSettings.getProperty("url"),
        jdbcConnectionSettings.getProperty("username"),
        jdbcConnectionSettings.getProperty("password"))


def ensureClosed(object):
Ejemplo n.º 51
0
#!/usr/bin/env /oracle/product/middleware/Oracle_OSB1/common/bin/wlst.sh
from java.util import Properties
from java.io import FileInputStream

# ===============
#  Variable Defs
# ===============

prop = Properties()
prop.load(FileInputStream('osb.properties'))

ADMIN_SERVER = prop.getProperty('ADMIN_SERVER')
ADMIN_SERVER_PORT = int(prop.getProperty('ADMIN_SERVER_PORT'))
DATABASE = prop.getProperty('DATABASE')
DOMAIN = prop.getProperty('DOMAIN')
DOMAIN_HOME = prop.getProperty('DOMAIN_HOME')
LISTEN_ADDRESS = prop.getProperty('LISTEN_ADDRESS')
MACHINE = prop.getProperty('MACHINE')
MANAGED_SERVER = prop.getProperty('MANAGED_SERVER')
MANAGED_SERVER_PORT = int(prop.getProperty('MANAGED_SERVER_PORT'))
MDS_USER = prop.getProperty('MDS_USER')
MDS_PASSWORD = prop.getProperty('MDS_PASSWORD')
MW_HOME = prop.getProperty('MW_HOME')
NODE_MANAGER = prop.getProperty('NODE_MANAGER')
NODE_MANAGER_LISTEN_ADDRESS = prop.getProperty('NODE_MANAGER_LISTEN_ADDRESS')
NODE_MANAGER_PASSWORD = prop.getProperty('NODE_MANAGER_PASSWORD')
NODE_MANAGER_PORT = int(prop.getProperty('NODE_MANAGER_PORT'))
OSB_HOME = prop.getProperty('OSB_HOME')
SOAINFRA_USER = prop.getProperty('SOAINFRA_USER')
SOAINFRA_PASSWORD = prop.getProperty('SOAINFRA_PASSWORD')
WEBLOGIC_PASSWORD = prop.getProperty('WEBLOGIC_PASSWORD')
Ejemplo n.º 52
0
# -*- coding: utf-8 -*-
import sys, os, re
from datetime import date
from java.util import Properties
from java.io import FileInputStream

# Load the properties file.
properties = Properties()
properties.load(FileInputStream('gradle.properties'))

# Set the basic project information.
project = 'Armeria'
project_short = 'Armeria'
copyright = properties.get('inceptionYear') + '-' + str(date.today().year) + ', LINE Corporation'

# Set the project version and release.
# Use the last known stable release if the current version ends with '-SNAPSHOT'.
if re.match(r'^.*-SNAPSHOT$', properties.get('version')):
    release = '0.32.0'
else:
    release = properties.get('version')
version = re.match(r'^[0-9]+\.[0-9]+', release).group(0)

# Export the loaded properties and some useful values into epilogs
rst_epilog = '\n'
rst_epilog += '.. |baseurl| replace:: http://line.github.io/armeria/\n'
propIter = properties.entrySet().iterator()
while propIter.hasNext():
    propEntry = propIter.next()
    if propEntry.getKey() in [ 'release', 'version' ]:
        continue
Ejemplo n.º 53
0
from javax.servlet import Filter
from javax.servlet.http import HttpServletResponse

# Python
import contextlib
import os
import json
import urllib
from urlparse import urlparse

# Read VIVO deploy.properties file.
webinf = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
properties_file = os.path.join(webinf, "classes/deploy.properties")
in_stream = FileInputStream(properties_file)
properties = Properties()
properties.load(in_stream)

TOMCAT_HOME = properties.getProperty("tomcat.home").strip()

# setup logging
# TODO: make logging level conditional on the development setting in deploy.properties
import logging

logging.basicConfig(
    level=logging.INFO,
    filename=os.path.join(TOMCAT_HOME, "logs/vivo-etag-cache.log"),
    filemode="w",
    format="%(asctime)s - %(levelname)s - %(message)s",
)

VIVO_SOLR = properties.getProperty("vitro.local.solr.url").strip()
Ejemplo n.º 54
0
def getPushProperties():
    pushProperties = HashMap()
    pushPropertiesFileStr = "%s%s%s" % (adapterConfigBaseDir, FILE_SEPARATOR,
                                        PUSH_PROPERTIES_FILE)
    properties = Properties()
    debugMode = 0
    sortCSVFields = ""
    smartUpdateIgnoreFields = ""
    testConnNameSpace = "BMC.CORE"
    testConnClass = "BMC_ComputerSystem"
    try:
        logger.debug("Checking push properties file for debugMode [%s]" %
                     pushPropertiesFileStr)
        fileInputStream = FileInputStream(pushPropertiesFileStr)
        properties.load(fileInputStream)

        # Property: debugMode
        try:
            debugModeStr = properties.getProperty("debugMode")
            if isNoneOrEmpty(debugModeStr) or string.lower(
                    string.strip(debugModeStr)) == 'false':
                debugMode = 0
            elif string.lower(string.strip(debugModeStr)) == 'true':
                debugMode = 1
        except:
            logger.debugException(
                "Unable to read debugMode property from push.properties")

        if debugMode:
            logger.debug(
                "Debug mode = TRUE. XML data pushed to Remedy/Atrium will be persisted in the directory: %s"
                % adapterResBaseDir)
        else:
            logger.debug("Debug mode = FALSE")

        # Property: smartUpdateIgnoreFields
        try:
            smartUpdateIgnoreFields = properties.getProperty(
                "smartUpdateIgnoreFields")
        except:
            logger.debugException(
                "Unable to read smartUpdateIgnoreFields property from push.properties"
            )

        # Property: sortCSVFields
        try:
            sortCSVFields = properties.getProperty("sortCSVFields")
        except:
            logger.debugException(
                "Unable to read sortCSVFields property from push.properties")

        # Property: testConnNameSpace
        try:
            testConnNameSpace = properties.getProperty("testConnNameSpace")
        except:
            logger.debugException(
                "Unable to read testConnNameSpace property from push.properties"
            )

        # Property: testConnClass
        try:
            testConnClass = properties.getProperty("testConnClass")
        except:
            logger.debugException(
                "Unable to read testConnClass property from push.properties")

        fileInputStream.close()
    except:
        logger.debugException("Unable to process %s file." %
                              PUSH_PROPERTIES_FILE)

    return debugMode, smartUpdateIgnoreFields, sortCSVFields, testConnNameSpace, testConnClass
Ejemplo n.º 55
0
    def doInBackground(self):
        #print "\n- Checking for the latest version..."
        try:
            url = URL(self.app.scriptVersionUrl)
            uc = url.openConnection()
            ins = uc.getInputStream()
            p = Properties()
            p.load(ins)
            latestScriptVersion = p.getProperty("script")
            self.app.latestToolsVersion = p.getProperty("tools")
        except (UnknownHostException, SocketException):
            print "I can't connect to:\n%s" % url
            ins.close()
            return

        if latestScriptVersion == self.app.SCRIPTVERSION:
            #using latest script
            print "  already using the latest script version:", self.app.SCRIPTVERSION
            if self.app.latestToolsVersion == self.app.TOOLSVERSION:
                #using latest tools
                print "  already using the latest tools version:", self.app.TOOLSVERSION
                if self.mode != "auto":
                    JOptionPane.showMessageDialog(
                        self.app.preferencesFrame,
                        self.app.strings.getString("using_latest"))
                    return
            else:
                #not using latest tools
                print "  tools can be updated: %s -> %s" % (
                    self.app.TOOLSVERSION, self.app.latestToolsVersion)
                if self.app.mode == "stable":
                    infoString = self.app.strings.getString(
                        "update_tools_question")
                else:
                    infoString = self.app.strings.getString(
                        "dev_update_tools_question")
                answer = JOptionPane.showConfirmDialog(
                    Main.parent, infoString,
                    self.app.strings.getString("updates_available"),
                    JOptionPane.YES_NO_OPTION)
                if answer == 0:
                    #Download the updated tools data
                    print "\n- Update tools data"
                    try:
                        self.app.toolsProgressDialog
                    except AttributeError:
                        from java.awt import Dialog
                        self.app.toolsProgressDialog = ToolsProgressDialog(
                            Main.parent,
                            self.app.strings.getString(
                                "download_tools_updates"),
                            Dialog.ModalityType.APPLICATION_MODAL, self.app)
                    self.app.toolsProgressDialog.show()
        else:
            #not using latest script
            print "a new script version is available:\n%s -> %s" % (
                self.app.SCRIPTVERSION, latestScriptVersion)
            messageArguments = array(
                [self.app.SCRIPTVERSION, latestScriptVersion], String)
            formatter = MessageFormat("")
            if self.app.mode == "stable":
                formatter.applyPattern(
                    self.app.strings.getString("updates_warning"))
                infoBtnString = self.app.strings.getString("Visit_Wiki")
            else:
                formatter.applyPattern(
                    self.app.strings.getString("dev_updates_warning"))
                infoBtnString = self.app.strings.getString("Visit_git")
            msg = formatter.format(messageArguments)
            options = [
                self.app.strings.getString("Do_not_check_for_updates"),
                infoBtnString,
                self.app.strings.getString("cancel")
            ]
            answer = JOptionPane.showOptionDialog(
                Main.parent, msg,
                self.app.strings.getString("updates_available"),
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                None, options, options[1])
            if answer == 0:
                self.app.properties.setProperty("check_for_update", "off")
                self.app.save_config(self)
            elif answer == 1:
                if self.app.mode == "stable":
                    url = self.app.SCRIPTWEBSITE
                else:
                    url = self.app.GITWEBSITE
                OpenBrowser.displayUrl(url)
Ejemplo n.º 56
0
from java.util import Properties
from java.util import Random
from java.io import FileInputStream
from java.lang import System
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test


testname = System.getProperty("sql.testname")
test = Test(0, testname)

testConfig = "./src/test/use-cases/"
sqlQueryFilename = testConfig + testname + ".sql"
connectionSettingsFile=testConfig + testname
jdbcConnectionSettings = Properties();
jdbcConnectionSettings.load( FileInputStream(connectionSettingsFile) )

sqlQuery = open(sqlQueryFilename,"r").readline()

# Load the JDBC drivers.
DriverManager.registerDriver(OracleDriver())

def getConnection():
    return DriverManager.getConnection(jdbcConnectionSettings.getProperty("url"),
            jdbcConnectionSettings.getProperty("username"),
            jdbcConnectionSettings.getProperty("password"))

def ensureClosed(object):
    try: object.close()
    except: pass
Ejemplo n.º 57
0
def datasource(cluster,user,password,url,env,jdbc_driver,timeOut,maxConn,minConn,reapTime,unusdTimeout,agedTimeout):

# Declare global variables 

global AdminConfig 
global AdminControl



## JDBCProvider ##


name = "jdbcOracle"+ env

print " Name of JDBC Provider which will be created ---> " + name

print " ----------------------------------------------------------------------------------------- "

# Gets the name of cell

cell = AdminControl.getCell()

cellid = AdminConfig.getid('/Cell:'+ cell +'/')

print " ----------------------------------------------------------------------------------------- "



# checking for the existence of Cluster


Serverid = AdminConfig.getid('/Cell:'+ cell +'/ServerCluster:'+ cluster +'/')

print " Checking for existence of Server :" + cluster

if len(Serverid) == 0:

print "Cluster doesnot exists "

else:

print "Cluster exist:"+ cluster

print " ----------------------------------------------------------------------------------------- "


## removing old jdbc provider and creating a new jdbc provider 

print " Checking for the existence of JDBC Provider :"+ name 

s2 = AdminConfig.getid('/Cell:'+ cell +'/ServerCluster:'+ cluster +'/JDBCProvider:'+ name) 

if len(s2) > 0:

print " JDBC Provider exists with name :"+ name

print " Removing JDBC Provider with name :"+ name

AdminConfig.remove(s2)

print " JDBC Provider removed "

AdminConfig.save()

print " Saving Configuraion "

print " ----------------------------------------------------------------------------------------- " 

## Creating New JDBC Provider ##

print " Creating New JDBC Provider :"+ name 

n1 = ["name" , name ]

desc = ["description" , "Oracle JDBC Driver"]

impn = ["implementationClassName" , "oracle.jdbc.pool.OracleConnectionPoolDataSource"]

classpath = ["classpath" , jdbc_driver ]

attrs1 = [n1 , impn , desc , classpath]

jdbc = AdminConfig.create('JDBCProvider' , Serverid , attrs1)

print " New JDBC Provider created :"+ name 

AdminConfig.save()

print " Saving Configuraion " 

print " ----------------------------------------------------------------------------------------- "

## checking for the existence of JAASAuthData and deleting ## 

node = AdminControl.getNode()

alias1 = node +"/"+ env

print " Checking for the existence of JAASAUTHDATA :"+ alias1 

jaasAuthDataList = AdminConfig.list("JAASAuthData")

if len(jaasAuthDataList) == 0: 

print " Creating New JAASAuthData with Alias name :"+ alias1

sec = AdminConfig.getid('/Cell:'+ cell +'/Security:/')

alias_attr = ["alias" , alias1]

desc_attr = ["description" , "alias"]

userid_attr = ["userId" , user ]

password_attr = ["password" , password]

attrs = [alias_attr , desc_attr , userid_attr , password_attr ]

authdata = AdminConfig.create('JAASAuthData' , sec , attrs)

print " Created new JASSAuthData with Alias name :"+ alias1

AdminConfig.save()

print " Saving Configuraion "

print " ----------------------------------------------------------------------------------------- "

else :

matchFound = 0 

jaasAuthDataList = AdminConfig.list("JAASAuthData") 

jaasAuthDataList=jaasAuthDataList.split(lineSeparator)

for jaasAuthId in jaasAuthDataList:

getAlias = AdminConfig.showAttribute(jaasAuthId, "alias")

if (cmp(getAlias,alias1) == 0):

print " JAASAuthData exists with name :"+ alias1

print " Removing JAASAuthData with name :"+ alias1

AdminConfig.remove(jaasAuthId)

print " JAASAuthData removed " 

AdminConfig.save()

print " Saving Configuraion " 

matchFound = 1

break

if (matchFound == 0):

print " No match was found for the given JASSAuthData : "+ alias1

#endIf

print " ----------------------------------------------------------------------------------------- "


## J2C Authentication Entries ##

print " Creating New JAASAuthData with Alias name :"+ alias1

sec = AdminConfig.getid('/Cell:'+ cell +'/Security:/')

alias_attr = ["alias" , alias1]

desc_attr = ["description" , "alias"]

userid_attr = ["userId" , user ]

password_attr = ["password" , password]

attrs = [alias_attr , desc_attr , userid_attr , password_attr ]

authdata = AdminConfig.create('JAASAuthData' , sec , attrs)

print " Created new JASSAuthData with Alias name :"+ alias1 

AdminConfig.save()

print " Saving Configuraion "

print " ----------------------------------------------------------------------------------------- " 

## DataSource ##

datasource = "DataSource"+ env

print " Name of datasource which will be created on JDBC Provider :"+ name +" is :"+ datasource

ds = AdminConfig.getid('/Cell:'+ cell +'/ServerCluster:'+ cluster +'/JDBCProvider:'+ name) 

name1 = ["name" , datasource]

jndi = ["jndiName" , "jdbc/tiers3DS"]

authentication = ["authDataAlias" , alias1]

st_cachesize = ["statementCacheSize" , "150"]

ds_hlpclass = ["datasourceHelperClassname" , "com.ibm.websphere.rsadapter.Oracle10gDataStoreHelper"]

map_configalias_attr=["mappingConfigAlias", "DefaultPrincipalMapping"]

map_attrs=[authentication , map_configalias_attr]

mapping_attr=["mapping", map_attrs]

ds_attr = [name1 , jndi , authentication , st_cachesize , ds_hlpclass ,mapping_attr ]

newds = AdminConfig.create('DataSource' , ds , ds_attr)

print " New DataSource created with name :"+ datasource 

AdminConfig.save()

print " Saving Configuraion "

print " ----------------------------------------------------------------------------------------- "

## set the properties for the datasource ##

print " Setting the properties for DataSource :"+ datasource

newds1 = AdminConfig.getid('/Cell:'+ cell +'/ServerCluster:'+ cluster +'/JDBCProvider:'+ name +'/DataSource:'+ datasource)

propSet = AdminConfig.create('J2EEResourcePropertySet' , newds1 , "")

name3 = ["name" , "URL"]

type = ["type" , "java.lang.String"]

required = ["required" , "true"]

value = ["value" , url]

rpAttrs = [name3 , type , required , value]

jrp = AdminConfig.create('J2EEResourceProperty' , propSet , rpAttrs)


print " Properties created for DataSource :"+ datasource 

AdminConfig.save()

print " Saving Configuraion "

print " ----------------------------------------------------------------------------------------- "

# Create an associated connection pool for the new DataSource#

print " Creating Connection Pool Setting for DataSource :"+ datasource

timeout = ["connectionTimeout" , timeOut]

maxconn = ["maxConnections" , maxConn]

minconn = ["minConnections" , minConn]

reaptime = ["reapTime" , reapTime]

unusedtimeout = ["unusedTimeout" , unusdTimeout]

agedtimeout = ["agedTimeout" , agedTimeout]

purgepolicy = ["purgePolicy" , "EntirePool"]

connPoolAttrs = [timeout , maxconn , minconn , reaptime , unusedtimeout , agedtimeout , purgepolicy] 

AdminConfig.create("ConnectionPool", newds , connPoolAttrs)

print " Connection Pool Setting created for DataSource :"+ datasource 

AdminConfig.save()

print " Saving Configuraion "

print " ----------------------------------------------------------------------------------------- "


## Full Syncronization ##

print " Syncronizing configuration with Master Repository "

nodelist = AdminTask.listManagedNodes().split(lineSep)

for nodename in nodelist :

print " Doing Full Resyncronization of node.......... "

####################Identifying the ConfigRepository MBean and assign it to variable######################

repo = AdminControl.completeObjectName('type=ConfigRepository,process=nodeagent,node='+ nodename +',*')

print AdminControl.invoke(repo, 'refreshRepositoryEpoch')

sync = AdminControl.completeObjectName('cell='+ cell +',node='+ nodename +',type=NodeSync,*')

print AdminControl.invoke(sync , 'sync')

#time.sleep(20)

print " ----------------------------------------------------------------------------------------- "

print " Full Resyncronization completed "

print " ----------------------------------------------------------------------------------------- "

#######Restarting Node Agent#########

nodelist = AdminTask.listManagedNodes().split(lineSep)

for nodename in nodelist :

print " Restarting Nodeagent of "+nodename+" node " 

na = AdminControl.queryNames('type=NodeAgent,node='+nodename+',*') 

AdminControl.invoke(na,'restart','true true') 

print " ----------------------------------------------------------------------------------------- "

time.sleep(30)

##########Testing Database Connection################

dsid = AdminConfig.getid('/ServerCluster:'+ cluster +'/JDBCProvider:'+ name +'/DataSource:'+ datasource +'/')

print " Testing Database Connection"

print AdminControl.testConnection(dsid)

print " ----------------------------------------------------------------------------------------- "
####################################################################################################################
####################################################################################################################

#main program starts here

arglen=len(sys.argv)

num_exp_args=2

if (arglen != num_exp_args):

print "Two arguments are required.one of them is property file"

print " ----------------------------------------------------------------------------------------- "

sys.exit(-1)

propFile=sys.argv[0]

properties=Properties();

try:

properties.load(FileInputStream(propFile))

print " ----------------------------------------------------------------------------------------- "

print "Succesfully read property file "+propFile

print " ----------------------------------------------------------------------------------------- "

except:

print "Cannot read property file "+propFile
sys.exit(-1)

print " ----------------------------------------------------------------------------------------- "

cluster = str(properties.getProperty("CLUSTER_NAME"))
env = sys.argv[1]
user = str(properties.getProperty("dbms.userId"))
password = str(properties.getProperty("dbms.password"))
url = str(properties.getProperty("dbms.url"))
jdbc_driver = str(properties.getProperty("JDBC_DRIVER_PATH"))
timeOut = int(properties.getProperty("TIMEOUT"))
maxConn = int(properties.getProperty("MAXCONN"))
minConn = int(properties.getProperty("MINCONN"))
reapTime = int(properties.getProperty("REAPTIME"))
unusdTimeout = int(properties.getProperty("UNUSEDTIMEOUT"))
agedTimeout = int(properties.getProperty("AGEDTIMEOUT"))

datasource(cluster,user,password,url,env,jdbc_driver,timeOut,maxConn,minConn,reapTime,unusdTimeout,agedTimeout)
Ejemplo n.º 58
0
# -*- coding: utf-8 -*-
import sys, os, re
from datetime import date
from java.util import Properties
from java.io import FileInputStream

# Load the properties file.
properties = Properties()
properties.load(FileInputStream('gradle.properties'))

# Set the basic project information.
project = 'Armeria'
project_short = 'Armeria'
copyright = properties.get('inceptionYear') + '-' + str(
    date.today().year) + ', LINE Corporation'

# Set the project version and release.
# Use the last known stable release if the current version ends with '-SNAPSHOT'.
if re.match(r'^.*-SNAPSHOT$', properties.get('version')):
    release = '0.31.0.Final'
else:
    release = properties.get('version')
version = re.match(r'^[0-9]+\.[0-9]+', release).group(0)

# Export the loaded properties and some useful values into epilogs
rst_epilog = '\n'
rst_epilog += '.. |baseurl| replace:: http://line.github.io/armeria/\n'
propIter = properties.entrySet().iterator()
while propIter.hasNext():
    propEntry = propIter.next()
    if propEntry.getKey() in ['release', 'version']: