first overflow service commit

This commit is contained in:
snoop 2017-06-22 12:07:45 +09:00
commit 19427d74a7
42 changed files with 2595 additions and 0 deletions

65
.gitignore vendored Normal file
View File

@ -0,0 +1,65 @@
# 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
### Go template
# Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/
.idea/
*.iml
vendor/
glide.lock

221
gateway/service_test.go Normal file
View File

@ -0,0 +1,221 @@
package gateway
import (
"testing"
"reflect"
"github.com/stretchr/testify/assert"
"encoding/json"
"github.com/golang/glog"
"fmt"
"git.loafle.net/overflow/overflow_proxy_service/proxy/member"
"git.loafle.net/overflow/overflow_proxy_service/proxy/target"
)
func TestServices(t *testing.T) {
InitServices()
meb, _ := g_services["Member"]
m := make(map[string]string)
m["email"] = "geek@loafle.com"
m["pw"] = "qwer5795"
convertParam(meb, m)
//val := []reflect.Value{reflect.ValueOf(meb.(*proxy.MemberService))}
va := reflect.ValueOf(meb).MethodByName("Regist").Call([]reflect.Value{})
//reflect.ValueOf(meb).MethodByName("Read").Call(reflect.ValueOf(meb))
assert.Equal(t, 0, len(va))
}
func TestServiceParam(t *testing.T) {
InitServices()
meb, _ := g_services["Member"]
m := make(map[string]string)
m["email"] = "geek@loafle.com"
m["pw"] = "qwer5795"
paramStr, err := json.Marshal(m)
if err != nil {
glog.Fatal("Json Marshal Failed : ", err.Error())
}
err = json.Unmarshal(paramStr, meb)
if err != nil {
glog.Fatal("Json Unmarshal Failed : ", err.Error())
}
//assert.ObjectsAreEqual(proxy.MemberService{}, meb)
}
//
//type Member struct {
// Email string `json:"email"`
// Password string `json:"password"`
//}
//
//type MemberService struct {
// ServiceName string `json:"serviceName"`
// MethodName string `json:"methodName"`
// Param *Member `json:"param"`
//}
func TestExecServices(t *testing.T) {
//res := `{"serviceName":"Member","methodName":"Regist","param":{"email":"geek@loafle.com","password":"qwer5795"}}`
res := `{"email":"geekloafle@loafle.com","pwSalt":"dssdft","company":"loafle"}`
m := make(map[string]string)
m["model"] = res
InitServices()
meb, _ := g_services["Member"]
methodName := reflect.ValueOf(meb).MethodByName("Regist")
params := make([]reflect.Value, methodName.Type().NumIn())
var NewObj reflect.Value
for i := 0; i < methodName.Type().NumIn(); i++{
temp := methodName.Type().In(i)
switch temp.Kind() {
case reflect.Ptr:
NewObj = reflect.New(temp.Elem())
convertParam(NewObj.Interface(), m)
params[i] = NewObj
}
}
result := methodName.Call(params)[0].String()
fmt.Println(result)
}
//func TestReflectType(t *testing.T) {
//ss := &MemberService{}
////t1 := reflect.ValueOf(ss.Param).Elem()
//
//ms1 := reflect.New(reflect.TypeOf(ss.Param)).Elem().Type()
//
//fmt.Println(ms1)
////ss.Param = ms1
////ss.Param.Email = "ddd"
////fmt.Println(ss.Param.Email)
//ms := reflect.New(reflect.ValueOf(ss.Param).Type()).Elem()
//fmt.Printf("created a [%T]\n", reflect.ValueOf(ms).Type())
//}
func TestConvertParamModel(t *testing.T) {
res := `{"email":"geek@loafle.com","pwSalt":"dssdft","company":"loafle"}`
m := make(map[string]string)
m["model"] = res
mem := &member.Member{}
convertParam(mem, m)
fmt.Println(mem.Email)
}
func TestParamTypeCreate(t *testing.T) {
ms := member.NewMemberService()
res := `{"email":"geek@loafle.com","pwSalt":"dssdft","company":"loafle"}`
method := reflect.ValueOf(ms).MethodByName("Regist")
var NewObj reflect.Value;
for i := 0; i < method.Type().NumIn(); i++ {
tt := method.Type().In(i)
t.Log(tt)
switch tt.Kind() {
case reflect.Ptr :
NewObj = reflect.New(tt.Elem())
}
//obj = NewObj.Elem().Interface()
//intPtr := reflect.New(tt)
//obj := intPtr.Elem().Interface()
err := json.Unmarshal([]byte(res), NewObj.Interface())
if err != nil {
t.Log(err)
}
t.Log(NewObj)
}
params := make([]reflect.Value, method.Type().NumIn())
params[0] = NewObj;
result := method.Call(params)[0].String()
t.Log(result)
}
func TestListReflect(t *testing.T) {
res := "[{\"id\":1,\"ip\":3232235882,\"port\":5432,\"targetType\":\"DATABASE\",\"vendorName\":\"PostgreSQL 9.5.0\",\"kinds\":\"PostgreSQL\",\"version\":\"9.5.0\",\"createDate\":1496631864025,\"member\":{\"id\":1,\"email\":\"ddddd@loafle.com\",\"pwSalt\":\"salktttt\",\"digest\":\"bbbbbbbbb\",\"name\":\"snnnnn\",\"company\":\"loafle\",\"phone\":\"000-000-0000\",\"authorizedDate\":null}},{\"id\":2,\"ip\":3232235882,\"port\":5432,\"targetType\":\"DATABASE\",\"vendorName\":\"PostgreSQL 9.5.0\",\"kinds\":\"PostgreSQL\",\"version\":\"9.5.0\",\"createDate\":1496635285090,\"member\":{\"id\":1,\"email\":\"ddddd@loafle.com\",\"pwSalt\":\"salktttt\",\"digest\":\"bbbbbbbbb\",\"name\":\"snnnnn\",\"company\":\"loafle\",\"phone\":\"000-000-0000\",\"authorizedDate\":null}},{\"id\":3,\"ip\":3232235882,\"port\":5432,\"targetType\":\"DATABASE\",\"vendorName\":\"PostgreSQL 9.5.0\",\"kinds\":\"PostgreSQL\",\"version\":\"9.5.0\",\"createDate\":1496642868260,\"member\":{\"id\":1,\"email\":\"ddddd@loafle.com\",\"pwSalt\":\"salktttt\",\"digest\":\"bbbbbbbbb\",\"name\":\"snnnnn\",\"company\":\"loafle\",\"phone\":\"000-000-0000\",\"authorizedDate\":null}},{\"id\":4,\"ip\":3232235882,\"port\":5432,\"targetType\":\"DATABASE\",\"vendorName\":\"PostgreSQL 9.5.0\",\"kinds\":\"PostgreSQL\",\"version\":\"9.5.0\",\"createDate\":1496814093714,\"member\":{\"id\":1,\"email\":\"ddddd@loafle.com\",\"pwSalt\":\"salktttt\",\"digest\":\"bbbbbbbbb\",\"name\":\"snnnnn\",\"company\":\"loafle\",\"phone\":\"000-000-0000\",\"authorizedDate\":null}},{\"id\":5,\"ip\":3232235882,\"port\":5432,\"targetType\":\"DATABASE\",\"vendorName\":\"PostgreSQL 9.5.0\",\"kinds\":\"PostgreSQL\",\"version\":\"9.5.0\",\"createDate\":1496814103052,\"member\":{\"id\":1,\"email\":\"ddddd@loafle.com\",\"pwSalt\":\"salktttt\",\"digest\":\"bbbbbbbbb\",\"name\":\"snnnnn\",\"company\":\"loafle\",\"phone\":\"000-000-0000\",\"authorizedDate\":null}},{\"id\":6,\"ip\":3232235882,\"port\":5432,\"targetType\":\"DATABASE\",\"vendorName\":\"PostgreSQL 9.5.0\",\"kinds\":\"PostgreSQL\",\"version\":\"9.5.0\",\"createDate\":1496814184478,\"member\":{\"id\":1,\"email\":\"ddddd@loafle.com\",\"pwSalt\":\"salktttt\",\"digest\":\"bbbbbbbbb\",\"name\":\"snnnnn\",\"company\":\"loafle\",\"phone\":\"000-000-0000\",\"authorizedDate\":null}}]";
t.Log(res)
ts := target.NewTargetService()
method := reflect.ValueOf(ts).MethodByName("CreateList")
var NewObj reflect.Value;
for i := 0; i < method.Type().NumIn(); i++ {
tt := method.Type().In(i)
t.Log(tt)
switch tt.Kind() {
case reflect.Ptr :
NewObj = reflect.New(tt.Elem())
case reflect.Slice :
NewObj = reflect.MakeSlice(tt, 0, 0)
}
err := json.Unmarshal([]byte(res), NewObj.Interface())
if err != nil {
t.Log(err)
}
t.Log(NewObj)
}
params := make([]reflect.Value, method.Type().NumIn())
params[0] = NewObj;
result := method.Call(params)[0].String()
t.Log(result)
//ts.cre
}

