コード例 #1
0
    def SaveSettings(self, e):
        
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = head + "\\GUI_Settings.db3"
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'UPDATE settings SET Setting_Value = "' + self.API_Key_TF.getText() + '" WHERE Setting_Name = "API_Key";'
            resultSet = stmt.executeQuery(SQL_Statement)
        except:
            pass
        try:
            if self.local_settings.getPrivate():
                SQL_Statement = 'UPDATE settings SET Setting_Value = "1" WHERE Setting_Name = "Private";' 
                resultSet = stmt.executeQuery(SQL_Statement)
            else:
                SQL_Statement = 'UPDATE settings SET Setting_Value = "0" WHERE Setting_Name = "Private";'  
                resultSet = stmt.executeQuery(SQL_Statement)
        except:
            pass

        self.Error_Message.setText("Settings Saved")
        stmt.close()
        dbConn.close()
コード例 #2
0
def _jdbc_connect_jython(jclassname, jars, libs, props, *args):
    if _jdbc_name_to_const is None:
        from java.sql import Types
        types = Types
        types_map = {}
        const_re = re.compile('[A-Z][A-Z_]*$')
        for i in dir(types):
            if const_re.match(i):
                types_map[i] = getattr(types, i)
        _init_types(types_map)
    global _java_array_byte
    if _java_array_byte is None:
        import jarray

        def _java_array_byte(data):
            return jarray.array(data, 'b')

    # register driver for DriverManager
    jpackage = jclassname[:jclassname.rfind('.')]
    dclassname = jclassname[jclassname.rfind('.') + 1:]
    # print jpackage
    # print dclassname
    # print jpackage
    from java.lang import Class
    from java.lang import ClassNotFoundException
    try:
        Class.forName(jclassname).newInstance()
    except ClassNotFoundException:
        if not jars:
            raise
        _jython_set_classpath(jars)
        Class.forName(jclassname).newInstance()
    from java.sql import DriverManager
    return DriverManager.getConnection(*args)
コード例 #3
0
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = 'Select Setting_Name, Setting_Value from settings;' 
           resultSet = stmt.executeQuery(SQL_Statement)
           while resultSet.next():
               if resultSet.getString("Setting_Name") == "Program_Exec_Name":
                   self.Program_Executable_TF.setText(resultSet.getString("Setting_Value"))
                   self.local_settings.setSetting('ExecFile', resultSet.getString("Setting_Value"))
                   self.local_settings.setSetting('Exec_Prog_Flag', 'true')
                   self.Exec_Program_CB.setSelected(True)
                   self.Program_Executable_TF.setEnabled(True)
                   self.Find_Program_Exec_BTN.setEnabled(True)
           self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()
コード例 #4
0
ファイル: pool.py プロジェクト: VanyaDNDZ/doj-sybase
    def __init__(self, connectURI, username, password, pool_name):
        self.connectionPool = GenericObjectPool(None)
        self._pool_name = pool_name

        source = BasicDataSource()
        source.setUrl(connectURI)
        source.setUsername(username)
        source.setPassword(password)
        source.setInitialSize(1) # Number of connections to start with
        source.setMinIdle(5)     # Allow a bottom of 5 idle connections
        source.setMaxActive(10)  # Max of 10 database connection
        source.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED)
        source.setMinEvictableIdleTimeMillis(500) 

        self.connectionFactory = DataSourceConnectionFactory(source)

        #  Now we'll create the PoolableConnectionFactory, which wraps
        #  the "real" Connections created by the ConnectionFactory with
        #  the classes that implement the pooling functionality.
        self.poolableConnectionFactory = PoolableConnectionFactory(self.connectionFactory,
                self.connectionPool,
                None,
                None,
                False,
                True)

        #  Finally, we create the PoolingDriver itself...
        Class.forName("org.apache.commons.dbcp.PoolingDriver")
        driver = DriverManager.getDriver("jdbc:apache:commons:dbcp:")

        #  ...and register our pool with it.
        driver.registerPool(self._pool_name, self.connectionPool)
コード例 #5
0
ファイル: dbapi2.py プロジェクト: LetschM/iis
def _jdbc_connect_jython(jclassname, jars, libs, *args):
    if _converters is None:
        from java.sql import Types
        types = Types
        types_map = {}
        const_re = re.compile('[A-Z][A-Z_]*$')
        for i in dir(types):
            if const_re.match(i):
                types_map[i] = getattr(types, i)
        _init_converters(types_map)
    global _java_array_byte
    if _java_array_byte is None:
        import jarray
        def _java_array_byte(data):
            return jarray.array(data, 'b')
    # register driver for DriverManager
    jpackage = jclassname[:jclassname.rfind('.')]
    dclassname = jclassname[jclassname.rfind('.') + 1:]
    # print jpackage
    # print dclassname
    # print jpackage
    from java.lang import Class
    from java.lang import ClassNotFoundException
    try:
        Class.forName(jclassname).newInstance()
    except ClassNotFoundException:
        if not jars:
            raise
        _jython_set_classpath(jars)
        Class.forName(jclassname).newInstance()
    from java.sql import DriverManager
    return DriverManager.getConnection(*args)
コード例 #6
0
ファイル: database.py プロジェクト: mmisono/osv-jython-flask
def connect_db(jdbc_url, driverName):
    try:
        Class.forName(driverName).newInstance()
        dbConn = DriverManager.getConnection(jdbc_url)
    except Exception, msg:
        print msg
        sys.exit(1)
コード例 #7
0
    def get_profiles(self):
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
            self.Error_Message.setText("Database opened")
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = "select profile_name from profiles where volatility_version = '" + self.Version_CB.getSelectedItem() + "';" 
           resultSet = stmt.executeQuery(SQL_Statement)
           profile_list = []
           while resultSet.next():
              profile_list.append(resultSet.getString("profile_name"))

           stmt.close()
           dbConn.close()
           return profile_list
        except SQLException as e:
            self.Error_Message.setText("Error Reading plugins")
            stmt.close()
            dbConn.close()
            return "Error"
