Blame view

json_utility.go 6.76 KB
ea858b8a7   Marko Tikvić   refactoring
1
  package webutility
64041a2ea   Marko Tikvić   first commit
2
3
  
  import (
79071a5d4   Marko Tikvić   Using database/sq...
4
  	"database/sql"
8dbe745c3   Marko Tikvić   merged tables uti...
5
  	"encoding/json"
66478e04f   Marko Tikvić   payload now retur...
6
  	"fmt"
8dbe745c3   Marko Tikvić   merged tables uti...
7
  	"io"
d2ddf82ef   Marko Tikvić   started on new rbac
8
  	"net/http"
17a4d0447   Marko Tikvić   mutex lock for pa...
9
  	"sync"
2ea67927f   Marko Tikvić   added support for...
10
  	"time"
1d0f61553   Marko Tikvić   can't fetch clob
11

0e41f4d80   Marko Tikvić   refactored due to...
12
  	"git.to-net.rs/marko.tikvic/gologger"
64041a2ea   Marko Tikvić   first commit
13
  )
2ea67927f   Marko Tikvić   added support for...
14
  var (
67337ffa8   Marko Tikvić   payload editing
15
16
17
  	mu        = &sync.Mutex{}
  	metadata  = make(map[string]Payload)
  	updateQue = make(map[string][]byte)
2ea67927f   Marko Tikvić   added support for...
18

79071a5d4   Marko Tikvić   Using database/sq...
19
  	metadataDB    *sql.DB
2ea67927f   Marko Tikvić   added support for...
20
21
22
23
  	activeProject string
  
  	inited bool
  )
8dbe745c3   Marko Tikvić   merged tables uti...
24