135
gateway/services.go Normal file
View File

@ -0,0 +1,135 @@
package gateway
import (
"golang.org/x/net/context"
pb "git.loafle.net/overflow/overflow_api_service/grpc"
"github.com/golang/glog"
"encoding/json"
"reflect"
"errors"
"log"
"git.loafle.net/overflow/overflow_service/proxy/noauthagent"
"git.loafle.net/overflow/overflow_service/proxy/target"
"git.loafle.net/overflow/overflow_service/proxy/member"
"git.loafle.net/overflow/overflow_service/proxy/crawler"
"git.loafle.net/overflow/overflow_service/proxy/crawlerInputItem"
"git.loafle.net/overflow/overflow_service/proxy/crawlerinputitemmapping"
"git.loafle.net/overflow/overflow_service/proxy/sensor"
"git.loafle.net/overflow/overflow_service/proxy/sensorItem"
"git.loafle.net/overflow/overflow_service/proxy/sensorItemCategory"
"git.loafle.net/overflow/overflow_service/proxy/sensorItemMapping"
"git.loafle.net/overflow/overflow_service/proxy/agent"
//"google.golang.org/grpc/metadata"
)
var g_services map[string]interface{}
func AddServices(name string, s interface{}) {
if g_services == nil {
g_services = make(map[string]interface{},0)
}
g_services[name] = s
}
type Services interface {
GetModel()(interface{})
}
func InitServices() {
g_services = make(map[string]interface{},0)
// proxy services save
//AddServices("Agent", agent.NewAgentService())
AddServices("Member", member.NewMemberService())
AddServices("NoAuthAgent", noauthagent.NewNoAuthAgentService())
AddServices("Agent", agent.NewAgentService())
AddServices("Target", target.NewTargetService())
AddServices("Crawler", crawler.NewCrawlerService())
AddServices("CrawlerInputItem", crawlerInputItem.NewCrawlerInputItemService())
AddServices("CrawlerInputItemMapping", crawlerinputitemmapping.NewCrawlerInputItemMappingService())
AddServices("Sensor", sensor.NewSensorService())
AddServices("SensorItem", sensorItem.NewSensorItemService())
AddServices("SensorItemCategory", sensorItemCategory.NewSensorItemCategoryService())
AddServices("SensorItemMapping", sensorItemMapping.NewSensorItemMappingService())
}
type ServiceImpl struct {
}
func (s *ServiceImpl) ExecServices(c context.Context, in *pb.ServiceInput) (*pb.ServiceOutput, error) {
// Check Service Name
serviceName, ok := g_services[in.ServiceName]
//metadata.FromContext(c)
log.Println("Service Name : " + in.ServiceName + " MethodName : " + in.MethodName)
if !ok {
return nil, errors.New("Not Exist Service Name")
}
pbs := &pb.ServiceOutput{}
methodName := reflect.ValueOf(serviceName).MethodByName(in.MethodName)
if methodName.IsValid() == false {
return pbs, errors.New("Not Exist Method Name")
}
params := make([]reflect.Value, methodName.Type().NumIn())
var NewObj reflect.Value
for i := 0; i < methodName.Type().NumIn(); i++{
temp := methodName.Type().In(i)
switch temp.Kind() {
case reflect.Ptr:
NewObj = reflect.New(temp.Elem())
}
convertParam(NewObj.Interface(), in.Param)
params[i] = NewObj
}
// Todo Call Service Method
results := methodName.Call(params);
result := results[0].Interface().(string)
var err error = nil;
if len(result) > 1 {
obj := results[1].Interface()
if obj != nil {
log.Println("err : " + err.Error())
err = obj.(error)
return pbs, err
}
}
pbs.ResultStr = result
return pbs, nil
}
func convertParam(sn interface{}, param map[string]string) {
// param convert string
//paramStr, err := json.Marshal(param)
//if err != nil {
// glog.Fatal("Json Marshal Failed : ", err.Error())
//}
paramStr := param["model"]
// service converting
log.Println("input model : ", paramStr)
err := json.Unmarshal([]byte(paramStr), sn)
if err != nil {
glog.Fatal("Json Unmarshal Failed : ", err.Error())
}
}

32
glide.yaml Normal file
View File

@ -0,0 +1,32 @@
package: git.loafle.net/overflow/overflow_gateway_service
import:
- package: git.loafle.net/overflow/overflow_api_service
version: master
repo: https://git.loafle.net/overflow/overflow_api_service.git
vcs: git
subpackages:
- grpc
- package: git.loafle.net/overflow/overflow_proxy_service
version: master
repo: https://git.loafle.net/overflow/overflow_proxy_service.git
vcs: git
subpackages:
- proxy/member
- proxy/noauthagent
- proxy/agent
- package: github.com/golang/glog
- package: github.com/grpc-ecosystem/grpc-gateway
version: ^1.2.2
subpackages:
- runtime
- package: golang.org/x/net
subpackages:
- context
- package: google.golang.org/grpc
- package: git.loafle.net/overflow/overflow_gateway_service
subpackages:
- gateway
testImport:
- package: github.com/stretchr/testify
subpackages:
- assert

17
gwrpc_main.go Normal file
View File

@ -0,0 +1,17 @@
package main
import (
"flag"
"github.com/golang/glog"
"git.loafle.net/overflow/overflow_gateway_service/server"
)
func main() {
flag.Parse()
defer glog.Flush()
if err := server.RunGwRpc(); err != nil {
glog.Fatal(err)
}
}

View File

