def DiscoveryMain(Framework):
	OSHVResult = ObjectStateHolderVector()	
	ipAddress = Framework.getDestinationAttribute('ip_address')
	credentialsId = Framework.getDestinationAttribute('credentialsId')
	hostId = Framework.getDestinationAttribute('hostId')
	
	hostOsh = ms_exchange_utils.restoreHostById(hostId)
	hostName = Framework.getDestinationAttribute('hostName')	
	if not hostName or hostName == 'N/A':
		hostName = ms_exchange_utils.getHostNameFromWmi(Framework)
	
	if not hostName:
		errobj = errorobject.createError(errorcodes.FAILED_GETTING_INFORMATION_NO_PROTOCOL, ['host name'], 'Failed to obtain host name')
		logger.reportErrorObject(errobj)
		return
	
	props = Properties()
	props.put(AgentConstants.PROP_WMI_NAMESPACE, WMI_NAMESPACE)	
	try:
		wmiClient = Framework.createClient(props)
		wmiAgent = WmiAgent(wmiClient, Framework)
		try:
			discoverExchangeServer(wmiAgent, ipAddress, credentialsId, OSHVResult, Framework, hostOsh, hostName)
		finally:			
			wmiClient.close()
	except Exception, ex:
		message = ex.getMessage()
		if (re.search("Invalid\sclass", message)):
			message = 'Unable to get Exchange data from WMI'
		logger.debugException(message)
		errormessages.resolveAndReport(message, WMI_PROTOCOL, Framework)
Ejemplo n.º 2
0
def createSQLServerConnection(serverName, port, schemaName, userName, password):
    try:
        url = (
            "jdbc:mercury:sqlserver://"
            + serverName
            + ":"
            + str(port)
            + ";DatabaseName="
            + schemaName
            + ";allowPortWithNamedInstance=true"
        )
        logger.info("URL: ", url)
        driverName = "com.mercury.jdbc.sqlserver.SQLServerDriver"
        props = Properties()
        props.put("user", userName)
        props.put("password", password)
        cl = Class.forName(driverName, 1, Thread.currentThread().getContextClassLoader())
        jdbcDriver = cl.newInstance()
        conn = jdbcDriver.connect(url, props)
        unlockConnection(conn)
        return conn
    except Exception, e:
        logger.error("setConnection: ")
        logger.error(e)
        raise Exception(e)
Ejemplo n.º 3
0
def DiscoveryMain(Framework):
    Framework = jee_connection.EnhancedFramework(Framework)
    isAppResourcesDiscoveryEnabled = _asBoolean(Framework.getParameter('discoverAppResources'))
    isJmsResourcesDiscoveryEnabled = _asBoolean(Framework.getParameter('discoverJMSResources'))

    platform = jee.Platform.JBOSS
    try:
        r'''In addition to the credentials we have to specify port number and
        version of the platform.
        Credentials may be defined without such information that is very important
        for establishing connections
        '''
        port = entity.WeakNumeric(int)
        port.set(Framework.getDestinationAttribute('port'))
        version = Framework.getDestinationAttribute('version')

        properties = Properties()
        properties.put(CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT, str(port.value()))
        properties.put(AgentConstants.VERSION_PROPERTY, version)

        client = Framework.createClient(properties)

        jmxProvider = jmx.Provider(client)
    except (Exception, JException), exc:
        logger.warnException("Failed to establish connection")
        jee_connection.reportError(Framework, str(exc), platform.getName())
Ejemplo n.º 4
0
def main():
  # Create the new layer
  newProjection = currentView().getProjectionCode()
  newLayerSchema = createSchema()
  newLayerSchema.append("ID","INTEGER")
  newLayerSchema.append("GEOMETRY","GEOMETRY")
  geometryType = getGeometryType(POINT,D2)
  newLayerSchema.get("GEOMETRY").setGeometryType(geometryType)
  newLayerName = "/APLICACIONES/GIS/gvSIG-desktop-2.2.0/mynewlayer.shp"
  newLayer = createShape(newLayerSchema,newLayerName,CRS=newProjection,geometryType=POINT)
  # Connect to the database
  props = Properties()
  props.put("user","YOUR_USER")
  props.put("password","YOUR_PASSWD")
  db = Driver().connect("jdbc:postgresql://localhost/YOUR_DB", props)
  # Get geometry info from database and insert it into the new layer
  c = db.createStatement()
  rs = c.executeQuery("select table.id, ST_X(table.coordinatesxy),ST_Y(table.coordenatesxy) from YOUR_TABLES where YOUR_WHERE_CLAUSE")
  data = {}
  while rs.next():
    id = rs.getInt(1)
    newX = rs.getObject(2)
    newY = rs.getObject(3)
    print(id,newX,newY)
    newGeom = createPoint(newX,newY)
    dbValues = {"ID":id,"GEOMETRY":newGeom}
    newLayer.append(dbValues)
  rs.close()
  c.close()
  db.close()
  
  currentView().addLayer(newLayer)
  newLayer.commit()
Ejemplo n.º 5
0
def _createSshClient(framework, cred_id, port=1000):
    try:
        from java.util import Properties
        props = Properties()
        props.put(Protocol.PROTOCOL_ATTRIBUTE_PORT, str(port))
        return framework.createClient(cred_id, props)
    except JException, je:
        raise ovm_flow.ConnectionException(je.getMessage())
Ejemplo n.º 6
0
 def _load_config(self):
     """ Returns the default jclouds client configuration. """
     endpoint = "http://" + self.__config.address + "/api"
     props = Properties()
     props.put("abiquo.endpoint", endpoint)
     [props.put(name, value)
             for (name, value) in self.__config.client_config]
     return props
Ejemplo n.º 7
0
def _createSshClient(framework, cred_id, port=1000):
    try:
        from java.util import Properties
        props = Properties()
        props.put(Protocol.PROTOCOL_ATTRIBUTE_PORT, str(port))
        return framework.createClient(cred_id, props)
    except JException, je:
        raise ovm_flow.ConnectionException(je.getMessage())
Ejemplo n.º 8
0
def getDBConnection(userName, password, driverName, connectionURL):
    """
    Return PyConnection to the database (see Jython's zxJDBC description)
    @param userName: the username to connect to DB with
    @param password: the password to connect to DB with
    @param driverName: name of the driver to connect through
    @return: com.ziclix.python.sql.PyConnection
    """
    jdbcDriver = Class.forName(driverName, 1,
               Thread.currentThread().getContextClassLoader()).newInstance()
    props = Properties()
    props.put('user', userName)
    props.put('password', password)
    return PyConnection(jdbcDriver.connect(connectionURL, props))
Ejemplo n.º 9
0
def properties(props_dict):
    """
    make a java.util.Properties from a python dict
    """
    p = Properties()
    for k in props_dict.iterkeys():
        v = props_dict[k]
        if isinstance(v,bool):
            if v:
                v = 'true'
            else:
                v = 'false'
        p.put(k,v)
    return p
