Example #1
0
func TestParseCommandArgs(t *testing.T) {
	if cmd, err := parseCommandArgs(nil); err == nil {
		validateCommandParsed(t, "command", cmd, nil)
	} else {
		t.Errorf("Unexpected parse error: %s", err.Error())
	}

	expected := []string{"/test.sh", "arg1"}
	json1 := json.RawMessage(`"/test.sh arg1"`)
	if cmd, err := parseCommandArgs(json1); err == nil {
		validateCommandParsed(t, "json1", cmd, expected)
	} else {
		t.Errorf("Unexpected parse error json1: %s", err.Error())
	}

	json2 := json.RawMessage(`["/test.sh","arg1"]`)
	if cmd, err := parseCommandArgs(json2); err == nil {
		validateCommandParsed(t, "json2", cmd, expected)
	} else {
		t.Errorf("Unexpected parse error json2: %s", err.Error())
	}

	json3 := json.RawMessage(`{ "a": true }`)
	if _, err := parseCommandArgs(json3); err == nil {
		t.Errorf("Expected parse error for json3")
	}

}
Example #2
0
func TestUnmarshalSingleErrs(t *testing.T) {
	err := unmarshalSingle(json.RawMessage{}, "", "foo")
	assert.Error(t, err)

	var foo string
	err = unmarshalSingle(json.RawMessage([]byte(`{"bar":"baz"}`)), "foo", &foo)
	assert.Error(t, err)

	var outInt int
	var outStr string
	var outBool bool
	var outSlice []struct{}

	err = unmarshalSingle(json.RawMessage([]byte(`{"foo": "bar"}`)), "foo", &outInt)
	assert.Error(t, err)
	assert.Empty(t, outInt)
	err = unmarshalSingle(json.RawMessage([]byte(`{"foo": 1}`)), "foo", &outStr)
	assert.Error(t, err)
	assert.Empty(t, outStr)
	err = unmarshalSingle(json.RawMessage([]byte(`{"foo": "bar"}`)), "foo", &outBool)
	assert.Error(t, err)
	assert.Empty(t, outBool)
	err = unmarshalSingle(json.RawMessage([]byte(`{"foo": "bar"}`)), "foo", &outSlice)
	assert.Error(t, err)
	assert.Empty(t, outSlice)
}
Example #3
0
func TestParseInterfaces(t *testing.T) {
	if interfaces, err := parseInterfaces(nil); err != nil {
		t.Errorf("Unexpected parse error: %s", err.Error())
	} else if len(interfaces) > 0 {
		t.Errorf("Expected no interfaces, but got %s", interfaces)
	}

	json1 := json.RawMessage(`"eth0"`)
	expected1 := []string{"eth0"}
	if interfaces, err := parseInterfaces(json1); err != nil {
		t.Errorf("Unexpected parse error: %s", err.Error())
	} else if !reflect.DeepEqual(interfaces, expected1) {
		t.Errorf("Expected %s, got: %s", expected1, interfaces)
	}

	json2 := json.RawMessage(`["ethwe","eth0"]`)
	expected2 := []string{"ethwe", "eth0"}
	if interfaces, err := parseInterfaces(json2); err != nil {
		t.Errorf("Unexpected parse error: %s", err.Error())
	} else if !reflect.DeepEqual(interfaces, expected2) {
		t.Errorf("Expected %s, got: %s", expected2, interfaces)
	}

	json3 := json.RawMessage(`{ "a": true }`)
	if _, err := parseInterfaces(json3); err == nil {
		t.Errorf("Expected parse error for json3")
	}
}
Example #4
0
// 转换到下层对象
func (this ContentModel) Encode(webqq *WebQQ) (v Content) {
	matches := contentPatten.FindAllStringSubmatch(this.Message, -1)
	if matches == nil { // 没有图片
		v = make([]json.RawMessage, 1, 2)
		b, err := json.Marshal(this.Message)
		util.Try(err)
		v[0] = json.RawMessage(b)
	} else {
		v = make([]json.RawMessage, 0, len(matches)*2+2) // 123[]1[]2[]3 = 3*2+1 = 7
		for _, v1 := range matches {
			switch v1[1] {
			case "offpic":
				b, err := json.Marshal([]interface{}{v1[1], Offpic{Success: 1, FilePath: v1[2]}})
				if err == nil {
					v = append(v, b)
				}
			case "cface":
				b, err := json.Marshal([]interface{}{v1[1], Cface{Key: webqq.cface_key, Name: v1[2], Server: DefaultServer}})
				if err == nil {
					v = append(v, json.RawMessage(b))
				}
			case "face":
				b, err := json.Marshal([]interface{}{v1[1], util.ToInt(v1[2])})
				if err == nil {
					v = append(v, json.RawMessage(b))
				}
			}
		}
	}

	b, err := json.Marshal([]interface{}{"font", this.Font})
	util.Try(err)
	v = append(v, json.RawMessage(b))
	return v
}
Example #5
0
File: grants.go Project: logan/heim
func (gs *GrantManager) Authority(
	ctx scope.Context, manager Account, managerKey *security.ManagedKey) (
	subjectKeyPair *security.ManagedKeyPair, public, private *json.RawMessage, err error) {

	managerKeyPair, err := manager.Unlock(managerKey)
	if err != nil {
		return nil, nil, nil, err
	}

	subjectKeyPair, err = gs.unlockSubjectKeyPair(ctx, manager, managerKeyPair)
	if err != nil {
		return nil, nil, nil, err
	}

	sourceCapability, err := gs.AccountCapability(ctx, manager)
	if err != nil {
		return nil, nil, nil, err
	}

	public = new(json.RawMessage)
	if publicBytes := sourceCapability.PublicPayload(); publicBytes != nil {
		*public = json.RawMessage(publicBytes)
	}

	private = new(json.RawMessage)
	privateBytes, err := sourceCapability.DecryptPayload(gs.SubjectKeyPair, managerKeyPair)
	if err != nil {
		return nil, nil, nil, err
	}
	*private = json.RawMessage(privateBytes)

	return
}
Example #6
0
func (c *client) info(ch Channel) ClientInfo {
	channelInfo, ok := c.channelInfo[ch]
	if !ok {
		channelInfo = []byte{}
	}
	var rawDefaultInfo *json.RawMessage
	var rawChannelInfo *json.RawMessage
	if len(c.defaultInfo) > 0 {
		raw := json.RawMessage(c.defaultInfo)
		rawDefaultInfo = &raw
	} else {
		rawDefaultInfo = nil
	}
	if len(channelInfo) > 0 {
		raw := json.RawMessage(channelInfo)
		rawChannelInfo = &raw
	} else {
		rawChannelInfo = nil
	}
	return ClientInfo{
		User:        c.User,
		Client:      c.UID,
		DefaultInfo: rawDefaultInfo,
		ChannelInfo: rawChannelInfo,
	}
}
Example #7
0
// PushPrivate handle for push private message.
func PushPrivate(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method Not Allowed", 405)
		return
	}
	body := ""

	res := map[string]interface{}{"ret": app.OK}

	defer app.RetPWrite(w, r, res, &body, time.Now())
	// param
	bodyBytes, err := ioutil.ReadAll(r.Body)
	if err != nil {
		res["ret"] = app.ParamErr
		logger.Errorf("ioutil.ReadAll() failed (%s)", err.Error())
		return
	}
	body = string(bodyBytes)
	params := r.URL.Query()
	key := params.Get("key")
	expireStr := params.Get("expire")
	if key == "" {
		res["ret"] = app.ParamErr
		return
	}
	expire, err := strconv.ParseUint(expireStr, 10, 32)
	if err != nil {
		res["ret"] = app.ParamErr
		logger.Errorf("strconv.ParseUint(\"%s\", 10, 32) error(%v)", expireStr, err)
		return
	}
	node := myrpc.GetComet(key)
	if node == nil || node.CometRPC == nil {
		res["ret"] = app.NotFoundServer
		return
	}
	client := node.CometRPC.Get()
	if client == nil {
		res["ret"] = app.NotFoundServer
		return
	}
	rm := json.RawMessage(bodyBytes)
	msg, err := rm.MarshalJSON()
	if err != nil {
		res["ret"] = app.ParamErr
		logger.Errorf("json.RawMessage(\"%s\").MarshalJSON() error(%v)", body, err)
		return
	}
	args := &myrpc.CometPushPrivateArgs{Msg: json.RawMessage(msg), Expire: uint(expire), Key: key}
	ret := 0
	if err := client.Call(myrpc.CometServicePushPrivate, args, &ret); err != nil {
		logger.Errorf("client.Call(\"%s\", \"%v\", &ret) error(%v)", myrpc.CometServicePushPrivate, args, err)
		res["ret"] = app.InternalErr
		return
	}
	return
}
Example #8
0
func (c *serverCodec) WriteResponse(r *rpc.Response, x interface{}) error {
	// If return error: nothing happens.
	// In r.Error will be "" or .Error() of error returned by:
	// - ReadRequestBody()
	// - called RPC method
	c.mutex.Lock()
	b, ok := c.pending[r.Seq]
	if !ok {
		c.mutex.Unlock()
		return errors.New("invalid sequence number in response")
	}
	delete(c.pending, r.Seq)
	c.mutex.Unlock()

	if replies, ok := x.(*[]*json.RawMessage); r.ServiceMethod == "JSONRPC2.Batch" && ok {
		if len(*replies) == 0 {
			return nil
		}
		c.encmutex.Lock()
		defer c.encmutex.Unlock()
		return c.enc.Encode(replies)
	}

	if b == nil {
		// Notification. Do not respond.
		return nil
	}
	resp := serverResponse{Version: "2.0", ID: b}
	if r.Error == "" {
		if x == nil {
			resp.Result = &null
		} else {
			resp.Result = x
		}
	} else if r.Error[0] == '{' && r.Error[len(r.Error)-1] == '}' {
		// Well… this check for '{'…'}' isn't too strict, but I
		// suppose we're trusting our own RPC methods (this way they
		// can force sending wrong reply or many replies instead
		// of one) and normal errors won't be formatted this way.
		raw := json.RawMessage(r.Error)
		resp.Error = &raw
	} else {
		raw := json.RawMessage(newError(r.Error).Error())
		resp.Error = &raw
	}
	c.encmutex.Lock()
	defer c.encmutex.Unlock()
	return c.enc.Encode(resp)
}
Example #9
0
func TestService(t *testing.T) {
	s := rpc.NewServer()
	s.RegisterCodec(NewCodec(), "application/json")
	s.RegisterService(new(Service1), "")

	var res Service1Response
	if err := execute(t, s, "Service1.Multiply", &Service1Request{4, 2}, &res); err != nil {
		t.Error("Expected err to be nil, but got", err)
	}
	if res.Result != 8 {
		t.Error("Expected res.Result to be 8, but got", res.Result)
	}
	if err := execute(t, s, "Service1.ResponseError", &Service1Request{4, 2}, &res); err == nil {
		t.Errorf("Expected to get %q, but got nil", ErrResponseError)
	} else if err.Error() != ErrResponseError.Error() {
		t.Errorf("Expected to get %q, but got %q", ErrResponseError, err)
	}
	if code, res := executeRaw(t, s, json.RawMessage(`{"method":"Service1.Multiply","params":null,"id":5}`)); code != 400 {
		t.Error("Expected response code to be 400, but got", code)
	} else if v, ok := field("result", res.Bytes()); !ok || v != nil {
		t.Errorf("Expected ok to be true and v to be nil, but got %v and %v", ok, v)
	}
	if err := execute(t, s, "Service1.ResponseJsonError", &Service1Request{4, 2}, &res); err == nil {
		t.Errorf("Expected to get %q, but got nil", ErrResponseError)
	} else if jsonErr, ok := err.(*Error); !ok {
		t.Error("Expected err to be of a *json.Error type")
	} else if !reflect.DeepEqual(jsonErr.Data, ErrResponseJsonError.Data) {
		t.Errorf("Expected jsonErr to be %q, but got %q", ErrResponseJsonError, jsonErr)
	}
}
Example #10
0
// GetPrivate implements the Storage GetPrivate method.
func (s *MySQLStorage) GetPrivate(key string, mid int64) ([]*myrpc.Message, error) {
	db := s.getConn(key)
	if db == nil {
		return nil, ErrNoMySQLConn
	}
	now := time.Now().Unix()
	rows, err := db.Query(getPrivateMsgSQL, key, mid)
	if err != nil {
		glog.Errorf("db.Query(\"%s\",\"%s\",%d,now) failed (%v)", getPrivateMsgSQL, key, mid, err)
		return nil, err
	}
	expire := int64(0)
	cmid := int64(0)
	msg := json.RawMessage([]byte{})
	msgs := []*myrpc.Message{}
	for rows.Next() {
		if err := rows.Scan(&cmid, &expire, &msg); err != nil {
			glog.Errorf("rows.Scan() failed (%v)", err)
			return nil, err
		}
		if now > expire {
			glog.Warningf("user_key: \"%s\" mid: %d expired", key, cmid)
			continue
		}
		msgs = append(msgs, &myrpc.Message{MsgId: cmid, GroupId: myrpc.PrivateGroupId, Msg: msg})
	}
	return msgs, nil
}
Example #11
0
func defaultSchemaLoader(root interface{}, ref *Ref, cache ResolutionCache) (*schemaLoader, error) {
	if cache == nil {
		cache = resCache
	}

	var ptr *jsonpointer.Pointer
	if ref != nil {
		ptr = ref.GetPointer()
	}

	currentRef := nextRef(root, ref, ptr)

	return &schemaLoader{
		root:        root,
		loadingRef:  ref,
		startingRef: ref,
		cache:       cache,
		loadDoc: func(path string) (json.RawMessage, error) {
			data, err := swag.LoadFromFileOrHTTP(path)
			if err != nil {
				return nil, err
			}
			return json.RawMessage(data), nil
		},
		currentRef: currentRef,
	}, nil
}
Example #12
0
func flush(c *cli.Context, keys *[]string, values *[]json.RawMessage) error {

	var buf bytes.Buffer

	if _, err := buf.Write([]byte("{")); err != nil {
		return err
	}
	for i, k := range *keys {
		fmt.Fprintf(&buf, "\"%s\":", k)
		if _, err := buf.Write((*values)[i]); err != nil {
			return err
		}
		if i < len(*keys)-1 {
			if _, err := buf.Write([]byte(",")); err != nil {
				return err
			}
		}
	}
	if _, err := buf.Write([]byte("}")); err != nil {
		return err
	}

	var src = json.RawMessage(buf.Bytes())
	// send to admin
	if err := post(c, "load", &src, nil); err != nil {
		return err
	}

	// reset the key and value buffers
	*keys = (*keys)[:0]
	*values = (*values)[:0]

	return nil

}
func (q *esQuery) MarshalJSON() ([]byte, error) {
	var buff bytes.Buffer
	//buff.Grow(queryWrapLength + len(filters) + len(sorts))
	if q.allowDeleted == false {
		q.filters = append(q.filters, json.RawMessage([]byte(`{"missing":{"field":"Deleted","existence":true,"null_value":true}}`)))
	}

	buff.Write(queryWrapPrefix)
	if len(q.filters) > 0 {
		filters, _ := json.Marshal(q.filters)
		buff.Write(queryWrapFilterPrefix)
		buff.Write(filters)
		buff.Write(queryWrapObjectClose)
	}
	buff.Write(queryWrapObjectClose)
	buff.Write(queryWrapObjectClose)

	if len(q.sorts) > 0 {
		sorts, _ := json.Marshal(q.sorts)

		buff.Write(queryWrapSortPrefix)
		buff.Write(sorts)
	}
	buff.Write(queryWrapObjectClose)

	log.Println(buff.String())
	return buff.Bytes(), nil
}
func (l AppRoutes) RoutingInfo() receptor.RoutingInfo {
	data, _ := json.Marshal(l)
	routingInfo := json.RawMessage(data)
	return receptor.RoutingInfo{
		AppRouter: &routingInfo,
	}
}
Example #15
0
func main() {
	flag.Parse()

	c := client.NewHTTPClient(*address)
	if err := c.WaitUntilReady(*waitDuration); err != nil {
		log.Fatal(err)
	}

	serviceMethod, params := flag.Arg(0), json.RawMessage(flag.Arg(1))
	if *legacyCall {
		var resp json.RawMessage
		if err := c.Call(serviceMethod, &params, &resp); err != nil {
			log.Fatal(err)
		}
		fmt.Println(string(resp))
	} else {
		rd := c.Stream(serviceMethod, &params)
		defer rd.Close()
		for {
			var resp json.RawMessage
			if err := rd.NextResult(&resp); err == io.EOF {
				break
			} else if err != nil {
				log.Fatal(err)
			}
			fmt.Println(string(resp))
		}
	}
}
Example #16
0
File: room.go Project: logan/heim
func (rb *RoomBinding) broadcast(
	ctx scope.Context, db gorp.SqlExecutor, packetType proto.PacketType, payload interface{}, exclude ...proto.Session) error {

	encodedPayload, err := json.Marshal(payload)
	if err != nil {
		return err
	}

	packet := &proto.Packet{Type: packetType, Data: json.RawMessage(encodedPayload)}
	broadcastMsg := BroadcastMessage{
		Event:   packet,
		Exclude: make([]string, 0, len(exclude)),
	}
	if rb != nil {
		broadcastMsg.Room = rb.RoomName
	}
	for _, s := range exclude {
		if s != nil {
			broadcastMsg.Exclude = append(broadcastMsg.Exclude, s.ID())
		}
	}

	encoded, err := json.Marshal(broadcastMsg)
	if err != nil {
		return err
	}

	escaped := strings.Replace(string(encoded), "'", "''", -1)
	_, err = db.Exec(fmt.Sprintf("NOTIFY broadcast, '%s'", escaped))
	return err
}
Example #17
0
func TestVia(t *testing.T) {
	t.Parallel()
	canonicalKey := http.CanonicalHeaderKey("via")
	var testText = "notnedomi 2.2"
	v, err := New(config.NewHandler("via", json.RawMessage(`{"text": "notnedomi 2.2"}`)), nil,
		testStringHandler(t, testText))

	if err != nil {
		t.Errorf("Got error when initializing via - %s", err)
	}
	var expect, got []string
	recorder := httptest.NewRecorder()
	v.RequestHandle(nil, recorder, nil)
	expect = []string{testText}
	got = recorder.Header()[canonicalKey]
	if !reflect.DeepEqual(got, expect) {
		t.Errorf("expected via header to be equal to %s but got %s", expect, got)
	}

	recorder.Header().Set(canonicalKey, "holla")
	expect = []string{"holla", testText}
	v.RequestHandle(nil, recorder, nil)
	got = recorder.Header()[canonicalKey]
	if !reflect.DeepEqual(got, expect) {
		t.Errorf("expected via header to be equal to %s but got %s", expect, got)
	}
}
Example #18
0
// ReadFrame decodes the next JSON object in the stream, or returns an error. The returned
// byte slice will be modified the next time ReadFrame is invoked and should not be altered.
func (r *jsonFrameReader) Read(data []byte) (int, error) {
	// Return whatever remaining data exists from an in progress frame
	if n := len(r.remaining); n > 0 {
		if n <= len(data) {
			data = append(data[0:0], r.remaining...)
			r.remaining = nil
			return n, nil
		}

		n = len(data)
		data = append(data[0:0], r.remaining[:n]...)
		r.remaining = r.remaining[n:]
		return n, io.ErrShortBuffer
	}

	// RawMessage#Unmarshal appends to data - we reset the slice down to 0 and will either see
	// data written to data, or be larger than data and a different array.
	n := len(data)
	m := json.RawMessage(data[:0])
	if err := r.decoder.Decode(&m); err != nil {
		return 0, err
	}

	// If capacity of data is less than length of the message, decoder will allocate a new slice
	// and set m to it, which means we need to copy the partial result back into data and preserve
	// the remaining result for subsequent reads.
	if len(m) > n {
		data = append(data[0:0], m[:n]...)
		r.remaining = m[n:]
		return n, io.ErrShortBuffer
	}
	return len(m), nil
}
Example #19
0
// CreateRequestMessage creates the request json message using the given input.
// Note, the input *MUST* be a pointer to a valid backend type that this
// client recognises.
func (cs *ClientServerImpl) CreateRequestMessage(input interface{}) ([]byte, error) {
	msg := &RequestMessage{}

	recognizedTypes := cs.GetRecognizedTypes()
	for typeStr, typeVal := range recognizedTypes {
		if reflect.TypeOf(input) == reflect.PtrTo(typeVal) {
			msg.Type = typeStr
			break
		}
	}
	if msg.Type == "" {
		return nil, &UnrecognizedWSRequestType{reflect.TypeOf(input).String()}
	}
	messageData, err := jsonutil.BuildJSON(input)
	if err != nil {
		return nil, &NotMarshallableWSRequest{msg.Type, err}
	}
	msg.Message = json.RawMessage(messageData)

	send, err := json.Marshal(msg)
	if err != nil {
		return nil, &NotMarshallableWSRequest{msg.Type, err}
	}
	return send, nil
}
Example #20
0
func TestUnmarshalSingleBool(t *testing.T) {
	// doesn't currently get exercised in normal usage
	var out bool
	err := unmarshalSingle(json.RawMessage([]byte(`{"foo": true}`)), "foo", &out)
	require.NoError(t, err)
	assert.True(t, out)
}
Example #21
0
func Train(m Metric) (int, int) {
	mr := m.Result()
	num_errors := 0
	evals := m.GetEvaluators()
	evals_config := m.GetEvaluatorConfigs()
	new_eval_config := make([]json.RawMessage, len(evals))
	for i, e := range evals {
		logrus.Debugf("Training Evaluator: %s", e.GetDescription())
		err := e.Train(mr.Data, mr.Total)
		if err != nil {
			num_errors += 1
			continue
		}
		j, err := json.Marshal(e)
		if err != nil {
			num_errors += 1
			new_eval_config[i] = evals_config[i]
			continue
		}
		raw := json.RawMessage(j)
		new_eval_config[i] = raw
	}

	m.SetEvaluatorConfigs(new_eval_config)
	return num_errors, len(evals)

}
Example #22
0
func (s *S) provisionTestResource(c *C, name string, apps []string) (*ct.Resource, *ct.Provider) {
	data := []byte(`{"foo":"bar"}`)
	handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		c.Assert(req.URL.Path, Equals, "/things")
		in, err := ioutil.ReadAll(req.Body)
		c.Assert(err, IsNil)
		c.Assert(string(in), Equals, string(data))
		w.Write([]byte(fmt.Sprintf(`{"id":"/things/%s","env":{"foo":"baz"}}`, name)))
	})
	srv := httptest.NewServer(handler)
	defer srv.Close()

	host, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
	s.m.MapTo(&resourceDiscoverd{
		fn: func() []*discoverd.Service {
			return []*discoverd.Service{{
				Addr: srv.Listener.Addr().String(),
				Host: host,
				Port: port,
			}}
		},
	}, (*resource.DiscoverdClient)(nil))

	p := s.createTestProvider(c, &ct.Provider{URL: fmt.Sprintf("discoverd+http://%s/things", name), Name: name})
	conf := json.RawMessage(data)
	out := &ct.Resource{}
	res, err := s.Post("/providers/"+p.ID+"/resources", &ct.ResourceReq{Config: &conf, Apps: apps}, out)
	c.Assert(err, IsNil)
	c.Assert(res.StatusCode, Equals, 200)
	return out, p
}
Example #23
0
func main() {
	domain := flag.String("d", "x.blax.me", "Base domain")
	port := flag.Int("p", 53530, "Listen port")
	flag.Parse()

	log.SetLevel(log.DebugLevel)

	options := wire.DNSTransportServerOptions{
		BaseDomain: *domain,
		Port:       *port,
	}
	options_str, err := json.Marshal(options)
	if err != nil {
		fmt.Printf("Unable to build option: %v\n", err)
		return
	}

	server := wire.DNSTransportServer{}
	if err = server.Open(json.RawMessage(options_str)); err != nil {
		fmt.Printf("Unable to open server: %v\n", err)
		return
	}

	for {
		data := <-server.UpstreamBuf
		server.DownstreamBuf <- data
	}
}
Example #24
0
func TestSubmitTasks(t *testing.T) {
	var err error
	var ts *httptest.Server

	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(201)
	}))
	defer ts.Close()

	TASKS_ADDRESS = ts.URL + "/%s/tasks"

	i := 0
	reader := JsonReaderFunc(func(d *json.RawMessage) error {
		if i == 5 {
			return io.EOF
		}
		i++
		data := json.RawMessage("1")
		d = &data
		return nil
	})

	n, err := SubmitTasks("", reader)
	if err != nil {
		t.Error(err)
	}

	if n != 5 {
		t.Error("n != 5")
	}
}
Example #25
0
func makeJson(data interface{}) string {
	str, err := json.Marshal(data)
	if err != nil {
		return ""
	}
	return string(json.RawMessage(str))
}
Example #26
0
func (this *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) {
	var obj map[string]json.RawMessage
	if err := json.Unmarshal(raw, &obj); err != nil {
		return nil, "", err
	}
	rawID, found := obj[this.idKey]
	if !found {
		log.Error(this.idKey, " not found in JSON content.")
		return nil, "", common.ErrObjectNotFound
	}
	var id string
	if err := json.Unmarshal(rawID, &id); err != nil {
		return nil, "", err
	}
	rawConfig := json.RawMessage(raw)
	if len(this.configKey) > 0 {
		configValue, found := obj[this.configKey]
		if !found {
			log.Error(this.configKey, " not found in JSON content.")
			return nil, "", common.ErrObjectNotFound
		}
		rawConfig = configValue
	}
	config, err := this.LoadWithID([]byte(rawConfig), id)
	if err != nil {
		return nil, id, err
	}
	return config, id, nil
}
Example #27
0
// JSONDoc loads a json document from either a file or a remote url
func JSONDoc(path string) (json.RawMessage, error) {
	data, err := swag.LoadFromFileOrHTTP(path)
	if err != nil {
		return nil, err
	}
	return json.RawMessage(data), nil
}
func (repo CloudControllerRouteServiceBindingRepository) Bind(
	instanceGUID string,
	routeGUID string,
	userProvided bool,
	opaque_params string,
) error {
	var rs io.ReadSeeker
	if opaque_params != "" {
		opaqueJSON := json.RawMessage(opaque_params)
		s := struct {
			Parameters *json.RawMessage `json:"parameters"`
		}{
			&opaqueJSON,
		}

		jsonBytes, err := json.Marshal(s)
		if err != nil {
			return err
		}

		rs = bytes.NewReader(jsonBytes)
	} else {
		rs = strings.NewReader("")
	}

	return repo.gateway.UpdateResourceSync(
		repo.config.APIEndpoint(),
		getPath(instanceGUID, routeGUID, userProvided),
		rs,
	)
}
Example #29
0
func (r *jsonRPCRequest) setMethodAndParams(args []string) error {
	switch {
	case len(args) == 0:
		return fmt.Errorf("missing 'method' (first argument)")
	case len(args) == 1:
		r.Method = args[0]
	case len(args) > 1:
		r.Method = args[0]

		if strings.ContainsRune(args[1], '=') {
			// if first argument conatins a '=' i assume
			// a list of key-value pairs, forming a map
			// or an 'object' in javascript terms
			r.Params = kvPairsToMap(args[1:])

		} else if len(args[1]) > 1 && strings.TrimLeft(args[1], " \n\t")[0] == '{' {
			raw := json.RawMessage(args[1])
			if ok, err := isValidJSON(args[1]); !ok {
				return err
			}
			r.Params = &raw
		} else {
			r.Params = args[1:]
		}
	}
	return nil
}
Example #30
0
func (t *thirdPartyResourceDataEncoder) Encode(obj runtime.Object, stream io.Writer) (err error) {
	switch obj := obj.(type) {
	case *extensions.ThirdPartyResourceData:
		return encodeToJSON(obj, stream)
	case *extensions.ThirdPartyResourceDataList:
		// TODO: There are likely still better ways to do this...
		listItems := make([]json.RawMessage, len(obj.Items))

		for ix := range obj.Items {
			buff := &bytes.Buffer{}
			err := encodeToJSON(&obj.Items[ix], buff)
			if err != nil {
				return err
			}
			listItems[ix] = json.RawMessage(buff.Bytes())
		}

		if t.gvk.Empty() {
			return fmt.Errorf("thirdPartyResourceDataEncoder was not given a target version")
		}

		encMap := struct {
			Kind       string               `json:"kind,omitempty"`
			Items      []json.RawMessage    `json:"items"`
			Metadata   unversioned.ListMeta `json:"metadata,omitempty"`
			APIVersion string               `json:"apiVersion,omitempty"`
		}{
			Kind:       t.gvk.Kind + "List",
			Items:      listItems,
			Metadata:   obj.ListMeta,
			APIVersion: t.gvk.GroupVersion().String(),
		}

		encBytes, err := json.Marshal(encMap)
		if err != nil {
			return err
		}

		_, err = stream.Write(encBytes)
		return err
	case *versioned.InternalEvent:
		event := &versioned.Event{}
		err := versioned.Convert_versioned_InternalEvent_to_versioned_Event(obj, event, nil)
		if err != nil {
			return err
		}

		enc := json.NewEncoder(stream)
		err = enc.Encode(event)
		if err != nil {
			return err
		}

		return nil
	case *unversioned.Status, *unversioned.APIResourceList:
		return t.delegate.Encode(obj, stream)
	default:
		return fmt.Errorf("unexpected object to encode: %#v", obj)
	}
}