@ -0,0 +1,85 @@
package agent
import (
"encoding/json"
//"fmt"
//"git.loafle.net/overflow/overflow_proxy_service/proxy"
"git.loafle.net/overflow/overflow_proxy_service/proxy/member"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
"time"
)
type AgentService struct {
}
type Agent struct {
Id json.Number `json:"id,Number,omitempty"`
AuthorizedDate int64 `json:"authorizedDate,Number,omitempty"`
Description string `json:"description,omitempty"`
Member member.Member `json:"member,omitempty"`
LastPollingDate int64 `json:"lastPollingDate,omitempty"`
Status string `json:"status,omitempty"`
}
func NewAgentService() *AgentService {
return &AgentService{}
}
func NewAgent(desc string, member member.Member) *Agent {
na := &Agent{
AuthorizedDate: time.Now().Unix(),
Description: desc,
Member: member,
}
return na
}
func (as *AgentService) SaveAgent(agent *Agent) (string, error) {
//bytes, err := json.Marshal(agent)
//if err != nil {
// return "", err
//}
//fmt.Println(agent.Member.Id)
//fmt.Println(string(bytes))
//paramMap := make(map[string]string)
//paramMap["com.loafle.overflow.agent.model.Agent"] = string(bytes)
//
//out, err := proxy.InvokeDB("agent", "create", paramMap)
out, err := utils.InvokeDB("agent", "create", agent)
if err != nil {
return "", err
}
return out, nil
}
func (as *AgentService) GetAgentList(mem *member.Member) (string, error) {
//paramMap := make(map[string]string)
//
//mem := member.NewMember()
//mem.Id = json.Number(memberId)
//
//bytes, err := json.Marshal(mem)
//if err != nil {
// return "", err
//}
//
//paramMap["com.loafle.overflow.member.model.Member"] = string(bytes)
//
//out, err := proxy.InvokeDB("agent", "findAgentListByMemberId", paramMap)
out, err := utils.InvokeDBByModel("agent", "findAgentListByMemberId", mem, "com.loafle.overflow.member.model.Member")
if err != nil {
return "", err
}
return out, nil
}
func (as *AgentService) GetModel() interface{} {
return &Agent{}
}

View File

@ -0,0 +1,33 @@
package agent
import (
"encoding/json"
"testing"
"git.loafle.net/overflow/overflow_proxy_service/proxy/member"
)
func TestSaveAgent(t *testing.T) {
m := member.Member{}
m.Id = json.Number("1")
agt := NewAgent("test agent424", m)
as := NewAgentService()
res, err := as.SaveAgent(agt)
if err != nil {
t.Log(res)
}
}
func TestListAgent(t *testing.T) {
as := NewAgentService()
m := member.Member{}
m.Id = "1"
if res, err := as.getAgentList(&m); err != nil {
t.Fatal(err)
}else {
t.Log(res)
}
}

View File

@ -0,0 +1,84 @@
package apikey
import (
"encoding/json"
"git.loafle.net/overflow/commons_go/model/timestamp"
//"git.loafle.net/overflow/overflow_proxy_service/proxy"
//"log"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
)
type ApiKeyService struct {
}
type ApiKey struct {
Id json.Number `json:"id,Number,omitempty"`
Apikey string `json:"apiKey,omitempty"`
CreateDAte timestamp.Timestamp`json:"createDate,omitempty"`
HostName string `json:"hostName,omitempty"`
}
func NewApiKeyService() *ApiKeyService {
return &ApiKeyService{}
}
func(k *ApiKeyService)SaveApikey(key *ApiKey) (string, error) {
//bytes, err := json.Marshal(key)
//
//if err != nil {
// return "", err
//}
//
//m := make(map[string]string)
//
//m["com.loafle.overflow.keystore.model.Apikey"] = string(bytes)
//
//out := proxy.InvokeDB("apiKey", "create", m)
//
//log.Print(out)
out, err := utils.InvokeDBByModel("apiKey", "create", key, "com.loafle.overflow.keystore.model.Apikey")
if err != nil {
return "", err
}
return out, nil
}
func(k *ApiKeyService)CheckApikey(apikey string) (bool, error) {
ak := ApiKey{
Apikey:apikey,
}
//bytes, err := json.Marshal(ak)
//
//if err != nil {
// return false, err
//}
//
//m := make(map[string]string)
//
//m["com.loafle.overflow.keystore.model.Apikey"] = string(bytes)
//
//out := proxy.InvokeDB("apiKey", "findByApiKey", m)
//
//log.Print(out)
_, err := utils.InvokeDB("apiKey", "findByApiKey", ak)
if err != nil {
return false, err
}
return true, nil
}

View File

@ -0,0 +1 @@
package apikey

View File

@ -0,0 +1,58 @@
package crawler
import (
"encoding/json"
"git.loafle.net/overflow/commons_go/model/timestamp"
//"git.loafle.net/overflow/overflow_proxy_service/proxy"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
)
type CrawlerService struct {
}
func NewCrawlerService() *CrawlerService {
return &CrawlerService{}
}
type Crawler struct {
Id json.Number `json:"id,Number,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
CrawlerType string `json:"crawlerType,omitempty"`
CreateDate timestamp.Timestamp `json:"createDate,omitempty"`
}
func (c *CrawlerService)List() (string, error) {
//out := proxy.InvokeDB("crawler", "findAll", nil)
out, err := utils.InvokeDB("crawler", "findAll", nil)
if err != nil {
return "", err
}
return out, nil
}
func (c *CrawlerService)Create(ct * Crawler) (string, error) {
out, err := utils.InvokeDB("crawler", "create", ct)
if err != nil {
return "", err
}
return out, nil
}

View File

@ -0,0 +1,14 @@
package crawler
import "testing"
func TestList(t *testing.T) {
cs := NewCrawlerService()
out := cs.List()
t.Log(out)
}

View File

@ -0,0 +1,38 @@
package crawlerInputItem
import (
"git.loafle.net/overflow/commons_go/model/timestamp"
"encoding/json"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
)
type CrawlerInputItem struct {
Id json.Number `json:"id,Number,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
DataType string `json:"dataType,omitempty"`
CreateDate timestamp.Timestamp `json:"createDate,omitempty"`
}
type CrawlerInputItemSerivce struct {
}
func NewCrawlerInputItemService() *CrawlerInputItemSerivce {
return &CrawlerInputItemSerivce{}
}
func (c *CrawlerInputItemSerivce)Create(cii * CrawlerInputItem) (string, error) {
out, err := utils.InvokeDB("crawlerInputItem", "create", cii)
if err != nil {
return "", err
}
return out, nil;
}

View File

@ -0,0 +1 @@
package crawlerInputItem

View File

@ -0,0 +1,55 @@
package crawlerinputitemmapping
import (
"git.loafle.net/overflow/commons_go/model/timestamp"
"encoding/json"
"git.loafle.net/overflow/overflow_proxy_service/proxy/crawler"
"git.loafle.net/overflow/overflow_proxy_service/proxy/crawlerInputItem"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
)
type CrawlerInputItemMapping struct {
Id json.Number `json:"id,Number,omitempty"`
Crawler crawler.Crawler `json:"crawler,omitempty"`
CrawlerInputItem crawlerInputItem.CrawlerInputItem `json:"crawlerInputItem,omitempty"`
Priority json.Number `json:"priority,Number,omitempty"`
RequiredType bool `json:"requiredType,omitempty"`
CreateDate timestamp.Timestamp `json:"createDate,omitempty"`
}
type CrawlerInputItemMappingService struct {
}
func NewCrawlerInputItemMappingService() *CrawlerInputItemMappingService {
return &CrawlerInputItemMappingService{}
}
func (c *CrawlerInputItemMappingService)Create(ciim *CrawlerInputItemMapping) (string, error) {
out, err := utils.InvokeDB("crawlerInputItemMapping", "create", ciim)
if err != nil {
return "", err
}
return out, nil;
}
func (c *CrawlerInputItemMappingService)List(cr *crawler.Crawler) (string, error) {
out, err := utils.InvokeDBByModel("crawlerInputItemMapping", "findByCrawlerId", cr, "com.loafle.overflow.crawler.model.Crawler")
if err != nil {
return "", err
}
return out, nil;
}

View File

@ -0,0 +1,25 @@
package crawlerinputitemmapping
import (
"testing"
"git.loafle.net/overflow/overflow_proxy_service/proxy/crawler"
)
func TestListCrawler(t *testing.T) {
niin := NewCrawlerInputItemMappingService()
cc := &crawler.Crawler{}
cc.Id = "1";
out := niin.List(cc)
t.Log(out)
}

