Ejemplo n.º 1
0
func (c *ValueEquationController) Initiate(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputJson
	var e error
	csr, e := c.Ctx.Find(new(PlantModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	defer csr.Close()
	PlantList := make([]PlantModel, 0)
	e = csr.Fetch(&PlantList, 0, false)
	if e != nil {
		return e.Error()
	}
	csr, e = c.Ctx.Find(new(PhaseModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	PhaseList := make([]PhaseModel, 0)
	e = csr.Fetch(&PhaseList, 0, false)
	if e != nil {
		return e.Error()
	}
	csr, e = c.Ctx.Find(new(UnitModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	UnitList := make([]UnitModel, 0)
	e = csr.Fetch(&UnitList, 0, false)
	if e != nil {
		return e.Error()
	}
	result := tk.M{}
	result.Set("PlantList", PlantList)
	result.Set("PhaseList", PhaseList)
	result.Set("UnitList", UnitList)
	return ResultInfo(result, e)
}
Ejemplo n.º 2
0
func (g *GetDatabase) ResultFromDatabase(dataSettingId string, out interface{}) error {

	c, e := dbox.NewConnection(g.desttype, &g.ConnectionInfo)
	if e != nil {
		return e
	}

	e = c.Connect()
	if e != nil {
		return e
	}

	defer c.Close()

	iQ := c.NewQuery()
	if g.CollectionSettings[dataSettingId].Collection != "" {
		iQ.From(g.CollectionSettings[dataSettingId].Collection)
	}

	for _, val := range g.CollectionSettings[dataSettingId].MapsColumns {
		iQ.Select(val.Source)
	}

	if len(g.CollectionSettings[dataSettingId].FilterCond) > 0 {
		iQ.Where(g.CollectionSettings[dataSettingId].filterDbox)
	}

	csr, e := iQ.Cursor(nil)

	if e != nil {
		return e
	}
	if csr == nil {
		return e
	}
	defer csr.Close()

	results := make([]toolkit.M, 0)
	e = csr.Fetch(&results, 0, false)
	if e != nil {
		return e
	}

	ms := []toolkit.M{}
	for _, val := range results {
		m := toolkit.M{}
		for _, column := range g.CollectionSettings[dataSettingId].MapsColumns {
			m.Set(column.Source, "")
			if val.Has(column.Destination) {
				m.Set(column.Source, val[column.Destination])
			}
		}
		ms = append(ms, m)
	}

	if edecode := toolkit.Unjson(toolkit.Jsonify(ms), out); edecode != nil {
		return edecode
	}
	return nil
}
Ejemplo n.º 3
0
func (a *GroupController) FindUserLdap(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson
	payload := map[string]interface{}{}
	err := r.GetPayload(&payload)
	if err != nil {
		return helper.CreateResult(false, nil, err.Error())
	}

	addr := payload["Address"].(string)
	basedn := payload["BaseDN"].(string)
	filter := payload["Filter"].(string)
	username := payload["Username"].(string)
	password := payload["Password"].(string)
	var attr []string

	err = toolkit.Serde(payload["Attribute"], &attr, "json")
	if err != nil {
		return helper.CreateResult(false, err, "error")
	}

	param := toolkit.M{}

	param.Set("username", username)
	param.Set("password", password)
	param.Set("attributes", attr)

	arrm, err := acl.FindDataLdap(addr, basedn, filter, param)
	if err != nil {
		return helper.CreateResult(false, err, "error")
	}

	return helper.CreateResult(true, arrm, "success")
}
Ejemplo n.º 4
0
func Finds(o orm.IModel, param toolkit.M) (dbox.ICursor, error) {
	var filters []*dbox.Filter

	params := toolkit.M{}
	params.Set("where", filters)

	if qe := param.Get("order", nil); qe != nil {
		params.Set("order", qe.([]string))
	}
	if qe := param.Get("skip", nil); qe != nil {
		params.Set("skip", qe.(int))
	}
	if qe := param.Get("take", nil); qe != nil {
		params.Set("limit", qe.(int))
	}
	if qe := param.Get("where", nil); qe != nil {
		filters = append(filters, qe.(*dbox.Filter))
		params.Set("where", filters)
	}

	c, e := ctx().Find(o, params)
	if e != nil {
		return nil, errors.New("Core.Find: " + e.Error())
	}
	return c, nil
}
Ejemplo n.º 5
0
func (c *Cursor) Fetch(result interface{}) (bool, error) {
	if !c.rows.Next() {
		return false, nil
	}

	e := c.rows.Scan(c.rowMemory...)

	if e != nil {
		return false, createError("Fetch", e.Error())
	}

	rowData := toolkit.M{}

	for i, each := range c.rowDataRaw {
		value := "NULL"

		if each != nil {
			value = string(each)
		}

		rowData.Set(c.columns[i], value)
	}

	*(result.(*toolkit.M)) = rowData

	return true, nil
}
Ejemplo n.º 6
0
func (s *ScenarioSimulation) Initiate(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputJson
	//csr, e := s.DB().Find(new(PlantModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	csr, e := s.DB().Connection.NewQuery().Select("Plant").From("MasterPlant").Cursor(nil)
	PlantList := make([]PlantModel, 0)
	e = csr.Fetch(&PlantList, 0, true)
	if e != nil {
		return e.Error()
	}

	//csr, e = s.DB().Find(new(UnitModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	csr, e = s.DB().Connection.NewQuery().Select("Unit").From("MasterUnit").Cursor(nil)
	UnitList := make([]UnitModel, 0)
	e = csr.Fetch(&UnitList, 0, true)
	if e != nil {
		return e.Error()
	}

	defer csr.Close()

	result := tk.M{}
	result.Set("PlantList", PlantList)
	result.Set("UnitList", UnitList)
	return ResultInfo(result, e)
}
Ejemplo n.º 7
0
func saverechistory(key string, dt toolkit.M) (err error) {
	err = nil
	fullfilename := filepath.Join(toolkit.ToString(histConf.Get("recpath", "")), mapRecHistory[key])
	if EC_DATA_PATH != "" {
		fullfilename = filepath.Join(EC_DATA_PATH, "datagrabber", "historyrec", mapRecHistory[key])
	}
	// fmt.Println(fullfilename, " - Key - ", key, " - filename - ", mapRecHistory)
	cconfig := toolkit.M{"newfile": true, "useheader": true, "delimiter": ","}
	conn, err := prepareconnection("csv", fullfilename, "", "", "", cconfig)
	if err != nil {
		return
	}

	q := conn.NewQuery().SetConfig("multiexec", true).Insert()
	for k, v := range dt {
		if toolkit.TypeName(v) == "toolkit.M" {
			dt.Set(k, fmt.Sprintf("%v", v))
		}
	}

	err = q.Exec(toolkit.M{}.Set("data", dt))
	conn.Close()

	return
}
Ejemplo n.º 8
0
func (p *PageController) LoadWidgetPageData(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson

	payload := []toolkit.M{}

	if err := r.GetPayload(&payload); err != nil {
		return helper.CreateResult(false, nil, err.Error())
	}

	result := toolkit.M{}

	for _, each := range payload {
		filter := each.GetString("filter")
		namespace := each.GetString("namespace")
		fields := strings.Split(each.Get("fields").(string), ",")
		dsID := each.GetString("value")

		opt := toolkit.M{"fields": fields, "value": filter}
		data, err := helper.FetchDataFromDSWithFilter(dsID, 0, opt)
		if err != nil {
			return helper.CreateResult(false, nil, err.Error())
		}

		result.Set(namespace, data)
	}

	return helper.CreateResult(true, result, "")
}
Ejemplo n.º 9
0
func (q *Query) generateIndex(filters []*dbox.Filter) (output []int, e error) {
	var n int = 0
	for {
		tdread, e := q.reader.Read()
		if e != nil && e != io.EOF {
			break
		}
		n++

		tm := toolkit.M{}

		for i, v := range tdread {
			tolower := strings.ToLower(q.headerColumn[i].name)
			tm.Set(tolower, v)
			if q.headerColumn[i].dataType == "int" {
				tm[tolower] = cast.ToInt(v, cast.RoundingAuto)
			} else if q.headerColumn[i].dataType == "float" {
				tm[tolower] = cast.ToF64(v, (len(v) - (strings.IndexAny(v, "."))), cast.RoundingAuto)
			}
		}

		match := dbox.MatchM(tm, filters)
		if (len(filters) == 0 || match) && len(tm) > 0 {
			output = append(output, n)
		}

		if e == io.EOF {
			break
		}
	}

	e = q.resetReader()
	return
}
Ejemplo n.º 10
0
func (a *UserController) TestFindUserLdap(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson
	payload := map[string]interface{}{}
	err := r.GetPayload(&payload)
	if err != nil {
		return helper.CreateResult(false, nil, err.Error())
	}

	addr := toolkit.ToString(payload["Address"])  //192.168.0.200:389
	basedn := toolkit.ToString(payload["BaseDN"]) //DC=eaciit,DC=local
	filter := toolkit.ToString(payload["Filter"]) //(&(objectclass=person)(objectclass=organizationalPerson)(cn=*))
	var attr []string

	err = toolkit.Serde(payload["Attribute"], &attr, "json")
	if err != nil {
		return helper.CreateResult(true, err, "error")
	}

	param := toolkit.M{}

	param.Set("username", toolkit.ToString(payload["Username"])) //Alip Sidik
	param.Set("password", toolkit.ToString(payload["Password"])) //Password.1
	// param.Set("attributes", []string{"cn", "givenName"})
	param.Set("attributes", attr)

	arrtkm, err := acl.FindDataLdap(addr, basedn, filter, param)
	if err != nil {
		return helper.CreateResult(true, err, "error")
	}
	return helper.CreateResult(true, arrtkm, "sukses")
}
Ejemplo n.º 11
0
func getresultobj(strsplits []string, tval interface{}, val toolkit.M) interface{} {
	var xval interface{}
	if val == nil {
		val = toolkit.M{}
	}

	switch {
	case len(strsplits) == 1:
		xval = tval
	case len(strsplits) > 1:
		tm := toolkit.M{}
		if val.Has(strsplits[1]) {
			tm, _ = toolkit.ToM(val[strsplits[1]])
		}
		xval = val.Set(strsplits[1], getresultobj(strsplits[1:], tval, tm))
	}

	return xval
	// if  {
	// 	val = tval
	// } else {
	// 	val = val.Set(k, v)
	// 	if val == nil {

	// 	} else {

	// 	}

	// 	val = getresultobj(strsplits[1:], tval)
	// }

	// return val
}
Ejemplo n.º 12
0
func (s *ScenarioSimulation) GetDataSimulation(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputJson

	result, status, msg := tk.M{}, "", ""

	simDataTmp := []tk.M{}
	filter := tk.M{}
	filter.Set("name", "GetAllScenarioSimulation")
	csr, err := s.DB().Connection.NewQuery().Command("procedure", filter).Cursor(nil)
	defer csr.Close()

	err = csr.Fetch(&simDataTmp, 0, true)

	if err != nil {
		msg = err.Error()
		status = "NOK"
	} else {
		status = "OK"
	}

	SimulationDatas := constructScenarionSimulation(simDataTmp)

	result.Set("Status", status)
	result.Set("Message", msg)
	result.Set("Data", SimulationDatas)

	return result
}
Ejemplo n.º 13
0
func decodeTSV(file []byte) (retVal interface{}, e error) {
	reader := csv.NewReader(strings.NewReader(string(file)))
	reader.Comma = '\t'
	records, e := reader.ReadAll()

	if e != nil {
		return
	}

	var list []interface{}

	for _, row := range records {
		line := toolkit.M{}
		for idx, val := range row {
			line.Set(toolkit.ToString(idx), val)
		}

		list = append(list, line)
	}

	if len(list) > 0 {
		retVal = list[0]
	}

	return
}
Ejemplo n.º 14
0
func (q *Query) execQueryPartUpdate(dt toolkit.M, Cond QueryCondition) error {

	if len(dt) == 0 {
		return errorlib.Error(packageName, "Query", modQuery, "data to update is not found")
	}

	writer := q.Connection().(*Connection).writer
	reader := q.Connection().(*Connection).reader
	tempHeader := []string{}

	for _, val := range q.Connection().(*Connection).headerColumn {
		tempHeader = append(tempHeader, val.name)
	}

	for {
		foundChange := false

		recData := toolkit.M{}
		dataTemp, e := reader.Read()
		for i, val := range dataTemp {
			recData.Set(tempHeader[i], val)
		}

		if len(Cond.Find) > 0 || (len(Cond.Find) == 0 && toolkit.IdField(dt) == "") {
			foundChange = Cond.getCondition(recData)
		}

		// Check ID IF Condition Not Found
		if nameid := toolkit.IdField(dt); nameid != "" && !foundChange {
			if recData.Has(nameid) && dt[nameid] == recData[nameid] {
				foundChange = true
			}
		}

		if foundChange && len(dataTemp) > 0 {
			for n, v := range tempHeader {
				if dt.Has(v) {
					dataTemp[n] = cast.ToString(dt[v])
				}
			}
		}

		if e == io.EOF {
			if dataTemp != nil {
				writer.Write(dataTemp)
				writer.Flush()
			}
			break
		} else if e != nil {
			return errorlib.Error(packageName, modQuery, "Update", e.Error())
		}
		if dataTemp != nil {
			writer.Write(dataTemp)
			writer.Flush()
		}
	}

	return nil
}
Ejemplo n.º 15
0
func foundCondition(dataCheck toolkit.M, cond toolkit.M) bool {
	resBool := true

	for key, val := range cond {
		if key == "$and" || key == "$or" {
			for i, sVal := range val.([]interface{}) {
				rVal := sVal.(map[string]interface{})
				mVal := toolkit.M{}
				for rKey, mapVal := range rVal {
					mVal.Set(rKey, mapVal)
				}

				xResBool := foundCondition(dataCheck, mVal)
				if key == "$and" {
					resBool = resBool && xResBool
				} else {
					if i == 0 {
						resBool = xResBool
					} else {
						resBool = resBool || xResBool
					}
				}
			}
		} else {
			if reflect.ValueOf(val).Kind() == reflect.Map {
				mVal := val.(map[string]interface{})
				tomVal, _ := toolkit.ToM(mVal)
				switch {
				case tomVal.Has("$ne"):
					if tomVal["$ne"].(string) == dataCheck.Get(key, "").(string) {
						resBool = false
					}
				case tomVal.Has("$regex"):
					resBool, _ = regexp.MatchString(tomVal["$regex"].(string), dataCheck.Get(key, "").(string))
				case tomVal.Has("$gt"):
					if tomVal["$gt"].(string) >= dataCheck.Get(key, "").(string) {
						resBool = false
					}
				case tomVal.Has("$gte"):
					if tomVal["$gte"].(string) > dataCheck.Get(key, "").(string) {
						resBool = false
					}
				case tomVal.Has("$lt"):
					if tomVal["$lt"].(string) <= dataCheck.Get(key, "").(string) {
						resBool = false
					}
				case tomVal.Has("$lte"):
					if tomVal["$lte"].(string) < dataCheck.Get(key, "").(string) {
						resBool = false
					}
				}
			} else if reflect.ValueOf(val).Kind() == reflect.String && val != dataCheck.Get(key, "").(string) {
				resBool = false
			}
		}
	}

	return resBool
}
Ejemplo n.º 16
0
func (a *ConfigurationController) Default(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputTemplate
	data := tk.M{}
	d, _ := os.Getwd()
	d = strings.Replace(strings.Replace(d, "\\cli", "", -1), "/cli", "", -1)
	data.Set("data_dir", d+tk.PathSeparator+filepath.Join("data", "Output")+tk.PathSeparator)
	data.Set("log_dir", d+tk.PathSeparator+filepath.Join("data", "Log")+tk.PathSeparator)
	return data
}
Ejemplo n.º 17
0
func (a *SessionController) GetSession(r *knot.WebContext) interface{} {
	var filter *dbox.Filter
	r.Config.OutputType = knot.OutputJson
	_ = a.InitialSetDatabase()

	payload := map[string]interface{}{}
	err := r.GetForms(&payload)
	if err != nil {
		return helper.CreateResult(false, nil, err.Error())
	}
	if strings.Contains(toolkit.TypeName(payload["find"]), "float") {
		payload["find"] = toolkit.ToInt(payload["find"], toolkit.RoundingAuto)
	}

	tSession := new(acl.Session)
	if find := toolkit.ToString(payload["find"]); find != "" {
		filter = new(dbox.Filter)
		filter = dbox.Contains("loginid", find)
	}
	take := toolkit.ToInt(payload["take"], toolkit.RoundingAuto)
	skip := toolkit.ToInt(payload["skip"], toolkit.RoundingAuto)

	// c, err := acl.Find(tAccess, filter, toolkit.M{}.Set("take", take).Set("skip", skip))
	// c, err := acl.Find(tSession, nil, toolkit.M{}.Set("take", payload["take"].(int)).Set("skip", payload["skip"].(int)))
	c, err := acl.Find(tSession, filter, toolkit.M{}.Set("take", take).Set("skip", skip))
	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	}

	data := toolkit.M{}
	arrm := make([]toolkit.M, 0, 0)
	err = c.Fetch(&arrm, 0, false)
	for i, val := range arrm {
		arrm[i].Set("duration", time.Since(val["created"].(time.Time)).Hours())
		arrm[i].Set("status", "ACTIVE")
		if val["expired"].(time.Time).Before(time.Now().UTC()) {
			arrm[i].Set("duration", val["expired"].(time.Time).Sub(val["created"].(time.Time)).Hours())
			arrm[i].Set("status", "EXPIRED")
		}
	}
	c.Close()

	c, err = acl.Find(tSession, filter, nil)

	data.Set("Datas", arrm)
	data.Set("total", c.Count())

	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	} else {
		return helper.CreateResult(true, data, "")
	}

}
Ejemplo n.º 18
0
func (c *DashboardController) GetData(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputJson

	d := struct {
		StartDate string
		EndDate   string
		Plant     []string
	}{}

	e := k.GetPayload(&d)

	type ReturnValue struct {
		PlantList         []PowerPlantCoordinates
		PlantCapacityList []tk.M
	}

	var (
		Result ReturnValue
	)

	filter := tk.M{}
	curr, e := c.DB().Find(&PowerPlantCoordinates{}, filter)

	if e != nil {
	}

	e = curr.Fetch(&Result.PlantList, 0, false)

	if e != nil {
		return e.Error()
	}

	defer curr.Close()

	//selectedPeriod := d.StartDate
	selectedPeriod := time.Now().Year() - 1

	cursor, _ := c.DB().Connection.NewQuery().
		Select("PlantCode as _id").
		From("ValueEquation_Dashboard").
		Where(dbox.Eq("Year", selectedPeriod)).
		Aggr(dbox.AggrSum, "InstalledCapacity", "TotalCapacity").
		Group("PlantCode").
		Cursor(nil)

	defer cursor.Close()
	e = cursor.Fetch(&Result.PlantCapacityList, 0, false)

	result := tk.M{}
	result.Set("success", true)
	result.Set("Data", Result)
	return ResultInfo(result, e)
}
Ejemplo n.º 19
0
func (a *SessionController) GetSession(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson
	_ = a.InitialSetDatabase()

	// payload := map[string]interface{}{}
	// err := r.GetPayload(&payload)
	// if err != nil {
	// 	return helper.CreateResult(false, nil, err.Error())
	// }

	tSession := new(acl.Session)

	data := toolkit.M{}

	arrm := make([]toolkit.M, 0, 0)
	// c, err := acl.Find(tSession, nil, toolkit.M{}.Set("take", payload["take"].(int)).Set("skip", payload["skip"].(int)))
	c, err := acl.Find(tSession, nil, toolkit.M{}.Set("take", 10).Set("skip", 0))
	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	}

	err = c.Fetch(&arrm, 0, false)
	for i, val := range arrm {
		tUser := new(acl.User)
		e := acl.FindByID(tUser, toolkit.ToString(val.Get("userid", "")))
		if e != nil {
			continue
		}
		arrm[i].Set("username", tUser.LoginID)
		arrm[i].Set("duration", time.Since(val["created"].(time.Time)).Hours())
		arrm[i].Set("status", "ACTIVE")
		if val["expired"].(time.Time).Before(time.Now().UTC()) {
			arrm[i].Set("duration", val["expired"].(time.Time).Sub(val["created"].(time.Time)).Hours())
			arrm[i].Set("status", "EXPIRED")
		}
		arrm[i].Set("username", tUser.LoginID)
		// toolkit.Printf("Debug date : %v : %v\n", toolkit.TypeName(val["created"]), val["created"].(time.Time))
	}
	c.Close()

	c, err = acl.Find(tSession, nil, nil)

	data.Set("Datas", arrm)
	data.Set("total", c.Count())
	// data.Set("total", 100)

	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	} else {
		return helper.CreateResult(true, data, "")
	}

}
Ejemplo n.º 20
0
func (r *Rpc) Do(method string, in toolkit.M, result *toolkit.Result) error {
	if r.Fns == nil {
		r.Fns = map[string]RpcFn{}
	}

	in.Set("rpc", r)
	fn, fnExist := r.Fns[method]
	if !fnExist {
		return errors.New("Method " + method + " is not exist")
	}
	return fn(in, result)
}
Ejemplo n.º 21
0
func ACL() {
	var driver, host, db, user, pass string

	fmt.Println("Setup ACL database ==============")

	fmt.Print("  driver (mongo/json/csv/mysql) : ")
	fmt.Scanln(&driver)

	fmt.Print("  host (& port) : ")
	fmt.Scanln(&host)

	fmt.Print("  database name : ")
	fmt.Scanln(&db)

	fmt.Print("  username : "******"  password : "******"driver", driver)
	config.Set("host", host)
	config.Set("db", db)
	config.Set("user", user)
	config.Set("pass", pass)

	fmt.Println("ACL Configuration saved!")
	colonycore.SetConfig(colonycore.CONF_DB_ACL, config)
}
Ejemplo n.º 22
0
func filterCondition(cond toolkit.M) *dbox.Filter {
	fb := new(dbox.Filter)

	for key, val := range cond {
		if key == "$and" || key == "$or" {
			afb := []*dbox.Filter{}
			for _, sVal := range val.([]interface{}) {
				rVal := sVal.(map[string]interface{})
				mVal := toolkit.M{}
				for rKey, mapVal := range rVal {
					mVal.Set(rKey, mapVal)
				}

				afb = append(afb, filterCondition(mVal))
			}

			if key == "$and" {
				fb = dbox.And(afb...)
			} else {
				fb = dbox.Or(afb...)
			}

		} else {
			if reflect.ValueOf(val).Kind() == reflect.Map {
				mVal := val.(map[string]interface{})
				tomVal, _ := toolkit.ToM(mVal)
				switch {
				case tomVal.Has("$eq"):
					fb = dbox.Eq(key, tomVal["$eq"].(string))
				case tomVal.Has("$ne"):
					fb = dbox.Ne(key, tomVal["$ne"].(string))
				case tomVal.Has("$regex"):
					fb = dbox.Contains(key, tomVal["$regex"].(string))
				case tomVal.Has("$gt"):
					fb = dbox.Gt(key, tomVal["$gt"].(string))
				case tomVal.Has("$gte"):
					fb = dbox.Gte(key, tomVal["$gte"].(string))
				case tomVal.Has("$lt"):
					fb = dbox.Lt(key, tomVal["$lt"].(string))
				case tomVal.Has("$lte"):
					fb = dbox.Lte(key, tomVal["$lte"].(string))
				}
			} else {
				fb = dbox.Eq(key, val)
			}
		}
	}

	return fb
}
Ejemplo n.º 23
0
func (c *Connection) OnQuery(query string, name string) []string {
	var astr = []string{}

	rows, e := c.Sql.Query(query)
	if e != nil {
		toolkit.Println(e.Error())
		return nil
	}

	defer rows.Close()
	columns, e := rows.Columns()
	if e != nil {
		toolkit.Println(e.Error())
		return nil
	}

	count := len(columns)

	tableData := []toolkit.M{}
	values := make([]interface{}, count)
	valuePtrs := make([]interface{}, count)

	for rows.Next() {
		for i := 0; i < count; i++ {
			valuePtrs[i] = &values[i]
		}

		rows.Scan(valuePtrs...)
		entry := toolkit.M{}

		for i, col := range columns {
			var v interface{}
			val := values[i]
			b, ok := val.([]byte)
			if ok {
				v = string(b)
			} else {
				v = val
			}
			entry.Set(strings.ToLower(col), v)
		}
		tableData = append(tableData, entry)
	}
	for _, val := range tableData {
		astr = append(astr, val[name].(string))
	}

	return astr

}
Ejemplo n.º 24
0
func (a *AdministrationController) GetAccess(r *knot.WebContext) interface{} {
	var filter *dbox.Filter
	r.Config.OutputType = knot.OutputJson
	a.InitialSetDatabase()

	payload := map[string]interface{}{}
	err := r.GetForms(&payload)

	if strings.Contains(toolkit.TypeName(payload["find"]), "float") {
		payload["find"] = toolkit.ToInt(payload["find"], toolkit.RoundingAuto)
	}

	tAccess := new(acl.Access)
	if find := toolkit.ToString(payload["find"]); find != "" {
		filter = new(dbox.Filter)
		filter = dbox.Or(dbox.Contains("id", find),
			dbox.Contains("title", find),
			dbox.Contains("group1", find),
			dbox.Contains("group2", find),
			dbox.Contains("group3", find),
			dbox.Contains("specialaccess1", find),
			dbox.Contains("specialaccess2", find),
			dbox.Contains("specialaccess3", find),
			dbox.Contains("specialaccess4", find))
	}

	data := toolkit.M{}
	arrm := make([]toolkit.M, 0, 0)

	take := toolkit.ToInt(payload["take"], toolkit.RoundingAuto)
	skip := toolkit.ToInt(payload["skip"], toolkit.RoundingAuto)

	c, err := acl.Find(tAccess, filter, toolkit.M{}.Set("take", take).Set("skip", skip))
	if err == nil {
		err = c.Fetch(&arrm, 0, false)
	}
	c.Close()

	c, err = acl.Find(tAccess, filter, nil)
	data.Set("Datas", arrm)
	data.Set("total", c.Count())

	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	} else {
		return helper.CreateResult(true, data, "")
	}

}
Ejemplo n.º 25
0
func prepareConnection() (dbox.IConnection, error) {
	config := toolkit.M{}
	config.Set("dateformat", "2006-01-02 15:04:05")
	ci := &dbox.ConnectionInfo{"localhost:3306", "test", "root", "", config}
	c, e := dbox.NewConnection("mysql", ci)
	if e != nil {
		return nil, e
	}

	e = c.Connect()
	if e != nil {
		return nil, e
	}
	return c, nil
}
Ejemplo n.º 26
0
func (w *WidgetController) FetchDataSources(ids string) (toolkit.Ms, error) {
	widgetData := toolkit.Ms{}
	_ids := strings.Split(ids, ",")
	for _, _id := range _ids {
		data, err := helper.FetchDataFromDS(_id, 0)
		if err != nil {
			return nil, err
		}
		datasourcewidget := toolkit.M{}
		datasourcewidget.Set("Data", data)
		widgetData = append(widgetData, datasourcewidget)
	}

	return widgetData, nil
}
Ejemplo n.º 27
0
func getSelected(js []toolkit.M, field []string) []toolkit.M {
	var getRemField = toolkit.M{}
	for _, v := range js {
		for i, _ := range v {
			getRemField.Set(i, i)
		}

		if field[0] != "*" {
			fields := removeDuplicatesUnordered(getRemField, field)
			for _, field := range fields {
				v.Unset(field)
			}
		}
	}
	return js
}
Ejemplo n.º 28
0
func (q *Query) execQueryPartDelete(Cond QueryCondition) error {

	writer := q.Connection().(*Connection).writer
	reader := q.Connection().(*Connection).reader
	tempHeader := []string{}

	for _, val := range q.Connection().(*Connection).headerColumn {
		tempHeader = append(tempHeader, val.name)
	}

	for {
		foundDelete := true
		recData := toolkit.M{}

		dataTemp, e := reader.Read()
		for i, val := range dataTemp {
			recData.Set(tempHeader[i], val)
			if q.Connection().(*Connection).headerColumn[i].dataType == "int" {
				recData[tempHeader[i]] = cast.ToInt(val, cast.RoundingAuto)
			} else if q.Connection().(*Connection).headerColumn[i].dataType == "float" {
				recData[tempHeader[i]] = cast.ToF64(val, (len(val) - (strings.IndexAny(val, "."))), cast.RoundingAuto)
			}
		}

		foundDelete = Cond.getCondition(recData)

		if e == io.EOF {
			if !foundDelete && dataTemp != nil {
				writer.Write(dataTemp)
				writer.Flush()
			}
			break
		} else if e != nil {
			return errorlib.Error(packageName, modQuery, "Delete", e.Error())
		}

		if !foundDelete && dataTemp != nil {
			writer.Write(dataTemp)
			writer.Flush()
		}
	}

	return nil

}
Ejemplo n.º 29
0
func (a *UserController) GetUser(r *knot.WebContext) interface{} {
	var filter *dbox.Filter
	r.Config.OutputType = knot.OutputJson
	_ = a.InitialSetDatabase()

	payload := map[string]interface{}{}
	err := r.GetForms(&payload)
	if err != nil {
		return helper.CreateResult(false, nil, err.Error())
	}
	if strings.Contains(toolkit.TypeName(payload["find"]), "float") {
		payload["find"] = toolkit.ToInt(payload["find"], toolkit.RoundingAuto)
	}

	tUser := new(acl.User)
	if find := toolkit.ToString(payload["find"]); find != "" {
		filter = new(dbox.Filter)
		filter = dbox.Or(dbox.Contains("id", find),
			dbox.Contains("fullname", find),
			dbox.Contains("email", find))
	}
	take := toolkit.ToInt(payload["take"], toolkit.RoundingAuto)
	skip := toolkit.ToInt(payload["skip"], toolkit.RoundingAuto)

	c, err := acl.Find(tUser, filter, toolkit.M{}.Set("take", take).Set("skip", skip))
	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	}

	data := toolkit.M{}
	arrm := make([]toolkit.M, 0, 0)
	err = c.Fetch(&arrm, 0, false)
	c.Close()

	c, err = acl.Find(tUser, filter, nil)

	data.Set("Datas", arrm)
	data.Set("total", c.Count())

	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	} else {
		return helper.CreateResult(true, data, "")
	}
}
Ejemplo n.º 30
0
func (h *HistoryModule) GetLog(datas []interface{}, date string) interface{} {
	for _, v := range datas {
		vMap, _ := toolkit.ToM(v)

		logConf := vMap["logconf"].(map[string]interface{})
		dateNow := time.Now()
		dateNowFormat := dateNow.Format(logConf["filepattern"].(string))
		fileName := fmt.Sprintf("%s-%s", logConf["filename"], dateNowFormat)
		h.logPath = f.Join(logConf["logpath"].(string), fileName)
	}

	file, err := os.Open(h.logPath)
	if err != nil {
		return err.Error()
	}
	defer file.Close()

	getHours := strings.Split(date, ":")
	containString := getHours[0] + ":" + getHours[1]
	scanner := bufio.NewScanner(file)
	lines := 0
	containLines := 0

	var logs []interface{}
	for scanner.Scan() {
		lines++
		contains := strings.Contains(scanner.Text(), containString)
		if contains {
			containLines = lines
		}

		if lines == containLines {
			logs = append(logs, "<li>"+scanner.Text()+"</li>")
		}
	}

	if err := scanner.Err(); err != nil {
		return err.Error()
	}

	var addSlice = toolkit.M{}
	addSlice.Set("logs", logs)

	return addSlice
}