github.com/myafeier/fabric@v1.0.1-0.20170722181825-3a4b1f2bce86/common/config/standardvalues.go (about)

     1  /*
     2  Copyright IBM Corp. 2017 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8                   http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package config
    18  
    19  import (
    20  	"fmt"
    21  	"reflect"
    22  
    23  	"github.com/golang/protobuf/proto"
    24  )
    25  
    26  type standardValues struct {
    27  	lookup map[string]proto.Message
    28  }
    29  
    30  // NewStandardValues accepts a structure which must contain only protobuf message
    31  // types.  The structure may embed other (non-pointer) structures which satisfy
    32  // the same condition.  NewStandard values will instantiate memory for all the proto
    33  // messages and build a lookup map from structure field name to proto message instance
    34  // This is a useful way to easily implement the Values interface
    35  func NewStandardValues(protosStructs ...interface{}) (*standardValues, error) {
    36  	sv := &standardValues{
    37  		lookup: make(map[string]proto.Message),
    38  	}
    39  
    40  	for _, protosStruct := range protosStructs {
    41  		logger.Debugf("Initializing protos for %T\n", protosStruct)
    42  		if err := sv.initializeProtosStruct(reflect.ValueOf(protosStruct)); err != nil {
    43  			return nil, err
    44  		}
    45  	}
    46  
    47  	return sv, nil
    48  }
    49  
    50  // Deserialize looks up the backing Values proto of the given name, unmarshals the given bytes
    51  // to populate the backing message structure, and returns a referenced to the retained deserialized
    52  // message (or an error, either because the key did not exist, or there was an an error unmarshaling
    53  func (sv *standardValues) Deserialize(key string, value []byte) (proto.Message, error) {
    54  	msg, ok := sv.lookup[key]
    55  	if !ok {
    56  		return nil, fmt.Errorf("Unexpected key %s", key)
    57  	}
    58  
    59  	err := proto.Unmarshal(value, msg)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  
    64  	return msg, nil
    65  }
    66  
    67  func (sv *standardValues) initializeProtosStruct(objValue reflect.Value) error {
    68  	objType := objValue.Type()
    69  	if objType.Kind() != reflect.Ptr {
    70  		return fmt.Errorf("Non pointer type")
    71  	}
    72  	if objType.Elem().Kind() != reflect.Struct {
    73  		return fmt.Errorf("Non struct type")
    74  	}
    75  
    76  	numFields := objValue.Elem().NumField()
    77  	for i := 0; i < numFields; i++ {
    78  		structField := objType.Elem().Field(i)
    79  		logger.Debugf("Processing field: %s\n", structField.Name)
    80  		switch structField.Type.Kind() {
    81  		case reflect.Ptr:
    82  			fieldPtr := objValue.Elem().Field(i)
    83  			if !fieldPtr.CanSet() {
    84  				return fmt.Errorf("Cannot set structure field %s (unexported?)", structField.Name)
    85  			}
    86  			fieldPtr.Set(reflect.New(structField.Type.Elem()))
    87  		default:
    88  			return fmt.Errorf("Bad type supplied: %s", structField.Type.Kind())
    89  		}
    90  
    91  		proto, ok := objValue.Elem().Field(i).Interface().(proto.Message)
    92  		if !ok {
    93  			return fmt.Errorf("Field type %T does not implement proto.Message", objValue.Elem().Field(i))
    94  		}
    95  
    96  		_, ok = sv.lookup[structField.Name]
    97  		if ok {
    98  			return fmt.Errorf("Ambiguous field name specified, multiple occurrences of %s", structField.Name)
    99  		}
   100  
   101  		sv.lookup[structField.Name] = proto
   102  	}
   103  
   104  	return nil
   105  }