Exemplo n.º 1
0
func getGoogleResults(latitude float64, longitude float64) (*json.Json, error) {
	// Get reults from google, with a request such as:
	//https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY
	latlng := fmt.Sprintf("%f,%f", latitude, longitude)
	//apiKey := "SOME_API_KEY"

	// We can handle all the different HTTP codes later. (if time)
	uri := fmt.Sprintf("%v?latlng=%v", GOOGLE_GEOCODE_URI, latlng)
	resp, err := http.Get(uri)
	defer resp.Body.Close()

	if err != nil {
		log.Println("Failed to get a response from Google.", err)
		return nil, err
	}

	payload, err := json.NewFromReader(resp.Body)

	if err != nil {
		log.Println("Failed to parse Google response to JSON", err)
		return nil, err
	}

	return payload, nil
}
Exemplo n.º 2
0
func (b *Adaptor) GetReputationProviderUrl() (string, error) {

	url := fmt.Sprintf("%s/reputation_provider_api/v2/urls", b.bossURL)
	authToken := fmt.Sprintf("token=%s", b.authToken)
	client := &http.Client{}
	req, _ := http.NewRequest("GET", url, nil)
	req.Header.Set("Authorization", authToken)
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)

	curl := fmt.Sprintf("curl -v -X GET %s --header 'Authorization: <auth token>' --header 'Content-Type: application/json'", url)

	if err != nil {
		return "", fmt.Errorf("http client error (%s) - %s", curl, err)
	}
	defer resp.Body.Close()

	urls, err := simplejson.NewFromReader(resp.Body)

	if err != nil {
		return "", fmt.Errorf("json parse error (%s) - %s", curl, err)
	}

	reportUrl := urls.Get("create_report").MustString("create_report")
	return reportUrl, nil
}
Exemplo n.º 3
0
func getSubnet(r *http.Request) (*SapiProvisionedSubnets, error) {
	var port *sjson.Json
	var sapiSubnet = &SapiProvisionedSubnets{}

	post, err := sjson.NewFromReader(r.Body)
	if err != nil {
		return nil, err
	}

	port, ok := post.CheckGet("subnet")
	if !ok {
		return nil, ErrorNoPort
	}

	b, err := port.Encode()
	if err != nil {
		return nil, err
	}
	if err = json.Unmarshal(b, sapiSubnet); err != nil {
		return nil, err
	}
	if err != nil {
		return nil, err
	}

	return sapiSubnet, nil
}
Exemplo n.º 4
0
/*
	doc := JobConfig.Copy()
	// parse job config.xml
	updateJobConfigXml(doc, cfg)
	job_data, err := doc.WriteToString()
	if err != nil {
		log.Errorf("write to string failed")
		fmt.Fprintf(w, "write to string failed")
		return
	}

	job, err := JenkinsClient.CreateJob(job_data, jobid)
	if err != nil {
		log.Errorf("create job: %s failed", jobid)
		fmt.Fprintf(w, err.Error())
		return
	}

	//creating job is ok
	log.Debugf("job base:%s, job raw:", job.Base, job.Raw)
	data := map[string]string{"name": job.Raw.Name} // "description": job.Raw.Description,
	// "displayName": job.Raw.DisplayName,
	// "url":         job.Raw.URL

	jsonData, err := json.Marshal(data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(jsonData)
}
*/
func HandlerCreateJob(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		tCreateJob, err := template.ParseFiles("views/createJob.html")
		if err != nil {
			fmt.Println(w, err.Error())
			return
		}
		tCreateJob.Execute(w, nil)
	} else {
		js, err := simplejs.NewFromReader(r.Body)
		if err != nil {
			log.Errorf(err.Error())
			log.Errorf("read request body failed")
			fmt.Fprintf(w, err.Error())
			return
		}
		defer r.Body.Close()
		fmt.Println(js)
		jobid, cfg := parseCreateJobBody(js)
		if cfg == nil {
			log.Errorf("parse request body failed")
			fmt.Fprintf(w, "parse request body failed")
			return
		}

		doc := JobConfig.Copy()
		// parse job config.xml
		updateJobConfigXml(doc, cfg)
		job_data, err := doc.WriteToString()
		if err != nil {
			log.Errorf("write to string failed")
			fmt.Fprintf(w, "write to string failed")
			return
		}
		cookie, _ := r.Cookie("sessionId")
		jc := getJenkinsClient(cookie.Value)
		job, err := jc.CreateJob(job_data, jobid)
		if err != nil {
			log.Errorf("create job: %s failed", jobid)
			fmt.Fprintf(w, err.Error())
			return
		}

		//creating job is ok
		log.Debugf("job base:%s, job raw:", job.Base, job.Raw)
		data := map[string]string{"name": job.Raw.Name} // "description": job.Raw.Description,
		// "displayName": job.Raw.DisplayName,
		// "url":         job.Raw.URL

		jsonData, err := json.Marshal(data)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Write(jsonData)
	}
}
Exemplo n.º 5
0
func (s *S) TestWriteError(c *check.C) {
	s.T.WriteError(errors.New("my error", http.StatusInternalServerError))
	c.Assert(s.T.statusCode, check.Equals, http.StatusInternalServerError)
	c.Assert(s.Writer.Code, check.Equals, http.StatusInternalServerError)

	json, err := simplejson.NewFromReader(s.Writer.Body)
	c.Assert(err, check.IsNil)

	msg := json.Get("errors").GetIndex(0).Get("_all").GetIndex(0).MustString()
	c.Assert(msg, check.Equals, "my error")
}
Exemplo n.º 6
0
func (h *Handler) GoogleSearch(query string) {
	var queryUrl = fmt.Sprintf("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s", urlLib.QueryEscape(query))
	res, err := http.Get(queryUrl)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()
	json, _ := simpleJson.NewFromReader(res.Body)
	result, _ := json.Get("responseData").Get("results").GetIndex(0).Get("url").String()
	unescaped, _ := urlLib.QueryUnescape(result)
	h.conn.Privmsg(h.channel, unescaped)
}
Exemplo n.º 7
0
func (s *S) TestWriteResult(c *check.C) {
	result := map[string]string{
		"test": "ok",
	}
	s.T.WriteResult(&result)

	c.Assert(s.T.statusCode, check.Equals, http.StatusOK)
	c.Assert(s.Writer.Code, check.Equals, http.StatusOK)

	json, err := simplejson.NewFromReader(s.Writer.Body)
	c.Assert(err, check.IsNil)
	msg := json.Get("test").MustString()
	c.Assert(msg, check.Equals, "ok")
}
Exemplo n.º 8
0
func (s *S) TestWriteResultWithStatusCode(c *check.C) {
	result := map[string]string{
		"test": "with-status-code",
	}
	s.T.WriteResultWithStatusCode(http.StatusMethodNotAllowed, &result)

	c.Assert(s.T.statusCode, check.Equals, http.StatusMethodNotAllowed)
	c.Assert(s.Writer.Code, check.Equals, http.StatusMethodNotAllowed)

	json, err := simplejson.NewFromReader(s.Writer.Body)
	c.Assert(err, check.IsNil)

	msg := json.Get("test").MustString()
	c.Assert(msg, check.Equals, "with-status-code")
}
Exemplo n.º 9
0
func (h *Handler) Youtube(videoId string) {
	if "" == GetYoutubeApiKey() {
		return
	}
	var apiUrl = fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=%s&key=%s", videoId, GetYoutubeApiKey())
	res, err := http.Get(apiUrl)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()
	json, _ := simpleJson.NewFromReader(res.Body)
	title, _ := json.Get("items").GetIndex(0).Get("snippet").Get("title").String()
	h.conn.Privmsg(h.channel, title)
}
Exemplo n.º 10
0
func main() {
	f := getFileHandle()
	j, err := json.NewFromReader(f)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	res, err := j.EncodePretty()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	if *colors {
		fmt.Printf("%s\n", colorize(res))
	} else {
		fmt.Printf("%s\n", res)
	}
}
Exemplo n.º 11
0
func handleSync(r *http.Request) (err error) {
	post, err := sjson.NewFromReader(r.Body)
	if err != nil {
		return
	}
	openstack, ok := post.CheckGet("sina_openstack")
	if !ok {
		return ErrorNoSinaOpenstack
	}

	if err := syncNet(openstack); err != nil {
		return err
	}
	if err := syncSubnet(openstack); err != nil {
		return err
	}
	if err := syncPort(openstack); err != nil {
		return err
	}

	return nil
}
Exemplo n.º 12
0
func getOSMResults(latitude float64, longitude float64) (*json.Json, error) {
	// http://nominatim.openstreetmap.org/reverse?format=json&lat=52.5487429714954&lon=-1.81602098644987&zoom=18&addressdetails=1

	// We can handle all the different HTTP codes later. (if time)
	uri := fmt.Sprintf("%v?lat=%f&lon=%f&format=json", OSM_GEOCODE_URI, latitude, longitude)
	resp, err := http.Get(uri)
	defer resp.Body.Close()

	if err != nil {
		log.Println("Failed to get a response from OSM.", err)
		return nil, err
	}

	payload, err := json.NewFromReader(resp.Body)

	if err != nil {
		log.Println("Failed to parse OSM response to JSON", err)
		return nil, err
	}

	return payload, nil
}
Exemplo n.º 13
0
func getNet(r *http.Request) (*SapiProvisionedNets, error) {
	var network *sjson.Json
	var sapiNet = &SapiProvisionedNets{}

	post, err := sjson.NewFromReader(r.Body)
	if err != nil {
		return nil, err
	}
	network, ok := post.CheckGet("network")
	if !ok {
		return nil, ErrorNoNet
	}
	b, err := network.Encode()
	if err != nil {
		return nil, err
	}

	if err = json.Unmarshal(b, sapiNet); err != nil {
		return nil, err
	}

	return sapiNet, nil
}
Exemplo n.º 14
0
func registerTor(rw http.ResponseWriter, r *http.Request) {
	var (
		data struct {
			Type string `json:"switch_type"`
			Mgr  string `json:"mgr"`
			Src  string `json:"tunnel_src"`
		}
		sapiTor  = new(SapiTor)
		sapiTors = make([]*SapiTor, 0)
	)

	decoder := json.NewDecoder(r.Body)
	if err := decoder.Decode(&data); err != nil {
		fmt.Println(err)
		HttpError(rw, "Bad Request", nil, http.StatusBadRequest)
		return
	}
	if data.Type == "" || data.Mgr == "" || data.Src == "" {
		HttpError(rw, "Bad Request", nil, http.StatusBadRequest)
		return
	}
	if err := SelectAllTors(&sapiTors); err != nil {
		HttpError(rw, "Database Error", err, http.StatusInternalServerError)
		return
	}

	sapiTor.TorIp = data.Mgr
	sapiTor.TunnelSrcIp = data.Src
	sapiTor.Type = data.Type
	Log().Info(fmt.Sprintf("registerTor: Tor %s", sapiTor))
	sapiTor.insert()

	//need refresh topology
	tors = append(tors, sapiTor.TorIp)
	InitInmemoryData([]string{sapiTor.TorIp})
	refresh <- true

	//TODO: tunnel sync
	go func() {
		client := NewHttpAgent()
		Log().Info(fmt.Sprintf("registerTor: make tunnel sync request %s", torconf+"/tsync"))
		_, bodystr, _ := client.Post(torconf + "/tsync").ReqData(
			struct {
				Src        string `json:"src"`
				TunnelType string `json:"tunnel_type"`
			}{
				Src:        sapiTor.TunnelSrcIp,
				TunnelType: "vxlan",
			},
		).Issue()
		Log().Info(fmt.Sprintf("registerTor: request got response %s", bodystr))

		respj, _ := sjson.NewFromReader(strings.NewReader(bodystr))
		tunnels, _ := respj.CheckGet("tunnels")
		all, _ := tunnels.Array()
		for _, tunnel := range all {
			if m, ok := tunnel.(map[string]interface{}); ok {
				ip, _ := m["ip_address"].(string)
				if ip != sapiTor.TunnelSrcIp {
					//new tunnel with existing tunnel src ip.
					goTunnelSync(sapiTor.Type, sapiTor.TorIp, sapiTor.TunnelSrcIp, ip)
				}
			}
		}

		for _, tor := range sapiTors {
			//new tunnel form existing tunnel src ip to new tunnel src ip.
			goTunnelSync(tor.Type, tor.TorIp, tor.TunnelSrcIp, sapiTor.TunnelSrcIp)
		}
		Log().Info(fmt.Sprintf("registerTor: tunnel sync done, send signal to channel tunnelSyncDone"))
		tunnelSyncDone <- true
	}()
	rw.Write([]byte("OK"))
}
Exemplo n.º 15
0
func init() {
	var i *Item
	v := pb.NewView("main")

	i = v.NewItem("Pinboard: Search All").SetIcon("Pinboard").SetOrder(4).SetSubtitle("Enter a query")
	i.SetActionRunsInBackground(false)
	i.SetRender(func(c *Context) {
		if c.Input.IsEmpty() {
			return
		}
		c.Self.SetOrder(-1)
		c.Self.SetSubtitle("Query: " + c.Input.String())
	})
	i.SetRun(func(c *Context) Items {
		if c.Input.IsEmpty() {
			return nil
		}

		m := make(map[string]string)
		for item := range search(url.QueryEscape(c.Input.String())) {
			m[item[0]] = item[1]
		}

		var items = &Items{}
		for t, url := range m {
			// TODO: parse posts as a pin
			items.Add(NewItem(t).SetURL(url))
		}
		return *items

		// d, _ := goquery.NewDocument(uri)
		// d.Find("a.bookmark_title").Each(func(i int, s *goquery.Selection) {
		// 	t := strings.TrimSpace(s.Text())
		// 	h, _ := s.Attr("href")
		// 	items.Add(NewItem(t).SetURL(h))
		// })
		// return *items
	})

	i = v.NewItem("Pinboard: Preferences").SetOrder(9998)
	i.SetIcon("DebugTemplate").SetRun(ShowViewFunc("config"))

	v = pb.GetView("main")
	i = v.NewItem("Pinboard: Popular").SetIcon("Pinboard")

	i.SetSubtitle("Hold ⌃(CTRL) to discard the cache.")
	i.SetActionRunsInBackground(false)
	i.SetMatch(func(c *Context) bool {
		return c.Input.String() == ""
	})
	i.SetRun(func(c *Context) Items {
		cache := c.Cache
		var items *Items
		if c.Action.IsControlKey() {
			items = nil
		} else {
			items = cache.GetItems("popular")
		}
		if items == nil {
			items = &Items{}

			url := "http://feeds.pinboard.in/json/popular/"
			res, err := http.Get(url)
			if err != nil {
				c.Logger.Println(err)
			}
			defer res.Body.Close()
			j, err := json.NewFromReader(res.Body)
			if err != nil {
				c.Logger.Println(err)
			}
			for _, post := range j.MustArray() {
				p := post.(map[string]interface{})
				title := p["u"].(string)
				if d, ok := p["d"].(string); ok && d != "" {
					title = d
				} else if n, ok := p["n"].(string); ok && n != "" {
					title = n
				}
				title = strings.Replace(title, "\n", " ", -1)
				url := p["u"].(string)
				items.Add(NewItem(title).SetURL(url))
			}
			cache.SetItems("popular", items, pb.Config.GetTimeDuration("cachelife"))
		}
		return *items
	})

	i = v.NewItem("Pinboard: Recent").SetIcon("Pinboard")

	i.SetSubtitle("Hold ⌃(CTRL) to discard the cache.")
	i.SetActionRunsInBackground(false)
	i.SetMatch(func(c *Context) bool {
		return c.Input.String() == ""
	})
	i.SetRun(func(c *Context) Items {
		cache := c.Cache
		var items *Items
		if c.Action.IsControlKey() {
			items = nil
		} else {
			items = cache.GetItems("recent")
		}
		if items == nil {
			items = &Items{}

			url := "http://feeds.pinboard.in/json/recent/"
			res, err := http.Get(url)
			if err != nil {
				c.Logger.Println(err)
			}
			defer res.Body.Close()
			j, err := json.NewFromReader(res.Body)
			if err != nil {
				c.Logger.Println(err)
			}
			for _, post := range j.MustArray() {
				p := post.(map[string]interface{})
				title := p["u"].(string)
				if d, ok := p["d"].(string); ok && d != "" {
					title = d
				} else if n, ok := p["n"].(string); ok && n != "" {
					title = n
				}
				title = strings.Replace(title, "\n", " ", -1)
				url := p["u"].(string)
				items.Add(NewItem(title).SetURL(url))
			}
			cache.SetItems("recent", items, pb.Config.GetTimeDuration("cachelife"))
		}
		return *items
	})

	v = pb.GetView("main")
	i = v.NewItem("Pinboard: Browse User").SetIcon("Pinboard")

	i.SetSubtitle("Enter a username")
	i.SetActionRunsInBackground(false)
	i.SetRender(func(c *Context) {
		if c.Input.String() != "" {
			c.Self.SetSubtitle("Query: " + c.Input.String())
		}
	})
	i.SetRun(func(c *Context) Items {
		var out Items
		c.Logger.Println(c.Input.String())
		if c.Input.String() == "" {
			c.Action.ShowView("main")
			return out
		}
		url := "http://feeds.pinboard.in/json/u:" + c.Input.String()
		res, err := http.Get(url)
		if err != nil {
			c.Logger.Println(err)
			c.Action.ShowView("main")
			return out
		}
		defer res.Body.Close()
		j, err := json.NewFromReader(res.Body)
		if err != nil {
			c.Logger.Println(err)
			c.Action.ShowView("main")
			return out
		}

		for _, post := range j.MustArray() {
			p := post.(map[string]interface{})
			title := p["u"].(string)
			if d, ok := p["d"].(string); ok && d != "" {
				title = d
			} else if n, ok := p["n"].(string); ok && n != "" {
				title = n
			}
			title = strings.Replace(title, "\n", " ", -1)
			url := p["u"].(string)
			(&out).Add(NewItem(title).SetURL(url))
		}
		return out
	})
}