0e41f4d80   Marko Tikvić   refactored due to...
25
26
27
28
  var logger *gologger.Logger
  
  func init() {
  	var err error
04651a369   Marko Tikvić   new log name
29
  	logger, err = gologger.New("metadata", gologger.MaxLogSize100KB)
0e41f4d80   Marko Tikvić   refactored due to...
30
31
32
33
34
  	if err != nil {
  		fmt.Printf("webutility: %s
  ", err.Error())
  	}
  }
64041a2ea   Marko Tikvić   first commit
35
36
37
  type LangMap map[string]map[string]string
  
  type Field struct {
d2ddf82ef   Marko Tikvić   started on new rbac
38
39
40
41
  	Parameter string `json:"param"`
  	Type      string `json:"type"`
  	Visible   bool   `json:"visible"`
  	Editable  bool   `json:"editable"`
64041a2ea   Marko Tikvić   first commit
42
  }
8dbe745c3   Marko Tikvić   merged tables uti...
43
44
45
46
47
48
49
  type CorrelationField struct {
  	Result   string   `json:"result"`
  	Elements []string `json:"elements"`
  	Type     string   `json:"type"`
  }
  
  type Translation struct {
ecec68b18   Marko Tikvić   updated todo list
50
  	Language     string            `json:"language"`
8dbe745c3   Marko Tikvić   merged tables uti...
51
  	FieldsLabels map[string]string `json:"fieldsLabels"`
64041a2ea   Marko Tikvić   first commit
52
  }
4a51e54d7   Marko Tikvić   simplified
53
  type Payload struct {
d2ddf82ef   Marko Tikvić   started on new rbac
54
55
56
57
  	Method       string             `json:"method"`
  	Params       map[string]string  `json:"params"`
  	Lang         []Translation      `json:"lang"`
  	Fields       []Field            `json:"fields"`
4a51e54d7   Marko Tikvić   simplified
58
59
  	Correlations []CorrelationField `json:"correlationFields"`
  	IdField      string             `json:"idField"`
e1fbb41f9   Marko Tikvić   added comments
60

66478e04f   Marko Tikvić   payload now retur...
61
  	// Data holds JSON payload. It can't be used for itteration.
d2ddf82ef   Marko Tikvić   started on new rbac
62
  	Data interface{} `json:"data"`
4a51e54d7   Marko Tikvić   simplified
63
  }
79071a5d4   Marko Tikvić   Using database/sq...
64
65
66
67
68
69
70
71
72
73
74
75
  // NewPayload returs a payload sceleton for entity described with etype.
  func NewPayload(r *http.Request, etype string) Payload {
  	pload := metadata[etype]
  	pload.Method = r.Method + " " + r.RequestURI
  	return pload
  }
  
  // DecodeJSON decodes JSON data from r to v.
  // Returns an error if it fails.
  func DecodeJSON(r io.Reader, v interface{}) error {
  	return json.NewDecoder(r).Decode(v)
  }
2ea67927f   Marko Tikvić   added support for...
76
  // LoadPayloadsdetaData loads all payloads' information into 'metadata' variable.
79071a5d4   Marko Tikvić   Using database/sq...
77
  func LoadPayloadsMetadata(db *sql.DB, project string) error {
2ea67927f   Marko Tikvić   added support for...
78
79
  	metadataDB = db
  	activeProject = project
62a69beda   Marko Tikvić   Init/Reload Table...
80

2ea67927f   Marko Tikvić   added support for...
81
82
83
  	mu.Lock()
  	defer mu.Unlock()
  	err := initMetadata(project)
d66628295   Marko Tikvić   cleaned up
84
85
86
  	if err != nil {
  		return err
  	}
2ea67927f   Marko Tikvić   added support for...
87
88
89
90
  	inited = true
  
  	return nil
  }
61efd58cd   Marko Tikvić   Put hotload enabl...
91
92
93
94
95
  func EnableHotloading(interval int) {
  	if interval > 0 {
  		go hotload(interval)
  	}
  }
67337ffa8   Marko Tikvić   payload editing
96
97
98
99
100
101
102
103
104
105
106
107
  func GetMetadataForAllEntities() map[string]Payload {
  	return metadata
  }
  
  func GetMetadataForEntity(t string) (Payload, bool) {
  	p, ok := metadata[t]
  	return p, ok
  }
  
  func QueEntityModelUpdate(entityType string, v interface{}) {
  	updateQue[entityType], _ = json.Marshal(v)
  }
79071a5d4   Marko Tikvić   Using database/sq...
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
  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()
  
  	count := 0
  	success := 0
  	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 {
  			logger.Log("couldn't init: '%s' metadata: %s
  %s
  ", name, err.Error(), load)
  		} else {
  			success++
  			metadata[name] = p
  		}
  		count++
  	}
  	perc := float32(success/count) * 100.0
  	logger.Log("loaded %d/%d (%.1f%%) entities
  ", success, count, perc)
  
  	return nil
  }
  
  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 {
  			logger.Log("hotload failed: %v
  ", err)
  			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 {
  			logger.Log("hotload rset error: %v
  ", rows.Err())
  			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 {
  			logger.Log("webutility: refresh: prep: %v
  ", err)
  			rows.Close()
  			continue
  		}
  
  		for rows.Next() {
  			var load string
  			rows.Scan(&load)
  			p := Payload{}
  			err := json.Unmarshal([]byte(load), &p)
  			if err != nil {
  				logger.Log("couldn't refresh: '%s' metadata: %s
  %s
  ", e, err.Error(), load)
  			} else {
  				metadata[e] = p
  			}
  		}
  		rows.Close()
  	}
  }
  
  /*
4b3627bba   Marko Tikvić   added role ID to ...
230
231
232
233
  func UpdateEntityModels(command string) (total, upd, add int, err error) {
  	if command != "force" && command != "missing" {
  		return total, 0, 0, errors.New("uknown command: " + command)
  	}
2ea67927f   Marko Tikvić   added support for...
234
  	if !inited {
67337ffa8   Marko Tikvić   payload editing
235
  		return 0, 0, 0, errors.New("webutil: metadata not initialized but update was tried.")
2ea67927f   Marko Tikvić   added support for...
236
  	}
67337ffa8   Marko Tikvić   payload editing
237
  	total = len(updateQue)
2ea67927f   Marko Tikvić   added support for...
238
  	forUpdate := make([]string, 0)
67337ffa8   Marko Tikvić   payload editing
239
  	forAdd := make([]string, 0)
2ea67927f   Marko Tikvić   added support for...
240

67337ffa8   Marko Tikvić   payload editing
241
  	for k, _ := range updateQue {
2ea67927f   Marko Tikvić   added support for...
242
  		if _, exists := metadata[k]; exists {
4b3627bba   Marko Tikvić   added role ID to ...
243
  			if command == "force" {
67337ffa8   Marko Tikvić   payload editing
244
245
  				forUpdate = append(forUpdate, k)
  			}
2ea67927f   Marko Tikvić   added support for...
246
  		} else {
67337ffa8   Marko Tikvić   payload editing
247
  			forAdd = append(forAdd, k)
2ea67927f   Marko Tikvić   added support for...
248
249
250
251
  		}
  	}
  
  	for _, k := range forUpdate {
2ea67927f   Marko Tikvić   added support for...
252
  		_, err := metadataDB.PrepAndExe(`update entities set
67337ffa8   Marko Tikvić   payload editing
253
254
255
  			entity_model = :1
  			where entity_type = :2`,
  			string(updateQue[k]),
2ea67927f   Marko Tikvić   added support for...
256
257
258
  			k)
  
  		if err != nil {
0e41f4d80   Marko Tikvić   refactored due to...
259
260
  			logger.Log("webutility: update metadata: prep and exe: %v
  ", err)
2ea67927f   Marko Tikvić   added support for...
261
262
263
  			continue
  		}
  		upd++
0e41f4d80   Marko Tikvić   refactored due to...
264
265
  		logger.Log("webutility: updated %s payload model
  ", k)
2ea67927f   Marko Tikvić   added support for...
266
  	}
67337ffa8   Marko Tikvić   payload editing
267
268
  	blankPayload, _ := json.Marshal(Payload{})
  	for _, k := range forAdd {
67337ffa8   Marko Tikvić   payload editing
269
270
271
272
273
274
275
276
277
  		_, err := metadataDB.PrepAndExe(`insert into entities
  			(projekat, metadata, entity_type, entity_model)
  			values(:1, :2, :3, :4)`,
  			activeProject,
  			string(blankPayload),
  			k,
  			string(updateQue[k]))
  
  		if err != nil {
0e41f4d80   Marko Tikvić   refactored due to...
278
279
  			logger.Log("webutility: add metadata: prep and exe: %v
  ", err)
67337ffa8   Marko Tikvić   payload editing
280
281
282
  			continue
  		}
  		metadata[k] = Payload{}
2ea67927f   Marko Tikvić   added support for...
283
  		add++
0e41f4d80   Marko Tikvić   refactored due to...
284
285
  		logger.Log("webutility: added %s to the payload models
  ", k)
4b3627bba   Marko Tikvić   added role ID to ...
286

2ea67927f   Marko Tikvić   added support for...
287
  	}
67337ffa8   Marko Tikvić   payload editing
288
  	return total, upd, add, nil
2ea67927f   Marko Tikvić   added support for...
289
  }
d66628295   Marko Tikvić   cleaned up
290

67337ffa8   Marko Tikvić   payload editing
291
292
  func ModifyMetadataForEntity(entityType string, p *Payload) error {
  	md, err := json.Marshal(*p)
2ea67927f   Marko Tikvić   added support for...
293
294
295
  	if err != nil {
  		return err
  	}
67337ffa8   Marko Tikvić   payload editing
296

d66628295   Marko Tikvić   cleaned up
297
298
  	mu.Lock()
  	defer mu.Unlock()
2ea67927f   Marko Tikvić   added support for...
299
300
301
302
303
304
305
306
307
  	_, 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   Marko Tikvić   cleaned up
308
309
310
  	}
  	return nil
  }
67337ffa8   Marko Tikvić   payload editing
311
312
313
314
315
316
317
318
  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   Marko Tikvić   cleaned up
319
  }
79071a5d4   Marko Tikvić   Using database/sq...
320
  */