Esempio n. 1
0
func traverseMention() {
	// retrieve one mention, evaluate, and write it back to the database
	session, err := database() // establish session with database
	if err != nil {
		panic(err)
	}
	defer session.Close()
	d := session.DB("batcave2").C("mention")

	var mention Mention

	err = d.Find(bson.M{"Sentiment": nil}).One(&mention)
	if err != nil {
		fmt.Println("Find error: Mentions without sentiment", err)
		time.Sleep(10 * time.Second) // wait for new mentions to show up in database
		return
	}

	id := bson.ObjectId(mention.Id)

	fmt.Println("Mention: ", mention) // debugging
	mention.Sentiment = parseMention(mention.Text)
	fmt.Println("Sentiment: ", mention.Sentiment) // debugging

	err = d.UpdateId(id, bson.M{"$addToSet": bson.M{"Sentiment": mention.Sentiment}})

	if err != nil {
		fmt.Println("Update: ", err)
	}
}
Esempio n. 2
0
File: set.go Progetto: Laller/nocrud
func decodeId(s string) (bson.ObjectId, error) {
	val, err := base64.URLEncoding.DecodeString(s)
	if err != nil {
		panic("Can't decode id: " + err.Error())
	}
	return bson.ObjectId(val), nil
}
Esempio n. 3
0
// Save the DataModel to DataStore
func SaveModel(mgo_db string, m DataModel, conn *mgo.Session) (err error) {
	if conn == nil {
		conn, err = MgoConnGet(mgo_db)
		if err != nil {
			return
		}
		defer conn.Close()
	}
	if conn != nil {
		bsonMid := m.MidGet()
		c := conn.DB(mgo_db).C(m.Type())
		//Debug("SAVING ", mgo_db, " type=", m.Type(), " Mid=", bsonMid)
		if len(bsonMid) < 5 {
			m.MidSet(bson.NewObjectId())
			if err = c.Insert(m); err != nil {
				Log(ERROR, "MGOU ERROR on insert ", err, " TYPE=", m.Type(), " ", m.MidGet())
			} else {
				//Log(DEBUG, "successfully inserted!!!!!!  ", m.MidGet(), " oid=", m.OidGet())
			}
		} else {
			// YOU MUST NOT SEND Mid  "_id" to Mongo
			mid := m.MidGet()
			m.MidSet("") // omitempty means it doesn't get sent
			if err = c.Update(bson.M{"_id": bson.ObjectId(bsonMid)}, m); err != nil {
				Log(ERROR, "MGOU ERROR on update ", err, " ", bsonMid, " MID=?", m.MidGet())
			}
			m.MidSet(mid)
		}
	} else {
		Log(ERROR, "MGOU Nil connection")
		return errors.New("no db connection")
	}
	return
}
Esempio n. 4
0
func (p *UserGroup) readField1(iprot thrift.TProtocol) error {
	if v, err := iprot.ReadString(); err != nil {
		return fmt.Errorf("error reading field 1: %s", err)
	} else {
		p.ID = bson.ObjectId(v)
	}
	return nil
}
Esempio n. 5
0
func (self *query_base) OneDocumentID() (id bson.ObjectId, err error) {
	q, err := self.thisQuery.mongoQuery()
	if err != nil {
		return bson.ObjectId(""), err
	}
	var doc DocumentBase
	err = q.One(&doc)
	return doc.ID, err
}
Esempio n. 6
0
func ToObjectId(id string) (bid bson.ObjectId, err error) {
	var d []byte
	d, err = hex.DecodeString(id)
	if err != nil || len(d) != 12 {
		err = fmt.Errorf("Invalid input to ObjectIdHex: %q", id)
		return
	}
	bid = bson.ObjectId(d)
	return
}
func (ca *ConnectedAgent) String(m *model.Model) string {
	if ca.station != nil {
		if station, err := m.FindStationById(bson.ObjectId(*ca.station)); err == nil {
			return fmt.Sprintf("Agent %s in station %s", ca.login, station.Name)
		} else {
			return fmt.Sprintf("Agent %s in unknown station %s", ca.login, *ca.station)
		}
	} else {
		return fmt.Sprintf("Agent %s outside a station", ca.login)
	}
}
Esempio n. 8
0
func (self *Ref) SetStringID(str string) error {
	switch len(str) {
	case 0, 12:
		self.ID = bson.ObjectId(str)
	case 24:
		self.ID = bson.ObjectIdHex(str)
	default:
		return errs.Format("Invalid string for bson.ObjectId: '%s'", str)
	}
	return nil
}
Esempio n. 9
0
func (op *Operation) ObjectId() (bson.ObjectId, error) {
	var object bson.M

	switch op.Op {
	case Update:
		object = op.UpdateObject
	default:
		object = op.Object
	}

	id, ok := object["_id"]
	if !ok {
		return bson.ObjectId(""), OperationError{"_id does not exist in object", op}
	}

	bid, ok := id.(bson.ObjectId)
	if !ok {
		return bson.ObjectId(""), OperationError{"Could not find a bson objectid", op}
	}
	return bid, nil
}
Esempio n. 10
0
// Get retriives task by id
func (t *Task) Get(id string) (*TaskRow, error) {

	var tr TaskRow
	err := t.coll.FindId(bson.ObjectId(id)).One(&tr) // .Sort("created").
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, ErrNotFound
		}
		return nil, err
	}
	return &tr, nil
}
Esempio n. 11
0
func main() {
	c, m := ConnectToMongoAndGetCollection()
	unprocessedSessions := GetAllRelevantSessions(c)
	r := lib.ConnectToRedis()
	var results []GameSessionResult
	for _, session := range unprocessedSessions {
		results = append(results, getWinsAndLosses(session, r))
	}

	increasingWins := func(r1, r2 *GameSessionResult) bool {
		return (r1.Wins - r1.Losses) > (r2.Wins - r2.Losses)
	}
	OrderedBy(increasingWins).Sort(results)
	for i, result := range results {
		results[i] = result.getCreatorName(c)
	}
	for i, result := range results {
		results[i] = result.getSessionDetails(m)
	}
	var ogres []GameSessionResult
	var humans []GameSessionResult
	for _, result := range results {
		if result.Session.Team == "ogres" {
			ogres = append(ogres, result)
		} else {
			humans = append(humans, result)
		}
	}

	fmt.Println("Top ogres")
	for _, result := range ogres {
		fmt.Printf("%d,%s,%s,%s,%d,%d,%d\n", result.PreliminaryRank, bson.ObjectId(result.Session.ID), result.CreatorName, result.Email, result.Playtime, result.Wins, result.Losses)
	}
	fmt.Println("Top humans")
	for _, result := range humans {
		fmt.Printf("%d,%s,%s,%s,%d,%d,%d\n", result.PreliminaryRank, bson.ObjectId(result.Session.ID), result.CreatorName, result.Email, result.Playtime, result.Wins, result.Losses)
	}

}
Esempio n. 12
0
// GetAndDelete returns task and deletes it if found. If not found returns nil, model.ErrNotFound
func (t *Task) GetAndDelete(id string) (*TaskRow, error) {

	var tr TaskRow
	_, err := t.coll.FindId(bson.ObjectId(id)).Apply(mgo.Change{Remove: true, ReturnNew: false}, &tr)
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, ErrNotFound
		}
		return nil, err
	}

	return &tr, nil
}
Esempio n. 13
0
func (application *Application) Init(filename *string) {
	gob.Register(bson.ObjectId(""))

	data, err := ioutil.ReadFile(*filename)

	if err != nil {
		glog.Fatalf("Can't read configuration file: %s", err)
		panic(err)
	}

	application.Configuration = &Configuration{}

	err = json.Unmarshal(data, &application.Configuration)

	if err != nil {
		glog.Fatalf("Can't parse configuration file: %s", err)
		panic(err)
	}

	application.Store = sessions.NewCookieStore([]byte(application.Configuration.Secret))
}
Esempio n. 14
0
//Saves Firewall Request to MongoDB
func UpdateFirewallStatus(id string, statusUpdate string) {
	//var pass string
	log.Printf("Updating status to:\t%s for firewall:\t%s\n\n", statusUpdate, id)
	// TODO - Append Status Variable to fwreq with Current Queue
	session, err := mgo.Dial("localhost")
	if err != nil {
		log.Println(err)
	}
	defer session.Close()
	requestCollection := session.DB("firewallapp").C("fwreq")
	hexId, hexErr := hex.DecodeString(id)
	if hexErr != nil {
		log.Printf("\n\nERROR:\t%s\n\n", hexErr)
	}
	updateId := bson.M{"_id": bson.ObjectId(hexId)}
	update := bson.M{"$set": bson.M{"status": statusUpdate}}
	updateErr := requestCollection.Update(updateId, update)
	if updateErr != nil {
		log.Printf("Can't update document %v\n", updateErr)
	}
}
Esempio n. 15
0
func tarjanSort(successors map[bson.ObjectId][]bson.ObjectId) [][]bson.ObjectId {
	// http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
	data := &tarjanData{
		successors: successors,
		nodes:      make([]tarjanNode, 0, len(successors)),
		index:      make(map[bson.ObjectId]int, len(successors)),
	}

	// Sort all nodes to stabilize the logic.
	var all []string
	for id := range successors {
		all = append(all, string(id))
	}
	sort.Strings(all)
	for _, strid := range all {
		id := bson.ObjectId(strid)
		if _, seen := data.index[id]; !seen {
			data.strongConnect(id)
		}
	}
	return data.output
}
Esempio n. 16
0
func New(c *Config) *Goat {
	// Initialize session store
	gob.Register(bson.ObjectId(""))
	s := sessions.NewCookieStore([]byte("sevenbyelevensecretbomberboy"))
	r := mux.NewRouter()

	mx := http.NewServeMux()
	mx.Handle("/", r)

	result := &Goat{
		Router:       r,
		sessionstore: s,
		routes:       make(map[string]*route),
		servemux:     mx,
	}

	if c != nil {
		result.Config = *c
	}

	return result
}
Esempio n. 17
0
func init() {
	var err error
	mongo_server := os.Getenv("OPENSHIFT_MONGODB_DB_URL")
	if mongo_server == "" {
		db_session, err = mgo.Dial("localhost")
	} else {
		db_session, err = mgo.Dial(mongo_server + MONGO_DB_NAME)
	}
	if err != nil {
		log.Print("db connection: ", err)
	}
	// register bson's ObjectId with the gob for cookie encoding
	gob.Register(bson.ObjectId(""))
	gob.RegisterName("app/models.Flash", &Flash{"", ""})
	gob.RegisterName("app/models.Filter", &Filter{})

	database = db_session.DB("").Name
	Router = pat.New()
	//create an index for the email field on the users collection
	if err := db_session.DB(database).C("users").EnsureIndex(mgo.Index{
		Key:    []string{"email"},
		Unique: true,
	}); err != nil {
		log.Print("context: ", err)
	}
	if err := db_session.DB(database).C("users").EnsureIndexKey("location"); err != nil {
		log.Print("context: ", err)
	}
	if err := db_session.DB(database).C("users").EnsureIndexKey("country"); err != nil {
		log.Print("context: ", err)
	}
	store = sessions.NewCookieStore([]byte("508a664e65427d3f91000001"))
	if sentry, err = raven.NewClient(SENTRY_DSN); err != nil {
		log.Print("could not connect to sentry: ", err)
	}
	loadTranslations()
}
Esempio n. 18
0
func (s *AEServer) HandleResponseComment(sess sessions.Session, params martini.Params, r *http.Request) (int, string) {
	id := bson.ObjectIdHex(params["id"])
	user := s.GetAuthedUser(sess)
	if user == nil {
		return 401, Message("Not authorized to reply!")
	}

	comment := user.MakeComment(r.Body)
	if comment == nil {
		return http.StatusBadRequest, Message("Poorly formatted JSON")
	}

	question, ok := s.questions.FindByID(id).(*Question)
	if !ok {
		return http.StatusForbidden, Message("No such question!")
	}
	resp_id := params["resp"]
	resp := question.GetResponse(bson.ObjectId(resp_id))
	resp.AddComment(comment)

	s.questions.Update(question)

	return 200, string(comment.JsonBytes())
}
Esempio n. 19
0
func (id ObjectId) Valid() bool {
	return bson.ObjectId(id).Valid()
}
Esempio n. 20
0
func bid(n int) bson.ObjectId {
	return bson.ObjectId(fmt.Sprintf("%024d", n))
}
Esempio n. 21
0
		""},
	{bson.M{"_": float64(5.05)},
		"\x01_\x00333333\x14@"},
	{bson.M{"_": "yo"},
		"\x02_\x00\x03\x00\x00\x00yo\x00"},
	{bson.M{"_": bson.M{"a": true}},
		"\x03_\x00\x09\x00\x00\x00\x08a\x00\x01\x00"},
	{bson.M{"_": []interface{}{true, false}},
		"\x04_\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"},
	{bson.M{"_": []byte("yo")},
		"\x05_\x00\x02\x00\x00\x00\x00yo"},
	{bson.M{"_": bson.Binary{0x80, []byte("udef")}},
		"\x05_\x00\x04\x00\x00\x00\x80udef"},
	{bson.M{"_": bson.Undefined}, // Obsolete, but still seen in the wild.
		"\x06_\x00"},
	{bson.M{"_": bson.ObjectId("0123456789ab")},
		"\x07_\x000123456789ab"},
	{bson.M{"_": false},
		"\x08_\x00\x00"},
	{bson.M{"_": true},
		"\x08_\x00\x01"},
	{bson.M{"_": time.Unix(0, 258e6)}, // Note the NS <=> MS conversion.
		"\x09_\x00\x02\x01\x00\x00\x00\x00\x00\x00"},
	{bson.M{"_": nil},
		"\x0A_\x00"},
	{bson.M{"_": bson.RegEx{"ab", "cd"}},
		"\x0B_\x00ab\x00cd\x00"},
	{bson.M{"_": bson.JavaScript{"code", nil}},
		"\x0D_\x00\x05\x00\x00\x00code\x00"},
	{bson.M{"_": bson.Symbol("sym")},
		"\x0E_\x00\x04\x00\x00\x00sym\x00"},
