// NewUndertakerAPI creates a new instance of the undertaker API.
322808
func NewUndertakerAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*UndertakerAPI, error) {
	m, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}

	return newUndertakerAPI(&stateShim{st, m}, resources, authorizer)
}
405245
func (c *Client) NewRequest(s string) (*http.Request, error) {
	rel, err := url.Parse(c.BasePath + s)
	if err != nil {
		return nil, err
	}

	q := rel.Query()
	q.Set("api_key", c.APIKey)
	q.Set("rating", c.Rating)
	rel.RawQuery = q.Encode()

	u := c.BaseURL.ResolveReference(rel)

	if EnvBool("GIPHY_VERBOSE", false) {
		fmt.Println("giphy: GET", u.String())
	}

	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, err
	}

	req.Header.Add("User-Agent", c.UserAgent)
	return req, nil
}
678976
func NewUniterAPI(context facade.Context) (*UniterAPI, error) {
	authorizer := context.Auth()
	if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() {
		return nil, common.ErrPerm
	}
	st := context.State()
	resources := context.Resources()
	accessUnit := unitAccessor(authorizer, st)
	leadershipChecker, err := context.LeadershipChecker()
	if err != nil {
		return nil, errors.Trace(err)
	}
	accessApplication := func() (common.AuthFunc, error) {
		switch tag := authorizer.GetAuthTag().(type) {
		case names.ApplicationTag:
			return func(applicationTag names.Tag) bool {
				return tag == applicationTag
			}, nil
		case names.UnitTag:
			entity, err := st.Unit(tag.Id())
			if err != nil {
				return nil, errors.Trace(err)
			}
			applicationName := entity.ApplicationName()
			applicationTag := names.NewApplicationTag(applicationName)
			return func(tag names.Tag) bool {
				return tag == applicationTag
			}, nil
		default:
			return nil, errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag)
		}
	}
	accessMachine := func() (common.AuthFunc, error) {
		switch tag := authorizer.GetAuthTag().(type) {
		// Application agents can't access machines.
		case names.ApplicationTag:
			return func(tag names.Tag) bool {
				return false
			}, nil
		case names.UnitTag:
			entity, err := st.Unit(tag.Id())
			if err != nil {
				return nil, errors.Trace(err)
			}
			machineId, err := entity.AssignedMachineId()
			if err != nil {
				return nil, errors.Trace(err)
			}
			machineTag := names.NewMachineTag(machineId)
			return func(tag names.Tag) bool {
				return tag == machineTag
			}, nil
		default:
			return nil, errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag)
		}
	}
	accessCloudSpec := func() (func() bool, error) {
		var appName string
		var err error

		switch tag := authorizer.GetAuthTag().(type) {
		case names.ApplicationTag:
			appName = tag.Id()
		case names.UnitTag:
			entity, err := st.Unit(tag.Id())
			if err != nil {
				return nil, errors.Trace(err)
			}
			appName = entity.ApplicationName()
		default:
			return nil, errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag)
		}

		app, err := st.Application(appName)
		if err != nil {
			return nil, errors.Trace(err)
		}
		config, err := app.ApplicationConfig()
		if err != nil {
			return nil, errors.Trace(err)
		}
		return func() bool {
			return config.GetBool(application.TrustConfigOptionName, false)
		}, nil
	}

	m, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}

	storageAccessor, err := getStorageState(st)
	storageAPI, err := newStorageAPI(
		stateShim{st}, storageAccessor, resources, accessUnit)
	if err != nil {
		return nil, err
	}
	msAPI, err := meterstatus.NewMeterStatusAPI(st, resources, authorizer)
	if err != nil {
		return nil, errors.Annotate(err, "could not create meter status API handler")
	}
	accessUnitOrApplication := common.AuthAny(accessUnit, accessApplication)

	cloudSpec := cloudspec.NewCloudSpec(
		resources,
		cloudspec.MakeCloudSpecGetterForModel(st),
		cloudspec.MakeCloudSpecWatcherForModel(st),
		common.AuthFuncForTag(m.ModelTag()),
	)

	return &UniterAPI{
		LifeGetter:                 common.NewLifeGetter(st, accessUnitOrApplication),
		DeadEnsurer:                common.NewDeadEnsurer(st, accessUnit),
		AgentEntityWatcher:         common.NewAgentEntityWatcher(st, resources, accessUnitOrApplication),
		APIAddresser:               common.NewAPIAddresser(st, resources),
		ModelWatcher:               common.NewModelWatcher(m, resources, authorizer),
		RebootRequester:            common.NewRebootRequester(st, accessMachine),
		UpgradeSeriesAPI:           common.NewExternalUpgradeSeriesAPI(st, resources, authorizer, accessMachine, accessUnit, logger),
		LeadershipSettingsAccessor: leadershipSettingsAccessorFactory(st, leadershipChecker, resources, authorizer),
		MeterStatus:                msAPI,
		// TODO(fwereade): so *every* unit should be allowed to get/set its
		// own status *and* its application's? This is not a pleasing arrangement.
		StatusAPI: NewStatusAPI(st, accessUnitOrApplication, leadershipChecker),

		st:                st,
		m:                 m,
		auth:              authorizer,
		resources:         resources,
		leadershipChecker: leadershipChecker,
		accessUnit:        accessUnit,
		accessApplication: accessApplication,
		accessMachine:     accessMachine,
		accessCloudSpec:   accessCloudSpec,
		cloudSpec:         cloudSpec,
		StorageAPI:        storageAPI,
	}, nil
}
953995
func NewMockCheckoutCommandAPI(ctrl *gomock.Controller) *MockCheckoutCommandAPI {
	mock := &MockCheckoutCommandAPI{ctrl: ctrl}
	mock.recorder = &MockCheckoutCommandAPIMockRecorder{mock}
	return mock
}
29227
func NewMockDeployStepAPI(ctrl *gomock.Controller) *MockDeployStepAPI {
	mock := &MockDeployStepAPI{ctrl: ctrl}
	mock.recorder = &MockDeployStepAPIMockRecorder{mock}
	return mock
}
943926
func NewAPI(m *gobot.Master) *API {
	return &API{
		master: m,
		router: pat.New(),
		Port:   "3000",
		start: func(a *API) {
			log.Println("Initializing API on " + a.Host + ":" + a.Port + "...")
			http.Handle("/", a)

			go func() {
				if a.Cert != "" && a.Key != "" {
					http.ListenAndServeTLS(a.Host+":"+a.Port, a.Cert, a.Key, nil)
				} else {
					log.Println("WARNING: API using insecure connection. " +
						"We recommend using an SSL certificate with Gobot.")
					http.ListenAndServe(a.Host+":"+a.Port, nil)
				}
			}()
		},
	}
}
798800
func (c *Client) NewMapReduceRequest(request, contentType string) *RpbMapRedReq {
	return &RpbMapRedReq{
		Request:     []byte(request),
		ContentType: []byte(contentType),
	}
}
763375
func NewGreeterAPI(spec *loads.Document) *GreeterAPI {
	return &GreeterAPI{
		handlers:            make(map[string]map[string]http.Handler),
		formats:             strfmt.Default,
		defaultConsumes:     "application/json",
		defaultProduces:     "application/json",
		customConsumers:     make(map[string]runtime.Consumer),
		customProducers:     make(map[string]runtime.Producer),
		ServerShutdown:      func() {},
		spec:                spec,
		ServeError:          errors.ServeError,
		BasicAuthenticator:  security.BasicAuth,
		APIKeyAuthenticator: security.APIKeyAuth,
		BearerAuthenticator: security.BearerAuth,
		JSONConsumer:        runtime.JSONConsumer(),
		TxtProducer:         runtime.TextProducer(),
		GetGreetingHandler: GetGreetingHandlerFunc(func(params GetGreetingParams) middleware.Responder {
			return middleware.NotImplemented("operation GetGreeting has not yet been implemented")
		}),
	}
}
554350
func NewCAASOperatorUpgraderAPI(
	authorizer facade.Authorizer,
	broker caas.Upgrader,
) (*API, error) {
	if !authorizer.AuthController() && !authorizer.AuthApplicationAgent() {
		return nil, common.ErrPerm
	}
	return &API{
		auth:   authorizer,
		broker: broker,
	}, nil
}
1300064
func NewReverseProxy(target *url.URL, fwdPath string) *httputil.ReverseProxy {
	targetQuery := target.RawQuery
	director := func(req *http.Request) {
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host
		if fwdPath == "" {
			// if no forward path specified, use path defined in target + query path
			req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
		} else {
			// use path defined in target + specified forward path
			req.URL.Path = singleJoiningSlash(target.Path, fwdPath)
		}
		if targetQuery == "" || req.URL.RawQuery == "" {
			req.URL.RawQuery = targetQuery + req.URL.RawQuery
		} else {
			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
		}
	}

	return &httputil.ReverseProxy{Director: director}
}
640813
func NewPublicWhisperAPI(w *Whisper) *PublicWhisperAPI {
	api := &PublicWhisperAPI{
		w:        w,
		lastUsed: make(map[string]time.Time),
	}
	return api
}
953765
func NewAPI(
	backend Backend,
	precheckBackend migration.PrecheckBackend,
	pool migration.Pool,
	resources facade.Resources,
	authorizer facade.Authorizer,
	presence facade.Presence,
) (*API, error) {
	if !authorizer.AuthController() {
		return nil, common.ErrPerm
	}
	return &API{
		backend:         backend,
		precheckBackend: precheckBackend,
		pool:            pool,
		authorizer:      authorizer,
		resources:       resources,
		presence:        presence,
	}, nil
}
909439
func NewAPI(caller base.APICaller, tag names.Tag) (*API, error) {
	if caller == nil {
		return nil, fmt.Errorf("caller is nil")
	}

	if tag == nil {
		return nil, fmt.Errorf("tag is nil")
	}

	return &API{
		facade: base.NewFacadeCaller(caller, proxyUpdaterFacade),
		tag:    tag,
	}, nil
}
234869
func newAPI(prefix string, resolver URLResolver, router routing.Routeable) *API {
	// Add initial and trailing slash to prefix
	prefixSlashes := strings.Trim(prefix, "/")
	if len(prefixSlashes) > 0 {
		prefixSlashes = "/" + prefixSlashes + "/"
	} else {
		prefixSlashes = "/"
	}

	info := information{prefix: prefix, resolver: resolver}

	api := &API{
		ContentType:      defaultContentTypHeader,
		router:           router,
		info:             info,
		middlewares:      make([]HandlerFunc, 0),
		contextAllocator: nil,
	}

	api.contextPool.New = func() interface{} {
		if api.contextAllocator != nil {
			return api.contextAllocator(api)
		}
		return api.allocateDefaultContext()
	}

	return api
}
37771
func NewUpgraderAPI(
	st *state.State,
	resources facade.Resources,
	authorizer facade.Authorizer,
) (*UpgraderAPI, error) {
	if !authorizer.AuthMachineAgent() && !authorizer.AuthApplicationAgent() {
		return nil, common.ErrPerm
	}
	getCanReadWrite := func() (common.AuthFunc, error) {
		return authorizer.AuthOwner, nil
	}
	model, err := st.Model()
	if err != nil {
		return nil, err
	}
	urlGetter := common.NewToolsURLGetter(model.UUID(), st)
	configGetter := stateenvirons.EnvironConfigGetter{State: st, Model: model}
	return &UpgraderAPI{
		ToolsGetter: common.NewToolsGetter(st, configGetter, st, urlGetter, getCanReadWrite),
		ToolsSetter: common.NewToolsSetter(st, getCanReadWrite),
		st:          st,
		m:           model,
		resources:   resources,
		authorizer:  authorizer,
	}, nil
}
1356090
func NewDiskAPI(client *Client) *DiskAPI {
	return &DiskAPI{
		&baseAPI{
			client: client,
			// FuncGetResourceURL
			FuncGetResourceURL: func() string {
				return "disk"
			},
		},
	}
}
239888
func NewReceiptFromRLP(data []byte) (*Receipt, error) {
	r := &Receipt{
		receipt: new(types.Receipt),
	}
	if err := rlp.DecodeBytes(common.CopyBytes(data), r.receipt); err != nil {
		return nil, err
	}
	return r, nil
}