View File

@ -0,0 +1,207 @@
package email
import (
"crypto/tls"
"encoding/json"
"fmt"
"git.loafle.net/overflow/commons_go/model/timestamp"
"git.loafle.net/overflow/overflow_proxy_service/proxy"
"git.loafle.net/overflow/overflow_proxy_service/proxy/member"
"github.com/google/uuid"
"log"
"net"
"net/mail"
"net/smtp"
"strings"
)
const (
FROM = "geek@loafle.com"
SERVER_NAME = "smtp.worksmobile.com:465"
SUBJECT = "This is the Test Email"
BODY_MSG = "This is an Example Email\n with two lines \n http://localhost:8080/v1/overflow/services"
SERVER_PASS = "@loafle@5795"
)
type Email struct {
Id json.Number `json:"id,Number,omitempty"`
Member member.Member `json:"member"`
From string `json:"_"`
Subj string `json:"_"`
AuthToken string `json:"authToken"`
IsInvalid bool `json:"isInvalid"`
IsConfirm bool `json:"isConfirm"`
CreateDate timestamp.Timestamp `json:"createDate,omitempty"`
UpdateDate timestamp.Timestamp `json:"updateDate,omitempty"`
ConfirmDate timestamp.Timestamp `json:"confirmDate,omitempty"`
SmtpServer string `json:"_"`
BodyMsg string `json:"_"`
}
func NewEmail(member member.Member, subject string) *Email {
if subject == "" {
subject = SUBJECT
}
return &Email{
Member: member,
From: FROM,
Subj: subject,
SmtpServer: SERVER_NAME,
}
}
type EmailService struct {
}
func NewEmailService() *EmailService {
return &EmailService{}
}
func (es *EmailService) checkError(err error) {
if err != nil {
log.Panic(err)
}
}
func (es *EmailService) getSendMailMessage(e *Email) string {
to := mail.Address{"Park Byung Eun", e.Member.Email}
from := mail.Address{"Overflow", e.From}
//body := "This is an Example Email\n with two lines \n http://localhost:8080/v1/overflow/services"
// Setup headers
headers := make(map[string]string)
headers["From"] = from.String()
headers["To"] = to.String()
headers["Subject"] = e.Subj
message := ""
for k, v := range headers {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + BODY_MSG
return message
}
func (es *EmailService) generationAuthToken(e *Email) string {
var tempToken string
uuid, _ := uuid.NewRandom()
tempToken += strings.ToUpper(uuid.String())
return tempToken
}
func (es *EmailService) SendEmailForAuth(e *Email) error {
to := mail.Address{"Park Byung Eun", e.Member.Email}
from := mail.Address{"Overflow", e.From}
message := es.getSendMailMessage(e)
host, _, _ := net.SplitHostPort(SERVER_NAME)
auth := smtp.PlainAuth("", FROM, SERVER_PASS, host)
// TLS config
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: host,
}
//Todo auth token generation
e.AuthToken = es.generationAuthToken(e)
e.IsInvalid = false
e.IsConfirm = false
conn, err := tls.Dial("tcp", SERVER_NAME, tlsconfig)
es.checkError(err)
c, err := smtp.NewClient(conn, host)
es.checkError(err)
// Auth
err = c.Auth(auth)
es.checkError(err)
// To && From
err = c.Mail(from.Address)
es.checkError(err)
err = c.Rcpt(to.Address)
es.checkError(err)
// Data
w, err := c.Data()
es.checkError(err)
_, err = w.Write([]byte(message))
es.checkError(err)
err = w.Close()
es.checkError(err)
c.Quit()
// Todo Save Email For DB
es.saveEmail(e)
return err
}
func (es *EmailService) getEmailMap(e *Email) map[string]string {
emMap := make(map[string]string)
str, err := json.Marshal(e)
if err != nil {
log.Fatal("Json Marshal Error: ", err)
}
emMap["com.loafle.overflow.email.model.EmailAuth"] = string(str)
return emMap
}
func (es *EmailService) saveEmail(e *Email) {
memMap := es.getEmailMap(e)
proxy.InvokeDB("emailAuth", "create", memMap)
}
func (es *EmailService) CheckAuthURL(e *Email) bool {
//Query from the database with an authentication token.
emMap := es.getEmailMap(e)
re := proxy.InvokeDB("emailAuth", "findByAuthToken", emMap)
tempEmail := &Email{}
json.Unmarshal([]byte(re), tempEmail)
r := strings.Compare(e.AuthToken, tempEmail.AuthToken)
//Todo Check for valid
log.Println(tempEmail)
if r == 0 {
// Todo isConfirm change true and db update
tempEmail.IsConfirm = true
tempEmail.UpdateDate = timestamp.Now()
tempEmail.ConfirmDate = timestamp.Now()
es.modifyEmailAuth(tempEmail)
return true
}
return false
}
func (es *EmailService) modifyEmailAuth(e *Email) {
emMap := es.getEmailMap(e)
proxy.InvokeDB("emailAuth", "update", emMap)
}

View File

@ -0,0 +1,44 @@
package email
import (
"testing"
"fmt"
"git.loafle.net/overflow/overflow_proxy_service/proxy/member"
"encoding/json"
)
func getEmailObj() (*Email,*EmailService) {
es := NewEmailService()
m := member.Member{
Email:"geek@loafle.com",
Name:"geek",
Company:"loafle",
Id:json.Number("4"),
}
e := NewEmail(m, "Hello Oveflow")
return e,es
}
func TestSendEmailForAuth(t *testing.T) {
e, es := getEmailObj()
es.SendEmailForAuth(e)
}
func TestEmailService_CheckAuthURL(t *testing.T) {
e, es := getEmailObj()
//e.Id = json.Number("2")
e.AuthToken = "3C03F8AB-1D4D-4C8A-8C36-EE2D644988B5"
rr := es.CheckAuthURL(e)
fmt.Println(rr)
}
func TestAuthTokenGeneration(t *testing.T) {
e, es := getEmailObj()
tt := es.generationAuthToken(e)
fmt.Println(tt)
}

View File

@ -0,0 +1,24 @@
package keystore
import (
"github.com/google/uuid"
)
type KeyStoreService struct {
}
func NewKeyStoreSerivce() *KeyStoreService {
return &KeyStoreService{}
}
func(k *KeyStoreService)CreateKey() (string,error) {
uu, err := uuid.NewUUID();
if err != nil {
return "", err
}
return uu.String(), nil
}

View File

@ -0,0 +1 @@
package keystore

View File

