// executeRequest executes the given request and checks the Response. For
// responses with non-2XX status, the body is read and closed, and an error is
// returned. If the error is nil, the caller must ensure that the response body
// is closed.
350053
func (c *InternalClient) executeRequest(req *http.Request) (*http.Response, error) {
	tracing.GlobalTracer.InjectHTTPHeaders(req)
	resp, err := c.httpClient.Do(req)
	if err != nil {
		if resp != nil {
			resp.Body.Close()
		}
		return nil, errors.Wrap(err, "getting response")
	}
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		defer resp.Body.Close()
		buf, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return resp, errors.Wrapf(err, "bad status '%s' and err reading body", resp.Status)
		}
		var msg string
		// try to decode a JSON response
		var sr successResponse
		if err = json.Unmarshal(buf, &sr); err == nil {
			msg = sr.Error.Error()
		} else {
			msg = string(buf)
		}
		return resp, errors.Errorf("server error %s: '%s'", resp.Status, msg)
	}
	return resp, nil
}
426878
func (c *Client) sendRequest(req request) (*jh.ResponseData, error) {
	request := jh.RequestData{
		ReqValue:   req.reqValue,
		ReqHeaders: req.reqHeader,
		ReqReader:  req.reqReader,
		ReqLength:  req.reqLength,
	}
	if req.expectedStatus == 0 {
		req.expectedStatus = http.StatusOK
	}
	respData := jh.ResponseData{
		RespValue:      req.resp,
		RespHeaders:    req.respHeader,
		ExpectedStatus: []int{req.expectedStatus},
	}
	err := c.client.SendRequest(req.method, req.url, "", &request, &respData)
	return &respData, err
}
774347
func (q *query) Execute(ctx context.Context, request *querypb.ExecuteRequest) (response *querypb.ExecuteResponse, err error) {
	defer q.server.HandlePanic(&err)
	ctx = callerid.NewContext(callinfo.GRPCCallInfo(ctx),
		request.EffectiveCallerId,
		request.ImmediateCallerId,
	)
	result, err := q.server.Execute(ctx, request.Target, request.Query.Sql, request.Query.BindVariables, request.TransactionId, request.Options)
	if err != nil {
		return nil, vterrors.ToGRPC(err)
	}
	return &querypb.ExecuteResponse{
		Result: sqltypes.ResultToProto3(result),
	}, nil
}
1106159
func (s *Store) execute(c *Connection, ex *ExecuteRequest) (*ExecuteResponse, error) {
	if c == nil {
		s.connsMu.RLock()
		c = s.conns[defaultConnID]
		s.connsMu.RUnlock()
	}
	c.SetLastUsedNow()

	start := time.Now()

	d := &databaseSub{
		ConnID:  c.ID,
		Atomic:  ex.Atomic,
		Queries: ex.Queries,
		Timings: ex.Timings,
	}
	cmd, err := newCommand(execute, d)
	if err != nil {
		return nil, err
	}
	b, err := json.Marshal(cmd)
	if err != nil {
		return nil, err
	}

	f := s.raft.Apply(b, s.ApplyTimeout)
	if e := f.(raft.Future); e.Error() != nil {
		if e.Error() == raft.ErrNotLeader {
			return nil, ErrNotLeader
		}
		return nil, e.Error()
	}

	switch r := f.Response().(type) {
	case *fsmExecuteResponse:
		return &ExecuteResponse{
			Results: r.results,
			Time:    time.Since(start).Seconds(),
			Raft:    RaftResponse{f.Index(), s.raftID},
		}, r.error
	case *fsmGenericResponse:
		return nil, r.error
	default:
		panic("unsupported type")
	}
}
129540
func (c *Client) Execute(command string) (response *Packet, err error) {
	return c.Send(Exec, command)
}
477388
func Execute(a *Action) error {
	seen := make(map[*Action]error)
	return execute(seen, a)
}
634002
func (a *API) executeCommand(f func(map[string]interface{}) interface{},
	res http.ResponseWriter,
	req *http.Request,
) {

	body := make(map[string]interface{})
	json.NewDecoder(req.Body).Decode(&body)

	if f != nil {
		a.writeJSON(map[string]interface{}{"result": f(body)}, res)
	} else {
		a.writeJSON(map[string]interface{}{"error": "Unknown Command"}, res)
	}
}
1188878
func (api *KrakenApi) doRequest(reqURL string, values url.Values, headers map[string]string, typ interface{}) (interface{}, error) {

	// Create request
	req, err := http.NewRequest("POST", reqURL, strings.NewReader(values.Encode()))
	if err != nil {
		return nil, fmt.Errorf("Could not execute request! #1 (%s)", err.Error())
	}

	req.Header.Add("User-Agent", APIUserAgent)
	for key, value := range headers {
		req.Header.Add(key, value)
	}

	// Execute request
	resp, err := api.client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("Could not execute request! #2 (%s)", err.Error())
	}
	defer resp.Body.Close()

	// Read request
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("Could not execute request! #3 (%s)", err.Error())
	}

	// Check mime type of response
	mimeType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
	if err != nil {
		return nil, fmt.Errorf("Could not execute request #4! (%s)", err.Error())
	}
	if mimeType != "application/json" {
		return nil, fmt.Errorf("Could not execute request #5! (%s)", fmt.Sprintf("Response Content-Type is '%s', but should be 'application/json'.", mimeType))
	}

	// Parse request
	var jsonData KrakenResponse

	// Set the KrakenResponse.Result to typ so `json.Unmarshal` will
	// unmarshal it into given type, instead of `interface{}`.
	if typ != nil {
		jsonData.Result = typ
	}

	err = json.Unmarshal(body, &jsonData)
	if err != nil {
		return nil, fmt.Errorf("Could not execute request! #6 (%s)", err.Error())
	}

	// Check for Kraken API error
	if len(jsonData.Error) > 0 {
		return nil, fmt.Errorf("Could not execute request! #7 (%s)", jsonData.Error)
	}

	return jsonData.Result, nil
}
629529
func (tsv *TabletServer) execRequest(
	ctx context.Context, timeout time.Duration,
	requestName, sql string, bindVariables map[string]*querypb.BindVariable,
	target *querypb.Target, options *querypb.ExecuteOptions, isBegin, allowOnShutdown bool,
	exec func(ctx context.Context, logStats *tabletenv.LogStats) error,
) (err error) {
	span, ctx := trace.NewSpan(ctx, "TabletServer."+requestName)
	if options != nil {
		span.Annotate("isolation-level", options.TransactionIsolation)
	}
	trace.AnnotateSQL(span, sql)
	if target != nil {
		span.Annotate("cell", target.Cell)
		span.Annotate("shard", target.Shard)
		span.Annotate("keyspace", target.Keyspace)
	}
	defer span.Finish()

	logStats := tabletenv.NewLogStats(ctx, requestName)
	logStats.Target = target
	logStats.OriginalSQL = sql
	logStats.BindVariables = bindVariables
	defer tsv.handlePanicAndSendLogStats(sql, bindVariables, logStats)
	if err = tsv.startRequest(ctx, target, isBegin, allowOnShutdown); err != nil {
		return err
	}

	ctx, cancel := withTimeout(ctx, timeout, options)
	defer func() {
		cancel()
		tsv.endRequest(isBegin)
	}()

	err = exec(ctx, logStats)
	if err != nil {
		return tsv.convertAndLogError(ctx, sql, bindVariables, err, logStats)
	}
	return nil
}
133176
func (tl *TestLauncher) ExecuteQuery(q string) (*QueryResults, error) {
	fq, err := tl.QueryController().Query(context.Background(), &query.Request{
		Authorization:  tl.Auth,
		OrganizationID: tl.Auth.OrgID,
		Compiler: lang.FluxCompiler{
			Query: q,
		}})
	if err != nil {
		return nil, err
	}

	results := make([]flux.Result, 0, 1)
	for res := range fq.Results() {
		results = append(results, res)
	}

	if err := fq.Err(); err != nil {
		fq.Done()
		return nil, err
	}

	return &QueryResults{
		Results: results,
		Query:   fq,
	}, nil
}
938593
func (c *Client) request(params *url.Values, v *Response) error {
	var body string
	if params != nil {
		body = params.Encode()
	}

	method := "GET"
	requestURL := fmt.Sprintf("%v/?%s", c.BaseURL, body)
	var requestBody io.Reader
	if c.UsePost {
		method = "POST"
		requestURL = c.BaseURL.String()
		requestBody = strings.NewReader(body)
	}
	request, err := http.NewRequest(method, requestURL, requestBody)
	if err != nil {
		return err
	}

	log.Debugf("HTTP REQUEST: %s %s %s", method, requestURL, body)

	if c.UsePost {
		request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}
	request.Header.Add("Accept", "application/json")
	request.Header.Add("User-Agent", "LinodeGo/"+ClientVersion+" Go/"+runtime.Version())

	response, err := c.HTTPClient.Do(request)
	if err != nil {
		log.Errorf("Failed to get API response: %v", err)
		return err
	}

	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Errorf("Failed to parse API response: %v", err)
		return err
	}

	log.Debugf("HTTP RESPONSE: %s", string(responseBody))

	// Status code 500 is a server error and means nothing can be done at this point.
	if response.StatusCode != 200 {
		return ErrUnexpectedResponse
	}

	if err = json.Unmarshal(responseBody, v); err != nil {
		return err
	}

	if len(v.Errors) > 0 {
		if v.Errors[0].ErrorCode == 4 {
			return ErrAuthentication
		}
		// Need to return all errors to client. Perhaps wrap the error structure as a property for a custom error class
		return errors.New(fmt.Sprintf("API Error: %s, Code %d", v.Errors[0].ErrorMessage, v.Errors[0].ErrorCode))
	}

	return nil
}
95715
func (q *lockBasedQueryExecutor) ExecuteQuery(namespace, query string) (commonledger.ResultsIterator, error) {
	return q.helper.executeQuery(namespace, query)
}
420497
func (a *netAPI) doRequest(ctx context.Context, requestPath string, req proto.Message, resp proto.Message) error {
	p, err := proto.Marshal(req)
	if err != nil {
		return err
	}

	u := *a.url // Make a copy of URL
	u.Path = requestPath
	httpReq, err := http.NewRequest("POST", u.String(), bytes.NewReader(p))
	httpReq.Header.Add("Content-Type", "application/x-protobuf")
	httpReq = httpReq.WithContext(ctx)
	httpResp, err := a.client.Do(httpReq)
	if err != nil {
		return err
	}
	defer httpResp.Body.Close()
	if httpResp.StatusCode != 200 {
		return fmt.Errorf("safebrowsing: unexpected server response code: %d", httpResp.StatusCode)
	}
	body, err := ioutil.ReadAll(httpResp.Body)
	if err != nil {
		return err
	}
	return proto.Unmarshal(body, resp)
}
321448
func (jolokiaClient *JolokiaClient) executePostRequestCallback(pattern string, wrapper func() ([]byte, error)) (string, error) {
	jsonReq, wrapError := wrapper()
	if wrapError != nil {
		return "", fmt.Errorf("JSON Wrap Failed: %v", wrapError)
	}
	requestUrl := jolokiaClient.url
	if pattern != "" {
		requestUrl = requestUrl + "/?" + pattern
	}
	request := &httpRequest{Url: requestUrl, Body: jsonReq}
	response, httpErr := performPostRequest(request, jolokiaClient.user, jolokiaClient.pass)
	if httpErr != nil {
		return "", fmt.Errorf("HTTP Request Failed: %v", httpErr)
	}
	if response.StatusCode != 200 {
		return "", fmt.Errorf("HTTP Request Error Code: %v", response.Status)
	}
	jolokiaResponse := string(response.Body)
	return jolokiaResponse, nil
}
1099199
func (as *AgentServer) Execute(request *pb.ExecutionRequest, stream pb.GleamAgent_ExecuteServer) error {

	dir := path.Join(*as.Option.Dir, fmt.Sprintf("%d", request.GetInstructionSet().GetFlowHashCode()), request.GetDir())
	os.MkdirAll(dir, 0755)

	allocated := *request.GetResource()

	as.plusAllocated(allocated)
	defer as.minusAllocated(allocated)

	request.InstructionSet.AgentAddress = fmt.Sprintf("%s:%d", *as.Option.Host, *as.Option.Port)

	statsChan := createStatsChanByInstructionSet(request.InstructionSet)

	defer deleteStatsChanByInstructionSet(request.InstructionSet)

	return as.executeCommand(stream, request, dir, statsChan)

}
1275871
func (c *Client) Request(verb, p string, ro *RequestOptions) (*http.Response, error) {
	req, err := c.RawRequest(verb, p, ro)
	if err != nil {
		return nil, err
	}

	resp, err := checkResp(c.HTTPClient.Do(req))
	if err != nil {
		return resp, err
	}

	return resp, nil
}
381053
func HTTPRequest(err error) (*http.Request, bool) {
	type httpError interface {
		HTTPRequest() *http.Request
	}

	var req *http.Request

	emperror.ForEachCause(err, func(err error) bool {
		if httpErr, ok := err.(httpError); ok {
			req = httpErr.HTTPRequest()

			return false
		}

		return true
	})

	return req, req != nil
}