b68ee9dcd09f2f2886e4cefe600e1a8ed2e93164
[ric-plt/e2mgr.git] / jsonSender.go
1 //
2 // Copyright 2019 AT&T Intellectual Property
3 // Copyright 2019 Nokia
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //      http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 package sender
18
19 import (
20         "../frontend"
21         "../rmr"
22         "fmt"
23         "github.com/pkg/errors"
24         "log"
25         "reflect"
26         "strconv"
27         "strings"
28         "sync/atomic"
29         "time"
30         "unicode"
31 )
32
33 var counter uint64
34
35 func SendJsonRmrMessage(command frontend.JsonCommand /*the copy is modified locally*/, xAction *[]byte, r *rmr.Service) error {
36         var payload []byte
37         _, err := fmt.Sscanf(command.PackedPayload, "%x", &payload)
38         if err != nil {
39                 return errors.New(fmt.Sprintf("convert inputPayloadAsStr to payloadAsByte. Error: %v\n", err))
40         }
41         command.PackedPayload = string(payload)
42         command.TransactionId = expandTransactionId(command.TransactionId)
43         if len(command.TransactionId) == 0 {
44                 command.TransactionId = string(*xAction)
45         }
46         command.PayloadHeader = expandPayloadHeader(command.PayloadHeader, &command)
47         rmrMsgId, err := rmr.MessageIdToUint(command.RmrMessageType)
48         if err != nil {
49                 return errors.New(fmt.Sprintf("invalid rmr message id: %s",command.WaitForRmrMessageType))
50         }
51         _, err = r.SendMessage(int(rmrMsgId), append([]byte(command.PayloadHeader), payload...), []byte(command.TransactionId))
52         return err
53 }
54
55 /*
56  * transactionId (xAction): The value may have a fixed value or $ or <prefix>$.
57  * $ is replaced by a value generated at runtime (possibly unique per message sent).
58  * If the tag does not exist, then the mock shall use the value taken from the incoming message.
59  */
60 func expandTransactionId(id string) string {
61         if len(id) == 1 && id[0] == '$' {
62                 return fmt.Sprintf("%d", incAndGetCounter())
63         }
64         if len(id) > 1 && id[len(id)-1] == '$' {
65                 return fmt.Sprintf("%s%d", id[:len(id)-1], incAndGetCounter())
66         }
67         return id
68 }
69
70 /*
71  * payloadHeader: A prefix to combine with the payload that will be the message’s payload. The value may include variables of the format $<name> or #<name> where:
72  *   $<name> expands to the value of <name> if it exists or the empty string if not.
73  *   #<name> expands to the length of the value of <name> if it exists or omitted if not.
74  * The intention is to allow the Mock to construct the payload header required by the setup messages (ranIp|ranPort|ranName|payload len|<payload>).
75  * Example: “payloadHeader”: “$ranIp|$ranPort|$ranName|#packedPayload|”
76  */
77
78 func expandPayloadHeader(header string, command *frontend.JsonCommand) string {
79         var name strings.Builder
80         var expandedHeader strings.Builder
81
82         r := strings.NewReader(header)
83         ch, err := r.ReadByte()
84         for {
85                 if err != nil {
86                         break
87                 }
88                 switch ch {
89                 case '$':
90                         for {
91                                 ch, err = r.ReadByte()  //on error ch == 0
92                                 if unicode.IsDigit(rune(ch)) || unicode.IsLetter(rune(ch)) {
93                                         name.WriteByte(ch)
94                                 } else {
95                                         if fieldValue := reflect.Indirect(reflect.ValueOf(command)).FieldByName(name.String()); fieldValue.IsValid() {
96                                                 switch fieldValue.Kind() {
97                                                 case reflect.String:
98                                                         expandedHeader.WriteString(fieldValue.String())
99                                                 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
100                                                         expandedHeader.WriteString(strconv.FormatInt(fieldValue.Int(), 10))
101                                                 case reflect.Bool:
102                                                         expandedHeader.WriteString(strconv.FormatBool(fieldValue.Bool()))
103                                                 case reflect.Float64, reflect.Float32:
104                                                         expandedHeader.WriteString(fmt.Sprintf("%g", fieldValue.Float()))
105                                                 default:
106                                                         log.Fatalf("invalid type for $%s, value must be a string, an int, a bool or a float", name.String())
107                                                 }
108                                         }
109                                         name.Reset()
110                                         break
111                                 }
112                         }
113                 case '#':
114                         for {
115                                 ch, err = r.ReadByte()  //on error ch == 0
116                                 if unicode.IsDigit(rune(ch)) || unicode.IsLetter(rune(ch)) {
117                                         name.WriteByte(ch)
118                                 } else {
119                                         if fieldValue := reflect.Indirect(reflect.ValueOf(command)).FieldByName(name.String()); fieldValue.IsValid() {
120                                                 if fieldValue.Kind() == reflect.String {
121                                                         expandedHeader.WriteString(strconv.FormatInt(int64(len(fieldValue.String())), 10))
122                                                 } else {
123                                                         log.Fatalf("invalid type for #%s, value must be a string", name.String())
124                                                 }
125                                         }
126                                         name.Reset()
127                                         break
128                                 }
129                         }
130                 default:
131                         if unicode.IsPrint(rune(ch)) {
132                                 expandedHeader.WriteByte(ch)
133                         }
134                         ch, err = r.ReadByte()
135                 }
136         }
137         return expandedHeader.String()
138 }
139
140 func incAndGetCounter() uint64 {
141         return atomic.AddUint64(&counter, 1)
142 }
143
144 func init() {
145         counter = uint64(time.Now().Second())
146 }