コード例 #8
0
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\GUI_Settings.db3"
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'Select Setting_Name, Setting_Value from settings;'
            resultSet = stmt.executeQuery(SQL_Statement)
            while resultSet.next():
                if resultSet.getString(
                        "Setting_Name") == "Volatility_Executable_Directory":
                    self.Program_Executable_TF.setText(
                        resultSet.getString("Setting_Value"))
                    self.local_settings.setVolatility_Directory(
                        resultSet.getString("Setting_Value"))
                    self.local_settings.setVolatility_Dir_Found(True)
                if resultSet.getString("Setting_Name") == "Volatility_Version":
                    self.Version_CB.setSelectedItem(
                        resultSet.getString("Setting_Value"))
            self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()
コード例 #9
0
def getConnection(jdbc_url, driverName):
	print "Using database at", jdbc_url, "driver", driverName
	try:
		Class.forName(driverName).newInstance()
	except Exception, msg:
		print msg
		sys.exit(-1)
コード例 #10
0
    def get_profiles(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\GUI_Settings.db3"
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
            self.Error_Message.setText("Database opened")
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = "select profile_name from profiles where volatility_version = '" + self.Version_CB.getSelectedItem(
            ) + "';"
            resultSet = stmt.executeQuery(SQL_Statement)
            profile_list = []
            while resultSet.next():
                profile_list.append(resultSet.getString("profile_name"))

            stmt.close()
            dbConn.close()
            return profile_list
        except SQLException as e:
            self.Error_Message.setText("Error Reading plugins")
            stmt.close()
            dbConn.close()
            return "Error"
コード例 #11
0
    def SaveSettings(self, e):

        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\GUI_Settings.db3"
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = ""
            if (self.local_settings.getVolatility_Dir_Found()):
                SQL_Statement = 'Update settings set Setting_Value = "' + self.Program_Executable_TF.getText() + '"' + \
                                ' where setting_name = "Volatility_Executable_Directory";'
                SQL_Statement2 = 'Update settings set Setting_Value = "' + self.Version_CB.getSelectedItem() + '"' + \
                                ' where setting_name = "Volatility_Version";'
            else:
                SQL_Statement = 'Insert into settings (Setting_Name, Setting_Value) values ("Volatility_Executable_Directory", "' +  \
                                self.Program_Executable_TF.getText() + '");'
                SQL_Statement2 = 'Insert into settings (Setting_Name, Setting_Value) values ("Volatility_Version", "' +  \
                                self.Version_CB.getSelectedItem() + '");'

            stmt.execute(SQL_Statement)
            stmt.execute(SQL_Statement2)
            self.Error_Message.setText("Volatility Executable Directory Saved")
            self.local_settings.setVolatility_Directory(
                self.Program_Executable_TF.getText())
        except SQLException as e:
            self.Error_Message.setText(e.getMessage())
        stmt.close()
        dbConn.close()
コード例 #12
0
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = head + "\\GUI_Settings.db3"
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'Select Setting_Name, Setting_Value from settings;' 
            resultSet = stmt.executeQuery(SQL_Statement)
            while resultSet.next():
                if resultSet.getString("Setting_Name") == "API_Key":
                    self.local_settings.setAPI_Key(resultSet.getString("Setting_Value"))
                    self.API_Key_TF.setText(resultSet.getString("Setting_Value"))
                if resultSet.getString("Setting_Name") == "Private":
                    private = resultSet.getString("Setting_Value")
                    if private == "1":
                        self.local_settings.setPrivate(True)
                    else:
                        self.local_settings.setPrivate(False)

            self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()
コード例 #13
0
class MethodSignatures(Object):
    __proxymaker__ = MiniClampMaker
    __java_package__ = 'custom_proxymaker.tests'

    def throwsException(self):
        pass
    throwsException._clamp = ClampMethod('throwsException', Void.TYPE, [], [RuntimeException], {}, [{}])

    def returnsLong(self):
        return 2
    returnsLong._clamp = ClampMethod('returnsLong', Long.TYPE, [], [], {}, [{}])

    def returnsObject(self):
        return Object()
    returnsObject._clamp = ClampMethod('returnsObject', Object, [], [], {}, [{}])

    def returnsArray(self):
        return [1,2,3]
    returnsArray._clamp = ClampMethod('returnsArray', Class.forName('[J'), [], [], {}, [{}])

    def returnsArrayObj(self):
        return [1,2,3]
    returnsArrayObj._clamp = ClampMethod('returnsArrayObj', Class.forName('[Ljava.lang.Object;'), [], [], {}, [{}])

    def acceptsString(self, arg):
        pass
    acceptsString._clamp = ClampMethod('acceptsString', Void.TYPE, [String], [], {}, [{}])

    def acceptsArray(self, arg):
        pass
    acceptsArray._clamp = ClampMethod('acceptsArray', Void.TYPE, [Class.forName('[J')], [], {}, [{}])
    
コード例 #14
0
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'Select Setting_Name, Setting_Value from settings;'
            resultSet = stmt.executeQuery(SQL_Statement)
            while resultSet.next():
                if resultSet.getString("Setting_Name") == "Program_Exec_Name":
                    self.Program_Executable_TF.setText(
                        resultSet.getString("Setting_Value"))
                    self.local_settings.setSetting(
                        'ExecFile', resultSet.getString("Setting_Value"))
                    self.local_settings.setSetting('Exec_Prog_Flag', 'true')
                    self.Exec_Program_CB.setSelected(True)
                    self.Program_Executable_TF.setEnabled(True)
                    self.Find_Program_Exec_BTN.setEnabled(True)
            self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()
コード例 #15
0
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = head + "\\gui_Settings.db3"
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = 'Select Protocol, cuckoo_host, cuckoo_port from cuckoo_server' 
           resultSet = stmt.executeQuery(SQL_Statement)
           while resultSet.next():
               self.Protocol_TF.setText(resultSet.getString("Protocol"))
               self.IP_Address_TF.setText(resultSet.getString("cuckoo_host"))
               self.Port_Number_TF.setText(resultSet.getString("cuckoo_port"))
               self.local_settings.setProtocol(resultSet.getString("Protocol"))
               self.local_settings.setIP_Address(resultSet.getString("cuckoo_host"))
               self.local_settings.setPort_Number(resultSet.getString("cuckoo_port"))
           self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()
コード例 #16
0
    def get_plugins(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
            self.Error_Message.setText("Database opened")
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = "select plugin_name from plugins where volatility_version = '" + self.Version_CB.getSelectedItem() + "' and " + \
                             " plugin_name in ('dumpcerts', 'dumpfiles', 'dumpregistry', 'linux_librarydump', 'linux_procdump', 'mac_dump_file', 'mac_procdump', 'moddump', 'procdump', 'vaddump');"
            resultSet = stmt.executeQuery(SQL_Statement)
            plugin_list = []
            while resultSet.next():
                plugin_list.append(resultSet.getString("plugin_name"))

            stmt.close()
            dbConn.close()
            return plugin_list
        except SQLException as e:
            self.Error_Message.setText("Error Reading plugins")
            stmt.close()
            dbConn.close()
            return "Error"
コード例 #17
0
    def SaveSettings(self, e):
        
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = head + "\\GUI_Settings.db3"
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = ""
           SQL_Statement = 'Update cuckoo_server set Protocol = "' + self.Protocol_TF.getText() + '", ' + \
                               '                     Cuckoo_Host = "' + self.IP_Address_TF.getText() + '", ' + \
                               '                     Cuckoo_port = "' + self.Port_Number_TF.getText() + '";' 
           
           #self.Error_Message.setText(SQL_Statement)
           stmt.execute(SQL_Statement)
           self.Error_Message.setText("Cuckoo settings Saved")
           #self.local_settings.setCuckoo_Directory(self.Program_Executable_TF.getText())
        except SQLException as e:
           self.Error_Message.setText(e.getMessage())
        stmt.close()
        dbConn.close()
コード例 #18
0
    def __findGeoLocationsInDB(self, databasePath, abstractFile):
        if not databasePath:
            return

        try:
            Class.forName("org.sqlite.JDBC") # load JDBC driver
            connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath)
            statement = connection.createStatement()
        except (ClassNotFoundException, SQLException) as ex:
            self._logger.log(Level.SEVERE, "Error opening database", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
            return

        try:
            resultSet = statement.executeQuery(
                "SELECT time, dest_lat, dest_lng, dest_title, dest_address, source_lat, source_lng FROM destination_history;")

            while resultSet.next():
                time = Long.valueOf(resultSet.getString("time")) / 1000
                dest_title = resultSet.getString("dest_title")
                dest_address = resultSet.getString("dest_address")

                dest_lat = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("dest_lat"))
                dest_lng = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("dest_lng"))
                source_lat = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("source_lat"))
                source_lng = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("source_lng"))

                artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_ROUTE)
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_CATEGORY, general.MODULE_NAME, "Destination"))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, time))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_END, general.MODULE_NAME, dest_lat))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_END, general.MODULE_NAME, dest_lng))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_START, general.MODULE_NAME, source_lat))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_START, general.MODULE_NAME, source_lng))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_NAME, general.MODULE_NAME, dest_title))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_LOCATION, general.MODULE_NAME, dest_address))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PROG_NAME, general.MODULE_NAME, "Google Maps History"))

                try:
                    # index the artifact for keyword search
                    blackboard = Case.getCurrentCase().getServices().getBlackboard()
                    blackboard.indexArtifact(artifact)
                except Blackboard.BlackboardException as ex:
                    self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + artifact.getArtifactID(), ex)
                    self._logger.log(Level.SEVERE, traceback.format_exc())
                    MessageNotifyUtil.Notify.error("Failed to index GPS route artifact for keyword search.", artifact.getDisplayName())

        except Exception as ex:
            self._logger.log(Level.SEVERE, "Error parsing Google map locations to the blackboard", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
        finally:
            try:
                if resultSet is not None:
                    resultSet.close()
                statement.close()
                connection.close()
            except Exception as ex:
                self._logger.log(Level.SEVERE, "Error closing the database", ex)
                self._logger.log(Level.SEVERE, traceback.format_exc())
コード例 #19
0
ファイル: browserlocation.py プロジェクト: sleuthkit/autopsy
    def __findGeoLocationsInDB(self, databasePath, abstractFile):
        if not databasePath:
            return

        try:
            Class.forName("org.sqlite.JDBC") #load JDBC driver
            connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath)
            statement = connection.createStatement()
        except (ClassNotFoundException) as ex:
            self._logger.log(Level.SEVERE, "Error loading JDBC driver", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
            return
        except (SQLException) as ex:
            # Error connecting to SQL databse.
            return

        resultSet = None
        try:
            resultSet = statement.executeQuery("SELECT timestamp, latitude, longitude, accuracy FROM CachedPosition;")
            while resultSet.next():
                timestamp = Long.valueOf(resultSet.getString("timestamp")) / 1000
                latitude = Double.valueOf(resultSet.getString("latitude"))
                longitude = Double.valueOf(resultSet.getString("longitude"))

                attributes = ArrayList()
                artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_TRACKPOINT)
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE, general.MODULE_NAME, latitude))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE, general.MODULE_NAME, longitude))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, timestamp))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PROG_NAME, general.MODULE_NAME, "Browser Location History"))
                # artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(),moduleName, accuracy))
                # NOTE: originally commented out

                artifact.addAttributes(attributes);
                try:
                    # index the artifact for keyword search
                    blackboard = Case.getCurrentCase().getServices().getBlackboard()
                    blackboard.indexArtifact(artifact)
                except Blackboard.BlackboardException as ex:
                    self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + str(artifact.getArtifactTypeName()), ex)
                    self._logger.log(Level.SEVERE, traceback.format_exc())
                    MessageNotifyUtil.Notify.error("Failed to index GPS trackpoint artifact for keyword search.", artifact.getDisplayName())

        except SQLException as ex:
            # Unable to execute browser location SQL query against database.
            pass
        except Exception as ex:
            self._logger.log(Level.SEVERE, "Error putting artifacts to blackboard", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
        finally:
            try:
                if resultSet is not None:
                    resultSet.close()
                statement.close()
                connection.close()
            except Exception as ex:
                # Error closing database.
                pass
コード例 #20
0
 def connect(self, database_path):
     try:
         Class.forName('org.sqlite.JDBC')
         self._connection = DriverManager.getConnection('jdbc:sqlite:%s' % database_path)
         self._connection.setAutoCommit(True)
     except ClassNotFoundException as e:
         self._log_error(e.getMessage())
     except SQLException as e:
         self._log_error(e.getMessage())
コード例 #21
0
ファイル: Project_Searcher.py プロジェクト: pombredanne/facoy
def get_db_connection():
    from java.lang import Class
    from java.sql import DriverManager
    Class.forName("com.mysql.jdbc.Driver").newInstance()
    newConn = DriverManager.getConnection(
        "jdbc:mysql://0.0.0.0:3306/stackoverflow?autoReconnect=true", "root",
        "1234")
    newConn.setAutoCommit(True)
    return newConn
コード例 #22
0
ファイル: Mysql.py プロジェクト: veelckoo/MTGOBOT
def connect(dburl="jdbc:mysql://localhost:3306/mtgo", dbuser="******", dbpass=None):
    try:
        try:
            Class.forName("com.mysql.jdbc.Driver").newInstance()
        except NameError:
            raise ErrorHandler("Internal MySQL error")
        conn = DriverManager.getConnection(dburl, dbuser, dbpass)
    except SQLException, error:
        raise ErrorHandler("MySQL error: %s" % str(error))
コード例 #23
0
ファイル: Indexer_Answer.py プロジェクト: pombredanne/facoy
def get_db_connection():
	from java.lang import Class
	from java.sql import DriverManager
	Class.forName("com.mysql.jdbc.Driver").newInstance()
	#########################################  경   로  ####################################
	#newConn = DriverManager.getConnection("jdbc:mysql://203.255.81.47:3306/stackoverflow?useUnicode=yes&characterEncoding=utf8&user=test")
	newConn = DriverManager.getConnection("jdbc:mysql://203.255.81.42:3306/stackoverflow?autoReconnect=true", "seal", "sel535424")
	newConn.setAutoCommit(True)
	return newConn
コード例 #24
0
    def __init__(self, *args, **kwds):
        unittest.TestCase.__init__(self, *args, **kwds)

        self._primitive_types = {
            Class.forName('java.lang.Boolean'): Boolean,
            Class.forName('java.lang.Integer'): Integer,
            Class.forName('java.lang.Long'): Long,
            Class.forName('java.lang.Double'): Double,
            Class.forName('java.lang.String'): String
        }
コード例 #25
0
    def processFbChat(self, extractedFile):

        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 extractedFile)
        except SQLException as e:
            self.log(
                Level.INFO, "Could not open database file (not SQLite) " +
                extractedFile + " (" + e.getMessage() + ")")
            return IngestModule.ProcessResult.OK

        self.getFBOwner(dbConn)

        # Query the autopsy_chat table in the database.
        try:
            stmt = dbConn.createStatement()
            resultSet = stmt.executeQuery("select message_id, user_id, sender_id, message||' '||attachment_description||' '||attachment_href message, " + \
                                          " sender_name, receiver_name, dttm from autopsy_chat;")
            self.log(Level.INFO, "query Autopsy_chat table")
        except SQLException as e:
            self.log(
                Level.INFO, "Error querying database for messages table (" +
                e.getMessage() + ") extractedFile ==> " + extractedFile)
            return IngestModule.ProcessResult.OK

        # Cycle through each row and create FB Chat List
        # message_id, user_id, sender_id, Message||' '||attachment_description||' '||attachment_href, sender_name, receiver_name, Recvd Dttm
        while resultSet.next():
            try:
                chatMessage = []
                chatMessage.append(resultSet.getString("message_Id"))
                chatMessage.append(resultSet.getInt("user_Id"))
                chatMessage.append(resultSet.getInt("sender_Id"))
                chatMessage.append(resultSet.getString("message"))
                chatMessage.append(resultSet.getString("sender_name"))
                chatMessage.append(resultSet.getString("receiver_name"))
                chatMessage.append(resultSet.getInt("dttm"))
                #                chatMessage.append(cMessage[0])
                self.chatMessages.append(chatMessage)
                self._logger.log(Level.INFO,
                                 "Chat Message ==> " + str(chatMessage))

            except SQLException as e:
                #pass
                self.log(
                    Level.INFO, "Error getting values from recipent table (" +
                    e.getMessage() + ")")

        # Close the database statement
        try:
            stmt.close()
            dbConn.close()
        except:
            pass
