func (test *TestIterationRepository) TestListIterationBySpace() { t := test.T() resource.Require(t, resource.Database) repo := iteration.NewIterationRepository(test.DB) spaceID := uuid.NewV4() for i := 0; i < 3; i++ { start := time.Now() end := start.Add(time.Hour * (24 * 8 * 3)) name := "Sprint #2" + strconv.Itoa(i) i := iteration.Iteration{ Name: name, SpaceID: spaceID, StartAt: &start, EndAt: &end, } repo.Create(context.Background(), &i) } repo.Create(context.Background(), &iteration.Iteration{ Name: "Other Spring #2", SpaceID: uuid.NewV4(), }) its, err := repo.List(context.Background(), spaceID) assert.Nil(t, err) assert.Len(t, its, 3) }
func (test *TestAreaRepository) TestCreateChildArea() { t := test.T() resource.Require(t, resource.Database) repo := area.NewAreaRepository(test.DB) name := "Area #24" name2 := "Area #24.1" i := area.Area{ Name: name, SpaceID: uuid.NewV4(), } err := repo.Create(context.Background(), &i) assert.Nil(t, err) // ltree field doesnt accept "-" , so we will save them as "_" expectedPath := strings.Replace((i.ID).String(), "-", "_", -1) area2 := area.Area{ Name: name2, SpaceID: uuid.NewV4(), Path: expectedPath, } err = repo.Create(context.Background(), &area2) assert.Nil(t, err) actualArea, err := repo.Load(context.Background(), area2.ID) actualPath := actualArea.Path require.Nil(t, err) require.NotNil(t, actualArea) assert.Equal(t, expectedPath, actualPath) }
func (test *TestCommentRepository) TestDeleteComment() { t := test.T() resource.Require(t, resource.Database) defer cleaner.DeleteCreatedEntities(test.DB)() repo := comment.NewCommentRepository(test.DB) parentID := "AA" c := &comment.Comment{ ParentID: parentID, Body: "Test AA", CreatedBy: uuid.NewV4(), ID: uuid.NewV4(), } repo.Create(context.Background(), c) if c.ID == uuid.Nil { t.Errorf("Comment was not created, ID nil") } c.Body = "Test AB" err := repo.Delete(context.Background(), c.ID) if err != nil { t.Error("Failed to Delete", err.Error()) } }
func (test *TestIterationRepository) TestCreateChildIteration() { t := test.T() resource.Require(t, resource.Database) repo := iteration.NewIterationRepository(test.DB) start := time.Now() end := start.Add(time.Hour * (24 * 8 * 3)) name := "Sprint #24" name2 := "Sprint #24.1" i := iteration.Iteration{ Name: name, SpaceID: uuid.NewV4(), StartAt: &start, EndAt: &end, } repo.Create(context.Background(), &i) i2 := iteration.Iteration{ Name: name2, SpaceID: uuid.NewV4(), StartAt: &start, EndAt: &end, ParentID: i.ID, } repo.Create(context.Background(), &i2) i2L, err := repo.Load(context.Background(), i2.ID) require.Nil(t, err) assert.NotEqual(t, uuid.Nil, i2.ParentID) assert.Equal(t, i2.ParentID, i2L.ParentID) }
func (test *TestAreaRepository) TestListImmediateChildrenOfGrandParents() { t := test.T() resource.Require(t, resource.Database) repo := area.NewAreaRepository(test.DB) name := "Area #240" name2 := "Area #240.1" name3 := "Area #240.1.3" // *** Create Parent Area *** i := area.Area{ Name: name, SpaceID: uuid.NewV4(), } err := repo.Create(context.Background(), &i) assert.Nil(t, err) // *** Create 'son' area *** expectedPath := strings.Replace((i.ID).String(), "-", "_", -1) area2 := area.Area{ Name: name2, SpaceID: uuid.NewV4(), Path: expectedPath, } err = repo.Create(context.Background(), &area2) require.Nil(t, err) childAreaList, err := repo.ListChildren(context.Background(), &i) assert.Equal(t, 1, len(childAreaList)) require.Nil(t, err) // *** Create 'grandson' area *** expectedPath = strings.Replace((i.ID).String()+"."+(area2.ID.String()), "-", "_", -1) area4 := area.Area{ Name: name3, SpaceID: uuid.NewV4(), Path: expectedPath, } err = repo.Create(context.Background(), &area4) require.Nil(t, err) childAreaList, err = repo.ListChildren(context.Background(), &i) // But , There is only 1 'son' . require.Nil(t, err) assert.Equal(t, 1, len(childAreaList)) assert.Equal(t, area2.ID, childAreaList[0].ID) // *** Confirm the grandson has no son childAreaList, err = repo.ListChildren(context.Background(), &area4) assert.Equal(t, 0, len(childAreaList)) }
func (rest *TestSpaceAreaREST) TestListAreas() { t := rest.T() resource.Require(t, resource.Database) // Create a new space where we'll create 3 areas var s *space.Space // Create another space where we'll create 1 area. var anotherSpace *space.Space application.Transactional(rest.db, func(app application.Application) error { var err error repo := app.Spaces() newSpace := &space.Space{ Name: "Test Space 1" + uuid.NewV4().String(), } s, err = repo.Create(context.Background(), newSpace) require.Nil(t, err) newSpace = &space.Space{ Name: "Another space" + uuid.NewV4().String(), } anotherSpace, err = repo.Create(context.Background(), newSpace) require.Nil(t, err) return nil }) svc, ctrl := rest.SecuredController() spaceId := s.ID anotherSpaceId := anotherSpace.ID var createdAreaUuids1 []uuid.UUID for i := 0; i < 3; i++ { name := "Test Area #20" + strconv.Itoa(i) spaceAreaContext := createSpaceArea(name, &name) _, c := test.CreateSpaceAreasCreated(t, svc.Context, svc, ctrl, spaceId.String(), spaceAreaContext) require.NotNil(t, c.Data.ID) require.NotNil(t, c.Data.Relationships.Space) createdAreaUuids1 = append(createdAreaUuids1, *c.Data.ID) } name := "area in a different space" anotherSpaceAreaContext := createSpaceArea(name, &name) _, createdArea := test.CreateSpaceAreasCreated(t, svc.Context, svc, ctrl, anotherSpaceId.String(), anotherSpaceAreaContext) require.NotNil(t, createdArea) _, areaList := test.ListSpaceAreasOK(t, svc.Context, svc, ctrl, spaceId.String()) assert.Len(t, areaList.Data, 3) for i := 0; i < len(createdAreaUuids1); i++ { assert.NotNil(t, searchInAreaSlice(createdAreaUuids1[i], areaList)) } _, anotherAreaList := test.ListSpaceAreasOK(t, svc.Context, svc, ctrl, anotherSpaceId.String()) assert.Len(t, anotherAreaList.Data, 1) assert.Equal(t, anotherAreaList.Data[0].ID, createdArea.Data.ID) }
func TestListIdentities(t *testing.T) { resource.Require(t, resource.Database) defer cleaner.DeleteCreatedEntities(DB)() service := goa.New("Test-Identities") app := gormapplication.NewGormDB(DB) identityController := NewIdentityController(service, app) _, ic := test.ListIdentityOK(t, service.Context, service, identityController) require.NotNil(t, ic) numberOfCurrentIdent := len(ic.Data) ctx := context.Background() identityRepo := app.Identities() identity := account.Identity{ Username: "******", Provider: "test-idp", ID: uuid.NewV4(), } err := identityRepo.Create(ctx, &identity) if err != nil { t.Fatal(err) } _, ic2 := test.ListIdentityOK(t, service.Context, service, identityController) require.NotNil(t, ic2) assert.Equal(t, numberOfCurrentIdent+1, len(ic2.Data)) assertIdent(t, identity, findIdent(identity.ID, ic2.Data)) identity2 := account.Identity{ Username: "******", Provider: "test-idp", ID: uuid.NewV4(), } err = identityRepo.Create(ctx, &identity2) if err != nil { t.Fatal(err) } _, ic3 := test.ListIdentityOK(t, service.Context, service, identityController) require.NotNil(t, ic3) assert.Equal(t, numberOfCurrentIdent+2, len(ic3.Data)) assertIdent(t, identity, findIdent(identity.ID, ic3.Data)) assertIdent(t, identity2, findIdent(identity2.ID, ic3.Data)) }
func createAndRegisterUser( passwordHasher security.PasswordHasher, repository lib.UserRepository, request *request.RegistrationRequest, ) (*model.User, error) { confirmationToken := uuid.NewV4().String() hashedPassword, err := passwordHasher.Hash(request.Password) if err != nil { return nil, err } user := model.NewUser( request.Email, hashedPassword, request.FirstName, request.LastName, confirmationToken, ) err = repository.Insert(user) if err != nil { return nil, err } return user, nil }
func BenchmarkEncoding(b *testing.B) { u := uuid.NewV4() su := New() for i := 0; i < b.N; i++ { su.Encode(u) } }
// Handler makes it possible to use a RouteHandler where a http.Handler is required func Handler(e *Endpoint) http.Handler { HTTPHandler := func(resWriter http.ResponseWriter, req *http.Request) { request := &Request{ ID: uuid.NewV4().String()[:8], Request: req, Response: resWriter, } request.Response.Header().Set("X-Request-Id", request.ID) if e.Params != nil { // We give request.Params the same type as e.Params request.Params = reflect.New(reflect.TypeOf(e.Params).Elem()).Interface() if err := request.ParseParams(); err != nil { request.Error(err) return } } defer request.handlePanic() accessGranted := e.Auth == nil || e.Auth(request) if accessGranted { e.Handler(request) } } return http.HandlerFunc(HTTPHandler) }
func DuplicateSlide(pptRootPath, slideName string) (newSlideName string, err error) { newSlideName = uuid.NewV4().String() + ".xml" newSlideName = "slilde2.xml" slidePath := filepath.Join(pptRootPath, c.PPTFolder, c.SlideFolder, slideName) newSlidePath := filepath.Join(pptRootPath, c.PPTFolder, c.SlideFolder, newSlideName) err = fo.CopyFile(slidePath, newSlidePath) if err != nil { return "", err } sourceSlideRelsPath := filepath.Join(pptRootPath, c.PPTFolder, c.SlideFolder, c.RelsFolder, slideName+relsExtension) newSlideRelsPath := filepath.Join(pptRootPath, c.PPTFolder, c.SlideFolder, c.RelsFolder, newSlideName+relsExtension) err = fo.CopyFile(sourceSlideRelsPath, newSlideRelsPath) if err != nil { return "", err } rid, err := createRelations(pptRootPath, newSlideName) if err != nil { return "", err } err = addSlideInPresentation(pptRootPath, rid) if err != nil { return "", err } return newSlideName, addSlideContentTypeInContentTypes(pptRootPath, newSlideName) }
func wrapRouterWithLogrus(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { defer func() { if err := recover(); err != nil { log.Printf("recovered from panic: %+v / %+v", err, req) // http.Error(w, http.StatusText(500), 500) } }() start := time.Now() h.ServeHTTP(w, req) took := time.Since(start) ip, err := getIP(req) if err != nil { log.Warnf("getIP error: %v", err) } log.WithFields(log.Fields{ "event_type": "router", "referrer": req.Referer(), "ua": req.UserAgent(), "method": req.Method, "path": req.URL.Path, "ip": ip, "uuid": uuid.NewV4(), }).Debugf("took %s", took) } }
func (test *TestIterationRepository) TestCreateIteration() { t := test.T() resource.Require(t, resource.Database) repo := iteration.NewIterationRepository(test.DB) start := time.Now() end := start.Add(time.Hour * (24 * 8 * 3)) name := "Sprint #24" i := iteration.Iteration{ Name: name, SpaceID: uuid.NewV4(), StartAt: &start, EndAt: &end, } repo.Create(context.Background(), &i) if i.ID == uuid.Nil { t.Errorf("Iteration was not created, ID nil") } if i.CreatedAt.After(time.Now()) { t.Errorf("Iteration was not created, CreatedAt after Now()?") } assert.Equal(t, start, *i.StartAt) assert.Equal(t, end, *i.EndAt) assert.Equal(t, name, i.Name) }
func WithLogrus(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { defer func() { if err := recover(); err != nil { log.WithFields(log.Fields{ "event_type": "panic_recover", "referrer": req.Referer(), "ua": req.UserAgent(), "method": req.Method, "path": req.URL.Path, "ip": req.RemoteAddr, "real_ip": getRealIP(req), "error": err, }).Errorln("WithLogrus error") } }() start := nowPacific() h.ServeHTTP(w, req) took := time.Since(start) log.WithFields(log.Fields{ "event_type": "web_server", "referrer": req.Referer(), "ua": req.UserAgent(), "method": req.Method, "path": req.URL.Path, "ip": req.RemoteAddr, "real_ip": getRealIP(req), "uuid": uuid.NewV4(), }).Debugf("took %s", took) } }
// NewAttachment creates a new attachment object. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) { attach := &Attachment{ UUID: gouuid.NewV4().String(), Name: name, } if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil { return nil, fmt.Errorf("MkdirAll: %v", err) } fw, err := os.Create(attach.LocalPath()) if err != nil { return nil, fmt.Errorf("Create: %v", err) } defer fw.Close() if _, err = fw.Write(buf); err != nil { return nil, fmt.Errorf("Write: %v", err) } else if _, err = io.Copy(fw, file); err != nil { return nil, fmt.Errorf("Copy: %v", err) } sess := x.NewSession() defer sessionRelease(sess) if err := sess.Begin(); err != nil { return nil, err } if _, err := sess.Insert(attach); err != nil { return nil, err } return attach, sess.Commit() }
func (k *Kloud) AuthPasswordLogin(r *kite.Request) (interface{}, error) { var req PasswordLoginRequest if err := getReq(r, &req); err != nil { return nil, err } if _, err := modelhelper.CheckAndGetUser(req.Username, req.Password); err != nil { return nil, errors.New("username and/or password does not match") } resp, err := k.authLogin(req.Username, &req.LoginRequest) if err != nil { return nil, err } kiteKey, err := k.Userdata.Keycreator.Create(req.Username, uuid.NewV4().String()) if err != nil { return nil, err } return &PasswordLoginResponse{ LoginResponse: *resp, KiteKey: kiteKey, }, nil }
func (test *TestAreaRepository) TestCreateArea() { t := test.T() resource.Require(t, resource.Database) repo := area.NewAreaRepository(test.DB) name := "Area 21" i := area.Area{ Name: name, SpaceID: uuid.NewV4(), } repo.Create(context.Background(), &i) if i.ID == uuid.Nil { t.Errorf("Area was not created, ID nil") } if i.CreatedAt.After(time.Now()) { t.Errorf("Area was not created, CreatedAt after Now()?") } assert.Equal(t, name, i.Name) }
// Create runs the create action. func (c *UserspaceController) Create(ctx *app.CreateUserspaceContext) error { return models.Transactional(c.db, func(db *gorm.DB) error { path := ctx.RequestURI data := Data{} err := c.db.Where("path = ?", path).First(&data).Error fmt.Println(err) if err != nil { data = Data{ ID: uuid.NewV4(), Path: ctx.RequestURI, Data: workitem.Fields(ctx.Payload), } err := c.db.Create(&data).Error if err != nil { goa.LogError(ctx, "error adding data", "error", err.Error()) return ctx.InternalServerError() } } else { err := c.db.Model(&data).Update("data", workitem.Fields(ctx.Payload)).Error if err != nil { goa.LogError(ctx, "error updating data", "error", err.Error()) return ctx.InternalServerError() } } return ctx.NoContent() }) }
func (v *vm) Create(attr vms.MachineAttributes) (vms.Machine, error) { if waitNextCall { time.Sleep(time.Duration(waitDelay) * time.Millisecond) waitNextCall = false waitDelay = 0 } if failNextCall { failNextCall = false return nil, failError } if nilNextCall { nilNextCall = false return nil, nil } if attr.Type == nil { attr.Type = &defaultMachineType } t, ok := attr.Type.(*machineType) if !ok { return nil, errors.New("VM Type not supported") } new_machine := machine{ id: uuid.NewV4().String(), name: attr.Name, machineType: *t, status: vms.StatusUp, } allMachines = append(allMachines, &new_machine) return &new_machine, nil }
// StartRecovery ... func (pr *passwordRecoverer) Start(email string) error { user, err := pr.userRepository.FindOneByUsername(email) if err != nil { return err } if !user.IsActive { return ErrPasswordRecovererUserIsNotActive } if !user.IsConfirmed { return ErrPasswordRecovererUserIsNotConfirmed } passwordRecovery, err := pr.passwordRecoveryRepository.Create(user.ID, uuid.NewV4().String()) if err != nil { return err } err = pr.mailer.Send(user.Username, map[string]interface{}{ "user_id": passwordRecovery.UserID, "confirmation_token": passwordRecovery.ConfirmationToken, }) if err != nil { return err } return nil }
func wrapHandlerFunc2(fn func(w http.ResponseWriter, req *http.Request)) func(w http.ResponseWriter, req *http.Request) { return func(w http.ResponseWriter, req *http.Request) { defer func() { if err := recover(); err != nil { log.Printf("recovered from panic: %+v / %+v", err, req) // http.Error(w, http.StatusText(500), 500) } }() start := time.Now() fn(w, req) // execute the handler took := time.Since(start) // ip, err := getIP(req) // if err != nil { // log.Warnf("getIP error: %v", err) // } log.WithFields(log.Fields{ "event_type": runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name(), "referrer": req.Referer(), "ua": req.UserAgent(), "method": req.Method, "path": req.URL.Path, "ip": req.RemoteAddr, "real_ip": getRealIP(req), "uuid": uuid.NewV4(), }).Debugf("took %s", took) } }
func (self *Connection) FragmentMessage(contents []byte) []domain.UserMessage { messageBase := domain.MessageBase{ SendRouteID: self.Route.ForwardToRouteID, SendBack: false, FromPeerID: self.Node.Config.PubKey, Nonce: mesh.GenerateNonce(), } fragmentsBuf := make([]domain.UserMessage, 0) maxContentLength := self.GetMaximumContentLength() fmt.Fprintf(os.Stdout, "MaxContentLength: %v\n", maxContentLength) remainingBytes := contents[:] messageID := (domain.MessageID)(uuid.NewV4()) for len(remainingBytes) > 0 { nBytesThisMessage := min(maxContentLength, (uint64)(len(remainingBytes))) bytesThisMessage := remainingBytes[:nBytesThisMessage] remainingBytes = remainingBytes[nBytesThisMessage:] message := domain.UserMessage{ MessageBase: messageBase, MessageID: messageID, Index: (uint64)(len(fragmentsBuf)), Count: 0, Contents: bytesThisMessage, } fragmentsBuf = append(fragmentsBuf, message) } fragments := make([]domain.UserMessage, 0) for _, message := range fragmentsBuf { message.Count = (uint64)(len(fragmentsBuf)) fragments = append(fragments, message) } fmt.Fprintf(os.Stdout, "Message fragmented in %v packets.\n", len(fragments)) return fragments }
func (rest *TestSpaceIterationREST) TestFailListIterationsByMissingSpace() { t := rest.T() resource.Require(t, resource.Database) svc, ctrl := rest.UnSecuredController() test.ListSpaceIterationsNotFound(t, svc.Context, svc, ctrl, uuid.NewV4().String()) }
// NewAttachment creates a new attachment object. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) { attach := &Attachment{ UUID: gouuid.NewV4().String(), Name: name, } localPath := attach.LocalPath() if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil { return nil, fmt.Errorf("MkdirAll: %v", err) } fw, err := os.Create(localPath) if err != nil { return nil, fmt.Errorf("Create: %v", err) } defer fw.Close() if _, err = fw.Write(buf); err != nil { return nil, fmt.Errorf("Write: %v", err) } else if _, err = io.Copy(fw, file); err != nil { return nil, fmt.Errorf("Copy: %v", err) } if _, err := x.Insert(attach); err != nil { return nil, err } return attach, nil }
// NewUser creates a new user. The object is not saved to the database. func (p *DynamoUserPeer) NewUser() *model.User { return &model.User{ Peer: p, ID: uuid.NewV4().String(), CreatedAt: time.Now(), } }
// AddKeyPair add the given key pair so it can be used to validate and // sign/generate tokens. If id is empty, a unique ID will be generated. The // last added key pair is also used to generate tokens for machine // registrations via "handleMachine" method. This can be overiden with the // kontorl.MachineKeyPicker function. func (k *Kontrol) AddKeyPair(id, public, private string) error { if k.keyPair == nil { k.log.Warning("Key pair storage is not set. Using in memory cache") k.keyPair = NewMemKeyPairStorage() } if id == "" { i := uuid.NewV4() id = i.String() } public = strings.TrimSpace(public) private = strings.TrimSpace(private) keyPair := &KeyPair{ ID: id, Public: public, Private: private, } // set last set key pair k.lastIDs = append(k.lastIDs, id) k.lastPublic = append(k.lastPublic, public) k.lastPrivate = append(k.lastPrivate, private) if err := keyPair.Validate(); err != nil { return err } return k.keyPair.AddKey(keyPair) }
func (s *scpRequest) DownloadFile(channel ssh.Channel, req *ssh.Request) error { uid := uuid.NewV4() s.filename = filepath.Join(os.TempDir(), uid.String()) log.Println("saving to:", s.filename) f, err := os.OpenFile(s.filename, os.O_CREATE|os.O_WRONLY, 0664) if err != nil { return errors.Wrap(err, "failed to open file for downloading") } h := sha1.New() mw := io.MultiWriter(f, h) // Read file contents var n int64 if n, err = io.CopyN(mw, channel, s.size); err != nil { return errors.Wrap(err, "failed to download file") } log.Println("copied", n, "bytes") if err = f.Close(); err != nil { return errors.Wrap(err, "failed to close file") } s.hash = fmt.Sprintf("%x", h.Sum(nil)) fmt.Println("Sha'd file", s.hash) return nil }
func (rest *TestAreaREST) TestFailShowAreaNotFound() { t := rest.T() resource.Require(t, resource.Database) svc, ctrl := rest.SecuredController() test.ShowAreaNotFound(t, svc.Context, svc, ctrl, uuid.NewV4().String()) }
func BenchmarkEtcdAdd(b *testing.B) { kon.SetStorage(NewEtcd(nil, kon.Kite.Log)) newKite := func() *protocol.Kite { id := uuid.NewV4() return &protocol.Kite{ Username: "******", Environment: "bench-env", Name: "mathworker", Version: "1.1.1", Region: "bench", Hostname: "bench-host", ID: id.String(), } } value := &kontrolprotocol.RegisterValue{ URL: "http://localhost:4444/kite", } b.ResetTimer() for i := 0; i < b.N; i++ { kon.storage.Add(newKite(), value) } }
// NewUpload creates a new upload object. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) { upload := &Upload{ UUID: gouuid.NewV4().String(), Name: name, } localPath := upload.LocalPath() if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil { return nil, fmt.Errorf("MkdirAll: %v", err) } fw, err := os.Create(localPath) if err != nil { return nil, fmt.Errorf("Create: %v", err) } defer fw.Close() if _, err = fw.Write(buf); err != nil { return nil, fmt.Errorf("Write: %v", err) } else if _, err = io.Copy(fw, file); err != nil { return nil, fmt.Errorf("Copy: %v", err) } if _, err := x.Insert(upload); err != nil { return nil, err } return upload, nil }