@ -0,0 +1,178 @@
package member
import (
"encoding/json"
"git.loafle.net/overflow/overflow_proxy_service/proxy"
"log"
"git.loafle.net/overflow/overflow_proxy_service/proxy/apikey"
"git.loafle.net/overflow/overflow_proxy_service/proxy/keystore"
"git.loafle.net/overflow/encryption_go"
"errors"
)
type Member struct {
Id json.Number `json:"id,Number,omitempty"`
Email string `json:"email"`
PwSalt string `json:"pwSalt"`
Digest string `json:"digest"`
Name string `json:"name"`
Company string `json:"company"`
Phone string `json:"phone"`
AuthorizedDate json.Number `json:"authorizedDate,Number"`
}
type MemberService struct {
}
var TARGET_DAO = "member"
func NewMember() *Member {
return &Member{}
}
func NewMemberService() *MemberService {
return &MemberService{}
}
func (m *MemberService) getMemberMap(mem *Member) map[string]string {
memMap := make(map[string]string)
str, err := json.Marshal(mem)
if err != nil {
log.Fatal("Json Marshal Error: ", err)
}
memMap["com.loafle.overflow.member.model.Member"] = string(str)
return memMap
}
func (m *MemberService) Login(mem *Member) (string,error) {
result,err := m.ReadByEmail(mem)
if err != nil {
return "", err
}
if result == "" {
return "", errors.New("login reject")
}
temp := Member{}
err = json.Unmarshal([]byte(result), &temp)
if err != nil {
return "", err
}
if temp.AuthorizedDate == "" {
return "", errors.New("Not authenticated.")
}
b := encryption.Check(mem.PwSalt, temp.PwSalt, temp.Digest)
if !b {
return "", errors.New("login reject")
}
return "login success", nil
}
func (m *MemberService) Regist(mem *Member) (string, error ){
log.Println("Call Regist", mem.Email, mem.PwSalt)
pwSalt, digest, err := encryption.Encrypt(mem.PwSalt)
if err != nil {
//log.Fatal("encryption Encrypt Error: ", err)
return "", err
}
mem.PwSalt = pwSalt
mem.Digest = digest
memMap := m.getMemberMap(mem)
re, err := proxy.InvokeDB(TARGET_DAO, "create", memMap)
if err != nil {
return "", err
}
return re, nil
}
func (m *MemberService) ReadByEmail(mem *Member) (string, error){
log.Println("Call ReadByEmail", mem.Email)
memMap := m.getMemberMap(mem)
re, err := proxy.InvokeDB(TARGET_DAO, "findByEmail", memMap)
if err != nil {
return "", err
}
return re, nil
}
func (m *MemberService) Read(mem *Member) (string, error) {
log.Println("Call Read", mem.Email)
// Todo Call DB Gateway
mem.Digest = "qwer5795"
//memMap := m.getMemberMap()
mm := make(map[string]string)
mm["id"] = string(mem.Id)
log.Println("Read Member", m)
re, err := proxy.InvokeDB(TARGET_DAO, "find", mm)
if err != nil {
return "", err
}
return re, err
}
func (m *MemberService) Modify(mem *Member) (string, error) {
log.Println("Call Modify", mem.Email, "::", mem.PwSalt)
// Todo Call DB Gateway
mem.Digest = "read"
memMap := m.getMemberMap(mem)
re, err := proxy.InvokeDB(TARGET_DAO, "update", memMap)
if err != nil {
return "", err
}
return re, nil
}
func (m *MemberService) Remove(mem *Member) (string, error) {
log.Println("Call Remove", mem.Email)
// Todo Call DB Gateway
//m.Digest = "read"
memMap := m.getMemberMap(mem)
re, err := proxy.InvokeDB(TARGET_DAO, "delete", memMap)
if err != nil {
return "", err
}
return re, nil
}
func (m *MemberService) EmailConfirm() (string, error) {
ks := keystore.NewKeyStoreSerivce()
key, err := ks.CreateKey()
if err != nil {
return "", err
}
log.Println(key)
ak := apikey.NewApiKeyService()
_, err = ak.SaveApikey(nil)
if err != nil {
return "", err
}
//log.Println(out)
return "", nil
}

View File

@ -0,0 +1,108 @@
package member
import (
"testing"
"encoding/json"
"github.com/golang/glog"
"fmt"
"log"
"git.loafle.net/overflow/overflow_proxy_service/proxy"
)
func TestMemberService_Login(t *testing.T) {
}
func TestMemberService_Regist(t *testing.T) {
//m := &MemberService{
// Param: &Member{
// Email:"geek2@loafle.com",
// PwSalt:"qwer5795",
// Company:"Loafle",
// Name:"Geek",
// Phone:"010-4055-6699",
// },
//}
ms := NewMemberService()
m := &Member{
Email:"geek2@loafle.com",
PwSalt:"qwer5795",
Company:"Loafle",
Name:"Geek",
Phone:"010-4055-6699",
}
retMem, _ := ms.Regist(m)
t.Log(retMem)
}
func TestMemberLogin(t *testing.T) {
//m := &MemberService{
// Param:&Member{
// Email:"geek@loafle.com",
// PwSalt:"qwer5795",
// },
//}
ms := NewMemberService()
m := &Member{
Email:"geek@loafle.com",
PwSalt:"qwer5795",
}
b, _ := ms.Login(m)
t.Log("LOGIN RESULT : ", b)
}
func TestMemberService_Read(t *testing.T) {
mm := make(map[string] string)
mm["id"] = "12"
rr, _ := proxy.InvokeDB(TARGET_DAO, "find", mm)
log.Println(rr)
}
func TestMemberService_ReadByEmail(t *testing.T) {
ms := NewMemberService()
m := &Member{
Email:"geek@loafle.com",
}
mm := ms.getMemberMap(m)
rr, _ := proxy.InvokeDB(TARGET_DAO, "findByEmail", mm)
log.Println(rr)
}
func TestMemberUpdate(t *testing.T) {
ms := NewMemberService()
m := &Member{
Id: "11",
Email:"keeg@loafle.com",
}
mm := ms.getMemberMap(m)
rr, _ := proxy.InvokeDB(TARGET_DAO, "update", mm)
log.Println(rr)
}
func TestComvertJson(t *testing.T) {
m := make(map[string]string)
m["email"] = "geek@loafle.com"
m["pwSalt"] = "qwer5795"
ss := NewMemberService()
paramStr, err := json.Marshal(m)
if err != nil {
glog.Fatal("Json Marshal Failed : ", err.Error())
}
fmt.Println(paramStr)
fmt.Println(ss)
// service converting
//mem, _ := ss.GetModel()
//err = json.Unmarshal(paramStr, mem)
//if err != nil {
// glog.Fatal("Json Unmarshal Failed : ", err.Error())
//}
//fmt.Println(mem.(*Member).Email)
}

View File

@ -0,0 +1,160 @@
package noauthagent
import (
"git.loafle.net/overflow/commons_go/model/timestamp"
"git.loafle.net/overflow/overflow_proxy_service/proxy"
"encoding/json"
"git.loafle.net/overflow/overflow_proxy_service/proxy/member"
"git.loafle.net/overflow/overflow_proxy_service/proxy/agent"
"errors"
)
type NoAuthAgentService struct {
}
func NewNoAuthAgentService() *NoAuthAgentService {
return &NoAuthAgentService{}
}
type NoAuthAgent struct {
Id json.Number `json:"id,Number,omitempty"`
TempKey string `json:"tempKey,omitempty"`
Date timestamp.Timestamp`json:"date,omitempty"`
ApiKey string `json:"apiKey,omitempty"`
AuthStatus string `json:"authStatus,omitempty"`
LocalIP int64 `json:"localIP,omitempty"`
HostName string `json:"hostName,omitempty"`
}
func NewNoAuthAgent(apikey string, localIp int64, hostName string) *NoAuthAgent {
na := &NoAuthAgent{
Date:timestamp.Now(),
ApiKey:apikey,
LocalIP:localIp,
HostName:hostName,
}
return na
}
func(as *NoAuthAgentService)SaveNoAuthAgent(na *NoAuthAgent) (string, error) {
bytes, err := json.Marshal(na)
if err != nil {
return "",err
}
memMap := make(map[string]string)
memMap["com.loafle.overflow.noauthagent.model.NoAuthAgent"] = string(bytes);
out, err := proxy.InvokeDB("noauthAgent", "create", memMap);
if err != nil {
return "", err
}
return out, nil;
}
func(as *NoAuthAgentService)CheckAuth(tempKey string) (string,error) {
memMap := make(map[string]string)
na := NewNoAuthAgent("", 0, "")
na.TempKey = tempKey
bytes, err := json.Marshal(na)
if err != nil {
return "", err;
}
memMap["com.loafle.overflow.noauthagent.model.NoAuthAgent"] = string(bytes);
out, err := proxy.InvokeDB("noauthAgent", "findByTempKey", memMap);
if err != nil {
return "", err
}
nn := NoAuthAgent{}
err = json.Unmarshal([]byte(out), &nn)
if err != nil {
return "", err
}
return out,nil;
}
func(as *NoAuthAgentService)GetNoAuthList(excludeStatus string) (string,error) {
memMap := make(map[string]string)
na := NewNoAuthAgent("", 0, "")
na.AuthStatus = excludeStatus
bytes, err := json.Marshal(na)
if err != nil {
return "", err;
}
memMap["com.loafle.overflow.noauthagent.model.NoAuthAgent"] = string(bytes);
out, err := proxy.InvokeDB("noauthAgent", "findAllByNoAuth", memMap);
if err != nil {
return "", err
}
return out,nil;
}
func (as *NoAuthAgentService)RequestAuth(noauthAgt NoAuthAgent, memberId, desc string) (string, error) {
paramMap := make(map[string]string)
noauthAgt.AuthStatus = "ACCEPT"
bytes, err := json.Marshal(noauthAgt)
if err != nil {
return "", err;
}
paramMap["com.loafle.overflow.noauthagent.model.NoAuthAgent"] = string(bytes)
out, err := proxy.InvokeDB("noauthAgent", "update", paramMap)
if err != nil {
return "", err
}
if len(out) == 0 {
return "", errors.New("Cannot update Agent. ")
}
m := member.Member{}
m.Id = json.Number(memberId)
newAgent := agent.NewAgent(desc, m)
newone, err := agent.NewAgentService().SaveAgent(newAgent)
if err!= nil {
return "", err
}
return newone, nil
}
func (as *NoAuthAgentService)ReadNoAuthAgent(id string) (string, error){
mm := make(map[string]string)
mm["id"] = id
out, err := proxy.InvokeDB("noauthAgent", "find", mm)
if err != nil {
return "", err
}
return out, nil
}