Ejemplo n.º 10
0
def getDBConnection(userName, password, driverName, connectionURL):
    """
    Return PyConnection to the database (see Jython's zxJDBC description)
    @param userName: the username to connect to DB with
    @param password: the password to connect to DB with
    @param driverName: name of the driver to connect through
    @return: com.ziclix.python.sql.PyConnection
    """
    jdbcDriver = Class.forName(
        driverName, 1,
        Thread.currentThread().getContextClassLoader()).newInstance()
    props = Properties()
    props.put('user', userName)
    props.put('password', password)
    return PyConnection(jdbcDriver.connect(connectionURL, props))
Ejemplo n.º 11
0
 def load_context(self):
     """ Creates and configures the context. """
     if not self.__context:  # Avoid loading the same context twice
         endpoint = "http://" + self.__config.address + "/api"
         config = Properties()
         config.put("abiquo.endpoint", endpoint)
         config.put("jclouds.max-retries", "0")  # Do not retry on 5xx errors
         config.put("jclouds.max-redirects", "0")  # Do not follow redirects on 3xx responses
         # Wait at most 2 minutes in Machine discovery
         config.put("jclouds.timeouts.InfrastructureClient.discoverSingleMachine", "120000")
         config.put("jclouds.timeouts.InfrastructureClient.discoverMultipleMachines", "120000")
         print "Connecting to: %s" % endpoint
         self.__context = AbiquoContextFactory().createContext(self.__config.user, self.__config.password, config)
         atexit.register(self.__del__)  # Close context automatically when exiting
     return self.__context
Ejemplo n.º 12
0
def DiscoveryMain(Framework):
    Framework = jee_connection.EnhancedFramework(Framework)
    '''
    create client
    make discovery of domain and servers
    '''
    platform = jee.Platform.WEBSPHERE
    properties = Properties()
    properties.put('server_was_config', 'services:connectors:SOAP_CONNECTOR_ADDRESS:host,services:connectors:SOAP_CONNECTOR_ADDRESS:port,clusterName')
    properties.put('datasource_was_config', 'jndiName,URL,propertySet,connectionPool')
    try:
        client = Framework.createClient(properties)
    except (Exception, JException), exc:
        logger.warnException("Failed to establish connection")
        jee_connection.reportError(Framework, str(exc), platform.getName())
Ejemplo n.º 13
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    logger.debug(" ###### Connecting to EView 400 client")
    codePage = Framework.getCodePage()
    properties = Properties()
    properties.put(BaseAgent.ENCODING, codePage)

    localshell = None
    try:
        client = Framework.createClient(ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME)
        localshell = shellutils.ShellUtils(client, properties, ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME)
    except Exception, ex:
        exInfo = ex.getMessage()
        errormessages.resolveAndReport(exInfo, ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME, Framework)
        logger.error(exInfo)
Ejemplo n.º 14
0
def createOracleConnection(serverName, port, sid, userName, password):
    try:
        url = 'jdbc:mercury:oracle://' + serverName + ':' + str(port) + ';databaseName=' + sid
        driverName = 'com.mercury.jdbc.oracle.OracleDriver'
        props = Properties()
        props.put('user', userName)
        props.put('password', password)
        cl = Class.forName(driverName, 1, Thread.currentThread().getContextClassLoader())
        jdbcDriver = cl.newInstance()
        conn = jdbcDriver.connect(url, props)
        unlockConnection(conn)
        return conn
    except Exception, e:
        logger.error('setConnection: ')
        logger.error(e)
        raise Exception(e)
Ejemplo n.º 15
0
def createOracleConnection(serverName, port, sid, userName, password):
    try:
        url = "jdbc:mercury:oracle://" + serverName + ":" + str(port) + ";databaseName=" + sid
        driverName = "com.mercury.jdbc.oracle.OracleDriver"
        props = Properties()
        props.put("user", userName)
        props.put("password", password)
        cl = Class.forName(driverName, 1, Thread.currentThread().getContextClassLoader())
        jdbcDriver = cl.newInstance()
        conn = jdbcDriver.connect(url, props)
        unlockConnection(conn)
        return conn
    except Exception, e:
        logger.error("setConnection: ")
        logger.error(e)
        raise Exception(e)
Ejemplo n.º 16
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    logger.debug(" ###### Connecting to EView client")
    logger.info (os.getenv('COMPUTERNAME'))
    codePage = Framework.getCodePage()
    properties = Properties()
    properties.put(BaseAgent.ENCODING, codePage)

    localshell = None
    try:
        client = Framework.createClient(ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME)
        localshell = shellutils.ShellUtils(client, properties, ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME)
    except Exception, ex:
        exInfo = ex.getMessage()
        errormessages.resolveAndReport(exInfo, ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME, Framework)
        logger.error(exInfo)
Ejemplo n.º 17
0
 def _load_config(self):
     """ Returns the default jclouds client configuration """
     props = Properties()
     [
         props.put(name, value)
         for (name, value) in self.__config.client_config
     ]
     return props
Ejemplo n.º 18
0
def createSQLServerConnection(serverName, port, schemaName, userName, password):
    try:
        url = 'jdbc:mercury:sqlserver://' + serverName + ':' + str(port)+';DatabaseName='+schemaName+';allowPortWithNamedInstance=true'
        logger.info('URL: ',url)
        driverName = 'com.mercury.jdbc.sqlserver.SQLServerDriver'
        props = Properties()
        props.put('user', userName)
        props.put('password', password)
        cl = Class.forName(driverName, 1, Thread.currentThread().getContextClassLoader())
        jdbcDriver = cl.newInstance()
        conn = jdbcDriver.connect(url, props)
        unlockConnection(conn)
        return conn
    except Exception, e:
        logger.error('setConnection: ')
        logger.error(e)
        raise Exception(e)
Ejemplo n.º 19
0
def _createClient(framework, protocol):
    '''
    @types: Framework, str -> Client
    @raise flow.ConnectionException
    '''

    codePage = framework.getCodePage()
    properties = Properties()
    properties.put(BaseAgent.ENCODING, codePage)

    LOCAL_SHELL = ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME
    try:
        client = (_isLocalShellRequired(protocol)
                  and framework.createClient(LOCAL_SHELL)
                  or framework.createClient(properties))
        return client
    except JException, je:
        raise flow.ConnectionException(je.getMessage())
Ejemplo n.º 20
0
def DiscoveryMain(Framework):
    Framework = jee_connection.EnhancedFramework(Framework)
    """
    create client
    make discovery of domain and servers
    """
    platform = jee.Platform.WEBSPHERE
    properties = Properties()
    properties.put(
        "server_was_config",
        "services:connectors:SOAP_CONNECTOR_ADDRESS:host,services:connectors:SOAP_CONNECTOR_ADDRESS:port,clusterName",
    )
    properties.put("datasource_was_config", "jndiName,URL,propertySet,connectionPool")
    try:
        client = Framework.createClient(properties)
    except (Exception, JException), exc:
        logger.warnException("Failed to establish connection")
        jee_connection.reportError(Framework, str(exc), platform.getName())
