github.com/TIBCOSoftware/flogo-lib@v0.5.9/app/propertyresolver/json.go (about)

     1  package propertyresolver
     2  
     3  import (
     4  	"encoding/json"
     5  	"io/ioutil"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/TIBCOSoftware/flogo-lib/app"
    10  	"github.com/TIBCOSoftware/flogo-lib/logger"
    11  )
    12  
    13  var preload = make(map[string]interface{})
    14  
    15  var log = logger.GetLogger("app-props-json-resolver")
    16  
    17  // Comma separated list of json files overriding default application property values
    18  // e.g. FLOGO_APP_PROPS_JSON=app1.json,common.json
    19  const EnvAppPropertyFileConfigKey = "FLOGO_APP_PROPS_JSON"
    20  
    21  func init() {
    22  
    23  	filePaths := getExternalFiles()
    24  	if filePaths != "" {
    25  		// Register value resolver
    26  		app.RegisterPropertyValueResolver("json", &JSONFileValueResolver{})
    27  
    28  		// preload props from files
    29  		files := strings.Split(filePaths, ",")
    30  		if len(files) > 0 {
    31  			for _, filePath := range files {
    32  				props := make(map[string]interface{})
    33  
    34  				file, e := ioutil.ReadFile(filePath)
    35  				if e != nil {
    36  					log.Errorf("Can not read - %s due to error - %v", filePath, e)
    37  					panic("")
    38  				}
    39  				e = json.Unmarshal(file, &props)
    40  				if e != nil {
    41  					log.Errorf("Can not read - %s due to error - %v", filePath, e)
    42  					panic("")
    43  				}
    44  
    45  				for k, v := range props {
    46  					preload[k] = v
    47  				}
    48  			}
    49  		}
    50  	}
    51  }
    52  
    53  func getExternalFiles() string {
    54  	key := os.Getenv(EnvAppPropertyFileConfigKey)
    55  	if len(key) > 0 {
    56  		return key
    57  	}
    58  	return ""
    59  }
    60  
    61  // Resolve property value from external files
    62  type JSONFileValueResolver struct {
    63  }
    64  
    65  func (resolver *JSONFileValueResolver) LookupValue(toResolve string) (interface{}, bool) {
    66  	val, found := preload[toResolve]
    67  	return val, found
    68  }