View File

@ -0,0 +1,105 @@
package noauthagent
import (
"github.com/google/uuid"
"testing"
"encoding/json"
)
func TestCreateUUid(t *testing.T) {
uu, err := uuid.NewUUID()
if err != nil {
t.Fatal(err)
}
t.Log(uu)
}
func TestCreateNoAuthAgent(t *testing.T) {
na := NewNoAuthAgent("233421390283", 111, "Snoop")
na.TempKey = "1111111"
na.AuthStatus = "WAIT"
nas := NewNoAuthAgentService()
out, err := nas.SaveNoAuthAgent(na)
if err != nil {
t.Fatal(err)
}
t.Log(out)
}
func TestCheckAuthNoAuthAgent(t *testing.T) {
na := NewNoAuthAgent("2334278390283", 111, "Snoop")
na.TempKey = "alsdkjf;alkdjsf;la"
na.AuthStatus = "WAIT"
nas := NewNoAuthAgentService()
out, err := nas.CheckAuth(na.TempKey)
if err != nil {
t.Fatal(err)
}
t.Log(out)
//
}
func TestNoAuthList(t *testing.T) {
nas := NewNoAuthAgentService()
out, err := nas.GetNoAuthList("ACCEPT")
if err != nil {
t.Fatal(err)
}
t.Log(out)
}
func TestRequestAuth(t *testing.T) {
nas := NewNoAuthAgentService()
res, err := nas.ReadNoAuthAgent("1")
na := NoAuthAgent{}
json.Unmarshal([]byte(res), na)
newone, err := nas.RequestAuth(na, "1", "test")
if err!= nil {
t.Fatal(err)
}
t.Log(newone)
}
func TestCheckAuth(t *testing.T) {
ns := NewNoAuthAgentService()
str, err := ns.CheckAuth("3398473-90847903874")
if err != nil {
t.Fatal(err)
}
t.Log(str)
}

45
proxy/sensor/sensor.go Normal file
View File

@ -0,0 +1,45 @@
package sensor
import (
"encoding/json"
"git.loafle.net/overflow/commons_go/model/timestamp"
"git.loafle.net/overflow/overflow_proxy_service/proxy/target"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
"git.loafle.net/overflow/overflow_proxy_service/proxy/crawler"
)
type Sensor struct {
Id json.Number `json:"id,Number,omitempty"`
Target target.Target `json:"target,omitempty"`
Notification string `json:"notification,omitempty"`
Crawler crawler.Crawler `json:"crawler,omitempty"`
CreateDate timestamp.Timestamp `json:"createDate,omitempty"`
}
type SensorService struct {
}
func NewSensorService() *SensorService {
return &SensorService{}
}
func (ss *SensorService) Create(s *Sensor) (string, error) {
out, err := utils.InvokeDB("sensor", "create", s)
if err != nil {
return "", err
}
return out, nil
}
func (ss *SensorService) List(t *target.Target) (string, error) {
out, err := utils.InvokeDBByModel("sensor", "findAllByTargetId", t, "com.loafle.overflow.target.model.Target")
if err != nil {
return "", err
}
return out, nil
}

View File

@ -0,0 +1,18 @@
package sensor
import (
"encoding/json"
"git.loafle.net/overflow/overflow_proxy_service/proxy/target"
"testing"
)
func TestSensorService_List(t *testing.T) {
ts := &target.Target{}
ts.Id = json.Number("1")
ss := NewSensorService()
res, _ := ss.List(ts)
t.Log(res)
}

View File

@ -0,0 +1,47 @@
package sensorItem
import (
"encoding/json"
"git.loafle.net/overflow/commons_go/model/timestamp"
"git.loafle.net/overflow/overflow_proxy_service/proxy/crawler"
"git.loafle.net/overflow/overflow_proxy_service/proxy/sensorItemCategory"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
)
type SensorItem struct {
Id json.Number `json:"id,Number,omitempty"`
Crawler crawler.Crawler `json:"crawler,omitempty"`
SensorItemCategory sensorItemCategory.SensorItemCategory `json:"sensorItemCategory,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
DataType string `json:"dataType,omitempty"`
CreateDate timestamp.Timestamp `json:"createDate,omitempty"`
}
type SensorItemService struct {
}
func NewSensorItemService() *SensorItemService {
return &SensorItemService{}
}
func (sis *SensorItemService) Create(si *SensorItem) (string, error) {
out, err := utils.InvokeDBByModel("sensorItem", "create", si, "com.loafle.overflow.sensor.model.SensorItem")
if err != nil {
return "", err
}
return out, nil
}
func (ss *SensorItemService) List(cr *crawler.Crawler) (string, error) {
out, err := utils.InvokeDBByModel("sensorItem", "findAllByCrawlerId", cr, "com.loafle.overflow.crawler.model.Crawler")
if err != nil {
return "", err
}
return out, nil
}

View File

@ -0,0 +1,18 @@
package sensorItem
import (
"encoding/json"
"git.loafle.net/overflow/overflow_proxy_service/proxy/crawler"
"testing"
)
func TestSensorItemService_List(t *testing.T) {
cr := &crawler.Crawler{}
cr.Id = json.Number("1")
sis := NewSensorItemService()
res, _ := sis.List(cr)
t.Log(res)
}

View File

@ -0,0 +1,30 @@
package sensorItemCategory
import (
"encoding/json"
"git.loafle.net/overflow/commons_go/model/timestamp"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
)
type SensorItemCategory struct {
Id json.Number `json:"id,Number,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
CreateDate timestamp.Timestamp `json:"createDate,omitempty"`
}
type SensorItemCategoryService struct {
}
func NewSensorItemCategoryService() *SensorItemCategoryService {
return &SensorItemCategoryService{}
}
func (sics *SensorItemCategoryService) Create(sic *SensorItemCategory) (string, error) {
out, err := utils.InvokeDBByModel("sensorItemCategory", "create", sic, "com.loafle.overflow.sensor.model.SensorItemCategory")
if err != nil {
return "", err
}
return out, nil
}

