def createLdapExtendedEntryManagers(self, authConfiguration): ldapExtendedConfigurations = self.createLdapExtendedConfigurations(authConfiguration) appInitializer = CdiUtil.bean(AppInitializer) persistanceFactoryService = CdiUtil.bean(PersistanceFactoryService) ldapEntryManagerFactory = persistanceFactoryService.getPersistenceEntryManagerFactory(LdapEntryManagerFactory) persistenceType = ldapEntryManagerFactory.getPersistenceType() ldapExtendedEntryManagers = [] for ldapExtendedConfiguration in ldapExtendedConfigurations: connectionConfiguration = ldapExtendedConfiguration["connectionConfiguration"] ldapProperties = Properties() for key, value in connectionConfiguration.items(): value_string = value if isinstance(value_string, list): value_string = ", ".join(value) else: value_string = str(value) ldapProperties.setProperty(persistenceType + "." + key, value_string) ldapEntryManager = ldapEntryManagerFactory.createEntryManager(ldapProperties) ldapExtendedEntryManagers.append({ "ldapConfiguration" : ldapExtendedConfiguration["ldapConfiguration"], "ldapProperties" : ldapProperties, "loginAttributes" : ldapExtendedConfiguration["loginAttributes"], "localLoginAttributes" : ldapExtendedConfiguration["localLoginAttributes"], "ldapEntryManager" : ldapEntryManager }) return ldapExtendedEntryManagers
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() CmdbOIDFactory = CmdbObjectID.Factory hostId = CmdbOIDFactory.restoreObjectID(Framework.getDestinationAttribute('hostId')) sqlServerId = CmdbOIDFactory.restoreObjectID(Framework.getDestinationAttribute('id')) try: props = Properties() instance_name = Framework.getDestinationAttribute('instanceName') if instance_name and instance_name != 'NA' and instance_name.find('\\') != -1: props.setProperty('sqlprotocol_dbsid', instance_name[instance_name.find('\\')+1:]) mssqlClient = Framework.createClient(props) connection = SqlServerConnection.ClientSqlServerConnection(mssqlClient) logger.debug("got connection") discoveryOptions = SqlServerDiscoveryOptions() discoveryOptions.discoverConfigs = Boolean.parseBoolean(Framework.getParameter('discoverConfigs')) discoveryOptions.discoverDbUser = Boolean.parseBoolean(Framework.getParameter('discoverDbUser')) discoveryOptions.discoverSqlFile = Boolean.parseBoolean(Framework.getParameter('discoverSqlFile')) discoveryOptions.discoverSqlJob = Boolean.parseBoolean(Framework.getParameter('discoverSqlJob')) discoveryOptions.discoverProcedures = Boolean.parseBoolean(Framework.getParameter('discoverStoredProcedures')) discoveryOptions.discoverInternalProcedures = Boolean.parseBoolean(Framework.getParameter('discoverInternalProcedures')) sqlServer = SqlServer.SqlServer(connection, discoveryOptions) OSHVResult.addAll(sqlServer.collectData(hostId, sqlServerId, discoveryOptions.discoverConfigs)) mssqlClient.close() except JavaException, ex: strException = ex.getMessage() errormessages.resolveAndReport(strException, ClientsConsts.SQL_PROTOCOL_NAME, Framework)
def connectToDb(localFramework, ipAddress, dbPort): try: theDbClient = None ## Get protocols protocols = localFramework.getAvailableProtocols(ipAddress, ClientsConsts.SQL_PROTOCOL_NAME) for protocolID in protocols: ## If this protocol entry is not for a Sybase DB, ignore it if localFramework.getProtocolProperty(protocolID, CollectorsConstants.SQL_PROTOCOL_ATTRIBUTE_DBTYPE) != 'Sybase': debugPrint(5, '[' + SCRIPT_NAME + ':DiscoveryMain] Ignoring non Sybase protocol entry...') continue ## Don't bother reconnecting if a connection has already been established if not theDbClient: ## Set DB properties dbConnectionProperties = Properties() dbConnectionProperties.setProperty(CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT, dbPort) # Establish JDBC connection debugPrint(5, '[' + SCRIPT_NAME + ':connectToDb] Attempting connection to CiscoWorks database at port <%s>...' % dbPort) try: theDbClient = localFramework.createClient(protocolID, dbConnectionProperties) except: theDbClient and theDBClient.close() return theDbClient except: excInfo = logger.prepareJythonStackTrace('') logger.warn('[' + SCRIPT_NAME + ':connectToDb] Exception: <%s>' % excInfo) pass
def _sapJmxConnect(credId, ip, Framework): r'''@types: str, str, Framework -> Result ''' message = None status = False for version in SAPJmxAgent.getAvailableVersions(): props = Properties() props.setProperty(AgentConstants.VERSION_PROPERTY, version) logger.debug('Trying to connect to ip=%s by \'%s\' '\ 'protocol (assuming version %s)...' % (ip, _PROTOCOL_NAME, version)) try: sap = Framework.getAgent(AgentConstants.SAP_JMX_AGENT, ip, credId, props) sap.connect() except: message = 'error: %s' % sys.exc_info()[1] logger.debug('connection to ip=%s by \'%s\' '\ 'protocol failed. %s' % (ip, _PROTOCOL_NAME, message)) continue else: logger.debug('connection to ip=%s by \'%s\' '\ 'protocol is successful' % (ip, _PROTOCOL_NAME)) status = True break finally: sap and sap.disconnect() return Result(status, message)
def write_variables(program_name, variable_map, file_path, append=False): """ Write the dictionary of variables to the specified file. :param program_name: name of tool that invoked the method which will be written to the variable properties file :param variable_map: the dictionary of variables :param file_path: the file to which to write the properties :param append: defaults to False. Append properties to the end of file :raises VariableException if an error occurs while storing the variables in the file """ _method_name = 'write_variables' _logger.entering(program_name, file_path, append, class_name=_class_name, method_name=_method_name) props = Properties() for key in variable_map: value = variable_map[key] props.setProperty(key, value) comment = exception_helper.get_message('WLSDPLY-01731', program_name) output_stream = None try: output_stream = FileOutputStream(File(file_path), Boolean(append)) props.store(output_stream, comment) output_stream.close() except IOException, ioe: ex = exception_helper.create_variable_exception('WLSDPLY-20007', file_path, ioe.getLocalizedMessage(), error=ioe) _logger.throwing(ex, class_name=_class_name, method_name=_method_name) if output_stream is not None: output_stream.close() raise ex
def __createConnection(self): "create database" self.__connection = None try: logger.info("RegisterJDBC driver: com.mysql.jdbc.Driver") driver = com.mysql.jdbc.Driver.newInstance() if driver and driver.acceptsURL(self.__rootJdbcUrl): props = Properties() props.setProperty("user", "root") props.setProperty("password", self.__rootPwd) logger.info("Create JDBC connection:" + self.__rootJdbcUrl) self.__connection = driver.connect(self.__rootJdbcUrl, props) if self.__connection: logger.info("Create db select prepared statement") self.__dbstmt = self.__connection.prepareStatement("show databases;") rs = self.__dbstmt.executeQuery() self.__databases = [] while (rs.next()): db = rs.getString(1) self.__databases.append(db) except: self.__connection = None type, value, traceback = sys.exc_info() logger.severe("create connection error:" + `value`)
def _jdbc_connect_jpype(jclassname, url, driver_args, jars, libs): import jpype if not jpype.isJVMStarted(): args = [] class_path = [] if jars: class_path.extend(jars) class_path.extend(_get_classpath()) if class_path: args.append('-Djava.class.path=%s' % os.path.pathsep.join(class_path)) if libs: # path to shared libraries libs_path = os.path.pathsep.join(libs) args.append('-Djava.library.path=%s' % libs_path) # jvm_path = ('/usr/lib/jvm/java-6-openjdk' # '/jre/lib/i386/client/libjvm.so') jvm_path = jpype.getDefaultJVMPath() global old_jpype if hasattr(jpype, '__version__'): try: ver_match = re.match('\d+\.\d+', jpype.__version__) if ver_match: jpype_ver = float(ver_match.group(0)) if jpype_ver < 0.7: old_jpype = True except ValueError: pass if old_jpype: jpype.startJVM(jvm_path, *args) else: jpype.startJVM(jvm_path, *args, ignoreUnrecognized=True, convertStrings=True) if not jpype.isThreadAttachedToJVM(): jpype.attachThreadToJVM() if _jdbc_name_to_const is None: types = jpype.java.sql.Types types_map = {} for i in types.__javaclass__.getClassFields(): if old_jpype: const = i.getStaticAttribute() else: const = i.__get__(i) types_map[i.getName()] = const _init_types(types_map) global _java_array_byte if _java_array_byte is None: def _java_array_byte(data): return jpype.JArray(jpype.JByte, 1)(data) # register driver for DriverManager jpype.JClass(jclassname) if isinstance(driver_args, dict): Properties = jpype.java.util.Properties info = Properties() for k, v in driver_args.items(): info.setProperty(k, v) dargs = [ info ] else: dargs = driver_args return jpype.java.sql.DriverManager.getConnection(url, *dargs)
def getApplicationHierarchy(self): appsProps = [] params = HashMap() params.put('OBJECT_TYPE', 'FUGR') params.put('REFRESH', 'X') # function = self.__client.getFunction('RS_COMPONENT_VIEW') # function.getImportParameterList().setValue("FUGR", "OBJECT_TYPE"); # function.getImportParameterList().setValue("X", "REFRESH"); fields = ArrayList() fields.add('ID') fields.add('TYPE') fields.add('NAME') fields.add('PARENT') fields.add('TEXT') appsRS = self.__client.executeFunction('RS_COMPONENT_VIEW', params, 'NODETAB', fields) while appsRS.next(): prop = Properties() prop.setProperty('id', appsRS.getString("ID")) prop.setProperty('type', appsRS.getString("TYPE")) prop.setProperty('data_name', appsRS.getString("NAME")) prop.setProperty('parent', appsRS.getString("PARENT")) prop.setProperty('description', appsRS.getString("TEXT")) appsProps.append(prop) return appsProps;
def __init__(self): self.originalOut = sys.stdout # Setup pig props = Properties() props.putAll(javasystem.getProperties()) for f in os.environ.get("DEFAULT_PIG_OPTS_FILES").split(","): PropertiesUtil.loadPropertiesFromFile(props, f) props.setProperty('log4jconf', os.environ.get('LOG4J_CONF')) pigOpts = os.environ.get('PIG_OPTS') if pigOpts: for opt in pigOpts.strip().split(' '): opt = opt.split('=') props.setProperty(opt[0], opt[1]) pigContext = PigContext(ExecType.LOCAL, props) params = ArrayList() paramFiles = ArrayList() pigContext.setParams(params) pigContext.setParamFiles(paramFiles) PigMain.configureLog4J(props, pigContext) pigInputStream = PigInputStream() reader = ConsoleReader(pigInputStream, OutputStreamWriter(javasystem.out)) inputStream = ConsoleReaderInputStream(reader) self.pigBufferedReader = PigBufferedReader(InputStreamReader(pigInputStream)) self.grunt = PigGrunt(self.pigBufferedReader, pigContext) self.grunt.setConsoleReader(reader) self.pigServer = self.grunt.pig
def getShellUtils(Framework, shellName, credentials, ip, codepage, warningsList, errorsList): failedPorts = [] #check which credential is good for the shell: client = None for credentialId in credentials: try: port = None props = Properties() props.setProperty(BaseAgent.ENCODING, codepage) props.setProperty(CollectorsConstants.ATTR_CREDENTIALS_ID, credentialId) logger.debug('try credential %s' % credentialId) client = Framework.createClient(props) shellUtils = shellutils.ShellUtils(client, None, shellName) if shellUtils: return (shellUtils, credentialId) except IOException, ioEx: strException = str(ioEx.getMessage()) errormessages.resolveAndAddToObjectsCollections( strException, shellName, warningsList, errorsList) if client: client.close() # we failed to connect - add the problematic port to failedPorts list if port: failedPorts.append(port) except (UnsupportedEncodingException, UnsupportedCharsetException), ex: strException = str(ex.getClass().getName()) shouldStop = errormessages.resolveAndAddToObjectsCollections( strException, shellName, warningsList, errorsList) if client: client.close() if shouldStop: return (None, None)
def __createConnection(self): "create database" self.__connection = None try: logger.info("RegisterJDBC driver: com.mysql.jdbc.Driver") driver = com.mysql.jdbc.Driver.newInstance() if driver and driver.acceptsURL(self.__rootJdbcUrl): props = Properties() props.setProperty("user", "root") props.setProperty("password", self.__rootPwd) logger.info("Create JDBC connection:" + self.__rootJdbcUrl) self.__connection = driver.connect(self.__rootJdbcUrl, props) if self.__connection: logger.info("Create db select prepared statement") self.__dbstmt = self.__connection.prepareStatement( "show databases;") rs = self.__dbstmt.executeQuery() self.__databases = [] while (rs.next()): db = rs.getString(1) self.__databases.append(db) except: self.__connection = None type, value, traceback = sys.exc_info() logger.severe("create connection error:" + ` value `)
def discoverServersByCredentials(self, suitableProtocols): ''' Try to discover application server using of one of the passed credentials @types: list(ProtocolObject) -> None ''' #if we connected to some port with any credential we would not try it again with another credential successedPorts = [] self.connected = 0 areThereAnyJars = 0 missingJarsError = None for suitableProtocol in suitableProtocols: protocol = suitableProtocol[0] portNum = suitableProtocol[1] username = self.getProtocolProperty( protocol, CollectorsConstants.PROTOCOL_ATTRIBUTE_USERNAME, '') port = portNum logger.debug('Passed port ', str(portNum)) if port == None: port = self.getProtocolProperty( protocol, CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT, None) logger.debug('Port fetched from credentials :', str(portNum)) #we don't check two credenials with same port if we succedded if (port in successedPorts): logger.debug('Port %s added to the successed list' % str(port)) continue self.initPrivate(protocol) versions = self.getAvalableVersions(self.Framework, self.ip_address, port) properties = Properties() properties.setProperty(AgentConstants.PORT_PROPERTY, port) self.setProperties(properties) credentials_id = protocol.getIdAsString() for currentVersion in versions: logger.debug('trying version: %s' % currentVersion) properties.setProperty(AgentConstants.VERSION_PROPERTY, self.generateVersion(currentVersion)) jmxAgent = None try: jmxAgent = self.Framework.createClient( credentials_id, properties) self.connected = 1 areThereAnyJars = 1 except AuthenticationException: areThereAnyJars = 1 self.addErrorMessage( 'Failed to connect with given user/password.Please check credentials' ) except MissingJarsException, e: if missingJarsError != None: missingJarsError = missingJarsError + '\n' + e.getMessage( ) else: missingJarsError = e.getMessage() except: areThereAnyJars = 1
def createClient(framework, ipAddress, namespace, credentialsId): ''' Framework, string, string, string -> CimClient @raise ValueError if any parameter is incorrect @raise ValueError if client fails to be created ''' properties = Properties() if ipAddress: properties.setProperty(cim.ClientProperty.IP_ADDRESS, ipAddress) else: raise ValueError("IP Address is None") if namespace: properties.setProperty(cim.ClientProperty.NAMESPACE, namespace) else: raise ValueError("Namespace is None") if credentialsId: properties.setProperty(cim.ClientProperty.CREDENTIALS_ID, credentialsId) properties.setProperty(SblimClientProperties.HTTP_POOL_SIZE, "0") #disable HTTP pool to support ESXes 4.1 properties.setProperty(SblimClientProperties.USE_MPOST, "false") try: client = framework.createClient(properties) return client except JException, jex: msg = jex.getMessage() logger.error("Failed to create client: %s" % msg) raise ValueError("Failed to create client")
def persistNewProfileName(domainConfigurationDirectory, profileName): from oracle.fabric.profiles.impl import ProfileConstants; fileName = domainConfigurationDirectory + File.separatorChar + 'server-profile-mbean-config.xml' profileProperties = Properties() profileProperties.loadFromXML(FileInputStream(fileName)) profileProperties.setProperty(ProfileConstants.CURRENT_SOA_PROFILE_PROPERTY_NAME, profileName) profileProperties.storeToXML(FileOutputStream(fileName), None)
def getShellUtils(Framework, shellName, credentials, ip, codepage, warningsList, errorsList): failedPorts = [] #check which credential is good for the shell: client = None for credentialId in credentials: try: port = None props = Properties() props.setProperty(BaseAgent.ENCODING, codepage) props.setProperty(CollectorsConstants.ATTR_CREDENTIALS_ID, credentialId) logger.debug('try credential %s' % credentialId) client = Framework.createClient(props) shellUtils = shellutils.ShellUtils(client, None, shellName) if shellUtils: return (shellUtils, credentialId) except IOException, ioEx: strException = str(ioEx.getMessage()) errormessages.resolveAndAddToObjectsCollections(strException, shellName, warningsList, errorsList) if client: client.close() # we failed to connect - add the problematic port to failedPorts list if port: failedPorts.append(port) except (UnsupportedEncodingException, UnsupportedCharsetException), ex: strException = str(ex.getClass().getName()) shouldStop = errormessages.resolveAndAddToObjectsCollections(strException, shellName, warningsList, errorsList) if client: client.close() if shouldStop: return (None, None)
def _string_to_properties(string, string_props_separator_char): """ Convert a delimited string into a java.util.Properties object :param string: the delimited string :param string_props_separator_char:, the delimiter used to separate properties :return: the java.util.Properties object :raises: DeployException: if the string is not formatted as expected (i.e., name=value pairs separated by the specified separator) """ _method_name = '_string_to_properties' _logger.entering(string, string_props_separator_char, class_name=_class_name, method_name=_method_name) result = Properties() if string is not None and len(string) > 0: elements = string.split(string_props_separator_char) for element in elements: stripped_element = element.strip() prop_key_value = stripped_element.split('=') if len(prop_key_value) == 2: key = prop_key_value[0].strip() value = prop_key_value[1].strip() result.setProperty(key, value) else: ex = exception_helper.create_deploy_exception('WLSDPLY-08018', string) _logger.throwing(ex, class_name=_class_name, method_name=_method_name) raise ex _logger.exiting(class_name=_class_name, method_name=_method_name, result=result) return result
def DiscoveryMain(Framework): protocolName = "NTCMD" OSHVResult = ObjectStateHolderVector() param = Framework.getParameter('discoverSoftware') if (param != None) and not Boolean.parseBoolean(param): logger.debug( 'No discovery for software by NTCMD, parameter discoverSoftware is false' ) return OSHVResult hostID = Framework.getDestinationAttribute('hostId') hostOSH = modeling.createOshByCmdbIdString('host', hostID) clientShUtils = None try: props = Properties() props.setProperty(AgentConstants.PROP_NTCMD_AGENT_COMMAND_TIMEOUT, '100000') client = Framework.createClient(props) if client is None: raise Exception, 'Failed to create NTCMD client' except Exception, ex: strException = ex.getMessage() errormessages.resolveAndReport(strException, protocolName, Framework)
def save_versions(self): print "save versions" versionsProperties = Properties() outFile = FileOutputStream(self.versionsFileName) versionsProperties.setProperty("script", self.app.SCRIPTVERSION) versionsProperties.setProperty("tools", self.app.TOOLSVERSION) versionsProperties.store(outFile, None) outFile.close()
def _buildConnectionProps(instNr, connClient=None): props = Properties() logger.debug('Connecting to a SAP instance number:', str(instNr)) props.setProperty(Protocol.SAP_PROTOCOL_ATTRIBUTE_SYSNUMBER, instNr) if connClient: logger.debug('Connecting to a SAP system with client: %s' % connClient) props.setProperty(Protocol.SAP_PROTOCOL_ATTRIBUTE_CLIENT, connClient) return props
def connect(self, framework): credentialsId = framework.getDestinationAttribute('credentialsId')#user selects the creds in the UI so we already know them connection_ip = framework.getDestinationAttribute('ip_address') self._credentialsId = credentialsId try: props = Properties() props.setProperty('ip_address', connection_ip) except Exception, e: pass
def DiscoveryMain(Framework): # General variables OSHVResult = ObjectStateHolderVector() properties = Properties() protocol = Framework.getDestinationAttribute('Protocol') processToPortDict = {} ## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]} databaseDict = {} ## {instanceName/SID:[dbType, listeningPort, ipAddress, installPath, version, status]} database_ip_service_endpoints ={} ## {instanceName:[ip_address:port]} client = None secondClient = None isWindows = 'true' # Attempt to create a client try: client = Framework.createClient() ## We have a client ## Get processes running on the box if(client): dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':DiscoveryMain] Got client <%s>' % client.getClientType()) if client.getClientType() == 'wmi': ## Open a second client connection to the DEFAULT namespace for registry access props = Properties() props.setProperty(AgentConstants.PROP_WMI_NAMESPACE, 'root\\DEFAULT') secondClient = Framework.createClient(props) processToPortDict = dbconnect_agentutils.getProcListByWMI(client, secondClient) # elif client.getClientType() == 'snmp': # processToPortDict = dbconnect_agentutils.getProcListBySNMP(client) else: Framework.reportWarning('Unable to connect using WMI') ## We have process and port infromation ## Find databases, if any if processToPortDict != None and len(processToPortDict) > 0: for pid in processToPortDict.keys(): logger.debug('dddd: ', '[' + SCRIPT_NAME + ':DiscoveryMain] Got process/service/software <%s> listening on port <%s:%s>' % ((processToPortDict[pid])[dbconnect_utils.PROCESSNAME_INDEX], (processToPortDict[pid])[dbconnect_utils.IP_INDEX], (processToPortDict[pid])[dbconnect_utils.PORT_INDEX])) if Framework.getParameter('discover_oracle').strip().lower() == 'true': dbconnect_oracle.findDatabases(client, processToPortDict, databaseDict, isWindows, secondClient) if Framework.getParameter('discover_mssql').strip().lower() == 'true': dbconnect_mssql.findDatabases(client, processToPortDict, databaseDict, database_ip_service_endpoints, isWindows, secondClient) if databaseDict != None and len(databaseDict) > 0: for dbName in databaseDict.keys(): dbconnect_utils.debugPrint('Found <%s> instance <%s> (%s) with listener port <%s:%s> and installed in <%s>' % ((databaseDict[dbName])[dbconnect_utils.DBTYPE_INDEX], dbName, (databaseDict[dbName])[dbconnect_utils.STATUS_INDEX], (databaseDict[dbName])[dbconnect_utils.IP_INDEX], (databaseDict[dbName])[dbconnect_utils.PORT_INDEX], (databaseDict[dbName])[dbconnect_utils.PATH_INDEX])) OSHVResult.addAll(dbconnect_utils.makeDbOSHs(databaseDict)) else: Framework.reportWarning('No databases found') else: ## If we're here, we couldn't find any processes, service, or software ## and we have no data to search for databases Framework.reportWarning('Unable to get a list or processes, services, or installed software') else: dbconnect_utils.debugPrint('Unable to connect using WMI') except Exception, ex: exInfo = ex.getMessage() errormessages.resolveAndReport(exInfo, protocol, Framework)
def mainFunction(Framework, OSHVResult, softNameToInstSoftOSH=None): ''' This function uses registry to provide information about installed software. ''' props = Properties() props.setProperty(AgentConstants.PROP_WMI_NAMESPACE, 'root\\DEFAULT') wmiClient = None try: try: wmiClient = Framework.createClient(props) hostOSH = createHostOSH(Framework, wmiClient) OSHVResult.add(hostOSH) registryColumns = {'DisplayName': {}, 'InstallLocation': {}, 'DisplayVersion': {}, 'Publisher': {}, 'ProductID': {}, 'InstallDate': {}} keyNames = registryColumns.keys() # These are the Registry sections, where the Software Uninstall information is stored keyPaths = ['SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'] for keyPath in keyPaths: try: result = getRegistrySubkeys(wmiClient, keyPath, keyNames) _mergeDictionaries(registryColumns, result) except JavaException, e: logger.info('Not a 64bit OS: ' + str(e)) # do the work _createSoftware(registryColumns['DisplayName'], registryColumns['InstallLocation'], registryColumns['DisplayVersion'], registryColumns['Publisher'], registryColumns['ProductID'], registryColumns['InstallDate'], hostOSH, OSHVResult, softNameToInstSoftOSH) try: props = Properties() props.setProperty(AgentConstants.PROP_WMI_NAMESPACE, 'root\\cimv2') client = Framework.createClient(props) wmiProvider = WmiAgentProvider(client) hostDiscoverer = WmiHostDiscoverer(wmiProvider) if hostDiscoverer.isWin2008(): logger.debug('win2008 detected') discoverWin2008HotFixes(wmiProvider, hostOSH, OSHVResult) elif hostDiscoverer.isWindows8_2012(): logger.debug('win 8 or win 2012 detected') discoverWin8_2012HotFixes(wmiProvider, hostOSH, OSHVResult) else: logger.debug('Non-win2008/8/2012 detected') finally: client.close() except JavaException, ex: exInfo = ex.getMessage() errormessages.resolveAndReport(exInfo, 'WMI', Framework)
def create_default_client(framework, cred_id, ip_address): client = None properties = Properties() properties.setProperty("ip_address", ip_address) try: client = framework.createClient(cred_id, properties) except(Exception, JavaException), e: msg = e.getMessage() if hasattr(e, 'getMessage') else str(e) raise ConnectionException(msg or 'Connection failed')
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() ip = Framework.getDestinationAttribute('ip_address') sid = Framework.getDestinationAttribute('sid') port = Framework.getDestinationAttribute('port') hostId = Framework.getDestinationAttribute('hostId') if (ip == None) or (ip == 'NA'): #checked and pass all IPs of given host ips = Framework.getTriggerCIDataAsList('host_ips') else: ips = [ip] for currIP in ips: if len(currIP) == 0: continue logger.debug('Checking sqlserver with no user on ipaddress:', currIP) protocols = Framework.getAvailableProtocols( currIP, ClientsConsts.SQL_PROTOCOL_NAME) for protocol in protocols: dbClient = None try: try: if dbutils.protocolMatch( Framework, protocol, 'microsoftsqlserver', sid, port) or dbutils.protocolMatch( Framework, protocol, 'microsoftsqlserverntlm', sid, port): props = Properties() props.setProperty('ip_address', currIP) dbClient = Framework.createClient(protocol, props) hostOSH = modeling.createOshByCmdbIdString( 'host', hostId) oracleOSH = modeling.createDatabaseOSH( 'sqlserver', sid, str(dbClient.getPort()), dbClient.getIpAddress(), hostOSH, protocol, None, dbClient.getTimeout(), dbClient.getDbVersion(), dbClient.getAppVersion()) logger.debug( 'Successfully connected to sqlserver object ', sid, ' on ', currIP) OSHVResult.add(oracleOSH) #since this is knownn oracle and we found credentials for it we can finish execution return OSHVResult except: if logger.isDebugEnabled(): logger.debugException( 'Unexpected CreateClient() for sqlserver client Exception:' ) finally: if dbClient != None: dbClient.close() Framework.reportWarning('Failed to connect using all protocols') return OSHVResult
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() ip = Framework.getDestinationAttribute("ip_address") sid = Framework.getDestinationAttribute("sid") port = Framework.getDestinationAttribute("port") hostId = Framework.getDestinationAttribute("hostId") if (ip == None) or (ip == "NA"): # checked and pass all IPs of given host ips = Framework.getTriggerCIDataAsList("host_ips") else: ips = [ip] for currIP in ips: if len(currIP) == 0: continue logger.debug("Checking sqlserver with no user on ipaddress:", currIP) protocols = Framework.getAvailableProtocols(currIP, ClientsConsts.SQL_PROTOCOL_NAME) for protocol in protocols: dbClient = None try: try: if dbutils.protocolMatch( Framework, protocol, "microsoftsqlserver", sid, port ) or dbutils.protocolMatch(Framework, protocol, "microsoftsqlserverntlm", sid, port): props = Properties() props.setProperty("ip_address", currIP) dbClient = Framework.createClient(protocol, props) hostOSH = modeling.createOshByCmdbIdString("host", hostId) oracleOSH = modeling.createDatabaseOSH( "sqlserver", sid, str(dbClient.getPort()), dbClient.getIpAddress(), hostOSH, protocol, None, dbClient.getTimeout(), dbClient.getDbVersion(), dbClient.getAppVersion(), ) logger.debug("Successfully connected to sqlserver object ", sid, " on ", currIP) OSHVResult.add(oracleOSH) # since this is knownn oracle and we found credentials for it we can finish execution return OSHVResult except: if logger.isDebugEnabled(): logger.debugException("Unexpected CreateClient() for sqlserver client Exception:") finally: if dbClient != None: dbClient.close() Framework.reportWarning("Failed to connect using all protocols") return OSHVResult
def _connectToIamService(framework, credentialsId): """Connection method for the **Identity and Access Management** @types: Framework, str -> IamClient """ from com.hp.ucmdb.discovery.library.clients.cloud.aws import ServiceType from com.hp.ucmdb.discovery.library.clients.cloud.aws import Client properties = Properties() properties.setProperty("credentialsId", credentialsId) properties.setProperty(Client.AWS_SERVICE_TYPE_PROPERTY, ServiceType.IAM.name()) # @UndefinedVariable return framework.createClient(properties).getService()
def connect(self, framework): credentialsId = framework.getDestinationAttribute( 'credentialsId' ) #user selects the creds in the UI so we already know them connection_ip = framework.getDestinationAttribute('ip_address') self._credentialsId = credentialsId try: props = Properties() props.setProperty('ip_address', connection_ip) except Exception, e: pass
def _connectToEc2Service(framework, credentialsId): """Connection method for the **Elastic Cloud Service** @types: Framework, str -> Ec2Client """ from com.hp.ucmdb.discovery.library.clients.cloud.aws import ServiceType from com.hp.ucmdb.discovery.library.clients.cloud.aws import Client properties = Properties() properties.setProperty(Client.AWS_SERVICE_TYPE_PROPERTY, ServiceType.EC2.name()) # @UndefinedVariable properties.setProperty("credentialsId", credentialsId) return framework.createClient(properties).getService()
def DiscoveryMain(Framework): properties = Properties() SITE_ID = Framework.getDestinationAttribute('SITE_ID') instance_number = Framework.getDestinationAttribute('instance_number') connection_client = Framework.getDestinationAttribute('connection_client') logger.debug('Connecting to a SAP instance number:', str(instance_number)) properties.setProperty(Protocol.SAP_PROTOCOL_ATTRIBUTE_SYSNUMBER, instance_number) if (connection_client is not None) and (connection_client != 'NA'): logger.debug('Connecting to a SAP system with client:', str(connection_client)) properties.setProperty(Protocol.SAP_PROTOCOL_ATTRIBUTE_CLIENT, connection_client) discoverScenarioProcesses = Boolean.parseBoolean(Framework.getParameter('discoverScenarioProcesses')) GET_PROCESS_STEPS = Boolean.parseBoolean(Framework.getParameter('getProcessSteps')) reportCIsInChunks = Boolean.parseBoolean(Framework.getParameter('reportCIsInChunks')) errormsg = '' client = None try: try: client = Framework.createClient(properties) solman = saputils.SapSolman(client) except (NoClassDefFoundError, MissingJarsException, ExceptionInInitializerError): errormsg = 'SAP drivers are missing' logger.debugException(errormsg) except: errormsg = 'Connection failed' logger.debugException(errormsg) else: try: sVector, sysToOshPairs = discoverSystems(solman) Framework.sendObjects(sVector) sVector.clear() sysNames = [system.getName() for system, _ in sysToOshPairs] sys_name_to_system = {} for system, _ in sysToOshPairs: sys_name_to_system[system.getName()] = system component2system = logicalComponents(sysNames, solman) businessProcesses(Framework, solman, component2system, sys_name_to_system, SITE_ID, GET_PROCESS_STEPS, reportCIsInChunks, discoverScenarioProcesses) except: strmsg = str(sys.exc_info()[1]) if (strmsg.upper().find('TABLE_NOT_AVAILABLE') > -1): errmsg = 'No solution manager found' logger.debugException(errmsg) Framework.reportError(errmsg) else: # unknown exception caught raise except JException, ex: ex_info = ex.getMessage() errormessages.resolveAndReport(ex_info, 'SAP JCO', Framework)
def discoverServersByCredentials(self, suitableProtocols): ''' Try to discover application server using of one of the passed credentials @types: list(ProtocolObject) -> None ''' #if we connected to some port with any credential we would not try it again with another credential successedPorts = [] self.connected = 0 areThereAnyJars = 0 missingJarsError = None for suitableProtocol in suitableProtocols: protocol = suitableProtocol[0] portNum = suitableProtocol[1] username = self.getProtocolProperty(protocol, CollectorsConstants.PROTOCOL_ATTRIBUTE_USERNAME, '') port = portNum logger.debug('Passed port ', str(portNum)) if port == None: port = self.getProtocolProperty(protocol, CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT, None) logger.debug('Port fetched from credentials :', str(portNum)) #we don't check two credenials with same port if we succedded if (port in successedPorts): logger.debug('Port %s added to the successed list' % str(port)) continue self.initPrivate(protocol) versions = self.getAvalableVersions(self.Framework, self.ip_address, port) properties = Properties() properties.setProperty(AgentConstants.PORT_PROPERTY, port) self.setProperties(properties) credentials_id = protocol.getIdAsString() for currentVersion in versions: logger.debug('trying version: %s' % currentVersion) properties.setProperty(AgentConstants.VERSION_PROPERTY, self.generateVersion(currentVersion)) jmxAgent = None try: jmxAgent = self.Framework.createClient(credentials_id, properties) self.connected = 1 areThereAnyJars = 1 except AuthenticationException: areThereAnyJars = 1 self.addErrorMessage('Failed to connect with given user/password.Please check credentials') except MissingJarsException, e: if missingJarsError != None: missingJarsError = missingJarsError + '\n' + e.getMessage() else: missingJarsError = e.getMessage() except: areThereAnyJars = 1
def createWmiClient(Framework, namespace=None): try: if namespace: props = Properties() props.setProperty(AgentConstants.PROP_WMI_NAMESPACE, namespace) return Framework.createClient(props) else: return Framework.createClient() except: errobj = errorobject.createError(errorcodes.CONNECTION_FAILED_NO_PROTOCOL, ["WMI"], 'Failed to connect') logger.reportErrorObject(errobj) logger.debugException('Failed to to connect')
def _create_client(create_client_fn, client_type, protocol, address, port): properties = Properties() properties.setProperty(BaseClient.CREDENTIALS_ID, protocol) properties.setProperty(Protocol.PROTOCOL_ATTRIBUTE_PORT, str(port)) properties.setProperty('host', address) properties.setProperty('protocol', 'https') properties.setProperty('autoAcceptCerts', 'true') client = create_client_fn(client_type, properties) try: yield client finally: client.close()
def _connectToEc2Service(framework, credentialsId): """Connection method for the **Elastic Cloud Service** @types: Framework, str -> Ec2Client """ from com.hp.ucmdb.discovery.library.clients.cloud.aws import ServiceType from com.hp.ucmdb.discovery.library.clients.cloud.aws import Client properties = Properties() properties.setProperty(Client.AWS_SERVICE_TYPE_PROPERTY, ServiceType.EC2.name()) #@UndefinedVariable properties.setProperty('credentialsId', credentialsId) return framework.createClient(properties).getService()
def _connectToIamService(framework, credentialsId): """Connection method for the **Identity and Access Management** @types: Framework, str -> IamClient """ from com.hp.ucmdb.discovery.library.clients.cloud.aws import ServiceType from com.hp.ucmdb.discovery.library.clients.cloud.aws import Client properties = Properties() properties.setProperty('credentialsId', credentialsId) properties.setProperty(Client.AWS_SERVICE_TYPE_PROPERTY, ServiceType.IAM.name()) #@UndefinedVariable return framework.createClient(properties).getService()
def mainFunction(Framework): warningsList = [] errorsList = [] _vector = ObjectStateHolderVector() ip_address = Framework.getDestinationAttribute('ip_address') macAddress = Framework.getDestinationAttribute('ip_mac_address') ip_domain = Framework.getDestinationAttribute('ip_domain') host_cmdbid = Framework.getDestinationAttribute('host_cmdbid') host_key = Framework.getDestinationAttribute('host_key') host_macs = Framework.getTriggerCIDataAsList('mac_addrs') ucmdb_version = modeling.CmdbClassModel().version() ip_address = __getIpObjectFromDestinationData(ip_address, macAddress) credentials = netutils.getAvailableProtocols(Framework, ClientsConsts.WMI_PROTOCOL_NAME, str(ip_address), ip_domain) if len(credentials) == 0: msg = errormessages.makeErrorMessage(protocolName, pattern=errormessages.ERROR_NO_CREDENTIALS) errobj = errorobject.createError(errorcodes.NO_CREDENTIALS_FOR_TRIGGERED_IP, [protocolName], msg) warningsList.append(errobj) logger.debug(msg) return (_vector, warningsList, errorsList) for credential in credentials: client = None try: debug_string = ip_domain + "\\" + str(ip_address) props = Properties() props.setProperty(CollectorsConstants.DESTINATION_DATA_IP_ADDRESS, str(ip_address)) logger.debug('try to get wmi agent for: ', debug_string) client = Framework.createClient(credential, props) logger.debug('got wmi agent for: ', debug_string) hostForLinkOSH = modeling.createHostOSH(str(ip_address)) # create wmi OSH wmiOSH = modeling.createWmiOSH(str(ip_address)) wmiOSH.setAttribute('credentials_id', client.getCredentialId()) wmiOSH.setContainer(hostForLinkOSH) _vector = doWMI(client, wmiOSH, ip_address, ip_domain, hostForLinkOSH, host_cmdbid, host_key, host_macs, ucmdb_version) if _vector.size() > 0: Framework.saveState(credential) del warningsList[:] del errorsList[:] break except Exception, ex: strException = str(ex.getMessage()) shouldStop = errormessages.resolveAndAddToObjectsCollections(strException, protocolName, warningsList, errorsList) if shouldStop: break except:
def testPropertiesDefault(self): prop_value = Properties() prop_value.setProperty('value1', 'foo') prop_value.setProperty('value2', 'bar') prop_value.setProperty('value3', 'equal') prop_default = Properties(prop_value) expected_value = {'value3': 'equal', 'value1': 'foo', 'value2': 'bar'} converted_type, converted_value = self._custom_helper.convert( prop_value, 'java.util.Properties') self.common_test_converted(expected_value, alias_constants.PROPERTIES, converted_value, converted_type) self.common_test_default(prop_default, 'java.util.Properties', converted_value, converted_type, True)
def createWmiClient(Framework, namespace=None): try: if namespace: props = Properties() props.setProperty(AgentConstants.PROP_WMI_NAMESPACE, namespace) return Framework.createClient(props) else: return Framework.createClient() except: errobj = errorobject.createError( errorcodes.CONNECTION_FAILED_NO_PROTOCOL, ["WMI"], 'Failed to connect') logger.reportErrorObject(errobj) logger.debugException('Failed to to connect')
def create_property_object(properties_string): """ create a java Properties instance from a string properties. :param properties_string: semi-colon separated string of key=value properties :return: java Properties instance """ result = JProperties() if properties_string is not None and len(properties_string) > 0: str_properties = properties_string.split(';') for str_property in str_properties: property_elements = str_property.split('=') result.setProperty(property_elements[0], property_elements[1]) return result
def _establish_connection(framework, config): properties = Properties() creds_id = config.credentialsId inst_nr = config.instance_number client_nr = config.connection_client properties.setProperty('credentialsId', creds_id) if inst_nr: properties.setProperty(Protocol.SAP_PROTOCOL_ATTRIBUTE_SYSNUMBER, inst_nr) if client_nr: properties.setProperty(Protocol.SAP_PROTOCOL_ATTRIBUTE_CLIENT, client_nr) try: return framework.createClient(properties) except (NoClassDefFoundError, MissingJarsException, ExceptionInInitializerError): errormsg = 'SAP JCo drivers are missing' logger.debugException(errormsg) raise flow.ConnectionException(errormsg) except JcoException, jco: errormsg = jco.getMessage() logger.debugException(errormsg) if config.ip_address and config.instance_number: cred_args = sap_flow.getCredentialId(framework) logger.debug('cred_args:', cred_args) if not cred_args: raise flow.ConnectionException(errormsg) for args in cred_args: logger.debug('args:', args) properties.setProperty('credentialsId', args[0]) try: return framework.createClient(properties) except: logger.debugException('') raise flow.ConnectionException(errormsg)
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)
def testPropertiesNotDefault(self): prop_value = Properties() prop_value.setProperty('value1', 'foo') prop_value.setProperty('value2', 'bar') prop_value.setProperty('value3', 'equal') expected_value = {'value1': 'foo', 'value2': 'bar', 'value3': 'equal'} prop_default = {'value2': 'foo', 'value1': 'bar', 'value3': 'equal'} converted_type, converted_value = self._custom_helper.convert( prop_value, 'java.util.Properties') self.common_test_converted(expected_value, alias_constants.PROPERTIES, converted_value, converted_type) self.assertEquals(PyOrderedDict, type(converted_value)) self.common_test_default(prop_default, 'dict', converted_value, converted_type, False)
def DiscoveryMain(Framework): properties = Properties() properties.setProperty('timeoutDiscover', Framework.getParameter('timeoutDiscover')) properties.setProperty('retryDiscover', Framework.getParameter('retryDiscover')) properties.setProperty('pingProtocol', Framework.getParameter('pingProtocol')) properties.setProperty('threadPoolSize', Framework.getParameter('threadPoolSize')) virtualMode = Framework.getParameter( 'virtualModeDiscover').lower() == "true" byRangeFlag = Framework.getParameter("byScopeDiscover").lower() == "true" netAddress = Framework.getDestinationAttribute("netAddress") netMask = Framework.getDestinationAttribute("netMask") probeName = Framework.getDestinationAttribute("probeName") ignoreClientType = getGlobalSetting().getPropertyStringValue( 'pingClientTypeIp', "False").lower() == "false" try: client = Framework.createClient(ClientsConsts.ICMP_PROTOCOL_NAME, properties) try: ipRange = getRangeByNetwork(netAddress, netMask) if byRangeFlag: rangesList = icmp_utils.getProbeRanges([ipRange], probeName, Framework) else: rangesList = [ipRange] logger.info('Start working on range: ', len(rangesList)) totalReportedIps = 0 for aRange in rangesList: totalReportedIps += icmp_utils.pingIPsInRange( Framework, client, aRange, virtualMode, netAddress, netMask, ignoreClientType=ignoreClientType) Framework.saveState(aRange.toRangeString()) logger.debug('Total reported IPs %s ' % totalReportedIps) logger.info('Finished working on all ranges..') Framework.clearState() if not totalReportedIps: logger.reportWarning( "No live DataCenter IPs found in probe ranges") finally: client.close() except: msg = logger.prepareJythonStackTrace('') errormessages.resolveAndReport(msg, ClientsConsts.ICMP_PROTOCOL_NAME, Framework) return ObjectStateHolderVector()
def DiscoveryMain(Framework): properties = Properties() vector = ObjectStateHolderVector() properties.setProperty('timeoutDiscover', Framework.getParameter('timeoutDiscover')) properties.setProperty('retryDiscover', Framework.getParameter('retryDiscover')) properties.setProperty('pingProtocol', Framework.getParameter('pingProtocol')) properties.setProperty('threadPoolSize', Framework.getParameter('threadPoolSize')) ip = Framework.getDestinationAttribute('ip_address') domainName = Framework.getDestinationAttribute('domain_name') id = Framework.getTriggerCIData('id') ports = getUDAAvailablePorts(Framework) try: client = Framework.createClient(ClientsConsts.ICMP_PROTOCOL_NAME, properties) try: range_uda_status = {} range_result = pingIPsInRange(Framework, client, ip, ports) range_uda_status.update(range_result) for x in range_uda_status.values(): logger.debug(x) #build the udaStatus context = UdaState.Builder(x.ip).computerName( x.computerName ).alive(x.alive).portAlive(x.portAlive).isDDMI( x.isDDMI).isNative(x.isNative).isWin(x.isWin).osType( x.osType).agentVersion( str(x.agentVersion) + ('-fips' if x.isFIPSEnabled else '')).UDUniqueId( x.UDUniqueId).build() #save UdaStatusService.getInstance().saveUdaStatus(context) if Framework.getParameter('isCreateUDA') == 'true': if x.UDUniqueId: hostOsh = modeling.createHostOSH(x.ip) hostOsh.setStringAttribute( InventoryUtils.ATTR_UD_UNIQUE_ID, x.UDUniqueId) uda = ObjectStateHolder('uda') uda.setStringAttribute('application_ip', x.ip) uda.setStringAttribute('application_ip_domain', domainName) uda.setStringAttribute('discovered_product_name', 'uda') uda.setStringAttribute('version', str(x.agentVersion)) uda.setContainer(hostOsh) vector.add(hostOsh) vector.add(uda) finally: client.close() except: msg = logger.prepareJythonStackTrace('') errormessages.resolveAndReport(msg, ClientsConsts.ICMP_PROTOCOL_NAME, Framework) return vector
def DiscoveryMain(Framework): vector = ObjectStateHolderVector() codePage = Framework.getCodePage() props = Properties() props.setProperty(BaseAgent.ENCODING, codePage) shell = None try: client = Framework.createClient(props) shell = shellutils.ShellFactory().createShell(client) dnsResolver = dns_resolver.NsLookupDnsResolver(shell) language = shell.osLanguage logger.debug("Using '%s' language bundle" % language.bundlePostfix) bundle = shellutils.getLanguageBundle('langMsCluster', language, Framework) clusterCmd = ms_cluster_discoverer.createClusterCmd(shell, bundle) if clusterCmd.isUsingCmd(): bundle = clusterCmd.detectLangBandle(Framework) clusterCmd.setBundle(bundle) vector.addAll(_discoverTopology(clusterCmd, bundle, dnsResolver)) except NoInstanceFound: errobj = errorobject.createError( errorcodes.MS_CLUSTER_INSTANCES_NOT_FOUND, None, 'MS cluster instances not found in discovery') logger.reportWarningObject(errobj) except: msg = str(sys.exc_info()[1]) logger.debugException(msg) if (msg.lower().find('timeout') > -1): errobj = errorobject.createError( errorcodes.CONNECTION_TIMEOUT_NO_PROTOCOL, None, 'Connection timed out - reactivate with larger timeout value') logger.reportErrorObject(errobj) logger.debugException('Connection timed out') else: errobj = errormessages.resolveError(msg, 'ntcmd') logger.reportErrorObject(errobj) logger.errorException(msg) try: shell and shell.closeClient() except: logger.debugException() logger.error("Unable to close shell") return vector
def getTransactions(self): transactions = [] whereClauses = ArrayList() whereClauses.add("OBJECT = 'TRAN'") result = self.executeQuery('TADIR', whereClauses, 'OBJECT,OBJ_NAME,DEVCLASS')#@@CMD_PERMISION sap protocol execution while result.next(): type = result.getString("OBJECT") if type == 'TRAN': transid = result.getString("OBJ_NAME"); devClass = result.getString("DEVCLASS"); prop = Properties() prop.setProperty('data_name',transid) prop.setProperty('devclass',devClass) transactions.append(prop) return transactions
def _snmpConnect(credentialId, ip, Framework): r'''@types: str, str, Framework -> Result @raise java.lang.Exception on connection failure ''' properties = Properties() properties.setProperty('credentialsId', credentialId) properties.setProperty('ip_address', ip) client = None try: client = Framework.createClient(properties) SnmpConnectionTester(client).testSnmpConnection() finally: client and client.close() return Result(True)
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() # which is needed when running a remote command involving special characters properties = Properties() protocol = Framework.getDestinationAttribute('Protocol') codePage = Framework.getDestinationAttribute('codepage') if (codePage != None) and (codePage != 'NA'): properties.setProperty( BaseAgent.ENCODING, codePage) properties.setProperty('QUOTE_CMD', 'true') try: client = Framework.createClient(properties) shellUtils = shellutils.ShellUtils(client) except Exception, ex: exInfo = ex.getMessage() errormessages.resolveAndReport(exInfo, protocol, Framework)
def createClientOfVersion(self, clientVersion): logger.debug("Connecting by URL '%s'" % self.urlString) logger.debug("Protocol version '%s'" % clientVersion) properties = Properties() properties.setProperty(BaseClient.CREDENTIALS_ID, self.credentialsId) properties.setProperty(ConnectionProperty.VERSION, clientVersion) properties.setProperty(ConnectionProperty.URL, self.urlString) if self.logLevel: properties.setProperty(ConnectionProperty.LOG_LEVEL, self.logLevel) return self.framework.createClient(properties)
def createJavaClient(framework, ipAddress, credentialsId): ''' Framework, string, string -> ClientWrapper @raise ValueError if any parameter is incorrect @raise ValueError if client fails to be created ''' properties = Properties() if ipAddress: properties.setProperty(JavaClientProperty.IP_ADDRESS, ipAddress) else: raise ValueError("IP Address is None") if credentialsId: properties.setProperty(JavaClientProperty.CREDENTIALS_ID, credentialsId) client = framework.createClient(properties) return ClientWrapper(client)