Exemple #1
0
func main() {
	tracelog.Start(tracelog.LevelTrace)

	// Init mongo
	tracelog.Started("main", "Initializing Mongo")
	err := mongo.Startup(helper.MainGoRoutine)
	if err != nil {
		tracelog.CompletedError(err, helper.MainGoRoutine, "initApp")
		os.Exit(1)
	}

	// Load message strings
	localize.Init("en-US")

	SessionConfig, err := session.GetSessionConfig("session")

	tracelog.Trace("main", "SessionConfig", "Session : On[%v]", SessionConfig.On)
	tracelog.Trace("main", "SessionConfig", "Session : On[%v]", SessionConfig.Provider)
	tracelog.Trace("main", "SessionConfig", "Session : On[%v]", SessionConfig.SavePath)

	beego.SessionOn = SessionConfig.On
	beego.SessionProvider = SessionConfig.Provider
	beego.SessionSavePath = SessionConfig.SavePath

	beego.Run()

	tracelog.Completed(helper.MainGoRoutine, "Website Shutdown")
	tracelog.Stop()
}
func DealersAroundZipCode(zipCode string, radius int32, make string, newCars bool) (EdmundsDealerResponse, error) {
	queryStr, err := DealerServiceQueryString(zipCode, radius, make, newCars)
	if err != nil {
		return EdmundsDealerResponse{}, err
	}

	tracelog.Trace("Query String", "DealersAroundZipCode", queryStr)

	resp, err := http.Get(queryStr)
	if err != nil {
		return EdmundsDealerResponse{}, err
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return EdmundsDealerResponse{}, err
	}

	resp.Body.Close()

	tracelog.Trace("Response Returned", "DealersAroundZipCode", "%s", data)

	response := &EdmundsDealerResponse{}
	err = json.Unmarshal(data, response)
	if err != nil {
		return EdmundsDealerResponse{}, err
	}

	return *response, err
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	lat, latErr := strconv.ParseFloat(vars["lat"], 32)
	if latErr != nil {
		ReturnErrorToClient(w, latErr, "Invalid latitude value. Expecting a floating point number")
		return
	}

	lng, lngErr := strconv.ParseFloat(vars["lng"], 32)
	if lngErr != nil {
		ReturnErrorToClient(w, lngErr, "Invalid longitude value. Expecting a floating point number")
		return
	}

	tracelog.Trace("Lat Value", "main", "Lat is %f", lat)
	tracelog.Trace("Lng Value", "main", "Lng is %f", lng)

	postalCode, postaCodeErr := ReverseGeocodeToPostalCode(lat, lng)
	if postaCodeErr != nil {
		ReturnErrorToClient(w, postaCodeErr, "Error determining zip code from given coordinates")
		return
	}

	tracelog.Trace("Postal Code Value", "main", "Postal Code is %s", postalCode)
	var response = GeocodeResponse{postalCode}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(response); err != nil {
		tracelog.Error(err, "An error occurred while encoding json response", "NearbyHandler")
		panic(err)
	}
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	brand := vars["brand"]
	postalCode := vars["postalCode"]

	tracelog.Trace("Brand Value", "main", "Brand is %s", brand)
	tracelog.Trace("Postal Code", "main", "PostalCode is %s", postalCode)

	// now call the Edmunds API
	dealers, dealerErr := DealersAroundZipCode(postalCode, 100, brand, true)
	if dealerErr != nil {
		ReturnErrorToClient(w, dealerErr, "Error calling dealer service with zip code "+postalCode)
		tracelog.Error(dealerErr, "DealersAroundZipCode failed", "HomeHandler")
		return
	}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(dealers); err != nil {
		tracelog.Error(err, "JSON encoding failed", "HomeHandler")
		panic(err)
	}
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	lat := vars["lat"]
	lng := vars["lng"]
	distance := vars["distance"]

	tracelog.Trace("Latitude", "main", "Lat is %s", lat)
	tracelog.Trace("Longitude", "main", "Lng is %s", lng)
	tracelog.Trace("Distance", "main", "Distance is %s", distance)

	// call the GasFeed API

	stations, stationErr := NearbyGasStations(lat, lng, distance)
	if stationErr != nil {
		ReturnErrorToClient(w, stationErr, "Error calling gas station pricing service with lat "+lat+" lng "+lng+" and distance "+distance)
		tracelog.Error(stationErr, "NearbyGasStations failed", "HomeHandler")
		return
	}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(stations); err != nil {
		tracelog.Error(err, "JSON encoding failed", "HomeHandler")
		panic(err)
	}
}
func NearbyGasStations(lat string, lng string, distance string) (GasPriceResponse, error) {
	queryStr, err := NearbyGasStationQueryString(lat, lng, distance)
	if err != nil {
		return GasPriceResponse{}, err
	}

	tracelog.Trace("Query String", "NearbyGasStations", queryStr)

	resp, err := http.Get(queryStr)
	if err != nil {
		return GasPriceResponse{}, err
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return GasPriceResponse{}, err
	}

	resp.Body.Close()

	response := &GasPriceResponse{}
	err = json.Unmarshal(data, response)
	if err != nil {
		return GasPriceResponse{}, err
	}

	return *response, err
}
// TestInvalidStation is a sample to run an endpoint test that returns
// an empty result set
func TestInvalidStation(t *testing.T) {
	r, _ := http.NewRequest("GET", "/buoy/station/000000", nil)
	w := httptest.NewRecorder()
	beego.BeeApp.Handlers.ServeHTTP(w, r)

	log.Trace("testing", "TestStation", "Code[%d]\n%s", w.Code, w.Body.String())

	var response struct {
		StationID string `json:"station_id"`
		Name      string `json:"name"`
		LocDesc   string `json:"location_desc"`
		Condition struct {
			Type        string    `json:"type"`
			Coordinates []float64 `json:"coordinates"`
		} `json:"condition"`
		Location struct {
			WindSpeed     float64 `json:"wind_speed_milehour"`
			WindDirection int     `json:"wind_direction_degnorth"`
			WindGust      float64 `json:"gust_wind_speed_milehour"`
		} `json:"location"`
	}
	json.Unmarshal(w.Body.Bytes(), &response)

	Convey("Subject: Test Station Endpoint\n", t, func() {
		Convey("Status Code Should Be 200", func() {
			So(w.Code, ShouldEqual, 200)
		})
		Convey("The Result Should Not Be Empty", func() {
			So(w.Body.Len(), ShouldBeGreaterThan, 0)
		})
		Convey("The Result Should Be Empty For Station 00000", func() {
			So(response.StationID, ShouldBeBlank)
		})
	})
}
Exemple #8
0
// FindStation retrieves the specified station
func FindStation(service *services.Service, stationId string) (buoyStation *buoyModels.BuoyStation, err error) {
	defer helper.CatchPanic(&err, service.UserId, "FindStation")

	tracelog.Started(service.UserId, "FindStation")

	queryMap := bson.M{"station_id": stationId}

	buoyStation = &buoyModels.BuoyStation{}
	err = service.DBAction(Config.Database, "buoy_stations",
		func(collection *mgo.Collection) error {
			tracelog.Trace(service.UserId, "FindStation", "Query : %s", mongo.ToString(queryMap))
			return collection.Find(queryMap).One(buoyStation)
		})

	if err != nil {
		if strings.Contains(err.Error(), "not found") == false {
			tracelog.CompletedError(err, service.UserId, "FindStation")
			return buoyStation, err
		}

		err = nil
	}

	tracelog.Completed(service.UserId, "FindStation")
	return buoyStation, err
}
func FindUserByName(service *services.Service, userName string) (*userModel.UserInfo, error) {
	log.Startedf(service.UserID, "FindUserByName", "userName[%s]", userName)
	var userInfo userModel.UserInfo
	f := func(collection *mgo.Collection) error {
		queryMap := bson.M{
			"$or": []bson.M{
				bson.M{"user_name": userName},
				bson.M{"user_email": userName},
				bson.M{"user_mobile": userName},
			},
		}
		log.Trace(service.UserID, "FindUserByName", "MGO : db.user_infos.find(%s).limit(1)", mongo.ToString(queryMap))
		return collection.Find(queryMap).One(&userInfo)
	}

	if err := service.DBAction(Config.Database, "user_infos", f); err != nil {
		if err != mgo.ErrNotFound {
			log.CompletedError(err, service.UserID, "FindUserByName")
			return nil, err
		}
	}

	log.Completedf(service.UserID, "FindUserByName", "userInfo%+v", &userInfo)
	return &userInfo, nil
}
func (controller *UserController) UserLogin() {
	var params struct {
		UserName string `form:"user_name" valid:"Required; MinSize(4)" error:"invalid_user_name"`
		UserPwd  string `form:"user_pwd" valid:"Required; MinSize(6)" error:"invalid_user_pwd"`
	}

	if controller.ParseAndValidate(&params) == false {
		return
	}

	userInfo, err := userService.UserLogin(&controller.Service, params.UserName, params.UserPwd)
	if err != nil {
		log.CompletedErrorf(err, controller.UserID, "UserController.UserLogin", "UserName[%s]", params.UserName)
		controller.ServeError(err)
		return
	}

	// set session
	if len(userInfo.ID) > 0 {
		log.Trace("UserController", "UserLogin", "userID[%s]", userInfo.ID.Hex())
		controller.SetSession("UserID", userInfo.ID.Hex())
	}
	controller.Data["json"] = userInfo
	controller.ServeJson()
}
func ReverseGeocodeToPostalCode(lat float64, lng float64) (string, error) {
	queryStr, err := googleReverseGeocodeQueryStr(lat, lng)
	if err != nil {
		return "", err
	}

	resp, err := http.Get(queryStr)
	if err != nil {
		return "", err
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	resp.Body.Close()

	response := &GoogleReverseGeocodeResponse{}
	err = json.Unmarshal(data, response)
	if err != nil {
		return "", err
	}

	tracelog.Trace("response", "from google", string(data))

	if len(response.Results) == 0 {
		tracelog.Trace("Response from Google", "length of results", "is zero")
		return "", googleZeroResultsError
	}

	for _, result := range response.Results {
		for _, addressComp := range result.AddressComponents {
			for _, aType := range addressComp.Types {
				tracelog.Trace("loop", "aType", aType)
				if aType == "postal_code" {
					tracelog.Trace("loop", "shortname", addressComp.ShortName)
					return addressComp.ShortName, nil
				}
			}
		}
	}

	tracelog.Trace("Response from Google", "address components", "didnt' find postal code")

	return "", googleZeroResultsError
}
Exemple #12
0
// Startup brings the manager to a running state.
func Startup(sessionID string) error {
	// If the system has already been started ignore the call.
	if singleton.sessions != nil {
		return nil
	}

	log.Started(sessionID, "Startup")

	// Pull in the configuration.
	var config mongoConfiguration
	if err := envconfig.Process("mgo", &config); err != nil {
		log.CompletedError(err, sessionID, "Startup")
		return err
	}

	// Create the Mongo Manager.
	singleton = mongoManager{
		sessions: make(map[string]mongoSession),
	}

	// Log the mongodb connection straps.
	log.Trace(sessionID, "Startup", "MongoDB : Hosts[%s]", config.Hosts)
	log.Trace(sessionID, "Startup", "MongoDB : Database[%s]", config.Database)
	log.Trace(sessionID, "Startup", "MongoDB : Username[%s]", config.UserName)

	hosts := strings.Split(config.Hosts, ",")

	// Create the strong session.
	if err := CreateSession(sessionID, "strong", MasterSession, hosts, config.Database, config.UserName, config.Password); err != nil {
		log.CompletedError(err, sessionID, "Startup")
		return err
	}

	// Create the monotonic session.
	if err := CreateSession(sessionID, "monotonic", MonotonicSession, hosts, config.Database, config.UserName, config.Password); err != nil {
		log.CompletedError(err, sessionID, "Startup")
		return err
	}

	log.Completed(sessionID, "Startup")
	return nil
}
func SaveMsg(service *services.Service, message msgModel.Message) (*msgModel.Message, error) {
	log.Startedf(service.UserID, "SaveMsg", "UserID[%s]", message.CreatedBy)
	f := func(collection *mgo.Collection) error {

		if len(message.ID) > 0 {
			log.Trace(service.UserID, "SaveMsg", "MGO : db.message.update(%s)", mongo.ToString(message))
			return collection.Update(bson.M{"_id": message.ID}, &message)
		} else {
			log.Trace(service.UserID, "SaveMsg", "MGO : db.message.insert(%s)", mongo.ToString(message))
			return collection.Insert(&message)
		}

	}
	if err := service.DBAction(Config.Database, "message", f); err != nil {
		if err != mgo.ErrNotFound {
			log.CompletedError(err, service.UserID, "SaveMsg")
			return nil, err
		}
	}
	log.Completedf(service.UserID, "SaveMsg", "message%+v", &message)
	return &message, nil
}
func SaveSettings(service *services.Service, settings settingsModel.WinSettings) (*settingsModel.WinSettings, error) {
	log.Startedf(service.UserID, "SaveSettings", "UserID[%s]", settings.UserID)
	f := func(collection *mgo.Collection) error {

		if len(settings.ID) > 0 {
			log.Trace(service.UserID, "SaveSettings", "MGO : db.win_settings.update(%s)", mongo.ToString(settings))
			return collection.Update(bson.M{"_id": settings.ID}, &settings)
		} else {
			log.Trace(service.UserID, "SaveSettings", "MGO : db.win_settings.insert(%s)", mongo.ToString(settings))
			return collection.Insert(&settings)
		}

	}
	if err := service.DBAction(Config.Database, "win_settings", f); err != nil {
		if err != mgo.ErrNotFound {
			log.CompletedError(err, service.UserID, "SaveSettings")
			return nil, err
		}
	}
	log.Completedf(service.UserID, "SaveSettings", "settings%+v", &settings)
	return &settings, nil
}
func SaveInfo(service *services.Service, information infoModel.Information) (*infoModel.Information, error) {
	log.Startedf(service.UserID, "SaveInfo", "UserID[%s]", information.CreatedBy)
	f := func(collection *mgo.Collection) error {

		if len(information.ID) > 0 {
			log.Trace(service.UserID, "SaveInfo", "MGO : db.information.update(%s)", mongo.ToString(information))
			return collection.Update(bson.M{"_id": information.ID}, &information)
		} else {
			log.Trace(service.UserID, "SaveInfo", "MGO : db.information.insert(%s)", mongo.ToString(information))
			return collection.Insert(&information)
		}

	}
	if err := service.DBAction(Config.Database, "information", f); err != nil {
		if err != mgo.ErrNotFound {
			log.CompletedError(err, service.UserID, "SaveInfo")
			return nil, err
		}
	}
	log.Completedf(service.UserID, "SaveInfo", "information%+v", &information)
	return &information, nil
}
// Handles a transaction
func HandleTransaction(b []byte) {
	tracelog.Trace(TAG, "HandleTransaction", "Converting JSON to Transaction...")
	t := TransactionFromJSON(b)
	tracelog.Info(TAG, "HandleTransaction", t.String())

	msg := messages.TransactionMessage{Hash: t.Hash}

	jsonData, err := json.Marshal(msg)
	if err != nil {
		tracelog.Error(err, "Error trying to marshal", "HandleTransaction")
	}

	publish(string(jsonData))
}
Exemple #17
0
// Startup brings the manager to a running state
func Startup(sessionId string) (err error) {
	defer helper.CatchPanic(&err, sessionId, "Startup")

	// If the system has already been started ignore the call
	if singleton != nil {
		return err
	}

	tracelog.Started(sessionId, "Startup")

	// Pull in the configuration
	config := mongoConfiguration{}
	err = envconfig.Process("mgo", &config)
	if err != nil {
		tracelog.CompletedError(err, sessionId, "Startup")
		return err
	}

	// Create the Mongo Manager
	singleton = &mongoManager{
		sessions: map[string]*mongoSession{},
	}

	// Log the mongodb connection straps
	tracelog.Trace(sessionId, "Startup", "MongoDB : Hosts[%s]", config.Hosts)
	tracelog.Trace(sessionId, "Startup", "MongoDB : Database[%s]", config.Database)
	tracelog.Trace(sessionId, "Startup", "MongoDB : Username[%s]", config.UserName)

	hosts := strings.Split(config.Hosts, ",")

	// Create the strong and monotonic sessions
	err = CreateSession(sessionId, "strong", MASTER_SESSION, hosts, config.Database, config.UserName, config.Password)
	err = CreateSession(sessionId, "monotonic", MONOTONIC_SESSION, hosts, config.Database, config.UserName, config.Password)

	tracelog.Completed(sessionId, "Startup")
	return err
}
// Prepare is called before controllers are called.
func Prepare() *services.Service {
	var service services.Service

	// TODO: Add Test User To Environment
	service.UserID = "testing"

	err := service.Prepare()
	if err != nil {
		log.Error(err, service.UserID, "Prepare")
		return nil
	}

	log.Trace(service.UserID, "Before", "UserID[%s]", service.UserID)
	return &service
}
func NearbyHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	var placeType = vars["type"]
	// TODO: may want to validate type

	lat, latErr := strconv.ParseFloat(vars["lat"], 32)
	if latErr != nil {
		ReturnErrorToClient(w, latErr, "Invalid latitude value. Expecting a floating point number")
		return
	}

	lng, lngErr := strconv.ParseFloat(vars["lng"], 32)
	if lngErr != nil {
		ReturnErrorToClient(w, lngErr, "Invalid longitude value. Expecting a floating point number")
		return
	}

	tracelog.Trace("Type Value", "main", "Type is %s", placeType)
	tracelog.Trace("Lat Value", "main", "Lat is %f", lat)
	tracelog.Trace("Lng Value", "main", "Lng is %f", lng)

	response, nearbyErr := NearbySearch(placeType, lat, lng)
	if nearbyErr != nil {
		ReturnErrorToClient(w, nearbyErr, "Nearby Search returned an error")
		return
	}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(response); err != nil {
		tracelog.Error(err, "An error occurred while encoding json response", "NearbyHandler")
		panic(err)
	}
}
func UserLogup(service *services.Service, userInfo userModel.UserInfo) (*userModel.UserInfo, error) {
	log.Startedf(service.UserID, "UserLogup", "user[%s]", userInfo.UserName)
	f := func(collection *mgo.Collection) error {
		log.Trace(service.UserID, "UserLogup", "MGO : db.user_infos.insert(%s)", mongo.ToString(userInfo))
		return collection.Insert(&userInfo)
	}
	if err := service.DBAction(Config.Database, "user_infos", f); err != nil {
		if err != mgo.ErrNotFound {
			log.CompletedError(err, service.UserID, "UserLogup")
			return nil, err
		}
	}
	log.Completedf(service.UserID, "UserLogup", "userInfo%+v", &userInfo)
	return &userInfo, nil
}
// Prepare is called prior to the baseController method.
func (baseController *BaseController) Prepare() {

	UserID := baseController.GetSession("UserID")
	if UserID == nil {
		UserID = "Unknown"
	}
	baseController.UserID = UserID.(string)

	if err := baseController.Service.Prepare(); err != nil {
		log.Errorf(err, baseController.UserID, "BaseController.Prepare", baseController.Ctx.Request.URL.Path)
		baseController.ServeError(err)
		return
	}

	log.Trace(baseController.UserID, "BaseController.Prepare", "UserID[%s] Path[%s]", baseController.UserID, baseController.Ctx.Request.URL.Path)
}
func SaveFile(service *services.Service, fileInfo fileModels.FileInfo) (*fileModels.FileInfo, error) {
	log.Startedf(service.UserID, "SaveFile", "FileHash[%s]", fileInfo.FileHash)

	f := func(collection *mgo.Collection) error {
		log.Trace(service.UserID, "SaveFile", "MGO : db.file_infos.insert(%s)", mongo.ToString(fileInfo))
		return collection.Insert(&fileInfo)
	}
	if err := service.DBAction(Config.Database, "file_infos", f); err != nil {
		if err != mgo.ErrNotFound {
			log.CompletedError(err, service.UserID, "SaveFile")
			return nil, err
		}
	}

	log.Completedf(service.UserID, "SaveFile", "fileInfo%+v", &fileInfo)
	return &fileInfo, nil
}
Exemple #23
0
// Prepare is called prior to the baseController method.
func (baseController *BaseController) Prepare() {
	baseController.UserID = baseController.GetString("userID")
	if baseController.UserID == "" {
		baseController.UserID = baseController.GetString(":userID")
	}

	if baseController.UserID == "" {
		baseController.UserID = "Unknow"
	}

	if err := baseController.Service.Prepare(); err != nil {
		log.Errorf(err, baseController.UserID, "BaseController.Prepare", baseController.Ctx.Request.URL.Path)
		baseController.ServeError(err)
		return
	}
	log.Trace(baseController.UserID, "BaseController.Prepare", "UserID[%s] Path[%s]", baseController.UserID, baseController.Ctx.Request.URL.Path)
}
Exemple #24
0
// Prepare is called prior to the baseController method
func (baseController *BaseController) Prepare() {
	baseController.UserId = baseController.GetString("userId")
	if baseController.UserId == "" {
		baseController.UserId = baseController.GetString(":userId")
	}
	if baseController.UserId == "" {
		baseController.UserId = "Unknown"
	}

	err := baseController.Service.Prepare()
	if err != nil {
		tracelog.Errorf(err, baseController.UserId, "BaseController.Prepare", baseController.Ctx.Request.URL.Path)
		baseController.ServeError(err)
		return
	}

	tracelog.Trace(baseController.UserId, "BaseController.Prepare", "UserId[%s] Path[%s]", baseController.UserId, baseController.Ctx.Request.URL.Path)
}
func googleReverseGeocodeQueryStr(lat float64, lng float64) (string, error) {
	var queryStr = bytes.NewBufferString(googleGeocodeURL + "?")
	_, err := queryStr.WriteString(fmt.Sprintf("latlng=%f,%f", lat, lng))
	if err != nil {
		return "", err
	}

	if GoogleAPIKey != "" {
		_, err := queryStr.WriteString(fmt.Sprintf("&key=%s", GoogleAPIKey))
		if err != nil {
			return "", err
		}
	}

	tracelog.Trace("Query String", "googleReverseGeocodeQueryStr", queryStr.String())

	return queryStr.String(), err
}
func googlePlacesQueryStr(placeType string, lat float64, lng float64) (string, error) {
	var queryStr = bytes.NewBufferString(googlePlacesURL + "?")
	_, err := queryStr.WriteString(fmt.Sprintf("location=%f,%f&rankby=distance&types=%s", lat, lng, placeType))
	if err != nil {
		return "", err
	}

	if GoogleAPIKey != "" {
		_, err := queryStr.WriteString(fmt.Sprintf("&key=%s", GoogleAPIKey))
		if err != nil {
			return "", err
		}
	}

	tracelog.Trace("Query String", "googlePlacesQueryStr", queryStr.String())

	return queryStr.String(), err
}
// Starts the main server.
func RunServer() {
	origin := "http://localhost/"
	url := "wss://ws.blockchain.info:443/inv"

	// Connect
	tracelog.Info(TAG, "RunServer", "Connecting to %s...\n", url)
	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		log.Fatal(err)
	}
	tracelog.Info(TAG, "RunServer", "Connected!")

	// Subscribe
	subscriptionMessage := "{\"op\":\"unconfirmed_sub\"}"
	subscriptionBytes := []byte(subscriptionMessage)
	tracelog.Info(TAG, "Subscribing with %s...\n", subscriptionMessage)
	if _, err := ws.Write(subscriptionBytes); err != nil {
		log.Fatal(err)
	}
	tracelog.Info(TAG, "RunServer", "Subscribed!")

	jsonData := make([]byte, 0)
	// Forever
	for {
		n := -1
		buffer := make([]byte, 1024)
		// Read
		tracelog.Trace(TAG, "RunServer", "Reading from socket...")
		if n, err = ws.Read(buffer); err != nil {
			log.Fatal(err)
		}

		jsonData = append(jsonData, buffer[:n]...)

		if IsValidJson(jsonData) {
			// Process
			go HandleTransaction(jsonData)

			// Restart
			jsonData = make([]byte, 0)
		}
	}
}
Exemple #28
0
// FindRegion retrieves the stations for the specified region
func FindRegion(service *services.Service, region string) ([]buoyModels.BuoyStation, error) {
	log.Startedf(service.UserID, "FindRegion", "region[%s]", region)

	var buoyStations []buoyModels.BuoyStation
	f := func(collection *mgo.Collection) error {
		queryMap := bson.M{"region": region}

		log.Trace(service.UserID, "FindRegion", "Query : db.buoy_stations.find(%s)", mongo.ToString(queryMap))
		return collection.Find(queryMap).All(&buoyStations)
	}

	if err := service.DBAction(Config.Database, "buoy_stations", f); err != nil {
		log.CompletedError(err, service.UserID, "FindRegion")
		return nil, err
	}

	log.Completedf(service.UserID, "FindRegion", "buoyStations%+v", buoyStations)
	return buoyStations, nil
}
Exemple #29
0
// FindStation retrieves the specified station
func FindStation(service *services.Service, stationID string) (*buoyModels.BuoyStation, error) {
	log.Startedf(service.UserID, "FindStation", "stationID[%s]", stationID)
	var buoyStation buoyModels.BuoyStation
	//DBCall 方法
	f := func(collection *mgo.Collection) error {
		queryMap := bson.M{"station_id": stationID}

		log.Trace(service.UserID, "FindStation", "MGO : db.buoy_stations.find(%s).limit(1)", mongo.ToString(queryMap))
		return collection.Find(queryMap).One(&buoyStation)
	}

	if err := service.DBAction(Config.Database, "buoy_stations", f); err != nil {
		if err != mgo.ErrNotFound {
			log.CompletedError(err, service.UserID, "FindStation")
			return nil, err
		}
	}
	log.Completedf(service.UserID, "FindStation", "buoyStation%+v", &buoyStation)
	return &buoyStation, nil
}
func FindMsg(service *services.Service, userID string) (*msgModel.Message, error) {
	log.Startedf(service.UserID, "FindMsg", "userID[%s]", userID)

	var message msgModel.Message
	f := func(collection *mgo.Collection) error {
		queryMap := bson.M{"user_id": userID}

		log.Trace(service.UserID, "FindMsg", "MGO : db.message.find(%s).limit(1)", mongo.ToString(queryMap))
		return collection.Find(queryMap).One(&message)
	}

	if err := service.DBAction(Config.Database, "message", f); err != nil {
		if err != mgo.ErrNotFound {
			log.CompletedError(err, service.UserID, "FindMsg")
			return nil, err
		}
	}

	log.Completedf(service.UserID, "FindMsg", "message%+v", &message)
	return &message, nil
}