View File

@ -0,0 +1 @@
package sensorItemCategory

View File

@ -0,0 +1,65 @@
package sensorItemMapping
import (
"encoding/json"
"git.loafle.net/overflow/commons_go/model/timestamp"
"git.loafle.net/overflow/overflow_proxy_service/proxy/sensor"
"git.loafle.net/overflow/overflow_proxy_service/proxy/sensorItem"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
)
type SensorItemMapping struct {
Id json.Number `json:"id,Number,omitempty"`
Sensor sensor.Sensor `json:"sensor,omitempty"`
SensorItem sensorItem.SensorItem `json:"sensorItem,omitempty"`
CreateDate timestamp.Timestamp `json:"createDate,omitempty"`
}
type SensorItemMappingService struct {
}
func NewSensorItemMappingService() *SensorItemMappingService {
return &SensorItemMappingService{}
}
func (sims *SensorItemMappingService) Create(sim *SensorItemMapping) (string, error) {
out, err := utils.InvokeDBByModel("sensorItemMapping", "create", sim, "com.loafle.overflow.sensor.model.SensorItemMapping")
if err != nil {
return "", err
}
return out, nil
}
func (sims *SensorItemMappingService) CreateAll(siml *[]*SensorItemMapping) (string, error) {
outlist := make([]string, 0)
for _, sim := range *siml {
out,err := sims.Create(sim)
if err != nil {
return "", err
}
outlist = append(outlist, out)
}
bytes,err := json.Marshal(outlist)
if err != nil {
return "", err
}
return string(bytes), nil
}
func (ss *SensorItemMappingService) List(s *sensor.Sensor) (string, error) {
out, err := utils.InvokeDBByModel("sensorItemMapping", "findAllBySensorId", s, "com.loafle.overflow.sensor.model.Sensor")
if err != nil {
return "", err
}
return out, nil
}

View File

@ -0,0 +1,60 @@
package sensorItemMapping
import (
"encoding/json"
"git.loafle.net/overflow/overflow_proxy_service/proxy/sensor"
"testing"
"fmt"
"sync"
"strconv"
)
func TestSensorItemMappingService_List(t *testing.T) {
s := &sensor.Sensor{}
s.Id = json.Number("1")
sims := NewSensorItemMappingService()
res, _ := sims.List(s)
t.Log(res)
}
func TestSensorItemMappingService_List_GoRutine(t *testing.T) {
//s := &sensor.Sensor{}
//s.Id = json.Number("14")
sims := NewSensorItemMappingService()
il := make([]int, 0)
il = append(il, 1)
il = append(il, 2)
il = append(il, 3)
il = append(il, 13)
il = append(il, 14)
for _, ii := range il {
go func(i int) {
s := &sensor.Sensor{}
s.Id = json.Number(strconv.Itoa(ii))
res, _ := sims.List(s)
fmt.Print(res)
}(ii)
}
wg := sync.WaitGroup{}
wg.Add(1)
wg.Wait()
//res, _ := sims.List(s)
//
//t.Log(res)
}

37
proxy/service.go Normal file
View File

@ -0,0 +1,37 @@
package proxy
import (
"log"
pb "git.loafle.net/overflow/overflow_api_db/build/golang"
"google.golang.org/grpc"
"golang.org/x/net/context"
)
func InvokeDB(targetDb, methodName string, param map[string]string) (string, error) {
in := &pb.DBInput{}
in.TargetDao = targetDb
in.Method = methodName
in.Param = param
conn, err := grpc.Dial(":50006", grpc.WithInsecure())
if err != nil {
//log.Fatal("Rpc Error: ", err)
return "", err
}
defer conn.Close()
client := pb.NewDBClient(conn)
out, err := client.Exec(context.Background(), in)
if err != nil {
//log.Fatal("Rpc Client Error: ", err)
return "", err
}
log.Print(out)
return out.Result, nil
}

12
proxy/session/session.go Normal file
View File

@ -0,0 +1,12 @@
package session
import "git.loafle.net/overflow/overflow_proxy_service/proxy/member"
//FIXME:: test session member
func GetSessionMember() *member.Member {
m := member.NewMember()
m.Id = "1";
return m;
}

View File

@ -0,0 +1,134 @@
package target
import (
"encoding/json"
"git.loafle.net/overflow/commons_go/model/timestamp"
"git.loafle.net/overflow/overflow_proxy_service/proxy/member"
"git.loafle.net/overflow/overflow_proxy_service/proxy"
"fmt"
"git.loafle.net/overflow/overflow_proxy_service/proxy/utils"
"git.loafle.net/overflow/overflow_proxy_service/proxy/session"
)
type Target struct {
Id json.Number `json:"id,Number,omitempty"`
Ip int64 `json:"ip,omitempty"`
Port int `json:"port,omitempty"`
TargetType string `json:"targetType,omitempty"`
VendorName string `json:"vendorName,omitempty"`
Kinds string `json:"kinds,omitempty"`
Version string `json:"version,omitempty"`
CreateDate timestamp.Timestamp `json:"createDate,omitempty"`
PortType string `json:"portType,omitempty"`
Member *member.Member `json:"member,omitempty"`
}
type TargetService struct {
}
func NewTargetService() *TargetService {
return &TargetService{}
}
func (t *TargetService)GetModel() interface{} {
return &Target{}
}
func (t *TargetService)List(tm *Target) (string, error) {
tm.Member.Id = session.GetSessionMember().Id
bytes, err := json.Marshal(tm)
if err != nil {
return "", err
}
m := make(map[string]string)
m["com.loafle.overflow.target.model.Target"] = string(bytes)
out, err := proxy.InvokeDB("target", "findAll", m)
if err != nil {
return "", err
}
return out, err;
}
func (t *TargetService)Create(tm *Target) (string,error) {
//bytes, err := json.Marshal(tm)
//
//if err != nil {
// return ""
//}
//
//m := make(map[string]string)
//m["com.loafle.overflow.target.model.Target"] = string(bytes)
//
//out := proxy.InvokeDB("target", "create", m)
out, err := utils.InvokeDB("target", "create", tm)
if err != nil {
return "", err
}
return out, nil
}
func (t *TargetService)CreateAll(tmlist *[]*Target) (string,error) {
outlist := make([]string, 0)
for _, ttt := range *tmlist {
ttt.Member = session.GetSessionMember()
out,err := t.Create(ttt)
if err != nil {
return "", err
}
outlist = append(outlist, out)
}
bytes,err := json.Marshal(outlist)
if err != nil {
return "", err
}
return string(bytes), nil
}
func (t *TargetService)CreateListTT(tmlist *[]*Target) (string, error) {
bytes, err := json.Marshal(tmlist)
if err != nil {
return "",err
}
m := make(map[string]string)
m["java.util.List"] = string(bytes)
fmt.Println(string(bytes))
out, err := proxy.InvokeDB("target", "createAll", m)
if err != nil {
return "", err
}
//
//
return out, nil;
//return ""
}

View File

