func (intermediate *intermediateAwsPolicyDocument) document() (*awsPolicyDocument, error) { var statements []*awsPolicyStatement switch s := intermediate.Statements.(type) { case []interface{}: if err := mapstructure.Decode(s, &statements); err != nil { return nil, errwrap.Wrapf("Error parsing statement: {{err}}", err) } case map[string]interface{}: var singleStatement *awsPolicyStatement if err := mapstructure.Decode(s, &singleStatement); err != nil { return nil, errwrap.Wrapf("Error parsing statement: {{err}}", err) } statements = append(statements, singleStatement) default: return nil, errors.New("Unknown error parsing statement") } document := &awsPolicyDocument{ Version: intermediate.Version, Id: intermediate.Id, Statements: statements, } return document, nil }
func mapDecode(o *Order, customProvider OrderCustomProvider) (order *Order, err error) { /* Map OrderCustom */ orderCustom := customProvider.NewOrderCustom() if orderCustom != nil && o.Custom != nil { err = mapstructure.Decode(o.Custom, orderCustom) if err != nil { return nil, err } o.Custom = orderCustom } /* Map PostionCustom */ for _, position := range o.Positions { positionCustom := customProvider.NewPositionCustom() if positionCustom != nil && position.Custom != nil { err = mapstructure.Decode(position.Custom, positionCustom) if err != nil { return nil, err } position.Custom = positionCustom } } return o, nil }
func (h *GenericHandler) Handle(event model.WatchEvent) error { if i, ok := event.Object.(map[string]interface{}); ok { var metadata *model.ObjectMeta var kind string var selector map[string]interface{} if h.kindHandled == RCKind { var rc model.ReplicationController mapstructure.Decode(i, &rc) if rc == (model.ReplicationController{}) || rc.Spec == nil { log.Infof("Couldn't decode %+v to rc.", i) return nil } kind = rc.Kind selector = rc.Spec.Selector metadata = rc.Metadata } else if h.kindHandled == ServiceKind { var svc model.Service mapstructure.Decode(i, &svc) if svc == (model.Service{}) || svc.Spec == nil { log.Infof("Couldn't decode %+v to service.", i) return nil } kind = svc.Kind selector = svc.Spec.Selector metadata = svc.Metadata } else { return fmt.Errorf("Unrecognized handled kind [%s].", h.kindHandled) } serviceEvent := &client.ExternalServiceEvent{ ExternalId: metadata.Uid, EventType: constructEventType(event), } switch event.Type { case "MODIFIED": fallthrough case "ADDED": err := h.add(selector, metadata, event, serviceEvent, constructResourceType(kind)) if err != nil { return err } case "DELETED": service := client.Service{ Kind: constructResourceType(kind), } serviceEvent.Service = service default: return nil } _, err := h.rancherClient.ExternalServiceEvent.Create(serviceEvent) return err } return fmt.Errorf("Couldn't decode event [%#v]", event) }
func New(credential, builder map[string]interface{}) (*DigitalOcean, error) { d := DigitalOcean{} // Credentials if err := mapstructure.Decode(credential, &d.Creds); err != nil { return nil, err } // Builder data if err := mapstructure.Decode(builder, &d.Builder); err != nil { return nil, err } if d.Creds.ClientID == "" { return nil, errors.New("credentials client_id is empty") } if d.Creds.APIKey == "" { return nil, errors.New("credentials api_key is empty") } d.Builder.ClientID = d.Creds.ClientID d.Builder.APIKey = d.Creds.APIKey d.Client = digitalocean.DigitalOceanClient{}.New(d.Creds.ClientID, d.Creds.APIKey) // authenticate credentials with a simple call _, err := d.Regions() if err != nil { return nil, errors.New("authentication with DigitalOcean failed.") } return &d, nil }
func handleChangeNotification(socket *websocket.Conn, userID string, err chan string) { res, errr := r.Table("notifications"). Filter(r.Row.Field("UserId"). Eq(userID)). Changes(). Run(api.Sess) var value HandleChange if errr != nil { err <- errr.Error() } for res.Next(&value) { var notif api.Notification var simpleNotif api.WebSocketNotification mapstructure.Decode(value.NewVal, ¬if) if notif.Id == "" { mapstructure.Decode(value.OldVal, ¬if) simpleNotif.OldVal = true } else { simpleNotif.OldVal = false } simpleNotif.Title = "notification" simpleNotif.Type = notif.Type simpleNotif.Name = notif.Name simpleNotif.UserIdFrom = notif.UserIdFrom simpleNotif.IdLink = notif.IdLink simpleNotif.CreatedAt = notif.CreatedAt errr := socket.WriteJSON(simpleNotif) if errr != nil { err <- errr.Error() } } }
// mapDecode maps interfaces to specific types provided by customProvider func mapDecode(cust *Customer, customProvider CustomerCustomProvider) (customer *Customer, err error) { /* Map CustomerCustom */ customerCustom := customProvider.NewCustomerCustom() if customerCustom != nil && cust.Custom != nil { err = mapstructure.Decode(cust.Custom, customerCustom) if err != nil { return nil, err } cust.Custom = customerCustom } /* Map AddressCustom */ for _, address := range cust.Addresses { addressCustom := customProvider.NewAddressCustom() if addressCustom != nil && address.Custom != nil { err = mapstructure.Decode(address.Custom, addressCustom) if err != nil { return nil, err } address.Custom = addressCustom } } return cust, nil }
// Parses YAML structure to typed list of Hops func parseConfigMap(configMap map[string]interface{}) (hops, error) { if err := validateConfig(configMap); err != nil { return nil, err } hopsConfig := make(hops) rh := make(rawHops) err := mapstructure.Decode(configMap, &rh) if err != nil { panic(err) } for name, defs := range rh { for _, def := range defs { if dockMap, ok := def["docker"]; ok { docker := Docker{} err := mapstructure.Decode(dockMap, &docker) if err != nil { panic(err) } hopsConfig[name] = []Hop{&docker} } else { return nil, fmt.Errorf( "There's no definition of docker for %v", name) } } } return hopsConfig, nil }
func (sd *sortableDistroByNumStaticHost) Less(i, j int) bool { if sd.distros[i].Provider != evergreen.HostTypeStatic && sd.distros[j].Provider != evergreen.HostTypeStatic { return false } if sd.distros[i].Provider == evergreen.HostTypeStatic && sd.distros[j].Provider != evergreen.HostTypeStatic { return true } if sd.distros[i].Provider != evergreen.HostTypeStatic && sd.distros[j].Provider == evergreen.HostTypeStatic { return false } h1 := &static.Settings{} h2 := &static.Settings{} err := mapstructure.Decode(sd.distros[i].ProviderSettings, h1) if err != nil { return false } err = mapstructure.Decode(sd.distros[j].ProviderSettings, h2) if err != nil { return false } return len(h1.Hosts) > len(h2.Hosts) }
func (p *PostProcessor) Configure(raws ...interface{}) error { // Store the raw configs for usage later p.rawConfigs = raws for _, raw := range raws { err := mapstructure.Decode(raw, &p.config) if err != nil { return err } } ppExtraConfig := make(map[string]interface{}) if p.config.OutputPath == "" { p.config.OutputPath = "packer_{{ .BuildName }}_{{.Provider}}.box" ppExtraConfig["output"] = p.config.OutputPath } _, err := template.New("output").Parse(p.config.OutputPath) if err != nil { return fmt.Errorf("output invalid template: %s", err) } // Store the extra configuration for post-processors p.rawConfigs = append(p.rawConfigs, ppExtraConfig) // TODO(mitchellh): Properly handle multiple raw configs var mapConfig map[string]interface{} if err := mapstructure.Decode(raws[0], &mapConfig); err != nil { return err } p.premade = make(map[string]packer.PostProcessor) errors := make([]error, 0) for k, raw := range mapConfig { pp := keyToPostProcessor(k) if pp == nil { continue } // Create the proper list of configurations ppConfigs := make([]interface{}, 0, len(p.rawConfigs)+1) copy(ppConfigs, p.rawConfigs) ppConfigs = append(ppConfigs, raw) if err := pp.Configure(ppConfigs...); err != nil { errors = append(errors, err) } p.premade[k] = pp } if len(errors) > 0 { return &packer.MultiError{errors} } return nil }
func (h *GenericHandler) Handle(event model.WatchEvent) error { if i, ok := event.Object.(map[string]interface{}); ok { var metadata *model.ObjectMeta var kind string var selector map[string]interface{} if h.kindHandled == RCKind { var rc model.ReplicationController mapstructure.Decode(i, &rc) kind = rc.Kind selector = rc.Spec.Selector metadata = rc.Metadata } else if h.kindHandled == ServiceKind { var svc model.Service mapstructure.Decode(i, &svc) kind = svc.Kind selector = svc.Spec.Selector metadata = svc.Metadata } else { return fmt.Errorf("Unrecognized handled kind [%s].", h.kindHandled) } ts, err := time.Parse(time.RFC3339, metadata.CreationTimestamp) if err != nil { return err } serviceEvent := &client.ServiceEvent{ Name: metadata.Name, ExternalId: metadata.Uid, EventType: constructEventType(event), ResourceType: constructResourceType(kind), ExternalTimestamp: ts.Unix(), } switch event.Type { case "MODIFIED": fallthrough case "ADDED": err = h.add(selector, metadata, event, serviceEvent, serviceEvent.ResourceType) if err != nil { return err } case "DELETED": // No extra fields required for delete default: return nil } _, err = h.rancherClient.ServiceEvent.Create(serviceEvent) return err } return fmt.Errorf("Couldn't decode event [%#v]", event) }
// LoadBlocks will load the blocks that are stored in the raw_blocks data and // mix it up with the user input that we give it. func (t *JsonTemplate) LoadBlocks(user_input interface{}) { var blocks []map[string]interface{} var input map[string]interface{} mapstructure.Decode(t.raw_block_data, &blocks) mapstructure.Decode(user_input, &input) for _, block := range blocks { t.blocks = append(t.blocks, t.LoadBlock(block, input)) } t.wg.Wait() }
func Start(orientChan chan orient.Event, shootChan chan shoot.Event) { port := 4242 var upgrader = websocket.Upgrader{ ReadBufferSize: 2048, WriteBufferSize: 2048, CheckOrigin: func(r *http.Request) bool { return true }, } http.HandleFunc("/control", func(w http.ResponseWriter, r *http.Request) { log.Debug("Connection received") conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Fatal(err) } defer conn.Close() for { messageType, reader, err := conn.NextReader() if err != nil { log.Println(err) return } if messageType == websocket.TextMessage { packet := Packet{} decoder := json.NewDecoder(reader) if err := decoder.Decode(&packet); err != nil { log.Warning(err) continue } switch packet.Type { case "orient": event := orient.Event{} mapstructure.Decode(packet.Payload, &event) orientChan <- event case "shoot": event := shoot.Event{} mapstructure.Decode(packet.Payload, &event) shootChan <- event default: log.Info("Oops unknown packet: ", packet) } } } }) go http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil) log.Infof("Websocket server started on port %d", port) }
func testCredsWrite(t *testing.T, roleName string, data map[string]interface{}, expectError bool) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.WriteOperation, Path: fmt.Sprintf("creds/%s", roleName), Data: data, ErrorOk: true, Check: func(resp *logical.Response) error { if resp == nil { return fmt.Errorf("response is nil") } if resp.Data == nil { return fmt.Errorf("data is nil") } if expectError { var e struct { Error string `mapstructure:"error"` } if err := mapstructure.Decode(resp.Data, &e); err != nil { return err } if len(e.Error) == 0 { return fmt.Errorf("expected error, but write succeeded.") } return nil } if roleName == testDynamicRoleName { var d struct { Key string `mapstructure:"key"` } if err := mapstructure.Decode(resp.Data, &d); err != nil { return err } if d.Key == "" { return fmt.Errorf("Generated key is an empty string") } // Checking only for a parsable key _, err := ssh.ParsePrivateKey([]byte(d.Key)) if err != nil { return fmt.Errorf("Generated key is invalid") } } else { if resp.Data["key_type"] != KeyTypeOTP { return fmt.Errorf("Incorrect key_type") } if resp.Data["key"] == nil { return fmt.Errorf("Invalid key") } } return nil }, } }
// APISave returns true if the file is local only func (parser *Parser) APISave(payloads []*get3w.SavePayload) error { for _, payload := range payloads { switch payload.Type { case get3w.PayloadTypeConfig: if payload.Status == get3w.PayloadStatusModified || payload.Status == get3w.PayloadStatusAdded { var config get3w.Config if err := mapstructure.Decode(payload.Data, &config); err != nil { return err } parser.Config = &config if err := parser.WriteConfig(); err != nil { return err } } case get3w.PayloadTypePage: if payload.Status == get3w.PayloadStatusModified || payload.Status == get3w.PayloadStatusAdded { var page get3w.Page if err := mapstructure.Decode(payload.Data, &page); err != nil { return err } if err := parser.WritePage(&page); err != nil { return err } } case get3w.PayloadTypeSection: if payload.Status == get3w.PayloadStatusModified || payload.Status == get3w.PayloadStatusAdded { var section get3w.Section if err := mapstructure.Decode(payload.Data, §ion); err != nil { return err } if err := parser.saveSection(§ion); err != nil { return err } } else if payload.Status == get3w.PayloadStatusRemoved { var section get3w.Section if err := mapstructure.Decode(payload.Data, §ion); err != nil { return err } if err := parser.deleteSection(section.Path); err != nil { return err } } } } return nil }
func (s *SourceOptionsSlice) UnmarshalJSON(data []byte) error { var maps []map[string]interface{} err := json.Unmarshal(data, &maps) if err != nil { return bosherr.WrapError(err, "Unmarshalling sources") } for _, m := range maps { if optType, ok := m["Type"]; ok { var err error var opts SourceOptions switch { case optType == "HTTP": var o HTTPSourceOptions err, opts = mapstruc.Decode(m, &o), o case optType == "InstanceMetadata": var o InstanceMetadataSourceOptions err, opts = mapstruc.Decode(m, &o), o case optType == "ConfigDrive": var o ConfigDriveSourceOptions err, opts = mapstruc.Decode(m, &o), o case optType == "File": var o FileSourceOptions err, opts = mapstruc.Decode(m, &o), o case optType == "CDROM": var o CDROMSourceOptions err, opts = mapstruc.Decode(m, &o), o default: err = bosherr.Errorf("Unknown source type '%s'", optType) } if err != nil { return bosherr.WrapErrorf(err, "Unmarshalling source type '%s'", optType) } *s = append(*s, opts) } else { return bosherr.Error("Missing source type") } } return nil }
// marshal merges config a and b and decodes the merge config into the provided // structure. func marshal(a Config, b Config, rawVal interface{}) (err error) { err = mapstructure.Decode(&a, rawVal) if err != nil { return } if b != nil { err = mapstructure.Decode(&b, rawVal) if err != nil { return } } return }
// Marshals the config into a Struct func Marshal(rawVal interface{}) (err error) { err = mapstructure.Decode(defaults, rawVal) if err != nil { return } err = mapstructure.Decode(config, rawVal) if err != nil { return } err = mapstructure.Decode(override, rawVal) if err != nil { return } return }
func (p *PostProcessor) Configure(raws ...interface{}) error { for _, raw := range raws { err := mapstructure.Decode(raw, &p.config) if err != nil { return err } } if p.config.OutputPath == "" { p.config.OutputPath = "packer_{{ .BuildName }}_{{.Provider}}.box" } _, err := template.New("output").Parse(p.config.OutputPath) if err != nil { return fmt.Errorf("output invalid template: %s", err) } // TODO(mitchellh): Properly handle multiple raw configs var mapConfig map[string]interface{} if err := mapstructure.Decode(raws[0], &mapConfig); err != nil { return err } packerConfig := map[string]interface{}{ packer.BuildNameConfigKey: p.config.PackerBuildName, } p.premade = make(map[string]packer.PostProcessor) errors := make([]error, 0) for k, raw := range mapConfig { pp := keyToPostProcessor(k) if pp == nil { continue } if err := pp.Configure(raw, packerConfig); err != nil { errors = append(errors, err) } p.premade[k] = pp } if len(errors) > 0 { return &packer.MultiError{errors} } return nil }
func testAccStepReadRole(t *testing.T, name string, sql string) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.ReadOperation, Path: "roles/" + name, Check: func(resp *logical.Response) error { if resp == nil { if sql == "" { return nil } return fmt.Errorf("bad: %#v", resp) } var d struct { SQL string `mapstructure:"sql"` } if err := mapstructure.Decode(resp.Data, &d); err != nil { return err } if d.SQL != sql { return fmt.Errorf("bad: %#v", resp) } return nil }, } }
// ExtractListeners accepts a Page struct, specifically a ListenerPage struct, // and extracts the elements into a slice of Listener structs. In other words, // a generic collection is mapped into a relevant slice. func ExtractListeners(page pagination.Page) ([]Listener, error) { var resp struct { Listeners []Listener `mapstructure:"listeners" json:"listeners"` } err := mapstructure.Decode(page.(ListenerPage).Body, &resp) return resp.Listeners, err }
func testAccStepConfig(t *testing.T, d map[string]interface{}, expectError bool) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.UpdateOperation, Path: "config/connection", Data: d, ErrorOk: true, Check: func(resp *logical.Response) error { if expectError { if resp.Data == nil { return fmt.Errorf("data is nil") } var e struct { Error string `mapstructure:"error"` } if err := mapstructure.Decode(resp.Data, &e); err != nil { return err } if len(e.Error) == 0 { return fmt.Errorf("expected error, but write succeeded.") } return nil } else if resp != nil { return fmt.Errorf("response should be nil") } return nil }, } }
// FromParameters constructs a new Driver with a given parameters map // Required parameters: // - username // - password // - authurl // - container func FromParameters(parameters map[string]interface{}) (*Driver, error) { params := Parameters{ ChunkSize: defaultChunkSize, InsecureSkipVerify: false, } if err := mapstructure.Decode(parameters, ¶ms); err != nil { return nil, err } if params.Username == "" { return nil, fmt.Errorf("No username parameter provided") } if params.Password == "" { return nil, fmt.Errorf("No password parameter provided") } if params.AuthURL == "" { return nil, fmt.Errorf("No authurl parameter provided") } if params.Container == "" { return nil, fmt.Errorf("No container parameter provided") } if params.ChunkSize < minChunkSize { return nil, fmt.Errorf("The chunksize %#v parameter should be a number that is larger than or equal to %d", params.ChunkSize, minChunkSize) } return New(params) }
func (p *Page) getRenderingConfig() *helpers.Blackfriday { p.renderingConfigInit.Do(func() { pageParam := p.GetParam("blackfriday") siteParam := viper.GetStringMap("blackfriday") combinedParam := siteParam if pageParam != nil { combinedParam = make(map[string]interface{}) for k, v := range siteParam { combinedParam[k] = v } pageConfig := cast.ToStringMap(pageParam) for key, value := range pageConfig { combinedParam[key] = value } } p.renderingConfig = helpers.NewBlackfriday() if err := mapstructure.Decode(combinedParam, p.renderingConfig); err != nil { jww.FATAL.Printf("Failed to get rendering config for %s:\n%s", p.BaseFileName(), err.Error()) } }) return p.renderingConfig }
func testAccStepReadPolicy(t *testing.T, name string, value string) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.ReadOperation, Path: "roles/" + name, Check: func(resp *logical.Response) error { if resp == nil { if value == "" { return nil } return fmt.Errorf("bad: %#v", resp) } var d struct { Policy string `mapstructure:"policy"` } if err := mapstructure.Decode(resp.Data, &d); err != nil { return err } if d.Policy != value { return fmt.Errorf("bad: %#v", resp) } return nil }, } }
// ParseENV parse environment only func (c *FlagEnv) ParseENV(v interface{}) error { data := make(map[string]interface{}) for camelName, f := range c.flags { switch f.flagType { case stringFlag: data[camelName] = ENVString(f.envName, f.defStr) case stringSliceFlag: data[camelName] = ENVStringSlice(f.name, f.defStrSlice) case intFlag: data[camelName] = ENVInt(f.name, f.defInt) case intSliceFlag: data[camelName] = ENVIntSlice(f.name, f.defIntSlice) case float64Flag: data[camelName] = ENVFloat64(f.name, f.defFloat64) case boolFlag: data[camelName] = ENVBool(f.name, f.defBool) case durationFlag: data[camelName] = ENVDuration(f.name, f.defDuration) } } mapstructure.Decode(data, v) return nil }
// See the CloudServersProvider interface for details. func (gsp *genericServersProvider) ServerById(id string) (*Server, error) { var s *Server err := gsp.context.WithReauth(gsp.access, func() error { url := gsp.endpoint + "/servers/" + id return perigee.Get(url, perigee.Options{ Results: &struct{ Server **Server }{&s}, MoreHeaders: map[string]string{ "X-Auth-Token": gsp.access.AuthToken(), }, OkCodes: []int{200}, }) }) // Compatibility with v0.0.x -- we "map" our public and private // addresses into a legacy structure field for the benefit of // earlier software. if err != nil { return s, err } err = mapstructure.Decode(s.RawAddresses, &s.Addresses) return s, err }
// See the CloudServersProvider interface for details. func (gcp *genericServersProvider) ListServers() ([]Server, error) { var ss []Server err := gcp.context.WithReauth(gcp.access, func() error { url := gcp.endpoint + "/servers/detail" return perigee.Get(url, perigee.Options{ CustomClient: gcp.context.httpClient, Results: &struct{ Servers *[]Server }{&ss}, MoreHeaders: map[string]string{ "X-Auth-Token": gcp.access.AuthToken(), }, }) }) // Compatibility with v0.0.x -- we "map" our public and private // addresses into a legacy structure field for the benefit of // earlier software. if err != nil { return ss, err } for _, s := range ss { err = mapstructure.Decode(s.RawAddresses, &s.Addresses) if err != nil { return ss, err } } return ss, err }
// Extract will retrieve a Config resource from an operation result. func (r commonResult) Extract() (*Config, error) { if r.Err != nil { return nil, r.Err } var response struct { Config Config `mapstructure:"configuration"` } err := mapstructure.Decode(r.Body, &response) val := r.Body.(map[string]interface{})["configuration"].(map[string]interface{}) if t, ok := val["created"].(string); ok && t != "" { creationTime, err := time.Parse(time.RFC3339, t) if err != nil { return &response.Config, err } response.Config.Created = creationTime } if t, ok := val["updated"].(string); ok && t != "" { updatedTime, err := time.Parse(time.RFC3339, t) if err != nil { return &response.Config, err } response.Config.Updated = updatedTime } return &response.Config, err }
// LoadAuthorize gets authorization data with given code func (s *RethinkDBStorage) LoadAuthorize(code string) (*osin.AuthorizeData, error) { result, err := r.Table(authorizeTable).Filter(r.Row.Field("Code").Eq(code)).Run(s.session) if err != nil { return nil, err } defer result.Close() var dataMap map[string]interface{} err = result.One(&dataMap) if err != nil { return nil, err } var client osin.Client clientID := dataMap["Client"].(map[string]interface{})["Id"].(string) client, err = s.GetClient(clientID) if err != nil { return nil, err } dataMap["Client"] = client var dataStruct osin.AuthorizeData err = mapstructure.Decode(dataMap, &dataStruct) if err != nil { return nil, err } return &dataStruct, nil }
// Parse parse environment and flag func (c *FlagEnv) Parse(v interface{}) error { c.parseCli() c.cliApp.Before = func(context *cli.Context) error { data := make(map[string]interface{}) for camelName, f := range c.flags { switch f.flagType { case stringFlag: data[camelName] = context.String(f.name) case stringSliceFlag: data[camelName] = context.StringSlice(f.name) case intFlag: data[camelName] = context.Int(f.name) case intSliceFlag: data[camelName] = context.IntSlice(f.name) case float64Flag: data[camelName] = context.Float64(f.name) case boolFlag: data[camelName] = context.Bool(f.name) case durationFlag: data[camelName] = context.Duration(f.name) } } mapstructure.Decode(data, v) return nil } c.cliApp.RunAndExitOnError() return nil }