func (cmd *UpdateUserProvidedService) Execute(c flags.FlagContext) {
	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()
	if !serviceInstance.IsUserProvided() {
		cmd.ui.Failed(T("Service Instance is not user provided"))
		return
	}

	drainUrl := c.String("l")
	credentials := strings.Trim(c.String("p"), `'"`)
	routeServiceUrl := c.String("r")

	credentialsMap := make(map[string]interface{})

	if c.IsSet("p") {
		jsonBytes, err := util.GetContentsFromFlagValue(credentials)
		if err != nil && strings.HasPrefix(credentials, "@") {
			cmd.ui.Failed(err.Error())
		}

		if bytes.IndexAny(jsonBytes, "[{") != -1 {
			err = json.Unmarshal(jsonBytes, &credentialsMap)
			if err != nil {
				cmd.ui.Failed(T("JSON is invalid: {{.ErrorDescription}}", map[string]interface{}{"ErrorDescription": err.Error()}))
			}
		} else {
			for _, param := range strings.Split(credentials, ",") {
				param = strings.Trim(param, " ")
				credentialsMap[param] = cmd.ui.Ask("%s", param)
			}
		}
	}

	cmd.ui.Say(T("Updating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceName": terminal.EntityNameColor(serviceInstance.Name),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	serviceInstance.Params = credentialsMap
	serviceInstance.SysLogDrainUrl = drainUrl
	serviceInstance.RouteServiceUrl = routeServiceUrl

	apiErr := cmd.userProvidedServiceInstanceRepo.Update(serviceInstance.ServiceInstanceFields)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
	cmd.ui.Say(T("TIP: Use '{{.CFRestageCommand}}' for any bound apps to ensure your env variable changes take effect",
		map[string]interface{}{
			"CFRestageCommand": terminal.CommandColor(cf.Name() + " restage"),
		}))

	if routeServiceUrl == "" && credentials == "" && drainUrl == "" {
		cmd.ui.Warn(T("No flags specified. No changes were made."))
	}
}
func (cmd *UpdateUserProvidedService) Execute(c flags.FlagContext) error {
	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()
	if !serviceInstance.IsUserProvided() {
		return errors.New(T("Service Instance is not user provided"))
	}

	drainURL := c.String("l")
	credentials := strings.Trim(c.String("p"), `'"`)
	routeServiceURL := c.String("r")

	credentialsMap := make(map[string]interface{})

	if c.IsSet("p") {
		jsonBytes, err := util.GetContentsFromFlagValue(credentials)
		if err != nil {
			return err
		}

		err = json.Unmarshal(jsonBytes, &credentialsMap)
		if err != nil {
			for _, param := range strings.Split(credentials, ",") {
				param = strings.Trim(param, " ")
				credentialsMap[param] = cmd.ui.Ask(param)
			}
		}
	}

	cmd.ui.Say(T("Updating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceName": terminal.EntityNameColor(serviceInstance.Name),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	serviceInstance.Params = credentialsMap
	serviceInstance.SysLogDrainURL = drainURL
	serviceInstance.RouteServiceURL = routeServiceURL

	err := cmd.userProvidedServiceInstanceRepo.Update(serviceInstance.ServiceInstanceFields)
	if err != nil {
		return err
	}

	cmd.ui.Ok()
	cmd.ui.Say(T("TIP: Use '{{.CFRestageCommand}}' for any bound apps to ensure your env variable changes take effect",
		map[string]interface{}{
			"CFRestageCommand": terminal.CommandColor(cf.Name + " restage"),
		}))

	if routeServiceURL == "" && credentials == "" && drainURL == "" {
		cmd.ui.Warn(T("No flags specified. No changes were made."))
	}
	return nil
}
Esempio n. 3
0
func (cmd *BindRouteService) Execute(c flags.FlagContext) error {
	var port int

	host := c.String("hostname")
	domain := cmd.domainReq.GetDomain()
	path := c.String("path")
	if !strings.HasPrefix(path, "/") && len(path) > 0 {
		path = fmt.Sprintf("/%s", path)
	}

	var parameters string

	if c.IsSet("parameters") {
		jsonBytes, err := util.GetContentsFromFlagValue(c.String("parameters"))
		if err != nil {
			return err
		}
		parameters = string(jsonBytes)
	}

	route, err := cmd.routeRepo.Find(host, domain, path, port)
	if err != nil {
		return err
	}

	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()

	cmd.ui.Say(T("Binding route {{.URL}} to service instance {{.ServiceInstanceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceInstanceName": terminal.EntityNameColor(serviceInstance.Name),
			"URL":         terminal.EntityNameColor(route.URL()),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	err = cmd.routeServiceBindingRepo.Bind(serviceInstance.GUID, route.GUID, serviceInstance.IsUserProvided(), parameters)
	if err != nil {
		if httpErr, ok := err.(errors.HTTPError); ok && httpErr.ErrorCode() == errors.ServiceInstanceAlreadyBoundToSameRoute {
			cmd.ui.Warn(T("Route {{.URL}} is already bound to service instance {{.ServiceInstanceName}}.",
				map[string]interface{}{
					"URL": route.URL(),
					"ServiceInstanceName": serviceInstance.Name,
				}))
		} else {
			return err
		}
	}

	cmd.ui.Ok()
	return nil
}
Esempio n. 4
0
func (cmd *Curl) Execute(c flags.FlagContext) {
	path := c.Args()[0]
	method := c.String("X")
	headers := c.StringSlice("H")
	var body string
	if c.IsSet("d") {
		jsonBytes, err := util.GetContentsFromFlagValue(c.String("d"))
		if err != nil {
			cmd.ui.Failed(err.Error())
		}
		body = string(jsonBytes)
	}
	verbose := c.Bool("v")

	reqHeader := strings.Join(headers, "\n")

	if verbose {
		trace.EnableTrace()
	}

	responseHeader, responseBody, apiErr := cmd.curlRepo.Request(method, path, reqHeader, body)
	if apiErr != nil {
		cmd.ui.Failed(T("Error creating request:\n{{.Err}}", map[string]interface{}{"Err": apiErr.Error()}))
	}

	if verbose {
		return
	}

	if c.Bool("i") {
		cmd.ui.Say(responseHeader)
	}

	if c.String("output") != "" {
		err := cmd.writeToFile(responseBody, c.String("output"))
		if err != nil {
			cmd.ui.Failed(T("Error creating request:\n{{.Err}}", map[string]interface{}{"Err": err}))
		}
	} else {
		if strings.Contains(responseHeader, "application/json") {
			buffer := bytes.Buffer{}
			err := json.Indent(&buffer, []byte(responseBody), "", "   ")
			if err == nil {
				responseBody = buffer.String()
			}
		}

		cmd.ui.Say(responseBody)
	}
	return
}
func (cmd *CreateUserProvidedService) Execute(c flags.FlagContext) {
	name := c.Args()[0]
	drainUrl := c.String("l")
	routeServiceUrl := c.String("r")
	credentials := strings.Trim(c.String("p"), `"'`)
	credentialsMap := make(map[string]interface{})

	if c.IsSet("p") {
		jsonBytes, err := util.GetContentsFromFlagValue(credentials)
		if err != nil && strings.HasPrefix(credentials, "@") {
			cmd.ui.Failed(err.Error())
		}

		if bytes.IndexAny(jsonBytes, "[{") != -1 {
			err = json.Unmarshal(jsonBytes, &credentialsMap)
			if err != nil {
				cmd.ui.Failed(err.Error())
			}
		} else {
			for _, param := range strings.Split(credentials, ",") {
				param = strings.Trim(param, " ")
				credentialsMap[param] = cmd.ui.Ask("%s", param)
			}
		}
	}

	cmd.ui.Say(T("Creating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceName": terminal.EntityNameColor(name),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	err := cmd.userProvidedServiceInstanceRepo.Create(name, drainUrl, routeServiceUrl, credentialsMap)
	if err != nil {
		cmd.ui.Failed(err.Error())
		return
	}

	cmd.ui.Ok()
}
func (cmd *BindRouteService) Execute(c flags.FlagContext) {
	host := c.String("hostname")
	domain := cmd.domainReq.GetDomain()
	path := "" // path is not currently supported
	var parameters string

	if c.IsSet("parameters") {
		jsonBytes, err := util.GetContentsFromFlagValue(c.String("parameters"))
		if err != nil {
			cmd.ui.Failed(err.Error())
		}
		parameters = string(jsonBytes)
	}

	route, err := cmd.routeRepo.Find(host, domain, path)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()
	if !serviceInstance.IsUserProvided() {
		var requiresRouteForwarding bool
		for _, requirement := range serviceInstance.ServiceOffering.Requires {
			if requirement == "route_forwarding" {
				requiresRouteForwarding = true
				break
			}
		}

		confirmed := c.Bool("force")
		if requiresRouteForwarding && !confirmed {
			confirmed = cmd.ui.Confirm(T("Binding may cause requests for route {{.URL}} to be altered by service instance {{.ServiceInstanceName}}. Do you want to proceed?",
				map[string]interface{}{
					"URL": route.URL(),
					"ServiceInstanceName": serviceInstance.Name,
				}))

			if !confirmed {
				cmd.ui.Warn(T("Bind cancelled"))
				return
			}
		}
	}

	cmd.ui.Say(T("Binding route {{.URL}} to service instance {{.ServiceInstanceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceInstanceName": terminal.EntityNameColor(serviceInstance.Name),
			"URL":         terminal.EntityNameColor(route.URL()),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	err = cmd.routeServiceBindingRepo.Bind(serviceInstance.Guid, route.Guid, serviceInstance.IsUserProvided(), parameters)
	if err != nil {
		if httpErr, ok := err.(errors.HttpError); ok && httpErr.ErrorCode() == errors.ROUTE_ALREADY_BOUND_TO_SAME_SERVICE {
			cmd.ui.Warn(T("Route {{.URL}} is already bound to service instance {{.ServiceInstanceName}}.",
				map[string]interface{}{
					"URL": route.URL(),
					"ServiceInstanceName": serviceInstance.Name,
				}))
		} else {
			cmd.ui.Failed(err.Error())
		}
	}

	cmd.ui.Ok()
}
	"github.com/cloudfoundry/cli/cf/util"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("JSONHelpers", func() {
	Describe("GetContentsFromFlagValue", func() {
		It("returns bytes when given a file name prefixed with @", func() {
			tempfile, err := ioutil.TempFile("", "get-data-test")
			Expect(err).NotTo(HaveOccurred())
			fileData := `{"foo": "bar"}`
			ioutil.WriteFile(tempfile.Name(), []byte(fileData), os.ModePerm)

			bs, err := util.GetContentsFromFlagValue("@" + tempfile.Name())
			Expect(err).NotTo(HaveOccurred())
			Expect(bs).To(Equal([]byte(fileData)))
		})

		It("returns an error when given an empty string", func() {
			_, err := util.GetContentsFromFlagValue("")
			Expect(err).To(HaveOccurred())
		})

		It("returns bytes when given a file name not prefixed with @", func() {
			tempfile, err := ioutil.TempFile("", "get-data-test")
			Expect(err).NotTo(HaveOccurred())
			fileData := `{"foo": "bar"}`
			ioutil.WriteFile(tempfile.Name(), []byte(fileData), os.ModePerm)