@ -0,0 +1,114 @@
package target
import (
"testing"
//"git.loafle.net/overflow/overflow_proxy_service/proxy/member"
"git.loafle.net/overflow/overflow_proxy_service/proxy/member"
)
func TestCreateTarget(t *testing.T) {
tt := Target{
Ip:3232235882,
Port:5432,
TargetType:"DATABASE",
Kinds:"PostgreSQL0000000",
Version:"9.5.0",
VendorName:"PostgreSQL 9.5.0",
PortType:"TCP",
Member:&member.Member{Id:"1"},
}
ts := NewTargetService()
ts.Create(&tt)
}
func TestFindAll(t *testing.T) {
tt := Target{
Member:&member.Member{Id:"1"},
}
ts := NewTargetService()
str := ts.List(&tt)
t.Log(str)
}
func TestCreateAll(t *testing.T) {
tl := make([]*Target, 0)
tl = append(tl, &Target{
Ip:3232235882,
Port:5432,
TargetType:"DATABASE",
Kinds:"PostgreSQL2222",
Version:"9.5.0",
VendorName:"PostgreSQL 9.5.0",
PortType:"TCP",
Member:&member.Member{Id:"1"},
})
tl = append(tl, &Target{
Ip:3232235882,
Port:5432,
TargetType:"DATABASE",
Kinds:"PostgreSQL3333",
Version:"9.5.0",
VendorName:"PostgreSQL 9.5.0",
PortType:"TCP",
Member:&member.Member{Id:"1"},
})
tl = append(tl, &Target{
Ip:3232235882,
Port:5432,
TargetType:"DATABASE",
Kinds:"PostgreSQL4444",
Version:"9.5.0",
VendorName:"PostgreSQL 9.5.0",
PortType:"TCP",
Member:&member.Member{Id:"1"},
})
tl = append(tl, &Target{
Ip:3232235882,
Port:5432,
TargetType:"DATABASE",
Kinds:"PostgreSQL5555",
Version:"9.5.0",
VendorName:"PostgreSQL 9.5.0",
PortType:"TCP",
Member:&member.Member{Id:"1"},
})
tl = append(tl, &Target{
Ip:3232235882,
Port:5432,
TargetType:"DATABASE",
Kinds:"PostgreSQL6666",
Version:"9.5.0",
VendorName:"PostgreSQL 9.5.0",
PortType:"TCP",
Member:&member.Member{Id:"1"},
})
ts := NewTargetService()
ts.CreateListTT(&tl)
}

View File

@ -0,0 +1,44 @@
package utils
import (
"encoding/json"
"git.loafle.net/overflow/overflow_proxy_service/proxy"
)
func InvokeDB( db string, method string, obj interface{}) (string, error) {
var m map[string]string = nil;
if obj != nil {
bytes, err := json.Marshal(obj)
if err != nil {
return "", err
}
m = make(map[string]string)
m[GenerateModelStr(db)] = string(bytes)
}
out, err := proxy.InvokeDB(db, method, m)
return out, err
}
func InvokeDBByModel( db string, method string, obj interface{}, model string) (string, error) {
bytes, err := json.Marshal(obj)
if err != nil {
return "", err
}
m := make(map[string]string)
m[model] = string(bytes)
out, err := proxy.InvokeDB(db, method, m)
return out, err
}

21
proxy/utils/string.go Normal file
View File

@ -0,0 +1,21 @@
package utils
import "strings"
const (
defaultPackage = "com.loafle.overflow."
modelPackageName = ".model."
)
func GenerateModelStr(model string) string {
tm := strings.Title(model)
res := defaultPackage
res += model
res += modelPackageName
res += tm
return res
}

View File

@ -0,0 +1,38 @@
package utils
import (
"testing"
"strings"
)
func TestStringUpper(t *testing.T) {
res := "crawlerInputItem"
aa := strings.Title(res)
t.Log(aa)
}
func TestGM(t *testing.T) {
t.Log(GenerateModelStr("target"))
}
func TestNil(t *testing.T) {
var oo interface{}
oo = nil;
if oo == nil {
t.Log("nil!!!")
}
}

20
rpc_main.go Normal file
View File

@ -0,0 +1,20 @@
package main
import (
"git.loafle.net/overflow/overflow_gateway_service/gateway"
"flag"
"github.com/golang/glog"
"git.loafle.net/overflow/overflow_gateway_service/server"
)
func main() {
flag.Parse()
defer glog.Flush()
gateway.InitServices()
if err := server.RunRpc(); err != nil {
glog.Fatal("Gateway Server Failed: ", err)
}
}

58
server/gwrpc.go Normal file
View File

@ -0,0 +1,58 @@
package server
import (
"flag"
"golang.org/x/net/context"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc"
pb "git.loafle.net/overflow/overflow_api_service/grpc"
"net/http"
"strings"
"github.com/golang/glog"
)
var (
overflowEndpoint = flag.String("echo_endpoint", ":9090", "/v1/overflow/services")
)
func RunGwRpc() (err error) {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
err = pb.RegisterOverflowGatewayHandlerFromEndpoint(ctx, mux, *overflowEndpoint, opts)
if err != nil {
return err
}
return http.ListenAndServe(":8080", allowCORS(mux))
}
//https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/main.go
func allowCORS(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
preflightHandler(w, r)
return
}
}
h.ServeHTTP(w, r)
})
}
func preflightHandler(w http.ResponseWriter, r *http.Request) {
headers := []string{"Content-Type", "Accept"}
w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ","))
methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"}
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
glog.Infof("preflight request for %s", r.URL.Path)
return
}

23
server/rpc.go Normal file
View File

@ -0,0 +1,23 @@
package server
import (
"net"
"google.golang.org/grpc"
pb "git.loafle.net/overflow/overflow_api_service/grpc"
"git.loafle.net/overflow/overflow_gateway_service/gateway"
)
func RunRpc() error {
l, err := net.Listen("tcp", ":9090")
if err != nil {
return err
}
s := grpc.NewServer()
pb.RegisterOverflowGatewayServer(s, &gateway.ServiceImpl{})
s.Serve(l)
return nil
}

119
server/rpc_test.go Normal file
View File

@ -0,0 +1,119 @@
package server
import (
"testing"
"git.loafle.net/overflow/overflow_gateway_service/gateway"
"flag"
"github.com/golang/glog"
"time"
"fmt"
"os"
"net/http"
"bytes"
"io/ioutil"
"log"
"google.golang.org/grpc"
pb "git.loafle.net/overflow/overflow_api_service/grpc"
"golang.org/x/net/context"
)
func startRpcServerTest() <- chan error{
ch := make(chan error, 2)
go func() {
if err := RunRpc(); err != nil {
ch <- fmt.Errorf("cannot run grpc service: %v", err)
}
}()
go func() {
if err := RunGwRpc(); err != nil {
ch <- fmt.Errorf("cannot run gateway service: %v", err)
}
}()
return ch
}
func callGatewayRpc() string {
time.Sleep(2 * time.Second)
url := "http://localhost:8080/v1/overflow/services"
glog.Infoln("URL : ", url)
var jsonStr = []byte(`{"serviceName":"Member","methodName":"Regist","param":{"email":"geek@loafle.com","password":"qwer5795"}}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
if err != nil {
glog.Error(err)
}
req.Header.Set("X-Custom-Header", "myvalue")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
glog.Error(err)
}
defer resp.Body.Close()
log.Println("response Status:", resp.Status)
log.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
log.Println("response Body:", string(body))
return string(body)
}
func TestRpcServer(t *testing.T) {
flag.Parse()
defer glog.Flush()
gateway.InitServices()
errch := startRpcServerTest()
chStr := make(chan string , 1)
go func() {
chStr <- callGatewayRpc()
}()
select {
case err := <- errch:
log.Println(err)
os.Exit(1)
case status := <-chStr:
log.Println( status)
os.Exit(1)
}
}
func TestRPC(t *testing.T) {
conn, err := grpc.Dial(":9090", grpc.WithInsecure());
if err != nil {
t.Log(err)
}
client := pb.NewOverflowGatewayClient(conn)
si := pb.ServiceInput{}
si.MethodName = "create"
si.ServiceName = "member"
si.Param = make(map[string]string)
si.Param["1"] = "2222"
so, err := client.ExecServices(context.Background(), &si)
t.Log(so.ResultStr)
}