Example #1
0
func (client *RegistryClient) Repository(name, tag string) (*Repository, error) {
	if tag == "" {
		tag = "latest"
	}

	uri := fmt.Sprintf("/%s/manifests/%s", name, tag)

	data, hdr, err := client.doRequest("GET", uri, nil, nil)
	if err != nil {
		return nil, err
	}

	repo := &Repository{}
	if err := json.Unmarshal(data, &repo); err != nil {
		log.Errorf("repo err data:%s", err)
		return nil, err
	}

	// to get repository size
	j, _ := simplejson.NewJson([]byte(data))
	history, _ := j.Get("history").Array()
	//log.Debugf("history data:%s",history)
	for _, h := range history {
		v1, _ := h.(map[string]interface{})["v1Compatibility"]
		vs := v1.(string)
		vj, _ := simplejson.NewJson([]byte(vs))
		vz, _ := vj.Get("Size").Int64()
		repo.Size += vz
		//log.Debugf("each size:%s",vz)
	}

	//log.Debugf("repository data:%s",repo)
	repo.Digest = hdr.Get("Docker-Content-Digest")
	return repo, nil
}
Example #2
0
func (s *QueryBuilderSuite) TestGetItemQuery(c *gocheck.C) {
	primary := dynamodb.NewStringAttribute("domain", "")
	key := dynamodb.PrimaryKey{primary, nil}
	table := s.server.NewTable("sites", key)

	q := dynamodb.NewQuery(table)
	q.AddKey(table, &dynamodb.Key{HashKey: "test"})

	queryJson, err := simplejson.NewJson([]byte(q.String()))
	if err != nil {
		c.Fatal(err)
	}

	expectedJson, err := simplejson.NewJson([]byte(`
{
	"Key": {
		"domain": {
			"S": "test"
		}
	},
	"TableName": "sites"
}
	`))
	if err != nil {
		c.Fatal(err)
	}
	c.Check(queryJson, gocheck.DeepEquals, expectedJson)
}
Example #3
0
func (s *QueryBuilderSuite) TestGetItemQuery(c *check.C) {
	primary := NewStringAttribute("domain", "")
	key := PrimaryKey{primary, nil}
	table := s.server.NewTable("sites", key)

	q := NewQuery(table)
	q.AddKey(&Key{HashKey: "test"})

	{
		queryJson, err := simplejson.NewJson([]byte(q.String()))
		if err != nil {
			c.Fatal(err)
		}

		expectedJson, err := simplejson.NewJson([]byte(`
		{
			"Key": {
				"domain": {
					"S": "test"
				}
			},
			"TableName": "sites"
		}
		`))
		if err != nil {
			c.Fatal(err)
		}
		c.Check(queryJson, check.DeepEquals, expectedJson)
	}

	// Use ConsistentRead
	{
		q.SetConsistentRead(true)
		queryJson, err := simplejson.NewJson([]byte(q.String()))
		if err != nil {
			c.Fatal(err)
		}

		expectedJson, err := simplejson.NewJson([]byte(`
		{
			"ConsistentRead": "true",
			"Key": {
				"domain": {
					"S": "test"
				}
			},
			"TableName": "sites"
		}
		`))
		if err != nil {
			c.Fatal(err)
		}
		c.Check(queryJson, check.DeepEquals, expectedJson)
	}
}
Example #4
0
func TestAddKeyConditions(t *testing.T) {
	auth := &aws.Auth{AccessKey: "", SecretKey: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"}
	server := dynamodb.Server{*auth, aws.USEast}
	primary := dynamodb.NewStringAttribute("domain", "")
	key := dynamodb.PrimaryKey{primary, nil}
	table := server.NewTable("sites", key)

	q := dynamodb.NewQuery(table)
	acs := []dynamodb.AttributeComparison{
		*dynamodb.NewStringAttributeComparison("domain", "EQ", "example.com"),
		*dynamodb.NewStringAttributeComparison("path", "EQ", "/"),
	}
	q.AddKeyConditions(acs)
	queryString := []byte(q.String())
	json, err := simplejson.NewJson(queryString)

	if err != nil {
		t.Logf("JSON err : %s\n", err)
		t.Fatalf("Invalid JSON : %s\n", queryString)
	}

	expected_json, err := simplejson.NewJson([]byte(`
{
  "KeyConditions": {
    "domain": {
      "AttributeValueList": [
        {
          "S": "example.com"
        }
      ],
      "ComparisonOperator": "EQ"
    },
    "path": {
      "AttributeValueList": [
        {
          "S": "/"
        }
      ],
      "ComparisonOperator": "EQ"
    }
  },
  "TableName": "sites"
}
	`))
	if err != nil {
		t.Logf("JSON err : %s\n", err)
		t.Fatalf("Invalid JSON : %s\n", expected_json)
	}

	if !reflect.DeepEqual(json, expected_json) {
		t.Fatalf("Unexpected KeyConditions structure")
	}
}
Example #5
0
func (s *QueryBuilderSuite) TestMapUpdates(c *check.C) {
	primary := NewStringAttribute("domain", "")
	key := PrimaryKey{primary, nil}
	table := s.server.NewTable("sites", key)

	q := NewQuery(table)
	q.AddKey(&Key{HashKey: "test"})

	subAttr1 := NewStringAttribute(":Updates1", "subval1")
	subAttr2 := NewNumericAttribute(":Updates2", "2")
	exp := &Expression{
		Text: "SET #Updates0.#Updates1=:Updates1, #Updates0.#Updates2=:Updates2",
		AttributeNames: map[string]string{
			"#Updates0": "Map",
			"#Updates1": "submap1",
			"#Updates2": "submap2",
		},
		AttributeValues: []Attribute{*subAttr1, *subAttr2},
	}
	q.AddUpdateExpression(exp)
	queryJson, err := simplejson.NewJson([]byte(q.String()))
	if err != nil {
		c.Fatal(err)
	}
	expectedJson, err := simplejson.NewJson([]byte(`
{
	"UpdateExpression": "SET #Updates0.#Updates1=:Updates1, #Updates0.#Updates2=:Updates2",
	"ExpressionAttributeNames": {
		"#Updates0": "Map",
		"#Updates1": "submap1",
		"#Updates2": "submap2"
	},
	"ExpressionAttributeValues": {
        ":Updates1": {"S": "subval1"},
        ":Updates2": {"N": "2"}
	},
	"Key": {
		"domain": {
			"S": "test"
		}
	},
	"TableName": "sites"
}
	`))
	if err != nil {
		c.Fatal(err)
	}
	c.Check(queryJson, check.DeepEquals, expectedJson)
}
Example #6
0
func (s *QueryBuilderSuite) TestAddQueryFilterConditions(c *check.C) {
	primary := NewStringAttribute("domain", "")
	key := PrimaryKey{primary, nil}
	table := s.server.NewTable("sites", key)

	q := NewQuery(table)
	acs := []AttributeComparison{
		*NewStringAttributeComparison("domain", "EQ", "example.com"),
	}
	qf := []AttributeComparison{
		*NewNumericAttributeComparison("count", COMPARISON_GREATER_THAN, 5),
	}
	q.AddKeyConditions(acs)
	q.AddQueryFilter(qf)
	queryJson, err := simplejson.NewJson([]byte(q.String()))

	if err != nil {
		c.Fatal(err)
	}

	expectedJson, err := simplejson.NewJson([]byte(`
{
  "KeyConditions": {
    "domain": {
      "AttributeValueList": [
        {
          "S": "example.com"
        }
      ],
      "ComparisonOperator": "EQ"
    }
  },
  "QueryFilter": {
    "count": {
      "AttributeValueList": [
        { "N": "5" }
      ],
      "ComparisonOperator": "GT"
    }
  },
  "TableName": "sites"
}
	`))
	if err != nil {
		c.Fatal(err)
	}
	c.Check(queryJson, check.DeepEquals, expectedJson)
}
Example #7
0
func main() {
	str := `{cmd_name:"Pmd.UserJsMessageForwardUserPmd_CS","msg":{"errno":"0","st":1470339434,"data":{"ret":0,"uid":1126119,"errno":"0","userInfo":{"roundNum":41,"signature":"","gender":"男","giftCoupon":0,"nickName":"1126119","headUrl":"http:\/\/1251210123.cdn.myqcloud.com\/1251210123\/QZONESTATIC\/headImages\/97.jpg","uid":1126119,"remainder":17187041,"maxMulti":59,"sumRecharge":0,"platId":0,"subPlatId":0,"bankChips":0},"gmLevel":0,"roomInfo":[{"lowestCarry":1,"maxSeat":20,"bankerConfig":{"selectChips":[3000000,5000000,8000000,10000000],"lowestBankerChips":3000000},"lowestBet":100,"roomName":"房间10002","roomId":10002,"maxUser":10000},{"lowestCarry":500000,"maxSeat":20,"bankerConfig":{"selectChips":[30000000,50000000,80000000,100000000],"lowestBankerChips":30000000},"lowestBet":100,"roomName":"房间10004","roomId":10004,"maxUser":10000}]},"do":"Cmd.UserInfoSynRequestLobbyCmd_S"}}`
	var jsmap map[string]interface{}
	err1 := json.Unmarshal([]byte(str), &jsmap)
	if err1 != nil {
		fmt.Println(err1)
	}
	fmt.Println(jsmap["msg"].(map[string]interface{})["errno"])
	fmt.Println(jsmap["cmd_name"])
	_, err := sjson.NewJson([]byte(`{"do":"register-auto", "gameid":301, "data":{"mid":"-24912448"}}`))
	fmt.Println(err)
	sjs, _ := sjson.NewJson([]byte(`{
	"curequip":[1,2,3,4,5],
	"effect":70,
	"gold":50,
	"item":{},
	"lottery":{"item":[0,0,0,0,0,0,0,0,0],"itemgot":[0,0,0,0,0,0,0,0,0],"refreshtime":0},
	"music":1,
	"name":"强哥",
	"silver":60,
	"stage":{},
	"strength":100,
	"version":1
		}`))
	sjs2, _ := sjson.NewJson([]byte(`{}`))
	var i json.Number
	i = "100"
	sjs2.Set("cur", i)
	//sjs2.Set("cur", "100")
	sjs.Set("sjs2", sjs2)
	sjs.Get("curequip").MustArray()[2] = 10
	jsstr, _ := sjs.MarshalJSON()
	sjs, _ = sjson.NewJson(jsstr)
	//fmt.Println(string(jsstr))
	sjs3 := sjs.Get("sjs2")
	sjs.Get("effect").UnmarshalJSON([]byte(`{}`))
	//fmt.Println(sjs.Map())
	fmt.Println(sjs3.Get("cur"))
	//fmt.Println("aaa", sjs.Get("lottery").Get("item").MustArray()[0])
	//fmt.Println("bbb", sjs.Get("sjs2").Get("cur").MustString(""))
	sjs2.Set("key", make(map[string]interface{}))
	//b, _ := sjs2.MarshalJSON()
	fmt.Println(sjs.Get("sjs2").Get("cur").Int())
	test()
	sjs, _ = sjson.NewJson([]byte(`[{"do":"register-auto", "gameid":301, "data":{"mid":"-24912448"}},{"do":"register-auto", "gameid":301, "data":{"mid":"-24912448"}}]`))
	d, _ := sjs.GetIndex(0).MarshalJSON()
	fmt.Println(string(d))
}
Example #8
0
func (t *Table) DescribeTable() (*TableDescriptionT, error) {
	q := NewQuery(t)
	jsonResponse, err := t.Server.queryServer(target("DescribeTable"), q)
	if err != nil {
		return nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)
	if err != nil {
		return nil, err
	}

	var tableDescription TableDescriptionT

	// TODO: Populate tableDescription.AttributeDefinitions.

	tableDescription.CreationDateTime, _ = json.Get("CreationDateTime").Float64()
	tableDescription.ItemCount, _ = json.Get("ItemCount").Int64()

	// TODO: Populate tableDescription.KeySchema.
	// TODO: Populate tableDescription.LocalSecondaryIndexes.
	// TODO: Populate tableDescription.ProvisionedThroughPut.

	tableDescription.TableName, _ = json.Get("TableName").String()
	tableDescription.TableSizeBytes, _ = json.Get("TableSizeBytes").Int64()
	tableDescription.TableStatus, _ = json.Get("TableStatus").String()

	return &tableDescription, nil
}
Example #9
0
func main() {

	pb.Init(funcs)

	setupViews()

	if InDev != "" {
		pb.Logger.Printf("in:\n%s\n", pb.Input.Raw())
	}

	out := pb.Run()

	if InDev != "" {
		nice := out
		js, err := sjson.NewJson([]byte(out))
		if err == nil {
			b, err := js.EncodePretty()
			if err == nil {
				nice = string(b)
			}
		}
		pb.Logger.Println("out:", string(nice))
	}

	fmt.Println(out)
}
Example #10
0
func (t *Table) deleteItem(key *Key, expected []Attribute, condition *Expression) (bool, error) {
	q := NewQuery(t)
	q.AddKey(key)

	if expected != nil {
		q.AddExpected(expected)
	}

	if condition != nil {
		q.AddConditionExpression(condition)
	}

	jsonResponse, err := t.Server.queryServer(target("DeleteItem"), q)

	if err != nil {
		return false, err
	}

	_, err = simplejson.NewJson(jsonResponse)
	if err != nil {
		return false, err
	}

	return true, nil
}
Example #11
0
func runQuery(q *Query, t *Table) ([]map[string]*Attribute, error) {
	jsonResponse, err := t.Server.queryServer("DynamoDB_20120810.Query", q)
	if err != nil {
		return nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)
	if err != nil {
		return nil, err
	}

	itemCount, err := json.Get("Count").Int()
	if err != nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return nil, errors.New(message)
	}

	results := make([]map[string]*Attribute, itemCount)

	for i, _ := range results {
		item, err := json.Get("Items").GetIndex(i).Map()
		if err != nil {
			message := fmt.Sprintf("Unexpected response %s", jsonResponse)
			return nil, errors.New(message)
		}
		results[i] = parseAttributes(item)
	}
	return results, nil
}
Example #12
0
func buildError(r *http.Response, jsonBody []byte) error {

	ddbError := Error{
		StatusCode: r.StatusCode,
		Status:     r.Status,
	}

	json, err := simplejson.NewJson(jsonBody)
	if err != nil {
		return err
	}
	message := json.Get("Message").MustString()
	if message == "" {
		message = json.Get("message").MustString()
	}
	ddbError.Message = message

	// Of the form: com.amazon.coral.validate#ValidationException
	// We only want the last part
	codeStr := json.Get("__type").MustString()
	hashIndex := strings.Index(codeStr, "#")
	if hashIndex > 0 {
		codeStr = codeStr[hashIndex+1:]
	}
	ddbError.Code = codeStr

	return &ddbError
}
Example #13
0
func (t *Table) AddItem(hashKey string, rangeKey string, attributes []Attribute) (bool, error) {

	if len(attributes) == 0 {
		return false, errors.New("At least one attribute is required.")
	}

	q := NewQuery(t)
	q.AddKey(t, hashKey, rangeKey)
	q.AddUpdates(attributes, "ADD")

	jsonResponse, err := t.Server.queryServer(target("UpdateItem"), q)

	if err != nil {
		return false, err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return false, err
	}

	units := json.Get("ConsumedCapacityUnits")

	if units == nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return false, errors.New(message)
	}

	return true, nil

}
Example #14
0
func (f FtpOpe) FtpWalkDir(IP string, user string, pwd string, path string) (js *json.Json, err error) {
	lf := &FtpBase{IP, user, pwd, "", nil}
	err = lf.Conn()
	if err != nil {
		return
	}

	if path[0] != '/' {
		var dir string
		dir, err = lf.conn.CurrentDir()
		if err != nil {
			return
		}
		path = dir + "/" + path
	}

	js, err = json.NewJson([]byte(`{}`))
	entrys, err := lf.conn.List(path)
	for i := range entrys {
		switch entrys[i].Type {
		case ftp.EntryTypeFile:
			js.Set(entrys[i].Name, "file")
		case ftp.EntryTypeFolder:
			js.Set(entrys[i].Name, "folder")
		}
	}

	lf.Close()
	return
}
Example #15
0
func TestConvertWithNewLines(t *testing.T) {
	assert := assert.New(t)

	s := `<?xml version="1.0" encoding="UTF-8"?>
  <osm>
   <foo>
	 	foo

		bar
	</foo>
  </osm>`

	// Build SimpleJSON
	json, err := sj.NewJson([]byte(`{
	  "osm": {
	    "foo": "foo\n\n\t\tbar"
	  }
	}`))
	assert.NoError(err)

	expected, err := json.MarshalJSON()
	assert.NoError(err)

	// Then encode it in JSON
	res, err := Convert(strings.NewReader(s))
	assert.NoError(err)

	// Assertion
	assert.JSONEq(string(expected), res.String(), "Drumroll")
}
Example #16
0
func (t *Table) modifyAttributes(key *Key, attributes, expected []Attribute, action string) (bool, error) {

	if len(attributes) == 0 {
		return false, errors.New("At least one attribute is required.")
	}

	q := NewQuery(t)
	q.AddKey(t, key)
	q.AddUpdates(attributes, action)

	if expected != nil {
		q.AddExpected(expected)
	}

	jsonResponse, err := t.Server.queryServer(target("UpdateItem"), q)

	if err != nil {
		return false, err
	}

	_, err = simplejson.NewJson(jsonResponse)
	if err != nil {
		return false, err
	}

	return true, nil
}
Example #17
0
func test1() {
	text := []byte(`{
				"int_array":[1,2,3],
				"map":{
					"string_array": ["v1", "v2"]
				},
				"int": 2,
				"bool": true
			}`)
	j, err := json.NewJson(text)
	checkError(err)
	arr, err := j.Get("int_array").Array()
	checkError(err)
	fmt.Println("get int_array:")
	for _, v := range arr {
		fmt.Printf("%s ", v.(jj.Number)) // 这是多么不漂亮的写法啊
	}
	fmt.Println()

	// 使用 GetPath + Must* 还是非常方便的
	fmt.Println("use GetPath & MustArray to get string_array:")
	for _, v := range j.GetPath("map", "string_array").MustArray() {
		fmt.Printf("%s ", v.(string))
	}
	fmt.Println()

	fmt.Println("use GetPath & MustArray to get string_array (no error):")
	for _, v := range j.GetPath("no_exists", "string_array").MustArray() { // 不存在的信息也不会出错
		fmt.Printf("%s ", v.(string))
	}
	fmt.Println()

	fmt.Printf("int: %d\n", j.Get("int").MustInt())
	fmt.Printf("int: %d\n", j.Get("int_not_exists").MustInt(9)) // 当想要的字段不存在时,使用默认值是不错的
}
Example #18
0
File: scan.go Project: Zariel/goamz
func (t *Table) FetchPartialResults(query Query) ([]map[string]*Attribute, *Key, error) {
	jsonResponse, err := t.Server.queryServer(target("Scan"), query)
	if err != nil {
		return nil, nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)
	if err != nil {
		return nil, nil, err
	}

	itemCount, err := json.Get("Count").Int()
	if err != nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return nil, nil, errors.New(message)
	}

	results := make([]map[string]*Attribute, itemCount)
	for i, _ := range results {
		item, err := json.Get("Items").GetIndex(i).Map()
		if err != nil {
			message := fmt.Sprintf("Unexpected response %s", jsonResponse)
			return nil, nil, errors.New(message)
		}
		results[i] = parseAttributes(item)
	}

	var lastEvaluatedKey *Key
	if lastKeyMap := json.Get("LastEvaluatedKey").MustMap(); lastKeyMap != nil {
		lastEvaluatedKey = parseKey(t, lastKeyMap)
	}

	return results, lastEvaluatedKey, nil
}
Example #19
0
func getConfig(filename string) (*Config, error) {
	// Load config file
	file, err := os.Open(filename)

	if err != nil {
		log.Fatal(err)
		return nil, err
	}

	// Read all file contents into a bytes.Buffer
	var contents bytes.Buffer
	buf := make([]byte, 1024)
	for {
		n, err := file.Read(buf)
		if err != nil && err != io.EOF {
			log.Fatal(err)
		}
		if n == 0 {
			break
		}

		contents.Write(buf[:n])
	}

	json, err := simplejson.NewJson(contents.Bytes())
	config := new(Config)
	config.json_data = json
	return config, err
}
Example #20
0
func (t *Table) putItem(hashKey, rangeKey string, attributes, expected []Attribute) (bool, error) {
	if len(attributes) == 0 {
		return false, errors.New("At least one attribute is required.")
	}

	q := NewQuery(t)

	keys := t.Key.Clone(hashKey, rangeKey)
	attributes = append(attributes, keys...)

	q.AddItem(attributes)
	if expected != nil {
		q.AddExpected(expected)
	}

	jsonResponse, err := t.Server.queryServer(target("PutItem"), q)

	if err != nil {
		return false, err
	}

	_, err = simplejson.NewJson(jsonResponse)
	if err != nil {
		return false, err
	}

	return true, nil
}
Example #21
0
func putDataE(w rest.ResponseWriter, r *rest.Request) {
	host := r.PathParam("host")
	if host == "" {
		rest.Error(w, "host is empty", 400)
		return
	}
	var jsonBody []byte
	jsonBody, _ = ioutil.ReadAll(r.Body)
	//if err != nil { log.Fatal(err) }
	simpleDataFromBody, err2 := simplejson.NewJson(jsonBody)
	if err2 != nil {
		rest.Error(w, "body (json) is empty", 400)
		return
	}

	if simpleDataFromBody.Get("message").MustString() == "" {
		rest.Error(w, "message for "+host+" is not valued", 400)
		return
	}
	if simpleDataFromBody.Get("details").MustString() == "" {
		rest.Error(w, "details for "+host+" is not valued", 400)
		return
	}

	CompteurE++
	if CompteurE%2 == 0 {
		time.Sleep(500 * time.Millisecond)
	}

	defer r.Body.Close()
	w.Header().Set("X-Host", host)
}
Example #22
0
func (c *Config) UnmarshalJSON(data []byte) error {
	js, err := simpleJson.NewJson(data)
	if err != nil {
		return err
	}
	if c.Host, err = js.Get("host").String(); err != nil {
		c.Host = ""
	}
	// Port can be string either int
	if c.Port, err = js.Get("port").Int(); err != nil {
		p, err := js.Get("port").String()
		c.Port, err = strconv.Atoi(p)
		if err != nil {
			c.Port = 0
		}
	}
	if c.UserName, err = js.Get("username").String(); err != nil {
		c.UserName = ""
	}
	if c.Password, err = js.Get("password").String(); err != nil {
		c.Password = ""
	}
	if c.CaCert, err = js.Get("caCert").String(); err != nil {
		c.CaCert = ""
	}
	if c.ClientCert, err = js.Get("clientCert").String(); err != nil {
		c.ClientCert = ""
	}
	if c.PrivateKey, err = js.Get("privateKey").String(); err != nil {
		c.PrivateKey = ""
	}
	return nil
}
Example #23
0
func RequestVars(url string) (objGoApp GoAPP, err error) {
	resp, err := http.Get(url)
	if err != nil {
		return objGoApp, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusNotFound {
		return objGoApp, errors.New("vars not found")
	} else if resp.StatusCode != http.StatusOK {
		return objGoApp, errors.New(fmt.Sprintf("request error code[%d]", resp.StatusCode))
	}
	jsonstr, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return objGoApp, err
	}
	objson, err := json.NewJson(jsonstr)
	if err != nil {
		return objGoApp, err
	}
	objGoApp.Alloc, _ = objson.Get("memstats").Get("Alloc").Int64()
	objGoApp.Sys, _ = objson.Get("memstats").Get("Sys").Int64()
	objGoApp.HeapAlloc, _ = objson.Get("memstats").Get("HeapAlloc").Int64()
	objGoApp.HeapInuse, _ = objson.Get("memstats").Get("HeapInuse").Int64()
	objGoApp.Objects, _ = objson.Get("memstats").Get("HeapObjects").Int64()
	return objGoApp, err
}
Example #24
0
func (s *Server) ListTables() ([]string, error) {
	var tables []string

	query := NewEmptyQuery()

	jsonResponse, err := s.queryServer(target("ListTables"), query)

	if err != nil {
		return nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return nil, err
	}

	response, err := json.Get("TableNames").Array()

	if err != nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return nil, errors.New(message)
	}

	for _, value := range response {
		if t, ok := (value).(string); ok {
			tables = append(tables, t)
		}
	}

	return tables, nil
}
Example #25
0
func (t *Table) getItem(key *Key, consistentRead bool) (map[string]*Attribute, error) {
	q := NewQuery(t)
	q.AddKey(t, key)

	if consistentRead {
		q.ConsistentRead(consistentRead)
	}

	jsonResponse, err := t.Server.queryServer(target("GetItem"), q)
	if err != nil {
		return nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)
	if err != nil {
		return nil, err
	}

	itemJson, ok := json.CheckGet("Item")
	if !ok {
		// We got an empty from amz. The item doesn't exist.
		return nil, ErrNotFound
	}

	item, err := itemJson.Map()
	if err != nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return nil, errors.New(message)
	}

	return parseAttributes(item), nil

}
Example #26
0
func (t *Table) PutItem(hashKey string, rangeKey string, attributes []Attribute) (bool, error) {

	if len(attributes) == 0 {
		return false, errors.New("At least one attribute is required.")
	}

	q := NewQuery(t)

	keys := t.Key.Clone(hashKey, rangeKey)
	attributes = append(attributes, keys...)

	q.AddItem(attributes)

	jsonResponse, err := t.Server.queryServer(target("PutItem"), q)

	if err != nil {
		return false, err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return false, err
	}

	units, _ := json.CheckGet("ConsumedCapacityUnits")

	if units == nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return false, errors.New(message)
	}

	return true, nil
}
Example #27
0
func (batchWriteItem *BatchWriteItem) Execute() (map[string]interface{}, error) {
	q := NewEmptyQuery()
	q.AddWriteRequestItems(batchWriteItem.ItemActions)

	jsonResponse, err := batchWriteItem.Server.queryServer("DynamoDB_20120810.BatchWriteItem", q)

	if err != nil {
		return nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return nil, err
	}

	unprocessed, err := json.Get("UnprocessedItems").Map()
	if err != nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return nil, errors.New(message)
	}

	if len(unprocessed) == 0 {
		return nil, nil
	} else {
		return unprocessed, errors.New("One or more unprocessed items.")
	}

}
Example #28
0
func (t *Table) modifyItem(key *Key, attributes []Attribute, action string) (bool, error) {

	if len(attributes) == 0 {
		return false, errors.New("At least one attribute is required.")
	}

	q := NewQuery(t)
	q.AddKey(t, key)
	q.AddUpdates(attributes, action)

	jsonResponse, err := t.Server.queryServer(target("UpdateItem"), q)

	if err != nil {
		return false, err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return false, err
	}

	units, _ := json.CheckGet("ConsumedCapacityUnits")

	if units == nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return false, errors.New(message)
	}

	return true, nil

}
Example #29
0
func buildError(r *http.Response, jsonBody []byte) error {

	ddbError := Error{
		StatusCode: r.StatusCode,
		Status:     r.Status,
	}
	// TODO return error if Unmarshal fails?

	json, err := simplejson.NewJson(jsonBody)
	if err != nil {
		log.Printf("Failed to parse body as JSON")
		return err
	}
	ddbError.Message = json.Get("Message").MustString()

	// Of the form: com.amazon.coral.validate#ValidationException
	// We only want the last part
	codeStr := json.Get("__type").MustString()
	hashIndex := strings.Index(codeStr, "#")
	if hashIndex > 0 {
		codeStr = codeStr[hashIndex+1:]
	}
	ddbError.Code = codeStr

	return &ddbError
}
Example #30
0
func (t *Table) GetItem(hashKey string, rangeKey string) (map[string]*Attribute, error) {
	q := NewQuery(t)
	q.AddKey(t, hashKey, rangeKey)

	jsonResponse, err := t.Server.queryServer(target("GetItem"), q)

	if err != nil {
		return nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return nil, err
	}

	item, err := json.Get("Item").Map()

	if err != nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return nil, errors.New(message)
	}

	return parseAttributes(item), nil
}