コード例 #26
0
 def dbOpen(self):
     self.database = "MACard.db"
     driver = "org.sqlite.JDBC"
     self.url = "jdbc:sqlite:" + self.database
     Class.forName(driver)
     try:
         self.db = DriverManager.getConnection(self.url);
         self.stat = self.db.createStatement()
         self.stat.executeUpdate("CREATE TABLE IF NOT EXISTS " + self.TABLENAME + " ("+ self.CARDID + " INTEGER, " + self.COUNTRY + " TEXT, "+ self.CARDURL + " TEXT, " + self.CARDNAME + " TEXT, "+ self.CARDALTERNATIVE + " TEXT);");
     except SQLException, e:
         self.requestAdd("DB OPEN ERROR")
コード例 #27
0
def getConnection(jdbc_url, driverName):
    """
        Given the name of a JDBC driver class and the url to be used 
        to connect to a database, attempt to obtain a connection to 
        the database.
    """
    try:
        Class.forName(driverName).newInstance()
    except Exception, msg:
        print msg
        sys.exit(-1)
コード例 #28
0
    def connnectToManifestDb(self, dbFile):
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % dbFile)
        except SQLException as e:
            self.log(
                Level.INFO, "Could not open database file (not SQLite) " +
                extractedFile + " (" + e.getMessage() + ")")
            return IngestModule.ProcessResult.OK

        return dbConn
