Blame view
payload.go
9.17 KB
ea858b8a7 refactoring |
1 |
package webutility |
64041a2ea first commit |
2 3 |
import ( |
79071a5d4 Using database/sq... |
4 |
"database/sql" |
8dbe745c3 merged tables uti... |
5 |
"encoding/json" |
f84e7607d added dictionary;... |
6 |
"errors" |
66478e04f payload now retur... |
7 |
"fmt" |
d2ddf82ef started on new rbac |
8 |
"net/http" |
68e590a60 load metadata fro... |
9 |
"strings" |
17a4d0447 mutex lock for pa... |
10 |
"sync" |
2ea67927f added support for... |
11 |
"time" |
64041a2ea first commit |
12 |
) |
2ea67927f added support for... |
13 |
var ( |
3fffcb954 removed old http API |
14 15 |
mu = &sync.Mutex{} metadata = make(map[string]Payload) |
67337ffa8 payload editing |
16 |
updateQue = make(map[string][]byte) |
2ea67927f added support for... |
17 |
|
79071a5d4 Using database/sq... |
18 |
metadataDB *sql.DB |
2ea67927f added support for... |
19 |
activeProject string |
18fcd6d6b merged with util ... |
20 21 |
inited bool metaDriver string |
2ea67927f added support for... |
22 |
) |
8dbe745c3 merged tables uti... |
23 |
|
707782344 lint; vet |
24 |
// LangMap ... |
64041a2ea first commit |
25 |
type LangMap map[string]map[string]string |
707782344 lint; vet |
26 |
// Field ... |
64041a2ea first commit |
27 |
type Field struct { |
d2ddf82ef started on new rbac |
28 29 30 31 |
Parameter string `json:"param"` Type string `json:"type"` Visible bool `json:"visible"` Editable bool `json:"editable"` |
64041a2ea first commit |
32 |
} |
707782344 lint; vet |
33 |
// CorrelationField ... |
8dbe745c3 merged tables uti... |
34 35 36 37 38 |
type CorrelationField struct { Result string `json:"result"` Elements []string `json:"elements"` Type string `json:"type"` } |
707782344 lint; vet |
39 |
// Translation ... |
8dbe745c3 merged tables uti... |
40 |
type Translation struct { |
ecec68b18 updated todo list |
41 |
Language string `json:"language"` |
8dbe745c3 merged tables uti... |
42 |
FieldsLabels map[string]string `json:"fieldsLabels"` |
64041a2ea first commit |
43 |
} |
707782344 lint; vet |
44 |
// PaginationLinks ... |
31a4e1302 started work on p... |
45 46 47 48 49 50 |
type PaginationLinks struct { Base string `json:"base"` Next string `json:"next"` Prev string `json:"prev"` Self string `json:"self"` } |
707782344 lint; vet |
51 |
// PaginationParameters ... |
31a4e1302 started work on p... |
52 |
type PaginationParameters struct { |
368c7f87b pagination work |
53 |
URL string `json:"-"` |
31a4e1302 started work on p... |
54 55 56 57 58 |
Offset int64 `json:"offset"` Limit int64 `json:"limit"` SortBy string `json:"sortBy"` Order string `json:"order"` } |
707782344 lint; vet |
59 |
// GetPaginationParameters ... |
368c7f87b pagination work |
60 61 62 63 64 65 66 67 68 |
// TODO(marko) func GetPaginationParameters(req *http.Request) (p PaginationParameters) { return p } // TODO(marko) func (p *PaginationParameters) paginationLinks() (links PaginationLinks) { return links } |
707782344 lint; vet |
69 |
// Payload ... |
4a51e54d7 simplified |
70 |
type Payload struct { |
d2ddf82ef started on new rbac |
71 72 73 74 |
Method string `json:"method"` Params map[string]string `json:"params"` Lang []Translation `json:"lang"` Fields []Field `json:"fields"` |
4a51e54d7 simplified |
75 |
Correlations []CorrelationField `json:"correlationFields"` |
707782344 lint; vet |
76 |
IDField string `json:"idField"` |
e1fbb41f9 added comments |
77 |
|
31a4e1302 started work on p... |
78 |
// Pagination |
368c7f87b pagination work |
79 80 81 |
Count int64 `json:"count"` Total int64 `json:"total"` Links PaginationLinks `json:"_links"` |
31a4e1302 started work on p... |
82 83 |
// Data holds JSON payload. It can't be used for itteration. |
d2ddf82ef started on new rbac |
84 |
Data interface{} `json:"data"` |
4a51e54d7 simplified |
85 |
} |
8a070abe2 improved |
86 87 88 89 90 91 92 |
func (p *Payload) addLang(code string, labels map[string]string) { t := Translation{ Language: code, FieldsLabels: labels, } p.Lang = append(p.Lang, t) } |
707782344 lint; vet |
93 |
// SetData ... |
ad8e9dd2a added middleware ... |
94 95 96 |
func (p *Payload) SetData(data interface{}) { p.Data = data } |
707782344 lint; vet |
97 |
// SetPaginationInfo ... |
368c7f87b pagination work |
98 |
func (p *Payload) SetPaginationInfo(count, total int64, params PaginationParameters) { |
31a4e1302 started work on p... |
99 100 |
p.Count = count p.Total = total |
368c7f87b pagination work |
101 |
p.Links = params.paginationLinks() |
31a4e1302 started work on p... |
102 |
} |
368c7f87b pagination work |
103 104 105 106 107 |
// NewPayload returs a payload sceleton for entity described with key. func NewPayload(r *http.Request, key string) Payload { p := metadata[key] p.Method = r.Method + " " + r.RequestURI return p |
79071a5d4 Using database/sq... |
108 |
} |
f84e7607d added dictionary;... |
109 110 |
// InitPayloadsMetadata loads all payloads' information into 'metadata' variable. func InitPayloadsMetadata(drv string, db *sql.DB, project string) error { |
1b7dfab73 Payload changed t... |
111 |
var err error |
f84e7607d added dictionary;... |
112 |
if drv != "ora" && drv != "mysql" { |
1b7dfab73 Payload changed t... |
113 114 |
err = errors.New("driver not supported") return err |
f84e7607d added dictionary;... |
115 |
} |
1b7dfab73 Payload changed t... |
116 |
|
18fcd6d6b merged with util ... |
117 |
metaDriver = drv |
2ea67927f added support for... |
118 119 |
metadataDB = db activeProject = project |
62a69beda Init/Reload Table... |
120 |
|
2ea67927f added support for... |
121 122 |
mu.Lock() defer mu.Unlock() |
1b7dfab73 Payload changed t... |
123 |
err = initMetadata(project) |
d66628295 cleaned up |
124 125 126 |
if err != nil { return err } |
2ea67927f added support for... |
127 128 129 130 |
inited = true return nil } |
707782344 lint; vet |
131 |
// EnableHotloading ... |
61efd58cd Put hotload enabl... |
132 133 134 135 136 |
func EnableHotloading(interval int) { if interval > 0 { go hotload(interval) } } |
707782344 lint; vet |
137 |
// GetMetadataForAllEntities ... |
67337ffa8 payload editing |
138 139 140 |
func GetMetadataForAllEntities() map[string]Payload { return metadata } |
707782344 lint; vet |
141 |
// GetMetadataForEntity ... |
67337ffa8 payload editing |
142 143 144 145 |
func GetMetadataForEntity(t string) (Payload, bool) { p, ok := metadata[t] return p, ok } |
707782344 lint; vet |
146 |
// QueEntityModelUpdate ... |
67337ffa8 payload editing |
147 148 149 |
func QueEntityModelUpdate(entityType string, v interface{}) { updateQue[entityType], _ = json.Marshal(v) } |
707782344 lint; vet |
150 |
// UpdateEntityModels ... |
63b2ae620 renamed files |
151 152 153 154 155 156 |
func UpdateEntityModels(command string) (total, upd, add int, err error) { if command != "force" && command != "missing" { return total, 0, 0, errors.New("webutility: unknown command: " + command) } if !inited { |
707782344 lint; vet |
157 |
return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried") |
63b2ae620 renamed files |
158 159 160 161 162 163 |
} total = len(updateQue) toUpdate := make([]string, 0) toAdd := make([]string, 0) |
707782344 lint; vet |
164 |
for k := range updateQue { |
63b2ae620 renamed files |
165 166 167 168 169 170 171 172 173 174 |
if _, exists := metadata[k]; exists { if command == "force" { toUpdate = append(toUpdate, k) } } else { toAdd = append(toAdd, k) } } var uStmt *sql.Stmt |
18fcd6d6b merged with util ... |
175 |
if metaDriver == "ora" { |
63b2ae620 renamed files |
176 177 178 179 |
uStmt, err = metadataDB.Prepare("update entities set entity_model = :1 where entity_type = :2") if err != nil { return } |
18fcd6d6b merged with util ... |
180 |
} else if metaDriver == "mysql" { |
63b2ae620 renamed files |
181 182 183 184 185 186 |
uStmt, err = metadataDB.Prepare("update entities set entity_model = ? where entity_type = ?") if err != nil { return } } for _, k := range toUpdate { |
63b2ae620 renamed files |
187 188 |
_, err = uStmt.Exec(string(updateQue[k]), k) if err != nil { |
63b2ae620 renamed files |
189 190 191 192 193 194 195 |
return } upd++ } blankPayload, _ := json.Marshal(Payload{}) var iStmt *sql.Stmt |
18fcd6d6b merged with util ... |
196 |
if metaDriver == "ora" { |
63b2ae620 renamed files |
197 198 199 200 |
iStmt, err = metadataDB.Prepare("insert into entities(projekat, metadata, entity_type, entity_model) values(:1, :2, :3, :4)") if err != nil { return } |
18fcd6d6b merged with util ... |
201 |
} else if metaDriver == "mysql" { |
63b2ae620 renamed files |
202 203 204 205 206 207 208 209 |
iStmt, err = metadataDB.Prepare("insert into entities(projekat, metadata, entity_type, entity_model) values(?, ?, ?, ?)") if err != nil { return } } for _, k := range toAdd { _, err = iStmt.Exec(activeProject, string(blankPayload), k, string(updateQue[k])) if err != nil { |
63b2ae620 renamed files |
210 211 212 213 214 215 216 217 |
return } metadata[k] = Payload{} add++ } return total, upd, add, nil } |
79071a5d4 Using database/sq... |
218 219 220 221 222 223 224 225 226 227 |
func initMetadata(project string) error { rows, err := metadataDB.Query(`select entity_type, metadata from entities where projekat = ` + fmt.Sprintf("'%s'", project)) if err != nil { return err } defer rows.Close() |
79071a5d4 Using database/sq... |
228 229 230 231 232 233 234 235 236 237 238 |
if len(metadata) > 0 { metadata = nil } metadata = make(map[string]Payload) for rows.Next() { var name, load string rows.Scan(&name, &load) p := Payload{} err := json.Unmarshal([]byte(load), &p) if err != nil { |
b3f1275cd refactored middle... |
239 240 241 |
fmt.Printf("webutility: couldn't init: '%s' metadata: %s: %s ", name, err.Error(), load) |
79071a5d4 Using database/sq... |
242 |
} else { |
79071a5d4 Using database/sq... |
243 244 |
metadata[name] = p } |
79071a5d4 Using database/sq... |
245 |
} |
79071a5d4 Using database/sq... |
246 247 248 |
return nil } |
707782344 lint; vet |
249 |
// LoadMetadataFromFile expects file in format: |
8a070abe2 improved |
250 251 |
// // [ payload A identifier ] |
d9855ed8c : -> = |
252 253 |
// key1 = value1 // key2 = value2 |
8a070abe2 improved |
254 255 |
// ... // [ payload B identifier ] |
d9855ed8c : -> = |
256 257 |
// key1 = value1 // key2 = value2 |
8a070abe2 improved |
258 |
// ... |
707782344 lint; vet |
259 260 |
// // TODO(marko): Currently supports only one hardcoded language... |
68e590a60 load metadata fro... |
261 |
func LoadMetadataFromFile(path string) error { |
18fcd6d6b merged with util ... |
262 |
lines, err := ReadFileLines(path) |
68e590a60 load metadata fro... |
263 264 265 |
if err != nil { return err } |
68e590a60 load metadata fro... |
266 267 268 |
metadata = make(map[string]Payload) var name string |
3ad172fb6 refactored and ma... |
269 |
for i, l := range lines { |
8a070abe2 improved |
270 |
// skip empty lines |
f74a6c349 refactored |
271 |
if l = strings.TrimSpace(l); len(l) == 0 { |
3ad172fb6 refactored and ma... |
272 273 |
continue } |
18fcd6d6b merged with util ... |
274 |
if IsWrappedWith(l, "[", "]") { |
68e590a60 load metadata fro... |
275 |
name = strings.Trim(l, "[]") |
8a070abe2 improved |
276 277 278 |
p := Payload{} p.addLang("sr", make(map[string]string)) metadata[name] = p |
68e590a60 load metadata fro... |
279 280 |
continue } |
3ad172fb6 refactored and ma... |
281 |
if name == "" { |
707782344 lint; vet |
282 |
return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [no header] [%s]", i+1, l) |
3ad172fb6 refactored and ma... |
283 |
} |
d9855ed8c : -> = |
284 |
parts := strings.Split(l, "=") |
8a070abe2 improved |
285 |
if len(parts) != 2 { |
707782344 lint; vet |
286 |
return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [invalid format] [%s]", i+1, l) |
3ad172fb6 refactored and ma... |
287 |
} |
f74a6c349 refactored |
288 289 |
k := strings.TrimSpace(parts[0]) v := strings.TrimSpace(parts[1]) |
3ad172fb6 refactored and ma... |
290 291 |
if v != "-" { metadata[name].Lang[0].FieldsLabels[k] = v |
68e590a60 load metadata fro... |
292 293 294 295 296 |
} } return nil } |
79071a5d4 Using database/sq... |
297 298 299 300 301 302 303 304 305 306 |
func hotload(n int) { entityScan := make(map[string]int64) firstCheck := true for { time.Sleep(time.Duration(n) * time.Second) rows, err := metadataDB.Query(`select ora_rowscn, entity_type from entities where projekat = ` + fmt.Sprintf("'%s'", activeProject)) if err != nil { |
b3f1275cd refactored middle... |
307 308 |
fmt.Printf("webutility: hotload failed: %v ", err) |
79071a5d4 Using database/sq... |
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
time.Sleep(time.Duration(n) * time.Second) continue } var toRefresh []string for rows.Next() { var scanID int64 var entity string rows.Scan(&scanID, &entity) oldID, ok := entityScan[entity] if !ok || oldID != scanID { entityScan[entity] = scanID toRefresh = append(toRefresh, entity) } } rows.Close() if rows.Err() != nil { |
b3f1275cd refactored middle... |
327 328 |
fmt.Printf("webutility: hotload rset error: %v ", rows.Err()) |
79071a5d4 Using database/sq... |
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
time.Sleep(time.Duration(n) * time.Second) continue } if len(toRefresh) > 0 && !firstCheck { mu.Lock() refreshMetadata(toRefresh) mu.Unlock() } if firstCheck { firstCheck = false } } } func refreshMetadata(entities []string) { for _, e := range entities { fmt.Printf("refreshing %s ", e) rows, err := metadataDB.Query(`select metadata from entities where projekat = ` + fmt.Sprintf("'%s'", activeProject) + ` and entity_type = ` + fmt.Sprintf("'%s'", e)) if err != nil { |
b3f1275cd refactored middle... |
355 356 |
fmt.Printf("webutility: refresh: prep: %v ", err) |
79071a5d4 Using database/sq... |
357 358 359 360 361 362 363 364 365 366 |
rows.Close() continue } for rows.Next() { var load string rows.Scan(&load) p := Payload{} err := json.Unmarshal([]byte(load), &p) if err != nil { |
b3f1275cd refactored middle... |
367 368 369 |
fmt.Printf("webutility: couldn't refresh: '%s' metadata: %s %s ", e, err.Error(), load) |
79071a5d4 Using database/sq... |
370 371 372 373 374 375 376 |
} else { metadata[e] = p } } rows.Close() } } |
f84e7607d added dictionary;... |
377 |
/* |
67337ffa8 payload editing |
378 379 |
func ModifyMetadataForEntity(entityType string, p *Payload) error { md, err := json.Marshal(*p) |
2ea67927f added support for... |
380 381 382 |
if err != nil { return err } |
67337ffa8 payload editing |
383 |
|
d66628295 cleaned up |
384 385 |
mu.Lock() defer mu.Unlock() |
2ea67927f added support for... |
386 387 388 389 390 391 392 393 394 |
_, err = metadataDB.PrepAndExe(`update entities set metadata = :1 where projekat = :2 and entity_type = :3`, string(md), activeProject, entityType) if err != nil { return err |
d66628295 cleaned up |
395 396 397 |
} return nil } |
67337ffa8 payload editing |
398 399 400 401 402 403 404 405 |
func DeleteEntityModel(entityType string) error { _, err := metadataDB.PrepAndExe("delete from entities where entity_type = :1", entityType) if err == nil { mu.Lock() delete(metadata, entityType) mu.Unlock() } return err |
d66628295 cleaned up |
406 |
} |
79071a5d4 Using database/sq... |
407 |
*/ |