// composeResponseMessages takes the ResponseErrors (if any) and creates ResponseMessages from them.
519729
func composeResponseMessages(route restful.Route, decl *ApiDeclaration, config *Config) (messages []ResponseMessage) {
	if route.ResponseErrors == nil {
		return messages
	}
	// sort by code
	codes := sort.IntSlice{}
	for code := range route.ResponseErrors {
		codes = append(codes, code)
	}
	codes.Sort()
	for _, code := range codes {
		each := route.ResponseErrors[code]
		message := ResponseMessage{
			Code:    code,
			Message: each.Message,
		}
		if each.Model != nil {
			st := reflect.TypeOf(each.Model)
			isCollection, st := detectCollectionType(st)
			// collection cannot be in responsemodel
			if !isCollection {
				modelName := modelBuilder{}.keyFrom(st)
				modelBuilder{Models: &decl.Models, Config: config}.addModel(st, "")
				message.ResponseModel = modelName
			}
		}
		messages = append(messages, message)
	}
	return
}
994614
func ReplyInternalError(w http.ResponseWriter, message string) {
	LogRequest(nil, 500, time.Nanosecond, errors.New(message))
	Reply(w, Response{"message": message}, http.StatusInternalServerError)
}
278064
func NewMessageFromRequest(req protocol.Request, replyto string, choria *Framework) (msg *Message, err error) {
	reqm, err := NewMessage(req.Message(), req.Agent(), req.Collective(), "request", nil, choria)
	if err != nil {
		return msg, fmt.Errorf("could not create request message: %s", err)
	}

	if replyto != "" {
		reqm.replyTo = replyto
	}

	msg, err = NewMessage(req.Message(), req.Agent(), req.Collective(), "reply", reqm, choria)
	if err != nil {
		return msg, err
	}

	msg.RequestID = req.RequestID()
	msg.TTL = req.TTL()
	msg.TimeStamp = req.Time()
	msg.Filter, _ = req.Filter()
	msg.SenderID = choria.Config.Identity
	msg.SetBase64Payload(req.Message())
	msg.req = req

	return
}
637751
func ErrorResponse(text string, vargs ...interface{}) *Response {
	if len(vargs) > 0 {
		text = fmt.Sprintf(text, vargs...)
	}
	return &Response{
		Data: map[string]interface{}{
			"error": text,
		},
	}
}
989015
func (o *AddCommentToTaskDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	// response header X-Error-Code

	xErrorCode := o.XErrorCode
	if xErrorCode != "" {
		rw.Header().Set("X-Error-Code", xErrorCode)
	}

	rw.WriteHeader(o._statusCode)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}