コード例 #29
0
ファイル: PMExp.py プロジェクト: andinue/elizabeth-modules
 def dbOpen(self):
     self.database = "exp.db"
     driver = "org.sqlite.JDBC"
     self.url = "jdbc:sqlite:" + self.database
     Class.forName(driver)
     try:
         self.db = DriverManager.getConnection(self.url);
         self.stat = self.db.createStatement()
         self.stat.executeUpdate("CREATE TABLE IF NOT EXISTS " + self.TABLENAME + " (" + self.EMAIL + " TEXT, " + self.HOST + " TEXT, " + self.NICK + " TEXT, " +  self.EXP + " INTEGER);");
     except SQLException, e:
         self.requestAdd("ERROR : OPEN")
コード例 #30
0
ファイル: sample.py プロジェクト: favoritemedium/jython-jdbc
def getConnection(jdbc_url, driverName):
    """
        Given the name of a JDBC driver class and the url to be used 
        to connect to a database, attempt to obtain a connection to 
        the database.
    """
    try:
        Class.forName(driverName).newInstance()
    except Exception, msg:
        print msg
        sys.exit(-1)
コード例 #31
0
 def dbOpen(self):
     self.database = "CustomMsg.db"
     driver = "org.sqlite.JDBC"
     self.url = "jdbc:sqlite:" + self.database
     Class.forName(driver)
     try:
         self.db = DriverManager.getConnection(self.url);
         self.stat = self.db.createStatement()
         self.stat.executeUpdate("CREATE TABLE IF NOT EXISTS " + self.TABLENAME + " ("+ self.HOST + " TEXT PRIMARY KEY, "+  self.MSG + " TEXT);");
     except SQLException, e:
         self.requestAdd("ERROR")
