Beispiel #1
0
func (p *PicasaAPI) parseAlbums(js interface{}) ([]*PicasaAlbum, error) {
	jq := jsonq.NewQuery(js)
	entries, _ := jq.Array("feed", "entry")
	albums := make([]*PicasaAlbum, len(entries))

	for i, entry := range entries {
		eq := jsonq.NewQuery(entry)
		album := new(PicasaAlbum)
		album.ApiUrl, _ = eq.String("id", "$t")
		album.AlbumId, _ = eq.String("gphoto$id", "$t")
		album.Published, _ = eq.String("published", "$t")
		album.Updated, _ = eq.String("updated", "$t")
		album.Title, _ = eq.String("title", "$t")
		album.Summary, _ = eq.String("summary", "$t")
		album.Rights, _ = eq.String("gphoto$access", "$t")
		album.NumPhotos, _ = eq.Int("gphoto$numphotos", "$t")
		links, _ := eq.Array("link")
		for _, link := range links {
			lq := jsonq.NewQuery(link)
			s, err := lq.String("href")
			if err != nil {
				continue
			}
			album.Links = append(album.Links, s)
		}
		album.AlbumType, _ = eq.String("gphoto$albumType", "$t")
		album.Thumbnail, _ = eq.String("media$group", "media$thumbnail", "0", "url")
		albums[i] = album
	}
	return albums, nil
}
Beispiel #2
0
func (p *PicasaAPI) parsePhotos(js interface{}) ([]*PicasaPhoto, error) {
	jq := jsonq.NewQuery(js)
	entries, _ := jq.Array("feed", "entry")
	photos := make([]*PicasaPhoto, len(entries))

	for i, entry := range entries {
		eq := jsonq.NewQuery(entry)
		photo := new(PicasaPhoto)
		photo.ApiUrl, _ = eq.String("id", "$t")
		photo.PhotoId, _ = eq.String("gphoto$id", "$t")
		photo.AlbumId, _ = eq.String("gphoto$albumid", "$t")
		photo.Published, _ = eq.String("published", "$t")
		photo.Updated, _ = eq.String("updated", "$t")
		photo.Title, _ = eq.String("title", "$t")
		photo.Summary, _ = eq.String("summary", "$t")
		photo.Rights, _ = eq.String("gphoto$access", "$t")
		links, _ := eq.Array("link")
		for _, link := range links {
			lq := jsonq.NewQuery(link)
			s, err := lq.String("href")
			if err != nil {
				continue
			}
			photo.Links = append(photo.Links, s)
		}
		photo.Height, _ = eq.Int("gphoto$height", "$t")
		photo.Width, _ = eq.Int("gphoto$width", "$t")
		photo.Size, _ = eq.Int("gphoto$size", "$t")

		photo.Large.Url, _ = eq.String("media$group", "media$content", "0", "url")
		photo.Large.Height, _ = eq.Int("media$group", "media$content", "0", "height")
		photo.Large.Width, _ = eq.Int("media$group", "media$content", "0", "width")

		photo.Position, _ = eq.Int("gphoto$position", "$t")

		thumbnails, _ := eq.Array("media$group", "media$thumbnail")
		for _, thumb := range thumbnails {
			tq := jsonq.NewQuery(thumb)
			t := Image{}
			t.Url, _ = tq.String("url")
			t.Height, _ = tq.Int("height")
			t.Width, _ = tq.Int("width")
			photo.Thumbnails = append(photo.Thumbnails, t)
		}

		photo.ExifTags = map[string]string{}

		tags, _ := eq.Object("exif$tags")
		for key, obj := range tags {
			oq := jsonq.NewQuery(obj)
			photo.ExifTags[key], _ = oq.String("$t")
		}

		photos[i] = photo
	}
	return photos, nil
}
func getCord(address, city, state, zip string) (lat, lng float64) {
	// request http api
	res, err := http.Get(strings.Replace("http://maps.google.com/maps/api/geocode/json?address="+address+",+"+city+",+"+state+",+"+zip+"&sensor=false", " ", "+", -1))
	if err != nil {
		log.Fatal(err)
	}

	body, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		log.Fatal(err)
	}

	if res.StatusCode != 200 {
		log.Fatal("Unexpected status code", res.StatusCode)
	}
	data := map[string]interface{}{}
	dec := json.NewDecoder(strings.NewReader(string(body)))
	err = dec.Decode(&data)
	if err != nil {
		fmt.Println(err)
	}
	jq := jsonq.NewQuery(data)

	lat, err = jq.Float("results", "0", "geometry", "location", "lat")
	if err != nil {
		fmt.Println(err)
	}

	lng, err = jq.Float("results", "0", "geometry", "location", "lng")
	if err != nil {
		fmt.Println(err)
	}
	return
}
func pricetoBegin(x string) (y Data) {
	var price []int
	response, err := http.Get(x)
	if err != nil {
		return
	}
	defer response.Body.Close()
	resp := make(map[string]interface{})
	body, _ := ioutil.ReadAll(response.Body)
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return
	}
	ptr := resp["prices"].([]interface{})
	jq := jsonq.NewQuery(resp)
	for i, _ := range ptr {
		pr, _ := jq.Int("prices", fmt.Sprintf("%d", i), "low_estimate")
		price = append(price, pr)
	}
	min := price[0]
	for j, _ := range price {
		if price[j] <= min && price[j] != 0 {
			min = price[j]
		}
	}
	du, _ := jq.Int("prices", "0", "duration")
	dist, _ := jq.Float("prices", "0", "distance")
	d := Data{
		id:       "",
		price:    min,
		duration: du,
		distance: dist,
	}
	return d
}
Beispiel #5
0
// getCrittercismOAuthToken fetches a new OAuth Token from the Crittercism API given a username and password
func getCrittercismOAuthToken(login, password string) (token string, expires int, err error) {
	var params = fmt.Sprintf(`{"login": "******", "password": "******"}}`, login, password)

	// Construct REST Request
	url := fmt.Sprintf("%s/token", crittercismAPIURL)
	p := []byte(params)
	client := &http.Client{}
	req, _ := http.NewRequest("POST", url, bytes.NewBuffer(p))
	req.Header.Set("Content-Type", "application/json")

	// Make Request
	if resp, err := client.Do(req); err == nil {
		defer resp.Body.Close()

		// Parse JSON
		if body, err := ioutil.ReadAll(resp.Body); err == nil {
			data := map[string]interface{}{}
			dec := json.NewDecoder(strings.NewReader(string(body)))
			dec.Decode(&data)
			jq := jsonq.NewQuery(data)

			// Parse out the token
			token, _ := jq.String("access_token")
			expires, _ := jq.Int("expires")
			return token, expires, nil

		} else {
			return "", 0, err // Parse Error
		}

	} else {
		return "", 0, err // Request Error
	}
}
Beispiel #6
0
// NewSong creates a track and adds to the queue
func (mc Mixcloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offset int) (Song, error) {
	title, _ := trackData.String("name")
	id, _ := trackData.String("slug")
	duration, _ := trackData.Int("audio_length")
	url, _ := trackData.String("url")
	thumbnail, err := trackData.String("pictures", "large")
	if err != nil {
		// Song has no artwork, using profile avatar instead
		userObj, _ := trackData.Object("user")
		thumbnail, _ = jsonq.NewQuery(userObj).String("pictures", "thumbnail")
	}

	song := &AudioTrack{
		id:        id,
		title:     title,
		url:       url,
		thumbnail: thumbnail,
		submitter: user,
		duration:  duration,
		offset:    offset,
		format:    "best",
		skippers:  make([]string, 0),
		dontSkip:  false,
		service:   mc,
	}
	return song, nil
}
Beispiel #7
0
// GetItemName returns the name of a given id in the language provided
func (c *Census) GetItemName(id int, lang string) string {
	tmp := map[string]interface{}{}
	url := fmt.Sprintf("%vget/%v/item/?item_id=%v", BaseURL, c.namespace, id)
	if err := decodeURL(url, &tmp); err != nil {
		return err.Error()
	}
	jq := jsonq.NewQuery(tmp)
	a, _ := jq.ArrayOfObjects("item_list")
	item := a[0]
	q := jsonq.NewQuery(item)
	if lang == "" {
		lang = "en"
	}
	s, _ := q.String("name", lang)
	return s
}
Beispiel #8
0
func (c *Home) WSMain(in *goboots.In) *goboots.Out {

	defer in.Wsock.Close()

	type Resp struct {
		Success bool        `json:"success"`
		Error   string      `json:"error"`
		Kind    string      `json:"kind"`
		Payload interface{} `json:"payload"`
	}

	for {
		in.Wsock.SetWriteDeadline(time.Now().Add(time.Hour))
		in.Wsock.SetReadDeadline(time.Now().Add(time.Hour))
		raw := make(map[string]interface{})
		log.Println("[ws] will read msg")
		err := in.Wsock.ReadJSON(&raw)
		if err != nil {
			log.Println("[ws] error", err)
			return nil
		}
		q := jsonq.NewQuery(raw)
		kind, _ := q.String("kind")
		if kind == "top" {
			in.Wsock.WriteJSON(&Resp{true, "", "top", utils.GetLastTop()})
		}
	}
	return nil
}
func makeQuery(msg []byte) *jsonq.JsonQuery {
	data := map[string]interface{}{}
	dec := json.NewDecoder(bytes.NewReader(msg))
	dec.Decode(&data)
	jq := jsonq.NewQuery(data)
	return jq
}
Beispiel #10
0
func (c *Context) HTTPGetJSON(url string) (*jsonq.JsonQuery, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Accept", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 300 {
		return nil, fmt.Errorf("%v: returned %v", url, resp.Status)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	data := make(map[string]interface{})
	err = json.Unmarshal(body, &data)
	if err != nil {
		return nil, err
	}
	return jsonq.NewQuery(data), nil
}
Beispiel #11
0
func (l *localExecDriver) initCommandFromSession() error {
	if l.session == nil {
		return fmt.Errorf("localexec: unable to init command with nil session")
	}

	// Fetch all the values first
	jq := jsonq.NewQuery(l.session.Profile().GetParams())
	name, err := jq.String("command", "name")
	if err != nil {
		return err
	}
	args, err := jq.ArrayOfStrings("command", "args")
	if err != nil {
		return err
	}

	// Sanity checks
	if name == "" {
		return fmt.Errorf("localexec: profile param error: empty command")
	}

	l.cmd = exec.Command(name)
	if args != nil && len(args) > 0 {
		l.cmd.Args = append(l.cmd.Args, args...)
	}

	log.Printf("localexec: session assigned with command %v", l.cmd)
	return nil
}
func (p *Resource) NotifyMarathonHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infof("NotifyMarathonHandler is called!")

	dat, err := ioutil.ReadAll(req.Request.Body)

	if err != nil {
		logrus.Errorf("read notification body failed, error is %v", err)
		return
	}

	s := string(dat[:len(dat)])

	jsondata := map[string]interface{}{}
	result := json.NewDecoder(strings.NewReader(s))
	result.Decode(&jsondata)
	jq := jsonq.NewQuery(jsondata)
	value, _ := jq.String("eventType")
	logrus.Infof("Marathon callback starting ......................")
	logrus.Infof("Notification is %s", s)
	logrus.Infof("eventType is %s", value)

	res := response.Response{Success: true}
	resp.WriteEntity(res)
	return
}
Beispiel #13
0
// PerformGetRequest does all the grunt work for HTTPS GET request.
func PerformGetRequest(url string) (*jsonq.JsonQuery, error) {
	jsonString := ""

	if response, err := http.Get(url); err == nil {
		defer response.Body.Close()
		if response.StatusCode == 200 {
			if body, err := ioutil.ReadAll(response.Body); err == nil {
				jsonString = string(body)
			}
		} else {
			if response.StatusCode == 403 {
				return nil, errors.New("Invalid API key supplied.")
			}
			return nil, errors.New("Invalid ID supplied.")
		}
	} else {
		return nil, errors.New("An error occurred while receiving HTTP GET response.")
	}

	jsonData := map[string]interface{}{}
	decoder := json.NewDecoder(strings.NewReader(jsonString))
	decoder.Decode(&jsonData)
	jq := jsonq.NewQuery(jsonData)

	return jq, nil
}
Beispiel #14
0
func (self *Baidu) Mkdir(path string) error {
	url := fmt.Sprintf("https://pcs.baidu.com/rest/2.0/pcs/file?method=mkdir&access_token=%s", self.token.AccessToken)
	url += "&path=" + neturl.QueryEscape(fmt.Sprintf("/apps/%s/%s", self.dir, path))

	buf := new(bytes.Buffer)
	form := multipart.NewWriter(buf)
	form.Close()
	resp, err := self.client.Post(url, form.FormDataContentType(), buf)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	buf.Reset()
	_, err = io.Copy(buf, resp.Body)
	if err != nil {
		return errors.New("response body read error")
	}
	respBody := make(map[string]interface{})
	err = json.NewDecoder(buf).Decode(&respBody)
	if err != nil {
		return errors.New("return json decode error")
	}
	q := jsonq.NewQuery(respBody)
	if resp.StatusCode != http.StatusOK {
		errCode, _ := q.Int("error_code")
		errMsg, _ := q.String("error_msg")
		return errors.New(fmt.Sprintf("server error %d %s", errCode, errMsg))
	}
	return nil
}
func (m *MarathonService) CreateGroup(payload []byte, marathonEndpoint string) (deploymentId string, err error) {
	url := strings.Join([]string{"http://", marathonEndpoint, "/v2/groups"}, "")
	logrus.Debugf("start to post group json %b to marathon %v", string(payload), marathonEndpoint)
	resp, err := httpclient.Http_post(url, string(payload),
		httpclient.Header{"Content-Type", "application/json"})
	if err != nil {
		logrus.Errorf("post group to marathon failed, error is %v", err)
		return
	}
	defer resp.Body.Close()

	// if response status is greater than 400, means marathon returns error
	// else parse body, findout deploymentId, and return
	data, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode >= 400 {
		logrus.Errorf("marathon returned error code is %v", resp.StatusCode)
		logrus.Errorf("detail is %v", string(data))
		err = errors.New(string(data))
		return
	}

	// Parse data: marathon json data
	jsondata := map[string]interface{}{}
	result := json.NewDecoder(strings.NewReader(string(data)))
	result.Decode(&jsondata)
	jq := jsonq.NewQuery(jsondata)
	deploymentId, err = jq.String("deploymentId")
	return
}
Beispiel #16
0
func (c *CrittercismAPIClient) Request(method, path string, params *CrittercismAPIParams) (jq *jsonq.JsonQuery, outErr error) {
	c.RawRequest(
		method,
		path,
		params,
		func(resp *http.Response, err error) {
			if resp != nil && resp.Body != nil {
				defer resp.Body.Close()
			}

			if err != nil {
				outErr = err
				return
			}

			// Parse Body
			if body, outErr := ioutil.ReadAll(resp.Body); outErr == nil {
				data := map[string]interface{}{}
				dec := json.NewDecoder(strings.NewReader(string(body)))
				dec.Decode(&data)
				jq = jsonq.NewQuery(data)
			}
		},
	)

	return jq, outErr
}
// NewSong creates a track and adds to the queue
func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offset int, playlist Playlist) (Song, error) {
	title, _ := trackData.String("title")
	id, _ := trackData.Int("id")
	durationMS, _ := trackData.Int("duration")
	url, _ := trackData.String("permalink_url")
	thumbnail, err := trackData.String("artwork_url")
	if err != nil {
		// Song has no artwork, using profile avatar instead
		userObj, _ := trackData.Object("user")
		thumbnail, _ = jsonq.NewQuery(userObj).String("avatar_url")
	}

	song := &AudioTrack{
		id:        strconv.Itoa(id),
		title:     title,
		url:       url,
		thumbnail: thumbnail,
		submitter: user,
		duration:  durationMS / 1000,
		offset:    offset,
		format:    "mp3",
		playlist:  playlist,
		skippers:  make([]string, 0),
		dontSkip:  false,
		service:   sc,
	}
	return song, nil
}
Beispiel #18
0
func (self *Baidu) NewReader(length int, hash string) (io.Reader, hashbin.Callback, error) {
	path := neturl.QueryEscape(fmt.Sprintf("/apps/%s/%s/%d-%s", self.dir, hash[:2], length, hash))
	url := fmt.Sprintf("https://d.pcs.baidu.com/rest/2.0/pcs/file?method=download&access_token=%s&path=%s", self.token.AccessToken, path)
	resp, err := self.client.Get(url)
	if err != nil {
		return nil, nil, errors.New(fmt.Sprintf("get error: %s", url))
	}
	if resp.StatusCode != http.StatusOK {
		buf := new(bytes.Buffer)
		_, err = io.Copy(buf, resp.Body)
		if err != nil {
			return nil, nil, errors.New("response body read error")
		}
		respBody := make(map[string]interface{})
		err = json.NewDecoder(buf).Decode(&respBody)
		if err != nil {
			return nil, nil, errors.New("return json decode error")
		}
		q := jsonq.NewQuery(respBody)
		errCode, _ := q.Int("error_code")
		errMsg, _ := q.String("error_msg")
		return nil, nil, errors.New(fmt.Sprintf("fetch error %d %s", errCode, errMsg))
	}
	return resp.Body, func(err error) error {
		defer resp.Body.Close()
		if err != nil {
			return err
		}
		return nil
	}, nil
}
func createLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
	var u Uberdata
	URL := "http://maps.google.com/maps/api/geocode/json?address="

	json.NewDecoder(req.Body).Decode(&u)

	u.Id = bson.NewObjectId()

	URL = URL + u.Address + " " + u.City + " " + u.State + " " + u.Zip + "&sensor=false"
	URL = strings.Replace(URL, " ", "+", -1)
	fmt.Println("url is: " + URL)

	response, err := http.Get(URL)
	if err != nil {
		return
	}
	defer response.Body.Close()

	resp := make(map[string]interface{})
	body, _ := ioutil.ReadAll(response.Body)
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return
	}

	jq := jsonq.NewQuery(resp)
	status, err := jq.String("status")
	fmt.Println(status)
	if err != nil {
		return
	}
	if status != "OK" {
		err = errors.New(status)
		return
	}

	lat, err := jq.Float("results", "0", "geometry", "location", "lat")
	if err != nil {
		fmt.Println(err)
		return
	}
	lng, err := jq.Float("results", "0", "geometry", "location", "lng")
	if err != nil {
		fmt.Println(err)
		return
	}

	u.Coordinate.Lat = lat
	u.Coordinate.Lng = lng

	newSession().DB("tripplan").C("location").Insert(u)

	reply, _ := json.Marshal(u)

	rw.Header().Set("Content-Type", "application/json")
	rw.WriteHeader(201)
	fmt.Fprintf(rw, "%s", reply)

}
func fromJson(js string) *jsonq.JsonQuery {
	// usage: var, err := fromJson(json).String("value", "nestedvalue", "somearray, "0")
	data := map[string]interface{}{}
	dec := json.NewDecoder(strings.NewReader(js))
	dec.Decode(&data)
	jq := jsonq.NewQuery(data)
	return jq
}
Beispiel #21
0
func extractUuid(contents map[string]interface{}, uuidFields []string) string {
	jq := jsonq.NewQuery(contents)
	for _, uuidField := range uuidFields {
		uuid, err := jq.String(strings.Split(uuidField, ".")...)
		if err == nil && uuid != "" {
			return uuid
		}
	}
	return ""
}
Beispiel #22
0
func GetWorldLevelupInfo(worldName string) map[int]DefenceOneLevelUpInfo {
	defenceStr := readJsonFileAsString(worldName)

	data := map[string]interface{}{}
	dec := json.NewDecoder(strings.NewReader(defenceStr))
	dec.Decode(&data)
	jq := jsonq.NewQuery(data)

	levelUpMap := make(map[int]DefenceOneLevelUpInfo)

	for level := 2; level <= 30; level++ {
		var oneDefenceInfo DefenceOneLevelUpInfo
		oneDefenceInfo.PP = make(map[string]PositionNumInfo, 0)
		oneDefenceInfo.PI = make(map[string]PlantsInfo, 0)

		objectInfo, _ := jq.Object("l" + strconv.Itoa(level))
		v := reflect.ValueOf(objectInfo)
		i := v.Interface()
		v1 := i.(map[string]interface{})

		ppInfoTypeArray := reflect.ValueOf(v1["pp"])
		piInfoTypeArray := reflect.ValueOf(v1["pi"])
		if !ppInfoTypeArray.IsValid() && !piInfoTypeArray.IsValid() {
			continue
		}

		if ppInfoTypeArray.IsValid() {
			ppInfoArray := ppInfoTypeArray.Interface().([]interface{})
			for _, ppInfo := range ppInfoArray {
				var positionNumInfo PositionNumInfo
				positionNumInfo.T = reflect.ValueOf(reflect.ValueOf(ppInfo).Interface().(map[string]interface{})["T"]).String()
				positionNumInfo.N = reflect.ValueOf(reflect.ValueOf(ppInfo).Interface().(map[string]interface{})["N"]).String()
				oneDefenceInfo.PP[positionNumInfo.T] = positionNumInfo
			}
		}

		if piInfoTypeArray.IsValid() {
			piInfoArray := piInfoTypeArray.Interface().([]interface{})
			for _, piInfo := range piInfoArray {
				var plantsInfo PlantsInfo
				plantsInfo.T = reflect.ValueOf(reflect.ValueOf(piInfo).Interface().(map[string]interface{})["T"]).String()
				plantsInfo.L = reflect.ValueOf(reflect.ValueOf(piInfo).Interface().(map[string]interface{})["L"]).String()
				plantsInfo.A = reflect.ValueOf(reflect.ValueOf(piInfo).Interface().(map[string]interface{})["A"]).String()
				plantsInfo.Y = reflect.ValueOf(reflect.ValueOf(piInfo).Interface().(map[string]interface{})["Y"]).String()
				oneDefenceInfo.PI[plantsInfo.T] = plantsInfo
			}
		}
		levelUpMap[level] = oneDefenceInfo
	}
	//printObject("levelUpMap info  is ", levelUpMap);

	return levelUpMap
}
// NewRequest creates the requested song/playlist and adds to the queue
func (sc SoundCloud) NewRequest(user *gumble.User, url string) ([]Song, error) {
	var apiResponse *jsonq.JsonQuery
	var songArray []Song
	var err error
	timesplit := strings.Split(url, "#t=")
	url = fmt.Sprintf("http://api.soundcloud.com/resolve?url=%s&client_id=%s", timesplit[0], dj.conf.ServiceKeys.SoundCloud)
	if apiResponse, err = PerformGetRequest(url); err != nil {
		return nil, errors.New(fmt.Sprintf(INVALID_API_KEY, sc.ServiceName()))
	}

	tracks, err := apiResponse.ArrayOfObjects("tracks")
	if err == nil {
		// PLAYLIST
		// Create playlist
		title, _ := apiResponse.String("title")
		permalink, _ := apiResponse.String("permalink_url")
		playlist := &AudioPlaylist{
			id:    permalink,
			title: title,
		}

		if dj.conf.General.MaxSongPerPlaylist > 0 && len(tracks) > dj.conf.General.MaxSongPerPlaylist {
			tracks = tracks[:dj.conf.General.MaxSongPerPlaylist]
		}
		// Add all tracks
		for _, t := range tracks {
			if song, err := sc.NewSong(user, jsonq.NewQuery(t), 0, playlist); err == nil {
				songArray = append(songArray, song)
			}
		}
		return songArray, nil
	} else {
		// SONG
		// Calculate offset
		offset := 0
		if len(timesplit) == 2 {
			timesplit = strings.Split(timesplit[1], ":")
			multiplier := 1
			for i := len(timesplit) - 1; i >= 0; i-- {
				time, _ := strconv.Atoi(timesplit[i])
				offset += time * multiplier
				multiplier *= 60
			}
		}

		// Add the track
		if song, err := sc.NewSong(user, apiResponse, offset, nil); err == nil {
			return append(songArray, song), err
		}
		return nil, err
	}
}
Beispiel #24
0
func NewFromConfig(content string) (*Application, error) {
	data := map[string]interface{}{}
	dec := json.NewDecoder(strings.NewReader(content))
	err := dec.Decode(&data)

	if err != nil {
		return nil, fmt.Errorf("Your config file %s cannot be parsed: %s", content, err)
	}

	jq := jsonq.NewQuery(data)

	return NewFromJsonQuery(jq)
}
Beispiel #25
0
func GetCollections(c *Census) ([]*Collection, error) {
	var out []*Collection
	tmp := map[string]interface{}{}

	url := BaseURL + "get/" + c.namespace
	fmt.Printf("Getting url: %v\n", url)
	if err := decodeURL(url, &tmp); err != nil {
		return nil, err
	}
	jq := jsonq.NewQuery(tmp)
	n, err := jq.ArrayOfObjects("datatype_list")
	if err != nil {
		return nil, err
	}

	//fmt.Printf("%v\n", data)
	for _, v := range n {
		data := jsonq.NewQuery(v)
		out = append(out, parse_collection(data))
	}
	return out, nil
}
func (nr *NewrelicInsights) reformatDataBeforeToJson(data interface{}) interface{} {
	hostname, err := os.Hostname()
	if err != nil {
		return data
	}

	dataAsMapStringInterface, isMapStringInterface := data.(map[string]interface{})
	dataAsSliceInterface, isSliceInterface := data.([]interface{})

	if isSliceInterface {
		newData := make([]interface{}, 0)

		for _, sliceData := range dataAsSliceInterface {
			sliceDataAsMapStringInterface, isSliceDataAMapStringInterface := sliceData.(map[string]interface{})
			if isSliceDataAMapStringInterface {
				sliceDataAsMapStringInterface["Hostname"] = hostname
				sliceDataAsMapStringInterface["eventType"] = nr.EventType

				newData = append(newData, sliceDataAsMapStringInterface)
			}
		}
		return newData
	}

	if isMapStringInterface {
		newData := make(map[string]interface{})

		hasOnlyOneReadersData := len(dataAsMapStringInterface) == 1

		jq := jsonq.NewQuery(dataAsMapStringInterface)

		for readerPath, _ := range dataAsMapStringInterface {
			dataPayload, err := jq.Object(readerPath, "Data")
			if err == nil {
				if hasOnlyOneReadersData {
					newData = dataPayload
				} else {
					newData[readerPath] = dataPayload
				}
			}
		}

		newData["eventType"] = nr.EventType
		newData["Hostname"] = hostname

		return newData
	}

	return data
}
func getDigitalOceanInstances(config map[string]string) (instances Instances) {
	instances = make(Instances)

	if _, ok := config["client_id"]; !ok {
		log.Fatal("Missing client_id for ", config["name"], " DigitalOcean cloud")
	}

	if _, ok := config["api_key"]; !ok {
		log.Fatal("Missing api_key for ", config["name"], " DigitalOcean cloud")
	}

	resp, err := http.Get("https://api.digitalocean.com/droplets/?client_id=" + config["client_id"] + "&api_key=" + config["api_key"])

	if err != nil {
		log.Println("DigitalOcean API error:", err)
		return
	}

	defer resp.Body.Close()

	data := map[string]interface{}{}
	dec := json.NewDecoder(resp.Body)
	dec.Decode(&data)
	jq := jsonq.NewQuery(data)

	status, err := jq.String("status")

	if status == "ERROR" {
		err_msg, _ := jq.String("error_message")

		log.Println("DigitalOcean API error: ", err_msg)
		return
	}

	droplets, err := jq.ArrayOfObjects("droplets")

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

	for _, droplet := range droplets {
		instances[droplet["ip_address"].(string)] = []Tag{
			Tag{"Name", droplet["name"].(string)},
		}
	}

	return
}
Beispiel #28
0
func (qp *QueryParser) dataValue(datapath, jsonSelector string) (interface{}, error) {
	dataJsonBytes := qp.data[datapath]
	var dataJson map[string]interface{}

	err := json.Unmarshal(dataJsonBytes, &dataJson)
	if err != nil {
		return nil, err
	}

	jq := jsonq.NewQuery(dataJson)

	jsonSelectorChunks := strings.Split(jsonSelector, ".")
	jsonSelectorChunks = append([]string{"Data"}, jsonSelectorChunks...) // Always query from "Data" sub-structure.

	return jq.Interface(jsonSelectorChunks...)
}
Beispiel #29
0
// Returns a slice containing the names of all collections in the current database.
//
// Based on
// http://docs.mongodb.org/manual/reference/method/db.getCollectionNames/
func GetCollectionNames(db *mgo.Database) ([]string, error) {
	raw := make(map[string]interface{})
	err := db.Run(bson.D{{"listCollections", 1}}, &raw)
	if err != nil {
		return nil, err
	}
	jq := jsonq.NewQuery(raw)
	items, err := jq.ArrayOfObjects("cursor", "firstBatch")
	if err != nil {
		return nil, err
	}
	output := make([]string, len(items))
	for k, v := range items {
		output[k], _ = v["name"].(string)
	}
	return output, nil
}
Beispiel #30
0
func (m JsonRequestMatcher) Match(req *httper.Request, matcher *MatchOption) bool {
	data := map[string]interface{}{}
	err := json.Unmarshal([]byte(req.Payload), &data)
	jq := jsonq.NewQuery(data)

	path := strings.Split(matcher.Match.Path, "/")
	v, err := jq.String(path...)

	if err != nil {
		return false
	}

	if v == matcher.Match.Value {
		return true
	}

	return false
}