// generate Go representation of a security scheme
// it implemented as struct based middleware
326041
func (gs *goSecurity) generate(dir string) error {
	fileName := path.Join(dir, "oauth2_"+gs.Name+"_middleware.go")
	return commons.GenerateFile(gs, "./templates/golang/oauth2_middleware.tmpl", "oauth2_middleware", fileName, true)
}
1183995
func generateConfig() (cfg *gocd.Configuration, err error) {
	cfg = &gocd.Configuration{}
	qs := []*survey.Question{
		{
			Name:     "server",
			Prompt:   &survey.Input{Message: "GoCD Server (should contain '/go/' suffix)"},
			Validate: survey.Required,
		},
		{
			Name:   "username",
			Prompt: &survey.Input{Message: "Client Username"},
		},
		{
			Name:   "password",
			Prompt: &survey.Password{Message: "Client Password"},
		},
		{
			Name:   "skip_ssl_check",
			Prompt: &survey.Confirm{Message: "Skip SSL certificate validation"},
		},
	}

	err = survey.Ask(qs, cfg)
	return
}
778659
func (s SecretForDockerRegistryGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	err := generate.ValidateParams(s.ParamNames(), genericParams)
	if err != nil {
		return nil, err
	}
	delegate := &SecretForDockerRegistryGeneratorV1{}
	hashParam, found := genericParams["append-hash"]
	if found {
		hashBool, isBool := hashParam.(bool)
		if !isBool {
			return nil, fmt.Errorf("expected bool, found :%v", hashParam)
		}
		delegate.AppendHash = hashBool
		delete(genericParams, "append-hash")
	}
	params := map[string]string{}
	for key, value := range genericParams {
		strVal, isString := value.(string)
		if !isString {
			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
		}
		params[key] = strVal
	}
	delegate.Name = params["name"]
	delegate.Username = params["docker-username"]
	delegate.Email = params["docker-email"]
	delegate.Password = params["docker-password"]
	delegate.Server = params["docker-server"]
	return delegate.StructuredGenerate()
}
331531
func (l *remoteKeyClient) Generate(keyName string, curveType crypto.CurveType) (keyAddress crypto.Address, err error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	req := GenRequest{KeyName: keyName, CurveType: curveType.String()}
	l.logger.TraceMsg("Sending Generate request to remote key server: ", fmt.Sprintf("%v", req))
	resp, err := l.kc.GenerateKey(ctx, &req)
	if err != nil {
		l.logger.TraceMsg("Received Generate error response: ", err)
		return crypto.Address{}, err
	}
	l.logger.TraceMsg("Received Generate response to remote key server: ", fmt.Sprintf("%v", resp))
	return crypto.AddressFromHexString(resp.GetAddress())
}
495699
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	codegen.Reserved[g.Target] = true

	os.RemoveAll(g.OutDir)

	if err := os.MkdirAll(g.OutDir, 0755); err != nil {
		return nil, err
	}
	g.genfiles = []string{g.OutDir}
	if err := g.generateContexts(); err != nil {
		return nil, err
	}
	if err := g.generateControllers(); err != nil {
		return nil, err
	}
	if err := g.generateSecurity(); err != nil {
		return nil, err
	}
	if err := g.generateHrefs(); err != nil {
		return nil, err
	}
	if err := g.generateMediaTypes(); err != nil {
		return nil, err
	}
	if err := g.generateUserTypes(); err != nil {
		return nil, err
	}
	if !g.NoTest {
		if err := g.generateResourceTest(); err != nil {
			return nil, err
		}
	}

	return g.genfiles, nil
}
693110
func (self *SimpleSessionManager) Generate(uniq string) (interface{}, error) {
	if self.generator == nil {
		return nil, nil
	}
	return self.generator.Generate(uniq)
}
1145189
func (v *vaultService) GenerateKey(keyID string, ctx Context) (key [32]byte, sealedKey []byte, err error) {
	var contextStream bytes.Buffer
	ctx.WriteTo(&contextStream)

	payload := map[string]interface{}{
		"context": base64.StdEncoding.EncodeToString(contextStream.Bytes()),
	}
	s, err := v.client.Logical().Write(fmt.Sprintf("/transit/datakey/plaintext/%s", keyID), payload)
	if err != nil {
		return key, sealedKey, err
	}
	sealKey := s.Data["ciphertext"].(string)
	plainKey, err := base64.StdEncoding.DecodeString(s.Data["plaintext"].(string))
	if err != nil {
		return key, sealedKey, err
	}
	copy(key[:], []byte(plainKey))
	return key, []byte(sealKey), nil
}
281679
func Generate() (files []string, err error) {
	var outDir, ver string
	set := flag.NewFlagSet("app", flag.PanicOnError)
	set.StringVar(&outDir, "out", "", "")
	set.StringVar(&ver, "version", "", "")
	set.String("design", "", "")
	set.Parse(os.Args[1:])

	if err := codegen.CheckVersion(ver); err != nil {
		return nil, err
	}

	g := &Generator{OutDir: outDir, API: design.Design}

	return g.Generate()
}
1202822
func (g NamespaceGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	err := generate.ValidateParams(g.ParamNames(), genericParams)
	if err != nil {
		return nil, err
	}
	params := map[string]string{}
	for key, value := range genericParams {
		strVal, isString := value.(string)
		if !isString {
			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
		}
		params[key] = strVal
	}
	delegate := &NamespaceGeneratorV1{Name: params["name"]}
	return delegate.StructuredGenerate()
}
778982
func (gs *Server) Generate() error {
	if err := commons.CheckDuplicatedTitleTypes(gs.apiDef); err != nil {
		return err
	}
	if gs.RootImportPath == "" {
		return fmt.Errorf("invalid import path = empty. please set --import-path or set target dir under gopath")
	}
	// helper package
	gh := goramlHelper{
		rootImportPath: gs.RootImportPath,
		packageName:    "goraml",
		packageDir:     "goraml",
	}
	if err := gh.generate(gs.TargetDir); err != nil {
		return err
	}

	if err := generateAllStructs(gs.apiDef, gs.TargetDir); err != nil {
		return err
	}

	// security scheme
	if err := generateSecurity(gs.apiDef.SecuritySchemes, gs.TargetDir, gs.PackageName); err != nil {
		log.Errorf("failed to generate security scheme:%v", err)
		return err
	}

	// genereate resources
	rds, err := gs.generateServerResources(gs.TargetDir)
	if err != nil {
		return err
	}
	gs.ResourcesDef = rds

	// libraries
	if err := generateLibraries(gs.apiDef.Libraries, gs.TargetDir, gs.libsRootURLs); err != nil {
		return err
	}

	// routes
	if err := commons.GenerateFile(gs, "./templates/golang/server_routes.tmpl", "server_routes", filepath.Join(gs.TargetDir, "routes.go"), true); err != nil {
		return err
	}

	// generate main
	if gs.withMain {
		// HTML front page
		if err := commons.GenerateFile(gs, "./templates/index.html.tmpl", "index.html", filepath.Join(gs.TargetDir, "index.html"), false); err != nil {
			return err
		}
		// main file
		return commons.GenerateFile(gs, "./templates/golang/server_main_go.tmpl", "server_main_go", filepath.Join(gs.TargetDir, "main.go"), true)
	}

	return nil
}
869901
func (c *HMACStrategy) Generate() (string, string, error) {
	c.Lock()
	defer c.Unlock()

	if len(c.GlobalSecret) < minimumSecretLength {
		return "", "", errors.Errorf("secret for signing HMAC-SHA256 is expected to be 32 byte long, got %d byte", len(c.GlobalSecret))
	}

	var signingKey [32]byte
	copy(signingKey[:], c.GlobalSecret)

	if c.TokenEntropy < minimumEntropy {
		c.TokenEntropy = minimumEntropy
	}

	// When creating secrets not intended for usage by human users (e.g.,
	// client secrets or token handles), the authorization server should
	// include a reasonable level of entropy in order to mitigate the risk
	// of guessing attacks.  The token value should be >=128 bits long and
	// constructed from a cryptographically strong random or pseudo-random
	// number sequence (see [RFC4086] for best current practice) generated
	// by the authorization server.
	tokenKey, err := RandomBytes(c.TokenEntropy)
	if err != nil {
		return "", "", errors.WithStack(err)
	}

	signature := generateHMAC(tokenKey, &signingKey)

	encodedSignature := b64.EncodeToString(signature)
	encodedToken := fmt.Sprintf("%s.%s", b64.EncodeToString(tokenKey), encodedSignature)
	return encodedToken, encodedSignature, nil
}
41346
func (s *OnboardingService) Generate(ctx context.Context, req *platform.OnboardingRequest) (*platform.OnboardingResults, error) {
	return s.GenerateFn(ctx, req)
}
223034
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	firstNonEmpty := func(args ...string) string {
		for _, value := range args {
			if len(value) > 0 {
				return value
			}
		}
		return ""
	}

	g.Target = firstNonEmpty(g.Target, "client")
	g.ToolDirName = firstNonEmpty(g.ToolDirName, "tool")
	g.Tool = firstNonEmpty(g.Tool, defaultToolName(g.API))

	codegen.Reserved[g.Target] = true

	// Setup output directories as needed
	var pkgDir, toolDir, cliDir string
	{
		if !g.NoTool {
			toolDir = filepath.Join(g.OutDir, g.ToolDirName, g.Tool)
			if _, err = os.Stat(toolDir); err != nil {
				if err = os.MkdirAll(toolDir, 0755); err != nil {
					return
				}
			}

			cliDir = filepath.Join(g.OutDir, g.ToolDirName, "cli")
			if err = os.RemoveAll(cliDir); err != nil {
				return
			}
			if err = os.MkdirAll(cliDir, 0755); err != nil {
				return
			}
		}

		pkgDir = filepath.Join(g.OutDir, g.Target)
		if err = os.RemoveAll(pkgDir); err != nil {
			return
		}
		if err = os.MkdirAll(pkgDir, 0755); err != nil {
			return
		}
	}

	// Setup generation
	var funcs template.FuncMap
	var clientPkg string
	{
		funcs = template.FuncMap{
			"add":                func(a, b int) int { return a + b },
			"cmdFieldType":       cmdFieldType,
			"defaultPath":        defaultPath,
			"escapeBackticks":    escapeBackticks,
			"goify":              codegen.Goify,
			"gotypedef":          codegen.GoTypeDef,
			"gotypedesc":         codegen.GoTypeDesc,
			"gotypename":         codegen.GoTypeName,
			"gotyperef":          codegen.GoTypeRef,
			"gotyperefext":       goTypeRefExt,
			"join":               join,
			"joinStrings":        strings.Join,
			"multiComment":       multiComment,
			"pathParams":         pathParams,
			"pathTemplate":       pathTemplate,
			"signerType":         signerType,
			"tempvar":            codegen.Tempvar,
			"title":              strings.Title,
			"toString":           toString,
			"toValueTypeName":    toValueTypeName,
			"typeName":           typeName,
			"format":             format,
			"handleSpecialTypes": handleSpecialTypes,
		}
		clientPkg, err = codegen.PackagePath(pkgDir)
		if err != nil {
			return
		}
		arrayToStringTmpl = template.Must(template.New("client").Funcs(funcs).Parse(arrayToStringT))
	}

	if !g.NoTool {
		var cliPkg string
		cliPkg, err = codegen.PackagePath(cliDir)
		if err != nil {
			return
		}

		// Generate tool/main.go (only once)
		mainFile := filepath.Join(toolDir, "main.go")
		if _, err := os.Stat(mainFile); err != nil {
			g.genfiles = append(g.genfiles, toolDir)
			if err = g.generateMain(mainFile, clientPkg, cliPkg, funcs); err != nil {
				return nil, err
			}
		}

		// Generate tool/cli/commands.go
		g.genfiles = append(g.genfiles, cliDir)
		if err = g.generateCommands(filepath.Join(cliDir, "commands.go"), clientPkg, funcs); err != nil {
			return
		}
	}

	// Generate client/client.go
	g.genfiles = append(g.genfiles, pkgDir)
	if err = g.generateClient(filepath.Join(pkgDir, "client.go"), clientPkg, funcs); err != nil {
		return
	}

	// Generate client/$res.go and types.go
	if err = g.generateClientResources(pkgDir, clientPkg, funcs); err != nil {
		return
	}

	return g.genfiles, nil
}
471755
func (api *SSHKeyAPI) Generate(name string, passPhrase string, desc string) (*sacloud.SSHKeyGenerated, error) {

	var (
		method = "POST"
		uri    = fmt.Sprintf("%s/generate", api.getResourceURL())
	)

	type genRequest struct {
		Name           string
		GenerateFormat string
		Description    string
		PassPhrase     string
	}

	type request struct {
		SSHKey genRequest
	}
	type response struct {
		*sacloud.ResultFlagValue
		SSHKey *sacloud.SSHKeyGenerated
	}

	body := &request{
		SSHKey: genRequest{
			Name:           name,
			GenerateFormat: "openssh",
			PassPhrase:     passPhrase,
			Description:    desc,
		},
	}

	res := &response{}

	_, err := api.action(method, uri, body, res)
	if err != nil {
		return nil, fmt.Errorf("SSHKeyAPI: generate SSHKey is failed: %s", err)
	}
	return res.SSHKey, nil
}
1083432
func (gc Client) Generate() error {
	if err := commons.CheckDuplicatedTitleTypes(gc.apiDef); err != nil {
		return err
	}
	// helper package
	gh := goramlHelper{
		packageName: "goraml",
		packageDir:  "goraml",
	}
	if err := gh.generate(gc.TargetDir); err != nil {
		return err
	}

	// generate struct
	if err := generateAllStructs(gc.apiDef, gc.TargetDir); err != nil {
		return err
	}

	// libraries
	if err := generateLibraries(gc.libraries, gc.TargetDir, gc.libsRootURLs); err != nil {
		return err
	}

	if err := gc.generateHelperFile(gc.TargetDir); err != nil {
		return err
	}

	if err := gc.generateSecurity(gc.TargetDir); err != nil {
		return err
	}

	if err := gc.generateServices(gc.TargetDir); err != nil {
		return err
	}
	return gc.generateClientFile(gc.TargetDir)
}
139274
func (r *randomGraph) Generate(n int) ([]*triple.Triple, error) {
	maxEdges := r.nodes * r.nodes
	if n > maxEdges {
		return nil, fmt.Errorf("current configuration only allow a max of %d triples (%d requested)", maxEdges, n)
	}
	var trpls []*triple.Triple
	for _, idx := range rand.Perm(maxEdges)[:n] {
		i, j := idx/r.nodes, idx%r.nodes
		t, err := r.newTriple(i, j)
		if err != nil {
			return nil, err
		}
		trpls = append(trpls, t)
	}
	return trpls, nil
}
65229
func (s ConfigMapGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	err := ValidateParams(s.ParamNames(), genericParams)
	if err != nil {
		return nil, err
	}
	delegate := &ConfigMapGeneratorV1{}
	fromFileStrings, found := genericParams["from-file"]
	if found {
		fromFileArray, isArray := fromFileStrings.([]string)
		if !isArray {
			return nil, fmt.Errorf("expected []string, found :%v", fromFileStrings)
		}
		delegate.FileSources = fromFileArray
		delete(genericParams, "from-file")
	}
	fromLiteralStrings, found := genericParams["from-literal"]
	if found {
		fromLiteralArray, isArray := fromLiteralStrings.([]string)
		if !isArray {
			return nil, fmt.Errorf("expected []string, found :%v", fromFileStrings)
		}
		delegate.LiteralSources = fromLiteralArray
		delete(genericParams, "from-literal")
	}
	params := map[string]string{}
	for key, value := range genericParams {
		strVal, isString := value.(string)
		if !isString {
			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
		}
		params[key] = strVal
	}
	delegate.Name = params["name"]
	delegate.Type = params["type"]
	return delegate.StructuredGenerate()
}