Esempio n. 22
0
func (id ObjectId) GetBSON() (interface{}, error) {
	return bson.ObjectId(id), nil
}
Esempio n. 23
0
func init() {
	gob.Register(bson.ObjectId(""))
}
Esempio n. 24
0
func (m *Work) OnLoad() {
	if len(m.Mid) > 0 {
		m.Mhex = bson.ObjectId(m.Mid).Hex()
	}
}
Esempio n. 25
0
func (id ObjectId) Hex() string {
	return bson.ObjectId(id).Hex()
}
Esempio n. 26
0
// Normalize takes in an ejson map and normalizes it to regular bson.
func Normalize(m map[string]interface{}) error {
	for key := range m {
		if sm, ok := m[key].(map[string]interface{}); ok {
			if d, ok := sm["$date"].(float64); ok {
				tm := int64(d * 0.001) // convert the milliseconds to seconds
				t := time.Unix(tm, 0)
				m[key] = &t
			} else if id, ok := sm["$oid"].(string); ok {
				var oid bson.ObjectId
				if bson.IsObjectIdHex(id) {
					oid = bson.ObjectIdHex(id)
				} else {
					oid = bson.ObjectId(id)
				}
				m[key] = &oid
			} else if b, ok := sm["$undefined"].(bool); ok {
				if b {
					m[key] = nil
				}
			} else if ref, ok := sm["$ref"].(string); ok {
				if id, ok := sm["$id"].(string); ok {
					var oid bson.ObjectId
					if bson.IsObjectIdHex(id) {
						oid = bson.ObjectIdHex(id)
					} else {
						oid = bson.ObjectId(id)
					}
					dbref := mgo.DBRef{
						Collection: ref,
						Id:         oid,
					}
					m[key] = &dbref
				} else {
					return fmt.Errorf(`ejson: "%s" expected a {"$ref": "string", "$id": "hex"} got "%+v"`, key, sm)
				}
			} else if bin, ok := sm["$binary"].(string); ok {
				b64, err := base64.StdEncoding.DecodeString(bin)
				if err != nil {
					return fmt.Errorf(`ejson: "%s" expected valid a base64 string in $binary, got: %v`, key, err)
				}
				if t, ok := sm["$type"].(string); ok {
					ti, err := strconv.ParseUint(t, 16, 8)
					if err != nil {
						return fmt.Errorf(`ejson: "%s" expected a valid hex byte in $type, got: %v`, key, err)
					}
					bin := bson.Binary{
						Kind: byte(ti),
						Data: b64,
					}
					m[key] = &bin
				}
			} else {
				if err := Normalize(sm); err != nil {
					return err
				}
			}
		} else if sm, ok := m[key].([]interface{}); ok {
			for i := range sm {
				curr := (sm[i]).(map[string]interface{})
				if err := Normalize(curr); err != nil {
					return err
				}
			}
		}
	}
	return nil
}
Esempio n. 27
0
// Load message with given Id
func LoadMessage(id string) (*Message, error) {
	m := new(Message)
	err := Mongo.GetId("message", bson.ObjectId(id), m)
	return m, err
}