コード例 #32
0
    def __findTangoMessagesInDB(self, databasePath, abstractFile):
        if not databasePath:
            return

        try:
            Class.forName("org.sqlite.JDBC") # load JDBC driver
            connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath)
            statement = connection.createStatement()
        except (ClassNotFoundException, SQLException) as ex:
            self._logger.log(Level.SEVERE, "Error opening database", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
            return

        try:
            resultSet = statement.executeQuery(
                "SELECT conv_id, create_time, direction, payload FROM messages ORDER BY create_time DESC;")

            while resultSet.next():
                conv_id = resultSet.getString("conv_id") # seems to wrap around the message found in payload after decoding from base-64
                create_time = Long.valueOf(resultSet.getString("create_time")) / 1000
                if resultSet.getString("direction") == "1": # 1 incoming, 2 outgoing
                    direction = "Incoming"
                else:
                    direction = "Outgoing"
                payload = resultSet.getString("payload")

                artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_MESSAGE) #create a call log and then add attributes from result set.
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, create_time))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DIRECTION, general.MODULE_NAME, direction))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TEXT, general.MODULE_NAME, TangoMessageAnalyzer.decodeMessage(conv_id, payload)))
                artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_MESSAGE_TYPE, general.MODULE_NAME, "Tango Message"))

                try:
                    # index the artifact for keyword search
                    blackboard = Case.getCurrentCase().getServices().getBlackboard()
                    blackboard.indexArtifact(artifact)
                except Blackboard.BlackboardException as ex:
                    self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + artifact.getArtifactID(), ex)
                    self._logger.log(Level.SEVERE, traceback.format_exc())
                    MessageNotifyUtil.Notify.error("Failed to index Tango message artifact for keyword search.", artifact.getDisplayName())

        except Exception as ex:
           self._logger.log(Level.SEVERE, "Error parsing Tango messages to the blackboard", ex)
           self._logger.log(Level.SEVERE, traceback.format_exc())
        finally:
            try:
                if resultSet is not None:
                    resultSet.close()
                statement.close()
                connection.close()
            except Exception as ex:
                self._logger.log(Level.SEVERE, "Error closing database", ex)
                self._logger.log(Level.SEVERE, traceback.format_exc())
コード例 #33
0
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\config.db"

        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        if os.path.exists(settings_db):

            try:
                stmt = dbConn.createStatement()
                SQL_Statement = 'Select Key_Name, Key_Value from CONFIG;'
                resultSet = stmt.executeQuery(SQL_Statement)
                while resultSet.next():
                    if resultSet.getString("Key_Name") == "BUCKET":
                        self.local_settings.setBucket(
                            resultSet.getString("Key_Value"))
                        self.Bucket_TF.setText(
                            resultSet.getString("Key_Value"))
                    if resultSet.getString("Key_Name") == "ACCESS_KEY":
                        self.local_settings.setAccessKey(
                            resultSet.getString("Key_Value"))
                        self.Access_Key_TF.setText(
                            resultSet.getString("Key_Value"))
                    if resultSet.getString("Key_Name") == "SECRET_KEY":
                        self.local_settings.setSecretKey(
                            resultSet.getString("Key_Value"))
                        self.Secret_Key_TF.setText(
                            resultSet.getString("Key_Value"))
                    if resultSet.getString("Key_Name") == "AWS_REGION":
                        self.local_settings.setRegion(
                            resultSet.getString("Key_Value"))
                        self.Region_TF.setText(
                            resultSet.getString("Key_Value"))
                self.Error_Message.setText("Settings Read successfully!")
            except SQLException as e:
                self.Error_Message.setText("Error Reading Settings Database")

        else:

            try:
                stmt = dbConn.createStatement()
                SQL_Statement = 'CREATE TABLE CONFIG ( Setting_Name Text, Setting_Value Text)'
                resultSet = stmt.executeQuery(SQL_Statement)
            except SQLException as e:
                self.Error_Message.setText("Error Creating Settings Database")

        stmt.close()
        dbConn.close()
コード例 #34
0
    def autoconnection():
        # DBManager.lock.acquire()
        if DBManager.GlobalConn is not None:
            DBManager.GlobalConn.close()
            DBManager.GlobalConn = None

        Class.forName("com.mysql.jdbc.Driver").newInstance()
        newConn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/test?", "root", "")
        newConn.setAutoCommit(True)
        DBManager.GlobalConn = newConn

        pass
コード例 #35
0
ファイル: db.py プロジェクト: enix223/DataXfer
 def __init__(self, dbType):
     log_file_name = "history_%s.log" % datetime.now().strftime("%Y%m%d")
     self.logger = Logger.getLog(log_file_name)
     self.conn = None
     self.__stmt__ = None
     self.__rs__ = None
     config = dbType
     if config:
         try:
             Class.forName(config["DRIVER"]).newInstance()
             self.conn = DriverManager.getConnection(config["URL"], config["USER"], config["PASSWD"])
         except SQLException, e:
             self.logger.error("(db.py => __init__)Get %s connection error! \n %s" % (dbType, str(e)))
             raise Exception
