Exemplo n.º 1
0
func LoadJsonPermission(userReader io.Reader, groupReader io.Reader) (jPermission *JsonPermission, err os.Error) {
	// Load users
	usersDecoder := json.NewDecoder(userReader)
	var users Users
	if err = usersDecoder.Decode(&users); err != nil {
		return
	}

	// Load groups
	groupsDecoder := json.NewDecoder(groupReader)
	var groups Groups
	if err = groupsDecoder.Decode(&groups); err != nil {
		return nil, err
	}

	jPermission = &JsonPermission{
		users: make(map[string]*CachedUser),
	}

	// Cache users and merge groups into users.
	for name, user := range users {
		permissions := make([]string, len(user.Permissions))
		for i := range user.Permissions {
			permissions[i] = user.Permissions[i]
		}
		inhPerm := getInheritance(user.Groups, groups)
		for _, perm := range inhPerm {
			permissions = append(permissions, perm)
		}
		jPermission.users[name] = &CachedUser{permissions: permissions}
	}

	// Cache default user.
	defaultUser := &CachedUser{
		permissions: make([]string, 0),
	}
	for _, group := range groups {
		if group.Default {
			for _, perm := range group.Permissions {
				defaultUser.permissions = append(defaultUser.permissions, perm)
			}
			inhPerm := getInheritance(group.Inheritance, groups)
			for _, perm := range inhPerm {
				defaultUser.permissions = append(defaultUser.permissions, perm)
			}
		}
	}
	jPermission.defaultUser = defaultUser
	return jPermission, nil
}
Exemplo n.º 2
0
// deserialize decodes a value using json.
func deserialize(src []byte, dst interface{}) error {
	dec := json.NewDecoder(bytes.NewBuffer(src))
	if err := dec.Decode(dst); err != nil {
		return err
	}
	return nil
}
Exemplo n.º 3
0
func retrieveInfo(client oauth2_client.OAuth2Client, apiUrl, id string, m url.Values, value interface{}) (err os.Error) {
	uri := TWITTER_API_ENDPOINT
	for _, s := range []string{apiUrl, id} {
		if len(s) > 0 {
			if uri[len(uri)-1] != '/' {
				uri += "/"
			}
			uri += s
		}
	}
	headers := make(http.Header)
	headers.Set("Accept", "application/json")
	if m == nil {
		m = make(url.Values)
	}
	resp, _, err := oauth2_client.AuthorizedGetRequest(client, headers, uri, m)
	if err != nil {
		return err
	}
	if resp != nil {
		if resp.StatusCode >= 400 {
			var e ErrorResponse
			b, _ := ioutil.ReadAll(resp.Body)
			json.Unmarshal(b, &e)
			if len(e.Error) > 0 {
				err = os.NewError(e.Error)
			} else {
				err = os.NewError(string(b))
			}
		} else {
			err = json.NewDecoder(resp.Body).Decode(value)
		}
	}
	return err
}
Exemplo n.º 4
0
// StaticSet returns the whole of the static set members of that directory
func (dr *DirReader) StaticSet() ([]*blobref.BlobRef, os.Error) {
	if dr.staticSet != nil {
		return dr.staticSet, nil
	}
	staticSetBlobref := blobref.Parse(dr.ss.Entries)
	if staticSetBlobref == nil {
		return nil, fmt.Errorf("schema/filereader: Invalid blobref\n")
	}
	rsc, _, err := dr.fetcher.Fetch(staticSetBlobref)
	if err != nil {
		return nil, fmt.Errorf("schema/filereader: fetching schema blob %s: %v", staticSetBlobref, err)
	}
	ss := new(Superset)
	if err = json.NewDecoder(rsc).Decode(ss); err != nil {
		return nil, fmt.Errorf("schema/filereader: decoding schema blob %s: %v", staticSetBlobref, err)
	}
	if ss.Type != "static-set" {
		return nil, fmt.Errorf("schema/filereader: expected \"static-set\" schema blob for %s, got %q", staticSetBlobref, ss.Type)
	}
	for _, s := range ss.Members {
		member := blobref.Parse(s)
		if member == nil {
			return nil, fmt.Errorf("schema/filereader: invalid (static-set member) blobref\n")
		}
		dr.staticSet = append(dr.staticSet, member)
	}
	return dr.staticSet, nil
}
Exemplo n.º 5
0
func configure(flags ServerConfig) {
	if flag.NArg() == 1 {
		fname := flag.Arg(0)
		f, err := os.Open(fname)
		if err != nil {
			log.Fatalf("Config reading error: %s\n", err.String())
		}
		dec := json.NewDecoder(f)
		err = dec.Decode(&server)
		if err != nil {
			log.Fatalf("Config parsing error: %s\n", err.String())
		}
		action = "serve"
	}
	flag.Visit(func(flag *flag.Flag) {
		switch flag.Name {
		case "version":
			action = "version"
		case "port":
			server.Port = flags.Port
		case "host":
			server.Host = flags.Host
		case "tls-cert":
			server.TLSCertFile = flags.TLSCertFile
		case "tls-key":
			server.TLSKeyFile = flags.TLSKeyFile
		case "log":
			server.Log = flags.Log
		}
	})
}
Exemplo n.º 6
0
func (self *target) loadProfile(packageName string) os.Error {
	file, err := os.Open(packageName + ".gofiles")
	if err != nil {
		return err
	}
	defer file.Close()
	var prof Profile
	if err := json.NewDecoder(file).Decode(&prof); err != nil {
		return err
	}
	if packageName != "main" {
		self.targetName = prof.Target
	}
	for _, entry := range prof.GoFiles {
		// TODO parse wildcard and ~
		if _, exist := self.files[entry]; exist {
			continue
		}
		if src, err := self.ctx.getSource(entry); err != nil {
			return err
		} else if src != nil && src.packageName == packageName {
			self.files[src.filepath] = src
		}
	}
	return nil
}
Exemplo n.º 7
0
func TestServer(t *testing.T) {
	type addResp struct {
		Id     interface{} "id"
		Result Reply       "result"
		Error  string      "error"
	}

	cli, srv := net.Pipe()
	defer cli.Close()
	go ServeConn(srv)
	dec := json.NewDecoder(cli)

	// Send hand-coded requests to server, parse responses.
	for i := 0; i < 10; i++ {
		fmt.Fprintf(cli, `{"method": "Arith.Add", "id": "\u%04d", "params": [{"A": %d, "B": %d}]}`, i, i, i+1)
		var resp addResp
		err := dec.Decode(&resp)
		if err != nil {
			t.Fatalf("Decode: %s", err)
		}
		if resp.Error != "" {
			t.Fatalf("resp.Error: %s", resp.Error)
		}
		if resp.Id.(string) != string(i) {
			t.Fatalf("resp: bad id %q want %q", resp.Id.(string), string(i))
		}
		if resp.Result.C != 2*i+1 {
			t.Fatalf("resp: bad result: %d+%d=%d", i, i+1, resp.Result.C)
		}
	}
}
Exemplo n.º 8
0
func retrieveInfo(client oauth2_client.OAuth2Client, id, scope string, value interface{}) (err os.Error) {
	uri := FACEBOOK_GRAPH_API_ENDPOINT
	for _, s := range []string{id, scope} {
		if len(s) > 0 {
			if uri[len(uri)-1] != '/' {
				uri += "/"
			}
			uri += s
		}
	}
	resp, _, err := oauth2_client.AuthorizedGetRequest(client, nil, uri, nil)
	if err != nil {
		return err
	}
	if resp != nil {
		if resp.StatusCode >= 400 {
			e := new(ErrorResponse)
			b, _ := ioutil.ReadAll(resp.Body)
			if err = json.Unmarshal(b, e); err != nil {
				err = os.NewError(string(b))
			} else {
				err = e
			}
		} else {
			err = json.NewDecoder(resp.Body).Decode(value)
		}
	}
	return err
}
Exemplo n.º 9
0
func (p *MockGoogleClient) handleCreateGroup(req *http.Request) (resp *http.Response, err os.Error) {
	//fmt.Printf("calling handleCreateGroup\n")
	b := NewGroupResponse()
	err = json.NewDecoder(req.Body).Decode(b)
	if err != nil {
		panic(fmt.Sprintf("Error creating group: %s\n", err.String()))
		resp, _ = createJSONHttpResponseFromObj(req, NewGroupResponse())
		resp.Status = "500 INTERNAL SERVER ERROR"
		resp.StatusCode = http.StatusInternalServerError
		return
	}
	if b.Entry == nil {
		resp, err = createJSONHttpResponseFromObj(req, NewGroupResponse())
		resp.Status = "400 BAD REQUEST"
		resp.StatusCode = http.StatusBadRequest
		return
	}
	e := b.Entry
	groupId := p.generateId()
	e.Id.Value = groupId
	e.Etag = p.generateEtag()
	e.Updated.Value = time.UTC().Format(GOOGLE_DATETIME_FORMAT)
	p.groupsById[groupId] = e
	r := NewGroupResponse()
	r.Entry = e
	r.Entry.Xmlns = XMLNS_ATOM
	r.Entry.XmlnsGcontact = XMLNS_GCONTACT
	r.Entry.XmlnsBatch = XMLNS_GDATA_BATCH
	r.Entry.XmlnsGd = XMLNS_GD
	//fmt.Printf("Contact Entry: %v\n", c.Name)
	return createJSONHttpResponseFromObj(req, r)
}
Exemplo n.º 10
0
// home handles requests to the home page.
func home(req *web.Request) {
	token, err := credentials(req, "tok")
	if err != nil {
		homeLoggedOut(req)
		return
	}
	param := make(web.Values)
	url := "http://api.twitter.com/1/statuses/home_timeline.json"
	oauthClient.SignParam(token, "GET", url, param)
	url = url + "?" + param.FormEncodedString()
	resp, err := http.Get(url)
	if err != nil {
		req.Error(web.StatusInternalServerError, err)
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		req.Error(web.StatusInternalServerError, os.NewError(fmt.Sprint("Status ", resp.StatusCode)))
		return
	}
	var d interface{}
	err = json.NewDecoder(resp.Body).Decode(&d)
	if err != nil {
		req.Error(web.StatusInternalServerError, err)
		return
	}
	homeTempl.Execute(req.Respond(web.StatusOK, web.HeaderContentType, web.ContentTypeHTML), d)
}
Exemplo n.º 11
0
func LoadBlockDefs(reader io.Reader) (blocks BlockTypeList, err os.Error) {
	blocksStr := make(map[string]blockDef)
	decoder := json.NewDecoder(reader)
	err = decoder.Decode(&blocksStr)

	// Find the max block ID so we allocate the correct amount of memory. Also
	// range check the IDs.
	maxId := 0
	for idStr := range blocksStr {
		var id int
		id, err = strconv.Atoi(idStr)
		if err != nil {
			return
		}
		if id < BlockIdMin || id > BlockIdMax {
			err = os.NewError(fmt.Sprintf(
				"Encountered block type with ID %d which is outside the range"+
					"%d <= N <= %d", id, BlockIdMin, BlockIdMax))
			return
		}
		if id > maxId {
			maxId = id
		}
	}

	// Convert map string keys to ints.
	blocks = make(BlockTypeList, maxId+1)
	for idStr, blockDef := range blocksStr {
		var id int
		id, _ = strconv.Atoi(idStr)

		if blocks[id].defined {
			err = os.NewError(fmt.Sprintf(
				"Block ID %d defined more than once.", id))
		}

		var block *BlockType
		block, err = blockDef.LoadBlockType()
		if err != nil {
			return
		}
		block.id = BlockId(id)
		block.defined = true
		blocks[id] = *block
	}

	// Put VoidAspect in any undefined blocks rather than leave it nil, and also
	// set id on each block type.
	for id := range blocks {
		block := &blocks[id]
		block.id = BlockId(id)
		if !block.defined {
			void := makeVoidAspect()
			block.Aspect = void
			void.setAttrs(&block.BlockAttrs)
		}
	}

	return
}
Exemplo n.º 12
0
func (this *JSONInterface) Start() {
	for {
		d := json.NewDecoder(this.Conn)
		req := NewJSONRequest()
		err := d.Decode(req)
		if err != nil {
			fmt.Printf("%s\n", err)
			break
		}
		switch req.Action {
		case "stream":
			fmt.Printf("It's a stream request\n")
			port := int32(req.Parameters["port"].(float64))
			nodeid_string := req.Parameters["nodeid"].(string)
			nodeid := make([]byte, 20)
			_, err := fmt.Sscanf(nodeid_string, "%x", &nodeid)
			if err != nil {
				fmt.Printf("%s\n", err)
				break
			}
			fmt.Printf("nodeid: %x\n", nodeid)
			this.PipeStream(nodeid, port)
		case "store":

		}
	}
}
Exemplo n.º 13
0
func parseConfig() {
	configPath := ConfigFilePath()
	f, err := os.Open(configPath)
	switch {
	case err != nil && err.(*os.PathError).Error.(os.Errno) == syscall.ENOENT:
		// TODO: write empty file?
		return
	case err != nil:
		log.Printf("Error opening config file %q: %v", ConfigFilePath(), err)
		return
	}
	defer f.Close()
	dj := json.NewDecoder(f)
	if err := dj.Decode(&config); err != nil {
		extra := ""
		if serr, ok := err.(*json.SyntaxError); ok {
			if _, serr := f.Seek(0, os.SEEK_SET); serr != nil {
				log.Fatalf("seek error: %v", serr)
			}
			line, col, highlight := errorutil.HighlightBytePosition(f, serr.Offset)
			extra = fmt.Sprintf(":\nError at line %d, column %d (file offset %d):\n%s",
				line, col, serr.Offset, highlight)
		}
		log.Fatalf("error parsing JSON object in config file %s%s\n%v",
			ConfigFilePath(), extra, err)
	}
	if err := jsonconfig.EvaluateExpressions(config); err != nil {
		log.Fatalf("error expanding JSON config expressions in %s: %v", configPath, err)
	}

}
Exemplo n.º 14
0
func LoadDatabase(dir string) Database {
	d := make([]*Motif, 0)
	dirHandle, ok := os.Open(dir)
	if ok != nil {
		panic("database failure" + ok.String())
	}

	dbnames, _ := dirHandle.Readdirnames(0)

LOAD:
	for _, fname := range dbnames {
		if !strings.HasSuffix(fname, ".zellij") {
			continue
		}
		entry, _ := os.Open(path.Join(dir, fname))
		data := make([]*quadratic.Map, 2)
		data[0], data[1] = quadratic.NewMap(), quadratic.NewMap()
		json.NewDecoder(entry).Decode(&data)

		for _, m := range d {
			if m.Frame.Isomorphic(data[0]) {
				m.Variations = append(m.Variations, data[1])
				continue LOAD
			}
		}
		d = append(d, &Motif{fname, data[0], []*quadratic.Map{data[1]}, nil})
	}

	fmt.Fprintf(os.Stderr, "Loaded database with %v frames\n", len(d))

	return d
}
func (p *JSONMediaTypeInputHandler) OutputTo(req wm.Request, cxt wm.Context, writer io.Writer) (int, http.Header, os.Error) {
	defer func() {
		if p.reader != nil {
			if closer, ok := p.reader.(io.Closer); ok {
				closer.Close()
			}
		}
	}()
	//log.Printf("[JSONMTIH]: Calling OutputTo with reader %v\n", p.reader)
	if p.reader == nil {
		return p.handler.HandleJSONObjectInputHandler(req, cxt, writer, nil)
	}
	obj := jsonhelper.NewJSONObject()
	dec := json.NewDecoder(p.reader)
	err := dec.Decode(&obj)
	if err != nil {
		headers := make(http.Header)
		//headers.Set("Content-Type", wm.MIME_TYPE_JSON)
		m := jsonhelper.NewJSONObject()
		w := json.NewEncoder(writer)
		m.Set("status", "error")
		m.Set("message", err.String())
		m.Set("result", nil)
		w.Encode(m)
		return 500, headers, err
	}
	return p.handler.HandleJSONObjectInputHandler(req, cxt, writer, obj)
}
Exemplo n.º 16
0
func (user *TwUser) Get(r io.Reader) os.Error {
	dec := json.NewDecoder(r)
	if err := dec.Decode(user); err != nil {
		return err
	}
	return nil
}
Exemplo n.º 17
0
func (fs *CamliFileSystem) fetchSchemaSuperset(br *blobref.BlobRef) (*schema.Superset, os.Error) {
	blobStr := br.String()
	if ss, ok := fs.blobToSchema.Get(blobStr); ok {
		return ss.(*schema.Superset), nil
	}
	log.Printf("schema cache MISS on %q", blobStr)

	rsc, _, err := fs.fetcher.Fetch(br)
	if err != nil {
		return nil, err
	}
	defer rsc.Close()
	jd := json.NewDecoder(rsc)
	ss := new(schema.Superset)
	err = jd.Decode(ss)
	if err != nil {
		log.Printf("Error parsing %s as schema blob: %v", br, err)
		return nil, os.EINVAL
	}
	if ss.Type == "" {
		log.Printf("blob %s is JSON but lacks camliType", br)
		return nil, os.EINVAL
	}
	ss.BlobRef = br
	fs.blobToSchema.Add(blobStr, ss)
	return ss, nil
}
Exemplo n.º 18
0
func (tl *TwTimeLine) Get(r io.Reader) os.Error {
	dec := json.NewDecoder(r)
	if err := dec.Decode(tl); err != nil {
		return err
	}
	return nil
}
func (c *WebResourceGetTokenCall) Do() (*SiteverificationWebResourceGettokenResponse, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	if v, ok := c.opt_["verificationMethod"]; ok {
		params.Set("verificationMethod", fmt.Sprintf("%v", v))
	}
	if v, ok := c.opt_["identifier"]; ok {
		params.Set("identifier", fmt.Sprintf("%v", v))
	}
	if v, ok := c.opt_["type"]; ok {
		params.Set("type", fmt.Sprintf("%v", v))
	}
	urls := googleapi.ResolveRelative("https://www.googleapis.com/siteVerification/v1/", "token")
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("GET", urls, body)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(SiteverificationWebResourceGettokenResponse)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Get a verification token for placing on a website or domain.",
	//   "httpMethod": "GET",
	//   "id": "siteVerification.webResource.getToken",
	//   "parameters": {
	//     "identifier": {
	//       "description": "The URL or domain to verify.",
	//       "location": "query",
	//       "type": "string"
	//     },
	//     "type": {
	//       "description": "Type of resource to verify. Can be 'site' (URL) or 'inet_domain' (domain name).",
	//       "location": "query",
	//       "type": "string"
	//     },
	//     "verificationMethod": {
	//       "description": "The method to use for verifying a site or domain.",
	//       "location": "query",
	//       "type": "string"
	//     }
	//   },
	//   "path": "token",
	//   "response": {
	//     "$ref": "SiteverificationWebResourceGettokenResponse"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/siteverification"
	//   ]
	// }

}
Exemplo n.º 20
0
// ListKeys is generally discouraged in production (see http://wiki.basho.com/HTTP-List-Keys.html)
func ListKeys(c Client, b string, outch chan<- string, cc *http.ClientConn) (err os.Error) {
	resp, err := GetItem(c, b, "", http.Header{"Accept": []string{"application/json"}},
		http.Values{
			"keys":  []string{"stream"},
			"props": []string{"false"},
		}, cc)
	if resp != nil && resp.StatusCode == 200 {

		dec := json.NewDecoder(resp.Body)
		bi := BucketDetails{}
		for err = dec.Decode(&bi); err == nil; err = dec.Decode(&bi) {
			for i := range bi.Keys {
				outch <- bi.Keys[i]
			}
		}
		if err == os.EOF {
			err = nil
		}
	} else {
		return debugFailf(os.Stdout, true, "Unexpected response: %s", resp.Status)(resp)
	}
	close(outch)
	return

}
func (c *WebResourceListCall) Do() (*SiteverificationWebResourceListResponse, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	urls := googleapi.ResolveRelative("https://www.googleapis.com/siteVerification/v1/", "webResource")
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("GET", urls, body)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(SiteverificationWebResourceListResponse)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Get the list of your verified websites and domains.",
	//   "httpMethod": "GET",
	//   "id": "siteVerification.webResource.list",
	//   "path": "webResource",
	//   "response": {
	//     "$ref": "SiteverificationWebResourceListResponse"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/siteverification"
	//   ]
	// }

}
Exemplo n.º 22
0
//function that fetches the exchange rate from bitcoincharts
func getExchangeRate(c appengine.Context) float32 {

	client := urlfetch.Client(c)
	resp, err := client.Get("http://bitcoincharts.com/t/weighted_prices.json")
	if err != nil {
		log.Print("getExchangeRate err ", err)
		return -1.0
	}

	//decode the json
	dec := json.NewDecoder(resp.Body)

	var f interface{}
	if err2 := dec.Decode(&f); err != nil {
		log.Println("getExchangeRate err2 ", err2)
		return -1.0
	}

	m := f.(map[string]interface{})
	//get the value for USD 24h
	tmptocheck := m["USD"].(map[string]interface{})["24h"]

	switch v := tmptocheck.(type) {
	case string: //if value is string, it converts it
		newValue, _ := strconv.Atof32(tmptocheck.(string))
		//log.Print(newValue)
		return newValue
	default: //otherwise returns a false value (in case no data is fetched or something)
		return -1.0
	}

	return -1.0
}
Exemplo n.º 23
0
func ExpandURL(shortUrl string) (expandedUrl string, err os.Error) {
	param := http.EncodeQuery(map[string][]string{"shortUrl": {shortUrl}})
	res, _, err := http.Get("https://www.googleapis.com/urlshortener/v1/url?" + param)
	if err != nil {
		return
	}
	if res.StatusCode != 200 {
		err = os.NewError("failed to post")
		return
	}
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}
	var decbuf bytes.Buffer
	decbuf.Write(b)
	dec := json.NewDecoder(&decbuf)
	var out map[string]interface{}
	err = dec.Decode(&out)
	if err != nil {
		return
	}
	expandedUrl = out["longUrl"].(string)
	return
}
Exemplo n.º 24
0
func ShortenURL(longUrl string) (shortenUrl string, err os.Error) {
	var encbuf bytes.Buffer
	enc := json.NewEncoder(&encbuf)
	err = enc.Encode(map[string]string{"longUrl": longUrl})
	if err != nil {
		return
	}
	res, err := http.Post("https://www.googleapis.com/urlshortener/v1/url", "application/json", strings.NewReader(encbuf.String()))
	if err != nil {
		return
	}
	if res.StatusCode != 200 {
		err = os.NewError("failed to post")
		return
	}
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}
	var decbuf bytes.Buffer
	decbuf.Write(b)
	dec := json.NewDecoder(&decbuf)
	var out map[string]interface{}
	err = dec.Decode(&out)
	if err != nil {
		return
	}
	shortenUrl = out["id"].(string)
	return
}
Exemplo n.º 25
0
// NewClientCodec returns a new rpc.ClientCodec using JSON-RPC on conn.
func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec {
	return &clientCodec{
		dec:     json.NewDecoder(conn),
		enc:     json.NewEncoder(conn),
		c:       conn,
		pending: make(map[uint64]string),
	}
}
Exemplo n.º 26
0
// NewServerCodec returns a new rpc.ServerCodec using JSON-RPC on conn.
func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec {
	return &serverCodec{
		dec:     json.NewDecoder(conn),
		enc:     json.NewEncoder(conn),
		c:       conn,
		pending: make(map[uint64]*json.RawMessage),
	}
}
Exemplo n.º 27
0
func (c *BadgesGetCall) Do() (*Badge, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	urls := googleapi.ResolveRelative("https://www.googleapis.com/orkut/v2/", "people/{userId}/badges/{badgeId}")
	urls = strings.Replace(urls, "{userId}", cleanPathString(c.userId), 1)
	urls = strings.Replace(urls, "{badgeId}", strconv.Itoa64(c.badgeId), 1)
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("GET", urls, body)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(Badge)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Retrieves a badge from a user.",
	//   "httpMethod": "GET",
	//   "id": "orkut.badges.get",
	//   "parameterOrder": [
	//     "userId",
	//     "badgeId"
	//   ],
	//   "parameters": {
	//     "badgeId": {
	//       "description": "The ID of the badge that will be retrieved.",
	//       "format": "int64",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     },
	//     "userId": {
	//       "description": "The ID of the user whose badges will be listed. Can be me to refer to caller.",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     }
	//   },
	//   "path": "people/{userId}/badges/{badgeId}",
	//   "response": {
	//     "$ref": "Badge"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/orkut",
	//     "https://www.googleapis.com/auth/orkut.readonly"
	//   ]
	// }

}
func (c *AdclientsListCall) Do() (*AdClients, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	if v, ok := c.opt_["maxResults"]; ok {
		params.Set("maxResults", fmt.Sprintf("%v", v))
	}
	if v, ok := c.opt_["pageToken"]; ok {
		params.Set("pageToken", fmt.Sprintf("%v", v))
	}
	urls := googleapi.ResolveRelative("https://www.googleapis.com/adsense/v1/", "adclients")
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("GET", urls, body)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(AdClients)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "List all ad clients in this AdSense account.",
	//   "httpMethod": "GET",
	//   "id": "adsense.adclients.list",
	//   "parameters": {
	//     "maxResults": {
	//       "description": "The maximum number of ad clients to include in the response, used for paging.",
	//       "format": "int32",
	//       "location": "query",
	//       "maximum": "10000",
	//       "minimum": "0",
	//       "type": "integer"
	//     },
	//     "pageToken": {
	//       "description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
	//       "location": "query",
	//       "type": "string"
	//     }
	//   },
	//   "path": "adclients",
	//   "response": {
	//     "$ref": "AdClients"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/adsense",
	//     "https://www.googleapis.com/auth/adsense.readonly"
	//   ]
	// }

}
Exemplo n.º 29
0
func UpdateGroup(client oauth2_client.OAuth2Client, userId, projection string, original, value *ContactGroup) (response *GroupResponse, err os.Error) {
	var useUserId string
	if len(userId) <= 0 {
		useUserId = GOOGLE_DEFAULT_USER_ID
	} else {
		useUserId = url.QueryEscape(userId)
	}
	if len(projection) <= 0 {
		projection = GOOGLE_DEFAULT_PROJECTION
	}
	headers := make(http.Header)
	headers.Set("GData-Version", "3.0")
	headers.Set("If-Match", original.Etag)
	m := make(url.Values)
	if len(m.Get(CONTACTS_ALT_PARAM)) <= 0 {
		m.Set(CONTACTS_ALT_PARAM, "json")
	}
	uri := GOOGLE_GROUPS_API_ENDPOINT
	for _, s := range []string{useUserId, projection, original.GroupId()} {
		if len(s) > 0 {
			if uri[len(uri)-1] != '/' {
				uri += "/"
			}
			uri += s
		}
	}
	entry := &GroupEntryUpdateRequest{Entry: value}
	value.Xmlns = XMLNS_ATOM
	value.XmlnsGcontact = XMLNS_GCONTACT
	value.XmlnsBatch = XMLNS_GDATA_BATCH
	value.XmlnsGd = XMLNS_GD
	value.Etag = original.Etag
	value.Id = original.Id
	value.Updated.Value = time.UTC().Format(GOOGLE_DATETIME_FORMAT)
	value.Categories = make([]AtomCategory, 1)
	value.Categories[0].Scheme = ATOM_CATEGORY_SCHEME_KIND
	value.Categories[0].Term = ATOM_CATEGORY_TERM_GROUP
	buf, err := json.Marshal(entry)
	if err != nil {
		return
	}
	resp, _, err := oauth2_client.AuthorizedPutRequestBytes(client, headers, uri, m, buf)
	if err != nil {
		return
	}
	if resp != nil {
		if resp.StatusCode >= 400 {
			b, _ := ioutil.ReadAll(resp.Body)
			err = os.NewError(string(b))
		} else {
			response = new(GroupResponse)
			err = json.NewDecoder(resp.Body).Decode(response)
		}
	}
	return
}
func (c *TrainedmodelsPredictCall) Do() (*Output, os.Error) {
	var body io.Reader = nil
	body, err := googleapi.WithoutDataWrapper.JSONReader(c.input)
	if err != nil {
		return nil, err
	}
	ctype := "application/json"
	params := make(url.Values)
	params.Set("alt", "json")
	urls := googleapi.ResolveRelative("https://www.googleapis.com/prediction/v1.4/", "trainedmodels/{id}/predict")
	urls = strings.Replace(urls, "{id}", cleanPathString(c.id), 1)
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("POST", urls, body)
	req.Header.Set("Content-Type", ctype)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(Output)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Submit model id and request a prediction",
	//   "httpMethod": "POST",
	//   "id": "prediction.trainedmodels.predict",
	//   "parameterOrder": [
	//     "id"
	//   ],
	//   "parameters": {
	//     "id": {
	//       "description": "The unique name for the predictive model.",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     }
	//   },
	//   "path": "trainedmodels/{id}/predict",
	//   "request": {
	//     "$ref": "Input"
	//   },
	//   "response": {
	//     "$ref": "Output"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/prediction"
	//   ]
	// }

}