Browse Source

Adjust the package structure and class name, and modify the test method

pull/1/head
yichen 2 years ago
parent
commit
51e1172185
  1. 12
      agent/src/main/java/com/fanruan/AgentStarter.java
  2. 14
      agent/src/main/java/com/fanruan/agent/jdbc/connection/AgentConnection.java
  3. 12
      agent/src/main/java/com/fanruan/agent/jdbc/driver/AgentDriver.java
  4. 6
      agent/src/main/java/com/fanruan/agent/jdbc/resultset/AgentResultSet.java
  5. 10
      agent/src/main/java/com/fanruan/agent/jdbc/statement/AgentPreparedStatement.java
  6. 10
      agent/src/main/java/com/fanruan/agent/jdbc/statement/AgentStatement.java
  7. 12
      agent/src/main/java/com/fanruan/handler/DispatcherHelper.java
  8. 10
      agent/src/main/java/com/fanruan/handler/DispatcherImpl.java
  9. 2
      agent/src/main/java/com/fanruan/handler/ResponseEmitterImpl.java
  10. 3
      agent/src/main/java/com/fanruan/pojo/message/RpcRequest.java
  11. 7
      agent/src/test/java/Test.java
  12. 2
      service/src/main/java/com/fanruan/ServerStater.java
  13. 4
      service/src/main/java/com/fanruan/annotation/RemoteClass.java
  14. 7
      service/src/main/java/com/fanruan/pojo/message/RpcRequest.java
  15. 25
      service/src/main/java/com/fanruan/proxy/interceptor/Interceptor.java
  16. 12
      service/src/main/java/com/fanruan/proxy/interceptor/InterceptorUtils.java
  17. 13
      service/src/main/java/com/fanruan/service/ServiceDataBaseMetaData.java
  18. 22
      service/src/main/java/com/fanruan/service/jdbc/connection/ServiceConnection.java
  19. 14
      service/src/main/java/com/fanruan/service/jdbc/driver/ServiceDriver.java
  20. 8
      service/src/main/java/com/fanruan/service/jdbc/resultset/ServiceResultSet.java
  21. 14
      service/src/main/java/com/fanruan/service/jdbc/statement/ServicePreparedStatement.java
  22. 17
      service/src/main/java/com/fanruan/service/jdbc/statement/ServiceStatement.java
  23. 2
      service/src/test/java/AutoStarter.java
  24. 4
      service/src/test/java/Test.java
  25. 174
      test/src/test/java/TestUtil.java

12
agent/src/main/java/com/fanruan/AgentStarter.java