コード例 #36
0
ファイル: main.py プロジェクト: pavithra03/neofelis
 def actionPerformed(self, event):
   browsers = ["google-chrome", "firefox", "opera", "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla"]
   osName = System.getProperty("os.name")
   helpHTML = ClassLoader.getSystemResource("help.html").toString()
   if osName.find("Mac OS") == 0:
     Class.forName("com.apple.eio.FileManager").getDeclaredMethod( "openURL", [String().getClass()]).invoke(None, [helpHTML])
   elif osName.find("Windows") == 0:
     Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + helpHTML)
   else:
     browser = None
     for b in browsers:
       if browser == None and Runtime.getRuntime().exec(["which", b]).getInputStream().read() != -1:
         browser = b
         Runtime.getRuntime().exec([browser, helpHTML])
コード例 #37
0
 def __init__(self, release, db_url, username, password, jdbc_driver):
     self.jdbc_driver = jdbc_driver
     self.password = password
     self.username = username
     self.db_url = db_url
     Class.forName(jdbc_driver)
     self._conn = DriverManager.getConnection(db_url, username, password)
     wrapped_release = self.wrap_dict_as_obj(release)
     self.release = wrapped_release
     self.release_id = self.convert_id(wrapped_release.id)
     if "originTemplateId" in release and release['originTemplateId'] is not None:
         self.template_id = self.convert_id(wrapped_release.originTemplateId)
     else:
         self.template_id = "No Template"
コード例 #38
0
    def	registerExtenderCallbacks(self, callbacks):
        global statement,con

        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("SQLite Logger")

        # select sqlite jdbc jar file
        c = classPathHacker()
        c.addFile("C:\\sqlite-jdbc-3.8.11.2.jar")

        # database filename.
        jdbc_url = "jdbc:sqlite:database" + str(datetime.date.today()) + ".db"
        driver = "org.sqlite.JDBC"
        Class.forName(driver).newInstance()
        con = DriverManager.getConnection(jdbc_url)

        # create table
        self.sql = "CREATE TABLE if not exists log(host text,path text,method text,request text,response text,time text);"
        statement = con.prepareStatement(self.sql)
        statement.executeUpdate()
        
        self._log = ArrayList()
        self._lock = Lock()

        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        self._splitpane.setLeftComponent(scrollPane)

        tabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        tabs.addTab("Request", self._requestViewer.getComponent())
        tabs.addTab("Response", self._responseViewer.getComponent())
        self._splitpane.setRightComponent(tabs)

        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(tabs)

        callbacks.addSuiteTab(self)

        callbacks.registerHttpListener(self)
        
        return
コード例 #39
0
    def connect(self):
        """ Connects to a databased if the file being processed is a db.

        Args: -

        Returns:
            True: the connection is made
            False: no connection made
        """
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            self.dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % self.lclPath)
        except:
            return False
        else:
            return True
コード例 #40
0
def jdbc_test():
    """LJG: zxJDBC를 사용하면 한글처리가 에러나는데 JDBC를 직접 사용하면 한글처리가 성공한다
    추후 시간을 갖고 한글관련 문제를 처리하자.오늘은 여기까지 새벽 3시다.. 정말 한글이 싫다.ㅋㅋ
    """
    import sys
    import java
    from java.lang import Class
    from java.sql import DriverManager, SQLException
    
    jdbc_user = "******"
    jdbc_password = "******"
    jdbc_url = "jdbc:mysql://14.63.161.143/cdp"
    
    DriverManager.registerDriver(Class.forName("com.mysql.jdbc.Driver").newInstance())
    
    connection = DriverManager.getConnection(jdbc_url, jdbc_user, jdbc_password)
    
    statement = connection.createStatement()
    
    sql = "select * from test_sample"
    
    rs = statement.executeQuery(sql)
    
    while rs.next():
      row = rs.getString(2)
      print row
コード例 #41
0
ファイル: recipe-502222.py プロジェクト: zlrs/code-1
def javaClassToHtml(javaClass, level=0):
    """return html class representation."""
    if type(javaClass) is StringType or type(javaClass) is UnicodeType:
        class_ = Class.forName(javaClass)
        className = javaClass
    else:
        class_ = javaClass
        className = javaClass.__name__
    if Class.isInterface(class_):
        typeStr = 'interface'
    elif Modifier.isAbstract(Class.getModifiers(class_)):
        typeStr = 'abstract class'
    else:
        typeStr = 'class'
    #indent = (' '*level+1)*4)
    indent = ' ' * (level + 1) * 4
    header = '%s<p>%s %s' % (indent, typeStr, className)
    super_ = Class.getSuperclass(class_)
    if super_ is not None:
        header += ' extends ' + Class.getName(super_)
    interfaces = Class.getInterfaces(class_)
    if len(interfaces) > 0:
        interfacesNames = join(map(Class.getName, interfaces), ', ')
        header += ' implements %s' % (interfacesNames)
    body = membersToHtml(lambda: Class.getDeclaredFields(class_), level)
    body += membersToHtml(lambda: Class.getDeclaredConstructors(class_), level)
    body += membersToHtml(lambda: Class.getDeclaredMethods(class_), level)
    body = '%s{</p>\n%s<ul class="ind%i">\n%s' % (header, indent, level, body)
    body = boldJavaKeywords(classLink(className, body))
    li = '%s<li>\n%s\n%s</li>\n'
    ind2 = (' ' * (level + 2) * 4)
    for cl in Class.getDeclaredClasses(class_):
        body += li % (ind2, javaClassToHtml(Class.getName(cl), level+1), \
                indent*2)
    return '%s%s</ul>}' % (body, indent)
