Blame view
payload.go
8.48 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 |
// Payload ... |
4a51e54d7 simplified |
45 |
type Payload struct { |
d2ddf82ef started on new rbac |
46 |
Method string `json:"method"` |
28aa66b2f remove ommitempty... |
47 48 49 50 51 |
Params map[string]string `json:"params"` Lang []Translation `json:"lang"` Fields []Field `json:"fields"` Correlations []CorrelationField `json:"correlationFields"` IDField string `json:"idField"` |
e1fbb41f9 added comments |
52 |
|
28aa66b2f remove ommitempty... |
53 |
Links PaginationLinks `json:"_links"` |
31a4e1302 started work on p... |
54 55 |
// Data holds JSON payload. It can't be used for itteration. |
d2ddf82ef started on new rbac |
56 |
Data interface{} `json:"data"` |
4a51e54d7 simplified |
57 |
} |
4635f2c3c pagination utility |
58 59 60 61 62 63 |
// 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 } |
8a070abe2 improved |
64 65 66 67 68 69 70 |
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 |
71 |
// SetData ... |
ad8e9dd2a added middleware ... |
72 73 74 |
func (p *Payload) SetData(data interface{}) { p.Data = data } |
707782344 lint; vet |
75 |
// SetPaginationInfo ... |
4635f2c3c pagination utility |
76 77 78 79 |
func (p *Payload) SetPaginationInfo(count, total int64, params PaginationParams) { p.Links.Count = count p.Links.Total = total p.Links = params.links() |
79071a5d4 Using database/sq... |
80 |
} |
f84e7607d added dictionary;... |
81 82 |
// InitPayloadsMetadata loads all payloads' information into 'metadata' variable. func InitPayloadsMetadata(drv string, db *sql.DB, project string) error { |
1b7dfab73 Payload changed t... |
83 |
var err error |
f84e7607d added dictionary;... |
84 |
if drv != "ora" && drv != "mysql" { |
1b7dfab73 Payload changed t... |
85 86 |
err = errors.New("driver not supported") return err |
f84e7607d added dictionary;... |
87 |
} |
1b7dfab73 Payload changed t... |
88 |
|
18fcd6d6b merged with util ... |
89 |
metaDriver = drv |
2ea67927f added support for... |
90 91 |
metadataDB = db activeProject = project |
62a69beda Init/Reload Table... |
92 |
|
2ea67927f added support for... |
93 94 |
mu.Lock() defer mu.Unlock() |
1b7dfab73 Payload changed t... |
95 |
err = initMetadata(project) |
d66628295 cleaned up |
96 97 98 |
if err != nil { return err } |
2ea67927f added support for... |
99 100 101 102 |
inited = true return nil } |
707782344 lint; vet |
103 |
// EnableHotloading ... |
61efd58cd Put hotload enabl... |
104 105 106 107 108 |
func EnableHotloading(interval int) { if interval > 0 { go hotload(interval) } } |
707782344 lint; vet |
109 |
// GetMetadataForAllEntities ... |
67337ffa8 payload editing |
110 111 112 |
func GetMetadataForAllEntities() map[string]Payload { return metadata } |
707782344 lint; vet |
113 |
// GetMetadataForEntity ... |
67337ffa8 payload editing |
114 115 116 117 |
func GetMetadataForEntity(t string) (Payload, bool) { p, ok := metadata[t] return p, ok } |
707782344 lint; vet |
118 |
// QueEntityModelUpdate ... |
67337ffa8 payload editing |
119 120 121 |
func QueEntityModelUpdate(entityType string, v interface{}) { updateQue[entityType], _ = json.Marshal(v) } |
707782344 lint; vet |
122 |
// UpdateEntityModels ... |
63b2ae620 renamed files |
123 124 125 126 127 128 |
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 |
129 |
return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried") |
63b2ae620 renamed files |
130 131 132 133 134 135 |
} total = len(updateQue) toUpdate := make([]string, 0) toAdd := make([]string, 0) |
707782344 lint; vet |
136 |
for k := range updateQue { |
63b2ae620 renamed files |
137 138 139 140 141 142 143 144 145 146 |
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 ... |
147 |
if metaDriver == "ora" { |
63b2ae620 renamed files |
148 149 150 151 |
uStmt, err = metadataDB.Prepare("update entities set entity_model = :1 where entity_type = :2") if err != nil { return } |
18fcd6d6b merged with util ... |
152 |
} else if metaDriver == "mysql" { |
63b2ae620 renamed files |
153 154 155 156 157 158 |
uStmt, err = metadataDB.Prepare("update entities set entity_model = ? where entity_type = ?") if err != nil { return } } for _, k := range toUpdate { |
63b2ae620 renamed files |
159 160 |
_, err = uStmt.Exec(string(updateQue[k]), k) if err != nil { |
63b2ae620 renamed files |
161 162 163 164 165 166 167 |
return } upd++ } blankPayload, _ := json.Marshal(Payload{}) var iStmt *sql.Stmt |
18fcd6d6b merged with util ... |
168 |
if metaDriver == "ora" { |
63b2ae620 renamed files |
169 170 171 172 |
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 ... |
173 |
} else if metaDriver == "mysql" { |
63b2ae620 renamed files |
174 175 176 177 178 179 180 181 |
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 |
182 183 184 185 186 187 188 189 |
return } metadata[k] = Payload{} add++ } return total, upd, add, nil } |
79071a5d4 Using database/sq... |
190 191 192 193 194 195 196 197 198 199 |
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... |
200 201 202 203 204 205 206 207 208 209 210 |
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... |
211 212 213 |
fmt.Printf("webutility: couldn't init: '%s' metadata: %s: %s ", name, err.Error(), load) |
79071a5d4 Using database/sq... |
214 |
} else { |
79071a5d4 Using database/sq... |
215 216 |
metadata[name] = p } |
79071a5d4 Using database/sq... |
217 |
} |
79071a5d4 Using database/sq... |
218 219 220 |
return nil } |
707782344 lint; vet |
221 |
// LoadMetadataFromFile expects file in format: |
8a070abe2 improved |
222 223 |
// // [ payload A identifier ] |
d9855ed8c : -> = |
224 225 |
// key1 = value1 // key2 = value2 |
8a070abe2 improved |
226 227 |
// ... // [ payload B identifier ] |
d9855ed8c : -> = |
228 229 |
// key1 = value1 // key2 = value2 |
8a070abe2 improved |
230 |
// ... |
707782344 lint; vet |
231 232 |
// // TODO(marko): Currently supports only one hardcoded language... |
68e590a60 load metadata fro... |
233 |
func LoadMetadataFromFile(path string) error { |
18fcd6d6b merged with util ... |
234 |
lines, err := ReadFileLines(path) |
68e590a60 load metadata fro... |
235 236 237 |
if err != nil { return err } |
68e590a60 load metadata fro... |
238 239 240 |
metadata = make(map[string]Payload) var name string |
3ad172fb6 refactored and ma... |
241 |
for i, l := range lines { |
8a070abe2 improved |
242 |
// skip empty lines |
f74a6c349 refactored |
243 |
if l = strings.TrimSpace(l); len(l) == 0 { |
3ad172fb6 refactored and ma... |
244 245 |
continue } |
18fcd6d6b merged with util ... |
246 |
if IsWrappedWith(l, "[", "]") { |
68e590a60 load metadata fro... |
247 |
name = strings.Trim(l, "[]") |
8a070abe2 improved |
248 249 250 |
p := Payload{} p.addLang("sr", make(map[string]string)) metadata[name] = p |
68e590a60 load metadata fro... |
251 252 |
continue } |
3ad172fb6 refactored and ma... |
253 |
if name == "" { |
707782344 lint; vet |
254 |
return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [no header] [%s]", i+1, l) |
3ad172fb6 refactored and ma... |
255 |
} |
d9855ed8c : -> = |
256 |
parts := strings.Split(l, "=") |
8a070abe2 improved |
257 |
if len(parts) != 2 { |
707782344 lint; vet |
258 |
return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [invalid format] [%s]", i+1, l) |
3ad172fb6 refactored and ma... |
259 |
} |
f74a6c349 refactored |
260 261 |
k := strings.TrimSpace(parts[0]) v := strings.TrimSpace(parts[1]) |
3ad172fb6 refactored and ma... |
262 263 |
if v != "-" { metadata[name].Lang[0].FieldsLabels[k] = v |
68e590a60 load metadata fro... |
264 265 266 267 268 |
} } return nil } |
79071a5d4 Using database/sq... |
269 270 271 272 273 274 275 276 277 278 |
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... |
279 280 |
fmt.Printf("webutility: hotload failed: %v ", err) |
79071a5d4 Using database/sq... |
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
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... |
299 300 |
fmt.Printf("webutility: hotload rset error: %v ", rows.Err()) |
79071a5d4 Using database/sq... |
301 302 303 304 305 306 307 308 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 } 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... |
327 328 |
fmt.Printf("webutility: refresh: prep: %v ", err) |
79071a5d4 Using database/sq... |
329 330 331 332 333 334 335 336 337 338 |
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... |
339 340 341 |
fmt.Printf("webutility: couldn't refresh: '%s' metadata: %s %s ", e, err.Error(), load) |
79071a5d4 Using database/sq... |
342 343 344 345 346 347 348 |
} else { metadata[e] = p } } rows.Close() } } |
f84e7607d added dictionary;... |
349 |
/* |
67337ffa8 payload editing |
350 351 |
func ModifyMetadataForEntity(entityType string, p *Payload) error { md, err := json.Marshal(*p) |
2ea67927f added support for... |
352 353 354 |
if err != nil { return err } |
67337ffa8 payload editing |
355 |
|
d66628295 cleaned up |
356 357 |
mu.Lock() defer mu.Unlock() |
2ea67927f added support for... |
358 359 360 361 362 363 364 365 366 |
_, 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 |
367 368 369 |
} return nil } |
67337ffa8 payload editing |
370 371 372 373 374 375 376 377 |
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 |
378 |
} |
79071a5d4 Using database/sq... |
379 |
*/ |