@ -1,6 +1,6 @@
package com.fanruan; package com.fanruan;
import com.fanruan.handler.MyDispatcherImpl; import com.fanruan.handler.DispatcherImpl;
import com.fanruan.pojo.message.RpcRequest; import com.fanruan.pojo.message.RpcRequest;
import com.fanruan.serializer.KryoSerializer; import com.fanruan.serializer.KryoSerializer;
import com.fanruan.serializer.Serializer; import com.fanruan.serializer.Serializer;
@ -29,12 +29,12 @@ public class AgentStarter {
public final static Serializer SERIALIZER = new KryoSerializer(); public final static Serializer SERIALIZER = new KryoSerializer();
public static MyDispatcherImpl myDispatcherImpl; public static DispatcherImpl dispatcherImpl;
public static String AgentID; public static String AgentID;
public AgentStarter(String[][] DBs) { public AgentStarter(String[][] DBs) {
myDispatcherImpl = new MyDispatcherImpl(); dispatcherImpl = new DispatcherImpl();
try { try {
createSocket(DBs); createSocket(DBs);
@ -78,12 +78,12 @@ public class AgentStarter {
options.webSocketFactory = okHttpClient; options.webSocketFactory = okHttpClient;
Socket defaultSocket = IO.socket(URI.create(uri), options); Socket defaultSocket = IO.socket(URI.create(uri), options);
MyDispatcherImpl.CACHE.registerSocket("/", defaultSocket); DispatcherImpl.CACHE.registerSocket("/", defaultSocket);
configDefaultSocket(defaultSocket); configDefaultSocket(defaultSocket);
for(String[] dbInfo : DBs){ for(String[] dbInfo : DBs){
Socket socket = IO.socket(URI.create(uri + "/" + dbInfo[0]), options); Socket socket = IO.socket(URI.create(uri + "/" + dbInfo[0]), options);
MyDispatcherImpl.CACHE.registerSocket(dbInfo[0], socket); DispatcherImpl.CACHE.registerSocket(dbInfo[0], socket);
configSocket(socket, dbInfo[0]); configSocket(socket, dbInfo[0]);
Class.forName(dbInfo[1]); Class.forName(dbInfo[1]);
socket.connect(); socket.connect();
@ -129,7 +129,7 @@ public class AgentStarter {
RpcRequest rpcRequest = SERIALIZER.deserialize((byte[]) objects[0], RpcRequest.class); RpcRequest rpcRequest = SERIALIZER.deserialize((byte[]) objects[0], RpcRequest.class);
logger.debug(dbName + "-RPCRequest: " + rpcRequest.toString()); logger.debug(dbName + "-RPCRequest: " + rpcRequest.toString());
try { try {
myDispatcherImpl.doDispatch(rpcRequest, dbName); dispatcherImpl.doDispatch(rpcRequest, dbName);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }

14
agent/src/main/java/com/fanruan/agentjdbc/connection/MyConnection.java → agent/src/main/java/com/fanruan/agent/jdbc/connection/AgentConnection.java

@ -1,7 +1,7 @@
package com.fanruan.agentjdbc.connection; package com.fanruan.agent.jdbc.connection;
import com.fanruan.agentjdbc.statement.MyPreparedStatement; import com.fanruan.agent.jdbc.statement.AgentPreparedStatement;
import com.fanruan.agentjdbc.statement.MyStatement; import com.fanruan.agent.jdbc.statement.AgentStatement;
import java.sql.*; import java.sql.*;
import java.util.Map; import java.util.Map;
@ -11,23 +11,23 @@ import java.util.concurrent.Executor;
/** /**
* @author Yichen Dai * @author Yichen Dai
*/ */
public class MyConnection implements Connection { public class AgentConnection implements Connection {
final private Connection conn; final private Connection conn;
public MyConnection(Connection conn){ public AgentConnection(Connection conn){
this.conn = conn; this.conn = conn;
} }
@Override @Override
public Statement createStatement() throws SQLException { public Statement createStatement() throws SQLException {
Statement st = this.conn.createStatement(); Statement st = this.conn.createStatement();
return new MyStatement(st); return new AgentStatement(st);
} }
@Override @Override
public PreparedStatement prepareStatement(String sql) throws SQLException { public PreparedStatement prepareStatement(String sql) throws SQLException {
PreparedStatement pst = this.conn.prepareStatement(sql); PreparedStatement pst = this.conn.prepareStatement(sql);
return new MyPreparedStatement(pst); return new AgentPreparedStatement(pst);
} }
@Override @Override

12
agent/src/main/java/com/fanruan/agentjdbc/driver/MyDriver.java → agent/src/main/java/com/fanruan/agent/jdbc/driver/AgentDriver.java

@ -1,6 +1,6 @@
package com.fanruan.agentjdbc.driver; package com.fanruan.agent.jdbc.driver;
import com.fanruan.agentjdbc.connection.MyConnection; import com.fanruan.agent.jdbc.connection.AgentConnection;
import java.sql.*; import java.sql.*;
import java.util.Enumeration; import java.util.Enumeration;
@ -10,7 +10,7 @@ import java.util.logging.Logger;
/** /**
* @author Yichen Dai * @author Yichen Dai
*/ */
public class MyDriver implements Driver { public class AgentDriver implements Driver {
static public final int DRIVER_VERSION_MAJOR = 1; static public final int DRIVER_VERSION_MAJOR = 1;
@ -19,7 +19,7 @@ public class MyDriver implements Driver {
//依靠静态函数块注册驱动 //依靠静态函数块注册驱动
static{ static{
try { try {
DriverManager.registerDriver(new MyDriver()); DriverManager.registerDriver(new AgentDriver());
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Can't register driver"); throw new RuntimeException("Can't register driver");
} }
@ -27,7 +27,7 @@ public class MyDriver implements Driver {
@Override @Override
public Connection connect(String url, Properties info) throws SQLException { public Connection connect(String url, Properties info) throws SQLException {
return new MyConnection(DriverManager.getConnection(url, info)); return new AgentConnection(DriverManager.getConnection(url, info));
} }
@Override @Override
@ -35,7 +35,7 @@ public class MyDriver implements Driver {
Enumeration<Driver> registeredDrivers = DriverManager.getDrivers(); Enumeration<Driver> registeredDrivers = DriverManager.getDrivers();
while (registeredDrivers.hasMoreElements()) { while (registeredDrivers.hasMoreElements()) {
Driver driver = registeredDrivers.nextElement(); Driver driver = registeredDrivers.nextElement();
if(driver instanceof MyDriver){ if(driver instanceof AgentDriver){
continue; continue;
} }
if(driver.acceptsURL(url)){ if(driver.acceptsURL(url)){

6
agent/src/main/java/com/fanruan/agentjdbc/resultset/MyResultSet.java → agent/src/main/java/com/fanruan/agent/jdbc/resultset/AgentResultSet.java

@ -1,4 +1,4 @@
package com.fanruan.agentjdbc.resultset; package com.fanruan.agent.jdbc.resultset;
import java.io.InputStream; import java.io.InputStream;
import java.io.Reader; import java.io.Reader;
@ -8,11 +8,11 @@ import java.sql.*;
import java.util.Calendar; import java.util.Calendar;
import java.util.Map; import java.util.Map;
public class MyResultSet implements ResultSet { public class AgentResultSet implements ResultSet {
final private ResultSet resultSet; final private ResultSet resultSet;
public MyResultSet(ResultSet resultSet){ public AgentResultSet(ResultSet resultSet){
this.resultSet = resultSet; this.resultSet = resultSet;
} }

10
agent/src/main/java/com/fanruan/agentjdbc/statement/MyPreparedStatement.java → agent/src/main/java/com/fanruan/agent/jdbc/statement/AgentPreparedStatement.java

@ -1,7 +1,7 @@
package com.fanruan.agentjdbc.statement; package com.fanruan.agent.jdbc.statement;
import com.fanruan.agentjdbc.resultset.MyResultSet; import com.fanruan.agent.jdbc.resultset.AgentResultSet;
import java.io.InputStream; import java.io.InputStream;
import java.io.Reader; import java.io.Reader;
@ -13,17 +13,17 @@ import java.util.Calendar;
/** /**
* @author Yichen Dai * @author Yichen Dai
*/ */
public class MyPreparedStatement implements PreparedStatement { public class AgentPreparedStatement implements PreparedStatement {
final PreparedStatement pst; final PreparedStatement pst;
public MyPreparedStatement(PreparedStatement pst) { public AgentPreparedStatement(PreparedStatement pst) {
this.pst = pst; this.pst = pst;
} }
@Override @Override
public ResultSet executeQuery() throws SQLException { public ResultSet executeQuery() throws SQLException {
return new MyResultSet(pst.executeQuery()); return new AgentResultSet(pst.executeQuery());
} }
@Override @Override

10
agent/src/main/java/com/fanruan/agentjdbc/statement/MyStatement.java → agent/src/main/java/com/fanruan/agent/jdbc/statement/AgentStatement.java

@ -1,15 +1,15 @@
package com.fanruan.agentjdbc.statement; package com.fanruan.agent.jdbc.statement;
import com.fanruan.agentjdbc.resultset.MyResultSet; import com.fanruan.agent.jdbc.resultset.AgentResultSet;
import java.sql.*; import java.sql.*;
public class MyStatement implements Statement { public class AgentStatement implements Statement {
final private Statement st; final private Statement st;
public MyStatement(Statement statement) { public AgentStatement(Statement statement) {
this.st = statement; this.st = statement;
} }
@ -17,7 +17,7 @@ public class MyStatement implements Statement {
//使用与 Service 同名的类保证数据库对应的 JDBC //使用与 Service 同名的类保证数据库对应的 JDBC
@Override @Override
public ResultSet executeQuery(String sql) throws SQLException { public ResultSet executeQuery(String sql) throws SQLException {
return new MyResultSet(st.executeQuery(sql)); return new AgentResultSet(st.executeQuery(sql));
} }
@Override @Override

12
agent/src/main/java/com/fanruan/handler/DispatcherHelper.java

@ -25,17 +25,17 @@ public class DispatcherHelper {
}; };
public final static String[] CACHE_LIST = new String[]{ public final static String[] CACHE_LIST = new String[]{
"MyDriver", "Driver",
"MyConnection", "Connection",
"MyStatement", "Statement",
"MyPreparedStatement", "PreparedStatement",
"MyResultSet", "ResultSet",
}; };
public static boolean isInCacheList(String className){ public static boolean isInCacheList(String className){
for(String s : CACHE_LIST){ for(String s : CACHE_LIST){
if(Pattern.matches(".*" + s, className)){ if(Pattern.matches(".*" + s + ".*", className)){
return true; return true;
} }
} }

10
agent/src/main/java/com/fanruan/handler/MyDispatcherImpl.java → agent/src/main/java/com/fanruan/handler/DispatcherImpl.java

@ -12,12 +12,12 @@ import java.lang.reflect.Method;
/** /**
* @author Yichen Dai * @author Yichen Dai
*/ */
public class MyDispatcherImpl implements Dispatcher{ public class DispatcherImpl implements Dispatcher{
protected static final Logger logger = LogManager.getLogger(); protected static final Logger logger = LogManager.getLogger();
public final static String CLOSE_NAME = "close"; public final static String CLOSE_NAME = "close";
public MyDispatcherImpl(){} public DispatcherImpl(){}
@Override @Override
public void doDispatch(RpcRequest rpcRequest, String dbName) { public void doDispatch(RpcRequest rpcRequest, String dbName) {
@ -31,7 +31,7 @@ public class MyDispatcherImpl implements Dispatcher{
RESPONSE_EMITTER_IMPL.sendError(CACHE.getSocket(dbName), rpcRequest, e); RESPONSE_EMITTER_IMPL.sendError(CACHE.getSocket(dbName), rpcRequest, e);
} }
if(rpcRequest.isReply()){ if(res != null && !DispatcherHelper.isInCacheList(res.getClass().getName())){
RESPONSE_EMITTER_IMPL.replyWithData(CACHE.getSocket(dbName), rpcRequest, res); RESPONSE_EMITTER_IMPL.replyWithData(CACHE.getSocket(dbName), rpcRequest, res);
}else { }else {
RESPONSE_EMITTER_IMPL.sendOk(CACHE.getSocket(dbName), rpcRequest); RESPONSE_EMITTER_IMPL.sendOk(CACHE.getSocket(dbName), rpcRequest);
@ -98,9 +98,9 @@ public class MyDispatcherImpl implements Dispatcher{
if(DispatcherHelper.isInCacheList(resClassName)) { if(DispatcherHelper.isInCacheList(resClassName)) {
beanCache.cacheInstance(rpcRequest.getID(), res); beanCache.cacheInstance(rpcRequest.getID(), res);
} }
logger.info("invoke" + className + "-" + methodName + " and return a instance of" + res.getClass().getName()); logger.debug("invoke" + className + "-" + methodName + " and return a instance of" + res.getClass().getName());
}else{ }else{
logger.info("invoke" + className + "-" + methodName + " and no return value"); logger.debug("invoke" + className + "-" + methodName + " and no return value");
} }
return res; return res;
} }

2
agent/src/main/java/com/fanruan/handler/ResponseEmitterImpl.java

@ -16,7 +16,6 @@ public class ResponseEmitterImpl implements ResponseEmitter{
RpcResponse rpcResponse = new RpcResponse(); RpcResponse rpcResponse = new RpcResponse();
rpcResponse.setResult(null) rpcResponse.setResult(null)
.setID(rpcRequest.getID()) .setID(rpcRequest.getID())
.setBinding(rpcRequest.isBinding())
.setStatus(true); .setStatus(true);
byte[] bytes = AgentStarter.SERIALIZER.serialize(rpcResponse); byte[] bytes = AgentStarter.SERIALIZER.serialize(rpcResponse);
socket.emit("RPCResponse", bytes); socket.emit("RPCResponse", bytes);
@ -30,7 +29,6 @@ public class ResponseEmitterImpl implements ResponseEmitter{
+ "Error Message: " + e.getMessage() + "Error Message: " + e.getMessage()
+ " and check your code") + " and check your code")
.setID(rpcRequest.getID()) .setID(rpcRequest.getID())
.setBinding(rpcRequest.isBinding())
.setStatus(false); .setStatus(false);
byte[] bytes = AgentStarter.SERIALIZER.serialize(rpcResponse); byte[] bytes = AgentStarter.SERIALIZER.serialize(rpcResponse);
socket.emit("RPCResponse", bytes); socket.emit("RPCResponse", bytes);

3
agent/src/main/java/com/fanruan/pojo/message/RpcRequest.java

@ -9,9 +9,8 @@ import lombok.experimental.Accessors;
@Data @Data
@Accessors(chain = true) @Accessors(chain = true)
public class RpcRequest { public class RpcRequest {
private boolean reply;
private String ID; private String ID;
private boolean binding; // private boolean binding;
private String IDToInvoke; private String IDToInvoke;
private String serviceClassName; private String serviceClassName;
private String methodName; private String methodName;

7
agent/src/test/java/Test.java

@ -2,9 +2,6 @@ import com.fanruan.AgentStarter;
import com.fanruan.utils.DBProperties; import com.fanruan.utils.DBProperties;
import io.socket.client.Socket; import io.socket.client.Socket;
import java.io.IOException;
public class Test { public class Test {
@ -25,10 +22,10 @@ public class Test {
new AgentStarter(DBs); new AgentStarter(DBs);
Socket mainSocket = AgentStarter.myDispatcherImpl.CACHE.getSocket("/"); Socket mainSocket = AgentStarter.dispatcherImpl.CACHE.getSocket("/");
mainSocket.connect(); mainSocket.connect();
Socket socket = AgentStarter.myDispatcherImpl.CACHE.getSocket(DBProperties.HSQL[0]); Socket socket = AgentStarter.dispatcherImpl.CACHE.getSocket(DBProperties.HSQL[0]);
socket.connect(); socket.connect();
} }

2
service/src/main/java/com/fanruan/ServerStater.java

@ -45,7 +45,7 @@ public class ServerStater{
public ServerStater(String[][] dbs){ public ServerStater(String[][] dbs){
try{ try{
Class.forName("com.fanruan.servicejdbc.driver.MyDriver"); Class.forName("com.fanruan.service.jdbc.driver.ServiceDriver");
loadConfig(); loadConfig();
for(String[] dbInfo : dbs){ for(String[] dbInfo : dbs){
SocketIONamespace namespace = server.addNamespace("/" + dbInfo[0]); SocketIONamespace namespace = server.addNamespace("/" + dbInfo[0]);

4
service/src/main/java/com/fanruan/RemoteClass.java → service/src/main/java/com/fanruan/annotation/RemoteClass.java

@ -1,4 +1,4 @@
package com.fanruan; package com.fanruan.annotation;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
@ -12,5 +12,5 @@ import java.lang.annotation.Target;
@Target({ElementType.TYPE}) @Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface RemoteClass { public @interface RemoteClass {
public String remoteClassName() default ""; String remoteClassName() default "";
} }

7
service/src/main/java/com/fanruan/pojo/message/RpcRequest.java

@ -9,17 +9,12 @@ import lombok.experimental.Accessors;
@Data @Data
@Accessors(chain = true) @Accessors(chain = true)
public class RpcRequest { public class RpcRequest {
/**
* Marks whether the method delivered need loopback data
*/
private boolean reply;
/** /**
* Marks whether the method will create an instance requeired to be cached. * Marks whether the method will create an instance requeired to be cached.
* In the project, they are Drive( MyDriver ), Connection( MyConnection ), Statement( MyStatement ), * In the project, they are Drive( MyDriver ), Connection( MyConnection ), Statement( MyStatement ),
* PreparedStatement( MyPreparedStatement ), ResultSet( MyResult ). * PreparedStatement( MyPreparedStatement ), ResultSet( MyResult ).
*/ */
private boolean binding; // private boolean binding;
private String ID; private String ID;
private String IDToInvoke; private String IDToInvoke;
private String serviceClassName; private String serviceClassName;

25
service/src/main/java/com/fanruan/proxy/interceptor/Interceptor.java

@ -2,13 +2,12 @@ package com.fanruan.proxy.interceptor;
import com.corundumstudio.socketio.SocketIOClient; import com.corundumstudio.socketio.SocketIOClient;
import com.fanruan.RemoteClass; import com.fanruan.annotation.RemoteClass;
import com.fanruan.ServerStater; import com.fanruan.ServerStater;
import com.fanruan.cache.ClientCache; import com.fanruan.cache.ClientCache;
import com.fanruan.cache.ClientWrapper; import com.fanruan.cache.ClientWrapper;
import com.fanruan.cache.LockAndCondition; import com.fanruan.cache.LockAndCondition;
import com.fanruan.pojo.message.RpcRequest; import com.fanruan.pojo.message.RpcRequest;
import com.fanruan.servicejdbc.resultset.MyResultSet;
import com.fanruan.utils.Commons; import com.fanruan.utils.Commons;
import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy; import net.sf.cglib.proxy.MethodProxy;
@ -60,8 +59,7 @@ public class Interceptor implements MethodInterceptor {
logger.debug("start invoke " + method.getName()); logger.debug("start invoke " + method.getName());
RpcRequest rpcRequest = new RpcRequest(); RpcRequest rpcRequest = new RpcRequest();
rpcRequest.setReply(false) rpcRequest
.setBinding(false)
.setID(Commons.getID()) .setID(Commons.getID())
.setMethodName(method.getName()) .setMethodName(method.getName())
.setArgs(objects) .setArgs(objects)
@ -76,23 +74,16 @@ public class Interceptor implements MethodInterceptor {
rpcRequest.setServiceClassName(clazz.getName()); rpcRequest.setServiceClassName(clazz.getName());
} }
// Set whether the rpcResponses of this rpcRequest need to carry return value // // Some instance need to be bound one-to-one, to make sure the operator happen in service
if(o instanceof MyResultSet){ // // will be deliver to this specific corresponding instance.
boolean flag = InterceptorUtils.isInReplyList(method.getName()); // if(InterceptorUtils.isInBindList(o)){
if(flag) { // rpcRequest.setBinding(true);
rpcRequest.setReply(true); // }
}
}
// Some instance need to be bound one-to-one, to make sure the operator happen in service
// will be deliver to this specific corresponding instance.
if(InterceptorUtils.isInBindList(o)){
rpcRequest.setBinding(true);
}
// IDtoInvoke is an unique ID to identify an one-to-one binding relation. // IDtoInvoke is an unique ID to identify an one-to-one binding relation.
// It comes from rpcRequest in which the instance in the agent is created. // It comes from rpcRequest in which the instance in the agent is created.
String idToInvoke = InterceptorUtils.getInvokeHelper(o, "getID", String.class); String idToInvoke = InterceptorUtils.getInvokeHelper(o, "getID", String.class);
if(idToInvoke != null){ if(idToInvoke != null){
rpcRequest.setIDToInvoke(idToInvoke); rpcRequest.setIDToInvoke(idToInvoke);
} }

12
service/src/main/java/com/fanruan/proxy/interceptor/InterceptorUtils.java

@ -33,11 +33,11 @@ public class InterceptorUtils {
}; };
private final static String[] BIND_LIST = new String[]{ private final static String[] BIND_LIST = new String[]{
".*MyDriver.*", "Driver",
".*MyConnection.*", "Connection",
".*MyStatement.*", "Statement",
".*MyPreparedStatement.*", "PreparedStatement",
".*MyResultSet.*", "ResultSet",
}; };
public static boolean isInExcludedList(String methodName){ public static boolean isInExcludedList(String methodName){
@ -88,7 +88,7 @@ public class InterceptorUtils {
public static boolean isInBindList(String className){ public static boolean isInBindList(String className){
for(String pattern : BIND_LIST){ for(String pattern : BIND_LIST){
if(Pattern.matches(pattern, className)){ if(Pattern.matches(".*" + pattern + ".*", className)){
return true; return true;
} }
} }

13
service/src/main/java/com/fanruan/servicejdbc/MyDataBaseMetaData.java → service/src/main/java/com/fanruan/service/ServiceDataBaseMetaData.java

@ -1,14 +1,17 @@
package com.fanruan.servicejdbc; package com.fanruan.service;
import com.fanruan.servicejdbc.driver.MyDriver; import com.fanruan.service.jdbc.driver.ServiceDriver;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.RowIdLifetime; import java.sql.RowIdLifetime;
import java.sql.SQLException; import java.sql.SQLException;
public class MyDataBaseMetaData implements java.sql.DatabaseMetaData{ /**
* @author 85065
*/
public class ServiceDataBaseMetaData implements java.sql.DatabaseMetaData{
@Override @Override
public boolean allProceduresAreCallable() throws SQLException { public boolean allProceduresAreCallable() throws SQLException {
return false; return false;
@ -76,12 +79,12 @@ public class MyDataBaseMetaData implements java.sql.DatabaseMetaData{
@Override @Override
public int getDriverMajorVersion() { public int getDriverMajorVersion() {
return MyDriver.DRIVER_VERSION_MAJOR; return ServiceDriver.DRIVER_VERSION_MAJOR;
} }
@Override @Override
public int getDriverMinorVersion() { public int getDriverMinorVersion() {
return MyDriver.DRIVER_VERSION_MINOR; return ServiceDriver.DRIVER_VERSION_MINOR;
} }
@Override @Override

22
service/src/main/java/com/fanruan/servicejdbc/connection/MyConnection.java → service/src/main/java/com/fanruan/service/jdbc/connection/ServiceConnection.java

@ -1,12 +1,12 @@
package com.fanruan.servicejdbc.connection; package com.fanruan.service.jdbc.connection;
import com.corundumstudio.socketio.SocketIOClient; import com.corundumstudio.socketio.SocketIOClient;
import com.fanruan.RemoteClass; import com.fanruan.annotation.RemoteClass;
import com.fanruan.cache.ClientCache; import com.fanruan.cache.ClientCache;
import com.fanruan.servicejdbc.MyDataBaseMetaData; import com.fanruan.service.ServiceDataBaseMetaData;
import com.fanruan.servicejdbc.statement.MyPreparedStatement; import com.fanruan.service.jdbc.statement.ServicePreparedStatement;
import com.fanruan.servicejdbc.statement.MyStatement; import com.fanruan.service.jdbc.statement.ServiceStatement;
import com.fanruan.proxy.ProxyFactory; import com.fanruan.proxy.ProxyFactory;
import java.sql.*; import java.sql.*;
@ -17,15 +17,15 @@ import java.util.concurrent.Executor;
/** /**
* @author Yichen Dai * @author Yichen Dai
*/ */
@RemoteClass(remoteClassName = "com.fanruan.agentjdbc.connection.MyConnection") @RemoteClass(remoteClassName = "com.fanruan.agent.jdbc.connection.AgentConnection")
public class MyConnection implements Connection { public class ServiceConnection implements Connection {
private String ID; private String ID;
private Properties info; private Properties info;
private boolean autoCommit = true; private boolean autoCommit = true;
SocketIOClient client; SocketIOClient client;
public MyConnection(){ public ServiceConnection(){
} }
public void setID(String ID){ public void setID(String ID){
@ -44,14 +44,14 @@ public class MyConnection implements Connection {
@Override @Override
public Statement createStatement(){ public Statement createStatement(){
MyStatement st = (MyStatement) ProxyFactory.getProxy(MyStatement.class, info); ServiceStatement st = (ServiceStatement) ProxyFactory.getProxy(ServiceStatement.class, info);
st.setInfo(info); st.setInfo(info);
return st; return st;
} }
@Override @Override
public PreparedStatement prepareStatement(String sql) throws SQLException { public PreparedStatement prepareStatement(String sql) throws SQLException {
MyPreparedStatement pst = (MyPreparedStatement) ProxyFactory.getProxy(MyPreparedStatement.class, info); ServicePreparedStatement pst = (ServicePreparedStatement) ProxyFactory.getProxy(ServicePreparedStatement.class, info);
// 将需要准备的sql 加入 properties 中, 将用以标识生成的 ResultSet // 将需要准备的sql 加入 properties 中, 将用以标识生成的 ResultSet
info.setProperty("PreparedSQL", sql); info.setProperty("PreparedSQL", sql);
pst.setInfo(info); pst.setInfo(info);
@ -100,7 +100,7 @@ public class MyConnection implements Connection {
@Override @Override
public DatabaseMetaData getMetaData() throws SQLException { public DatabaseMetaData getMetaData() throws SQLException {
return new MyDataBaseMetaData(); return new ServiceDataBaseMetaData();
} }
@Override @Override

14
service/src/main/java/com/fanruan/servicejdbc/driver/MyDriver.java → service/src/main/java/com/fanruan/service/jdbc/driver/ServiceDriver.java

@ -1,7 +1,7 @@
package com.fanruan.servicejdbc.driver; package com.fanruan.service.jdbc.driver;
import com.fanruan.RemoteClass; import com.fanruan.annotation.RemoteClass;
import com.fanruan.servicejdbc.connection.MyConnection; import com.fanruan.service.jdbc.connection.ServiceConnection;
import com.fanruan.proxy.ProxyFactory; import com.fanruan.proxy.ProxyFactory;
import java.sql.*; import java.sql.*;
@ -12,8 +12,8 @@ import java.util.logging.Logger;
/** /**
* @author Yichen Dai * @author Yichen Dai
*/ */
@RemoteClass(remoteClassName = "com.fanruan.agentjdbc.driver.MyDriver") @RemoteClass(remoteClassName = "com.fanruan.agent.jdbc.driver.AgentDriver")
public class MyDriver implements Driver { public class ServiceDriver implements Driver {
static public final int DRIVER_VERSION_MAJOR = 1; static public final int DRIVER_VERSION_MAJOR = 1;
static public final int DRIVER_VERSION_MINOR = 1; static public final int DRIVER_VERSION_MINOR = 1;
@ -22,7 +22,7 @@ public class MyDriver implements Driver {
//依靠静态函数块注册驱动 //依靠静态函数块注册驱动
static{ static{
try { try {
DriverManager.registerDriver((MyDriver) ProxyFactory.getProxy(MyDriver.class, null)); DriverManager.registerDriver((ServiceDriver) ProxyFactory.getProxy(ServiceDriver.class, null));
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Can't register driver"); throw new RuntimeException("Can't register driver");
} }
@ -49,7 +49,7 @@ public class MyDriver implements Driver {
dbName = url.split(":")[1]; dbName = url.split(":")[1];
info.setProperty("agentDBName", dbName); info.setProperty("agentDBName", dbName);
} }
MyConnection myConn = (MyConnection) ProxyFactory.getProxy(MyConnection.class, info); ServiceConnection myConn = (ServiceConnection) ProxyFactory.getProxy(ServiceConnection.class, info);
myConn.setInfo(info); myConn.setInfo(info);
return myConn; return myConn;
} }

8
service/src/main/java/com/fanruan/servicejdbc/resultset/MyResultSet.java → service/src/main/java/com/fanruan/service/jdbc/resultset/ServiceResultSet.java

@ -1,7 +1,7 @@
package com.fanruan.servicejdbc.resultset; package com.fanruan.service.jdbc.resultset;
import com.fanruan.RemoteClass; import com.fanruan.annotation.RemoteClass;
import java.io.InputStream; import java.io.InputStream;
import java.io.Reader; import java.io.Reader;
@ -15,8 +15,8 @@ import java.util.Map;
/** /**
* @author Yichen Dai * @author Yichen Dai
*/ */
@RemoteClass(remoteClassName = "com.fanruan.agentjdbc.resultset.MyResultSet") @RemoteClass(remoteClassName = "com.fanruan.agent.jdbc.resultset.AgentResultSet")
public class MyResultSet implements ResultSet { public class ServiceResultSet implements ResultSet {
private String sql; private String sql;
private String ID; private String ID;

14
service/src/main/java/com/fanruan/servicejdbc/statement/MyPreparedStatement.java → service/src/main/java/com/fanruan/service/jdbc/statement/ServicePreparedStatement.java

@ -1,7 +1,7 @@
package com.fanruan.servicejdbc.statement; package com.fanruan.service.jdbc.statement;
import com.fanruan.RemoteClass; import com.fanruan.annotation.RemoteClass;
import com.fanruan.servicejdbc.resultset.MyResultSet; import com.fanruan.service.jdbc.resultset.ServiceResultSet;
import com.fanruan.proxy.ProxyFactory; import com.fanruan.proxy.ProxyFactory;
import java.io.InputStream; import java.io.InputStream;
@ -15,14 +15,14 @@ import java.util.Properties;
/** /**
* @author Yichen Dai * @author Yichen Dai
*/ */
@RemoteClass(remoteClassName = "com.fanruan.agentjdbc.statement.MyPreparedStatement") @RemoteClass(remoteClassName = "com.fanruan.agent.jdbc.statement.AgentPreparedStatement")
public class MyPreparedStatement implements PreparedStatement { public class ServicePreparedStatement implements PreparedStatement {
private Properties info; private Properties info;
private String ID; private String ID;
public MyPreparedStatement() {} public ServicePreparedStatement() {}
public String getID(){ public String getID(){
return this.ID; return this.ID;
@ -40,7 +40,7 @@ public class MyPreparedStatement implements PreparedStatement {
if(isClosed()) { if(isClosed()) {
throw new SQLException("This Statement is closed."); throw new SQLException("This Statement is closed.");
} }
MyResultSet rs = (MyResultSet) ProxyFactory.getProxy(MyResultSet.class, info); ServiceResultSet rs = (ServiceResultSet) ProxyFactory.getProxy(ServiceResultSet.class, info);
rs.setSql(info.getProperty("PreparedSQL")); rs.setSql(info.getProperty("PreparedSQL"));
return rs; return rs;
} }

17
service/src/main/java/com/fanruan/servicejdbc/statement/MyStatement.java → service/src/main/java/com/fanruan/service/jdbc/statement/ServiceStatement.java

@ -1,19 +1,22 @@
package com.fanruan.servicejdbc.statement; package com.fanruan.service.jdbc.statement;
import com.fanruan.RemoteClass; import com.fanruan.annotation.RemoteClass;
import com.fanruan.servicejdbc.resultset.MyResultSet; import com.fanruan.service.jdbc.resultset.ServiceResultSet;
import com.fanruan.proxy.ProxyFactory; import com.fanruan.proxy.ProxyFactory;
import java.sql.*; import java.sql.*;
import java.util.Properties; import java.util.Properties;
@RemoteClass(remoteClassName = "com.fanruan.agentjdbc.statement.MyStatement") /**
public class MyStatement implements Statement { * @author Yichen Dai
*/
@RemoteClass(remoteClassName = "com.fanruan.agent.jdbc.statement.AgentStatement")
public class ServiceStatement implements Statement {
private Properties info; private Properties info;
private String ID; private String ID;
public MyStatement() {} public ServiceStatement() {}
public String getID(){ public String getID(){
return this.ID; return this.ID;
@ -32,7 +35,7 @@ public class MyStatement implements Statement {
if(isClosed()) { if(isClosed()) {
throw new SQLException("This Statement is closed."); throw new SQLException("This Statement is closed.");
} }
MyResultSet rs = (MyResultSet) ProxyFactory.getProxy(MyResultSet.class, info); ServiceResultSet rs = (ServiceResultSet) ProxyFactory.getProxy(ServiceResultSet.class, info);
rs.setSql(sql); rs.setSql(sql);
return rs; return rs;
} }

2
service/src/test/java/AutoStarter.java

@ -14,7 +14,7 @@ public class AutoStarter {
new ServerStater(DBs); new ServerStater(DBs);
try { try {
Class.forName("com.fanruan.servicejdbc.driver.MyDriver"); Class.forName("com.fanruan.service.jdbc.driver.ServiceDriver");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }

4
service/src/test/java/Test.java

@ -51,7 +51,7 @@ public class Test {
ResultSet rs2 = null; ResultSet rs2 = null;
ResultSet rs3 = null; ResultSet rs3 = null;
try { try {
Class.forName("com.fanruan.servicejdbc.driver.MyDriver"); Class.forName("com.fanruan.service.jdbc.driver.ServiceDriver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", info); conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", info);
st = conn.createStatement(); st = conn.createStatement();
rs1 = st.executeQuery("select * from `student`"); rs1 = st.executeQuery("select * from `student`");
@ -158,7 +158,7 @@ public class Test {
ResultSet rs2 = null; ResultSet rs2 = null;
ResultSet rs3 = null; ResultSet rs3 = null;
try { try {
Class.forName("com.fanruan.servicejdbc.driver.MyDriver"); Class.forName("com.fanruan.service.jdbc.driver.ServiceDriver");
conn = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/test", info); conn = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/test", info);
st = conn.createStatement(); st = conn.createStatement();
rs1 = st.executeQuery("select * from student"); rs1 = st.executeQuery("select * from student");

174
test/src/test/java/TestUtil.java

@ -2,12 +2,10 @@
import com.fanruan.AgentStarter; import com.fanruan.AgentStarter;
import com.fanruan.ServerStater; import com.fanruan.ServerStater;
import com.fanruan.servicejdbc.driver.MyDriver; import com.fanruan.service.jdbc.driver.ServiceDriver;
import com.fanruan.proxy.ProxyFactory; import com.fanruan.proxy.ProxyFactory;
import com.fanruan.utils.DBProperties; import com.fanruan.utils.DBProperties;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.sql.*; import java.sql.*;
import java.util.Properties; import java.util.Properties;
@ -16,13 +14,34 @@ import java.util.Properties;
* @author Yichen Dai * @author Yichen Dai
* @date 2022/8/18 15:27 * @date 2022/8/18 15:27
*/ */
public class TestUtil { public class TestUtil {
static Connection conn = null;
static Statement st = null;
static PreparedStatement pst = null;
static ResultSet rs = null;
static void configService(){
String[][] DBs = new String[][]{
DBProperties.HSQL,
};
new ServerStater(DBs);
}
static void configAgent(){
String[][] DBs = new String[][]{
DBProperties.HSQL,
};
new AgentStarter(DBs);
}
@BeforeAll @BeforeAll
static void autoConfig(){ static void autoConfig(){
configService(); configService();
configAgent(); configAgent();
try { try {
// 等待socket连接
Thread.sleep(2000); Thread.sleep(2000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
@ -30,81 +49,122 @@ public class TestUtil {
} }
@Test @Test
void testCURD(){ void testConnect() throws SQLException {
// 建立连接
Properties info = new Properties(); Properties info = new Properties();
info.setProperty("user", "sa"); info.setProperty("user", "sa");
info.setProperty("password", ""); info.setProperty("password", "");
info.setProperty("agentID", "1001"); info.setProperty("agentID", "1001");
info.setProperty("agentDBName", DBProperties.HSQL[0]); info.setProperty("agentDBName", DBProperties.HSQL[0]);
Connection conn = null; Driver driver = (ServiceDriver) ProxyFactory.getProxy(ServiceDriver.class, null);
Statement st = null; conn = driver.connect("jdbc:hsqldb:mem:test", info);
PreparedStatement pst = null; }
ResultSet rs = null;
try {
// 创建 连接
Driver driver = (MyDriver) ProxyFactory.getProxy(MyDriver.class, null);
conn = driver.connect("jdbc:hsqldb:mem:test", info);
// 创建 statement
st = conn.createStatement();
// 创建表
st.executeUpdate("DROP TABLE student IF EXISTS;");
st.executeUpdate("CREATE TABLE student (" + @Test
"student_id INTEGER GENERATED BY DEFAULT AS IDENTITY " + void testCreateTable() throws SQLException {
"(START WITH 1, INCREMENT BY 1) NOT NULL," + testConnect();
"student_name VARCHAR(100) NOT NULL," + // 创建 statement
"student_address VARCHAR(100) NOT NULL," + st = conn.createStatement();
"PRIMARY KEY (student_id)" +
");");
// 插入数据 // 创建表
st.executeUpdate("INSERT INTO student VALUES" + int num = st.executeUpdate("DROP TABLE student IF EXISTS;");
"(1, '张三', '上海')," +
"(2, '李四', '北京')," +
"(3, '王五', '成都');");
Assertions.assertEquals(0, num);
// 预查询语句 删除指定 ID num = st.executeUpdate("CREATE TABLE student (" +
pst = conn.prepareStatement("delete from student where student_id = ?"); "student_id INTEGER GENERATED BY DEFAULT AS IDENTITY " +
"(START WITH 1, INCREMENT BY 1) NOT NULL," +
"student_name VARCHAR(100) NOT NULL," +
"student_address VARCHAR(100) NOT NULL," +
"PRIMARY KEY (student_id)" +
");");
pst.setInt(1, 1); Assertions.assertEquals(0, num);
}
pst.executeUpdate(); @Test
void testInsert() throws SQLException {
testCreateTable();
// 插入数据
int num = st.executeUpdate("INSERT INTO student VALUES" +
"(1, '张三', '上海')," +
"(2, '李四', '北京')," +
"(3, '王五', '成都');");
Assertions.assertEquals(3, num);
}
rs = st.executeQuery("select * from student"); @Test
void testUpdate() throws SQLException {
testInsert();
// 预查询语句 删除指定 ID
pst = conn.prepareStatement("UPDATE student" +
" SET student_name = '李华', student_address = '杭州'"+
"WHERE student_id = ?");
String[] nameStrings = new String[]{"张三", "李四", "王五"}; Assertions.assertNotNull(pst);
String[] addressStrings = new String[]{"上海", "北京", "成都"};
// 结果集断言 pst.setInt(1, 1);
int num = 2;
while(rs.next()) { int num = pst.executeUpdate();
Assertions.assertEquals(rs.getInt("student_id"), num);
Assertions.assertEquals(rs.getString("student_name"), nameStrings[num-1]); Assertions.assertEquals(1, num);
Assertions.assertEquals(rs.getString("student_address"), addressStrings[num-1]);
num++;
}
} catch (Exception e) {
e.printStackTrace();
}
} }
static void configService(){ @Test
String[][] DBs = new String[][]{ void testDelete() throws SQLException {
DBProperties.HSQL, testInsert();
}; // 预查询语句 删除指定 ID
new ServerStater(DBs); pst = conn.prepareStatement("delete from student where student_id = ?");
Assertions.assertNotNull(pst);
pst.setInt(1, 1);
int num = pst.executeUpdate();
Assertions.assertEquals(1, num);
} }
static void configAgent(){ @Test
String[][] DBs = new String[][]{ void testSelect() throws SQLException {
DBProperties.HSQL, testInsert();
}; rs = st.executeQuery("select * from student");
new AgentStarter(DBs);
String[] nameStrings = new String[]{"张三", "李四", "王五"};
String[] addressStrings = new String[]{"上海", "北京", "成都"};
// 结果集断言
int num = 1;
while(rs.next()) {
Assertions.assertEquals(rs.getInt("student_id"), num);
Assertions.assertEquals(rs.getString("student_name"), nameStrings[num-1]);
Assertions.assertEquals(rs.getString("student_address"), addressStrings[num-1]);
num++;
}
}
@AfterAll
static void close() throws SQLException {
if(rs!= null){
rs.close();
}
if(pst != null){
pst.close();
}
if(st != null){
st.close();
}
if(conn != null){
conn.close();
}
} }
} }

Loading…
Cancel
Save