コード例 #42
0
ファイル: query.py プロジェクト: Paul-Nguyen/mint
    def __activate__(self, context):
        self.response = context["response"]
        self.request = context["request"]
        self.systemConfig = context["systemConfig"]
        out = self.response.getPrintWriter("text/plain; charset=UTF-8")
        callType = self.request.getParameter("callType")
        apiClass = self.systemConfig.getObject("api").get(callType)
        className = apiClass.get("className")
        apiCallClass = Class.forName(className)
        apiCallObject = apiCallClass.newInstance()

        setScriptingServiceMethod = apiCallClass.getMethod(
            "setScriptingServices",
            self.get_class(
                "com.googlecode.fascinator.portal.services.ScriptingServices"))
        setScriptingServiceMethod.invoke(apiCallObject, context['Services'])
        if callType == "mint-stats":
            setScriptingServiceMethod = apiCallClass.getMethod(
                "setConfig",
                self.get_class("com.googlecode.fascinator.common.JsonSimple"))
            setScriptingServiceMethod.invoke(
                apiCallObject,
                JsonSimple(self.systemConfig.getObject("api", "mint-stats")))

        handleRequestMethod = apiCallClass.getMethod(
            "handleRequest",
            self.get_class("org.apache.tapestry5.services.Request"))
        responseString = handleRequestMethod.invoke(apiCallObject,
                                                    context["request"])
        out.println(responseString)

        out.close()
コード例 #43
0
def getReflectedField(self, field_name, method_class=None):
	"""Using reflection, we may need to tell the JVM to allow us to see the object."""

	# Typically, we will pull the field off the given object instance
	#   (traditionally named 'self' in Python)
	if method_class is None:
		try:
			field = self.class.getDeclaredField(field_name)
		except AttributeError:
			field = self.getDeclaredField(field_name)
	else:
		# But we may have situations where it is more straight-forward
		#   to get the method first, then pass self in
		#   (as all class methods are declared in Python)
		# If this the case, check if the class is just the name.
		#   (Java lets us get a class by its unique name reference)
		if isinstance(method_class, (unicode, str)):
			method_class = JavaClass.forName(method_class)
		field = method_class.getDeclaredField(field_name)

	# Java reflection respects class privacy by default.
	# But to be useful it needs to be able to inspect regardless.
	# Also, this code is in Python, so we already don't have a problem
	#   with respectfully-hidden-but-still-accessible private attributes.
	try:
		original_accesibility = field.isAccessible()
		field.setAccessible(True)
		# Note that this is very similar to Python's self.
		# An alternate way to write this is source.field in Python
		attribute = field.get(self)
	finally:
		# ... That all said, we'll still put this back out of politeness.
		field.setAccessible(original_accesibility)

	return attribute
コード例 #44
0
ファイル: ui.py プロジェクト: benteveo-kiwi/benteveo-toolbox
    def buildRequestTable(self, state, callbacks):
        """
        Builds the request list on the results page on the right.
        """
        splitpane = JSplitPane()
        splitpane.setDividerLocation(1000)

        endpointTable = Table(state.endpointTableModel)
        endpointTable.setDefaultRenderer(Class.forName('java.lang.Object'),
                                         CellHighlighterRenderer(state))

        endpointTable.getColumnModel().getColumn(0).setPreferredWidth(15)
        endpointTable.getColumnModel().getColumn(1).setPreferredWidth(500)
        endpointTable.setAutoCreateRowSorter(True)
        endpointTable.addMouseListener(TableMouseAdapter())

        endpointView = JScrollPane(endpointTable)
        callbacks.customizeUiComponent(endpointTable)
        callbacks.customizeUiComponent(endpointView)

        requestTable = Table(state.requestTableModel)
        requestTable.getColumnModel().getColumn(0).setPreferredWidth(500)

        requestView = JScrollPane(requestTable)
        callbacks.customizeUiComponent(requestTable)
        callbacks.customizeUiComponent(requestView)

        splitpane.setLeftComponent(endpointView)
        splitpane.setRightComponent(requestView)

        return splitpane
コード例 #45
0
ファイル: SelPanel.py プロジェクト: sedjrodonan/lositan
 def initTable(self, lociNames, pv, ci, locusFst):
     colNames = Vector()
     colNames.add('Locus')
     colNames.add('Het')
     colNames.add('Fst')
     colNames.add('P(simulated Fst < sample Fst)')
     colNames.add('FDR')
     data = Vector()
     self.data = data
     falses = self.calcFalsePositives(pv, ci, self.fdr)
     currentPos = 0
     for i in range(len(lociNames)):
         line = Vector()
         locus = lociNames[i]
         line.add(locus)
         if not locusFst[i]:
             line.add("NA")
             line.add("NA")
             line.add("NA")
             line.add("NA")
         else:
             line.add(str(pv[currentPos][0]))
             line.add(str(pv[currentPos][1]))
             line.add(str(self.getP(pv[currentPos])))
             line.add(str(falses[currentPos]))
             currentPos += 1
         data.add(line)
     self.table = JTable(data, colNames)
     self.table.setDefaultRenderer(
         Class.forName("java.lang.Object"),
         ColorRenderer(data, ci, self.chart.neuColor, self.chart.balColor,
                       self.chart.posColor))
コード例 #46
0
ファイル: SelPanel.py プロジェクト: samitha/lositan
 def initTable(self, lociNames, pv, ci, locusFst):
     colNames = Vector()
     colNames.add('Locus')
     colNames.add('Het')
     colNames.add('Fst')
     colNames.add('P(simulated Fst < sample Fst)')
     colNames.add('FDR')
     data = Vector()
     self.data = data
     falses = self.calcFalsePositives(pv, ci, self.fdr)
     currentPos = 0
     for i in range(len(lociNames)):
         line = Vector()
         locus = lociNames[i]
         line.add(locus)
         if not locusFst[i]:
             line.add("NA")
             line.add("NA")
             line.add("NA")
             line.add("NA")
         else:
             line.add(str(pv[currentPos][0]))
             line.add(str(pv[currentPos][1]))
             line.add(str(self.getP(pv[currentPos])))
             line.add(str(falses[currentPos]))
             currentPos += 1
         data.add(line)
     self.table = JTable(data, colNames)
     self.table.setDefaultRenderer(Class.forName("java.lang.Object"),
            ColorRenderer(data, ci, self.chart.neuColor,
                self.chart.balColor, self.chart.posColor))