217385
func (r *HttpResponse) ResponseError() error {
	class := r.StatusCode / 100
	if class != 2 && class != 3 {
		rt := 0

		if h := r.Header.Get("Retry-After"); h != "" {
			rt, _ = strconv.Atoi(h)
		}

		var body [256]byte
		var blen int

		if r.Body != nil {
			blen, _ = r.Body.Read(body[:])
		}

		return HttpError{Code: r.StatusCode,
			Message:    "HTTP " + r.Status,
			RetryAfter: rt,
			Header:     r.Header,
			Body:       body[:blen],
		}
	}

	return nil
}
868259
func replyWithError(w http.ResponseWriter, status, message string, args ...interface{}) error {
	return replyWithJSON(w, map[string]string{
		"status":        status,
		"error_message": fmt.Sprintf(message, args...),
	})
}
1287775
func (api *PublicWhisperAPI) Messages(ctx context.Context, crit Criteria) (*rpc.Subscription, error) {
	var (
		symKeyGiven = len(crit.SymKeyID) > 0
		pubKeyGiven = len(crit.PrivateKeyID) > 0
		err         error
	)

	// ensure that the RPC connection supports subscriptions
	notifier, supported := rpc.NotifierFromContext(ctx)
	if !supported {
		return nil, rpc.ErrNotificationsUnsupported
	}

	// user must specify either a symmetric or an asymmetric key
	if (symKeyGiven && pubKeyGiven) || (!symKeyGiven && !pubKeyGiven) {
		return nil, ErrSymAsym
	}

	filter := Filter{
		PoW:      crit.MinPow,
		Messages: make(map[common.Hash]*ReceivedMessage),
		AllowP2P: crit.AllowP2P,
	}

	if len(crit.Sig) > 0 {
		if filter.Src, err = crypto.UnmarshalPubkey(crit.Sig); err != nil {
			return nil, ErrInvalidSigningPubKey
		}
	}

	for i, bt := range crit.Topics {
		if len(bt) == 0 || len(bt) > 4 {
			return nil, fmt.Errorf("subscribe: topic %d has wrong size: %d", i, len(bt))
		}
		filter.Topics = append(filter.Topics, bt[:])
	}

	// listen for message that are encrypted with the given symmetric key
	if symKeyGiven {
		if len(filter.Topics) == 0 {
			return nil, ErrNoTopics
		}
		key, err := api.w.GetSymKey(crit.SymKeyID)
		if err != nil {
			return nil, err
		}
		if !validateDataIntegrity(key, aesKeyLength) {
			return nil, ErrInvalidSymmetricKey
		}
		filter.KeySym = key
		filter.SymKeyHash = crypto.Keccak256Hash(filter.KeySym)
	}

	// listen for messages that are encrypted with the given public key
	if pubKeyGiven {
		filter.KeyAsym, err = api.w.GetPrivateKey(crit.PrivateKeyID)
		if err != nil || filter.KeyAsym == nil {
			return nil, ErrInvalidPublicKey
		}
	}

	id, err := api.w.Subscribe(&filter)
	if err != nil {
		return nil, err
	}

	// create subscription and start waiting for message events
	rpcSub := notifier.CreateSubscription()
	go func() {
		// for now poll internally, refactor whisper internal for channel support
		ticker := time.NewTicker(250 * time.Millisecond)
		defer ticker.Stop()

		for {
			select {
			case <-ticker.C:
				if filter := api.w.GetFilter(id); filter != nil {
					for _, rpcMessage := range toMessage(filter.Retrieve()) {
						if err := notifier.Notify(rpcSub.ID, rpcMessage); err != nil {
							log.Error("Failed to send notification", "err", err)
						}
					}
				}
			case <-rpcSub.Err():
				api.w.Unsubscribe(id)
				return
			case <-notifier.Closed():
				api.w.Unsubscribe(id)
				return
			}
		}
	}()

	return rpcSub, nil
}
37314
func (o *GetEndpointIDLogOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(200)
	payload := o.Payload
	if payload == nil {
		// return empty array
		payload = models.EndpointStatusLog{}
	}

	if err := producer.Produce(rw, payload); err != nil {
		panic(err) // let the recovery middleware deal with this
	}
}
716874
func ResponseHeadersEncodeError(req *transport.Request, err error) error {
	return newServerEncodingError(req, nil, true /*isResponse*/, true /*isHeader*/, err)
}
300183
func sortedResponses(input map[int]spec.Response) responses {
	var res responses
	for k, v := range input {
		if k > 0 {
			res = append(res, respSort{k, v})
		}
	}
	sort.Sort(res)
	return res
}
71967
func ResponseError(format string, a ...interface{}) {
	response := ErrorResponse{Error: fmt.Sprintf(format, a...)}
	j, err := json.MarshalIndent(&response, "", "\t")
	if err != nil {
		panic(fmt.Sprintf("Failed to generate response for error:", err))
	}
	fmt.Println(string(j[:]))
}
120487
func (s *SendMessagesOutput) SetMessageResponse(v *MessageResponse) *SendMessagesOutput {
	s.MessageResponse = v
	return s
}
1287410
func (r *response) parseResponse(data []byte, c *challenge) error {
	fmap := newFieldMapper()
	fmap.Add("username", &(r.username))
	fmap.Add("realm", &(r.realm))
	fmap.Add("nonce", &(r.nonce))
	fmap.Add("cnonce", &(r.cnonce))
	fmap.Add("host", &(r.host))
	fmap.Add("digest-uri", &(r.digest_uri))
	fmap.Add("response", &(r.resp))
	fmap.Add("charset", &(r.charset))
	fmap.Add("authzid", &(r.auth_id))
	fmap.Add("qop", &(r.qop))

	uniq := map[string]int{"username": 0, "realm": 0, "nonce": 0, "cnonce": 0, "nc": 0}

	return sasl.EachToken(data, ',', func(token []byte) error {
		if !bytes.Contains(token, []byte{'='}) {
			return fmt.Errorf("Token does not contain key value pair: %s", token)
		}

		key, val := sasl.ExtractKeyValue(token, '=')

		if _, ok := uniq[string(key)]; ok {
			uniq[string(key)] += 1
			if uniq[string(key)] > 1 {
				return fmt.Errorf("More than one occurance of %s found", key)
			}
		}

		switch string(key) {
		case "nc":
			v, err := strconv.Atoi(string(val))
			if err != nil {
				return fmt.Errorf("Wrong nc value: %s", err)
			}
			r.nonce_count = v
		default:
			if err := fmap.Set(string(key), bytes.Trim(val, "\"")); err != nil {
				return err
			}
		}
		return nil
	})
}
770111
func (o *PutStatusProbeOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(200)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}
391370
func writeErrorResponseJSON(ctx context.Context, w http.ResponseWriter, err APIError, reqURL *url.URL) {
	// Generate error response.
	errorResponse := getAPIErrorResponse(ctx, err, reqURL.Path, w.Header().Get(responseRequestIDKey), w.Header().Get(responseDeploymentIDKey))
	encodedErrorResponse := encodeResponseJSON(errorResponse)
	writeResponse(w, err.HTTPStatusCode, encodedErrorResponse, mimeJSON)
}
770367
func (a *AuthServerCodec) WriteResponse(r *rpc.Response, body interface{}) error {
	// We do need a lock here, because the ServerCodec interface specifies
	//  that WriteResponse must be safe for concurrent use by multiple goroutines
	a.wBuffMutex.Lock()
	defer a.wBuffMutex.Unlock()

	a.buff.WriteBuff.Reset()

	// Let the underlying codec write the response to the buffer
	if err := a.wrappedcodec.WriteResponse(r, body); err != nil {
		return err
	}

	// Get the response from the buffer and write it to the actual connection
	response := a.buff.WriteBuff.Bytes()
	if err := auth.WriteLengthAndBytes(response, a.conn); err != nil {
		return err
	}

	return nil
}