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

     1  package resource
     2  
     3  import (
     4  	"errors"
     5  	"strings"
     6  )
     7  
     8  // ResourceManager interface
     9  type Manager interface {
    10  	// LoadResources tells the manager to load the specified resource set
    11  	LoadResource(config *Config) error
    12  
    13  	// GetResource get the resource that corresponds to the specified id
    14  	GetResource(id string) interface{}
    15  }
    16  
    17  var managers = make(map[string]Manager)
    18  
    19  // RegisterManager registers a resource manager for the specified type
    20  func RegisterManager(resourceType string, manager Manager) error {
    21  
    22  	_, exists := managers[resourceType]
    23  
    24  	if exists {
    25  		return errors.New("Resource Manager already registered for type: " + resourceType)
    26  	}
    27  
    28  	managers[resourceType] = manager
    29  	return nil
    30  }
    31  
    32  // GetManager gets the manager for the specified resource type
    33  func GetManager(resourceType string) Manager {
    34  	return managers[resourceType]
    35  }
    36  
    37  // Load specified resource into its corresponding Resource Manager
    38  func Load(config *Config) error {
    39  	resType, err := GetTypeFromID(config.ID)
    40  	if err != nil {
    41  		return err
    42  	}
    43  
    44  	manager := GetManager(resType)
    45  
    46  	if manager == nil {
    47  		return errors.New("unsupported resource type: " + resType)
    48  	}
    49  
    50  	return manager.LoadResource(config)
    51  }
    52  
    53  // Get gets the specified resource, id format is {type}:{id}"
    54  func Get(id string) (interface{}, error) {
    55  
    56  	resType, err := GetTypeFromID(id)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	manager := GetManager(resType)
    62  
    63  	if manager == nil {
    64  		return nil, errors.New("unsupported resource type: " + resType)
    65  	}
    66  
    67  	return manager.GetResource(id), nil
    68  }
    69  
    70  func GetTypeFromID(id string) (string, error) {
    71  
    72  	idx := strings.Index(id, ":")
    73  
    74  	if idx < 0 {
    75  		return "", errors.New("Invalid resource id: " + id)
    76  	}
    77  
    78  	return id[:idx], nil
    79  }