コード例 #47
0
 def __init__(self, global_config):
     BasePlugin.BasePlugin.__init__(self, global_config, self.required_config, self.plugin_scope)
     self.dbfile = self.global_config[self.plugin_name]['output_file']
     self.dburl = "jdbc:sqlite:" + self.dbfile
     dbdriver = "org.sqlite.JDBC"
     Class.forName(dbdriver)
     if (os.path.isfile(self.dbfile) == True):
         #use existing db schema
         self.logger.info("%s already exists, will be appending to database" % (self.dbfile))
         self.db = DriverManager.getConnection(self.dburl)
         stmt = self.db.createStatement()
     else:
         #create db file
         self.logger.info("creating db file %s" % (self.dbfile))
         self.db = DriverManager.getConnection(self.dburl)
         stmt = self.db.createStatement()
         stmt.executeUpdate('''CREATE TABLE IF NOT EXISTS "hiccuplog" (ref INTEGER, type BOOLEAN, url TEXT, headers TEXT, content BLOB)''')
コード例 #48
0
ファイル: checkCDA2.py プロジェクト: TADDM/taddm-tools
def connectToDB(driver, url, user, password):
    try:
        cls = Class.forName(driver)
        DriverManager.registerDriver(cls.newInstance())
        conn = DriverManager.getConnection(url, user, password)
        return conn
    except SQLException, desc:
        raise desc
コード例 #49
0
ファイル: lang.py プロジェクト: alonsodomin/wspydmin
def java_type(typename):
	if (typename == '') or (typename is None): return None
	if typename.startswth('java.'):
		return JavaClass.forName(typename)
	if typename.startswith('[L'):
		elementType = java_type(typename[2:-1])
		return JavaArray.new(elementType, 0).getClass()
	return None
コード例 #50
0
ファイル: rtm.py プロジェクト: hsnuhayato/tsml
def cdr2data(cdr, classname):
	ostrm = EncapsOutputStream(orb, True)
	ostrm.write_octet_array(cdr, 0, len(cdr))
	istrm = ostrm.create_input_stream()
	holder = Class.forName("RTC."+classname+"Holder", True, Manager.getClassLoader())
	streamable = holder.newInstance()
	streamable._read(istrm)
	return streamable.value
コード例 #51
0
ファイル: bootstrap.py プロジェクト: shamonj03/SUDV3
def on_event(type):
		message = type
		name = message + 'Event'
		package = 'com.joe.game.model.event'
		c = Class.forName(package + '.' + name)
		
		def handle(func):
			Game.getEventDispatcher().register(c, EHandler(func))
		return handle
コード例 #52
0
ファイル: util.py プロジェクト: carriercomm/atlas-lb
 def setStubs(self):
     ep = self.endpoint
     self.stubs = {}
     for (shortName,stubClassName) in self.stubNames.items():
         fullClassName = "%s.%s"%(self.package,stubClassName)
         stubClass = Class.forName(fullClassName)
         stubInstance = stubClass(ep,None)
         stubInstance.setUsername(self.user)
         stubInstance.setPassword(self.passwd)
         self.stubs[shortName] = stubInstance
コード例 #53
0
ファイル: rtm.py プロジェクト: hsnuhayato/tsml
def data2cdr(data):
	holder = Class.forName(data.getClass().getCanonicalName()+"Holder",
			       True, data.getClass().getClassLoader())
	streamable = holder.newInstance()
	#field = holder.getField("value")
	#field.set(streamable, data)
	streamable.value = data;
	strm = EncapsOutputStream(orb, True)
	streamable._write(strm)
	return strm.toByteArray()
コード例 #54
0
def setupDatabaseOcsg(dsMap):
  try:
    jarPath = os.path.join(WL_HOME, "server", "lib", "mbeantypes", OCSG_UTIL_JAR)
    cl = URLClassLoader(jarray.array([File(jarPath).toURI().toURL()], URL))
    clz = cl.loadClass(OCSG_UTIL_CLASS)
    m = clz.getMethod("main",jarray.array([Class.forName("[Ljava.lang.String;")],Class))
    m.invoke(None, jarray.array([dsMap[OCSG_DATASOURCE]],Object))
  except Exception, ex:
      print "Unable to populate database", ex
      sys.exit(1)
コード例 #55
0
ファイル: jvm.py プロジェクト: barmalei/scalpel
 def __init__(self, lang = 'nl'):
     Tokenizer.__init__(self, lang)
 
     self.memory, self.tags_map = "-mx512M", {}
     self.class_loader = self.ner_instance = None
     
     # test wheher tokenizer has been started under Jython
     try:
         from java.lang import Class
         self.class_loader = Class.forName("gravity.common.CustomClassLoader")(self.java_classpath())
     except: pass
コード例 #56
0
    def generates(self):
        """
        Returns the class of objects that it generates.

        @return: the classes
        @rtype: list
        """

        # very in-elegant, but works
        # http://www.prasannatech.net/2009/02/class-object-name-java-interface-jython.html
        return [Class.forName("[[Ljava.lang.Double;")]
コード例 #57
0
    def SaveSettings(self, e):
        
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = 'Insert into settings (Setting_Name, Setting_Value) values ("Program_Exec_Name", "' +  \
                           self.Program_Executable_TF.getText() + '");' 
           
           resultSet = stmt.executeQuery(SQL_Statement)
           self.Error_Message.setText("Settings Saved")
        except SQLException as e:
           self.Error_Message.setText("Error Inserting Settings " + str(e))
        stmt.close()
        dbConn.close()
コード例 #58
0
    def __get_connection(self):
        if self.db_connection_string in DatabaseAccess.CONNECTION_CACHE:
            connection, table_columns = DatabaseAccess.CONNECTION_CACHE[self.db_connection_string]
        else:
            # Establish the connection
            Class.forName(self.jdbc_driver_class)
            connection = DriverManager.getConnection(self.db_connection_string)

            # Get the column names
            meta = connection.getMetaData()
            res  = meta.getColumns(None, None, self.table_name, None);
            table_columns = []
            while (res.next()):
                table_columns.append(res.getString("COLUMN_NAME"))

            res.close()

            # Store the connection and column info in the cache
            DatabaseAccess.CONNECTION_CACHE[self.db_connection_string] = (connection, table_columns)

        return connection, table_columns