Ejemplo n.º 21
0
def _createClient(framework, protocol):
    '''
    @types: Framework, str -> Client
    @raise flow.ConnectionException
    '''

    codePage = framework.getCodePage()
    properties = Properties()
    properties.put(BaseAgent.ENCODING, codePage)

    LOCAL_SHELL = ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME
    try:
        client = (_isLocalShellRequired(protocol)
                  and framework.createClient(LOCAL_SHELL)
                  or framework.createClient(properties))
        return client
    except JException, je:
        raise flow.ConnectionException(je.getMessage())
Ejemplo n.º 22
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    exchangeServerId = Framework.getDestinationAttribute('id')
    fqdn = Framework.getDestinationAttribute('fqdn')
    hostName = getHostName(Framework)

    exchangeServerOsh = ms_exchange_utils.restoreExchangeServerOSH(
        exchangeServerId)

    props = Properties()
    props.put(AgentConstants.PROP_WMI_NAMESPACE, WMI_NAMESPACE)
    try:
        wmiClient = Framework.createClient(props)
        wmiAgent = WmiAgent(wmiClient, Framework)
        try:
            exchangeDiscoverer = ExchangeDiscoverer(wmiAgent,
                                                    exchangeServerOsh,
                                                    Framework, OSHVResult,
                                                    hostName)
            try:
                exchangeDiscoverer.doExchangeSystem(fqdn)
                exchangeDiscoverer.doFolderTrees()
            except:
                errorMsg = 'Failed to discover folder trees and public folders'
                logger.warnException(errorMsg)
                errobj = errorobject.createError(
                    errorcodes.FAILED_DISCOVERING_RESOURCE,
                    ['folder trees and public folders'], errorMsg)
                logger.reportWarningObject(errobj)

            if not exchangeDiscoverer.objectsDiscovered:
                errobj = errorobject.createError(
                    errorcodes.MS_EXCHANGE_OBJECTS_NOT_FOUND, None,
                    'Microsoft Exchange objects not found in discovery')
                logger.reportErrorObject(errobj)
        finally:
            wmiClient.close()
    except:
        exInfo = logger.prepareJythonStackTrace('')
        errormessages.resolveAndReport(exInfo, WMI_PROTOCOL, Framework)

    return OSHVResult
Ejemplo n.º 23
0
    def go(self):
        props = Properties()
        props.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.appserv.naming.S1ASCtxFactory")
        props.put(Context.PROVIDER_URL,"iiop://127.0.0.1:3700")

        context = InitialContext(props)
        tfactory = context.lookup("jms/MyConnectionFactory")

        tconnection = tfactory.createTopicConnection('receiver', 'receiver')
        tconnection.setClientID('myClientId:recv')
        tsession = tconnection.createTopicSession(False, Session.AUTO_ACKNOWLEDGE)

        subscriber = tsession.createDurableSubscriber(context.lookup("jms/MyFirstTopic"), 'mysub')

        subscriber.setMessageListener(self)

        tconnection.start()

        while True:
            time.sleep(1)
Ejemplo n.º 24
0
def DiscoveryMain(Framework):
    Framework = jee_connection.EnhancedFramework(Framework)
    port = entity.WeakNumeric(int)
    port.set(Framework.getDestinationAttribute('port'))
    version = Framework.getDestinationAttribute('version')

    resultVector = ObjectStateHolderVector()
    isAppResourcesDiscoveryEnabled = Boolean.valueOf(
        Framework.getParameter('discoverAppResources'))
    isJMSResourcesDiscoveryEnabled = Boolean.valueOf(
        Framework.getParameter('discoverJMSResources'))
    discoverDeployedOnlyApplications = Boolean.valueOf(
        Framework.getParameter("discoverDeployedOnlyApplications"))
    protocolType = (Framework.getDestinationAttribute('protocol')
                    or ClientsConsts.HTTP_PROTOCOL_NAME)

    properties = Properties()
    properties.put(CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT,
                   str(port.value()))
    properties.put(AgentConstants.VERSION_PROPERTY, version)
    properties.put(AgentConstants.PROP_WEBLOGIC_PROTOCOL, protocolType)

    platform = jee.Platform.WEBLOGIC

    try:
        client = Framework.createClient(properties)
    except (Exception, JException), exc:
        logger.warnException("Failed to establish connection")
        jee_connection.reportError(Framework, str(exc), platform.getName())
Ejemplo n.º 25
0
def DiscoveryMain(Framework):
    protocolName = Framework.getDestinationAttribute('Protocol')
    OSHVResult = ObjectStateHolderVector()
    try:
        HOST_IP = Framework.getDestinationAttribute('ip_address')
        MANAGER_PORT = Framework.getParameter('port')

        shellUtils = None
        try:
            codePage = Framework.getCodePage()
            properties = Properties()
            properties.put( BaseAgent.ENCODING, codePage)
            shellUtils = shellutils.ShellUtils(Framework, properties)
            discoveredOracleHomes = []
            if shellUtils.isWinOs():
                discoveredOracleHomes = OracleIASOracleHomeWindowsDiscoverer(shellUtils).discover()
            else:
                discoveredOracleHomes = OracleIASOracleHomeDiscoverer(shellUtils).discover()

            logger.debug('Discovered Oracle Homes from the running processes: %s' % discoveredOracleHomes)

            
            for oracleHomePath in discoveredOracleHomes:
                pathExists = 0
                if oracleHomePath and oracleHomePath.strip():
                    try:
                        opmnXML = shellUtils.safecat(str(oracleHomePath) + '/opmn/conf/opmn.xml')
                        parseOpmnXml(opmnXML, HOST_IP, oracleHomePath, MANAGER_PORT, shellUtils, OSHVResult, Framework)
                        pathExists = 1
                    except:
                        logger.debugException('')
                    if not pathExists:
                        Framework.reportWarning("Can't retrieve opmn.xml content.")
            if OSHVResult.size() == 0:
                Framework.reportError("Failed to discover Oracle AS")
        finally:
            shellUtils and shellUtils.closeClient()
    except JavaException, ex:
        logger.debugException('')
        errormessages.resolveAndReport(ex.getMessage(), protocolName, Framework)
Ejemplo n.º 26
0
def DiscoveryMain(Framework):
    Framework = jee_connection.EnhancedFramework(Framework)
    port = entity.WeakNumeric(int)
    port.set(Framework.getDestinationAttribute('port'))
    version = Framework.getDestinationAttribute('version')

    resultVector = ObjectStateHolderVector()
    isAppResourcesDiscoveryEnabled = Boolean.valueOf(Framework.getParameter('discoverAppResources'))
    isJMSResourcesDiscoveryEnabled = Boolean.valueOf(Framework.getParameter('discoverJMSResources'))
    discoverDeployedOnlyApplications = Boolean.valueOf(Framework.getParameter("discoverDeployedOnlyApplications"))
    protocolType = (Framework.getDestinationAttribute('protocol') or
                    ClientsConsts.HTTP_PROTOCOL_NAME)

    properties = Properties()
    properties.put(CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT, str(port.value()))
    properties.put(AgentConstants.VERSION_PROPERTY, version)
    properties.put(AgentConstants.PROP_WEBLOGIC_PROTOCOL, protocolType)

    platform = jee.Platform.WEBLOGIC

    try:
        client = Framework.createClient(properties)
    except (Exception, JException), exc:
        logger.warnException("Failed to establish connection")
        jee_connection.reportError(Framework, str(exc), platform.getName())
