This commit is contained in:
insanity 2017-05-25 17:58:36 +09:00
parent e09757ce17
commit b136b00187
7 changed files with 450 additions and 21 deletions

85
.gitignore vendored Normal file
View File

@ -0,0 +1,85 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Maven template
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# Avoid ignoring Maven wrapper jar file (.jar files are usually ignored)
!/.mvn/wrapper/maven-wrapper.jar
### Java template
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
.idea/
*.iml

108
pom.xml
View File

@ -16,6 +16,114 @@
<version>1.0.0-SNAPSHOT</version>
<name>com.loafle.overflow_proxy_db</name>
<properties>
<grpc.version>1.2.0</grpc.version>
<hibernate.version>4.3.10.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1200-jdbc41</version>
</dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/junit/junit &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>junit</groupId>-->
<!--<artifactId>junit</artifactId>-->
<!--<version>4.4</version>-->
<!--</dependency>-->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.loafle</groupId>
<artifactId>overflow_jpa_member_dao</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.4.1.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.2.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,7 +0,0 @@
package com.loafle;
public class App {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

View File

@ -0,0 +1,152 @@
package com.loafle.overflow.proxy.db;
import com.loafle.overflow.db.api.DBGrpc;
import com.loafle.overflow.db.api.DBInput;
import com.loafle.overflow.db.api.DBOutput;
import com.loafle.overflow.commons.dao.JPABaseDAO;
import com.loafle.overflow.member.dao.JPAMemberDAO;
import io.grpc.ServerBuilder;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
/**
* Created by insanity on 17. 5. 23.
*/
public class DBProxy {
private static final Logger logger = Logger.getLogger(DBProxy.class.getName());
private io.grpc.Server server;
private static Map<String, JPABaseDAO> daoMap = null;
public DBProxy() {
daoMap = new ConcurrentHashMap();
JPAMemberDAO memberDao = new JPAMemberDAO();
daoMap.put("member", memberDao);
}
public void start(int port) throws IOException {
server = ServerBuilder.forPort(port)
.addService(new ServiceImpl())
.build()
.start();
logger.info("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
DBProxy.this.stop();
System.err.println("*** server shut down");
}
});
}
public void stop() {
if (server != null) {
server.shutdown();
}
}
static class ServiceImpl extends DBGrpc.DBImplBase {
@Override
public void exec(DBInput request,
io.grpc.stub.StreamObserver<com.loafle.overflow.db.api.DBOutput> responseObserver) {
String targetDAO = request.getTargetDao();
JPABaseDAO dao = daoMap.get(targetDAO);
if(dao != null) {
try {
String jsonResult = doQuery(request, dao);
DBOutput reply = DBOutput.newBuilder()
.setResult(jsonResult)
.build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}catch(Exception e) {
e.printStackTrace();
responseObserver.onError(e);
}
}else {
responseObserver.onError(new Exception("Not assigned DAO :" + targetDAO));
}
}
private String doQuery(DBInput request, JPABaseDAO dao) throws Exception {
String methodName = request.getMethod();
Map<String, String> params = request.getParamsMap();
ObjectMapper mapper = new ObjectMapper();
List<Class> paramTypes = new ArrayList<Class>();
List<Object> valueList = new ArrayList<Object>();
for( String className : params.keySet() ){
//className - model name(with package) , value - model JsonString
Class<?> cls = Class.forName(className);
Object obj = mapper.readValue((String)params.get(className), cls);
valueList.add(obj);
paramTypes.add(cls);
}
Object retObj = null;
Method method = null;
try {
//Check if it belongs to the JPABaseDAO.
method = dao.getClass().getSuperclass().getMethod(methodName, Object.class);
if(method != null) {
retObj = method.invoke(dao, valueList.toArray(new Object[valueList.size()]));
}
}catch(NoSuchMethodException e) {
if(params.size() > 0) {
method = dao.getClass().getMethod(methodName, paramTypes.toArray(new Class[paramTypes.size()]));
retObj = method.invoke(dao, valueList.toArray(new Object[valueList.size()]));
}else {
method = dao.getClass().getMethod(methodName);
retObj = method.invoke(dao);
}
}catch(InvocationTargetException e) {
e.printStackTrace();
}
return mapper.writeValueAsString(retObj);
}
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
if(args.length <= 0) {
System.out.println("Port args");
System.out.println("first parameter is Port Number");
return;
}
int port = Integer.valueOf(args[0]);
final DBProxy server = new DBProxy();
server.start(port);
server.blockUntilShutdown();
}
}

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="overflow">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://192.168.1.106:5432/postgres" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.user" value="vertx" />
<property name="javax.persistence.jdbc.password" value="qwe123" />
<!--<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />-->
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>

View File

@ -1,11 +0,0 @@
package com.loafle;
import static org.junit.Assert.*;
import org.junit.Test;
public class AppTest {
@Test
public void testSum() {
fail("Not yet implemented");
}
}

View File

@ -0,0 +1,85 @@
package com.loafle;
import com.loafle.overflow.db.api.DBGrpc;
import com.loafle.overflow.db.api.DBInput;
import com.loafle.overflow.db.api.DBOutput;
import com.loafle.overflow.member.model.Member;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TestClient {
private static final Logger logger = Logger.getLogger(TestClient.class.getName());
private final ManagedChannel channel;
private final DBGrpc.DBBlockingStub dbStub;
public TestClient() {
channel = ManagedChannelBuilder.forAddress("127.0.0.1", 50006).usePlaintext(true).build();
dbStub = DBGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void execute() {
try {
Member m = new Member();
m.setName("insanity2222");
m.setCompany("loafle");
m.setDigest("bbbbbbbbb");
m.setPwSalt("salktttt");
m.setEmail("insanity@loafle.com");
m.setRegistDate(111110);
ObjectMapper mapper = new ObjectMapper();
DBInput request = DBInput.newBuilder()
.setTargetDao("member")
.setMethod("create")
.putParams("com.loafle.overflow.member.model.Member", mapper.writeValueAsString(m))
//.putParams("com.loafle.overflow.member.Member2", mapper.writeValueAsString(m2))
.build();
DBOutput response;
try {
response = dbStub.exec(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.log(Level.INFO, response.getResult());
}catch(Exception e) {
e.printStackTrace();
}
}
@Test
public void testRPCServer() {
TestClient client = new TestClient();
try {
client.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}