diff --git a/lib/commons-logging-1.0.4.jar b/lib/commons-logging-1.0.4.jar new file mode 100644 index 0000000..b73a80f Binary files /dev/null and b/lib/commons-logging-1.0.4.jar differ diff --git a/lib/commons-pool-1.6.jar b/lib/commons-pool-1.6.jar new file mode 100644 index 0000000..72ca75a Binary files /dev/null and b/lib/commons-pool-1.6.jar differ diff --git a/lib/derby.jar b/lib/derby.jar new file mode 100644 index 0000000..4941045 Binary files /dev/null and b/lib/derby.jar differ diff --git a/lib/jedis-2.0.0.jar b/lib/jedis-2.0.0.jar new file mode 100644 index 0000000..e9027ea Binary files /dev/null and b/lib/jedis-2.0.0.jar differ diff --git a/lib/log4j-1.2.17.jar b/lib/log4j-1.2.17.jar new file mode 100644 index 0000000..068867e Binary files /dev/null and b/lib/log4j-1.2.17.jar differ diff --git a/lib/sqlite-jdbc-3.7.2.jar b/lib/sqlite-jdbc-3.7.2.jar new file mode 100644 index 0000000..b0bec7b Binary files /dev/null and b/lib/sqlite-jdbc-3.7.2.jar differ diff --git a/lib/sqlite.jar b/lib/sqlite.jar new file mode 100644 index 0000000..0b47e2c Binary files /dev/null and b/lib/sqlite.jar differ diff --git a/lib/substance.jar b/lib/substance.jar new file mode 100644 index 0000000..5a623e1 Binary files /dev/null and b/lib/substance.jar differ diff --git a/src/org/kevin/db/derby/DerbyClient.java b/src/org/kevin/db/derby/DerbyClient.java new file mode 100644 index 0000000..63cedb9 --- /dev/null +++ b/src/org/kevin/db/derby/DerbyClient.java @@ -0,0 +1,65 @@ +/** + * DerbyClient.java + * kevin 2013-2-20 + * @version 0.1 + */ +package org.kevin.db.derby; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +import org.kevin.redis.data.vo.Host; + +/** + * @author kevin + * @since jdk1.6 + */ +public class DerbyClient { + + private static void testHostsAll() { + final String seplite = ", "; + DerbyDAO derbyStore = DerbyDAO.getInstance(); + // derbyStore.dropTable(); + // derbyStore.createTable(); + Connection conn = derbyStore.getConnection(); + derbyStore.execute("insert into hosts(ip, pwd, port) values('localhost', 'pwd', 6379)",conn); + derbyStore.execute("insert into hosts(ip, pwd, port) values('127.0.0.2', 'pwd', 6380)",conn); + derbyStore.execute("insert into hosts(ip, pwd, port) values('127.0.0.3', ' ', 6381)",conn); + derbyStore.execute("insert into hosts(ip, pwd, port) values('127.0.0.4', 'pwd', 6382)",conn); + // derbyStore.execute("insert into hosts values(1, 'localhost', 'pwd', 6379)", conn); + // derbyStore.execute("insert into hosts values(2, '127.0.0.2', 'pwd', 6380)", conn); + // derbyStore.execute("insert into hosts values(3, '127.0.0.3', 'pwd', 6381)", conn); + // derbyStore.execute("insert into hosts values(4, '127.0.0.4', 'pwd', 6382)", conn); + // System.out.println(conn); + ResultSet rs = derbyStore.query("select * from hosts", conn); + try { + while (rs.next()) { + // read the result set + System.out.print("["); + System.out.print("id=" + rs.getInt("id") + seplite); + System.out.print("ip=" + rs.getString("ip") + seplite); + System.out.print("pwd=" + rs.getString("pwd") + seplite); + System.out.print("port=" + rs.getInt("port")); + System.out.print("]"); + System.out.print("\r\n"); + } + } catch (SQLException e) { + e.printStackTrace(); + } + derbyStore.close(conn); + } + + private static void testDBList() { + List hosts = DerbyDB.getInstance().gethosts(); + for (Host host : hosts) { + System.out.println("[id:" + host.getId() + ", ip:" + host.getIp() + ", pwd:" + host.getPwd() + ", port:" + host.getPort() + "]"); + } + } + + public static void main(String[] args) { + testHostsAll(); + testDBList(); + } +} diff --git a/src/org/kevin/db/derby/DerbyDAO.java b/src/org/kevin/db/derby/DerbyDAO.java new file mode 100644 index 0000000..00c0b0a --- /dev/null +++ b/src/org/kevin/db/derby/DerbyDAO.java @@ -0,0 +1,163 @@ +/** + * DerbyDAO.java + * kevin 2013-2-20 + * @version 0.1 + */ +package org.kevin.db.derby; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; + +import org.apache.log4j.Logger; + +/** + * @author kevin + * @since jdk1.6 + */ +public class DerbyDAO { + + public static String driver = "org.apache.derby.jdbc.EmbeddedDriver"; + public static String protocol = "jdbc:derby:"; + + Properties props; + + Logger logger = Logger.getLogger(DerbyDAO.class); + + public DerbyDAO() { + init(); + } + + private static class DerbyDAOHolder { + static DerbyDAO instance = new DerbyDAO(); + } + + public static DerbyDAO getInstance() { + return DerbyDAOHolder.instance; + } + + private void init() { + try { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + logger.info("Load the embedded driver"); + Connection conn = null; + props = new Properties(); + props.put("user", "kevin"); + props.put("password", "edison"); + // create and connect the database named nosql + //conn = DriverManager.getConnection("jdbc:derby:nosql;create=true", props); + conn = DriverManager.getConnection("jdbc:derby:nosql;create=true"); + logger.info("create and connect to nosql"); + // System.out.println("create and connect to nosql"); + Statement s = conn.createStatement(); + try { + String checkhosts = "select 1 from hosts"; + s.execute(checkhosts); + } catch (SQLException e) { + String sql = "create table hosts(id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) primary key, ip varchar(32), pwd varchar(32), port integer, dbindex integer)"; + s.execute(sql); + logger.error("hosts not existed, create it:"); + //e.printStackTrace(); + } + //conn.setAutoCommit(false); + } catch (InstantiationException e) { + logger.error("InstantiationException:" + e.getCause().getMessage()); + // e.printStackTrace(); + } catch (IllegalAccessException e) { + logger.error("IllegalAccessException:" + e.getCause().getMessage()); + // e.printStackTrace(); + } catch (ClassNotFoundException e) { + logger.error("ClassNotFoundException:" + e.getCause().getMessage()); + // e.printStackTrace(); + } catch (SQLException e) { + logger.error("SQLException:" + e.getCause().getMessage()); + // e.printStackTrace(); + } + } + + public Connection getConnection() { + Connection conn = null; + try { + //conn = DriverManager.getConnection("jdbc:derby:nosql;create=true", props); + conn = DriverManager.getConnection("jdbc:derby:nosql;create=true"); + //logger.info("create and connect to nosql"); + logger.info("connect to db nosql"); + //conn.setAutoCommit(false); + } catch (SQLException e) { + logger.error("SQLException:" + e.getCause().getMessage()); + //e.printStackTrace(); + } + return conn; + } + + + public int execute(String sql, Connection connection) { + Statement statement; + int result = 0; + try { + statement = connection.createStatement(); + statement.setQueryTimeout(30); + result = statement.executeUpdate(sql); + statement.close(); + //result = statement.execute(sql); + } catch (SQLException e) { + logger.error("SQLException:" + e.getMessage()); + } + return result; + } + + public void dropTable() { + Connection conn = getConnection(); + String sql = "drop table hosts"; + execute(sql, conn); + close(conn); + } + + public void alertTable() { + Connection conn = getConnection(); + String sql = "alter table hosts add column dbindex integer default 0"; + execute(sql, conn); + close(conn); + } + + public ResultSet query(String sql, Connection connection) { + Statement statement; + ResultSet result = null; + try { + statement = connection.createStatement(); + statement.setQueryTimeout(30); + result = statement.executeQuery(sql); + } catch (SQLException e) { + logger.error("SQLException:" + e.getNextException()); + } + return result; + } + + public int delete(String sql, Connection connection) { + Statement statement; + int result = 0; + try { + statement = connection.createStatement(); + statement.setQueryTimeout(30); + result = statement.executeUpdate(sql); + } catch (SQLException e) { + logger.error("SQLException:" + e.getCause().getMessage()); + //e.printStackTrace(); + } + return result; + } + + public void close(Connection conn) { + try { + if (conn != null && !conn.isClosed()) { + conn.close(); + } + } catch (SQLException e) { + logger.error("SQLException:" + e.getCause().getMessage()); + //e.printStackTrace(); + } + } +} diff --git a/src/org/kevin/db/derby/DerbyDB.java b/src/org/kevin/db/derby/DerbyDB.java new file mode 100644 index 0000000..9a6f73b --- /dev/null +++ b/src/org/kevin/db/derby/DerbyDB.java @@ -0,0 +1,108 @@ +/** + * DerbyDB.java + * kevin 2013-2-20 + * @version 0.1 + */ +package org.kevin.db.derby; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.kevin.redis.data.vo.Host; +import org.kevin.redis.msg.PopMessage; + +/** + * @author kevin + * @since jdk1.6 + */ +public class DerbyDB { + + private static Connection conn = null; + private static DerbyDB derbyDB = null; + + private DerbyDB(){ + } + + public static DerbyDB getInstance(){ + if(null == derbyDB) + derbyDB = new DerbyDB(); + return derbyDB; + } + + public List gethosts(){ + DerbyDAO dbStore = DerbyDAO.getInstance(); + if(null == conn) + conn = dbStore.getConnection(); + ResultSet rs = dbStore.query("select * from hosts", conn); + List hostsList = new ArrayList(); + Host host = null; + try { + if(null != rs){ + while (rs.next()) { + // read the result set + host = new Host(); + host.setId(rs.getInt("id")); + host.setIp(rs.getString("ip")); + host.setDbIndex(rs.getInt("dbIndex")); + host.setPwd(rs.getString("pwd")); + host.setPort(rs.getInt("port")); + hostsList.add(host); + } + } + } catch (SQLException e) { + e.printStackTrace(); + //System.out.println("table is not existed"); + //e.printStackTrace(); + } + return hostsList; + } + + public void addHost(Host host){ + DerbyDAO dbStore = DerbyDAO.getInstance(); + if(null == conn) + conn = dbStore.getConnection(); + //ResultSet rs = dbStore.query("select ip, port, dbindex from hosts where ip='" + host.getIp() + "' and port=" + host.getPort() + "' and dbindex=" + host.getDbIndex(), conn); + ResultSet rs = dbStore.query("desc hosts ", conn); + if(null == rs) { + PopMessage.popWarn("No host is existed"); + dbStore.alertTable(); + } else { + try { + PopMessage.popWarn("Host table desc:" + rs.findColumn("name")); + } catch (SQLException e) { + e.printStackTrace(); + } + } + try { + if(rs.next()) + dbStore.execute("update hosts set ip='" + host.getIp() + "', port=" + host.getPort() + ", pwd='" + host.getPwd() + "' where ip='" + host.getIp() + "' and port=" + host.getPort()+ "' and dbindex=" + host.getDbIndex(), conn); + else{ + //int hostSeq = 0; + //ResultSet rseq = dbStore.query("select seq from SQLITE_SEQUENCE where name='hosts'", conn); + //if(rseq.next()) hostSeq = rseq.getInt("seq"); + //hostSeq += 1; + //dbStore.execute("insert into hosts values(" + hostSeq + ", '" + host.getIp() + "', 'pwd', " + host.getPort() +")", conn); + dbStore.execute("insert into hosts(ip, pwd, port, dbindex) values('" + host.getIp() + "', '" + host.getPwd() + "', " + host.getPort() + "', " + host.getDbIndex() +")", conn); + } + } catch (SQLException ex) { + PopMessage.popError("DB Query exception Cause: " + ex.getMessage()); + ex.printStackTrace(); + } + } + + public int removeHost(Host host){ + DerbyDAO dbStore = DerbyDAO.getInstance(); + if(null == conn) + conn = dbStore.getConnection(); + int result = dbStore.execute("delete from hosts where id=" + host.getId() + "", conn); +// try { +// conn.close(); +// } catch (SQLException e) { +// e.printStackTrace(); +// } + return result; + } +} diff --git a/src/org/kevin/db/derby/hosts.sql b/src/org/kevin/db/derby/hosts.sql new file mode 100644 index 0000000..95a241f --- /dev/null +++ b/src/org/kevin/db/derby/hosts.sql @@ -0,0 +1,7 @@ +CREATE TABLE hosts ( + id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) primary key, + ip varchar(32) NOT NULL, + pwd varchar(500), + port INTEGER, + addtime INTEGER default 0 + ); \ No newline at end of file diff --git a/src/org/kevin/db/derby/sample/SimpleApp.java b/src/org/kevin/db/derby/sample/SimpleApp.java new file mode 100644 index 0000000..28ae306 --- /dev/null +++ b/src/org/kevin/db/derby/sample/SimpleApp.java @@ -0,0 +1,262 @@ +/** + * SimpleApp.java + * kevin 2013-2-20 + * @version 0.1 + */ +package org.kevin.db.derby.sample; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Properties; + +/** + * @author kevin + * @since jdk1.6 + */ +public class SimpleApp { + /* the default framework is embedded*/ + private String framework = "embedded"; + private String driver = "org.apache.derby.jdbc.EmbeddedDriver"; + private String protocol = "jdbc:derby:"; + + public static void main(String[] args) + { + new SimpleApp().go(args); + System.out.println("SimpleApp finished"); + } + + void go(String[] args) + { + + parseArguments(args); + System.out.println("SimpleApp starting in " + framework + " mode"); + /* load the desired JDBC driver */ + loadDriver(); + + Connection conn = null; + ArrayList statements = new ArrayList(); //list of Statements, PreparedStatements + PreparedStatement psInsert = null; + PreparedStatement psUpdate = null; + Statement s = null; + ResultSet rs = null; + try + { + Properties props = new Properties(); // connection properties + // providing a user name and password is optional in the embedded + // and derbyclient frameworks + props.put("user", "user1"); + props.put("password", "user1"); + String dbName = "derbyDB"; // the name of the database + conn = DriverManager.getConnection(protocol + dbName+ ";create=true", props); + System.out.println("Connected to and created database " + dbName); + // We want to control transactions manually. Autocommit is on by + // default in JDBC. + conn.setAutoCommit(false); + /* Creating a statement object that we can use for running various + * SQL statements commands against the database.*/ + s = conn.createStatement(); + statements.add(s); + // We create a table... + s.execute("create table location(num int, addr varchar(40))"); + System.out.println("Created table location"); + // and add a few rows... + + // parameter 1 is num (int), parameter 2 is addr (varchar) + psInsert = conn.prepareStatement( + "insert into location values (?, ?)"); + statements.add(psInsert); + psInsert.setInt(1, 1956); + psInsert.setString(2, "Webster St."); + psInsert.executeUpdate(); + System.out.println("Inserted 1956 Webster"); + psInsert.setInt(1, 1910); + psInsert.setString(2, "Union St."); + psInsert.executeUpdate(); + System.out.println("Inserted 1910 Union"); + // Let's update some rows as well... + // parameter 1 and 3 are num (int), parameter 2 is addr (varchar) + psUpdate = conn.prepareStatement( + "update location set num=?, addr=? where num=?"); + statements.add(psUpdate); + psUpdate.setInt(1, 180); + psUpdate.setString(2, "Grand Ave."); + psUpdate.setInt(3, 1956); + psUpdate.executeUpdate(); + System.out.println("Updated 1956 Webster to 180 Grand"); + psUpdate.setInt(1, 300); + psUpdate.setString(2, "Lakeshore Ave."); + psUpdate.setInt(3, 180); + psUpdate.executeUpdate(); + System.out.println("Updated 180 Grand to 300 Lakeshore"); + /* + We select the rows and verify the results. + */ + rs = s.executeQuery("SELECT num, addr FROM location ORDER BY num"); + int number; // street number retrieved from the database + boolean failure = false; + if (!rs.next()) + { + failure = true; + reportFailure("No rows in ResultSet"); + } + if ((number = rs.getInt(1)) != 300) + { + failure = true; + reportFailure("Wrong row returned, expected num=300, got " + number); + } + if (!rs.next()) + { + failure = true; + reportFailure("Too few rows"); + } + if ((number = rs.getInt(1)) != 1910) + { + failure = true; + reportFailure("Wrong row returned, expected num=1910, got " + number); + } + if (rs.next()) + { + failure = true; + reportFailure("Too many rows"); + } + if (!failure) { + System.out.println("Verified the rows"); + } + // delete the table + s.execute("drop table location"); + System.out.println("Dropped table location"); + /* + We commit the transaction. Any changes will be persisted to + the database now. + */ + conn.commit(); + System.out.println("Committed the transaction"); + + if (framework.equals("embedded")) + { + try + { + DriverManager.getConnection("jdbc:derby:;shutdown=true"); + } + catch (SQLException se)//关闭数据库时会产生异常 + { + if (( (se.getErrorCode() == 50000) + && ("XJ015".equals(se.getSQLState()) ))) {//这是正常关闭 + // we got the expected exception + System.out.println("Derby shut down normally"); + // Note that for single database shutdown, the expected + // SQL state is "08006", and the error code is 45000. + } else { + // if the error code or SQLState is different, we have + // an unexpected exception (shutdown failed) + System.err.println("Derby did not shut down normally"); + printSQLException(se); + } + } + } + } + catch (SQLException sqle) + { + printSQLException(sqle); + } finally { + // release all open resources to avoid unnecessary memory usage + // ResultSet + try { + if (rs != null) { + rs.close(); + rs = null; + } + } catch (SQLException sqle) { + printSQLException(sqle); + } + // Statements and PreparedStatements + int i = 0; + while (!statements.isEmpty()) { + // PreparedStatement extend Statement + Statement st = (Statement)statements.remove(i); + try { + if (st != null) { + st.close(); + st = null; + } + } catch (SQLException sqle) { + printSQLException(sqle); + } + } + //Connection + try { + if (conn != null) { + conn.close(); + conn = null; + } + } catch (SQLException sqle) { + printSQLException(sqle); + } + } + } + private void loadDriver() { + + try { + Class.forName(driver).newInstance(); + System.out.println("Loaded the appropriate driver"); + } catch (ClassNotFoundException cnfe) { + System.err.println("\nUnable to load the JDBC driver " + driver); + System.err.println("Please check your CLASSPATH."); + cnfe.printStackTrace(System.err); + } catch (InstantiationException ie) { + System.err.println("\nUnable to instantiate the JDBC driver " + driver); + ie.printStackTrace(System.err); + } catch (IllegalAccessException iae) { + System.err.println( + "\nNot allowed to access the JDBC driver " + driver); + iae.printStackTrace(System.err); + } + } + /** + * Reports a data verification failure to System.err with the given message. + * + * @param message A message describing what failed. + */ + private void reportFailure(String message) { + System.err.println("\nData verification failed:"); + System.err.println('\t' + message); + } + /** + * Prints details of an SQLException chain to System.err. + * Details included are SQL State, Error code, Exception message. + * + * @param e the SQLException from which to print details. + */ + public static void printSQLException(SQLException e) + { + // Unwraps the entire exception chain to unveil the real cause of the + // Exception. + while (e != null) + { + System.err.println("\n----- SQLException -----"); + System.err.println(" SQL State: " + e.getSQLState()); + System.err.println(" Error Code: " + e.getErrorCode()); + System.err.println(" Message: " + e.getMessage()); + // for stack traces, refer to derby.log or uncomment this: + //e.printStackTrace(System.err); + e = e.getNextException(); + } + } + + private void parseArguments(String[] args) + { + if (args.length > 0) { + if (args[0].equalsIgnoreCase("derbyclient")) + { + framework = "derbyclient"; + driver = "org.apache.derby.jdbc.ClientDriver"; + protocol = "jdbc:derby://localhost:1527/"; + } + } + } +} diff --git a/src/org/kevin/db/derby/sample/TestDerbyBaisc.java b/src/org/kevin/db/derby/sample/TestDerbyBaisc.java new file mode 100644 index 0000000..6626d17 --- /dev/null +++ b/src/org/kevin/db/derby/sample/TestDerbyBaisc.java @@ -0,0 +1,40 @@ +/** + * TestDerbyBaisc.java + * kevin 2013-2-20 + * @version 0.1 + */ +package org.kevin.db.derby.sample; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +/** + * @author kevin + * @since jdk1.6 + */ +public class TestDerbyBaisc { + public static void main(String[] args) throws SQLException{ + try { + + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();//加载驱动 + Connection conn = DriverManager.getConnection("jdbc:derby:TESTDB;create=true");//连接数据库 + Statement st = conn.createStatement(); + st.execute("create table USER_INFO (ID INT NOT NULL,NAME VARCHAR(10) NOT NULL)");//建表 + st.executeUpdate("insert into USER_INFO(ID,NAME) values (1,'hermit')");//插入数据 + st.executeUpdate("insert into USER_INFO(ID,NAME) values (2,'test')");//插入数据 + ResultSet rs = st.executeQuery("select * from USER_INFO");//读取刚插入的数据 + while(rs.next()){ + int id = rs.getInt(1); + String name = rs.getString(2); + System.out.println("ID="+id); + System.out.println("NAME="+name); + } + } catch(Exception e){ + DriverManager.getConnection("jdbc:derby:;shutdown=true");//关闭数据库 + e.printStackTrace(); + } + } +} diff --git a/src/org/kevin/db/sqlite/DBStore.java b/src/org/kevin/db/sqlite/DBStore.java new file mode 100644 index 0000000..59f0a36 --- /dev/null +++ b/src/org/kevin/db/sqlite/DBStore.java @@ -0,0 +1,222 @@ +/** +* * DBStore.java + * kevin 2013-1-29 + * @version 0.1 + */ +package org.kevin.db.sqlite; + +/** + * @author kevin + * @since jdk1.6 + */ +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.apache.log4j.Logger; + +public class DBStore { + + Logger logger = Logger.getLogger(DBStore.class); + private static String dbName = "_nosql.db"; + private static String basedir = System.getProperty("user.dir"); + private static String dataDir = basedir + File.separator + "data"; + private Connection conn = null; + + public DBStore() { + dbName = dataDir + dbName; + try { + init(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static class DBStoreHolder { + private static DBStore instance; + public static DBStore getInstance(){ + if(null == instance) + instance = new DBStore(); + return instance; + } + } + + public static DBStore getInstance() { + return DBStoreHolder.getInstance(); + } + + public synchronized void init() { + //System.out.println("init dataDir:" + dataDir); + logger.info("init dataDir:" + dataDir); + File dbDir = new File(dataDir); + if (!dbDir.exists()) { + dbDir.mkdirs(); + } + try { + Class.forName("org.sqlite.JDBC"); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + File dbFile = new File(dbName); + if (!dbFile.exists()) { +// System.out.println("DB:" + dbName + " not existed"); + try { + dbFile.createNewFile(); + logger.info("create db file:" + dbName); + } catch (IOException e) { + e.printStackTrace(); + } + }else { + //System.out.println("DB path:" + dbName); + } + // if not existed, create it + if(!isExisted()) + createTable(); + + // update the sqlite db + //UpgreadDB.updateDB(); + } + + public Connection getConnection() { + //Connection conn = null; + close(); + try { + //System.setProperty("java.library.path", "native/Windows/amd64/sqlitejdbc.dll"); + conn = DriverManager.getConnection("jdbc:sqlite:" + dbName); + logger.info("getConnection dbName:" + dbName); + } catch (SQLException e) { + e.printStackTrace(); + System.out.println("SQLException:" + e.getMessage()); +// e.printStackTrace(); + } + return conn; + } + + //public int execute(String sql, Connection connection) { + public int execute(String sql) { + Statement statement; + int result = 0; + conn = getConnection(); + try { + statement = conn.createStatement(); + statement.setQueryTimeout(30); + result = statement.executeUpdate(sql); + //conn.commit(); + //statement.close(); + //close(conn); + close(conn); + } catch (SQLException e) { + e.printStackTrace(); + logger.error("SQLException:" + e.getMessage()); + //e.printStackTrace(); + } + + return result; + } + + public void createTable() { + conn = getConnection(); + logger.info("Start create table hosts..."); + String sql = "create table hosts(id integer primary key autoincrement, ip string, pwd string, dbindex integer, port integer)"; + //execute(sql, conn); + execute(sql); + sql = "create table systemversiom(id integer primary key autoincrement, version string, upgradeDate date, updateTime time)"; + //execute(sql, conn); + execute(sql); + logger.info("Create table hosts end"); + } + + public boolean isExisted(){ + conn = getConnection(); + //String sql = "select name from SQLITE_SEQUENCE where name='hosts'"; + String sql = "select 1 from hosts"; + ResultSet rs = query(sql); + try { + if(null != rs && rs.next()) + return true; + else{ + //return false; + logger.warn("Table is not existed."); + } + } catch (SQLException e) { + //e.printStackTrace(); + logger.error("SQLException:" + e.getMessage()); + return false; + } + //close(conn); + return false; + } + public void dropTable() { + conn = getConnection(); + String sql = "drop table hosts"; + execute(sql); + close(conn); + } + + //public ResultSet query(String sql, Connection connection) { + public ResultSet query(String sql) { + Statement statement; + ResultSet result = null; + conn = getConnection(); + try { + statement = conn.createStatement(); + statement.setQueryTimeout(30); + result = statement.executeQuery(sql); + //conn.close(); + } catch (SQLException e) { + e.printStackTrace(); + logger.error("SQLException query:" + e.getMessage()); + //return null; + //e.printStackTrace(); + } + return result; + } + + public int delete(String sql) { + Statement statement; + int result = 0; + conn = getConnection(); + try { + statement = conn.createStatement(); + //statement.setQueryTimeout(30); + result = statement.executeUpdate(sql); + //conn.commit(); + //statement.close(); + //close(conn); + close(); + } catch (SQLException e) { + e.printStackTrace(); + } + return result; + } + + public void close(Connection conn) { + try { + if (conn != null && !conn.isClosed()) { + conn.close(); + } + conn = null; + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void close() { + try { + if (conn != null && !conn.isClosed()) { + conn.close(); + } + conn = null; + } catch (SQLException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/org/kevin/db/sqlite/SQLiteJDBCLoader.java b/src/org/kevin/db/sqlite/SQLiteJDBCLoader.java new file mode 100644 index 0000000..1e0a63a --- /dev/null +++ b/src/org/kevin/db/sqlite/SQLiteJDBCLoader.java @@ -0,0 +1,252 @@ +/** + * SQLiteJDBCLoader.java + * kevin 2013-4-10 + * @version 0.1 + */ +package org.kevin.db.sqlite; + +/** + * Set the system properties, org.sqlite.lib.path, org.sqlite.lib.name, + * appropriately so that the SQLite JDBC driver can find *.dll, *.jnilib and + * *.so files, according to the current OS (win, linux, mac). + * + * The library files are automatically extracted from this project's package + * (JAR). + * + * usage: call {@link #initialize()} before using SQLite JDBC driver. + * + * @author kevin + * @since jdk1.6 + */ +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Properties; + +import org.sqlite.OSInfo; + +/** not used **/ +public class SQLiteJDBCLoader +{ + + private static boolean extracted = false; + + public static boolean initialize() { + loadSQLiteNativeLibrary(); + return extracted; + } + + static boolean getPureJavaFlag() { + return Boolean.parseBoolean(System.getProperty("sqlite.purejava", "false")); + } + + public static boolean isNativeMode() { + if (getPureJavaFlag()) + return false; + + // load the driver + initialize(); + return extracted; + } + + /** + * Computes the MD5 value of the input stream + * + * @param input + * @return + * @throws IOException + * @throws NoSuchAlgorithmException + */ + static String md5sum(InputStream input) throws IOException { + BufferedInputStream in = new BufferedInputStream(input); + + try { + MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); + DigestInputStream digestInputStream = new DigestInputStream(in, digest); + for (; digestInputStream.read() >= 0;) { + + } + ByteArrayOutputStream md5out = new ByteArrayOutputStream(); + md5out.write(digest.digest()); + return md5out.toString(); + } + catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("MD5 algorithm is not available: " + e); + } + finally { + in.close(); + } + } + + /** + * Extract the specified library file to the target folder + * + * @param libFolderForCurrentOS + * @param libraryFileName + * @param targetFolder + * @return + */ + private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName, + String targetFolder) { + String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; + final String prefix = "sqlite-" + getVersion() + "-"; + + String extractedLibFileName = prefix + libraryFileName; + File extractedLibFile = new File(targetFolder, extractedLibFileName); + + try { + if (extractedLibFile.exists()) { + // test md5sum value + String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath)); + String md5sum2 = md5sum(new FileInputStream(extractedLibFile)); + + if (md5sum1.equals(md5sum2)) { + return loadNativeLibrary(targetFolder, extractedLibFileName); + } + else { + // remove old native library file + boolean deletionSucceeded = extractedLibFile.delete(); + if (!deletionSucceeded) { + throw new IOException("failed to remove existing native library file: " + + extractedLibFile.getAbsolutePath()); + } + } + } + + // extract file into the current directory + InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); + FileOutputStream writer = new FileOutputStream(extractedLibFile); + byte[] buffer = new byte[1024]; + int bytesRead = 0; + while ((bytesRead = reader.read(buffer)) != -1) { + writer.write(buffer, 0, bytesRead); + } + + writer.close(); + reader.close(); + + if (!System.getProperty("os.name").contains("Windows")) { + try { + Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() }) + .waitFor(); + } + catch (Throwable e) {} + } + + return loadNativeLibrary(targetFolder, extractedLibFileName); + } + catch (IOException e) { + System.err.println(e.getMessage()); + return false; + } + + } + + private static synchronized boolean loadNativeLibrary(String path, String name) { + File libPath = new File(path, name); + if (libPath.exists()) { + + try { + System.load(new File(path, name).getAbsolutePath()); + return true; + } + catch (UnsatisfiedLinkError e) { + System.err.println(e); + return false; + } + + } + else + return false; + } + + private static void loadSQLiteNativeLibrary() { + if (extracted) + return; + + boolean runInPureJavaMode = getPureJavaFlag(); + if (runInPureJavaMode) { + extracted = false; + return; + } + + // Try loading library from org.sqlite.lib.path library path */ + String sqliteNativeLibraryPath = System.getProperty("org.sqlite.lib.path"); + String sqliteNativeLibraryName = System.getProperty("org.sqlite.lib.name"); + if (sqliteNativeLibraryName == null) + sqliteNativeLibraryName = System.mapLibraryName("sqlitejdbc"); + + if (sqliteNativeLibraryPath != null) { + if (loadNativeLibrary(sqliteNativeLibraryPath, sqliteNativeLibraryName)) { + extracted = true; + return; + } + } + + // Load the os-dependent library from a jar file + sqliteNativeLibraryPath = "/native/" + OSInfo.getNativeLibFolderPathForCurrentOS(); + + if (SQLiteJDBCLoader.class.getResource(sqliteNativeLibraryPath + "/" + sqliteNativeLibraryName) == null) { + // use nested VM version + return; + } + + // temporary library folder + String tempFolder = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); + /* Try extracting the library from jar */ + if (extractAndLoadLibraryFile(sqliteNativeLibraryPath, sqliteNativeLibraryName, tempFolder)) { + extracted = true; + return; + } + + extracted = false; + return; + } + + private static void getNativeLibraryFolderForTheCurrentOS() { + String osName = OSInfo.getOSName(); + String archName = OSInfo.getArchName(); + + } + + public static int getMajorVersion() { + String[] c = getVersion().split("\\."); + return (c.length > 0) ? Integer.parseInt(c[0]) : 1; + } + + public static int getMinorVersion() { + String[] c = getVersion().split("\\."); + return (c.length > 1) ? Integer.parseInt(c[1]) : 0; + } + + public static String getVersion() { + + URL versionFile = SQLiteJDBCLoader.class.getResource("/META-INF/maven/org.xerial/sqlite-jdbc/pom.properties"); + if (versionFile == null) + versionFile = SQLiteJDBCLoader.class.getResource("/META-INF/maven/org.xerial/sqlite-jdbc/VERSION"); + + String version = "unknown"; + try { + if (versionFile != null) { + Properties versionData = new Properties(); + versionData.load(versionFile.openStream()); + version = versionData.getProperty("version", version); + version = version.trim().replaceAll("[^0-9\\.]", ""); + } + } + catch (IOException e) { + System.err.println(e); + } + return version; + } + +} + diff --git a/src/org/kevin/db/sqlite/SqliteClient.java b/src/org/kevin/db/sqlite/SqliteClient.java new file mode 100644 index 0000000..48348be --- /dev/null +++ b/src/org/kevin/db/sqlite/SqliteClient.java @@ -0,0 +1,62 @@ +/** + * SqliteClient.java + * kevin 2013-2-11 + * @version 0.1 + */ +package org.kevin.db.sqlite; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +import org.kevin.redis.data.vo.Host; + +/** + * @author kevin + * @since jdk1.6 + */ +public class SqliteClient { + + private void testsqliteAll() { + final String seplite = ", "; + DBStore dbStore = DBStore.getInstance(); + dbStore.dropTable(); + dbStore.createTable(); + Connection conn = dbStore.getConnection(); + dbStore.execute( + "insert into hosts values(1, 'localhost', 'pwd', 6390)"); + dbStore.execute( + "insert into hosts values(2, '127.0.0.2', 'pwd', 6390)"); + dbStore.execute( + "insert into hosts values(3, '127.0.0.3', 'pwd', 6390)"); + dbStore.execute( + "insert into hosts values(4, '127.0.0.4', 'pwd', 6390)"); + // System.out.println(conn); + ResultSet rs = dbStore.query("select * from hosts"); + try { + while (rs.next()) { + // read the result set + System.out.print("["); + System.out.print("id=" + rs.getInt("id") + seplite); + System.out.print("ip=" + rs.getString("ip") + seplite); + System.out.print("pwd=" + rs.getString("pwd") + seplite); + System.out.print("port=" + rs.getInt("port")); + System.out.print("]"); + System.out.print("\r\n"); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + private static void testDBList(){ + List hosts = SqliteDB.getInstance().gethosts(); + for(Host host : hosts){ + System.out.println("[id:" + host.getId() + ", ip:" + host.getIp() + ", pwd:" + host.getPwd() + ", port:" + host.getPort() + "]"); + } + } + public static void main(String[] args) { + testDBList(); + } +} diff --git a/src/org/kevin/db/sqlite/SqliteDB.java b/src/org/kevin/db/sqlite/SqliteDB.java new file mode 100644 index 0000000..53e6944 --- /dev/null +++ b/src/org/kevin/db/sqlite/SqliteDB.java @@ -0,0 +1,102 @@ +/** + * DB.java + * kevin 2013-2-11 + * @version 0.1 + */ +package org.kevin.db.sqlite; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.kevin.redis.data.vo.Host; + +/** + * @author kevin + * @since jdk1.6 + */ +public class SqliteDB { + + //private static Connection conn = null; + + private static SqliteDB sqliteDB = null; + + public static SqliteDB getInstance(){ + if(null == sqliteDB) + sqliteDB = new SqliteDB(); + return sqliteDB; + } + public List gethosts(){ + DBStore dbStore = DBStore.getInstance(); +// if(null == conn) +// conn = dbStore.getConnection(); + //ResultSet rs = dbStore.query("select * from hosts", conn); + ResultSet rs = dbStore.query("select * from hosts"); + List hostsList = new ArrayList(); + Host host = null; + try { + if(null != rs){ + while (rs.next()) { + // read the result set + host = new Host(); + host.setId(rs.getInt("id")); + host.setIp(rs.getString("ip")); + host.setPwd(rs.getString("pwd")); + host.setDbIndex(rs.getInt("dbIndex")); + host.setPort(rs.getInt("port")); + hostsList.add(host); + } + } + } catch (SQLException e) { + e.printStackTrace(); + System.out.println("Table is not existed"); + //e.printStackTrace(); + } + dbStore.close(); + return hostsList; + } + + public void addHost(Host host){ + DBStore dbStore = DBStore.getInstance(); +// if(null == conn) +// conn = dbStore.getConnection(); + String sql = "select ip, port, dbindex from hosts where ip='" + host.getIp() + "' and port=" + host.getPort() + " and dbindex=" + host.getDbIndex(); + //System.out.println(sql); + ResultSet rs = dbStore.query(sql); + boolean isexisted = false; + try { + isexisted = rs.next(); + dbStore.close(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + if(isexisted){ + sql = "update hosts set ip='" + host.getIp() + "', port=" + host.getPort() + ", pwd='" + host.getPwd() + "', dbindex=" + host.getDbIndex() + " where ip='" + host.getIp() + "' and port=" + host.getPort() + " and dbindex=" + host.getDbIndex(); + //System.out.println("update: " + sql); + dbStore.execute(sql); + } else { + //int hostSeq = 0; + //ResultSet rseq = dbStore.query("select seq from SQLITE_SEQUENCE where name='hosts'", conn); + //if(rseq.next()) hostSeq = rseq.getInt("seq"); + //hostSeq += 1; + //dbStore.execute("insert into hosts values(" + hostSeq + ", '" + host.getIp() + "', 'pwd', " + host.getPort() +")", conn); + sql = "insert into hosts(id, ip, pwd, dbindex, port) values(NULL, '" + host.getIp() + "', '" + host.getPwd() + "', " + host.getDbIndex() + ", " + host.getPort() +")"; + System.out.println("insert: " + sql); + dbStore.execute(sql); + } + //dbStore.close(); + } + + public int removeHost(Host host){ + DBStore dbStore = DBStore.getInstance(); +// if(null == conn) +// conn = dbStore.getConnection(); + String sql = "delete from hosts where id=" + host.getId() + ""; + System.out.println("Delete SQL:" + sql); + int result = dbStore.delete(sql); + //dbStore.close(); + return result; + } + +} diff --git a/src/org/kevin/db/sqlite/sample/Test.java b/src/org/kevin/db/sqlite/sample/Test.java new file mode 100644 index 0000000..9a08aef --- /dev/null +++ b/src/org/kevin/db/sqlite/sample/Test.java @@ -0,0 +1,42 @@ +/** + * Test.java + * kevin 2013-4-16 + * @version 0.1 + */ +package org.kevin.db.sqlite.sample; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; + +/** + * @author kevin + * @since jdk1.6 + */ +public class Test { + public static void main(String[] args) throws Exception { +// System.setProperty("java.library.path", "."); + + Class.forName("org.sqlite.JDBC"); + Connection conn = DriverManager.getConnection("jdbc:sqlite:test3.db"); + //建立事务机制,禁止自动提交,设置回滚点 + conn.setAutoCommit(false); + + Statement stat = conn.createStatement(); + stat.executeUpdate("create table people (name, occupation);"); + stat.executeUpdate("insert into people values ('Gandhi', 'politics');"); + stat.executeUpdate("insert into people values ('Turing', 'computers');"); + stat.executeUpdate("insert into people values ('Wittgenstein', 'smartypants');"); + conn.commit(); + + ResultSet rs = stat.executeQuery("select * from people;"); + while (rs.next()) { + System.out.println("name = " + rs.getString("name")); + System.out.println("occupation = " + rs.getString("occupation")); + } + + rs.close(); + conn.close(); + } +} diff --git a/src/org/kevin/db/sqlite/sample/TestJDBCSqlite.java b/src/org/kevin/db/sqlite/sample/TestJDBCSqlite.java new file mode 100644 index 0000000..48fcc67 --- /dev/null +++ b/src/org/kevin/db/sqlite/sample/TestJDBCSqlite.java @@ -0,0 +1,75 @@ +/** + * TestJDBCSqlite.java + * kevin 2013-4-16 + * @version 0.1 + */ +package org.kevin.db.sqlite.sample; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; + +/** + * @author kevin + * @since jdk1.6 + */ +public class TestJDBCSqlite { + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + try { + long start = System.currentTimeMillis(); + + // 连接SQLite的JDBC + Class.forName("org.sqlite.JDBC"); + + // 建立一个数据库名winnie.db的连接,如果不存在就在当前目录下创建之 + // 红色部分路径要求全小写,大写会报错 + Connection conn = DriverManager + .getConnection("jdbc:sqlite:winnie.db"); + long end = System.currentTimeMillis(); + System.out.println("创建数据库文件并连接耗费时间:" + (end - start)); + // 关闭连接 + conn.close(); + + start = System.currentTimeMillis(); + conn = DriverManager.getConnection("jdbc:sqlite:winnie.db"); + end = System.currentTimeMillis(); + System.out.println("数据库连接耗费时间:" + (end - start)); + + start = System.currentTimeMillis(); + Statement stat = conn.createStatement(); + // 创建一个表,两列 + stat.executeUpdate("create table tbl1(name varchar(20), salary int);"); + end = System.currentTimeMillis(); + System.out.println("创建表耗费时间:" + (end - start)); + + // 插入数据 + start = System.currentTimeMillis(); + stat.executeUpdate("insert into tbl1 values('ZhangSan',8000);"); + stat.executeUpdate("insert into tbl1 values('LiSi',7800);"); + stat.executeUpdate("insert into tbl1 values('WangWu',5800);"); + stat.executeUpdate("insert into tbl1 values('ZhaoLiu',9100);"); + end = System.currentTimeMillis(); + System.out.println("插入四行数据耗费时间:" + (end - start)); + + start = System.currentTimeMillis(); + ResultSet rs = stat.executeQuery("select * from tbl1;"); // 查询数据 + while (rs.next()) { // 将查询到的数据打印出来 + System.out.print("name = " + rs.getString("name") + " "); // 列属性一 + System.out.println("salary = " + rs.getString("salary")); // 列属性二 + } + rs.close(); + end = System.currentTimeMillis(); + System.out.println("查询数据耗费时间:" + (end - start)); + + conn.close(); // 结束数据库的连接 + + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/org/kevin/db/sqlite/upgrade/UpgreadDB.java b/src/org/kevin/db/sqlite/upgrade/UpgreadDB.java new file mode 100644 index 0000000..7314f59 --- /dev/null +++ b/src/org/kevin/db/sqlite/upgrade/UpgreadDB.java @@ -0,0 +1,79 @@ +/** + * UpgreadDB.java + * kevin 2013-4-24 + * @version 0.1 + */ +package org.kevin.db.sqlite.upgrade; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.kevin.db.sqlite.DBStore; + +/** + * @author kevin + * @since jdk1.6 + */ +public class UpgreadDB { + + private static int current_version = 13; + + private void updateDB(){ + String sql = "select version from systemversiom"; + ResultSet rs = DBStore.getInstance().query(sql); + String version = "1.0"; + if(null!= rs){ + try { + while(rs.next()){ + version = rs.getString("version"); + } + } catch (SQLException e) { + e.printStackTrace(); + } + int _version = Integer.valueOf(version.replaceAll(".", "")); + while(_version < current_version){ + //updateVersion13(); + + try { + Class clazz = Class.forName("org.kevin.db.sqlite.DBStore"); + Method mtd = clazz.getMethod(("updateVersion" + _version), new Class[]{String.class}); + Object obj = (Object) clazz.newInstance(); + mtd.invoke(obj,new Object[]{"Jacky"}); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + _version++; + } + } + } + + private void updateVersion13(){ + DBStore dbStore = DBStore.getInstance(); + String sql = "delete from systemversiom"; + dbStore.execute(sql); + sql = "insert into systemversiom(id, version, upgradeDate, updateTime) values(NULL, '1.3', date(), time())"; + dbStore.execute(sql); + } + +} diff --git a/src/org/kevin/icon/brickwall.ico b/src/org/kevin/icon/brickwall.ico new file mode 100644 index 0000000..24718d4 Binary files /dev/null and b/src/org/kevin/icon/brickwall.ico differ diff --git a/src/org/kevin/image/add.png b/src/org/kevin/image/add.png new file mode 100644 index 0000000..efe6c29 Binary files /dev/null and b/src/org/kevin/image/add.png differ diff --git a/src/org/kevin/image/nosql.jpg b/src/org/kevin/image/nosql.jpg new file mode 100644 index 0000000..92524a8 Binary files /dev/null and b/src/org/kevin/image/nosql.jpg differ diff --git a/src/org/kevin/image/nosql.png b/src/org/kevin/image/nosql.png new file mode 100644 index 0000000..f82c93c Binary files /dev/null and b/src/org/kevin/image/nosql.png differ diff --git a/src/org/kevin/redis/Converter.java b/src/org/kevin/redis/Converter.java new file mode 100644 index 0000000..7ade123 --- /dev/null +++ b/src/org/kevin/redis/Converter.java @@ -0,0 +1,15 @@ +/** + * Converter.java + * 2011 Dec 12, 2011 + */ +package org.kevin.redis; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class Converter { + public static String doConvert(String input) { + return input + " is converted."; + } +} diff --git a/src/org/kevin/redis/RedisDB.java b/src/org/kevin/redis/RedisDB.java new file mode 100644 index 0000000..bfd77ed --- /dev/null +++ b/src/org/kevin/redis/RedisDB.java @@ -0,0 +1,820 @@ +/** + * RedisDB.java + * kevin 2013-2-5 + * @version 0.1 + */ +package org.kevin.redis; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Image; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.IOException; +import java.util.List; + +import javax.imageio.ImageIO; +import javax.swing.BorderFactory; +import javax.swing.BoxLayout; +import javax.swing.GroupLayout; +import javax.swing.GroupLayout.Alignment; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenuBar; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.LayoutStyle.ComponentPlacement; +import javax.swing.SwingConstants; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.border.LineBorder; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; + +import org.kevin.db.sqlite.SqliteDB; +import org.kevin.redis.adapter.ComponentResizeAdapter; +import org.kevin.redis.adapter.MainTreeResizeAdapter; +import org.kevin.redis.comboBox.HistoryComboBox; +import org.kevin.redis.constant.RedisConstants; +import org.kevin.redis.data.vo.Host; +import org.kevin.redis.menu.NoSQLMenu; +import org.kevin.redis.msg.PopMessage; +import org.kevin.redis.operation.DBOperation; +import org.kevin.redis.tree.DBTree; +import org.kevin.redis.window.AddWindow; +import org.kevin.redis.window.CopyWindow; +import org.kevin.redis.window.EditWindow; + +/** + * @author kevin + * @since jdk1.6 + */ +public class RedisDB { + /** + * + */ + private JFrame frame; + private static JPanel toolbar_panel, tree_panel, status_panel, dataTable_panel; + private JTextField ip_textField, port_textField, pwd_textField; + private JLabel lblHistory, lblIp, lblPort, lbldbIndex, lblPwd; + private JButton search_btn; + private JLabel lblOptstatuslb; + private JTree db_tree; + private static JScrollPane jsp, toolJsp; + private static JComboBox history_comboBox; + private JComboBox jcmbHosts; + private JComboBox dbIndex_comboBox; + private final String status = "Status:"; + + /** + * Auto-generated main method to display this JFrame + */ + public static void main(String[] args) { + EventQueue.invokeLater(new Runnable() { + public void run() { + try { + RedisDB redisDB = new RedisDB(); + redisDB.frame.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + public RedisDB() { + initGUI(); + } + + private void initGUI() { + frame = new JFrame(); + frame.setTitle("Redis DB"); + //frame.setBounds(100, 100, 669, 486); + frame.setBounds(200, 200, 720, 600); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + try { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); + } catch (ClassNotFoundException e2) { + // TODO Auto-generated catch block + e2.printStackTrace(); + } catch (InstantiationException e2) { + // TODO Auto-generated catch block + e2.printStackTrace(); + } catch (IllegalAccessException e2) { + // TODO Auto-generated catch block + e2.printStackTrace(); + } catch (UnsupportedLookAndFeelException e2) { + // TODO Auto-generated catch block + e2.printStackTrace(); + } + //frame.addComponentListener(new ComponentResizeAdapter(frame)); + + String src = "/org/kevin/image/nosql.jpg"; + //String src = "/org/kevin/image/nosql.png"; + Image image; + try { + //create the image icon obj + image = ImageIO.read(this.getClass().getResource(src)); + frame.setIconImage(image); //set the icon + } catch (IOException e1) { + e1.printStackTrace(); + } + + try { + //setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + //getContentPane().setLayout(null); + frame.setTitle("Java NoSQL Client " + RedisConstants.CLIENT_VERSION); + { + JMenuBar menu = new NoSQLMenu().initManu(); + frame.setJMenuBar(menu); + //menu.setBounds(10, 10, 180, 450); + } + { + toolbar_panel = new JPanel(); + toolbar_panel.setBorder(new LineBorder(new Color(0, 0, 0))); + toolbar_panel.setBounds(10, 10, 640, 50); + //frame.setLocationRelativeTo(null); + } + { +// JScrollPane tools_short = new ToolsPanel().createToolsPanel(); +// frame.getContentPane().add(tools_short); +// tools_short.setAutoscrolls(true); +// tools_short.setBounds(230, 10, 220, 300); + //frame.getContentPane().setLayout(new GridLayout(1, 2, 0, 0)); + } + { + tree_panel = new JPanel(); + tree_panel.setBorder(new LineBorder(new Color(0, 0, 0))); + tree_panel.setToolTipText("DB tree"); + tree_panel.addComponentListener(new MainTreeResizeAdapter(tree_panel));// for resize + //tree_panel.setBounds(10, 50, 200, 400); + //frame.setLocationRelativeTo(null); + } + JPanel searchPanel = new JPanel(); + searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.X_AXIS)); + final JTextField searchText = new JTextField("*"); + final JButton filterBtn = new JButton("Filter"); + filterBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String action = e.getActionCommand(); + //PopMessage.popMsg("searchBtn Name : " + searchBtn.getActionCommand()+ ", action:" + action); + if(filterBtn.getActionCommand().equalsIgnoreCase(action)){ + String filterText = searchText.getText(); + db_tree = DBTree.getDBTree().getkeys(filterText); + jsp = new JScrollPane(db_tree); + //jsp = DBTree.getDBTree().getTreePanel(filterText); + tree_panel.add(jsp, 0); + //jsp.setBounds(10, 70, 200, 380); + resize(); + //int width = tree_panel.getWidth(); + //int height = tree_panel.getHeight(); + //jsp.setPreferredSize(new Dimension(width, height)); + //tree.setPreferredSize(new Dimension()) + //jsp.setBounds(10, 70, (width - 20), (height - 80)); + // comment the updateUI as the resize to do it + tree_panel.updateUI(); + lblOptstatuslb.setText(status + "Query success"); + } + } + }); + + searchPanel.add(searchText); + searchPanel.add(filterBtn); + //JScrollPane jspTree = new JScrollPane(); + //jspTree.add(searchPanel); + tree_panel.add(searchPanel); + searchPanel.setBounds(10, 10, 220, 25); + searchPanel.setVisible(true); + + // Add the operation buttons add delete edit + JPanel actionPanel = new JPanel(); + actionPanel.setLayout(new BoxLayout(actionPanel, BoxLayout.X_AXIS)); + + final JButton addBtn = new JButton("ADD"); + //ImageIcon icon = new ImageIcon("src/org/kevin/image/add.png"); + //final JButton addBtn = new JButton(icon); + //final ImageButton addBtn = new ImageButton(icon); + addBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + //String action = e.getActionCommand(); + AddWindow.instance().showWindow(); + //PopMessage.popMsg("addBtn Name : " + addBtn.getActionCommand()+ ", action:" + action); + } + }); + actionPanel.add(addBtn); + + final JButton copyBtn = new JButton("COPY"); + copyBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + //String action = e.getActionCommand(); + //AddWindow.instance().showWindow(); + //String inputValue = JOptionPane.showInputDialog("Please input a value"); + + int selectedNode = db_tree.getSelectionCount(); + if(0 == selectedNode || null == db_tree.getSelectionPath()) + PopMessage.popMsg("No key was selected"); + else { + Object selected = db_tree.getSelectionModel().getSelectionPath().getLastPathComponent(); + DefaultMutableTreeNode node = (DefaultMutableTreeNode)selected; + if(null!= node && node.isRoot()){ + PopMessage.popMsg("The Key [" + node.toString() + "] is uneditable" ); + } else { + TreePath parent = db_tree.getSelectionPath().getParentPath(); + if(null == parent){ + PopMessage.popMsg("The Key [" + node.toString() + "] is uneditable" ); + } else { + //String inputValue = JOptionPane.showInputDialog(null, "Please input a value", "Copy", 1); + //PopMessage.popMsg("copyBtn Name : " + copyBtn.getActionCommand()+ ", action:" + action+ ", inputValue:" + inputValue ); + //if(null != inputValue && !inputValue.isEmpty()){ + CopyWindow.instance().showWindow(node.toString()); + //System.out.println("show COPY window"); + + //filterBtn.doClick(); + //} + } + } + } + } + }); + actionPanel.add(copyBtn); + //addBtn.setBounds(10, 5, 20, 10); + + final JButton delBtn = new JButton("DEL"); + delBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + //String action = e.getActionCommand(); + int selectedNode = db_tree.getSelectionCount(); + if(0 == selectedNode || null == db_tree.getSelectionPath()) + PopMessage.popMsg("No key was selected"); + else { + TreePath selectedPath = db_tree.getSelectionPath(); + Object selectedObj = selectedPath.getPathComponent(selectedNode); + //PopMessage.popMsg("selectedNode:" + selectedNode + ", selected:" + selectedObj ); + JDialog.setDefaultLookAndFeelDecorated(true); + int response = JOptionPane.showConfirmDialog(null, "Do you want to delete key [" + selectedObj.toString() + "]", "Confirm", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + + if(JOptionPane.YES_OPTION == response){ + int affectKeys = new DBOperation().remove(selectedObj.toString()); + if(affectKeys > 0){ + PopMessage.popMsg("Remove the key ["+ selectedObj.toString() +"]' success" ); + } else { + PopMessage.popWarn("Remove the key ["+ selectedObj.toString() +"]' fail" ); + } + //Robot robottest; + //try { + // robottest = new Robot(); + // robottest.waitForIdle(); + // robottest.mousePress(InputEvent.BUTTON1_MASK ); + // } catch (AWTException e1) { + // e1.printStackTrace(); + // } + filterBtn.doClick(); + //String tableype = RedistDataManagement.getType(selectedObj.toString()); + } else { + // Do nothing + } + } + } + }); + actionPanel.add(delBtn); + //delBtn.setBounds(10, 5, 20, 10); + + final JButton editBtn = new JButton("EDIT"); + editBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + + //String action = e.getActionCommand(); + int selectedNode = db_tree.getSelectionCount(); + if(0 == selectedNode || null == db_tree.getSelectionPath()) + PopMessage.popMsg("No key was selected"); + else { + //TreePath selectedPath = db_tree.getSelectionPath(); + //Object selectedObj = selectedPath.getPathComponent(selectedNode); + + //Object selected = db_tree.getLastSelectedPathComponent(); + Object selected = db_tree.getSelectionModel().getSelectionPath().getLastPathComponent(); + DefaultMutableTreeNode node = (DefaultMutableTreeNode)selected; + if(null!= node && node.isRoot()){ + PopMessage.popMsg("The Key [" + node.toString() + "] is uneditable" ); + } else { + TreePath parent = db_tree.getSelectionPath().getParentPath(); + if(null == parent){ + PopMessage.popMsg("The Key [" + node.toString() + "] is uneditable" ); + } else { + //PopMessage.popMsg("The Key [" + node.toString() + "]" ); + EditWindow.instance().showWindow(node.toString()); + //EditWindow.instance().showWindow(); + } + //String pathNode = node.getParent().getPath().getLastPathComponent().toString(); + //RedisTable.updateDetail(pathNode); + } + } + } + }); + actionPanel.add(editBtn); + //editBtn.setBounds(10, 5, 20, 10); + //JScrollPane actionJsp = new JScrollPane(); + //actionJsp.add(actionPanel); + tree_panel.add(actionPanel); + //tree_panel.add(actionJsp); + actionPanel.setBounds(10, 40, 220, 25); + actionPanel.setVisible(true); + { + db_tree = DBTree.getDBTree().createTree(); + //frame.getContentPane().add(jRedisTree); + //db_tree.setVisible(true); + db_tree.setBounds(10, 70, 200, 380); + jsp = new JScrollPane(db_tree); + //db_tree.setBounds(20, 20, tree_panel.getX(), tree_panel.getY()); + //JScrollPane jspTree = new JScrollPane(); + //jspTree.add(db_tree); + //jspTree.setVisible(true); + //tree_panel.add(db_tree); + tree_panel.add(jsp); + //int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; + //int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; + //getContentPane().add(jsp, BorderLayout.CENTER); + //tree_panel.add(jsp); + } + { +// JScrollPane pane = RedisTable.componentInfo(); +// //frame.getContentPane().add(pane); +// tree_panel.add(pane); +// tree_panel.setLayout(new GridLayout(1, 2, 0, 0)); +// //pane.setBounds(x, y, width, height); +// pane.setAutoscrolls(true); +// pane.setBounds(20, 10, 220, 300); + } + { + status_panel = new JPanel(); + status_panel.setBorder(new LineBorder(new Color(0, 0, 0))); + } + { + dataTable_panel = new JPanel(); + //dataTable_panel.setBorder(new LineBorder(new Color(0, 0, 0))); + dataTable_panel.setBorder(BorderFactory.createTitledBorder("Table Data")); + dataTable_panel.addComponentListener(new ComponentResizeAdapter(dataTable_panel)); + //frame.add(dataTable_panel); + } + { + // the status process + lblOptstatuslb = new JLabel(status); + +// histBox = new JComboBox(); +// histBox.addItem("default(212)"); +// top_panel.add(histBox); +// frame.setLocationRelativeTo(null); + + lblIp = new JLabel("IP:"); + lblIp.setHorizontalAlignment(SwingConstants.RIGHT); + frame.setLocationRelativeTo(null); + + ip_textField = new JTextField(); + ip_textField.setText("192.168.30.212"); + ip_textField.setColumns(10); + + lblPort = new JLabel("Port:"); + lblPort.setHorizontalAlignment(SwingConstants.RIGHT); + frame.setLocationRelativeTo(null); + + port_textField = new JTextField(); + port_textField.setText("6380"); + port_textField.setColumns(10); + + lblPwd = new JLabel("PWD:"); + pwd_textField = new JTextField(); + pwd_textField.setColumns(10); + + lbldbIndex = new JLabel("DB:"); + dbIndex_comboBox = new JComboBox(); + for(int i=0; i < 16; i++) + dbIndex_comboBox.addItem("" + i); + + search_btn = new JButton("Search"); + search_btn.addMouseListener(new MouseAdapter() { + @SuppressWarnings("unchecked") + @Override + public void mouseClicked(MouseEvent e) { + /* + String ipStr= ip_textField.getText(); + String portStr= port_textField.getText(); + String pwdStr= pwd_textField.getText(); + String dbIndexStr= dbIndex_comboBox.getSelectedItem().toString(); + + Integer dbIndex = Integer.valueOf(dbIndexStr); + RedisConstants.REDIS_SERVER_IP = ipStr; + RedisConstants.REDIS_SERVER_PWD = pwdStr; + RedisConstants.REDIS_SERVER_DBINDEX = dbIndex; + Integer port = Integer.valueOf(portStr); + try{ + RedisConstants.REDIS_SERVER_PORT = "".equals(port)? 6379:port;//6379 is the default port for redis + port_textField.setBackground(Color.WHITE); + } catch (Exception ex ){ + port_textField.setBackground(Color.red); + lblOptstatuslb.setText(status + "port error"); + return; + }*/ + constantHostInfo(); + // add host + Host host = new Host(); + host.setIp(RedisConstants.REDIS_SERVER_IP); + host.setPort(RedisConstants.REDIS_SERVER_PORT); + //host.setDbIndex(dbIndex); + host.setDbIndex(RedisConstants.REDIS_SERVER_DBINDEX); + //host.setPwd(pwdStr); + host.setPwd(RedisConstants.REDIS_SERVER_PWD); + //DerbyDB.getInstance().addHost(host); + SqliteDB.getInstance().addHost(host); + + // fresh the history + String newaddObj = host.getIp() + ":" + host.getPort() + ":" + host.getDbIndex() + ":" + host.getPwd(); + history_comboBox.removeItem(newaddObj); + history_comboBox.addItem(newaddObj); + history_comboBox.setSelectedItem(newaddObj); + + db_tree = DBTree.getDBTree().getkeys("*"); + //db_tree.setBounds(10, 10, 200, 430); + + //int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; + //int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; + //JScrollPane jsp = new JScrollPane(db_tree, v, h); + jsp = new JScrollPane(db_tree); + //jsp = DBTree.getDBTree().getTreePanel("*"); + //tree_panel.add(jsp, BorderLayout.CENTER); + tree_panel.add(jsp, 0); + //jsp.setVisible(true); + + //jsp.setBounds(10, 70, 200, 380); + int width = tree_panel.getWidth(); + int height = tree_panel.getHeight(); + //jsp.setPreferredSize(new Dimension(width, height)); + //tree.setPreferredSize(new Dimension()) + jsp.setBounds(10, 70, (width - 20), (height - 80)); + //resize(); + + //tree_panel.add(db_tree, 0); + lblOptstatuslb.setText(status + "Query success"); + //String about_content = "Test redis pop msg."; + //JOptionPane.showMessageDialog(null, about_content, "redis data", JOptionPane.INFORMATION_MESSAGE); + } + }); + } + + lblHistory = new JLabel("History:"); + history_comboBox = new JComboBox(); + history_comboBox.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + jcmbHosts = (JComboBox) e.getSource(); + String host = (String) jcmbHosts.getSelectedItem(); + String[] ipAndPort = host.split(":"); + ip_textField.setText(ipAndPort[0]); + port_textField.setText(ipAndPort[1]); + dbIndex_comboBox.setSelectedItem(ipAndPort[2]); + if(ipAndPort.length > 3) + pwd_textField.setText(ipAndPort[3]); + else + pwd_textField.setText(""); + // reinit the db connection pool + constantHostInfo(); + HistoryComboBox.getInstances().reInitConnectPool(); + + } + }); + //List hosts = DerbyDB.getInstance().gethosts(); + List hosts = SqliteDB.getInstance().gethosts(); + for(Host host : hosts){ + //System.out.println("[id:" + host.getId() + ", ip:" + host.getIp() + ", pwd:" + host.getPwd() + ", port:" + host.getPort() + "]"); + history_comboBox.addItem(host.getIp() + ":" + host.getPort() + ":" + host.getDbIndex() + ":" + host.getPwd()); + } + //history_comboBox.addItem("192.168.30.212:6380"); + //history_comboBox.addItem("192.168.30.212:6379"); + //history_comboBox.setSelectedIndex(0); + + toolJsp = new JScrollPane(); + JPanel jpa = new JPanel(); + jpa.add(lblHistory); + jpa.add(history_comboBox); + //history_comboBox.setBounds(10, 0, 100, 15); + + jpa.add(lblIp); + lblIp.setBounds(180, 0, 50, 15); + jpa.add(ip_textField); + //ip_textField.setBounds(250, 0, 100, 15); + + jpa.add(lblPort); + //lblPort.setBounds(260, 0, 50, 15); + jpa.add(port_textField); + //port_textField.setBounds(320, 0, 20, 15); + + jpa.add(lbldbIndex); + //lbldbIndex.setBounds(380, 0, 50, 15); + jpa.add(dbIndex_comboBox); + //dbIndex_comboBox.setBounds(440, 0, 50, 15); + + jpa.add(lblPwd); + //lblPwd.setBounds(500, 0, 50, 15); + jpa.add(pwd_textField); + //pwd_textField.setBounds(600, 0, 50, 15); + + jpa.add(search_btn); + //search_btn.setBounds(660, 0, 100, 15); + //jpa.setVisible(true); + + //toolJsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + //toolJsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + + GroupLayout groupLayout = new GroupLayout(frame.getContentPane()); + groupLayout.setHorizontalGroup( + groupLayout.createParallelGroup(Alignment.LEADING) + .addGroup(groupLayout.createSequentialGroup() + .addContainerGap() + .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) + .addComponent(toolbar_panel, GroupLayout.DEFAULT_SIZE, 633, Short.MAX_VALUE) + .addComponent(status_panel, GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE) + .addGroup(groupLayout.createSequentialGroup() + .addComponent(tree_panel, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE) + .addGap(18) + .addComponent(dataTable_panel, GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE))) + .addContainerGap()) + ); + groupLayout.setVerticalGroup( + groupLayout.createParallelGroup(Alignment.LEADING) + .addGroup(groupLayout.createSequentialGroup() + .addGap(1) + .addComponent(toolbar_panel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) + .addComponent(dataTable_panel, GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE) + .addComponent(tree_panel, GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE)) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(status_panel, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + + toolJsp.getViewport().add(jpa); + + toolbar_panel.add(toolJsp); + int tool_width = toolbar_panel.getWidth(); + int tool_height = toolbar_panel.getHeight(); + //System.out.println("tool_width:[" + tool_width + "], tool_height:[" + tool_height + "]"); + + if(null != history_comboBox) + tool_height = history_comboBox.getHeight(); + jpa.setBounds(0, 0, tool_width, (tool_height + 20)); + toolJsp.setBounds(0, 0, (tool_width), (tool_height + 20)); + //toolbar_panel.setVisible(true); + + GroupLayout gl_toolbar_panel = new GroupLayout(toolbar_panel); + gl_toolbar_panel.setHorizontalGroup( + gl_toolbar_panel.createParallelGroup(Alignment.LEADING) + .addGap(0, 640, Short.MAX_VALUE) + ); + gl_toolbar_panel.setVerticalGroup( + gl_toolbar_panel.createParallelGroup(Alignment.LEADING) + .addGap(0, 50, Short.MAX_VALUE) + ); + toolbar_panel.setLayout(gl_toolbar_panel); + //toolbar_panel.setVisible(true); + //toolbar_panel.setBounds(x, y, width, height); + + + /* + gl_toolbar_panel.setHorizontalGroup( + gl_toolbar_panel.createParallelGroup(Alignment.LEADING) + .addGroup(gl_toolbar_panel.createSequentialGroup() + .addContainerGap() + .addComponent(history_comboBox, GroupLayout.PREFERRED_SIZE, 154, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(lblIp, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE) + .addGap(10) + .addComponent(ip_textField, GroupLayout.PREFERRED_SIZE, 105, GroupLayout.PREFERRED_SIZE) + .addGap(10) + .addComponent(lblPort) + .addGap(10) + .addComponent(port_textField, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE) + .addGap(10) + .addComponent(lbldbIndex) + .addGap(10) + .addComponent(dbIndex_comboBox, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE) + .addGap(10) + .addComponent(lblPwd) + .addGap(10) + .addComponent(pwd_textField, GroupLayout.PREFERRED_SIZE, 54, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(search_btn) + .addGap(0)) + ); + gl_toolbar_panel.setVerticalGroup( + gl_toolbar_panel.createParallelGroup(Alignment.LEADING) + .addGroup(gl_toolbar_panel.createSequentialGroup() + .addGap(2) + .addComponent(lblIp, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE)) + .addGroup(gl_toolbar_panel.createSequentialGroup() + .addGap(2) + .addComponent(ip_textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) + .addComponent(lblPort, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE) + .addComponent(port_textField, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE) + .addComponent(lbldbIndex, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE) + .addComponent(dbIndex_comboBox, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE) + .addGroup(gl_toolbar_panel.createSequentialGroup() + .addGap(2) + .addComponent(lblPwd, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE)) + .addGroup(gl_toolbar_panel.createSequentialGroup() + .addGap(2) + .addComponent(pwd_textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) + .addGroup(gl_toolbar_panel.createSequentialGroup() + .addGap(2) + .addComponent(history_comboBox, GroupLayout.PREFERRED_SIZE, 17, Short.MAX_VALUE) + .addContainerGap()) + .addGroup(gl_toolbar_panel.createSequentialGroup() + .addComponent(search_btn) + .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + toolbar_panel.setLayout(gl_toolbar_panel); + */ + + GroupLayout gl_dataTable_panel = new GroupLayout(dataTable_panel); + gl_dataTable_panel.setHorizontalGroup( + gl_dataTable_panel.createParallelGroup(Alignment.LEADING) + .addGap(0, 332, Short.MAX_VALUE) + ); + gl_dataTable_panel.setVerticalGroup( + gl_dataTable_panel.createParallelGroup(Alignment.LEADING) + .addGap(0, 463, Short.MAX_VALUE) + ); + dataTable_panel.setLayout(gl_dataTable_panel); + + GroupLayout gl_tree_panel = new GroupLayout(tree_panel); + gl_tree_panel.setHorizontalGroup( + gl_tree_panel.createParallelGroup(Alignment.LEADING) + .addGap(0, 245, Short.MAX_VALUE) + ); + gl_tree_panel.setVerticalGroup( + gl_tree_panel.createParallelGroup(Alignment.LEADING) + .addGap(0, 463, Short.MAX_VALUE) + ); + tree_panel.setLayout(gl_tree_panel); + + GroupLayout gl_status_panel = new GroupLayout(status_panel); + gl_status_panel.setHorizontalGroup( + gl_status_panel.createParallelGroup(Alignment.LEADING) + .addGroup(gl_status_panel.createSequentialGroup() + .addContainerGap() + .addComponent(lblOptstatuslb, GroupLayout.DEFAULT_SIZE, 589, Short.MAX_VALUE) + .addContainerGap()) + ); + gl_status_panel.setVerticalGroup( + gl_status_panel.createParallelGroup(Alignment.LEADING) + .addComponent(lblOptstatuslb, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE) + ); + gl_status_panel.setHonorsVisibility(false); + + status_panel.setLayout(gl_status_panel); + frame.getContentPane().setLayout(groupLayout); + + /* + { + jTextField1 = new JTextField(); + getContentPane().add(jTextField1); + jTextField1.setText("jTextField1"); + jTextField1.setBounds(133, 7, 161, 28); + } + { + jTextField2 = new JTextField(); + getContentPane().add(jTextField2); + jTextField2.setText("jTextField2"); + jTextField2.setBounds(133, 49, 161, 28); + } + { + jButton1 = new JButton(); + getContentPane().add(jButton1); + jButton1.setText("OK"); + jButton1.setBounds(175, 98, 63, 28); + jButton1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + jButton1ActionPerformed(evt); + } + }); + }*/ + //frame.pack(); + + // make the frame to be loadded at windows center + Toolkit kit=Toolkit.getDefaultToolkit(); + Dimension screenSize=kit.getScreenSize(); + int screenHeight=screenSize.height; + int screenWidth=screenSize.width; + int width = 800; + int height = 600; + frame.setLocation( (screenWidth-width)/2, (screenHeight-height)/2 ); + frame.setExtendedState(JFrame.MAXIMIZED_BOTH); + //setSize(575, 272); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void updateMiddleTable(JScrollPane scrollPane){ + + } + + public static void resize(){ + treeResize(); + tollbarResize(); + } + + private void constantHostInfo(){ + + String ipStr= ip_textField.getText(); + String portStr= port_textField.getText(); + String pwdStr= pwd_textField.getText(); + String dbIndexStr= dbIndex_comboBox.getSelectedItem().toString(); + + Integer dbIndex = Integer.valueOf(dbIndexStr); + RedisConstants.REDIS_SERVER_IP = ipStr; + RedisConstants.REDIS_SERVER_PWD = pwdStr; + RedisConstants.REDIS_SERVER_DBINDEX = dbIndex; + Integer port = Integer.valueOf(portStr); + try{ + RedisConstants.REDIS_SERVER_PORT = "".equals(port)? 6379:port;//6379 is the default port for redis + port_textField.setBackground(Color.WHITE); + } catch (Exception ex ){ + port_textField.setBackground(Color.red); + lblOptstatuslb.setText(status + "port error"); + return; + } + } + + private static void treeResize(){ + if(null != jsp){ + int width = tree_panel.getWidth(); + int height = tree_panel.getHeight(); + //jsp.setPreferredSize(new Dimension(width, height)); + //tree.setPreferredSize(new Dimension()) + jsp.setBounds(10, 70, (width - 20), (height - 90)); + //jsp.updateUI(); + } + tree_panel.updateUI(); + } + + private static void tollbarResize(){ + if(null != toolJsp){ + int width = toolbar_panel.getWidth(); + int height = toolbar_panel.getHeight(); + if(null != history_comboBox) + height = history_comboBox.getHeight(); + //jsp.setPreferredSize(new Dimension(width, height)); + //tree.setPreferredSize(new Dimension()) + //System.out.println("tool_width:[" + width + "], tool_height:[" + height + "]"); + toolJsp.setBounds(0, 0, (width), (height + 20)); + //jsp.updateUI(); + } + toolbar_panel.updateUI(); + } + + /** + * @return the toolbar_panel + */ + public static final JPanel getToolbar_panel() { + return toolbar_panel; + } + + /** + * @return the tree_panel + */ + public static final JPanel getTree_panel() { + return tree_panel; + } + + /** + * @return the status_panel + */ + public static final JPanel getStatus_panel() { + return status_panel; + } + + /** + * @return the dataTable_panel + */ + public static final JPanel getDataTable_panel() { + return dataTable_panel; + } + +} diff --git a/src/org/kevin/redis/adapter/ComponentResizeAdapter.java b/src/org/kevin/redis/adapter/ComponentResizeAdapter.java new file mode 100644 index 0000000..b5ee398 --- /dev/null +++ b/src/org/kevin/redis/adapter/ComponentResizeAdapter.java @@ -0,0 +1,61 @@ +/** + * ComponentResizeAdapter.java + * kevin 2013-4-17 + * @version 0.1 + */ +package org.kevin.redis.adapter; + +import java.awt.Frame; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; + +import javax.swing.JPanel; + +import org.kevin.redis.table.RedisTable; + +/** + * @author kevin + * @since jdk1.6 + */ +public class ComponentResizeAdapter extends ComponentAdapter { + + Frame adaptee; + JPanel adapteep; + + + public ComponentResizeAdapter(Frame adaptee) { + this.adaptee = adaptee; + } + + /** + * @param adapteep + */ + public ComponentResizeAdapter(JPanel adapteep) { + this.adapteep = adapteep; + } + + public void componentResized(ComponentEvent e) { + RedisTable.resize(); + //adapteep.updateUI(); + //adapteep.revalidate(); + //System.out.println("adaptee Resize: " + adaptee.getTitle()); + //Component[] comps = adaptee.getComponents(); + //for(Component comp : comps){ + //System.out.println("adaptee Resize: " + comp.getName() + ", size: H" + comp.getSize().getHeight() + ", W:"+ comp.getSize().getWidth() ); + //Rectangle rt = comp.getBounds(); + //rt.setBounds(rt.getX(), rt.getY(), comp.getSize().getWidth(), comp.getSize().getHeight()); + //rt.setRect(comp.getX(), comp.getY(), comp.getSize().getWidth(), comp.getSize().getHeight()); + //int width = comp.getWidth() - 100; + //int height = comp.getHeight(); + //comp.setPreferredSize(new Dimension(width, height)); + //comp.revalidate(); +// JPanel treePanel = RedisDB.getTree_panel(); +// int width = treePanel.getWidth(); +// int height = treePanel.getHeight(); +// treePanel.setPreferredSize(new Dimension(width, height)); +// treePanel.getComponents(); +// treePanel.revalidate(); + //} + } + +} diff --git a/src/org/kevin/redis/adapter/MainTreeResizeAdapter.java b/src/org/kevin/redis/adapter/MainTreeResizeAdapter.java new file mode 100644 index 0000000..f3e24d7 --- /dev/null +++ b/src/org/kevin/redis/adapter/MainTreeResizeAdapter.java @@ -0,0 +1,32 @@ +/** + * MainTreeResizeAdapter.java + * kevin 2013-4-19 + * @version 0.1 + */ +package org.kevin.redis.adapter; + +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; + +import javax.swing.JPanel; + +import org.kevin.redis.RedisDB; + +/** + * @author kevin + * @since jdk1.6 + */ +public class MainTreeResizeAdapter extends ComponentAdapter { + + JPanel adapteep; + + public MainTreeResizeAdapter(JPanel adapteep) { + this.adapteep = adapteep; + } + + @Override + public void componentResized(ComponentEvent e) { + RedisDB.resize(); + } + +} diff --git a/src/org/kevin/redis/button/ImageButton.java b/src/org/kevin/redis/button/ImageButton.java new file mode 100644 index 0000000..992c7e8 --- /dev/null +++ b/src/org/kevin/redis/button/ImageButton.java @@ -0,0 +1,96 @@ +/** + * ImageButton.java + * kevin 2013-4-25 + * @version 0.1 + */ +package org.kevin.redis.button; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.border.Border; + +/** + * @author kevin + * @since jdk1.6 + */ +public class ImageButton extends JButton { + + private Border emptyBorder = BorderFactory.createEmptyBorder(0, 0, 0, 0); + private Color roverBorderColor = Color.gray; + private Border roverBorder = new Border() { + + public void paintBorder(Component c, Graphics g, int x, int y, + int width, int height) { + g.setColor(roverBorderColor); + g.drawRect(x, y, width - 1, height - 1); + } + + public Insets getBorderInsets(Component c) { + return new Insets(1, 1, 1, 1); + } + + public boolean isBorderOpaque() { + return true; + } + }; + + /** + * + */ + public ImageButton(String text) { + } + + public ImageButton(ImageIcon icon) { + setSize(icon.getImage().getWidth(null), icon.getImage().getHeight(null)); + setIcon(icon); + setMargin(new Insets(0, 0, 0, 0));// 将边框外的上下左右空间设置为0 + setIconTextGap(0);// 将标签中显示的文本和图标之间的间隔量设置为0 + setBorderPainted(false);// 不打印边框 + setBorder(null);// 除去边框 + setText(null);// 除去按钮的默认名称 + setFocusPainted(false);// 除去焦点的框 + setContentAreaFilled(false);// 除去默认的背景填充 + + this.setOpaque(false); + this.setBorder(emptyBorder); + this.setContentAreaFilled(false); + this.setFocusPainted(false); + this.setRolloverEnabled(true); + + this.addMouseListener(new MouseAdapter() { + + @Override + public void mouseEntered(MouseEvent e) { + if (isRolloverEnabled()) { + setBorder(roverBorder); + } + } + + @Override + public void mouseExited(MouseEvent e) { + if (isRolloverEnabled()) { + setBorder(emptyBorder); + } + } + }); + } + + private void setImage() { + ImageIcon ico = new ImageIcon("images/ico.png"); + ImageButton button = new ImageButton(ico); + // button.setPressedIcon(pressedIcon); + // button.setRolloverIcon(rolloverIcon); + // button.setSelectedIcon(selectedIcon); + // button.setRolloverSelectedIcon(rolloverSelectedIcon); + // button.setDisabledIcon(disabledIcon); + // button.setDisabledSelectedIcon(disabledSelectedIcon); + } +} diff --git a/src/org/kevin/redis/comboBox/HistoryComboBox.java b/src/org/kevin/redis/comboBox/HistoryComboBox.java new file mode 100644 index 0000000..ccf643b --- /dev/null +++ b/src/org/kevin/redis/comboBox/HistoryComboBox.java @@ -0,0 +1,27 @@ +/** + * HistoryComboBox.java + * kevin 2013-2-22 + * @version 0.1 + */ +package org.kevin.redis.comboBox; + +import org.kevin.redis.connection.RedisConnectionPool; + +/** + * @author kevin + * @since jdk1.6 + */ +public class HistoryComboBox { + + private static HistoryComboBox hisComb = null; + + public static HistoryComboBox getInstances() { + if (null == hisComb) + hisComb = new HistoryComboBox(); + return hisComb; + } + + public void reInitConnectPool(){ + RedisConnectionPool.refreshPool(); + } +} diff --git a/src/org/kevin/redis/connection/JedisFactory.java b/src/org/kevin/redis/connection/JedisFactory.java new file mode 100644 index 0000000..544966c --- /dev/null +++ b/src/org/kevin/redis/connection/JedisFactory.java @@ -0,0 +1,61 @@ +/** + * JedisFactory.java + * kevin 2013-4-10 + * @version 0.1 + */ +package org.kevin.redis.connection; + +/** + * @author kevin + * @since jdk1.6 + */ +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.Protocol; + +public class JedisFactory { + + private JedisPoolConfig jedisPoolConfig; + + private JedisPool jedisPool; + + public JedisFactory(JedisPoolConfig jedisPoolConfig) { + super(); + this.jedisPoolConfig = jedisPoolConfig; + } + + public Jedis getJedisInstance(String host) { + return getJedisPool(host, Protocol.DEFAULT_PORT).getResource(); + } + + public Jedis getJedisInstance(String host, int port) { + return getJedisPool(host, port).getResource(); + } + + public JedisPool getJedisPool(String host) { + return getJedisPool(host, Protocol.DEFAULT_PORT); + } + + public JedisPool getJedisPool(String host, int port) { + if (jedisPool == null) { + jedisPool = new JedisPool(jedisPoolConfig, host, port); + } + return jedisPool; + } + + /** + * 配合使用getJedisInstance方法后将jedis对象释放回连接池中 + * + * @param jedis 使用完毕的Jedis对象 + * @return true 释放成功;否则返回false + */ + public boolean release(Jedis jedis) { + if (jedisPool != null && jedis != null) { + jedisPool.returnResource(jedis); + return true; + } + return false; + } + +} diff --git a/src/org/kevin/redis/connection/JedisThreadPool.java b/src/org/kevin/redis/connection/JedisThreadPool.java new file mode 100644 index 0000000..d6e614e --- /dev/null +++ b/src/org/kevin/redis/connection/JedisThreadPool.java @@ -0,0 +1,127 @@ +/** + * JedisThreadPool.java + * 2011 Nov 27, 2011 + */ +package org.kevin.redis.connection; + +import java.util.Set; + +import org.kevin.redis.constant.RedisConstants; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.exceptions.JedisConnectionException; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class JedisThreadPool { + + private static JedisPool pool; + + static { + //String ip = "192.168.30.212"; + String ip = RedisConstants.REDIS_SERVER_IP; + // int port = 6380; + int port = RedisConstants.REDIS_SERVER_PORT; + int timeout = 1000; + String password = RedisConstants.REDIS_SERVER_PWD; + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxActive(100); + config.setMaxIdle(20); + // config.setMaxWait(1000); + config.setTestOnBorrow(true); + // pool = new JedisPool(config, "localhost"); + // pool = new JedisPool(config, "192.168.12.93"); + pool = new JedisPool(config, ip, port, timeout, password); + } + + public void initConnPool() { + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxActive(100); + config.setMaxIdle(20); + config.setMaxWait(1000l); + JedisPool pool = null; + Jedis jedis = null; + pool = new JedisPool(config, "", 6379); + boolean borrowOrOprSuccess = true; + try { + jedis = pool.getResource(); + // do redis opt by instance + } catch (JedisConnectionException e) { + borrowOrOprSuccess = false; + if (jedis != null) + pool.returnBrokenResource(jedis); + } finally { + if (borrowOrOprSuccess) + pool.returnResource(jedis); + } + jedis = pool.getResource(); + } + + public static void main(String[] args) { + JedisThreadPool demo = new JedisThreadPool(); + demo.test(); + } + + public void test() { + initInsert(); + // testThread(); + } + + private void initInsert() { + System.out.println("JedisThreadPool 插入数据开始"); + Jedis jedis = pool.getResource(); + //for (int i = 0; i < 20000; i++) { + //jedis.set(String.valueOf("lijian-key" + i), String.valueOf("lijian-value" + i)); + //} + Set sets = jedis.keys("*"); + for(String setkey : sets){ + System.out.println("Key: " + setkey); + } + pool.returnResource(jedis); + System.out.println("JedisThreadPool 插入数据结束"); + } + + private void testThread() { + long begin = System.currentTimeMillis(); + + Thread thread[] = new Thread[100]; + for (int i = 0; i < thread.length; i++) { + thread[i] = new MyThread(); + thread[i].start(); + } + + for (int i = 0; i < thread.length; i++) { + try { + thread[i].join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + long end = System.currentTimeMillis(); + System.out.println("线程执行时间是:" + (end - begin) + " ms"); + } + + class MyThread extends Thread { + @Override + public void run() { + Jedis jedis = JedisThreadPool.pool.getResource(); + for (int i = 0; i < 20000; i++) { + System.out.println(jedis.get(String.valueOf(i))); + } + JedisThreadPool.pool.returnResource(jedis); + } + } + + public static JedisPool getPool() { + return pool; + } + + public static void setPool(JedisPool pool) { + JedisThreadPool.pool = pool; + } +} diff --git a/src/org/kevin/redis/connection/RedisConnection.java b/src/org/kevin/redis/connection/RedisConnection.java new file mode 100644 index 0000000..ea46ad4 --- /dev/null +++ b/src/org/kevin/redis/connection/RedisConnection.java @@ -0,0 +1,44 @@ +/** + * RedisConnection.java + * 2011 Dec 16, 2011 + */ +package org.kevin.redis.connection; + +import org.kevin.redis.constant.RedisConstants; +import org.kevin.redis.msg.PopMessage; + +import redis.clients.jedis.Jedis; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class RedisConnection { + + + public static Jedis getJedis(String IP, int port){ + return new Jedis(RedisConstants.REDIS_SERVER_IP, RedisConstants.REDIS_SERVER_PORT); + } + + public static Jedis getJedis(int index){ + if(null == RedisConstants.REDIS_SERVER_IP){ + //TODO init or update redis db. + } + Jedis jedisDb = null; + try{ + jedisDb = new Jedis(RedisConstants.REDIS_SERVER_IP, RedisConstants.REDIS_SERVER_PORT); + jedisDb.select(RedisConstants.REDIS_SERVER_DBINDEX); + } catch (Exception ex ){ + PopMessage.popError("DB is unvaliable Cause: " + ex.getMessage()); + } + return jedisDb; + } + + public static Jedis getJedis(){ + return RedisConnectionPool.getConn(); + } + + public static int returnConn(Jedis jedisConn){ + return RedisConnectionPool.returnConn(jedisConn); + } +} diff --git a/src/org/kevin/redis/connection/RedisConnectionPool.java b/src/org/kevin/redis/connection/RedisConnectionPool.java new file mode 100644 index 0000000..d32a089 --- /dev/null +++ b/src/org/kevin/redis/connection/RedisConnectionPool.java @@ -0,0 +1,91 @@ +/** + * RedisConnectionPool.java + * kevin 2013-4-15 + * @version 0.1 + */ +package org.kevin.redis.connection; + +import org.kevin.redis.constant.RedisConstants; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +/** + * @author kevin + * @since jdk1.6 + */ +public class RedisConnectionPool { + + private static JedisPool pool; + + static { + initPool(); + } + + public static void refreshPool() { + initPool(); + } + + private static void initPool() { +// String ip = "192.168.30.212"; + String ip = RedisConstants.REDIS_SERVER_IP; +// int port = 6380; + int port = RedisConstants.REDIS_SERVER_PORT; + int timeout = 1000; +// String password = "authpwd"; + String password = RedisConstants.REDIS_SERVER_PWD; + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxActive(20); + config.setMaxIdle(5); + config.setMaxWait(1000); + config.setTestOnBorrow(true); + // pool = new JedisPool(config, "localhost"); + // pool = new JedisPool(config, "192.168.12.93"); + System.out.println("Init pool with ip:[" + ip + "], port:[" + port + "], password:[" + password + "]"); + if(null == password || password.isEmpty()) + pool = new JedisPool(config, ip, port, timeout); + else + pool = new JedisPool(config, ip, port, timeout, password); + } + + public void freshPoolConn(){ + if (null == pool){ + initPool(); + } else { + pool.destroy(); + initPool(); + } + } + + public static Jedis getConn() { + if (null == pool) + initPool(); + Jedis jedisConn = null; + try{ + //System.out.println("Pool size: " + pool.toString()); + jedisConn = pool.getResource(); + //System.out.println("jedisConn: " + jedisConn); + //jedisConn = new Jedis(RedisConstants.REDIS_SERVER_IP, RedisConstants.REDIS_SERVER_PORT); + //System.out.println("Get conn at dbindex:[" + RedisConstants.REDIS_SERVER_DBINDEX + "]"); + //jedisConn.auth(RedisConstants.REDIS_SERVER_PWD); + //jedisConn.select(RedisConstants.REDIS_SERVER_DBINDEX); + } catch (Exception ex){ + //System.out.println("renew pool"); + initPool(); + jedisConn = pool.getResource(); + //ex.printStackTrace(); + //jedisConn = new Jedis(RedisConstants.REDIS_SERVER_IP, RedisConstants.REDIS_SERVER_PORT); + //jedisConn.auth(RedisConstants.REDIS_SERVER_PWD); + //jedisConn.select(RedisConstants.REDIS_SERVER_DBINDEX); + } + //jedisConn.auth(RedisConstants.REDIS_SERVER_PWD); + jedisConn.select(RedisConstants.REDIS_SERVER_DBINDEX); + return jedisConn; + } + + public static int returnConn(Jedis jedisConn) { + pool.returnResource(jedisConn); + return 1; + } +} diff --git a/src/org/kevin/redis/constant/RedisConstants.java b/src/org/kevin/redis/constant/RedisConstants.java new file mode 100644 index 0000000..66ffbf5 --- /dev/null +++ b/src/org/kevin/redis/constant/RedisConstants.java @@ -0,0 +1,28 @@ +/** + * RedisConstants.java + * 2011 Dec 16, 2011 + */ +package org.kevin.redis.constant; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class RedisConstants { + + /** the redis db ip **/ + public static String CLIENT_VERSION = "1.3.2"; + + /** the redis db ip **/ + public static String REDIS_SERVER_IP = "127.0.0.1"; + /** the redis db port default is 6379 **/ + public static int REDIS_SERVER_PORT = 6379; + /** the redis db index default is 0 **/ + public static int REDIS_SERVER_DBINDEX = 0; + /** the redis db pwd default is null **/ + public static String REDIS_SERVER_PWD = ""; + /** space filed filter **/ + public static String FILEDS_SPACE = ", "; + + +} diff --git a/src/org/kevin/redis/data/vo/Host.java b/src/org/kevin/redis/data/vo/Host.java new file mode 100644 index 0000000..e4b6376 --- /dev/null +++ b/src/org/kevin/redis/data/vo/Host.java @@ -0,0 +1,94 @@ +/** + * Hosts.java + * kevin 2013-2-11 + * @version 0.1 + */ +package org.kevin.redis.data.vo; + +/** + * @author kevin + * @since jdk1.6 + */ +public class Host { + + private int id; + private String ip; + private int dbIndex; + private String pwd; + private int port; + + /** + * @return the id + */ + public final int getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public final void setId(int id) { + this.id = id; + } + + /** + * @return the ip + */ + public final String getIp() { + return ip; + } + + /** + * @param ip + * the ip to set + */ + public final void setIp(String ip) { + this.ip = ip; + } + + /** + * @return the pwd + */ + public final String getPwd() { + return pwd; + } + + /** + * @param pwd + * the pwd to set + */ + public final void setPwd(String pwd) { + this.pwd = pwd; + } + + /** + * @return the dbIndex + */ + public final int getDbIndex() { + return dbIndex; + } + + /** + * @param dbIndex the dbIndex to set + */ + public final void setDbIndex(int dbIndex) { + this.dbIndex = dbIndex; + } + + /** + * @return the port + */ + public final int getPort() { + return port; + } + + /** + * @param port + * the port to set + */ + public final void setPort(int port) { + this.port = port; + } + +} diff --git a/src/org/kevin/redis/lookandfell/LookAndFeel.java b/src/org/kevin/redis/lookandfell/LookAndFeel.java new file mode 100644 index 0000000..b2e0864 --- /dev/null +++ b/src/org/kevin/redis/lookandfell/LookAndFeel.java @@ -0,0 +1,71 @@ +/** + * LookAndFeel.java + * kevin 2013-4-24 + * @version 0.1 + */ +package org.kevin.redis.lookandfell; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; + +/** + * @author kevin + * @since jdk1.6 + */ +public class LookAndFeel extends JFrame { + private JPanel buttonPanel = null; + + public void launchFrame() { + //this.setSize(200, 300); + this.setSize(400, 600); + buttonPanel = new JPanel(); + // 得到所有安装的观感 + UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels(); + // new for + //JLabel lfClass = new JLabel(); + //StringBuilder stb = new StringBuilder(); + for (UIManager.LookAndFeelInfo info : infos) { + makeButton(info.getName(), info.getClassName()); + System.out.println("LookAndFeels Name:[" + info.getName() + "]"); + System.out.println("LookAndFeels Class:[" + info.getClass() + "]"); + //stb.append(info.getName()).append("\r\n"); + } + this.add(buttonPanel); + //lfClass.setText(stb.toString()); + //this.add(lfClass); + this.setVisible(true); + } + + private void makeButton(String bName, final String lookName) { + JButton b = new JButton(bName); + buttonPanel.add(b); + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + UIManager.setLookAndFeel(lookName); + } catch (ClassNotFoundException e1) { + e1.printStackTrace(); + } catch (InstantiationException e1) { + e1.printStackTrace(); + } catch (IllegalAccessException e1) { + e1.printStackTrace(); + } catch (UnsupportedLookAndFeelException e1) { + e1.printStackTrace(); + } + SwingUtilities.updateComponentTreeUI(LookAndFeel.this); + } + }); + } + + public static void main(String[] args) { + new LookAndFeel().launchFrame(); + } +} diff --git a/src/org/kevin/redis/lookandfell/LookAndFeelDemo.java b/src/org/kevin/redis/lookandfell/LookAndFeelDemo.java new file mode 100644 index 0000000..7ea4827 --- /dev/null +++ b/src/org/kevin/redis/lookandfell/LookAndFeelDemo.java @@ -0,0 +1,176 @@ +/** + * LookAndFeelDemo.java + * kevin 2013-4-24 + * @version 0.1 + */ +package org.kevin.redis.lookandfell; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalLookAndFeel; +import javax.swing.plaf.metal.OceanTheme; + +/** + * @author kevin + * @since jdk1.6 + */ +public class LookAndFeelDemo implements ActionListener { + private static String labelPrefix = "Number of button clicks: "; + private int numClicks = 0; + final JLabel label = new JLabel(labelPrefix + "0 "); + + // Specify the look and feel to use by defining the LOOKANDFEEL constant + // Valid values are: null (use the default), "Metal", "System", "Motif", + // and "GTK" + final static String LOOKANDFEEL = "Metal"; + + // If you choose the Metal L&F, you can also choose a theme. + // Specify the theme to use by defining the THEME constant + // Valid values are: "DefaultMetal", "Ocean", and "Test" + final static String THEME = "Test"; + + + public Component createComponents() { + JButton button = new JButton("I'm a Swing button!"); + button.setMnemonic(KeyEvent.VK_I); + button.addActionListener(this); + label.setLabelFor(button); + + JPanel pane = new JPanel(new GridLayout(0, 1)); + pane.add(button); + pane.add(label); + pane.setBorder(BorderFactory.createEmptyBorder( + 30, //top + 30, //left + 10, //bottom + 30) //right + ); + + return pane; + } + + public void actionPerformed(ActionEvent e) { + numClicks++; + label.setText(labelPrefix + numClicks); + } + + private static void initLookAndFeel() { + String lookAndFeel = null; + + if (LOOKANDFEEL != null) { + if (LOOKANDFEEL.equals("Metal")) { + lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName(); + // an alternative way to set the Metal L&F is to replace the + // previous line with: + // lookAndFeel = "javax.swing.plaf.metal.MetalLookAndFeel"; + + } + + else if (LOOKANDFEEL.equals("System")) { + lookAndFeel = UIManager.getSystemLookAndFeelClassName(); + } + + else if (LOOKANDFEEL.equals("Motif")) { + lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; + } + + else if (LOOKANDFEEL.equals("GTK")) { + lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"; + } + + else { + System.err.println("Unexpected value of LOOKANDFEEL specified: " + + LOOKANDFEEL); + lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName(); + } + + try { + + + UIManager.setLookAndFeel(lookAndFeel); + + // If L&F = "Metal", set the theme + + if (LOOKANDFEEL.equals("Metal")) { + if (THEME.equals("DefaultMetal")) + MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme()); + else if (THEME.equals("Ocean")) + MetalLookAndFeel.setCurrentTheme(new OceanTheme()); + else + MetalLookAndFeel.setCurrentTheme(new TestTheme()); + + UIManager.setLookAndFeel(new MetalLookAndFeel()); + } + + + + + } + + catch (ClassNotFoundException e) { + System.err.println("Couldn't find class for specified look and feel:" + + lookAndFeel); + System.err.println("Did you include the L&F library in the class path?"); + System.err.println("Using the default look and feel."); + } + + catch (UnsupportedLookAndFeelException e) { + System.err.println("Can't use the specified look and feel (" + + lookAndFeel + + ") on this platform."); + System.err.println("Using the default look and feel."); + } + + catch (Exception e) { + System.err.println("Couldn't get specified look and feel (" + + lookAndFeel + + "), for some reason."); + System.err.println("Using the default look and feel."); + e.printStackTrace(); + } + } + } + + private static void createAndShowGUI() { + //Set the look and feel. + initLookAndFeel(); + + //Make sure we have nice window decorations. + JFrame.setDefaultLookAndFeelDecorated(true); + + //Create and set up the window. + JFrame frame = new JFrame("SwingApplication"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + LookAndFeelDemo app = new LookAndFeelDemo(); + Component contents = app.createComponents(); + frame.getContentPane().add(contents, BorderLayout.CENTER); + + //Display the window. + frame.pack(); + frame.setVisible(true); + } + + public static void main(String[] args) { + //Schedule a job for the event dispatch thread: + //creating and showing this application's GUI. + javax.swing.SwingUtilities.invokeLater(new Runnable() { + public void run() { + createAndShowGUI(); + } + }); + } +} diff --git a/src/org/kevin/redis/lookandfell/TestTheme.java b/src/org/kevin/redis/lookandfell/TestTheme.java new file mode 100644 index 0000000..f665506 --- /dev/null +++ b/src/org/kevin/redis/lookandfell/TestTheme.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle or the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.kevin.redis.lookandfell; + +import javax.swing.plaf.ColorUIResource; +import javax.swing.plaf.metal.DefaultMetalTheme; + +/** + * This class describes a theme using "primary" colors. + * You can change the colors to anything else you want. + * + * 1.9 07/26/04 + */ +public class TestTheme extends DefaultMetalTheme { + + public String getName() { return "Toms"; } + + private final ColorUIResource primary1 = new ColorUIResource(255, 255, 0); + private final ColorUIResource primary2 = new ColorUIResource(0, 255, 255); + private final ColorUIResource primary3 = new ColorUIResource(255, 0, 255); + + protected ColorUIResource getPrimary1() { return primary1; } + protected ColorUIResource getPrimary2() { return primary2; } + protected ColorUIResource getPrimary3() { return primary3; } + +} diff --git a/src/org/kevin/redis/manage/HashMan.java b/src/org/kevin/redis/manage/HashMan.java new file mode 100644 index 0000000..9e2ab7a --- /dev/null +++ b/src/org/kevin/redis/manage/HashMan.java @@ -0,0 +1,66 @@ +/** + * HashMan.java + * kevin 2013-3-20 + * @version 0.1 + */ +package org.kevin.redis.manage; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author kevin + * @since jdk1.6 + */ +public class HashMan extends RedisTableMan { + + /* (non-Javadoc) + * @see org.kevin.redis.manage.RedisTableMan#add(java.lang.String, java.lang.Object) + */ + @SuppressWarnings("unchecked") + @Override + public int add(String key, Object obj) { + Map values = (HashMap) obj; + return add(key, values); + } + + /* (non-Javadoc) + * @see org.kevin.redis.manage.RedisTableMan#add(java.lang.String, java.util.Map) + */ + public int add(String key, Map valueMap) { + + int effectRows = 0; + try{ + //Iterator valueKeys = valueMap.keySet().iterator(); + redisConn.hmset(key, valueMap); + effectRows++; + } catch(Exception ex){ + + } + return effectRows; + //String mapKey = null; + //String mapValue = null; + //while(valueKeys.hasNext()){ + // mapKey = valueKeys.next(); + // mapValue = valueMap.get(mapKey); + //} + } + + /* (non-Javadoc) + * @see org.kevin.redis.manage.RedisTableMan#remove() + */ + @Override + public void remove(String key) { + redisConn.del(key); + //disconn(); + } + + /* (non-Javadoc) + * @see org.kevin.redis.manage.RedisTableMan#list() + */ + @Override + public Map list(String key) { + return redisConn.hgetAll(key); + } + +} diff --git a/src/org/kevin/redis/manage/ListMan.java b/src/org/kevin/redis/manage/ListMan.java new file mode 100644 index 0000000..52e798f --- /dev/null +++ b/src/org/kevin/redis/manage/ListMan.java @@ -0,0 +1,74 @@ +/** + * ListMan.java + * kevin 2013-3-20 + * @version 0.1 + */ +package org.kevin.redis.manage; + +import java.util.List; + +/** + * @author kevin + * @since jdk1.6 + */ +public class ListMan extends RedisTableMan { + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#add(java.lang.String, + * java.lang.Object) + */ + @SuppressWarnings("unchecked") + @Override + public int add(String key, Object obj) { + List values = (List) obj; + return add(key, values); + //for (String value : values) + // redisConn.sadd(key, value); + //disconn(); + } + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#add(java.lang.String, + * java.util.Map) + */ + public int add(String key, List valueList) { + + int effectRows = 0; + try{ + if (null != valueList) { + for (String value : valueList) + redisConn.sadd(key, value); + } + effectRows++; + } catch(Exception ex){ + + } + //disconn(); + return effectRows; + } + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#remove() + */ + @Override + public void remove(String key) { + redisConn.del(key); + //disconn(); + } + + /* (non-Javadoc) + * @see org.kevin.redis.manage.RedisTableMan#list() + */ + @Override + public List list(String key) { + Long llen = redisConn.llen(key); + return redisConn.lrange(key, 0, llen); + } + +} diff --git a/src/org/kevin/redis/manage/RedisTableMan.java b/src/org/kevin/redis/manage/RedisTableMan.java new file mode 100644 index 0000000..094ef91 --- /dev/null +++ b/src/org/kevin/redis/manage/RedisTableMan.java @@ -0,0 +1,64 @@ +/** + * RedisTableMan.java + * kevin 2013-3-20 + * @version 0.1 + */ +package org.kevin.redis.manage; + +import org.kevin.redis.connection.RedisConnection; + +import redis.clients.jedis.Jedis; + +/** + * @author kevin + * @since jdk1.6 + */ +public abstract class RedisTableMan { + + protected static Jedis redisConn = null; + + + public RedisTableMan() { + getconn(); + } + + /** + * Abstract method for add new data to redis, save data should instance the sub class implements + * + * @param value + * the String should make the value be a string + * the set should make the value be a hash map + * the list should make the value be a hash map for index + * the hash should make the value be a hash map for key and value + * @return + */ + protected abstract int add(String key, Object value); + + protected abstract void remove(String key); + + //static { + // redisConn = RedisConnection.getJedis(); + //} + + protected void getconn(){ + if(null == redisConn || !redisConn.isConnected()) + redisConn = RedisConnection.getJedis(); + } + + protected void disconn(){ + redisConn.disconnect(); + redisConn = null; + } + + /** + * @param key + */ + protected abstract Object list(String key); + + public static String getType(String key) { + //Jedis jedis = RedisConnection.getJedis(); + //String type = jedis.type(key); + String type = RedistDataManagement.getType(key); + return type; + } +} diff --git a/src/org/kevin/redis/manage/RedistDataManagement.java b/src/org/kevin/redis/manage/RedistDataManagement.java new file mode 100644 index 0000000..bfd53fa --- /dev/null +++ b/src/org/kevin/redis/manage/RedistDataManagement.java @@ -0,0 +1,114 @@ +/** + * RedistDataManagement.java + * 2011 Dec 16, 2011 + */ +package org.kevin.redis.manage; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.kevin.redis.connection.RedisConnection; + +import redis.clients.jedis.Jedis; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class RedistDataManagement { + + /** all key partten is * */ + private static String ALL_KEY_PATTEN = "*"; + + /** + * @param filterText + * @return + */ + public static Set listKeys(String filterText) { + if(null == filterText || ALL_KEY_PATTEN.equals(filterText)) + return listKeys(); + Jedis jedis = RedisConnection.getJedis(); + Set keys = null; + try{ + keys = jedis.keys("*" + filterText + "*"); + }catch (Exception ex ){ + System.out.println("The redis db is down."); + } + RedisConnection.returnConn(jedis); + return keys; + } + + /** + * Get all the db tables + * @return keys set + */ + public static Set listKeys(){ + Jedis jedis = RedisConnection.getJedis(); + Set keys = null; + try{ + keys = jedis.keys(ALL_KEY_PATTEN); + }catch (Exception ex ){ + System.out.println("The redis db is down."); + } + RedisConnection.returnConn(jedis); + return keys; + } + + /** + * @param pathNode + * @return + */ + public static String getType(String pathNode) { + Jedis jedis = RedisConnection.getJedis(); + String type = jedis.type(pathNode); + //PopMessage.popMsg(type); + RedisConnection.returnConn(jedis); + return type; + } + + /** + * @param pathNode + * @return + */ + public static Set getSetDetail(String pathNode) { + Jedis jedis = RedisConnection.getJedis(); + Set setMembers = jedis.smembers(pathNode); + RedisConnection.returnConn(jedis); + return setMembers; + } + /** + * @param pathNode + * @return + */ + public static Map getHashDetail(String pathNode) { + Jedis jedis = RedisConnection.getJedis(); + Map hashMembers = jedis.hgetAll(pathNode); + RedisConnection.returnConn(jedis); + return hashMembers; + } + + /** + * @param pathNode + * @return + */ + public static String getStringDetail(String pathNode) { + Jedis jedis = RedisConnection.getJedis(); + String stringMembers = jedis.get(pathNode); + RedisConnection.returnConn(jedis); + return stringMembers; + } + + /** + * @param pathNode + * @return + */ + public static List getListDetail(String pathNode) { + Jedis jedis = RedisConnection.getJedis(); + List listMembers = jedis.lrange(pathNode, 0, -1); + RedisConnection.returnConn(jedis); + return listMembers; + } + + +} diff --git a/src/org/kevin/redis/manage/SetMan.java b/src/org/kevin/redis/manage/SetMan.java new file mode 100644 index 0000000..242e238 --- /dev/null +++ b/src/org/kevin/redis/manage/SetMan.java @@ -0,0 +1,81 @@ +/** + * SetMan.java + * kevin 2013-3-20 + * @version 0.1 + */ +package org.kevin.redis.manage; + +import java.util.Set; +import java.util.Vector; + +/** + * @author kevin + * @since jdk1.6 + */ +public class SetMan extends RedisTableMan { + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#add(java.lang.String, + * java.lang.Object) + */ + @SuppressWarnings("unchecked") + @Override + public int add(String key, Object obj) { + Vector values = (Vector) obj; + return add(key, values); + //for (String value : values) + // redisConn.sadd(key, value); + //disconn(); + } + + public int edit(String key, Vector values) { + remove(key); + return add(key, values); + } + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#add(java.lang.String, + * java.util.Map) + */ + public int add(String key, Vector values) { + int effectRows = 0; + try{ + for (String value : values){ + //System.out.println("key:[" + key + "], value:[" + value + "]"); + redisConn.sadd(key, value); + } + effectRows++; + } catch(Exception ex){ + + } + return effectRows; + //disconn(); + } + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#remove() + */ + @Override + public void remove(String key) { + redisConn.del(key); + //disconn(); + } + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#list() + */ + @Override + public Set list(String key) { + return redisConn.smembers(key); + //return null; + } + +} diff --git a/src/org/kevin/redis/manage/StringMan.java b/src/org/kevin/redis/manage/StringMan.java new file mode 100644 index 0000000..676c36d --- /dev/null +++ b/src/org/kevin/redis/manage/StringMan.java @@ -0,0 +1,75 @@ +/** + * StringManagerment.java + * kevin 2013-3-20 + * @version 0.1 + */ +package org.kevin.redis.manage; + + +/** + * @author kevin + * @since jdk1.6 + */ +public class StringMan extends RedisTableMan { + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#add() + */ + @Override + public int add(String key, Object value) { + String strValue = (String) value; + return add(key, strValue); + //redisConn.set(key, strValue); + //disconn(); + } + + public int edit(String key, String value) { + remove(key); + return add(key, value); + } + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#add(java.lang.String, + * java.util.Map) + */ + public int add(String key, String value) { + //getconn(); + int effectRows = 0; + try{ + redisConn.set(key, value); + effectRows++; + } catch(Exception ex){ + + } + return effectRows; + //disconn(); + } + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#remove() + */ + @Override + public void remove(String key) { + //getconn(); + redisConn.del(key); + //disconn(); + } + + /* + * (non-Javadoc) + * + * @see org.kevin.redis.manage.RedisTableMan#list() + */ + @Override + public String list(String key) { + redisConn.get(key); + return key; + } + +} diff --git a/src/org/kevin/redis/menu/NoSQLMenu.java b/src/org/kevin/redis/menu/NoSQLMenu.java new file mode 100644 index 0000000..c1c6858 --- /dev/null +++ b/src/org/kevin/redis/menu/NoSQLMenu.java @@ -0,0 +1,231 @@ +/** + * Menu.java + * 2012 Jan 5, 2012 + */ +package org.kevin.redis.menu; + +import javax.swing.JMenuBar; + +import org.kevin.redis.menu.subs.DBMenu; +import org.kevin.redis.menu.subs.EditMenu; +import org.kevin.redis.menu.subs.FileMenu; +import org.kevin.redis.menu.subs.HelpMenu; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class NoSQLMenu extends JMenuBar { + /** + * + */ + private static final long serialVersionUID = 6565758005176550685L; + //JMenuItem menuItem_exit; + //JMenuItem menuItem_option; + //JMenuItem menuItem_about; + + public JMenuBar initManu(){ + JMenuBar menuBar; + //JMenu menu_File, menu_edit, menu_help; + menuBar = new JMenuBar(); + + //-------------------- file menu ----------------// + new FileMenu(menuBar).init(); +// menu_File = new JMenu("File(F)"); +// menu_File.setMnemonic(KeyEvent.VK_F); +// +// menuItem_exit = new JMenuItem("Exit(X)", KeyEvent.VK_X); +// //menuItem_option.addActionListener(); +// menuItem_exit.addActionListener(this); +// menuItem_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, +// ActionEvent.CTRL_MASK)); +// +// menu_File.add(menuItem_exit); + + //-------------------- edit menu ----------------// + //EditMenu.init(menuBar); + new EditMenu(menuBar).init(); +// menu_edit = new JMenu("Edit(E)"); +// menu_edit.setMnemonic(KeyEvent.VK_E); +// // add the item to the menu +// menuItem_option = new JMenuItem("Option(O)", KeyEvent.VK_O); +// menuItem_option.addActionListener(this); +// menuItem_option.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, +// ActionEvent.CTRL_MASK)); +// menu_edit.add(menuItem_option); + + new DBMenu(menuBar).init(); + //-------------------- help menu ----------------// + new HelpMenu(menuBar).init(); +// menu_help = new JMenu("Help(H)"); +// menu_help.setMnemonic(KeyEvent.VK_H); +// // add the item to the menu +// menuItem_about = new JMenuItem("About(A)", KeyEvent.VK_A); +// menuItem_about.addActionListener(this); +// menuItem_about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, +// ActionEvent.CTRL_MASK)); +// menu_help.add(menuItem_about); + + // add the menu to the bar + //menuBar.add(menu_File); + //menuBar.add(menu_edit); + //menuBar.add(menu_help); + + return menuBar; + } + +// @Override +// public void actionPerformed(ActionEvent e) { +// if(e.getSource() == menuItem_exit){ +// System.exit(0); +// return; +// } +// if(e.getSource() == menuItem_option){ +// //new PreferencesWindow("NoSQL Preferences"); +// PreferencesWindow pw = PreferencesWindow.instance(); +// pw.showWindow(); +// return; +// } +// if(e.getSource() == menuItem_about){ +// JOptionPane.showMessageDialog(this, "This is redis client done by java.\n Author: kevin edison\n Version: 1.0 ", "About", JOptionPane.INFORMATION_MESSAGE); +// return; +// } +// } + + /* + * This class is a pop window for configure the redis info + */ + /* class RedisConfig extends JFrame implements ActionListener { + *//** + * + *//* + private static final long serialVersionUID = -7899889629830144406L; + // button and button text + JLabel ip_lable, port_lable; + JTextField ip_text, port_text; + JPanel ip_panel, port_panel, btn_panel, control_panel; + JButton[] btn = new JButton[3]; + String[] btnText = {"Save", "Reset", "Cancel"}; + + RedisConfig(String title) { + this.setTitle(title); + //this.setBounds(400, 300, 200, 200); + //this.setAlwaysOnTop(true); + + ip_lable = new JLabel("Redis IP:"); + ip_text = new JTextField(15); + port_lable = new JLabel("Redis Port:"); + port_text = new JTextField(15); + + for (int i = 0; i < btn.length; i++) { + btn[i] = new JButton(btnText[i]); + btn[i].setActionCommand(String.valueOf(i)); + btn[i].addActionListener(this); + } + ip_panel = new JPanel(); + ip_panel.add(ip_lable); + ip_panel.add(ip_text); + //ip_panel.setLayout(null); + + port_panel = new JPanel(); + port_panel.add(port_lable); + port_panel.add(port_text); + //port_panel.setLayout(null); + + btn_panel = new JPanel(); + btn_panel.add(btn[0]); + btn_panel.add(btn[1]); + btn_panel.add(btn[2]); + //btn_panel.setLayout(null); + + control_panel = new JPanel(); + //control_panel.setLayout(new GridLayout(3, 1)); + control_panel.add(ip_panel); + control_panel.add(port_panel); + control_panel.add(btn_panel); + //control_panel.setLayout(null); + + GridLayout grid = new GridLayout(3, 1); + grid.setHgap(0);//set the component space between h type 设置组件之间的水平距离为h(int型) + grid.setVgap(0);//set the component space between V type设置组件之间的垂直距离为v(int型) + control_panel.setLayout(grid); + + this.setLayout(new BorderLayout()); + this.getContentPane().add(control_panel, BorderLayout.CENTER); + + + // make the frame to be loadded at windows center + Toolkit kit=Toolkit.getDefaultToolkit(); + Dimension screenSize=kit.getScreenSize(); + int screenHeight=screenSize.height; + int screenWidth=screenSize.width; + int width = 300; + int height = 200; + setLocation( (screenWidth-width)/2, (screenHeight-height)/2 ); + + setSize(width, height); + + //this.setLocation(100, 100); + //this.setSize(300, 200); + //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + this.setVisible(true); + this.setAlwaysOnTop(true); + addWindowListener(new HandlePopWin()); + } + + @Override + public void actionPerformed(ActionEvent e) { + + int i = Integer.parseInt(e.getActionCommand()); + switch (i) { + case 0: + btn[0] = (JButton) e.getSource(); + String redisIP, redisPort; + redisIP = ip_text.getText(); + redisPort = port_text.getText(); + if (null == redisIP || redisIP.length() == 0 || null == redisPort || redisPort.length() == 0) + // JOptionPane.showMessageDialog(this, "IP or port Can't be null!"); + JOptionPane.showMessageDialog(this, "IP or port Can't be null!", "Warn", JOptionPane.ERROR_MESSAGE); + else { + int port = Integer.valueOf(redisPort); + if (IPValidate.isIP(redisIP) && (port > 0 && port < 65535)) { + JOptionPane.showMessageDialog(this, "Set success!", "save", JOptionPane.INFORMATION_MESSAGE);//.showMessageDialog(this, "Save success!"); + RedisConstants.REDIS_SERVER_IP = redisIP; + RedisConstants.REDIS_SERVER_PORT = port; + break; + } + else{ + //JOptionPane.showMessageDialog(this, "IP or port unvaliad,please check!"); + JOptionPane.showMessageDialog(this, "IP or port unvaliad,please check!", "Warn", JOptionPane.ERROR_MESSAGE); + ip_text.setText(""); + port_text.setText(""); + ip_text.setFocusable(true); + break; + } + } + case 1: + btn[1] = (JButton) e.getSource(); + ip_text.setText(""); + port_text.setText(""); + ip_text.setFocusable(true); + break; + case 2: + btn[2] = (JButton) e.getSource(); + this.setVisible(false); + this.dispose(); + break; + } + + } + } + + class HandlePopWin extends WindowAdapter { + public void windowClosing(WindowEvent e) { + //e.getWindow().setVisible(false); + (e.getWindow()).dispose(); + //(new Frame()).setVisible(false); + //this.windowClosed(e); + } + }*/ +} diff --git a/src/org/kevin/redis/menu/subs/DBMenu.java b/src/org/kevin/redis/menu/subs/DBMenu.java new file mode 100644 index 0000000..8a2120a --- /dev/null +++ b/src/org/kevin/redis/menu/subs/DBMenu.java @@ -0,0 +1,65 @@ +/** + * DBMenu.java + * kevin 2013-4-25 + * @version 0.1 + */ +package org.kevin.redis.menu.subs; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; + +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.KeyStroke; + +import org.kevin.redis.window.dbcopy.DBCopyWindow; + +/** + * @author kevin + * @since jdk1.6 + */ +public class DBMenu implements ActionListener { + + private JMenuBar menuBar; + private JMenu menu_db; + JMenuItem menuItem_option; + + /** + * + */ + public DBMenu() { + } + + /** + * @param menuBar2 + */ + public DBMenu(JMenuBar menuBar) { + this.menuBar = menuBar; + } + + public void init() { + + menu_db = new JMenu("DB(D)"); + menu_db.setMnemonic(KeyEvent.VK_D); + // add the item to the menu + menuItem_option = new JMenuItem("DB COPY(B)", KeyEvent.VK_B); + menuItem_option.addActionListener(this); + menuItem_option.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, + ActionEvent.CTRL_MASK)); + menu_db.add(menuItem_option); + menuBar.add(menu_db); + } + + /* (non-Javadoc) + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == menuItem_option) { + DBCopyWindow.instance().showWindow(); + } + } + +} diff --git a/src/org/kevin/redis/menu/subs/EditMenu.java b/src/org/kevin/redis/menu/subs/EditMenu.java new file mode 100644 index 0000000..5720401 --- /dev/null +++ b/src/org/kevin/redis/menu/subs/EditMenu.java @@ -0,0 +1,64 @@ +/** + * EditMenu.java + * kevin 2013-4-24 + * @version 0.1 + */ +package org.kevin.redis.menu.subs; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; + +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.KeyStroke; + +import org.kevin.redis.window.PreferencesWindow; + +/** + * @author kevin + * @since jdk1.6 + */ +public class EditMenu implements ActionListener { + + private JMenuBar menuBar; + private JMenu menu_edit; + JMenuItem menuItem_option; + + /** + * + */ + public EditMenu() { + } + + /** + * + */ + public EditMenu(JMenuBar menuBar) { + this.menuBar = menuBar; + } + + public void init() { + + menu_edit = new JMenu("Edit(E)"); + menu_edit.setMnemonic(KeyEvent.VK_E); + // add the item to the menu + menuItem_option = new JMenuItem("Option(O)", KeyEvent.VK_O); + menuItem_option.addActionListener(this); + menuItem_option.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, + ActionEvent.CTRL_MASK)); + menu_edit.add(menuItem_option); + menuBar.add(menu_edit); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == menuItem_option) { + // new PreferencesWindow("NoSQL Preferences"); + PreferencesWindow pw = PreferencesWindow.instance(); + pw.showWindow(); + return; + } + } +} diff --git a/src/org/kevin/redis/menu/subs/FileMenu.java b/src/org/kevin/redis/menu/subs/FileMenu.java new file mode 100644 index 0000000..d22651a --- /dev/null +++ b/src/org/kevin/redis/menu/subs/FileMenu.java @@ -0,0 +1,68 @@ +/** + * FileMenu.java + * kevin 2013-4-24 + * @version 0.1 + */ +package org.kevin.redis.menu.subs; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; + +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.KeyStroke; + +/** + * @author kevin + * @since jdk1.6 + */ +public class FileMenu implements ActionListener { + private JMenuBar menuBar; + private JMenu menu_File; + private JMenuItem menuItem_exit; + + /** + * + */ + public FileMenu() { + } + + /** + * @param menuBar + */ + public FileMenu(JMenuBar menuBar) { + this.menuBar = menuBar; + } + + public void init() { + + menu_File = new JMenu("File(F)"); + menu_File.setMnemonic(KeyEvent.VK_F); + + menuItem_exit = new JMenuItem("Exit(X)", KeyEvent.VK_X); + // menuItem_option.addActionListener(); + menuItem_exit.addActionListener(this); + menuItem_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, + ActionEvent.CTRL_MASK)); + + menu_File.add(menuItem_exit); + menuBar.add(menu_File); + } + + /* + * (non-Javadoc) + * + * @see + * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + @Override + public void actionPerformed(ActionEvent e) { + if(e.getSource() == menuItem_exit){ + System.exit(0); + return; + } + } + +} diff --git a/src/org/kevin/redis/menu/subs/HelpMenu.java b/src/org/kevin/redis/menu/subs/HelpMenu.java new file mode 100644 index 0000000..db4c667 --- /dev/null +++ b/src/org/kevin/redis/menu/subs/HelpMenu.java @@ -0,0 +1,70 @@ +/** + * HelpMenu.java + * kevin 2013-4-24 + * @version 0.1 + */ +package org.kevin.redis.menu.subs; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; + +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.KeyStroke; + +import org.kevin.redis.constant.RedisConstants; + +/** + * @author kevin + * @since jdk1.6 + */ +public class HelpMenu implements ActionListener { + private JMenuBar menuBar; + private JMenu menu_help; + private JMenuItem menuItem_about; + + /** + * + */ + public HelpMenu() { + } + + /** + * @param menuBar2 + */ + public HelpMenu(JMenuBar menuBar) { + this.menuBar = menuBar; + } + + public void init() { + + menu_help = new JMenu("Help(H)"); + menu_help.setMnemonic(KeyEvent.VK_H); + // add the item to the menu + menuItem_about = new JMenuItem("About(A)", KeyEvent.VK_A); + menuItem_about.addActionListener(this); + menuItem_about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, + ActionEvent.CTRL_MASK)); + menu_help.add(menuItem_about); + menuBar.add(menu_help); + } + + /* + * (non-Javadoc) + * + * @see + * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + @Override + public void actionPerformed(ActionEvent e) { + if(e.getSource() == menuItem_about){ + JOptionPane.showMessageDialog(null, "This is redis client done by java.\n Author: kevin edison\n Version: " + RedisConstants.CLIENT_VERSION, "About", JOptionPane.INFORMATION_MESSAGE); + //JOptionPane.showInternalMessageDialog(this, "This is redis client done by java.\n Author: kevin edison\n Version: 1.0 ", "About", JOptionPane.INFORMATION_MESSAGE); + return; + } + } + +} diff --git a/src/org/kevin/redis/msg/PopMessage.java b/src/org/kevin/redis/msg/PopMessage.java new file mode 100644 index 0000000..ffa321d --- /dev/null +++ b/src/org/kevin/redis/msg/PopMessage.java @@ -0,0 +1,43 @@ +/** + * PopMessage.java + * kevin 2013-2-5 + * @version 0.1 + */ +package org.kevin.redis.msg; + +import javax.swing.JDialog; +import javax.swing.JOptionPane; + +/** + * @author kevin + * @since jdk1.6 + */ +public class PopMessage { + + public static void popMsg(String msg){ + JOptionPane.showMessageDialog(null, msg, "Information", JOptionPane.INFORMATION_MESSAGE); + } + + public static void popWarn(String msg){ + JOptionPane.showMessageDialog(null, msg, "Warning", JOptionPane.WARNING_MESSAGE); + } + + public static void popError(String msg){ + JOptionPane.showMessageDialog(null, msg, "Error", JOptionPane.ERROR_MESSAGE); + } + + public static int popConfirm(String msg){ + JDialog.setDefaultLookAndFeelDecorated(true); + int response = JOptionPane.showConfirmDialog(null, "Do you want to " + msg, "Confirm", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); +// if (response == JOptionPane.NO_OPTION) { +// System.out.println("No button clicked"); +// } else if (response == JOptionPane.YES_OPTION) { +// System.out.println("Yes button clicked"); +// } else if (response == JOptionPane.CLOSED_OPTION) { +// System.out.println("JOptionPane closed"); +// } + return response; + } + +} diff --git a/src/org/kevin/redis/operation/DBOperation.java b/src/org/kevin/redis/operation/DBOperation.java new file mode 100644 index 0000000..ca0546e --- /dev/null +++ b/src/org/kevin/redis/operation/DBOperation.java @@ -0,0 +1,53 @@ +/** + * DBOperation.java + * kevin 2013-3-8 + * @version 0.1 + */ +package org.kevin.redis.operation; + +import org.kevin.redis.manage.HashMan; +import org.kevin.redis.manage.ListMan; +import org.kevin.redis.manage.RedistDataManagement; +import org.kevin.redis.manage.SetMan; +import org.kevin.redis.manage.StringMan; + + +/** + * @author kevin + * @since jdk1.6 + */ +public class DBOperation { + + public int remove(String key) { + int affectKeys = 0; + String key_type = RedistDataManagement.getType(key); + if ( "list".equalsIgnoreCase(key_type)) { + //ListOperation listO = new ListOperation(); + //listO.remove(key);// this not implement + ListMan listM = new ListMan(); + listM.remove(key); + affectKeys ++; + } else if ( "hash".equalsIgnoreCase(key_type)) { + //HashOperation hash = new HashOperation(); + //hash.remove(key);// this not implement + HashMan hashm = new HashMan(); + hashm.remove(key); + affectKeys ++; + } else if ( "set".equalsIgnoreCase(key_type)) { + //SetOperation set = new SetOperation(); + //set.remove(key);// this not implement + SetMan setm = new SetMan(); + setm.remove(key); + affectKeys ++; + } else if ( "string".equalsIgnoreCase(key_type)) { + //StringOperation str = new StringOperation(); + //str.remove(key);// this not implement + StringMan strM = new StringMan(); + strM.remove(key); + affectKeys ++; + } else { + //PopMessage.popMsg("Unsupported key [" + key + "] for type[" + key_type + "]"); + } + return affectKeys; + } +} diff --git a/src/org/kevin/redis/operation/HashOperation.java b/src/org/kevin/redis/operation/HashOperation.java new file mode 100644 index 0000000..4d842e8 --- /dev/null +++ b/src/org/kevin/redis/operation/HashOperation.java @@ -0,0 +1,21 @@ +/** + * HashOperation.java + * kevin 2013-3-8 + * @version 0.1 + */ +package org.kevin.redis.operation; + +import org.kevin.redis.msg.PopMessage; + + +/** + * @author kevin + * @since jdk1.6 + */ +public class HashOperation { + + public int remove(String key) { + PopMessage.popMsg("remove for hash key:" + key); + return 0; + } +} diff --git a/src/org/kevin/redis/operation/ListOperation.java b/src/org/kevin/redis/operation/ListOperation.java new file mode 100644 index 0000000..32710ce --- /dev/null +++ b/src/org/kevin/redis/operation/ListOperation.java @@ -0,0 +1,28 @@ +/** + * ListOperation.java + * kevin 2013-3-8 + * @version 0.1 + */ +package org.kevin.redis.operation; + +import org.kevin.redis.msg.PopMessage; + + +/** + * @author kevin + * @since jdk1.6 + */ +public class ListOperation { + + public void remove() { + + } + + /** + * @param key + */ + public void remove(String key) { + PopMessage.popMsg("remove for list key:" + key); + } + +} diff --git a/src/org/kevin/redis/operation/SetOperation.java b/src/org/kevin/redis/operation/SetOperation.java new file mode 100644 index 0000000..5c9d0bc --- /dev/null +++ b/src/org/kevin/redis/operation/SetOperation.java @@ -0,0 +1,25 @@ +/** + * SetOperation.java + * kevin 2013-3-8 + * @version 0.1 + */ +package org.kevin.redis.operation; + +import org.kevin.redis.msg.PopMessage; + + +/** + * @author kevin + * @since jdk1.6 + */ +public class SetOperation { + + /** + * @param key + */ + public void remove(String key) { + PopMessage.popMsg("remove for set key:" + key); + + } + +} diff --git a/src/org/kevin/redis/operation/StringOperation.java b/src/org/kevin/redis/operation/StringOperation.java new file mode 100644 index 0000000..06e731f --- /dev/null +++ b/src/org/kevin/redis/operation/StringOperation.java @@ -0,0 +1,24 @@ +/** + * StringOperation.java + * kevin 2013-3-8 + * @version 0.1 + */ +package org.kevin.redis.operation; + +import org.kevin.redis.msg.PopMessage; + +/** + * @author kevin + * @since jdk1.6 + */ +public class StringOperation { + + /** + * @param key + */ + public void remove(String key) { + PopMessage.popMsg("remove for string key:" + key); + + } + +} diff --git a/src/org/kevin/redis/panel/PreferencesRightPanel.java b/src/org/kevin/redis/panel/PreferencesRightPanel.java new file mode 100644 index 0000000..b6e4089 --- /dev/null +++ b/src/org/kevin/redis/panel/PreferencesRightPanel.java @@ -0,0 +1,298 @@ +/** + * PreferencesRightPanel.java + * kevin 2013-2-21 + * @version 0.1 + */ +package org.kevin.redis.panel; + +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; +import java.util.Vector; + +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import javax.swing.plaf.basic.BasicTableHeaderUI; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableModel; +import javax.swing.table.TableRowSorter; + +import org.kevin.db.sqlite.SqliteDB; +import org.kevin.redis.data.vo.Host; +import org.kevin.redis.msg.PopMessage; +import org.kevin.redis.window.PreferencesWindow; + +/** + * @author kevin + * @since jdk1.6 + */ +public class PreferencesRightPanel { + + private static String hostNode = "Hosts"; + private static JTable data_table = null; + + /** + * @param pathNode + */ + public static void showPreferences(String pathNode) { + // PopMessage.popMsg(pathNode); + if (hostNode.equalsIgnoreCase(pathNode)) + showHostTable(); + } + public static JPanel showHostTable(String pathNode) { + return showHostTable(); + } + + private static JPanel showHostTable() { + + data_table = initJTable(); + + // JScrollPane scrollPane = new JScrollPane(); + // scrollPane.setBounds(100, 30, 400, 400); + + JButton remove_btn = new JButton("删除数据"); + remove_btn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + //removeDatas(); + removeData(); + showHostTable(); + } + }); + // scrollPane.add(button_1, BorderLayout.NORTH); + // scrollPane.add(button_1); + // scrollPane.add(table, BorderLayout.SOUTH); + // scrollPane.add(table); + JPanel tablePanle = PreferencesWindow.instance().getTablePanel(); + JScrollPane scrollPanle = new JScrollPane(); + //tablePanle.setLayout(new GridLayout(2, 1)); + //tablePanle.setAlignmentY(0); + tablePanle.removeAll(); + tablePanle.setLayout(new BoxLayout(tablePanle, BoxLayout.Y_AXIS)); + //tablePanle.setSize(tablePanle.getX(), tablePanle.getY()); + //tablePanle.setAlignmentX(0); + + scrollPanle.setViewportView(data_table); + + tablePanle.add(scrollPanle); + scrollPanle.setBounds(10, 10, tablePanle.getX(), tablePanle.getY()); + //scrollPanle.setVisible(true); + + tablePanle.add(remove_btn); + data_table.setBounds(10, 10, tablePanle.getX(), tablePanle.getY()); + + data_table.getColumn("ID").setCellRenderer( + new DefaultTableCellRenderer() { // rewrite setValue method + public void setValue(Object value) { + this.setHorizontalAlignment(SwingConstants.CENTER);// 居中 + super.setValue(value); + } + }); + // PreferencesWindow.instance().getContentPane().add(scrollPane, + // BorderLayout.EAST); + //PreferencesWindow.instance().getContentPane().add(tablePanle); + //tablePanle.setVisible(true); + tablePanle.updateUI(); + // scrollPane.updateUI(); + return tablePanle; + } + private static void removeData() { + int selectId = data_table.getSelectedRow(); + //PopMessage.popMsg("selectId:" + selectId); + + Host host = new Host(); + host.setId(Integer.valueOf((String) data_table.getValueAt(selectId, 0))); + host.setIp((String) data_table.getValueAt(selectId, 1)); + host.setPwd((String) data_table.getValueAt(selectId, 2)); + host.setPort(Integer.valueOf((String) data_table.getValueAt(selectId, 3))); + + PopMessage.popMsg("selectId:" + host.getId() + ", ip:" + host.getIp() + ", pwd:" + host.getPwd()+ ", ip:" + host.getPort() ); + SqliteDB.getInstance().removeHost(host); + //data_table.remove(selectId); + } + + private static int removeDatas() { + //int selectId = data_table.getSelectedRow(); + int[] selectRows = data_table.getSelectedRows(); + int effectedRows = 0; + + int response = JOptionPane.showConfirmDialog(null, "Do you want to delete row [" + compArray(selectRows) + "]", "Confirm", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if(JOptionPane.YES_OPTION == response){ + int allRows = selectRows.length; + for(int rowId : selectRows){ + Host host = new Host(); + host.setId(Integer.valueOf((String) data_table.getValueAt(rowId, 0))); + host.setIp((String) data_table.getValueAt(rowId, 1)); + host.setPwd((String) data_table.getValueAt(rowId, 2)); + host.setPort(Integer.valueOf((String) data_table.getValueAt(rowId, 3))); + + //PopMessage.popMsg("selectId:" + host.getId() + ", ip:" + host.getIp() + ", pwd:" + host.getPwd()+ ", ip:" + host.getPort() ); + effectedRows += SqliteDB.getInstance().removeHost(host); + } + if(effectedRows == allRows) PopMessage.popMsg("Delete successful!"); + else if(effectedRows > 0 ) PopMessage.popMsg("Success:[" + effectedRows +"], fail:[" + (allRows - effectedRows) + "]"); + else PopMessage.popMsg("Exception has occured!"); + } + return effectedRows; + //data_table.remove(selectId); + } + + private static String compArray(int[] selectRows){ + StringBuilder sbu = new StringBuilder(); + for(int rowId : selectRows){ + sbu.append(data_table.getValueAt(rowId, 0)).append(","); + } + sbu = sbu.deleteCharAt(sbu.length()-1); + return sbu.toString(); + } + public static JTable initJTable() { + final String space = ""; + //List hosts = DerbyDB.getInstance().gethosts(); + List hosts = SqliteDB.getInstance().gethosts(); + String[] headers = { "ID", "IP", "PWD", "DBIndex", "Port" }; + Object[][] table_data = null; + //DefaultTableModel dtm = new DefaultTableModel(new Object[] { "ID", "IP", "PWD", "DBIndex", "Port" }, 0); + DefaultTableModel dtm = new DefaultTableModel(headers, 0); + if (null != hosts && hosts.size() > 0) { + int arraySize = hosts.size(); + table_data = new String[arraySize][headers.length]; + int i = 0; + for (Host host : hosts) { + table_data[i][0] = space + host.getId(); + table_data[i][1] = host.getIp(); + table_data[i][2] = host.getPwd(); + table_data[i][3] = space + host.getDbIndex(); + table_data[i][4] = space + host.getPort(); + dtm.addRow(table_data[i]); + i++; + //System.out.println("[id:" + host.getId() + ", ip:" + host.getIp() + ", pwd:" + host.getPwd() + ", port:" + host.getPort() + "]"); + } + } else { + table_data = new String[1][4]; + table_data[0][0] = ""; + table_data[0][1] = ""; + table_data[0][2] = ""; + table_data[0][3] = ""; + table_data[0][4] = ""; + } + + // data_table = new JTable(table_data, header_name); + data_table = new JTable(); + data_table.setModel(dtm); + + // set the table header to be sorted + data_table.setRowSorter(new TableRowSorter(dtm)); + + JTableHeader th = data_table.getTableHeader(); + th.setUI(new BasicTableHeaderUI() { + JCheckBox chk = new JCheckBox("All"); + @Override + public void paint(Graphics g, JComponent c) { + super.paint(g, c); + //g.setColor(Color.red); + g.draw3DRect(5, 5, 10, 10, false); + } + }); + + // data_table.setTableHeader(data_table.getTableHeader()); + + // JTableHeader tableHeader = data_table.getTableHeader(); + // data_table.setTableHeader(tableHeader); + return data_table; + } +} + +/** + * TableModel类,继承了AbstractTableModel + * + */ +class Table_Model extends AbstractTableModel { + + private static final long serialVersionUID = -7495940408592595397L; + + private Vector content = null; + + private String[] title_name = { "ID", "IP", "PWD", "Port" }; + + public Table_Model() { + content = new Vector(); + } + + public Table_Model(int count) { + content = new Vector(count); + } + + public void addRow(String ip, String pwd, int port) { + Vector v = new Vector(4); + v.add(0, new Integer(content.size())); + v.add(1, ip); + v.add(2, pwd); + v.add(3, port); + content.add(v); + } + + public void removeRow(int row) { + content.remove(row); + } + + public void removeRows(int row, int count) { + for (int i = 0; i < count; i++) { + if (content.size() > row) { + content.remove(row); + } + } + } + + /** + * 让表格中某些值可修改,但需要setValueAt(Object value, int row, int col)方法配合才能使修改生效 + */ + public boolean isCellEditable(int rowIndex, int columnIndex) { + if (columnIndex == 0) { + return false; + } + return true; + } + + /** + * 使修改的内容生效 + */ + public void setValueAt(Object value, int row, int col) { + ((Vector) content.get(row)).remove(col); + ((Vector) content.get(row)).add(col, value); + this.fireTableCellUpdated(row, col); + } + + public String getColumnName(int col) { // 返回列名,即表头 + return title_name[col]; + } + + public int getColumnCount() { + return title_name.length; + } + + public int getRowCount() { + return content.size(); + } + + public Object getValueAt(int row, int col) { + return ((Vector) content.get(row)).get(col); + } + + /** + * 返回数据类型 + */ + public Class getColumnClass(int col) { + return getValueAt(0, col).getClass(); + } +} \ No newline at end of file diff --git a/src/org/kevin/redis/panel/ToolsPanel.java b/src/org/kevin/redis/panel/ToolsPanel.java new file mode 100644 index 0000000..7414699 --- /dev/null +++ b/src/org/kevin/redis/panel/ToolsPanel.java @@ -0,0 +1,28 @@ +/** + * ToolsPanel.java + * kevin 2013-2-5 + * @version 0.1 + */ +package org.kevin.redis.panel; + +import java.awt.Dimension; + +import javax.swing.JScrollPane; +import javax.swing.JTable; + +/** + * @author kevin + * @since jdk1.6 + */ +public class ToolsPanel { + + public JScrollPane createToolsPanel() { + String[] headers = { }; + Object[][] playerInfo = { }; + JTable table = new JTable(playerInfo, headers); + table.setPreferredScrollableViewportSize(new Dimension(550, 30)); + JScrollPane scrollPane = new JScrollPane(table); + return scrollPane; + } + +} diff --git a/src/org/kevin/redis/table/RedisTable.java b/src/org/kevin/redis/table/RedisTable.java new file mode 100644 index 0000000..93dd325 --- /dev/null +++ b/src/org/kevin/redis/table/RedisTable.java @@ -0,0 +1,611 @@ +/** + * RedisHash.java + * 2011 Dec 16, 2011 + */ +package org.kevin.redis.table; + +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.RowFilter; +import javax.swing.ScrollPaneLayout; +import javax.swing.SwingConstants; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableModel; +import javax.swing.table.TableRowSorter; + +import org.kevin.redis.RedisDB; +import org.kevin.redis.manage.RedistDataManagement; +import org.kevin.redis.msg.PopMessage; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class RedisTable { + + /**The value is [TABLE name:] **/ + private static String TABLE_NAME = "TABLE name:"; + /**The value is [TABLE Type:] **/ + private static String TABLE_TYPE = "TABLE Type:"; + private static String CONTETN_FILTR = "Contetn Filter:"; + private static String TAB_SPACE = " "; + /**The value is [ **/ + private static String VALUE_BRACE_START = "["; + /**The value is ] **/ + private static String VALUE_BRACE_END = "]"; + private static ScrollPaneLayout spLayout = new ScrollPaneLayout(); + //private static BorderLayout borderLayout = new BorderLayout(); + //private static int tableW=400, tableH=400; + + private static JScrollPane scrollPane; + private static JTable table; + static JPanel dateTable_panel = RedisDB.getDataTable_panel(); + + /** + * Create the table for the hash task from redis + * + * @return + */ + public static JScrollPane componentInfo() { + String[] taskHeaders = { "Column", "value", "type" }; + Object[][] playerInfo = { { "task:id", new Integer(66), "String" }, + { "status", new Integer(82), "int" } }; + JTable table = new JTable(playerInfo, taskHeaders); + table.setPreferredScrollableViewportSize(new Dimension(550, 30)); + JScrollPane scrollPane = new JScrollPane(table); + return scrollPane; + } + + /** + * @param pathNode + */ + public static void updateDetail(String pathNode) { + //PopMessage.popMsg("The selected key is:[" + pathNode + "]"); + if(null == pathNode || pathNode.isEmpty()){ + PopMessage.popMsg("The selected key is:[" + pathNode + "]"); + } else { + String tableype = RedistDataManagement.getType(pathNode); + //PopMessage.popMsg(tableype); + if("set".equals(tableype)) { + // get the id set from redis and add under this node + Set allKeysList = RedistDataManagement.getSetDetail(pathNode); + contractSetTable(pathNode, tableype, allKeysList); + } else if("hash".equals(tableype)){ + // get the hash from redis and add under this node + Map allHashList = RedistDataManagement.getHashDetail(pathNode); + contractHashTable(pathNode, tableype, allHashList); + } else if("list".equals(tableype)){ + // get the list from redis and add under this node + List allList = RedistDataManagement.getListDetail(pathNode); + contractListTable(pathNode, tableype, allList); + } else if("string".equals(tableype)){ + String stringValue = RedistDataManagement.getStringDetail(pathNode); + contractStringTable(pathNode, tableype, stringValue); + } else { + contractNoneTable(pathNode, tableype); + } + } + } + + /** + * @param pathNode + * @param tableype + * @param allList + */ + private static void contractListTable(String pathNode, String tableype, List members) { + String[] tableHeaders = { "Index", "Value", "Type" }; + Object[][] listInfo = null; + final String valueType = "String"; + if(null != members && members.size() > 0){ + int arraySize = members.size(); + //final String space = ""; + listInfo = new String[arraySize][3]; + for(int index = 0; index < arraySize; index++ ){ + listInfo[index][0] = String.valueOf(index + 1); + listInfo[index][1] = members.get(index); + listInfo[index][2] = valueType; + } + } else { + listInfo = new String[1][3]; + listInfo[0][0] = ""; + listInfo[0][1] = ""; + listInfo[0][2] = ""; + } + + //JPanel dateTable_panel = RedisDB.getDataTable_panel(); + if(null == dateTable_panel){ + dateTable_panel = RedisDB.getDataTable_panel(); + } + dateTable_panel.removeAll(); + + //JTable table = new JTable(listInfo, listHeaders); + //table.setName(tableype + "<" + pathNode + ">"); + + // set the table header to be sorted + DefaultTableModel dtm = new DefaultTableModel(listInfo, tableHeaders); + table = new JTable(dtm); + final TableRowSorter sorter = new TableRowSorter(dtm); + table.setRowSorter(sorter); + + AlignColumn(table, tableHeaders[0] , SwingConstants.CENTER); + //table.setPreferredScrollableViewportSize(new Dimension(550, 30)); + //JScrollPane scrollPane = new JScrollPane(table); + scrollPane = new JScrollPane(table); + + JPanel labelPanel = new JPanel(); + labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS)); + //String _desc = TABLE_NAME + pathNode + TAB_SPACE + TABLE_VALUE + tableype; + JLabel tableName = new JLabel(TABLE_NAME + TAB_SPACE + VALUE_BRACE_START + pathNode + VALUE_BRACE_END); + JLabel tableType = new JLabel(TABLE_TYPE + TAB_SPACE + VALUE_BRACE_START + tableype + VALUE_BRACE_END); + labelPanel.add(tableName); + labelPanel.add(tableType); + dateTable_panel.add(labelPanel); + labelPanel.setVisible(true); + tableType.setVisible(true); + labelPanel.setBounds(10, 20, 400, 35); + + JPanel filter = new JPanel(); + filter.setLayout(new BoxLayout(filter, BoxLayout.X_AXIS)); + JLabel contentFilter = new JLabel(CONTETN_FILTR + TAB_SPACE); + final JTextArea filterText = new JTextArea(); + JButton filterButton = new JButton("Filter"); + filter.add(contentFilter); + filter.add(filterText); + filter.add(filterButton); + dateTable_panel.add(filter); + filterButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String text = filterText.getText(); + if (text.length() == 0) { + sorter.setRowFilter(null); + } else { + sorter.setRowFilter(RowFilter.regexFilter(text)); + } + } + }); + filter.setBounds(10, 50, 400, 25); + /* + filterText.getDocument().addDocumentListener(new DocumentListener() { + + @Override + public void removeUpdate(DocumentEvent de) { + filterDE(de); + } + + @Override + public void insertUpdate(DocumentEvent de) { + filterDE(de); + } + + @Override + public void changedUpdate(DocumentEvent de) { + filterDE(de); + } + + });*/ + + //table.setLayout(borderLayout); + //table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); + + //table.setBounds(10, 20, 300, 440); + //RedisDB.updateMiddleTable(scrollPane); + //panel.remove(1); + scrollPane.setVisible(true); + //scrollPane.setBounds(10, 50, 400, 400); + scrollPane.setLayout(spLayout); + //scrollPane.resetKeyboardActions(); + //scrollPane.setBounds(30, 30, dateTable_panel.getX(), dateTable_panel.getY()); + dateTable_panel.add(scrollPane); + + // according to the auto width and height + int width = dateTable_panel.getWidth(); + int height = dateTable_panel.getHeight(); + //System.out.println("dateTable_panel: width:[" + width + "], height:[" + height + "]"); + scrollPane.setBounds(10, 80, (width - 20), (height - 90)); + dateTable_panel.setPreferredSize(new Dimension(width, height)); + + dateTable_panel.updateUI(); + + } + + /** + * @param de + */ + protected static void filterDE(DocumentEvent de) { + if(null != scrollPane) { + PopMessage.popMsg("The table filter:" + de.getOffset()); + //table.get + } + } + + private static void contractSetTable(String pathNode, String tableype, Set members){ + String[] tableHeaders = { "Field", "Value", "Type" }; + //Object[][] playerInfo = { { "", "", "" } }; + //PopMessage.popMsg("members.size():" + members.size()); + Object[][] setInfo = null; + //JTable table = new JTable(playerInfo, taskHeaders); + final String space = ""; + //JPanel dateTable_panel = RedisDB.getDataTable_panel(); + if(null == dateTable_panel){ + dateTable_panel = RedisDB.getDataTable_panel(); + } + if(null != members && members.size() > 0){ + int arraySize = members.size(); + setInfo = new String[arraySize][3]; + Iterator ite = members.iterator(); + String iteId = null; + //Integer setID = null; + int i = 0; + while (ite.hasNext()) { + iteId = (String) ite.next(); + //System.out.println("iteId:" + iteId); + //setID = (null == iteId) ? 0 : Integer.valueOf(iteId); + // create the new leaf + setInfo[i][0] = space + (i + 1); + setInfo[i][1] = iteId; + setInfo[i][2] = "String"; + i++; + } + } else { + setInfo = new String[1][3]; + setInfo[0][0] = ""; + setInfo[0][1] = ""; + setInfo[0][2] = ""; + // add the profile leaf to the profile node + //DefaultMutableTreeNode allKeysNodeLeaf = new DefaultMutableTreeNode(); + //allKeysNodeLeaf.setUserObject("no keys"); + // add the profile leaf to the profile node + //allKeysNode.add(allKeysNodeLeaf); + } + + dateTable_panel.removeAll(); + //Component comp = panel.getComponentAt(2, 2); + //JTable table = new JTable(setInfo, taskHeaders); + //table.setName(tableype + "<" + pathNode + ">"); + + // set the table header to be sorted + DefaultTableModel dtm = new DefaultTableModel(setInfo, tableHeaders); + //JTable table = new JTable(dtm); + table = new JTable(dtm); + final TableRowSorter sorter = new TableRowSorter(dtm); + table.setRowSorter(sorter); + //table.setRowSorter(new TableRowSorter(dtm)); + + AlignColumn(table, tableHeaders[0] , SwingConstants.CENTER); + //table.setPreferredScrollableViewportSize(new Dimension(550, 30)); + //JScrollPane scrollPane = new JScrollPane(table); + scrollPane = new JScrollPane(table); + + JPanel labelPanel = new JPanel(); + labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS)); + //String _desc = TABLE_NAME + pathNode + TAB_SPACE + TABLE_VALUE + tableype; + JLabel tableName = new JLabel(TABLE_NAME + TAB_SPACE + VALUE_BRACE_START + pathNode + VALUE_BRACE_END); + JLabel tableType = new JLabel(TABLE_TYPE + TAB_SPACE + VALUE_BRACE_START + tableype + VALUE_BRACE_END); + labelPanel.add(tableName); + labelPanel.add(tableType); + dateTable_panel.add(labelPanel); + labelPanel.setVisible(true); + tableType.setVisible(true); + labelPanel.setBounds(10, 20, 400, 35); + + //table.setLayout(borderLayout); + //table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); + + JPanel filter = new JPanel(); + filter.setLayout(new BoxLayout(filter, BoxLayout.X_AXIS)); + JLabel contentFilter = new JLabel(CONTETN_FILTR + TAB_SPACE); + final JTextArea filterText = new JTextArea(); + JButton filterButton = new JButton("Filter"); + filter.add(contentFilter); + filter.add(filterText); + filter.add(filterButton); + dateTable_panel.add(filter); + filterButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String text = filterText.getText(); + if (text.length() == 0) { + sorter.setRowFilter(null); + } else { + sorter.setRowFilter(RowFilter.regexFilter(text)); + } + } + }); + filter.setBounds(10, 50, 400, 25); + /* + filterText.getDocument().addDocumentListener(new DocumentListener() { + + @Override + public void removeUpdate(DocumentEvent de) { + filterDE(de); + } + + @Override + public void insertUpdate(DocumentEvent de) { + filterDE(de); + } + + @Override + public void changedUpdate(DocumentEvent de) { + filterDE(de); + } + + });*/ + + //table.setBounds(100, 20, 300, 440); + //RedisDB.updateMiddleTable(scrollPane); + //panel.remove(1); + scrollPane.setVisible(true); + //scrollPane.setBounds(10, 50, 400, 400); + scrollPane.setLayout(spLayout); + //scrollPane.setBounds(30, 30, dateTable_panel.getX(), dateTable_panel.getY()); + dateTable_panel.add(scrollPane); + + // according to the auto width and height + int width = dateTable_panel.getWidth(); + int height = dateTable_panel.getHeight(); + //System.out.println("dateTable_panel: width:[" + width + "], height:[" + height + "]"); + scrollPane.setBounds(10, 80, (width - 20), (height - 90)); + dateTable_panel.setPreferredSize(new Dimension(width, height)); + + dateTable_panel.updateUI(); + //dateTable_panel.setVisible(true); + //dateTable_panel.setLocale(null); + } + + private static void contractHashTable(String pathNode, String tableype, Map members){ + String[] tableHeaders = { "Field", "value", "type" }; + Object[][] tableInfo = new String[members.size()][3]; + //JTable table = new JTable(playerInfo, taskHeaders); + final String space = ""; + //JPanel dateTable_panel = RedisDB.getDataTable_panel(); + if(null == dateTable_panel){ + dateTable_panel = RedisDB.getDataTable_panel(); + } + if(null != members && members.size() > 0){ + Set memberSet = members.keySet(); + Iterator ite = memberSet.iterator(); + String iteId = null; + //Integer setID = null; + int i = 0; + while (ite.hasNext()) { + iteId = (String) ite.next(); + //System.out.println("iteId:" + iteId); + //setID = (null == iteId) ? 0 : Integer.valueOf(iteId); + // create the new leaf + tableInfo[i][0] = iteId; + tableInfo[i][1] = members.get(iteId); + tableInfo[i][2] = space; + i++; + } + } else { + tableInfo = new String[1][3]; + tableInfo[0][0] = ""; + tableInfo[0][1] = ""; + tableInfo[0][2] = ""; + // add the profile leaf to the profile node + //DefaultMutableTreeNode allKeysNodeLeaf = new DefaultMutableTreeNode(); + //allKeysNodeLeaf.setUserObject("no keys"); + // add the profile leaf to the profile node + //allKeysNode.add(allKeysNodeLeaf); + } + + dateTable_panel.removeAll(); + //JTable table = new JTable(tableInfo, taskHeaders); + //table.setLayout(borderLayout); + //table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); + + // set the table header to be sorted + DefaultTableModel dtm = new DefaultTableModel(tableInfo, tableHeaders); + //JTable table = new JTable(dtm); + table = new JTable(dtm); + final TableRowSorter sorter = new TableRowSorter(dtm); + table.setRowSorter(sorter); + //table.setRowSorter(new TableRowSorter(dtm)); + //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); + + AlignColumn(table, tableHeaders[0] , SwingConstants.CENTER); + //table.setPreferredScrollableViewportSize(new Dimension(550, 30)); + //table.setBounds(10, 30, 300, 400); + //table.setVisible(true); + //dateTable_panel.add(table); + + //JScrollPane scrollPane = new JScrollPane(table); + scrollPane = new JScrollPane(table); + + JPanel labelPanel = new JPanel(); + labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS)); + //String _desc = TABLE_NAME + pathNode + TAB_SPACE + TABLE_VALUE + tableype; + JLabel tableName = new JLabel(TABLE_NAME + TAB_SPACE + VALUE_BRACE_START + pathNode + VALUE_BRACE_END); + JLabel tableType = new JLabel(TABLE_TYPE + TAB_SPACE + VALUE_BRACE_START + tableype + VALUE_BRACE_END); + labelPanel.add(tableName); + labelPanel.add(tableType); + dateTable_panel.add(labelPanel); + labelPanel.setVisible(true); + tableType.setVisible(true); + labelPanel.setBounds(10, 20, 400, 35); + + JPanel filter = new JPanel(); + filter.setLayout(new BoxLayout(filter, BoxLayout.X_AXIS)); + JLabel contentFilter = new JLabel(CONTETN_FILTR + TAB_SPACE); + final JTextArea filterText = new JTextArea(); + JButton filterButton = new JButton("Filter"); + filter.add(contentFilter); + filter.add(filterText); + filter.add(filterButton); + dateTable_panel.add(filter); + filterButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String text = filterText.getText(); + if (text.length() == 0) { + sorter.setRowFilter(null); + } else { + sorter.setRowFilter(RowFilter.regexFilter(text)); + } + } + }); + filter.setBounds(10, 50, 400, 25); + /* + filterText.getDocument().addDocumentListener(new DocumentListener() { + + @Override + public void removeUpdate(DocumentEvent de) { + filterDE(de); + } + + @Override + public void insertUpdate(DocumentEvent de) { + filterDE(de); + } + + @Override + public void changedUpdate(DocumentEvent de) { + filterDE(de); + } + + });*/ + + dateTable_panel.add(scrollPane); + //scrollPane.setBounds(10, 50, 400, 400); + scrollPane.setLayout(spLayout); + //scrollPane.setVisible(true); + //scrollPane.setBounds(30, 30, dateTable_panel.getX(), dateTable_panel.getY()); + int width = dateTable_panel.getWidth(); + int height = dateTable_panel.getHeight(); + //System.out.println("dateTable_panel: width:[" + width + "], height:[" + height + "]"); + + scrollPane.setBounds(10, 80, (width - 20), (height - 90)); + dateTable_panel.setPreferredSize(new Dimension(width, height)); + //dateTable_panel.removeAll(); + dateTable_panel.updateUI(); + } + + + public static void resize(){ + + if(null == dateTable_panel){ + dateTable_panel = RedisDB.getDataTable_panel(); + } + int width = dateTable_panel.getWidth(); + int height = dateTable_panel.getHeight(); + if(null != scrollPane){ + scrollPane.setBounds(10, 50, (width - 20), (height - 60)); + } + //System.out.println("dateTable_panel: width:[" + width + "], height:[" + height + "]"); + dateTable_panel.setPreferredSize(new Dimension(width, height)); + dateTable_panel.updateUI(); + } + + private static void contractStringTable(String pathNode, String tableype, String stringValue){ + //JPanel dateTable_panel = RedisDB.getDataTable_panel(); + if(null == dateTable_panel){ + dateTable_panel = RedisDB.getDataTable_panel(); + } + dateTable_panel.removeAll(); + + JPanel stringPanel = new JPanel(); + stringPanel.setLayout(new BoxLayout(stringPanel, BoxLayout.Y_AXIS)); + //JLabel labLeft=new JLabel("align left", SwingConstants.LEFT); + //stringPanel.add(labLeft); + //stringPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); + + //JPanel namePanel = new JPanel(); + //namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.X_AXIS)); + // cant set the size for FlowLayout + //namePanel.setLayout(new FlowLayout(FlowLayout.LEFT)); + String nameLine = TABLE_NAME + TAB_SPACE + VALUE_BRACE_START + pathNode + VALUE_BRACE_END; + JLabel tableNameLab = new JLabel(nameLine); + //JLabel tableNameLab = new JLabel(TABLE_NAME); + //tableNameLab.setHorizontalAlignment(SwingConstants.LEFT); + //JLabel tableNameValue = new JLabel(pathNode); + //namePanel.add(tableNameLab); + //namePanel.add(tableNameValue); + + //JPanel typePanel = new JPanel(); + //typePanel.setLayout(new BoxLayout(typePanel, BoxLayout.X_AXIS)); + //typePanel.setLayout(new FlowLayout(FlowLayout.LEFT)); + String typeLine = TABLE_TYPE + TAB_SPACE + VALUE_BRACE_START + tableype + VALUE_BRACE_END; + JLabel tableTypeLab = new JLabel(typeLine); + //JLabel tableTypeLab = new JLabel(TABLE_TYPE); + //JLabel tableTypeValue = new JLabel(tableype); + //tableTypeLab.setHorizontalAlignment(SwingConstants.LEFT); + //typePanel.add(tableTypeLab); + //typePanel.add(tableTypeValue); + + //JPanel valuePanel = new JPanel(); + //valuePanel.setLayout(new BoxLayout(valuePanel, BoxLayout.X_AXIS)); + //valuePanel.setLayout(new FlowLayout(FlowLayout.LEFT)); + String value = "Table Value:" + TAB_SPACE + VALUE_BRACE_START + stringValue + VALUE_BRACE_END; + JLabel tablevalueLab = new JLabel(value); + //JLabel tablevalueLab = new JLabel("Table Value:"); + //JTextField tableValue = new JTextField(20); + //tableValue.setText(stringValue); + //tableValue.setColumns(30); + //valuePanel.add(tablevalueLab); + //valuePanel.add(tableValue); + //tableValue.setPreferredSize(new Dimension(50, 20)); + + stringPanel.add(tableNameLab); + stringPanel.add(tableTypeLab); + stringPanel.add(tablevalueLab); + //stringPanel.add(valuePanel); + //dateTable_panel.setLayout(new GridLayout(2, 2, 0, 0)); + dateTable_panel.add(stringPanel); + stringPanel.setVisible(true); + //tableNameLab.setLocation(10, 10); + //typePanel.setLocation(10, 50); + //valuePanel.setLocation(10, 70); + //stringPanel.setLocation(10, 10); + //tableNameLab.setBounds(10, 10, 400, 20); + //typePanel.setBounds(10, 50, 400, 20); + //valuePanel.setBounds(10, 70, 50, 20); + stringPanel.setBounds(10, 20, 400, 90); + + //dateTable_panel.add(tableNameLab); + //dateTable_panel.add(tableNameValue); + //dateTable_panel.add(tableTypeLab); + //dateTable_panel.add(tableTypeValue); + //dateTable_panel.add(tablevalueLab); + //dateTable_panel.add(tableValue); + + //tableNameLab.setBounds(10, 30, 100, 20); + //tableNameValue.setBounds(100, 30, 100, 20); + //tablevalueLab.setBounds(10, 50, 100, 20); + //tableValue.setBounds(100, 50, 100, 20); + //stringPanel.updateUI(); + dateTable_panel.updateUI(); + //dateTable_panel.repaint(); + //dateTable_panel.setVisible(true); + } + + private static void contractNoneTable(String pathNode, String tableype){ + + } + + private static void AlignColumn(JTable comp, String column, final int position){ + comp.getColumn(column).setCellRenderer( + new DefaultTableCellRenderer() { // rewrite setValue method + private static final long serialVersionUID = 1L; + + public void setValue(Object value) { + this.setHorizontalAlignment(position); + super.setValue(value); + } + }); + } +} diff --git a/src/org/kevin/redis/tree/DBTree.java b/src/org/kevin/redis/tree/DBTree.java new file mode 100644 index 0000000..2f856a6 --- /dev/null +++ b/src/org/kevin/redis/tree/DBTree.java @@ -0,0 +1,186 @@ +/** + * DBTree.java + * 2011 Dec 16, 2011 + */ +package org.kevin.redis.tree; + +import java.util.Iterator; + +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; + +import org.kevin.redis.constant.RedisConstants; +import org.kevin.redis.manage.RedistDataManagement; +import org.kevin.redis.table.RedisTable; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class DBTree { + + private static DBTree dbTree; + public static JTree tree; + DefaultMutableTreeNode rootNode; + private String rootNodeTitle = "RedisDB"; + private String keysTitle = "Redis"; + private String spaceNodeTitle = ""; + DefaultMutableTreeNode spaceNode, allKeysNode; + DefaultMutableTreeNode profileNode, encodingTaskNode, finishTaskNode; + //JPanel tree_panel; + JScrollPane jsp; + + public static DBTree getDBTree(){ + if(null == dbTree) + dbTree = new DBTree(); + return dbTree; + } + + private DBTree(){ + tree = new JTree(); + //jsp = new JScrollPane(); + //tree = new JTree(); + } + // Create the tree for redis db + public javax.swing.JTree createTree() { + // Create the default tree + //tree = new JTree(); + // create the root node + rootNode = new DefaultMutableTreeNode(); + // set the title for the root node + rootNode.setUserObject(rootNodeTitle); + + spaceNode = new DefaultMutableTreeNode(); + spaceNode.setUserObject(spaceNodeTitle); + rootNode.add(spaceNode); + + // Create the model object for the tree and accepted the root node while generate + javax.swing.tree.DefaultTreeModel dm = new DefaultTreeModel(rootNode); + // set the model to the tree and show the loaded node on the tree + tree.setModel(dm); + tree.addTreeSelectionListener(new TreeSelectionListener() { + @Override + public void valueChanged(TreeSelectionEvent tse) { + Object selected = tree.getLastSelectedPathComponent(); + DefaultMutableTreeNode node = (DefaultMutableTreeNode)selected; + if(null!= node && node.isRoot()){ + //PopMessage.popMsg("Root node:[" + node +"]"); + } else { + String pathNode = tse.getPath().getLastPathComponent().toString(); + RedisTable.updateDetail(pathNode); + } + } + }); + /*tree.addMouseListener(new MouseListener() { + + @Override + public void mouseReleased(MouseEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void mousePressed(MouseEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void mouseExited(MouseEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void mouseEntered(MouseEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void mouseClicked(MouseEvent e) { + // TODO Auto-generated method stub + + } + });*/ + /*tree.addTreeWillExpandListener(new TreeWillExpandListener() { + + public void treeWillCollapse(TreeExpansionEvent event) {// close node --折叠 + } + public void treeWillExpand(TreeExpansionEvent event) + throws ExpandVetoException {// expend node --打开 + String pathNode = event.getPath().getLastPathComponent().toString(); + //System.out.println("pathNode:" + pathNode); + //PopMessage.popMsg(pathNode); + } + });*/ + return tree; + } + + public javax.swing.JTree clearTree() { + rootNode.removeAllChildren(); + return tree; + } + + public JTree getkeys(String filterText){ + // Get the encoding task list node: + allKeysNode = new DefaultMutableTreeNode(); + allKeysNode.setUserObject(keysTitle + "<" + RedisConstants.REDIS_SERVER_IP + ":" + RedisConstants.REDIS_SERVER_PORT + ":" + RedisConstants.REDIS_SERVER_DBINDEX +">"); + rootNode.add(allKeysNode); + + // get the encoding task id list from redis and add under this node + java.util.Set allKeysList = RedistDataManagement.listKeys(filterText); + + if(null != allKeysList && allKeysList.size() > 0){ + Iterator ite = allKeysList.iterator(); + String iteId = null; + //Integer setID = null; + while (ite.hasNext()) { + iteId = (String) ite.next(); + //System.out.println("iteId:" + iteId); + //setID = (null == iteId) ? 0 : Integer.valueOf(iteId); + // create the new leaf + DefaultMutableTreeNode allKeysLeaf = new DefaultMutableTreeNode(); + allKeysLeaf.setUserObject(iteId); + // add the profile leaf to the profile node + allKeysNode.add(allKeysLeaf); + } + } else { + // add the profile leaf to the profile node + DefaultMutableTreeNode allKeysNodeLeaf = new DefaultMutableTreeNode(); + allKeysNodeLeaf.setUserObject("no keys"); + // add the profile leaf to the profile node + allKeysNode.add(allKeysNodeLeaf); + } + + tree.removeAll(); + // Create the model object for the tree and accepted the root node while generate + javax.swing.tree.DefaultTreeModel dm = new DefaultTreeModel(allKeysNode); + //dm.setRoot(rootNode); + // set the model to the tree and show the loaded node on the tree + tree.setModel(dm); + return tree; + } + + /** + * @param filterText + * @return + */ +// public JScrollPane getTreePanel(String filterText) { +// tree = getkeys(filterText); +// jsp.add(tree); +// tree.setBounds(10, 10, 200, 430); +// tree.setVisible(true); +// //int width = jsp.getWidth(); +// //int height = jsp.getHeight(); +// //jsp.setPreferredSize(new Dimension(width, height)); +// //jsp.setBounds(10, 70, width, height); +// //jsp.setBounds(10, 70, 200, 380); +// //jsp.updateUI(); +// return jsp; +// } +} diff --git a/src/org/kevin/redis/ui/ComponentReUI.java b/src/org/kevin/redis/ui/ComponentReUI.java new file mode 100644 index 0000000..62d3c33 --- /dev/null +++ b/src/org/kevin/redis/ui/ComponentReUI.java @@ -0,0 +1,15 @@ +/** + * ComponentReUI.java + * kevin 2013-4-19 + * @version 0.1 + */ +package org.kevin.redis.ui; + +/** + * @author kevin + * @since jdk1.6 + */ +public interface ComponentReUI { + + void resize(); +} diff --git a/src/org/kevin/redis/validate/ClassPathResource.java b/src/org/kevin/redis/validate/ClassPathResource.java new file mode 100644 index 0000000..80d6560 --- /dev/null +++ b/src/org/kevin/redis/validate/ClassPathResource.java @@ -0,0 +1,30 @@ +/** + * ClassPathResource.java + * 2012 Jan 5, 2012 + */ +package org.kevin.redis.validate; + +import java.io.IOException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class ClassPathResource { + + /** + * @param args + */ + public static boolean isMobileNO(String mobiles){ + Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$"); + Matcher m = p.matcher(mobiles); + System.out.println(m.matches()+"---"); + return m.matches(); + } + public static void main(String[] args) throws IOException { + System.out.println(ClassPathResource.isMobileNO("18616155153")); + } + +} diff --git a/src/org/kevin/redis/validate/IPValidate.java b/src/org/kevin/redis/validate/IPValidate.java new file mode 100644 index 0000000..69875b1 --- /dev/null +++ b/src/org/kevin/redis/validate/IPValidate.java @@ -0,0 +1,50 @@ +/** + * IPValidate.java + * 2012 Jan 5, 2012 + */ +package org.kevin.redis.validate; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class IPValidate { + + public static void main(String args[]) { + /* + ipv4,如果需要依次group出来的话 + ^([01]?dd?|2[0-4]d|25[0-5]).([01]?dd?|2[0-4]d|25[0-5]). ([01]?dd?|2[0-4]d|25[0-5]).([01]?dd?|2[0-4]d|25[0-5])$ + + 如果只是验证,可以精简为 + ^(([01]?dd?|2[0-4]d|25[0-5]).){3}([01]?dd?|2[0-4]d|25[0-5])$ + */ + + //p("127.0.0.1".matches("[0,255]{1,3}.[0,255]{1,3}.[0,255]{1,3}.[0,255]{1,3}")); + //String IpRule = "^(([01]?dd?|2[0-4]d|25[0-5]).){3}([01]?dd?|2[0-4]d|25[0-5])$"; + //p("127.0.0.1".matches("")); + // System.out.println(ClassPathResource.isMobileNO("18616155153")); + System.out.println(IPValidate.isIP("192.168.30.7")); + } + + public static boolean isMobileNO(String mobiles) { + Pattern p = Pattern.compile("^((13[0-9])|(15[^4,D])|(18[0,5-9]))d{8}$"); + Matcher m = p.matcher(mobiles); + System.out.println(m.matches()+"---"); + return m.matches(); + } + + public static boolean isIP(String ip) { + System.out.println("Given Ip:" + ip); + //Pattern p = Pattern.compile("[0-255]+.[0-255]+.[0-255]+.[0-255]+"); + Pattern p = Pattern.compile("[0-9]+.[0-9]+.[0-9]+.[0-9]+"); + //Pattern p = Pattern.compile("((25[0-5]|2[0-4]d|1dd|[1-9]d|d).){3}(25[0-5]|2[0-4]d|1dd|[1-9]d|[1-9])"); + //Pattern p = Pattern.compile("^([01]?dd?|2[0-4]d|25[0-5]).([01]?dd?|2[0-4]d|25[0-5]).([01]?dd?|2[0-4]d|25[0-5]).([01]?dd?|2[0-4]d|25[0-5])$"); + //Pattern p = Pattern.compile("^(([01]?dd?|2[0-4]d|25[0-5]).){3}([01]?dd?|2[0-4]d|25[0-5])$"); + Matcher m = p.matcher(ip); + System.out.println(m.matches()+"---"); + return m.matches(); + } +} diff --git a/src/org/kevin/redis/validate/PortValidate.java b/src/org/kevin/redis/validate/PortValidate.java new file mode 100644 index 0000000..0d5a69a --- /dev/null +++ b/src/org/kevin/redis/validate/PortValidate.java @@ -0,0 +1,21 @@ +/** + * PortValidate.java + * 2012 Jan 5, 2012 + */ +package org.kevin.redis.validate; + +/** + * @author kevin + * @since Jdk 1.6 + */ +public class PortValidate { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/org/kevin/redis/window/AddWindow.java b/src/org/kevin/redis/window/AddWindow.java new file mode 100644 index 0000000..9989f38 --- /dev/null +++ b/src/org/kevin/redis/window/AddWindow.java @@ -0,0 +1,796 @@ +/** + * AddWindow.java + * kevin 2013-3-12 + * @version 0.1 + */ +package org.kevin.redis.window; + +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import javax.swing.BoxLayout; +import javax.swing.GroupLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; + +import org.kevin.redis.manage.HashMan; +import org.kevin.redis.manage.ListMan; +import org.kevin.redis.manage.SetMan; +import org.kevin.redis.manage.StringMan; +import org.kevin.redis.msg.PopMessage; + +/** + * @author kevin + * @since jdk1.6 + */ +public class AddWindow extends JFrame implements ActionListener { + /** + * + */ + private static final long serialVersionUID = 6004860134205994966L; + private static AddWindow addWindow; + private static String addWindowTitle = "Add window"; + private static JLabel addTypeLbl = new JLabel("Table Type:"); + //private static JLabel tableDetailLbl = new JLabel("Table Detail:"); + private JComboBox type_comboBox = null; + JScrollPane typejsp, detailjsp; + JPanel comboBoxPanel = null; + JTable table = null; + DefaultTableModel defaultModel = null; + private String selectedTableType = "Set"; + + //public static void main(String[] args) { + // new AddWindow().instance().showWindow(); + //} + + private AddWindow() { + setTitle(addWindowTitle); + + JPanel selectPanle = new JPanel(); + selectPanle.setLayout(new BoxLayout(selectPanle, BoxLayout.X_AXIS)); + // typejsp = new JScrollPane(); + // JLabel addTypeLbl = new JLabel("Table Type:"); + comboBoxPanel = new JPanel(); + // comboBoxPanel.setSize(100, 50); + // comboBoxPanel.setLayout(new BoxLayout(comboBoxPanel, BoxLayout.X_AXIS)); + // comboBoxPanel.setVisible(true); + + type_comboBox = new JComboBox(); + type_comboBox.addItem("Set"); + type_comboBox.addItem("Hash"); + type_comboBox.addItem("List"); + type_comboBox.addItem("String"); + type_comboBox.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent ae) { + JComboBox selectedObj = (JComboBox)ae.getSource(); + //PopMessage.popMsg("type_comboBox selected : " + selectedObj.getSelectedItem()); + selectedTableType = selectedObj.getSelectedItem().toString(); + showDiffContents(selectedTableType); + } + }); + selectPanle.add(addTypeLbl); + selectPanle.add(type_comboBox); + //type_comboBox.setPreferredSize(new Dimension(100,50)); + type_comboBox.setLocation(80, 20); + + GroupLayout layout = new GroupLayout(this.getContentPane()); + this.getContentPane().setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(selectPanle, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE) + //.addComponent(addTypeLbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 600,GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) + //hGroup.addGroup(layout.createParallelGroup(Alignment.LEADING) + // .addComponent(type_comboBox, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 680,GroupLayout.PREFERRED_SIZE) + // ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 300,GroupLayout.PREFERRED_SIZE)); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + //.addComponent(addTypeLbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(type_comboBox, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + .addComponent(selectPanle, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE) + ); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + showDiffContents("Set"); + // comboBoxPanel.setLayout(layout); + // type_comboBox.setPreferredSize(new Dimension(50,50)); + // comboBoxPanel.setPreferredSize(new Dimension(50,50)); + // typejsp.add(addTypeLbl); + // comboBoxPanel.add(addTypeLbl); + // addTypeLbl.setBounds(10, 0, 50, 50); + + // typejsp.add(type_comboBox); + // comboBoxPanel.add(typejsp); + // comboBoxPanel.add(type_comboBox); + // type_comboBox.setBounds(60, 0, 50, 50); + // type_comboBox.setPreferredSize(new Dimension(50,50)); + + // this.getContentPane().add(typejsp, BorderLayout.NORTH); + // this.getContentPane().add(comboBoxPanel); + // comboBoxPanel.setPreferredSize(new Dimension(30,50)); + + // comboBoxPanel.setVisible(true); + // addTypeLbl.setVisible(true); + // comboBoxPanel.setBounds(10, 10, 100, 200); + // typejsp.updateUI(); + // typejsp.setVisible(true); + + // detailjsp = new JScrollPane(); + // JPanel detailPanel = new JPanel(); + // detailPanel.add(tableDetailLbl); + // detailjsp.add(detailPanel); + // this.getContentPane().add(detailPanel, BorderLayout.SOUTH); + // detailjsp.setBounds(10, 50, 400, 100); + // detailjsp.updateUI(); + // PopMessage.popMsg("Create the add window"); + }; + + public void showDiffContents(String tableType) { + comboBoxPanel.removeAll(); + + //JLabel tableTypelbl = new JLabel("Add type:" + tableType); + + //comboBoxPanel.setLayout(new BoxLayout(comboBoxPanel, BoxLayout.Y_AXIS)); + //comboBoxPanel.add(tableTypelbl); + + // init the ui + if("set".equalsIgnoreCase(tableType)){ + initSetTable(tableType); + } else if("list".equalsIgnoreCase(tableType)){ + initListTable(tableType); + } else if("hash".equalsIgnoreCase(tableType)){ + initHashTable(tableType); + } else if("string".equalsIgnoreCase(tableType)){ + initStringTable(tableType); + } else { + PopMessage.popMsg("Unsupported table type"); + } + // fresh + comboBoxPanel.updateUI(); + } + + public void initHashTable(final String tableType){ + + JLabel tableTypelbl = new JLabel("Add type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + String[] taskHeaders = { "Field", "Value", "Type" }; + String[][] setInfo = {{"key", "", ""}}; + + defaultModel = new DefaultTableModel(setInfo, taskHeaders); + + table = new JTable(defaultModel); + table.setName(tableType + "<" + tableNameText.getText() + ">"); + AlignColumn(table, taskHeaders[0] , SwingConstants.CENTER); + + JScrollPane panel = new JScrollPane(); + panel.setViewportView(table); + + JButton addSetBtn = new JButton("Save Data"); + addSetBtn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + String key = tableNameText.getText(); + if(key.isEmpty()){ + PopMessage.popMsg("Added type:[" + tableType + "] Table Key is required"); + } else { + + Map vMap = new HashMap(); + int rows = table.getRowCount(); + //table.getCellEditor(0, 0).getCellEditorValue(); + String cellField = null; + String cellValue = null; + for(int i = 0; i < rows; i ++){ + cellField = (String) table.getValueAt(i, 0); + cellValue = (String) table.getValueAt(i, 1); + //System.out.println("Get cellValue:[" + cellValue +"] at:["+ i + ", 0]"); + vMap.put(cellField, cellValue); + } + //StringBuilder values = new StringBuilder(); + //for(String value: vectorValues){ + //System.out.println("Get cellValue:[" + value +"] from vector"); + // values.append(value).append(","); + // } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + key + "] value:[ ... ]"); + //new HashMan().add(key, vMap); + int effectRow = new HashMan().add(key, vMap); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + } + }); + + //JPanel cellPanel = new JPanel(); + //cellPanel.add(addSetBtn); + + JPanel btnPanel = new JPanel(); + //btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS)); + btnPanel.add(addSetBtn); + //JScrollPane btnPanel = new JScrollPane(); + //addSetBtn.setSize(60, 20); + + JButton addRow = new JButton("Add Row"); + btnPanel.add(addRow); + addRow.addActionListener(this); + //addRow.setSize(60, 20); + + JButton addColumn = new JButton("Add Column"); + //btnPanel.add(addColumn); + addColumn.addActionListener(this); + //addColumn.setSize(60, 20); + + JButton removeRow = new JButton("Remove Row"); + btnPanel.add(removeRow); + removeRow.addActionListener(this); + //removeRow.setSize(60, 20); + + JButton removeColumn = new JButton("Remove Column"); + //btnPanel.add(removeColumn); + removeColumn.addActionListener(this); + //removeColumn.setSize(60, 20); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE) + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) + ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup() + // .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + // ); + //btnPanel.setAlignmentX(SwingConstants.RIGHT); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(panel, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup() + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + // ); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + ); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup().addComponent(addRow, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + } + + public void initListTable(final String tableType){ + + JLabel tableTypelbl = new JLabel("Add type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + String[] taskHeaders = { "Index", "Value", "Type" }; + String[][] setInfo = {{"1", "", ""}}; + + defaultModel = new DefaultTableModel(setInfo, taskHeaders); + + table = new JTable(defaultModel); + table.setName(tableType + "<" + tableNameText.getText() + ">"); + AlignColumn(table, taskHeaders[0] , SwingConstants.CENTER); + + JScrollPane panel = new JScrollPane(); + panel.setViewportView(table); + + JButton addSetBtn = new JButton("Save Data"); + addSetBtn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + String key = tableNameText.getText(); + if(key.isEmpty()){ + PopMessage.popMsg("Added type:[" + tableType + "] Table Key is required"); + } else { + + List vlist = new ArrayList(); + int rows = table.getRowCount(); + //table.getCellEditor(0, 0).getCellEditorValue(); + String cellValue = null; + for(int i = 0; i < rows; i ++){ + //cellValue = (String) table.getCellEditor(i, 1).getCellEditorValue(); + cellValue = (String) table.getValueAt(i, 1); + //System.out.println("Get cellValue:[" + cellValue +"] at:["+ i + ", 0]"); + vlist.add(i, cellValue); + } + //StringBuilder values = new StringBuilder(); + //for(String value: vectorValues){ + //System.out.println("Get cellValue:[" + value +"] from vector"); + // values.append(value).append(","); + // } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + tableNameText.getText() + "] value:[ ... ]"); + //new SetMan().add(key, vlist); + int effectRow = new ListMan().add(key, vlist); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + tableNameText.getText() + "] value:[" + strTableNameText.getText() + "]"); + } + }); + + //JPanel cellPanel = new JPanel(); + //cellPanel.add(addSetBtn); + + JPanel btnPanel = new JPanel(); + //btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS)); + btnPanel.add(addSetBtn); + //JScrollPane btnPanel = new JScrollPane(); + //addSetBtn.setSize(60, 20); + + JButton addRow = new JButton("Add Row"); + btnPanel.add(addRow); + addRow.addActionListener(this); + //addRow.setSize(60, 20); + + JButton addColumn = new JButton("Add Column"); + //btnPanel.add(addColumn); + addColumn.addActionListener(this); + //addColumn.setSize(60, 20); + + JButton removeRow = new JButton("Remove Row"); + btnPanel.add(removeRow); + removeRow.addActionListener(this); + //removeRow.setSize(60, 20); + + JButton removeColumn = new JButton("Remove Column"); + //btnPanel.add(removeColumn); + removeColumn.addActionListener(this); + //removeColumn.setSize(60, 20); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE) + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) + ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup() + // .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + // ); + //btnPanel.setAlignmentX(SwingConstants.RIGHT); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(panel, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup() + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + // ); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + ); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup().addComponent(addRow, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + } + + public void initSetTable(final String tableType){ + + JLabel tableTypelbl = new JLabel("Add type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + String[] taskHeaders = { "Field", "Value", "Type" }; + String[][] setInfo = {{"", "", ""}}; + + defaultModel = new DefaultTableModel(setInfo, taskHeaders); + + table = new JTable(defaultModel); + table.setName(tableType + "<" + tableNameText.getText() + ">"); + AlignColumn(table, taskHeaders[0] , SwingConstants.CENTER); + + JScrollPane panel = new JScrollPane(); + panel.setViewportView(table); + + JButton addSetBtn = new JButton("Save Data"); + addSetBtn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + String key = tableNameText.getText(); + if(key.isEmpty()){ + PopMessage.popMsg("Added type:[" + tableType + "] Table Key is required"); + } else { + Vector vectorValues = new Vector(); + int rows = table.getRowCount(); + //table.getCellEditor(0, 0).getCellEditorValue(); + String cellValue = null; + for(int i = 0; i < rows; i ++){ + //cellValue = (String) table.getCellEditor(i, 1).getCellEditorValue(); + cellValue = (String) table.getValueAt(i, 1); + //System.out.println("Get cellValue:[" + cellValue +"] at:["+ i + ", 0]"); + vectorValues.add(i, cellValue); + } + //StringBuilder values = new StringBuilder(); + //for(String value: vectorValues){ + //System.out.println("Get cellValue:[" + value +"] from vector"); + // values.append(value).append(","); + // } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + tableNameText.getText() + "] value:[" + values.toString() + "]"); + //new SetMan().add(key, vectorValues); + int effectRow = new SetMan().add(key, vectorValues); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + } + }); + + //JPanel cellPanel = new JPanel(); + //cellPanel.add(addSetBtn); + + JPanel btnPanel = new JPanel(); + //btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS)); + btnPanel.add(addSetBtn); + //JScrollPane btnPanel = new JScrollPane(); + //addSetBtn.setSize(60, 20); + + JButton addRow = new JButton("Add Row"); + btnPanel.add(addRow); + addRow.addActionListener(this); + //addRow.setSize(60, 20); + + JButton addColumn = new JButton("Add Column"); + //btnPanel.add(addColumn); + addColumn.addActionListener(this); + //addColumn.setSize(60, 20); + + JButton removeRow = new JButton("Remove Row"); + btnPanel.add(removeRow); + removeRow.addActionListener(this); + //removeRow.setSize(60, 20); + + JButton removeColumn = new JButton("Remove Column"); + //btnPanel.add(removeColumn); + removeColumn.addActionListener(this); + //removeColumn.setSize(60, 20); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE) + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) + ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup() + // .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + // ); + //btnPanel.setAlignmentX(SwingConstants.RIGHT); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(panel, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup() + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + // ); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + ); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup().addComponent(addRow, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + } + + public void initStringTable(final String tableType){ + + JLabel tableTypelbl = new JLabel("Add type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + //comboBoxPanel.add(tableNamelbl); + //comboBoxPanel.add(tableName); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + final JTextField strTableNameText = new JTextField(); + + JButton addStrBtn = new JButton("Save Data"); + //addStrBtn.addActionListener(this); + addStrBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String key = tableNameText.getText(); + String value = strTableNameText.getText(); + //int effectRows = new StringMan().add(key, value); + int effectRow = new StringMan().add(key, value); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + //if(effectRows > 0){ + // PopMessage.popMsg("Added type:[" + tableType + "] key:[" + key + "] value:[" + value + "] success"); + //} else { + // PopMessage.popWarn("Added type:[" + tableType + "] key:[" + key + "] value:[" + value + "] Fail"); + //} + } + }); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableNameText, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE) + .addComponent(addStrBtn, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(addbtn, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(addStrBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + //comboBoxPanel.add(strTableValuelbl); + //comboBoxPanel.add(strTableNameText); + } + + private static void AlignColumn(JTable comp, String column, final int position){ + comp.getColumn(column).setCellRenderer( + new DefaultTableCellRenderer() { // rewrite setValue method + private static final long serialVersionUID = 1L; + + public void setValue(Object value) { + this.setHorizontalAlignment(position); + super.setValue(value); + } + }); + } + + public static AddWindow instance() { + if (null == addWindow) + addWindow = new AddWindow(); + return addWindow; + } + + public void showWindow() { + // make the frame to be loadded at windows center + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension screenSize = kit.getScreenSize(); + int screenHeight = screenSize.height; + int screenWidth = screenSize.width; + // int width = 300; + int width = 800; + // int height = 200; + int height = 600; + setLocation((screenWidth - width) / 2, (screenHeight - height) / 2); + + // setBounds(200, 200, 400, 300); + setSize(680, 480); + // this.setLocation(100, 100); + // this.setSize(300, 200); + // this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + this.setVisible(true); + // this.setAlwaysOnTop(true); + addWindowListener(new HandlePopWin()); + } + + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("Add Column")){ + PopMessage.popMsg("Invalid new column for this window"); + //defaultModel.addColumn("AddColumn"); + } + if (e.getActionCommand().equals("Add Row")) + defaultModel.addRow(new Vector()); + if (e.getActionCommand().equals("Remove Column")) { + PopMessage.popMsg("Invalid new column for this window"); +// int columncount = defaultModel.getColumnCount() - 1; +// if (columncount >= 0) { +// TableColumnModel columnModel = table.getColumnModel(); +// TableColumn tableColumn = columnModel.getColumn(columncount); +// columnModel.removeColumn(tableColumn); +// defaultModel.setColumnCount(columncount); +// } + } + if (e.getActionCommand().equals("Remove Row")) { + int rowcount = defaultModel.getRowCount() - 1; + if (rowcount >= 0) { + defaultModel.removeRow(rowcount); + defaultModel.setRowCount(rowcount); + } + } + table.revalidate(); + } + + class HandlePopWin extends WindowAdapter { + public void windowClosing(WindowEvent e) { + // e.getWindow().setVisible(false); + (e.getWindow()).dispose(); + //System.exit(0); + // (new Frame()).setVisible(false); + // this.windowClosed(e); + } + } +} diff --git a/src/org/kevin/redis/window/CopyWindow.java b/src/org/kevin/redis/window/CopyWindow.java new file mode 100644 index 0000000..c66b5fb --- /dev/null +++ b/src/org/kevin/redis/window/CopyWindow.java @@ -0,0 +1,963 @@ +/** + * AddWindow.java + * kevin 2013-3-12 + * @version 0.1 + */ +package org.kevin.redis.window; + +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +import javax.swing.BoxLayout; +import javax.swing.GroupLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableModel; +import javax.swing.table.TableRowSorter; + +import org.kevin.redis.manage.HashMan; +import org.kevin.redis.manage.ListMan; +import org.kevin.redis.manage.RedisTableMan; +import org.kevin.redis.manage.SetMan; +import org.kevin.redis.manage.StringMan; +import org.kevin.redis.msg.PopMessage; + +import com.sun.xml.internal.ws.util.StringUtils; + +/** + * @author kevin + * @since jdk1.6 + */ +public class CopyWindow extends JFrame implements ActionListener { + /** + * + */ + private static final long serialVersionUID = 6004860134205994966L; + private static CopyWindow editWindow; + private static String editWindowTitle = "Copy window"; + private static JLabel editTypeLbl = new JLabel("Table Type:"); + //private static JLabel tableDetailLbl = new JLabel("Table Detail:"); + private JComboBox type_comboBox = null; + JScrollPane typejsp, detailjsp; + JPanel comboBoxPanel = null; + JTable table = null; + DefaultTableModel defaultModel = null; + private String selectedTableType = "Set"; + private String currentType = "Set"; + private String KEY_COPY = ".copy"; + + public static void main(String[] args) { + new CopyWindow().instance().showWindow(); + } + + private CopyWindow() { + setTitle(editWindowTitle); + + JPanel selectPanle = new JPanel(); + selectPanle.setLayout(new BoxLayout(selectPanle, BoxLayout.X_AXIS)); + // typejsp = new JScrollPane(); + // JLabel addTypeLbl = new JLabel("Table Type:"); + comboBoxPanel = new JPanel(); + // comboBoxPanel.setSize(100, 50); + // comboBoxPanel.setLayout(new BoxLayout(comboBoxPanel, BoxLayout.X_AXIS)); + comboBoxPanel.setVisible(true); + + type_comboBox = new JComboBox(); + type_comboBox.addItem("Set"); + type_comboBox.addItem("Hash"); + type_comboBox.addItem("List"); + type_comboBox.addItem("String"); + type_comboBox.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent ae) { + JComboBox selectedObj = (JComboBox)ae.getSource(); + //PopMessage.popMsg("type_comboBox selected : " + selectedObj.getSelectedItem()); + selectedTableType = selectedObj.getSelectedItem().toString(); + showDiffContents(selectedTableType); + } + }); + selectPanle.add(editTypeLbl); + selectPanle.add(type_comboBox); + //type_comboBox.setPreferredSize(new Dimension(100,50)); + //type_comboBox.setLocation(80, 20); + + GroupLayout layout = new GroupLayout(this.getContentPane()); + this.getContentPane().setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(selectPanle, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE) + //.addComponent(addTypeLbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 600,GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) + //hGroup.addGroup(layout.createParallelGroup(Alignment.LEADING) + // .addComponent(type_comboBox, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 680,GroupLayout.PREFERRED_SIZE) + // ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 300,GroupLayout.PREFERRED_SIZE)); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + //.addComponent(addTypeLbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(type_comboBox, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + .addComponent(selectPanle, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE) + ); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + //showDiffContents("Set"); + //type_comboBox.setSelectedItem(selectedTableType); + + // comboBoxPanel.setLayout(layout); + // type_comboBox.setPreferredSize(new Dimension(50,50)); + // comboBoxPanel.setPreferredSize(new Dimension(50,50)); + // typejsp.add(addTypeLbl); + // comboBoxPanel.add(addTypeLbl); + // addTypeLbl.setBounds(10, 0, 50, 50); + + // typejsp.add(type_comboBox); + // comboBoxPanel.add(typejsp); + // comboBoxPanel.add(type_comboBox); + // type_comboBox.setBounds(60, 0, 50, 50); + // type_comboBox.setPreferredSize(new Dimension(50,50)); + + // this.getContentPane().add(typejsp, BorderLayout.NORTH); + // this.getContentPane().add(comboBoxPanel); + // comboBoxPanel.setPreferredSize(new Dimension(30,50)); + + // comboBoxPanel.setVisible(true); + // addTypeLbl.setVisible(true); + // comboBoxPanel.setBounds(10, 10, 100, 200); + // typejsp.updateUI(); + // typejsp.setVisible(true); + + // detailjsp = new JScrollPane(); + // JPanel detailPanel = new JPanel(); + // detailPanel.add(tableDetailLbl); + // detailjsp.add(detailPanel); + // this.getContentPane().add(detailPanel, BorderLayout.SOUTH); + // detailjsp.setBounds(10, 50, 400, 100); + // detailjsp.updateUI(); + // PopMessage.popMsg("Create the add window"); + }; + + public void showDiffContents(String tableType) { + comboBoxPanel.removeAll(); + + //JLabel tableTypelbl = new JLabel("Add type:" + tableType); + + //comboBoxPanel.setLayout(new BoxLayout(comboBoxPanel, BoxLayout.Y_AXIS)); + //comboBoxPanel.add(tableTypelbl); + + // init the ui + if("set".equalsIgnoreCase(tableType)){ + initSetTable(null, tableType); + } else if("list".equalsIgnoreCase(tableType)){ + initListTable(null, tableType); + } else if("hash".equalsIgnoreCase(tableType)){ + initHashTable(null, tableType); + } else if("string".equalsIgnoreCase(tableType)){ + initStringTable(null, tableType); + } else { + PopMessage.popMsg("Unsupported table type"); + } + // fresh + comboBoxPanel.updateUI(); + } + + public void initHashTable(String key, final String tableType){ + + JLabel tableTypelbl = new JLabel("Table type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + String[] tableHeaders = { "Field", "Value", "Type" }; + //String[][] setInfo = {{"key", "", ""}}; + + Map value = null; + if(null == key){ + key = ""; + } else { + value = new HashMan().list(key); + } + tableNameText.setText(key + KEY_COPY); + + //JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + //String[] taskHeaders = { "Index", "Value", "Type" }; + final String space = ""; + String[][] valueInfo = null; + if(null != value && value.size() > 0){ + int arraySize = value.size(); + valueInfo = new String[arraySize][3]; + Set keySet = value.keySet(); + Iterator ite = keySet.iterator(); + String iteId = null; + int i = 0; + while (ite.hasNext()) { + iteId = (String) ite.next(); + valueInfo[i][0] = iteId; + valueInfo[i][1] = value.get(iteId); + valueInfo[i][2] = space; + i++; + } + } else { + valueInfo = new String[1][3]; + valueInfo[0][0] = ""; + valueInfo[0][1] = ""; + valueInfo[0][2] = ""; + } + + //defaultModel = new DefaultTableModel(valueInfo, tableHeaders); + + //table = new JTable(defaultModel); + //table.setName(tableType + "<" + tableNameText.getText() + ">"); + + + // set the table header to be sorted + DefaultTableModel dtm = new DefaultTableModel(valueInfo, tableHeaders); + table = new JTable(dtm); + table.setRowSorter(new TableRowSorter(dtm)); + + AlignColumn(table, tableHeaders[0] , SwingConstants.CENTER); + + JScrollPane panel = new JScrollPane(); + panel.setViewportView(table); + + JButton addSetBtn = new JButton("Save Data"); + addSetBtn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + String key = tableNameText.getText(); + if(key.isEmpty()){ + PopMessage.popMsg("Added type:[" + tableType + "] Table Key is required"); + } else { + + Map vMap = new HashMap(); + int rows = table.getRowCount(); + //table.getCellEditor(0, 0).getCellEditorValue(); + String cellField = null; + String cellValue = null; + for(int i = 0; i < rows; i ++){ + cellField = (String) table.getValueAt(i, 0); + cellValue = (String) table.getValueAt(i, 1); + //System.out.println("Get cellValue:[" + cellValue +"] at:["+ i + ", 0]"); + vMap.put(cellField, cellValue); + } + //StringBuilder values = new StringBuilder(); + //for(String value: vectorValues){ + //System.out.println("Get cellValue:[" + value +"] from vector"); + // values.append(value).append(","); + // } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + key + "] value:[ ... ]"); + int effectRow = new HashMan().add(key, vMap); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + } + }); + + //JPanel cellPanel = new JPanel(); + //cellPanel.add(addSetBtn); + + JPanel btnPanel = new JPanel(); + //btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS)); + btnPanel.add(addSetBtn); + //JScrollPane btnPanel = new JScrollPane(); + //addSetBtn.setSize(60, 20); + + JButton addRow = new JButton("Add Row"); + btnPanel.add(addRow); + addRow.addActionListener(this); + //addRow.setSize(60, 20); + + JButton addColumn = new JButton("Add Column"); + //btnPanel.add(addColumn); + addColumn.addActionListener(this); + //addColumn.setSize(60, 20); + + JButton removeRow = new JButton("Remove Row"); + btnPanel.add(removeRow); + removeRow.addActionListener(this); + //removeRow.setSize(60, 20); + + JButton removeColumn = new JButton("Remove Column"); + //btnPanel.add(removeColumn); + removeColumn.addActionListener(this); + //removeColumn.setSize(60, 20); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE) + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) + ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup() + // .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + // ); + //btnPanel.setAlignmentX(SwingConstants.RIGHT); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(panel, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup() + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + // ); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + ); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup().addComponent(addRow, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + } + + public void initListTable(String key, final String tableType){ + + JLabel tableTypelbl = new JLabel("Table type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + + List value = null; + if(null == key){ + key = ""; + } else { + value = new ListMan().list(key); + } + tableNameText.setText(key + KEY_COPY); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + String[] tableHeaders = { "Index", "Value", "Type" }; + final String space = ""; + String[][] valueInfo = null; + if(null != value && value.size() > 0){ + int arraySize = value.size(); + valueInfo = new String[arraySize][3]; + int i = 0; + for(String v : value){ + valueInfo[i][0] = space + (i + 1); + valueInfo[i][1] = v; + valueInfo[i][2] = "String"; + i++; + } + } else { + valueInfo = new String[1][3]; + valueInfo[0][0] = ""; + valueInfo[0][1] = ""; + valueInfo[0][2] = ""; + } + + //JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + //String[] taskHeaders = { "Index", "Value", "Type" }; + //String[][] setInfo = {{"1", "", ""}}; + + //defaultModel = new DefaultTableModel(valueInfo, taskHeaders); + //table = new JTable(defaultModel); + //table.setName(tableType + "<" + tableNameText.getText() + ">"); + + // set the table header to be sorted + DefaultTableModel dtm = new DefaultTableModel(valueInfo, tableHeaders); + table = new JTable(dtm); + table.setRowSorter(new TableRowSorter(dtm)); + + AlignColumn(table, tableHeaders[0] , SwingConstants.CENTER); + + JScrollPane panel = new JScrollPane(); + panel.setViewportView(table); + + JButton addSetBtn = new JButton("Save Data"); + addSetBtn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + String key = tableNameText.getText(); + if(key.isEmpty()){ + PopMessage.popMsg("Added type:[" + tableType + "] Table Key is required"); + } else { + + List vlist = new ArrayList(); + int rows = table.getRowCount(); + //table.getCellEditor(0, 0).getCellEditorValue(); + String cellValue = null; + for(int i = 0; i < rows; i ++){ + //cellValue = (String) table.getCellEditor(i, 1).getCellEditorValue(); + cellValue = (String) table.getValueAt(i, 1); + //System.out.println("Get cellValue:[" + cellValue +"] at:["+ i + ", 0]"); + vlist.add(i, cellValue); + } + //StringBuilder values = new StringBuilder(); + //for(String value: vectorValues){ + //System.out.println("Get cellValue:[" + value +"] from vector"); + // values.append(value).append(","); + // } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + tableNameText.getText() + "] value:[ ... ]"); + //new SetMan().add(key, vlist); + int effectRow = new ListMan().add(key, vlist); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + tableNameText.getText() + "] value:[" + strTableNameText.getText() + "]"); + } + }); + + //JPanel cellPanel = new JPanel(); + //cellPanel.add(addSetBtn); + + JPanel btnPanel = new JPanel(); + //btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS)); + btnPanel.add(addSetBtn); + //JScrollPane btnPanel = new JScrollPane(); + //addSetBtn.setSize(60, 20); + + JButton addRow = new JButton("Add Row"); + btnPanel.add(addRow); + addRow.addActionListener(this); + //addRow.setSize(60, 20); + + JButton addColumn = new JButton("Add Column"); + //btnPanel.add(addColumn); + addColumn.addActionListener(this); + //addColumn.setSize(60, 20); + + JButton removeRow = new JButton("Remove Row"); + btnPanel.add(removeRow); + removeRow.addActionListener(this); + //removeRow.setSize(60, 20); + + JButton removeColumn = new JButton("Remove Column"); + //btnPanel.add(removeColumn); + removeColumn.addActionListener(this); + //removeColumn.setSize(60, 20); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE) + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) + ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup() + // .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + // ); + //btnPanel.setAlignmentX(SwingConstants.RIGHT); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(panel, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup() + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + // ); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + ); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup().addComponent(addRow, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + } + + public void initSetTable(String key, final String tableType){ + + JLabel tableTypelbl = new JLabel("Table type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + + Set value = null; + if(null == key){ + key = ""; + } else { + value = new SetMan().list(key); + } + tableNameText.setText(key + KEY_COPY); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + String[] tableHeaders = { "Field", "Value", "Type" }; + final String space = ""; + String[][] valueInfo = null; + if(null != value && value.size() > 0){ + int arraySize = value.size(); + valueInfo = new String[arraySize][3]; + int i = 0; + for(String setv : value){ + valueInfo[i][0] = space + (i + 1); + valueInfo[i][1] = setv; + valueInfo[i][2] = "String"; + i++; + } + } else { + valueInfo = new String[1][3]; + valueInfo[0][0] = ""; + valueInfo[0][1] = ""; + valueInfo[0][2] = ""; + } + + //defaultModel = new DefaultTableModel(valueInfo, taskHeaders); + //table = new JTable(defaultModel); + //table.setName(tableType + "<" + tableNameText.getText() + ">"); + + // set the table header to be sorted + DefaultTableModel dtm = new DefaultTableModel(valueInfo, tableHeaders); + table = new JTable(dtm); + table.setRowSorter(new TableRowSorter(dtm)); + + AlignColumn(table, tableHeaders[0] , SwingConstants.CENTER); + + JScrollPane panel = new JScrollPane(); + panel.setViewportView(table); + + JButton addSetBtn = new JButton("Save Data"); + addSetBtn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + String key = tableNameText.getText(); + if(key.isEmpty()){ + PopMessage.popMsg("Added type:[" + tableType + "] Table Key is required"); + } else { + Vector vectorValues = new Vector(); + int rows = table.getRowCount(); + //table.getCellEditor(0, 0).getCellEditorValue(); + String cellValue = null; + for(int i = 0; i < rows; i ++){ + //cellValue = (String) table.getCellEditor(i, 1).getCellEditorValue(); + cellValue = (String) table.getValueAt(i, 1); + //System.out.println("Get cellValue:[" + cellValue +"] at:["+ i + ", 0]"); + vectorValues.add(i, cellValue); + } + //StringBuilder values = new StringBuilder(); + //for(String value: vectorValues){ + //System.out.println("Get cellValue:[" + value +"] from vector"); + // values.append(value).append(","); + // } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + tableNameText.getText() + "] value:[" + values.toString() + "]"); + //new SetMan().add(key, vectorValues); + int effectRow = new SetMan().add(key, vectorValues); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + } + }); + + //JPanel cellPanel = new JPanel(); + //cellPanel.add(addSetBtn); + + JPanel btnPanel = new JPanel(); + //btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS)); + btnPanel.add(addSetBtn); + //JScrollPane btnPanel = new JScrollPane(); + //addSetBtn.setSize(60, 20); + + JButton addRow = new JButton("Add Row"); + btnPanel.add(addRow); + addRow.addActionListener(this); + //addRow.setSize(60, 20); + + JButton addColumn = new JButton("Add Column"); + //btnPanel.add(addColumn); + addColumn.addActionListener(this); + //addColumn.setSize(60, 20); + + JButton removeRow = new JButton("Remove Row"); + btnPanel.add(removeRow); + removeRow.addActionListener(this); + //removeRow.setSize(60, 20); + + JButton removeColumn = new JButton("Remove Column"); + //btnPanel.add(removeColumn); + removeColumn.addActionListener(this); + //removeColumn.setSize(60, 20); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE) + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) + ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup() + // .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + // ); + //btnPanel.setAlignmentX(SwingConstants.RIGHT); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(panel, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup() + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + // ); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + ); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup().addComponent(addRow, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + } + + public void initStringTable(String key, final String tableType){ + + JLabel tableTypelbl = new JLabel("Table type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + String value = ""; + if(null == key){ + key = ""; + } else { + value = new StringMan().list(key); + } + tableNameText.setText(key + KEY_COPY); + + //comboBoxPanel.add(tableNamelbl); + //comboBoxPanel.add(tableName); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + final JTextField tableValueText = new JTextField(); + tableValueText.setText(value); + + // do search and get the data from redis + + JButton addStrBtn = new JButton("Save Data"); + //addStrBtn.addActionListener(this); + addStrBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String key = tableNameText.getText(); + String value = tableValueText.getText(); + //int effectRows = new StringMan().add(key, value); + //if(effectRows > 0){ + // PopMessage.popMsg("Added type:[" + tableType + "] key:[" + key + "] value:[" + value + "] success"); + // } else { + // PopMessage.popWarn("Added type:[" + tableType + "] key:[" + key + "] value:[" + value + "] Fail"); + //} + int effectRow = new StringMan().add(key, value); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + }); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE) + .addComponent(tableValueText, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE) + .addComponent(addStrBtn, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(addbtn, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableValueText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(addStrBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + //comboBoxPanel.add(strTableValuelbl); + //comboBoxPanel.add(strTableNameText); + } + + private static void AlignColumn(JTable comp, String column, final int position){ + comp.getColumn(column).setCellRenderer( + new DefaultTableCellRenderer() { // rewrite setValue method + private static final long serialVersionUID = 1L; + + public void setValue(Object value) { + this.setHorizontalAlignment(position); + super.setValue(value); + } + }); + } + + public static CopyWindow instance() { + if (null == editWindow) + editWindow = new CopyWindow(); + return editWindow; + } + + public void showWindow(String key) { + String type = RedisTableMan.getType(key); + String _curr = StringUtils.capitalize(type); + setCurrentType(_curr); + type_comboBox.setSelectedItem(_curr); + type_comboBox.setEnabled(false); + fileTableDate(key, _curr); + showWindow(); + } + + + /** + * @param currentType the currentType to set + */ + public final void setCurrentType(String currentType) { + this.currentType = currentType; + } + + /** + * @param key + * + */ + private void fileTableDate(String key, String tableType) { + if("set".equalsIgnoreCase(tableType)){ + initSetTable(key, tableType); + } else if("list".equalsIgnoreCase(tableType)){ + initListTable(key, tableType); + } else if("hash".equalsIgnoreCase(tableType)){ + initHashTable(key, tableType); + } else if("string".equalsIgnoreCase(tableType)){ + initStringTable(key, tableType); + } else { + PopMessage.popMsg("Unsupported table type"); + } + // fresh + comboBoxPanel.updateUI(); + } + + public void showWindow() { + // make the frame to be loadded at windows center + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension screenSize = kit.getScreenSize(); + int screenHeight = screenSize.height; + int screenWidth = screenSize.width; + // int width = 300; + int width = 800; + // int height = 200; + int height = 600; + setLocation((screenWidth - width) / 2, (screenHeight - height) / 2); + + // setBounds(200, 200, 400, 300); + setSize(680, 480); + // this.setLocation(100, 100); + // this.setSize(300, 200); + // this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + this.setVisible(true); + // this.setAlwaysOnTop(true); + addWindowListener(new HandlePopWin()); + } + + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("Add Column")){ + PopMessage.popMsg("Invalid new column for this window"); + //defaultModel.addColumn("AddColumn"); + } + if (e.getActionCommand().equals("Add Row")) + defaultModel.addRow(new Vector()); + if (e.getActionCommand().equals("Remove Column")) { + PopMessage.popMsg("Invalid new column for this window"); +// int columncount = defaultModel.getColumnCount() - 1; +// if (columncount >= 0) { +// TableColumnModel columnModel = table.getColumnModel(); +// TableColumn tableColumn = columnModel.getColumn(columncount); +// columnModel.removeColumn(tableColumn); +// defaultModel.setColumnCount(columncount); +// } + } + if (e.getActionCommand().equals("Remove Row")) { + int rowcount = defaultModel.getRowCount() - 1; + if (rowcount >= 0) { + defaultModel.removeRow(rowcount); + defaultModel.setRowCount(rowcount); + } + } + table.revalidate(); + } + + class HandlePopWin extends WindowAdapter { + public void windowClosing(WindowEvent e) { + // e.getWindow().setVisible(false); + (e.getWindow()).dispose(); + //System.exit(0); + // (new Frame()).setVisible(false); + // this.windowClosed(e); + } + } +} diff --git a/src/org/kevin/redis/window/EditWindow.java b/src/org/kevin/redis/window/EditWindow.java new file mode 100644 index 0000000..56909fa --- /dev/null +++ b/src/org/kevin/redis/window/EditWindow.java @@ -0,0 +1,987 @@ +/** + * AddWindow.java + * kevin 2013-3-12 + * @version 0.1 + */ +package org.kevin.redis.window; + +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +import javax.swing.BoxLayout; +import javax.swing.GroupLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableModel; +import javax.swing.table.TableRowSorter; + +import org.kevin.redis.manage.HashMan; +import org.kevin.redis.manage.ListMan; +import org.kevin.redis.manage.RedisTableMan; +import org.kevin.redis.manage.SetMan; +import org.kevin.redis.manage.StringMan; +import org.kevin.redis.msg.PopMessage; + +import com.sun.xml.internal.ws.util.StringUtils; + +/** + * @author kevin + * @since jdk1.6 + */ +public class EditWindow extends JFrame implements ActionListener { + /** + * + */ + private static final long serialVersionUID = 6004860134205994966L; + private static EditWindow editWindow; + private static String editWindowTitle = "Edit window"; + private static JLabel editTypeLbl = new JLabel("Table Type:"); + //private static JLabel tableDetailLbl = new JLabel("Table Detail:"); + private JComboBox type_comboBox = null; + JScrollPane typejsp, detailjsp; + JPanel comboBoxPanel = null; + JTable table = null; + DefaultTableModel defaultModel = null; + private String selectedTableType = "Set"; + private String currentType = "Set"; + + public static void main(String[] args) { + new EditWindow().instance().showWindow(); + } + + private EditWindow() { + setTitle(editWindowTitle); + + JPanel selectPanle = new JPanel(); + selectPanle.setLayout(new BoxLayout(selectPanle, BoxLayout.X_AXIS)); + // typejsp = new JScrollPane(); + // JLabel addTypeLbl = new JLabel("Table Type:"); + comboBoxPanel = new JPanel(); + // comboBoxPanel.setSize(100, 50); + // comboBoxPanel.setLayout(new BoxLayout(comboBoxPanel, BoxLayout.X_AXIS)); + comboBoxPanel.setVisible(true); + + type_comboBox = new JComboBox(); + type_comboBox.addItem("Set"); + type_comboBox.addItem("Hash"); + type_comboBox.addItem("List"); + type_comboBox.addItem("String"); + type_comboBox.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent ae) { + JComboBox selectedObj = (JComboBox)ae.getSource(); + //PopMessage.popMsg("type_comboBox selected : " + selectedObj.getSelectedItem()); + selectedTableType = selectedObj.getSelectedItem().toString(); + showDiffContents(selectedTableType); + } + }); + selectPanle.add(editTypeLbl); + selectPanle.add(type_comboBox); + //type_comboBox.setPreferredSize(new Dimension(100,50)); + //type_comboBox.setLocation(80, 20); + + GroupLayout layout = new GroupLayout(this.getContentPane()); + this.getContentPane().setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(selectPanle, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE) + //.addComponent(addTypeLbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 600,GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) + //hGroup.addGroup(layout.createParallelGroup(Alignment.LEADING) + // .addComponent(type_comboBox, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 680,GroupLayout.PREFERRED_SIZE) + // ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 300,GroupLayout.PREFERRED_SIZE)); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + //.addComponent(addTypeLbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(type_comboBox, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + .addComponent(selectPanle, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(comboBoxPanel, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE) + ); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + //showDiffContents("Set"); + //type_comboBox.setSelectedItem(selectedTableType); + + // comboBoxPanel.setLayout(layout); + // type_comboBox.setPreferredSize(new Dimension(50,50)); + // comboBoxPanel.setPreferredSize(new Dimension(50,50)); + // typejsp.add(addTypeLbl); + // comboBoxPanel.add(addTypeLbl); + // addTypeLbl.setBounds(10, 0, 50, 50); + + // typejsp.add(type_comboBox); + // comboBoxPanel.add(typejsp); + // comboBoxPanel.add(type_comboBox); + // type_comboBox.setBounds(60, 0, 50, 50); + // type_comboBox.setPreferredSize(new Dimension(50,50)); + + // this.getContentPane().add(typejsp, BorderLayout.NORTH); + // this.getContentPane().add(comboBoxPanel); + // comboBoxPanel.setPreferredSize(new Dimension(30,50)); + + // comboBoxPanel.setVisible(true); + // addTypeLbl.setVisible(true); + // comboBoxPanel.setBounds(10, 10, 100, 200); + // typejsp.updateUI(); + // typejsp.setVisible(true); + + // detailjsp = new JScrollPane(); + // JPanel detailPanel = new JPanel(); + // detailPanel.add(tableDetailLbl); + // detailjsp.add(detailPanel); + // this.getContentPane().add(detailPanel, BorderLayout.SOUTH); + // detailjsp.setBounds(10, 50, 400, 100); + // detailjsp.updateUI(); + // PopMessage.popMsg("Create the add window"); + }; + + public void showDiffContents(String tableType) { + comboBoxPanel.removeAll(); + + //JLabel tableTypelbl = new JLabel("Add type:" + tableType); + + //comboBoxPanel.setLayout(new BoxLayout(comboBoxPanel, BoxLayout.Y_AXIS)); + //comboBoxPanel.add(tableTypelbl); + + // init the ui + if("set".equalsIgnoreCase(tableType)){ + initSetTable(null, tableType); + } else if("list".equalsIgnoreCase(tableType)){ + initListTable(null, tableType); + } else if("hash".equalsIgnoreCase(tableType)){ + initHashTable(null, tableType); + } else if("string".equalsIgnoreCase(tableType)){ + initStringTable(null, tableType); + } else { + PopMessage.popMsg("Unsupported table type"); + } + // fresh + comboBoxPanel.updateUI(); + } + + public void initHashTable(String key, final String tableType){ + + JLabel tableTypelbl = new JLabel("Table type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + String[] tableHeaders = { "Field", "Value", "Type" }; + //String[][] setInfo = {{"key", "", ""}}; + + Map value = null; + if(null == key){ + key = ""; + } else { + value = new HashMan().list(key); + } + tableNameText.setText(key); + + //JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + //String[] taskHeaders = { "Index", "Value", "Type" }; + final String space = ""; + String[][] valueInfo = null; + if(null != value && value.size() > 0){ + int arraySize = value.size(); + valueInfo = new String[arraySize][3]; + Set keySet = value.keySet(); + Iterator ite = keySet.iterator(); + String iteId = null; + int i = 0; + while (ite.hasNext()) { + iteId = (String) ite.next(); + valueInfo[i][0] = iteId; + valueInfo[i][1] = value.get(iteId); + valueInfo[i][2] = space; + i++; + } + } else { + valueInfo = new String[1][3]; + valueInfo[0][0] = ""; + valueInfo[0][1] = ""; + valueInfo[0][2] = ""; + } + + //defaultModel = new DefaultTableModel(valueInfo, taskHeaders); + + //table = new JTable(defaultModel); + //table.setName(tableType + "<" + tableNameText.getText() + ">"); + + // set the table header to be sorted + //DefaultTableModel dtm = new DefaultTableModel(valueInfo, tableHeaders); + defaultModel = new DefaultTableModel(valueInfo, tableHeaders); + table = new JTable(defaultModel); + table.setRowSorter(new TableRowSorter(defaultModel)); + + AlignColumn(table, tableHeaders[0] , SwingConstants.CENTER); + + JScrollPane panel = new JScrollPane(); + panel.setViewportView(table); + + JButton addSetBtn = new JButton("Save Data"); + addSetBtn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + stopEditRow(); + String key = tableNameText.getText(); + if(key.isEmpty()){ + PopMessage.popMsg("Added type:[" + tableType + "] Table Key is required"); + } else { + + Map vMap = new HashMap(); + int rows = table.getRowCount(); + //table.getCellEditor(0, 0).getCellEditorValue(); + String cellField = null; + String cellValue = null; + for(int i = 0; i < rows; i ++){ + cellField = (String) table.getValueAt(i, 0); + cellValue = (String) table.getValueAt(i, 1); + //System.out.println("Get cellValue:[" + cellValue +"] at:["+ i + ", 0]"); + vMap.put(cellField, cellValue); + } + //StringBuilder values = new StringBuilder(); + //for(String value: vectorValues){ + //System.out.println("Get cellValue:[" + value +"] from vector"); + // values.append(value).append(","); + // } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + key + "] value:[ ... ]"); + int effectRow = new HashMan().add(key, vMap); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + } + }); + + //JPanel cellPanel = new JPanel(); + //cellPanel.add(addSetBtn); + + JPanel btnPanel = new JPanel(); + //btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS)); + btnPanel.add(addSetBtn); + //JScrollPane btnPanel = new JScrollPane(); + //addSetBtn.setSize(60, 20); + + JButton addRow = new JButton("Add Row"); + btnPanel.add(addRow); + addRow.addActionListener(this); + //addRow.setSize(60, 20); + + JButton addColumn = new JButton("Add Column"); + //btnPanel.add(addColumn); + addColumn.addActionListener(this); + //addColumn.setSize(60, 20); + + JButton removeRow = new JButton("Remove Row"); + btnPanel.add(removeRow); + removeRow.addActionListener(this); + //removeRow.setSize(60, 20); + + JButton removeColumn = new JButton("Remove Column"); + //btnPanel.add(removeColumn); + removeColumn.addActionListener(this); + //removeColumn.setSize(60, 20); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE) + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) + ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup() + // .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + // ); + //btnPanel.setAlignmentX(SwingConstants.RIGHT); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(panel, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup() + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + // ); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + ); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup().addComponent(addRow, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + } + + public void initListTable(String key, final String tableType){ + + JLabel tableTypelbl = new JLabel("Table type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + + List value = null; + if(null == key){ + key = ""; + } else { + value = new ListMan().list(key); + } + tableNameText.setText(key); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + String[] tableHeaders = { "Index", "Value", "Type" }; + final String space = ""; + String[][] valueInfo = null; + if(null != value && value.size() > 0){ + int arraySize = value.size(); + valueInfo = new String[arraySize][3]; + int i = 0; + for(String v : value){ + valueInfo[i][0] = space + (i + 1); + valueInfo[i][1] = v; + valueInfo[i][2] = "String"; + i++; + } + } else { + valueInfo = new String[1][3]; + valueInfo[0][0] = ""; + valueInfo[0][1] = ""; + valueInfo[0][2] = ""; + } + + //JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + //String[] taskHeaders = { "Index", "Value", "Type" }; + //String[][] setInfo = {{"1", "", ""}}; + + //defaultModel = new DefaultTableModel(valueInfo, taskHeaders); + //table = new JTable(defaultModel); + //table.setName(tableType + "<" + tableNameText.getText() + ">"); + + // set the table header to be sorted + //DefaultTableModel dtm = new DefaultTableModel(valueInfo, tableHeaders); + defaultModel = new DefaultTableModel(valueInfo, tableHeaders); + table = new JTable(defaultModel); + table.setRowSorter(new TableRowSorter(defaultModel)); + + AlignColumn(table, tableHeaders[0] , SwingConstants.CENTER); + + JScrollPane panel = new JScrollPane(); + panel.setViewportView(table); + + JButton addSetBtn = new JButton("Save Data"); + addSetBtn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + stopEditRow(); + String key = tableNameText.getText(); + if(key.isEmpty()){ + PopMessage.popMsg("Added type:[" + tableType + "] Table Key is required"); + } else { + + List vlist = new ArrayList(); + int rows = table.getRowCount(); + //table.getCellEditor(0, 0).getCellEditorValue(); + String cellValue = null; + for(int i = 0; i < rows; i ++){ + //cellValue = (String) table.getCellEditor(i, 1).getCellEditorValue(); + cellValue = (String) table.getValueAt(i, 1); + //System.out.println("Get cellValue:[" + cellValue +"] at:["+ i + ", 0]"); + vlist.add(i, cellValue); + } + //StringBuilder values = new StringBuilder(); + //for(String value: vectorValues){ + //System.out.println("Get cellValue:[" + value +"] from vector"); + // values.append(value).append(","); + // } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + tableNameText.getText() + "] value:[ ... ]"); + //new SetMan().add(key, vlist); + int effectRow = new ListMan().add(key, vlist); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + tableNameText.getText() + "] value:[" + strTableNameText.getText() + "]"); + } + }); + + //JPanel cellPanel = new JPanel(); + //cellPanel.add(addSetBtn); + + JPanel btnPanel = new JPanel(); + //btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS)); + btnPanel.add(addSetBtn); + //JScrollPane btnPanel = new JScrollPane(); + //addSetBtn.setSize(60, 20); + + JButton addRow = new JButton("Add Row"); + btnPanel.add(addRow); + addRow.addActionListener(this); + //addRow.setSize(60, 20); + + JButton addColumn = new JButton("Add Column"); + //btnPanel.add(addColumn); + addColumn.addActionListener(this); + //addColumn.setSize(60, 20); + + JButton removeRow = new JButton("Remove Row"); + btnPanel.add(removeRow); + removeRow.addActionListener(this); + //removeRow.setSize(60, 20); + + JButton removeColumn = new JButton("Remove Column"); + //btnPanel.add(removeColumn); + removeColumn.addActionListener(this); + //removeColumn.setSize(60, 20); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE) + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) + ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup() + // .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + // ); + //btnPanel.setAlignmentX(SwingConstants.RIGHT); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(panel, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup() + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + // ); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + ); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup().addComponent(addRow, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + } + + public void initSetTable(String key, final String tableType){ + + JLabel tableTypelbl = new JLabel("Table type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + + Set value = null; + if(null == key){ + key = ""; + } else { + value = new SetMan().list(key); + } + tableNameText.setText(key); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + //final JTextField strTableNameText = new JTextField(); + // set table + String[] tableHeaders = { "Field", "Value", "Type" }; + final String space = ""; + String[][] valueInfo = null; + if(null != value && value.size() > 0){ + int arraySize = value.size(); + valueInfo = new String[arraySize][3]; + int i = 0; + for(String setv : value){ + valueInfo[i][0] = space + (i + 1); + valueInfo[i][1] = setv; + valueInfo[i][2] = "String"; + i++; + } + } else { + valueInfo = new String[1][3]; + valueInfo[0][0] = ""; + valueInfo[0][1] = ""; + valueInfo[0][2] = ""; + } + + //defaultModel = new DefaultTableModel(valueInfo, taskHeaders); + + //table = new JTable(defaultModel); + //table.setName(tableType + "<" + tableNameText.getText() + ">"); + + // set the table header to be sorted + //DefaultTableModel dtm = new DefaultTableModel(valueInfo, tableHeaders); + defaultModel = new DefaultTableModel(valueInfo, tableHeaders); + table = new JTable(defaultModel); + table.setRowSorter(new TableRowSorter(defaultModel)); + + AlignColumn(table, tableHeaders[0] , SwingConstants.CENTER); + + JScrollPane panel = new JScrollPane(); + panel.setViewportView(table); + + JButton addSetBtn = new JButton("Save Data"); + addSetBtn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + stopEditRow(); + String key = tableNameText.getText(); + if(key.isEmpty()){ + PopMessage.popMsg("Added type:[" + tableType + "] Table Key is required"); + } else { + Vector vectorValues = new Vector(); + int rows = table.getRowCount(); + //table.getCellEditor(0, 0).getCellEditorValue(); + String cellValue = null; + for(int i = 0; i < rows; i ++){ + //cellValue = (String) table.getCellEditor(i, 1).getCellEditorValue(); + cellValue = (String) table.getValueAt(i, 1); + //System.out.println("Get cellValue:[" + cellValue +"] at:["+ i + ", 0]"); + vectorValues.add(i, cellValue); + } + //StringBuilder values = new StringBuilder(); + //for(String value: vectorValues){ + //System.out.println("Get cellValue:[" + value +"] from vector"); + // values.append(value).append(","); + // } + //PopMessage.popMsg("Added type:[" + tableType + "] key:[" + tableNameText.getText() + "] value:[" + values.toString() + "]"); + //new SetMan().add(key, vectorValues); + //int effectRow = new SetMan().add(key, vectorValues); + int effectRow = new SetMan().edit(key, vectorValues); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + } + }); + + //JPanel cellPanel = new JPanel(); + //cellPanel.add(addSetBtn); + + JPanel btnPanel = new JPanel(); + //btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS)); + btnPanel.add(addSetBtn); + //JScrollPane btnPanel = new JScrollPane(); + //addSetBtn.setSize(60, 20); + + JButton addRow = new JButton("Add Row"); + btnPanel.add(addRow); + addRow.addActionListener(this); + //addRow.setSize(60, 20); + + JButton addColumn = new JButton("Add Column"); + //btnPanel.add(addColumn); + addColumn.addActionListener(this); + //addColumn.setSize(60, 20); + + JButton removeRow = new JButton("Remove Row"); + btnPanel.add(removeRow); + removeRow.addActionListener(this); + //removeRow.setSize(60, 20); + + JButton removeColumn = new JButton("Remove Column"); + //btnPanel.add(removeColumn); + removeColumn.addActionListener(this); + //removeColumn.setSize(60, 20); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + ); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE) + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) + ); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup() + // .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) + // ); + //btnPanel.setAlignmentX(SwingConstants.RIGHT); + hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(panel, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(panel, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup() + // .addComponent(addSetBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(addColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeRow, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + //.addComponent(removeColumn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + // ); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(btnPanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + ); + //vGroup.addGap(5); + //vGroup.addGroup(layout.createParallelGroup().addComponent(addRow, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + } + + public void initStringTable(String key, final String tableType){ + + JLabel tableTypelbl = new JLabel("Table type:"); + JLabel tableTypevalue = new JLabel("[" + tableType + "]"); + + JLabel tableNamelbl = new JLabel("Table Key:" ); + final JTextField tableNameText = new JTextField(); + String value = ""; + if(null == key){ + key = ""; + } else { + value = new StringMan().list(key); + } + tableNameText.setText(key); + + //comboBoxPanel.add(tableNamelbl); + //comboBoxPanel.add(tableName); + + JLabel strTableValuelbl = new JLabel("Table value:" ); + final JTextField tableValueText = new JTextField(); + tableValueText.setText(value); + + // do search and get the data from redis + + JButton addStrBtn = new JButton("Save Data"); + //addStrBtn.addActionListener(this); + addStrBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + stopEditRow(); + String key = tableNameText.getText(); + String value = tableValueText.getText(); + //int effectRows = new StringMan().add(key, value); + //if(effectRows > 0){ + // PopMessage.popMsg("Added type:[" + tableType + "] key:[" + key + "] value:[" + value + "] success"); + // } else { + // PopMessage.popWarn("Added type:[" + tableType + "] key:[" + key + "] value:[" + value + "] Fail"); + //} + //int effectRow = new StringMan().add(key, value); + int effectRow = new StringMan().edit(key, value); + if(effectRow > 0){ + PopMessage.popMsg("Save data for key:[" + key + "] success"); + } else { + PopMessage.popMsg("Save data for key:[" + key + "] fail"); + } + } + }); + + GroupLayout layout = new GroupLayout(comboBoxPanel); + comboBoxPanel.setLayout(layout); + GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)); + hGroup.addGap(5); + hGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE) + .addComponent(tableValueText, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE) + .addComponent(addStrBtn, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + //hGroup.addGap(5); + //hGroup.addGroup(layout.createParallelGroup().addComponent(addbtn, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)); + layout.setHorizontalGroup(hGroup); + + GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableTypelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableTypevalue, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(tableNamelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableNameText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(strTableValuelbl, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) + .addComponent(tableValueText, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + vGroup.addGroup(layout.createParallelGroup() + .addComponent(addStrBtn, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)); + vGroup.addGap(5); + layout.setVerticalGroup(vGroup); + + //comboBoxPanel.add(strTableValuelbl); + //comboBoxPanel.add(strTableNameText); + } + + private static void AlignColumn(JTable comp, String column, final int position){ + comp.getColumn(column).setCellRenderer( + new DefaultTableCellRenderer() { // rewrite setValue method + private static final long serialVersionUID = 1L; + + public void setValue(Object value) { + this.setHorizontalAlignment(position); + super.setValue(value); + } + }); + } + + public static EditWindow instance() { + if (null == editWindow) + editWindow = new EditWindow(); + return editWindow; + } + + public void showWindow(String key) { + String type = RedisTableMan.getType(key); + String _curr = StringUtils.capitalize(type); + setCurrentType(_curr); + type_comboBox.setSelectedItem(_curr); + type_comboBox.setEnabled(false); + fileTableDate(key, _curr); + showWindow(); + } + + + /** + * @param currentType the currentType to set + */ + public final void setCurrentType(String currentType) { + this.currentType = currentType; + } + + /** + * @param key + * + */ + private void fileTableDate(String key, String tableType) { + if("set".equalsIgnoreCase(tableType)){ + initSetTable(key, tableType); + } else if("list".equalsIgnoreCase(tableType)){ + initListTable(key, tableType); + } else if("hash".equalsIgnoreCase(tableType)){ + initHashTable(key, tableType); + } else if("string".equalsIgnoreCase(tableType)){ + initStringTable(key, tableType); + } else { + PopMessage.popMsg("Unsupported table type"); + } + // fresh + comboBoxPanel.updateUI(); + } + + public void showWindow() { + // make the frame to be loadded at windows center + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension screenSize = kit.getScreenSize(); + int screenHeight = screenSize.height; + int screenWidth = screenSize.width; + // int width = 300; + int width = 800; + // int height = 200; + int height = 600; + setLocation((screenWidth - width) / 2, (screenHeight - height) / 2); + + // setBounds(200, 200, 400, 300); + setSize(680, 480); + // this.setLocation(100, 100); + // this.setSize(300, 200); + // this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + this.setVisible(true); + // this.setAlwaysOnTop(true); + addWindowListener(new HandlePopWin()); + } + + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("Add Column")){ + PopMessage.popMsg("Invalid new column for this window"); + //defaultModel.addColumn("AddColumn"); + } + if (e.getActionCommand().equals("Add Row")){ + defaultModel.addRow(new Vector()); + } + if (e.getActionCommand().equals("Remove Column")) { + PopMessage.popMsg("Invalid new column for this window"); +// int columncount = defaultModel.getColumnCount() - 1; +// if (columncount >= 0) { +// TableColumnModel columnModel = table.getColumnModel(); +// TableColumn tableColumn = columnModel.getColumn(columncount); +// columnModel.removeColumn(tableColumn); +// defaultModel.setColumnCount(columncount); +// } + } + if (e.getActionCommand().equals("Remove Row")) { + int rowselected = table.getSelectedRow(); + if(rowselected >= 0){ + defaultModel.removeRow(rowselected); + //int rowcount = defaultModel.getRowCount(); + //defaultModel.setRowCount(rowcount); + } + /* + int rowcount = defaultModel.getRowCount() - 1; + if (rowcount >= 0) { + defaultModel.removeRow(rowcount); + defaultModel.setRowCount(rowcount); + }*/ + } + //defaultModel.fireTableStructureChanged(); + table.revalidate(); + } + + private void stopEditRow(){ + if(table.isEditing()){ + int row = table.getEditingRow(); + int col = table.getEditingColumn(); + table.getCellEditor(row,col).stopCellEditing(); + } + } + class HandlePopWin extends WindowAdapter { + public void windowClosing(WindowEvent e) { + // e.getWindow().setVisible(false); + (e.getWindow()).dispose(); + //System.exit(0); + // (new Frame()).setVisible(false); + // this.windowClosed(e); + } + } +} diff --git a/src/org/kevin/redis/window/PreferencesWindow.java b/src/org/kevin/redis/window/PreferencesWindow.java new file mode 100644 index 0000000..2859467 --- /dev/null +++ b/src/org/kevin/redis/window/PreferencesWindow.java @@ -0,0 +1,290 @@ +/** + * PreferencesWindow.java + * kevin 2013-2-18 + * @version 0.1 + */ +package org.kevin.redis.window; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; + +import org.kevin.redis.constant.RedisConstants; +import org.kevin.redis.panel.PreferencesRightPanel; +import org.kevin.redis.validate.IPValidate; + +/** + * @author kevin + * @since jdk1.6 + */ +public class PreferencesWindow extends JFrame implements ActionListener { + + private static PreferencesWindow prefWindow; + static JScrollPane treePanel; + private static JPanel tablePanel; + private static String preferencesTitle = "NoSQL Preferences"; + private static final long serialVersionUID = -7899889629830144406L; + // button and button text + JLabel ip_lable, port_lable; + JTextField ip_text, port_text; + JPanel ip_panel, port_panel, btn_panel, control_panel; + JButton[] btn = new JButton[3]; + String[] btnText = {"Save", "Reset", "Cancel"}; + + private PreferencesWindow(){ + } + + public static PreferencesWindow instance(){ + if(null == prefWindow){ + prefWindow = new PreferencesWindow(preferencesTitle); + } + return prefWindow; + } + + private PreferencesWindow(String preferencesTitle) { + this.setTitle(preferencesTitle); + //this.getContentPane().setLayout(new GridLayout(1, 2)); + + treePanel = new JScrollPane(); + //treePanel.setBounds(10, 10, this.getX(), this.getY()); + //treePanel.setLayout(new GridLayout(1, 2)); + + //scrollPane = new JScrollPane(); + JTree prefTree = preferencesTree(); + + //scrollPane.setLayout(new ScrollPaneLayout()); + //treePanel.add(tablePanel); + //scrollPane.add(prefTree); + + treePanel.setViewportView(prefTree); + this.getContentPane().add(treePanel, BorderLayout.WEST); + treePanel.setVisible(true); + //this.getContentPane().add(treePanel); + //this.getContentPane().add(prefTree, BorderLayout.WEST); + //scrollPane.setBounds(10, 10, this.getX(), this.getY()); + //prefTree.setBounds(30, 30, this.getX(), this.getY()); + //treePanel.setBounds(30, 30, this.getX(), this.getY()); + //scrollPane.setVisible(true); + + //*****for table panel***// + + tablePanel = new JPanel(); + //tablePanel.setLayout(new ScrollPaneLayout()); + + //JTable data_table = PreferencesRightPanel.initJTable(); + //tablePanel.add(data_table); + + //JButton remove_btn = new JButton("删除数据"); + //tablePanel.add(remove_btn); + //tablePanel.setLayout(new GridLayout(1, 1)); + this.getContentPane().add(tablePanel); + //this.getContentPane().add(tablePanel); + //tablePanel.setBounds((treePanel.getX() + 10), (treePanel.getY() + 10), this.getX(), this.getY()); + //tablePanel.setLayout(new GridLayout(1, 2)); + //tablePanel.setVisible(true); + //this.getContentPane().add(prefTree, BorderLayout.WEST); + //showWindow(); + } + + private JTree preferencesTree(){ + String rootNodeTitle = "Preferences"; + String initNodeTitle = "Hosts"; + + DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(); + // set the title for the root node + rootNode.setUserObject(rootNodeTitle); + + DefaultMutableTreeNode initNode = new DefaultMutableTreeNode(); + initNode.setUserObject(initNodeTitle); + rootNode.add(initNode); + + JTree tree = new JTree(); + // Create the model object for the tree and accepted the root node while generate + javax.swing.tree.DefaultTreeModel dm = new DefaultTreeModel(rootNode); + // set the model to the tree and show the loaded node on the tree + tree.setModel(dm); + tree.addTreeSelectionListener(new TreeSelectionListener() { + @Override + public void valueChanged(TreeSelectionEvent e) { + String pathNode = e.getPath().getLastPathComponent().toString(); + //JScrollPane rightpanel = PreferencesRightPanel.showHostTable(pathNode); + //tablePanel = rightpanel; + //PreferencesWindow.instance().getContentPane().add(rightpanel, BorderLayout.EAST); + //rightpanel.setLayout(new ScrollPaneLayout() ); + //tablePanel.updateUI(); + //rightpanel.updateUI(); + PreferencesRightPanel.showPreferences(pathNode); + } + }); + return tree; + } + + private void PreferencesWindow(String title, int index) { + this.setTitle(title); + //this.setBounds(400, 300, 200, 200); + //this.setAlwaysOnTop(true); + + ip_lable = new JLabel("Redis IP:"); + ip_text = new JTextField(15); + port_lable = new JLabel("Redis Port:"); + port_text = new JTextField(15); + + for (int i = 0; i < btn.length; i++) { + btn[i] = new JButton(btnText[i]); + btn[i].setActionCommand(String.valueOf(i)); + btn[i].addActionListener(this); + } + ip_panel = new JPanel(); + ip_panel.add(ip_lable); + ip_panel.add(ip_text); + //ip_panel.setLayout(null); + + port_panel = new JPanel(); + port_panel.add(port_lable); + port_panel.add(port_text); + //port_panel.setLayout(null); + + btn_panel = new JPanel(); + btn_panel.add(btn[0]); + btn_panel.add(btn[1]); + btn_panel.add(btn[2]); + //btn_panel.setLayout(null); + + control_panel = new JPanel(); + //control_panel.setLayout(new GridLayout(3, 1)); + control_panel.add(ip_panel); + control_panel.add(port_panel); + control_panel.add(btn_panel); + //control_panel.setLayout(null); + + GridLayout grid = new GridLayout(3, 1); + grid.setHgap(0);//set the component space between h type 设置组件之间的水平距离为h(int型) + grid.setVgap(0);//set the component space between V type设置组件之间的垂直距离为v(int型) + control_panel.setLayout(grid); + + this.setLayout(new BorderLayout()); + this.getContentPane().add(control_panel, BorderLayout.CENTER); + + + // make the frame to be loadded at windows center + Toolkit kit=Toolkit.getDefaultToolkit(); + Dimension screenSize=kit.getScreenSize(); + int screenHeight=screenSize.height; + int screenWidth=screenSize.width; + int width = 300; + int height = 200; + setLocation( (screenWidth-width)/2, (screenHeight-height)/2 ); + + setSize(width, height); + + //this.setLocation(100, 100); + //this.setSize(300, 200); + //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + this.setVisible(true); + this.setAlwaysOnTop(true); + addWindowListener(new HandlePopWin()); + } + + public void showWindow(){ + // make the frame to be loadded at windows center + Toolkit kit=Toolkit.getDefaultToolkit(); + Dimension screenSize=kit.getScreenSize(); + int screenHeight=screenSize.height; + int screenWidth=screenSize.width; + //int width = 300; + int width = 800; + //int height = 200; + int height = 600; + setLocation( (screenWidth-width)/2, (screenHeight-height)/2 ); + + //setBounds(200, 200, 400, 300); + setSize(600, 480); + //this.setLocation(100, 100); + //this.setSize(300, 200); + //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + this.setVisible(true); + //this.setAlwaysOnTop(true); + addWindowListener(new HandlePopWin()); + } + + @Override + public void actionPerformed(ActionEvent e) { + + int i = Integer.parseInt(e.getActionCommand()); + switch (i) { + case 0: + btn[0] = (JButton) e.getSource(); + String redisIP, redisPort; + redisIP = ip_text.getText(); + redisPort = port_text.getText(); + if (null == redisIP || redisIP.length() == 0 || null == redisPort || redisPort.length() == 0) + // JOptionPane.showMessageDialog(this, "IP or port Can't be null!"); + JOptionPane.showMessageDialog(this, "IP or port Can't be null!", "Warn", JOptionPane.ERROR_MESSAGE); + else { + int port = Integer.valueOf(redisPort); + if (IPValidate.isIP(redisIP) && (port > 0 && port < 65535)) { + JOptionPane.showMessageDialog(this, "Set success!", "save", JOptionPane.INFORMATION_MESSAGE);//.showMessageDialog(this, "Save success!"); + RedisConstants.REDIS_SERVER_IP = redisIP; + RedisConstants.REDIS_SERVER_PORT = port; + break; + } + else{ + //JOptionPane.showMessageDialog(this, "IP or port unvaliad,please check!"); + JOptionPane.showMessageDialog(this, "IP or port unvaliad,please check!", "Warn", JOptionPane.ERROR_MESSAGE); + ip_text.setText(""); + port_text.setText(""); + ip_text.setFocusable(true); + break; + } + } + case 1: + btn[1] = (JButton) e.getSource(); + ip_text.setText(""); + port_text.setText(""); + ip_text.setFocusable(true); + break; + case 2: + btn[2] = (JButton) e.getSource(); + this.setVisible(false); + this.dispose(); + break; + } + + } + + /** + * @return the tablePanel + */ + public JPanel getTablePanel() { + return tablePanel; + } + + class HandlePopWin extends WindowAdapter { + public void windowClosing(WindowEvent e) { + //e.getWindow().setVisible(false); + (e.getWindow()).dispose(); + //(new Frame()).setVisible(false); + //this.windowClosed(e); + } + } +} diff --git a/src/org/kevin/redis/window/dbcopy/DBCopyWindow.java b/src/org/kevin/redis/window/dbcopy/DBCopyWindow.java new file mode 100644 index 0000000..ae88565 --- /dev/null +++ b/src/org/kevin/redis/window/dbcopy/DBCopyWindow.java @@ -0,0 +1,89 @@ +/** + * DBCopyWindow.java + * kevin 2013-4-25 + * @version 0.1 + */ +package org.kevin.redis.window.dbcopy; + +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JFrame; + +/** + * @author kevin + * @since jdk1.6 + */ +public class DBCopyWindow extends JFrame implements ActionListener { + + /** + * + */ + private static final long serialVersionUID = 1977098215935047379L; + private static String dbCopyTitle = "DB Copy"; + private static DBCopyWindow dbCopyWindow; + + private DBCopyWindow() { + } + + public static DBCopyWindow instance() { + if (null == dbCopyWindow) { + dbCopyWindow = new DBCopyWindow(dbCopyTitle); + } + return dbCopyWindow; + } + + /** + * + */ + private DBCopyWindow(String dbCopyTitle) { + this.setTitle(dbCopyTitle); + } + + public void showWindow() { + // make the frame to be loadded at windows center + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension screenSize = kit.getScreenSize(); + int screenHeight = screenSize.height; + int screenWidth = screenSize.width; + // int width = 300; + int width = 800; + // int height = 200; + int height = 600; + setLocation((screenWidth - width) / 2, (screenHeight - height) / 2); + + // setBounds(200, 200, 400, 300); + setSize(600, 480); + // this.setLocation(100, 100); + // this.setSize(300, 200); + // this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + this.setVisible(true); + // this.setAlwaysOnTop(true); + addWindowListener(new HandlePopWin()); + } + + class HandlePopWin extends WindowAdapter { + public void windowClosing(WindowEvent e) { + //e.getWindow().setVisible(false); + (e.getWindow()).dispose(); + //(new Frame()).setVisible(false); + //this.windowClosed(e); + } + } + /* + * (non-Javadoc) + * + * @see + * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + @Override + public void actionPerformed(ActionEvent e) { + + } + +}