Ejemplo n.º 27
0
def main():
    # Create the new layer
    newProjection = currentView().getProjectionCode()
    newLayerSchema = createSchema()
    newLayerSchema.append("ID", "INTEGER")
    newLayerSchema.append("GEOMETRY", "GEOMETRY")
    geometryType = getGeometryType(POINT, D2)
    newLayerSchema.get("GEOMETRY").setGeometryType(geometryType)
    newLayerName = "/APLICACIONES/GIS/gvSIG-desktop-2.2.0/mynewlayer.shp"
    newLayer = createShape(newLayerSchema,
                           newLayerName,
                           CRS=newProjection,
                           geometryType=POINT)
    # Connect to the database
    props = Properties()
    props.put("user", "YOUR_USER")
    props.put("password", "YOUR_PASSWD")
    db = Driver().connect("jdbc:postgresql://localhost/YOUR_DB", props)
    # Get geometry info from database and insert it into the new layer
    c = db.createStatement()
    rs = c.executeQuery(
        "select table.id, ST_X(table.coordinatesxy),ST_Y(table.coordenatesxy) from YOUR_TABLES where YOUR_WHERE_CLAUSE"
    )
    data = {}
    while rs.next():
        id = rs.getInt(1)
        newX = rs.getObject(2)
        newY = rs.getObject(3)
        print(id, newX, newY)
        newGeom = createPoint(newX, newY)
        dbValues = {"ID": id, "GEOMETRY": newGeom}
        newLayer.append(dbValues)
    rs.close()
    c.close()
    db.close()

    currentView().addLayer(newLayer)
    newLayer.commit()
    def go(self):
        props = Properties()
        props.put(Context.INITIAL_CONTEXT_FACTORY,
                  "com.sun.appserv.naming.S1ASCtxFactory")
        props.put(Context.PROVIDER_URL, "iiop://127.0.0.1:3700")

        context = InitialContext(props)
        tfactory = context.lookup("jms/MyConnectionFactory")

        tconnection = tfactory.createTopicConnection('receiver', 'receiver')
        tconnection.setClientID('myClientId:recv')
        tsession = tconnection.createTopicSession(False,
                                                  Session.AUTO_ACKNOWLEDGE)

        subscriber = tsession.createDurableSubscriber(
            context.lookup("jms/MyFirstTopic"), 'mysub')

        subscriber.setMessageListener(self)

        tconnection.start()

        while True:
            time.sleep(1)
Ejemplo n.º 29
0
def _toHTML(jjdata,lform,listform,vis):
    styleborder = "border: 1px solid black;border-collapse: collapse"
    builder = XMLBuilder.create("table").a("style",styleborder)
#    builder = XMLBuilder.create("table")
    padding = "padding: 5px"
    
    # header
    builder = builder.e("tr")
    for l in listform : 
        if l[FID] in vis : builder = builder.e("th").a("style",styleborder+";" +padding).t(l[FCOLUMNNAME]).up()

    builder = builder.up()
    # content
    for d in jjdata :
        builder = builder.e("tr")
        for j in listform :
            id = j[FID]
            (ttype,tafter) = miscutil.getColumnDescr(lform,id)
#            print id,d[id],d,type(d[id])
            if not id in vis : continue
            if ttype == cutil.DECIMAL : val = con.fToSDisp(d[id],tafter)
            elif ttype == cutil.BOOL : val = con.toS(d[id])
            else: val = con.toS(d[id])
            if val == None : val = ""
            
            align = "left"
            if ttype == cutil.DATE : align = "center"
            elif ttype == cutil.DECIMAL or ttype == cutil.LONG : align = "right"
            
            builder = builder.e("td").a("style",styleborder + ";" + padding + ";text-align: " + align).t(val).up()
        builder = builder.up()
    
    builder = builder.up()
    outputProperties = Properties()
    outputProperties.put(INDENT, "yes")
    return builder.root().asString(outputProperties)              
Ejemplo n.º 30
0
def _toHTML(jjdata,lform,listform,vis):
    styleborder = "border: 1px solid black;border-collapse: collapse"
    builder = XMLBuilder.create("table").a("style",styleborder)
#    builder = XMLBuilder.create("table")
    padding = "padding: 5px"
    
    # header
    builder = builder.e("tr")
    for l in listform : 
        if l[FID] in vis : builder = builder.e("th").a("style",styleborder+";" +padding).t(l[FCOLUMNNAME]).up()

    builder = builder.up()
    # content
    for d in jjdata :
        builder = builder.e("tr")
        for j in listform :
            id = j[FID]
            (ttype,tafter) = miscutil.getColumnDescr(lform,id)
#            print id,d[id],d,type(d[id])
            if not id in vis : continue
            if ttype == cutil.DECIMAL : val = con.fToSDisp(d[id],tafter)
            elif ttype == cutil.BOOL : val = con.toS(d[id])
            else: val = con.toS(d[id])
            if val == None : val = ""
            
            align = "left"
            if ttype == cutil.DATE : align = "center"
            elif ttype == cutil.DECIMAL or ttype == cutil.INT : align = "right"
            
            builder = builder.e("td").a("style",styleborder + ";" + padding + ";text-align: " + align).t(val).up()
        builder = builder.up()
    
    builder = builder.up()
    outputProperties = Properties()
    outputProperties.put(INDENT, "yes")
    return builder.root().asString(outputProperties)              
Ejemplo n.º 31
0
    def handle(self):
        try:
            size = int(self._readline())
            data = self._readbytes(size)
            params = pickle.loads(data)

            props = Properties()
            props.put('user', 'postgres')
            props.put('password', 'postgres')
            
            conn = Driver().connect('jdbc:postgresql:grafiexpress', props)
            h = HashMap()
            for k, v in params["params"].items():

                h.put(k,v)
                
            #h.put(JRParameter.REPORT_LOCALE, java.util.Locale(""))
            print params
            print params["report"]
            print h
            print conn
            report = JasperFillManager.fillReport(params["report"], h, conn)
            output = java.io.ByteArrayOutputStream()
            JasperExportManager.exportReportToPdfStream(report, output)
            output.close()
            data = output.toByteArray()

        except:
            print '\nexcept \n'
            self.request.send("0\n")
            print traceback.print_exc()
        else:
            print '\nelse \n'
            self.request.send(str(len(data))+"\n")
            self.request.send(data)
            print '\nelse \n'
