// loadResource loads the translations according to the locale
517065
func (t *Translator) loadResource(l string) error {
	ltext, err := lang.LoadLocaleText(l)
	if err != nil {
		return err
	}

	err = json.Unmarshal(ltext, &t.resources)
	if err != nil {
		return errors.New("unable to unmarshall locale data : " + err.Error())
	}

	return nil
}
239819
func doc2resource(doc resourceDoc) (storedResource, error) {
	res, err := doc2basicResource(doc)
	if err != nil {
		return storedResource{}, errors.Trace(err)
	}

	stored := storedResource{
		Resource:    res,
		storagePath: doc.StoragePath,
	}
	return stored, nil
}
820269
func (i18n *I18n) LoadTranslations() map[string]map[string]*Translation {
	var translations = map[string]map[string]*Translation{}

	for i := len(i18n.Backends); i > 0; i-- {
		backend := i18n.Backends[i-1]
		for _, translation := range backend.LoadTranslations() {
			if translations[translation.Locale] == nil {
				translations[translation.Locale] = map[string]*Translation{}
			}
			translations[translation.Locale][translation.Key] = translation
		}
	}
	return translations
}
1291119
func (t *Template) AddResource(name string, resource ResourceProperties) *Resource {
	templateResource := &Resource{Properties: resource}
	t.Resources[name] = templateResource
	return templateResource
}
92568
func (client CSRetryClient) GetResource(req charmstore.ResourceRequest) (charmstore.ResourceData, error) {
	args := client.retryArgs // a copy

	var data charmstore.ResourceData
	args.Func = func() error {
		var err error
		data, err = client.ResourceClient.GetResource(req)
		if err != nil {
			return errors.Trace(err)
		}
		return nil
	}

	var lastErr error
	args.NotifyFunc = func(err error, i int) {
		// Remember the error we're hiding and then retry!
		logger.Warningf("attempt %d/%d to download resource %q from charm store [channel (%v), charm (%v), resource revision (%v)] failed with error (will retry): %v",
			i, client.retryArgs.Attempts, req.Name, req.Channel, req.Charm, req.Revision, err)
		logger.Tracef("resource get error stack: %v", errors.ErrorStack(err))
		lastErr = err
	}

	err := retry.Call(args)
	if retry.IsAttemptsExceeded(err) {
		return data, errors.Annotate(lastErr, "failed after retrying")
	}
	if err != nil {
		return data, errors.Trace(err)
	}

	return data, nil
}
152566
func (ns *Namespace) getResource(cache *filecache.Cache, unmarshal func(b []byte) (bool, error), req *http.Request) error {
	switch req.URL.Scheme {
	case "":
		b, err := getLocal(req.URL.String(), ns.deps.Fs.Source, ns.deps.Cfg)
		if err != nil {
			return err
		}
		_, err = unmarshal(b)
		return err
	default:
		return ns.getRemote(cache, unmarshal, req)
	}
}
702616
func (m *resolversMap) Load(key string) (resolver.Resolver, bool) {
	i, ok := m.data.Load(key)
	if !ok {
		return nil, false
	}
	s, ok := i.(resolver.Resolver)
	return s, ok
}
1230749
func (c *UnitFacadeClient) GetResource(resourceName string) (resource.Resource, io.ReadCloser, error) {
	var response *http.Response
	req, err := api.NewHTTPDownloadRequest(resourceName)
	if err != nil {
		return resource.Resource{}, nil, errors.Annotate(err, "failed to build API request")
	}
	if err := c.Do(req, nil, &response); err != nil {
		return resource.Resource{}, nil, errors.Annotate(err, "HTTP request failed")
	}

	// HACK(katco): Combine this into one request?
	resourceInfo, err := c.getResourceInfo(resourceName)
	if err != nil {
		return resource.Resource{}, nil, errors.Trace(err)
	}

	// TODO(katco): Check headers against resource info
	// TODO(katco): Check in on all the response headers
	return resourceInfo, response.Body, nil
}
732057
func NewResource(p interface{}, selfUri string) *Resource {
	var r Resource

	r.Payload = p

	r.Links = make(LinkRelations)
	r.AddNewLink("self", selfUri)

	r.Embedded = make(Embedded)
	r.Curies = make(map[string]*CurieHandle)

	return &r
}
1189514
func (s *TaskScheduledEventDetails) SetResource(v string) *TaskScheduledEventDetails {
	s.Resource = &v
	return s
}
749796
func (c *Client) GetResource(ctx context.Context, project *string, res *primitives.Resource) (*manifold.Resource, error) {
	rs, err := c.GetResources(ctx, project, []*primitives.Resource{res})
	if err != nil {
		return nil, err
	}

	if len(rs) > 1 {
		// Names are unique per project. If no project is specified it could be
		// that there are multiple resources.
		// TODO: figure out if we can setup a test for this.
		return nil, ErrMultipleResourcesFound
	}

	return rs[0], nil
}
786042
func LoadReader(r io.Reader) error {
	env, err := Read(r)
	if err != nil {
		return err
	}
	LoadMap(env, false)
	return nil
}
214423
func (s *RelationalDatabaseEvent) SetResource(v string) *RelationalDatabaseEvent {
	s.Resource = &v
	return s
}
697112
func (c *TriggerController) syncResource(key string) error {
	if klog.V(4) {
		startTime := time.Now()
		klog.Infof("Started syncing resource %q", key)
		defer func() {
			klog.Infof("Finished syncing resource %q (%v)", key, time.Since(startTime))
		}()
	}

	parts := strings.SplitN(key, "/", 2)
	source := c.triggerSources[parts[0]]
	obj, exists, err := source.Store.GetByKey(parts[1])
	if err != nil {
		return fmt.Errorf("unable to retrieve %s %s from store: %v", parts[0], parts[1], err)
	}
	if !exists {
		return nil
	}

	return source.Reactor.ImageChanged(obj.(runtime.Object), c.tagRetriever)
}
1203460
func (l *Locale) ConfigureQorResource(res resource.Resourcer) {
	if res, ok := res.(*admin.Resource); ok {
		Admin := res.GetAdmin()
		res.UseTheme("l10n")

		if res.Permission == nil {
			res.Permission = roles.NewPermission()
		}
		res.Permission.Allow(roles.CRUD, "locale_admin").Allow(roles.Read, "locale_reader")

		res.Meta(&admin.Meta{Name: "Localization", Type: "localization", Valuer: func(value interface{}, ctx *qor.Context) interface{} {
			var languageCodes []string
			var db = ctx.GetDB()
			var scope = db.NewScope(value)
			db.New().Set("l10n:mode", "unscoped").Model(res.Value).Where(fmt.Sprintf("%v = ?", scope.PrimaryKey()), scope.PrimaryKeyValue()).Pluck("language_code", &languageCodes)
			return utils.SliceUniq(languageCodes)
		}})

		res.OverrideIndexAttrs(func() {
			var attrs = res.ConvertSectionToStrings(res.IndexAttrs())
			var hasLocalization bool
			for _, attr := range attrs {
				if attr == "Localization" || attr == "-Localization" {
					hasLocalization = true
					break
				}
			}

			if hasLocalization {
				res.IndexAttrs(res.IndexAttrs(), "-LanguageCode")
			} else {
				res.IndexAttrs(res.IndexAttrs(), "-LanguageCode", "Localization")
			}
		})
		res.OverrideShowAttrs(func() {
			res.ShowAttrs(res.ShowAttrs(), "-LanguageCode", "-Localization")
		})
		res.NewAttrs(res.NewAttrs(), "-LanguageCode", "-Localization")
		res.EditAttrs(res.EditAttrs(), "-LanguageCode", "-Localization")

		// Set meta permissions
		for _, field := range Admin.DB.NewScope(res.Value).Fields() {
			if isSyncField(field.StructField) {
				if meta := res.GetMeta(field.Name); meta != nil {
					permission := meta.Meta.Permission
					if permission == nil {
						permission = roles.Allow(roles.CRUD, "global_admin").Allow(roles.Read, "locale_reader")
					} else {
						permission = permission.Allow(roles.CRUD, "global_admin").Allow(roles.Read, "locale_reader")
					}

					meta.SetPermission(permission)
				}
			}
		}

		// Roles
		role := res.Permission.Role
		if _, ok := role.Get("global_admin"); !ok {
			role.Register("global_admin", func(req *http.Request, currentUser interface{}) bool {
				if getLocaleFromContext(&qor.Context{Request: req}) == Global {
					for _, locale := range getEditableLocales(req, currentUser) {
						if locale == Global {
							return true
						}
					}
				}
				return false
			})
		}

		if _, ok := role.Get("locale_admin"); !ok {
			role.Register("locale_admin", func(req *http.Request, currentUser interface{}) bool {
				currentLocale := getLocaleFromContext(&qor.Context{Request: req})
				for _, locale := range getEditableLocales(req, currentUser) {
					if locale == currentLocale {
						return true
					}
				}
				return false
			})
		}

		if _, ok := role.Get("locale_reader"); !ok {
			role.Register("locale_reader", func(req *http.Request, currentUser interface{}) bool {
				currentLocale := getLocaleFromContext(&qor.Context{Request: req})
				for _, locale := range getAvailableLocales(req, currentUser) {
					if locale == currentLocale {
						return true
					}
				}
				return false
			})
		}

		// Inject for l10n
		Admin.RegisterViewPath("github.com/qor/l10n/views")

		// Middleware
		Admin.GetRouter().Use(&admin.Middleware{
			Name: "l10n_set_locale",
			Handler: func(context *admin.Context, middleware *admin.Middleware) {
				db := context.GetDB().Set("l10n:locale", getLocaleFromContext(context.Context))
				if mode := context.Request.URL.Query().Get("locale_mode"); mode != "" {
					db = db.Set("l10n:mode", mode)
				}

				usingLanguageCodeAsPrimaryKey := false
				if res := context.Resource; res != nil {
					for idx, primaryField := range res.PrimaryFields {
						if primaryField.Name == "LanguageCode" {
							_, params := res.ToPrimaryQueryParams(res.GetPrimaryValue(context.Request), context.Context)
							if len(params) > idx {
								usingLanguageCodeAsPrimaryKey = true
								db = db.Set("l10n:locale", params[idx])

								// PUT usually used for localize
								if context.Request.Method == "PUT" {
									if _, ok := db.Get("l10n:localize_to"); !ok {
										db = db.Set("l10n:localize_to", getLocaleFromContext(context.Context))
									}
								}
								break
							}
						}
					}
				}

				if !usingLanguageCodeAsPrimaryKey {
					for key, values := range context.Request.URL.Query() {
						if regexp.MustCompile(`primary_key\[.+_language_code\]`).MatchString(key) {
							if len(values) > 0 {
								db = db.Set("l10n:locale", values[0])

								// PUT usually used for localize
								if context.Request.Method == "PUT" || context.Request.Method == "POST" {
									db = db.Set(key, "")
									if _, ok := db.Get("l10n:localize_to"); !ok {
										db = db.Set("l10n:localize_to", getLocaleFromContext(context.Context))
									}
								}
							}
						}
					}
				}

				if context.Request.URL.Query().Get("sorting") != "" {
					db = db.Set("l10n:mode", "locale")
				}
				context.SetDB(db)

				middleware.Next(context)
			},
		})

		// FunMap
		Admin.RegisterFuncMap("current_locale", func(context admin.Context) string {
			return getLocaleFromContext(context.Context)
		})

		Admin.RegisterFuncMap("global_locale", func() string {
			return Global
		})

		Admin.RegisterFuncMap("viewable_locales", func(context admin.Context) []string {
			return getAvailableLocales(context.Request, context.CurrentUser)
		})

		Admin.RegisterFuncMap("editable_locales", func(context admin.Context) []string {
			return getEditableLocales(context.Request, context.CurrentUser)
		})

		Admin.RegisterFuncMap("createable_locales", func(context admin.Context) []string {
			editableLocales := getEditableLocales(context.Request, context.CurrentUser)
			if _, ok := context.Resource.Value.(localeCreatableInterface); ok {
				return editableLocales
			}

			for _, locale := range editableLocales {
				if locale == Global {
					return []string{Global}
				}
			}
			return []string{}
		})

		if res.GetAction("Localize") == nil {
			argumentResource := Admin.NewResource(&LocalizeActionArgument{})
			argumentResource.Meta(&admin.Meta{
				Name: "From",
				Type: "select_one",
				Valuer: func(_ interface{}, context *qor.Context) interface{} {
					return Global
				},
				Collection: func(value interface{}, context *qor.Context) (results [][]string) {
					for _, locale := range getAvailableLocales(context.Request, context.CurrentUser) {
						results = append(results, []string{locale, locale})
					}
					return
				},
			})
			argumentResource.Meta(&admin.Meta{
				Name: "To",
				Type: "select_many",
				Valuer: func(_ interface{}, context *qor.Context) interface{} {
					return []string{getLocaleFromContext(context)}
				},
				Collection: func(value interface{}, context *qor.Context) (results [][]string) {
					for _, locale := range getEditableLocales(context.Request, context.CurrentUser) {
						results = append(results, []string{locale, locale})
					}
					return
				},
			})

			res.Action(&admin.Action{
				Name: "Localize",
				Handler: func(argument *admin.ActionArgument) error {
					var (
						db        = argument.Context.GetDB()
						arg       = argument.Argument.(*LocalizeActionArgument)
						results   = res.NewSlice()
						sqls      []string
						sqlParams []interface{}
					)

					for _, primaryValue := range argument.PrimaryValues {
						primaryQuerySQL, primaryParams := res.ToPrimaryQueryParams(primaryValue, argument.Context.Context)
						sqls = append(sqls, primaryQuerySQL)
						sqlParams = append(sqlParams, primaryParams...)
					}

					db.Set("l10n:locale", arg.From).Where(strings.Join(sqls, " OR "), sqlParams...).Find(results)

					reflectResults := reflect.Indirect(reflect.ValueOf(results))
					for i := 0; i < reflectResults.Len(); i++ {
						for _, to := range arg.To {
							if err := db.Set("l10n:localize_to", to).Unscoped().Save(reflectResults.Index(i).Interface()).Error; err != nil {
								return err
							}
						}
					}
					return nil
				},
				Modes:      []string{"index", "menu_item"},
				Permission: roles.Allow(roles.CRUD, roles.Anyone),
				Resource:   argumentResource,
			})
		}
	}
}
983130
func (formats *Formats) load(url string) error {
	ext := getExt(url)
	if loader, ok := Files.formats[ext]; ok {
		f, err := openFile(filepath.Join(formats.root, url))
		if err != nil {
			return fmt.Errorf("unable to open resource: %s", err)
		}
		defer f.Close()

		return loader.Load(url, f)
	}
	return fmt.Errorf("no `FileLoader` associated with this extension: %q in url %q", ext, url)
}
665786
func (d *Deps) LoadResources() error {
	// Note that the translations need to be loaded before the templates.
	if err := d.translationProvider.Update(d); err != nil {
		return err
	}

	if err := d.templateProvider.Update(d); err != nil {
		return err
	}

	return nil
}