github.com/Axway/agent-sdk@v1.1.101/pkg/filter/data.go (about) 1 package filter 2 3 import ( 4 "reflect" 5 "strings" 6 ) 7 8 const ( 9 filterTypeAttr = "attr" 10 filterTypeTag = "tag" 11 ) 12 13 // Data - Interface representing the data for filter evaluation 14 type Data interface { 15 GetValue(filterType string, filterKey string) (string, bool) 16 GetKeys(filterType string) []string 17 GetValues(filterType string) []string 18 } 19 20 // AgentFilterData - Represents the data for filter evaluation 21 type AgentFilterData struct { 22 tags map[string]string 23 attr map[string]string 24 } 25 26 // NewFilterData - Transforms the data to flat map which is used for filter evaluation 27 func NewFilterData(tags interface{}, attr interface{}) Data { 28 vTags := reflect.ValueOf(tags) 29 tagsMap := make(map[string]string) 30 // Todo address other types 31 if vTags.Kind() == reflect.Map { 32 for _, key := range vTags.MapKeys() { 33 tagKey := strings.ReplaceAll(key.String(), Dash, DashPlaceHolder) 34 value := vTags.MapIndex(key) 35 vInterface := reflect.ValueOf(value.Interface()) 36 if vInterface.Kind() == reflect.Ptr { 37 vInterface = vInterface.Elem() 38 } 39 if vInterface.Kind() == reflect.String { 40 keyValue := vInterface.String() 41 tagsMap[tagKey] = keyValue 42 } 43 if vInterface.Kind() == reflect.Slice { 44 tagsMap[tagKey] = parseStringSliceFilterData(vInterface) 45 } 46 } 47 } 48 49 return &AgentFilterData{ 50 tags: tagsMap, 51 } 52 } 53 54 func parseStringSliceFilterData(v reflect.Value) string { 55 var val = "" 56 for i := 0; i < v.Len(); i++ { 57 vItem := v.Index(i) 58 if vItem.Kind() == reflect.String { 59 if len(val) > 0 { 60 val += "," 61 } 62 val += vItem.String() 63 } 64 } 65 return val 66 } 67 68 // GetKeys - Returns all the map keys based on the filter data type 69 func (ad *AgentFilterData) GetKeys(ftype string) []string { 70 keys := make([]string, 0) 71 var m map[string]string 72 if ftype == filterTypeAttr { 73 m = ad.attr 74 } else { 75 m = ad.tags 76 } 77 78 for k := range m { 79 keys = append(keys, k) 80 } 81 return keys 82 } 83 84 // GetValues - Returns all the map values based on the filter data type 85 func (ad *AgentFilterData) GetValues(ftype string) []string { 86 values := make([]string, 0) 87 var m map[string]string 88 if ftype == filterTypeAttr { 89 m = ad.attr 90 } else { 91 m = ad.tags 92 } 93 for _, v := range m { 94 values = append(values, v) 95 } 96 return values 97 } 98 99 // GetValue - Returns the value for map entry based on the filter data type 100 func (ad *AgentFilterData) GetValue(ftype, fName string) (val string, ok bool) { 101 var m map[string]string 102 if ftype == filterTypeAttr { 103 m = ad.attr 104 } else { 105 m = ad.tags 106 } 107 if m != nil { 108 val, ok = m[fName] 109 } 110 return 111 }