Ejemplo n.º 32
0
def createClient(framework, ip, matchers=SiebelAgent.SIEBEL_DEFAULT_GATEWAY_MATCHERS, credentialsId=None, port=None):	
	properties = Properties()
	properties.put(AgentConstants.PROP_AGENT_OUTPUT_MATCHERS, matchers)
	properties.put(PROPERTY_IP_ADDRESS, ip)
	if port:
		properties.put(SiebelClient.PROPERTY_GATEWAY_PORT, port)
	if credentialsId:
		return framework.createClient(credentialsId, properties)
	else:
		return framework.createClient(properties)
Ejemplo n.º 33
0
def createClient(framework,
                 ip,
                 matchers=SiebelAgent.SIEBEL_DEFAULT_GATEWAY_MATCHERS,
                 credentialsId=None,
                 port=None):
    properties = Properties()
    properties.put(AgentConstants.PROP_AGENT_OUTPUT_MATCHERS, matchers)
    properties.put(PROPERTY_IP_ADDRESS, ip)
    if port:
        properties.put(SiebelClient.PROPERTY_GATEWAY_PORT, port)
    if credentialsId:
        return framework.createClient(credentialsId, properties)
    else:
        return framework.createClient(properties)
Ejemplo n.º 34
0
def DiscoveryMain(Framework):

    OSHVResult = ObjectStateHolderVector()

    protocol = 'SQL'

    try:
        schemaName = Framework.getParameter(PARAM_SCHEMA_NAME)
        tableName = Framework.getParameter(PARAM_TABLE_NAME)
        sqlQuery = Framework.getParameter(PARAM_SQL_QUERY)
        bulkSize = Framework.getParameter(import_utils.PARAM_BULK_SIZE)
        flushObjects = Framework.getParameter(import_utils.PARAM_FLUSH_OBJECTS)

        #Set connection related properties from triggered CI
        props = Properties()

        dbPort = Framework.getDestinationAttribute('database_port')
        if dbPort and dbPort != NA:
            props.put(Protocol.PROTOCOL_ATTRIBUTE_PORT, dbPort)

        db_instance_name = Framework.getDestinationAttribute('instance_name')
        if db_instance_name and db_instance_name != NA:
            props.put(Protocol.SQL_PROTOCOL_ATTRIBUTE_DBSID,
                      db_instance_name[db_instance_name.find('\\') + 1:])
        props.put(Protocol.SQL_PROTOCOL_ATTRIBUTE_DBNAME, schemaName)
        client = Framework.createClient(props)
        dbType = client.getProtocolDbType()

        queryFactory = DbQueryFactory(schemaName, tableName, dbType, sqlQuery)

        dataSource = DBDataSource(client, schemaName, queryFactory)

        if flushObjects and (flushObjects.lower() == "true"):
            import_utils.importFlushingCis(dataSource, OSHVResult, Framework,
                                           bulkSize)
        else:
            import_utils.importCis(dataSource, OSHVResult, Framework)

    except Exception, ex:
        exInfo = ex.getMessage()
        errormessages.resolveAndReport(exInfo, protocol, Framework)
Ejemplo n.º 35
0
def DiscoveryMain(Framework):

    OSHVResult = ObjectStateHolderVector()
    
    protocol = 'SQL'
    
    try:
        schemaName = Framework.getParameter(PARAM_SCHEMA_NAME)
        tableName = Framework.getParameter(PARAM_TABLE_NAME)
        sqlQuery = Framework.getParameter(PARAM_SQL_QUERY)
        bulkSize = Framework.getParameter(import_utils.PARAM_BULK_SIZE)
        flushObjects = Framework.getParameter(import_utils.PARAM_FLUSH_OBJECTS)
        
        #Set connection related properties from triggered CI
        props = Properties()
        
        dbPort = Framework.getDestinationAttribute('database_port')
        if dbPort and dbPort != NA:
            props.put(Protocol.PROTOCOL_ATTRIBUTE_PORT, dbPort)
        
        db_instance_name = Framework.getDestinationAttribute('instance_name')
        if db_instance_name and db_instance_name != NA:
            props.put(Protocol.SQL_PROTOCOL_ATTRIBUTE_DBSID, db_instance_name[db_instance_name.find('\\')+1:])
        props.put(Protocol.SQL_PROTOCOL_ATTRIBUTE_DBNAME, schemaName)
        client = Framework.createClient(props)
        dbType = client.getProtocolDbType()
        
        queryFactory = DbQueryFactory(schemaName, tableName, dbType, sqlQuery)

        dataSource = DBDataSource(client, schemaName, queryFactory)

        if flushObjects and (flushObjects.lower() == "true"):
            import_utils.importFlushingCis(dataSource, OSHVResult, Framework, bulkSize)
        else:
            import_utils.importCis(dataSource, OSHVResult, Framework)

    except Exception, ex:
        exInfo = ex.getMessage()
        errormessages.resolveAndReport(exInfo, protocol, Framework)
Ejemplo n.º 36
0
def execSshRemoteUsrPwd(hostname,
                        username,
                        password,
                        commandsSemiColonSeperated,
                        sessionTimeoutSecs=0,
                        waitForOutput=True):
    _hostname = hostname
    _username = username
    _password = password
    _command = commandsSemiColonSeperated

    jsch = JSch()

    session = jsch.getSession(_username, _hostname, 22)
    session.setPassword(_password)
    config = Properties()
    config.put("StrictHostKeyChecking", "no")
    config.put("GSSAPIAuthentication", "no")
    config.put("UnknownHostVerification", "no")
    #config.put("PreferredAuthentications", "publickey");
    session.setConfig(config)

    if (sessionTimeoutSecs > 0): session.setTimeout(sessionTimeoutSecs * 10)

    print 'Logging into Remote SSH Shell u/p Auth...'

    try:
        if (sessionTimeoutSecs > 0):
            session.connect(sessionTimeoutSecs * 1000)
        else:
            session.connect()
    except:
        return 'None'

    channel = session.openChannel("exec")
    channel.setCommand('source ~/.bash_profile 2>/dev/null; ' + _command)

    outputBuffer = String()

    stdin = channel.getInputStream()
    stdinExt = channel.getExtInputStream()

    channel.connect(sessionTimeoutSecs * 1000)

    if (waitForOutput == True):
        while (1):
            n = stdin.read()
            if n == -1:
                break
            if (chr(n) == '\n'):
                outputBuffer.append('|')
            elif (chr(n) == '\r'):
                outputBuffer.append('|')
            else:
                outputBuffer.append(chr(n))

        while (1):
            n = stdinExt.read()
            if n == -1:
                break
            if (chr(n) == '\n'):
                outputBuffer.append('|')
            elif (chr(n) == '\r'):
                outputBuffer.append('|')
            else:
                outputBuffer.append(chr(n))

    else:
        sleep(sessionTimeoutSecs)

    print "Command on: " + hostname + " : " + _command
    print "\toutput: " + outputBuffer.toString()

    channel.disconnect()
    session.disconnect()

    del channel
    del session

    return outputBuffer.toString()
Ejemplo n.º 37
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    
    protocol = Framework.getDestinationAttribute('Protocol')
    
    DEFAULT_MAIN_FC_PATH = ''
    #this default value would be used as last resort in case the file main.cf will not be found
    if protocol == 'ntcmd':
        DEFAULT_MAIN_FC_PATH = 'c:\\program Files\\VERITAS\\cluster server\\conf\config\\'
    else:
        DEFAULT_MAIN_FC_PATH = '/etc/VRTSvcs/conf/config/'

    # take the following parameter from the section 'destinationData name' ${PARAMETERS.<paramname>) defined in the pattern's xml file
    main_cf_path = Framework.getParameter('main_cf_path')

    properties = Properties()

    # Set codepage
    codePage = Framework.getCodePage()
    properties.put( BaseAgent.ENCODING, codePage)

    try:
        # Connect to the SSH/TELNET/NTCMD agent
        client = Framework.createClient(properties)
        clientShUtils = shellutils.ShellUtils(client)
    except:
        msg = sys.exc_info()[1]
        strmsg = '%s' % msg
        if (strmsg.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(strmsg, 'shell')
            logger.reportErrorObject(errobj)
            logger.errorException(strmsg)
    else:
        # Get main.cf path
        if ((main_cf_path == None) or (main_cf_path == 'NA')) and (protocol != 'ntcmd'):
            main_cf_path = getMainCFPath(clientShUtils)
            if (main_cf_path == None) or (main_cf_path == 'NA'):
                main_cf_path = DEFAULT_MAIN_FC_PATH
        if ((main_cf_path == None) or (main_cf_path == 'NA')) and (protocol == 'ntcmd'):
            main_cf_path = DEFAULT_MAIN_FC_PATH
        
        # Assemble the main.cf command
        cfFullPath = main_cf_path + 'main.cf'
        try:
            resBuffer = clientShUtils.safecat(cfFullPath)
        except:
            errorMessage = 'Failed to get configuration file:' + cfFullPath
            logger.debugException(errorMessage)
            errobj = errorobject.createError(errorcodes.FAILED_FINDING_CONFIGURATION_FILE, [cfFullPath], errorMessage)
            logger.reportErrorObject(errobj)
        else:        
            if resBuffer.find('Permission denied') > -1:
                errobj = errorobject.createError(errorcodes.PERMISSION_DENIED_NO_PROTOCOL_WITH_DETAILS, ['User has no permissions to read main.cf file'], 'User has no permissions to read main.cf file')
                logger.reportErrorObject(errobj)
            else:
                lastUpdateTime = file_ver_lib.getFileLastModificationTime(clientShUtils, cfFullPath)
                mainFunction(resBuffer, main_cf_path, clientShUtils, OSHVResult, protocol, Framework, lastUpdateTime)

        try:
            clientShUtils and clientShUtils.closeClient()
        except:
            logger.debugException('')
            logger.error('Unable to close shell')
    return OSHVResult
Ejemplo n.º 38
0
noindexFile = Path(collectionDir, 'noindex')
parsedDir = Path(collectionDir, 'parsed')
indexesDir = Path(collectionDir, 'indexes')
dedup = Path(collectionDir, 'dedup')
# More paths, for the graph-related info
parsedCaptures = Path(collectionDir, 'graph/parsed-captures')
linkGraph = Path(collectionDir, 'graph/link-graph')
inlinkCountsPage = Path(collectionDir, 'graph/inlink-counts-page')
inlinkCountsDomain = Path(collectionDir, 'graph/inlink-counts-domain')
parsedCaptureInlinkCounts = Path(collectionDir,
                                 'graph/parsed-capture-inlink-counts')
parsedCaptureBoost = Path(collectionDir, 'graph/parsed-capture-boost')

# Properties used for all jobs
props = Properties()
props.put('mapred.fairscheduler.pool', 'default')

# **************************************************
# Move any (w)arc files from 'incoming/' to 'arcs/'.
incoming = fs.globStatus(Path(incomingDir, '*.gz'))

print 'LOG: Incoming %d' % len(incoming)
if len(incoming) > 0:
    if not fs.exists(warcsDir):
        # print 'DEBUG: Bootstrap warcs dir: %s' % warcsDir
        fs.mkdirs(warcsDir)

    for newfile in incoming:
        # It's not unusual for (w)arc files to be put into the incoming directory
        # a second, third, etc. time.  The "ingest pipeline" can have various troubles
        # and the general approach is to re-run the file through the pipeline until
Ejemplo n.º 39
0
try:
    import com.ibm.db2.jcc.DB2Driver as Driver
except:
    print "\n\tNo jdbc driver available, start wsadmin with\n"
    print "\t\"-javaoption -Dcom.ibm.ws.scripting.classpath=path/db2jcc4.jar\"\n"
    print "\tSee http://scripting101.org/resources/installing-the-scripts/ for details\n"

# Get configuration from properties file
configParser = ConfigParser.ConfigParser()
configFilePath = r'ibmcnx/ibmcnx.properties'
configParser.read(configFilePath)

# Change User and Password
props = Properties()
props.put('user', configParser.get('Database', 'dbUser'))
props.put('password', configParser.get('Database', 'dbPassword'))

jdbcPath = 'jdbc:db2://' + configParser.get(
    'Database', 'dbHost') + ':' + configParser.get(
        'Database', 'dbPort') + '/' + configParser.get('Database', 'dbName')

conn = Driver().connect(jdbcPath, props)

stmt = conn.createStatement()

email = raw_input("\n\tMail address of profile you want to check: ").lower()

sql = 'select PROF_UID_LOWER,PROF_MAIL_LOWER,PROF_GUID,PROF_MAIL from empinst.employee where PROF_MAIL_LOWER = \'' + \
    email + '\' order by PROF_UID_LOWER'
rs = stmt.executeQuery(sql)
Ejemplo n.º 40
0
 def __init__(self):
     self.name = 'PoolConTest'
     self.log = Logger.getLogger(self.name)
     ds = DataSourceRegistry.getDataSource('localSource')
     if not ds:
         props = Properties()
         props.put("url", "jdbc:mysql://localhost/dataservice")
         props.put("username", "root")
         props.put("driverClassName", "com.mysql.jdbc.Driver")
         props.put("password", "ben")
         props.put("initialSize", "1")
         props.put("minIdle", "5")
         props.put("maxActive", "10")
         try:
             DataSourceRegistry.registerDataSource('localSource', props)
         finally:
             ds = DataSourceRegistry.getDataSource('localSource')
     self.ds = ds
     self.log.info(self.name + ': init...')
Ejemplo n.º 41
0
from javax.naming import InitialContext 
from javax.jms import *
from java.util import Properties

numberOfMessage = 10
messageText = "hello"

properties = Properties()
properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory")
properties.put("java.naming.provider.url","jnp://localhost:1099")
properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces")

context = InitialContext(properties)
factory =context.lookup("ConnectionFactory")
destination = context.lookup("queue/DemoJMSProviderGW")

connection =  factory.createConnection()
session = connection.createSession(False, Session.AUTO_ACKNOWLEDGE)
producer = session.createProducer(destination)

for i in range(numberOfMessage):
  producer.send(session.createTextMessage(messageText+' ' + `i`))



Ejemplo n.º 42
0
# coding=UTF-8
from java.util import Properties
import os

CELESTA_PROPERTIES = Properties()
CELESTA_PROPERTIES.put(
    'score.path', os.path.abspath(os.path.join(os.path.dirname(__file__),
                                               "..")))
CELESTA_PROPERTIES.put(
    'pylib.path', '/'
)  # Данная настройка необходима только в контексте запуска java приложения
CELESTA_PROPERTIES.put("h2.in-memory", "true")

# Список модулей для импорта модулем celestaunit.py
INITIALIZING_GRAINS = []
Ejemplo n.º 43
0
from com.ziclix.python.sql import zxJDBC
import os
import sys
from java.util import Properties

#add jar to your class path, then import it
sys.path.append('/root/Desktop/mysql-connector-java-5.1.42.jar')
import com.mysql.jdbc.Driver as Driver
props = Properties()
props.put('user','root')
props.put('password','redhat')
mysqlConn = zxJDBC.connect(Driver().connect('jdbc:mysql://localhost/construction',props))
cursor = mysqlConn.cursor()

#function to check user details
def chkUser(name):
    ls =[]
    sql = "SELECT * FROM users where uname = '"+name+"'"
    try:
        cursor.execute(sql)
        results = cursor.fetchall()
        i = 1
        for row in results:
            ls.append(str(i)+".")
            ls.append("name")
            ls.append(str(row[0]))
            ls.append("username")
            ls.append(str(row[1]))
            ls.append("userType")
            ls.append(str(row[3]))
            i+=1
Ejemplo n.º 44
0
warcsDir    = Path( collectionDir, 'warcs'      )
noindexFile = Path( collectionDir, 'noindex'    )
parsedDir   = Path( collectionDir, 'parsed'     )
indexesDir  = Path( collectionDir, 'indexes'    )
dedup       = Path( collectionDir, 'dedup'      )
# More paths, for the graph-related info
parsedCaptures            = Path( collectionDir, 'graph/parsed-captures'      )
linkGraph                 = Path( collectionDir, 'graph/link-graph'           )
inlinkCountsPage          = Path( collectionDir, 'graph/inlink-counts-page'   )
inlinkCountsDomain        = Path( collectionDir, 'graph/inlink-counts-domain' )
parsedCaptureInlinkCounts = Path( collectionDir, 'graph/parsed-capture-inlink-counts' )
parsedCaptureBoost        = Path( collectionDir, 'graph/parsed-capture-boost'         )

# Properties used for all jobs
props = Properties()
props.put('mapred.fairscheduler.pool', 'default')

# **************************************************
# Move any (w)arc files from 'incoming/' to 'arcs/'.
incoming = fs.globStatus( Path( incomingDir, '*.gz' ) )

print 'LOG: Incoming %d' % len(incoming)
if len(incoming) > 0:
    if not fs.exists( warcsDir ):
        # print 'DEBUG: Bootstrap warcs dir: %s' % warcsDir
        fs.mkdirs( warcsDir )

    for newfile in incoming:
        # It's not unusual for (w)arc files to be put into the incoming directory
        # a second, third, etc. time.  The "ingest pipeline" can have various troubles
        # and the general approach is to re-run the file through the pipeline until
Ejemplo n.º 45
0
from jarray import array
import sys
from java.lang import *
from java.util import Properties
from org.omg.CORBA import *
from org.omg.CosNotifyChannelAdmin import *
from org.omg.CosNotifyComm import *
from org.omg.CosNotification import *
from thread import *

log = grinder.logger.output

# setup ORB
args = array([], String)
props = Properties()
props.put("org.omg.CORBA.ORBClass", "org.jacorb.orb.ORB")
props.put("org.omg.CORBA.ORBSingletonClass", "org.jacorb.orb.ORBSingleton")
orb = ORB.init(args, props)
poa = orb.resolve_initial_references("RootPOA")
poa.the_POAManager().activate();

# start ORB Thread
def run_orb():
	orb.run()

start_new_thread(run_orb, ())

# resolve NotificationService
obj = orb.resolve_initial_references("NotificationService")
ecf = EventChannelFactoryHelper.narrow( obj )
channel = ecf.get_event_channel(0)
Ejemplo n.º 46
0
 def getS(self):
     outputProperties = Properties()
     outputProperties.put(INDENT, "yes")
     return self.__builder.root().asString(outputProperties)              
Ejemplo n.º 47
0
    def go(self):
        # parse the arguments to determine which framework is desired
        #parseArguments(args)
        """   The driver is installed by loading its class.
        In an embedded environment, this will start up Derby, since it is not already running.

        """
        ds = None
        conn = None
        props = Properties()
        props.put("user", self.username)
        props.put("password", self.password)
        print props

        # check for J2ME specification - J2ME must use a DataSource further on */
        javaspec = props.getProperty("java.specification.name")
        """
           The connection specifies create=true in the url to cause
           the database to be created. To remove the database,
           remove the directory derbyDB and its contents.
           The directory derbyDB will be created under
           the directory that the system property
           derby.system.home points to, or the current
           directory if derby.system.home is not set.

         """
        Class.forName(self.driver).newInstance()
        print "Loaded the appropriate driver."

        database = "derbyDB5"  # put here the name for your database
        dbStr = self.protocol + database + ";create=true"
        print dbStr
        conn = DriverManager.getConnection(dbStr, props)
        print "Connected to and created database derbyDB"

        conn.setAutoCommit(False)
        """    Creating a statement lets us issue commands against
        the connection.

        """
        s = conn.createStatement()

        #   We create a table, add a few rows, and update one.
        s.execute("create table derbyDB(num int, addr varchar(40))")
        print "Created table derbyDB"
        s.execute("insert into derbyDB values (1956,'Webster St.')")
        print "Inserted 1956 Webster"
        s.execute("insert into derbyDB values (1910,'Union St.')")
        print "Inserted 1910 Union"
        s.execute("insert into derbyDB values (1,'Wandering Oak')")
        print "Inserted 1 Wandering Oak"

        s.execute(
            "update derbyDB set num=180, addr='Grand Ave.' where num=1956")
        print "Updated 1956 Webster to 180 Grand"

        s.execute(
            "update derbyDB set num=300, addr='Lakeshore Ave.' where num=180")
        print "Updated 180 Grand to 300 Lakeshore"

        #  We select the rows and verify the results.
        rs = s.executeQuery("SELECT num, addr FROM derbyDB ORDER BY num")

        print "Verified the rows"
        stmt = conn.createStatement()
        Query = 'SELECT * FROM derbyDB'
        rs = stmt.executeQuery(Query)
        rsmd = RSMD(rs)
        printRSMD(rsmd, Query)

        rowCount = 0
        while (rs.next()):
            rowCount += 1
            row = (rs.getInt(1), rs.getString(2))
            print row

        stmt.close()  # close stmt connection
        s.execute("drop table derbyDB")
        print "Dropped table derbyDB"

        # We release the result and statement resources.
        rs.close()
        s.close()
        print "Closed result set and statements"

        #  We end the transaction and the connection.
        conn.commit()
        conn.close()
        print "Committed transaction and closed connection"
        """   In embedded mode, an application should shut down Derby.
           If the application fails to shut down Derby explicitly,
           the Derby does not perform a checkpoint when the JVM shuts down, which means
           that the next connection will be slower.
           Explicitly shutting down Derby with the URL is preferred.
           This style of shutdown will always throw an "exception".

        """
        gotSQLExc = False
        try:
            DriverManager.getConnection("jdbc:derby:;shutdown=true")
        except SQLException:
            print "Catching exceptions"
            gotSQLExc = True

        if (not gotSQLExc):
            print "Database did not shut down normally"
        else:
            print "Database shut down normally"
        print("SimpleApp finished")
Ejemplo n.º 48
0
# Load all jython commands, when they are not loaded
try:
    NewsActivityStreamService.listApplicationRegistrations()
except NameError:
    print "Connections Commands not loaded! Load now: "
    execfile("loadAll.py")

# add the jar to your classpath, then import it
# better to read WebSphere variable PROFILES_JDBC_DRIVER_HOME

import com.ibm.db2.jcc.DB2Driver as Driver

# Change User and Password
props = Properties()
props.put( 'user', 'lcuser' )
props.put( 'password', 'password' )

# Change Hostname, Port and maybe DB Name
conn = Driver().connect( 'jdbc:db2://cnxdb2.stoeps.local:50000/PEOPLEDB', props )

stmt = conn.createStatement()

email = raw_input( "Mail address of profile you want to check: " ).lower()

sql = 'select PROF_UID_LOWER,PROF_MAIL_LOWER,PROF_GUID,PROF_MAIL from empinst.employee where PROF_MAIL_LOWER = \'' + email + '\' order by PROF_UID_LOWER'
rs = stmt.executeQuery( sql )

employeeList = []
while ( rs.next() ):
    row = {}
Ejemplo n.º 49
0
# Hot Rod server test runner

import abstractServer
from org.infinispan.client.hotrod import RemoteCacheManager
from java.util import Properties

p = Properties()
#p.put("infinispan.client.hotrod.server_list", "192.168.1.65:11222;192.168.1.66:11222")
p.put("infinispan.client.hotrod.server_list", "192.168.1.65:11222")

remoteCacheManager = RemoteCacheManager(p)

class TestRunner(abstractServer.TestRunner):

   def doInit(self):
      self.remoteCache = remoteCacheManager.getCache()

   def doPut(self, key, value):
      self.remoteCache.put(key, value)

   def doGet(self, key):
      return self.remoteCache.get(key)

   def stop(self):
      self.remoteCache.stop()

Ejemplo n.º 50
0
from com.ziclix.python.sql import zxJDBC
import os
import sys
from java.util import Properties
sys.path.append('/root/Desktop/mysql-connector-java-5.1.42.jar')
import com.mysql.jdbc.Driver as Driver
props = Properties()
props.put('user', 'root')
props.put('password', 'avinash')
mysqlCon = zxJDBC.connect(Driver().connect('jdbc:mysql://localhost/inst_mang',
                                           props))


def getCon():
    return mysqlCon


cursor = mysqlCon.cursor()


def getCursor():
    return cursor
Ejemplo n.º 51
0
 def getS(self):
     outputProperties = Properties()
     outputProperties.put(INDENT, "yes")
     return self.__builder.root().asString(outputProperties)              
Ejemplo n.º 52
0
# Hot Rod server test runner

import abstractServer
from org.infinispan.client.hotrod import RemoteCacheManager
from java.util import Properties

p = Properties()
p.put("hotrod-servers", "127.0.0.1:11311")
p.put("maxActive", -1)
p.put("maxIdle", -1)

remoteCacheManager = RemoteCacheManager(p)

class TestRunner(abstractServer.TestRunner):

   def doInit(self):
      self.remoteCache = remoteCacheManager.getCache()

   def doPut(self, key, value):
      self.remoteCache.put(key, value)

   def doGet(self, key):
      return self.remoteCache.get(key)

   def stop(self):
      self.remoteCache.stop()

Ejemplo n.º 53
0
from jarray import array
import sys
from java.lang import *
from java.util import Properties
from org.omg.CORBA import *
from org.omg.CosNotifyChannelAdmin import *
from org.omg.CosNotifyComm import *
from org.omg.CosNotification import *
from thread import *

log = grinder.logger.output

# setup ORB
args = array([], String)
props = Properties()
props.put("org.omg.CORBA.ORBClass", "org.jacorb.orb.ORB")
props.put("org.omg.CORBA.ORBSingletonClass", "org.jacorb.orb.ORBSingleton")
orb = ORB.init(args, props)
poa = orb.resolve_initial_references("RootPOA")
poa.the_POAManager().activate()


# start ORB Thread
def run_orb():
    orb.run()


start_new_thread(run_orb, ())

# resolve NotificationService
obj = orb.resolve_initial_references("NotificationService")
Ejemplo n.º 54
0
import ConfigParser

# Only load commands if not initialized directly (call from menu)
if __name__ == "__main__":
    execfile("ibmcnx/loadCnxApps.py")

import com.ibm.db2.jcc.DB2Driver as Driver

# Get configuration from properties file
configParser = ConfigParser.ConfigParser()
configFilePath = r'ibmcnx/ibmcnx.properties'
configParser.read(configFilePath)

# Change User and Password
props = Properties()
props.put( 'user', configParser.get('Database','dbUser') )
props.put( 'password', configParser.get('Database','dbPassword') )

jdbcPath = 'jdbc:db2://' + configParser.get('Database','dbHost') + ':' + configParser.get('Database','dbPort') + '/' + configParser.get('Database','dbName')

conn = Driver().connect( jdbcPath, props )

stmt = conn.createStatement()

email = raw_input( "Mail address of profile you want to deactivate: " ).lower()

sql = 'select PROF_UID,PROF_MAIL,PROF_MAIL_LOWER,PROF_GUID from empinst.employee where PROF_MAIL_LOWER = \'' + email + '\' order by PROF_UID_LOWER'
rs = stmt.executeQuery( sql )

employeeList = []
while ( rs.next() ):
Ejemplo n.º 55
0
 def _load_config(self):
     """ Returns the default jclouds client configuration """
     props = Properties()
     [props.put(name, value)
             for (name, value) in self.__config.client_config]
     return props