@Test
  public void RawSqlParentLoad() {
    List<Data> exampleData = new ArrayList<>();
    exampleData.add(new Data(0));
    exampleData.add(new Data(1));
    exampleData.add(new Data(2));

    ChildA a = new ChildA(0);
    a.setData(exampleData);
    Ebean.save(a);

    ChildB b = new ChildB(1);
    b.setData(exampleData);
    Ebean.save(b);

    ChildA c = new ChildA(2);
    c.setData(exampleData);
    Ebean.save(c);

    RawSql rawSql =
        RawSqlBuilder.parse("select type, id, number from parent where number > 1").create();
    List<Parent> partial = Ebean.find(Parent.class).setRawSql(rawSql).findList();
    assertNotNull(partial.get(0).getData());
    assertEquals(partial.get(0).getData().get(0).getNumber().intValue(), 0);
  }
Esempio n. 2
0
  public void testNoIdQuery() {

    Update<NoIdEntity> upd = Ebean.createUpdate(NoIdEntity.class, "delete from NoIdEntity");
    upd.execute();

    NoIdEntity e0 = new NoIdEntity();
    e0.setId(1);
    e0.setValue("one");

    NoIdEntity e1 = new NoIdEntity();
    e1.setId(2);
    e1.setValue("two");

    Ebean.save(e0);
    Ebean.save(e1);

    List<NoIdEntity> list = Ebean.createNamedQuery(NoIdEntity.class, "noid").findList();

    Assert.assertEquals(2, list.size());
    NoIdEntity noIdEntity0 = list.get(0);
    Assert.assertNotNull(noIdEntity0);
    Assert.assertEquals(noIdEntity0.getValue(), "one");

    NoIdEntity noIdEntity1 = list.get(1);
    Assert.assertNotNull(noIdEntity1);
    Assert.assertEquals(noIdEntity1.getValue(), "two");
  }
  public void test() {

    TSMaster m0 = new TSMaster();
    m0.setName("m1");

    m0.addDetail(new TSDetail("m1 detail 1"));
    m0.addDetail(new TSDetail("m1 detail 2"));

    Ebean.save(m0);

    TSMaster master = Ebean.find(TSMaster.class, m0.getId());
    List<TSDetail> details = master.getDetails();

    TSDetail removedDetail = details.remove(1);

    BeanCollection<?> bc = (BeanCollection<?>) details;
    Set<?> modifyRemovals = bc.getModifyRemovals();

    Assert.assertNotNull(modifyRemovals);
    Assert.assertTrue(modifyRemovals.size() == 1);
    Assert.assertTrue(modifyRemovals.contains(removedDetail));

    Ebean.save(master);

    TSMaster masterReload = Ebean.find(TSMaster.class, m0.getId());
    List<TSDetail> detailsReload = masterReload.getDetails();

    // the removed bean has really been removed
    Assert.assertTrue(detailsReload.size() == 1);

    TSMaster master3 = Ebean.find(TSMaster.class, m0.getId());
    List<TSDetail> details3 = master3.getDetails();
    details3.clear();
  }
  @Test
  public void testQuery() {

    Car car = new Car();
    car.setLicenseNumber("MARIOS_CAR_LICENSE");
    Ebean.save(car);

    VehicleDriver driver = new VehicleDriver();
    driver.setName("Mario");
    driver.setVehicle(car);
    Ebean.save(driver);

    Query<VehicleDriver> query = Ebean.find(VehicleDriver.class);
    query.where().eq("vehicle.licenseNumber", "MARIOS_CAR_LICENSE");
    List<VehicleDriver> drivers = query.findList();

    Assert.assertNotNull(drivers);
    Assert.assertEquals(1, drivers.size());
    Assert.assertNotNull(drivers.get(0));

    Assert.assertEquals("Mario", drivers.get(0).getName());
    Assert.assertEquals("MARIOS_CAR_LICENSE", drivers.get(0).getVehicle().getLicenseNumber());

    Vehicle car2 = Ebean.find(Vehicle.class, car.getId());

    car2.setLicenseNumber("test");
    Ebean.save(car);
  }
Esempio n. 5
0
 @Override
 public void onStart(Application app) {
   // Check if the database is empty
   if (User.finder.findRowCount() == 0) {
     Map<String, List<Object>> all = (Map<String, List<Object>>) Yaml.load("initial-data.yml");
     Ebean.save(all.get("users"));
     Ebean.save(all.get("projects"));
     Ebean.save(all.get("tasks"));
   }
 }
  @Test
  public void testInsert() {

    SomePeriodBean bean = new SomePeriodBean();
    bean.setPeriod(Period.of(3, 4, 5));
    bean.setAnniversary(MonthDay.of(4, 29));
    Ebean.save(bean);

    SomePeriodBean bean1 = Ebean.find(SomePeriodBean.class, bean.getId());
    assertEquals(bean.getPeriod(), bean1.getPeriod());
    assertEquals(bean.getAnniversary(), bean1.getAnniversary());

    // insert fetch null value
    SomePeriodBean bean2 = new SomePeriodBean();
    Ebean.save(bean2);

    SomePeriodBean bean3 = Ebean.find(SomePeriodBean.class, bean2.getId());
    assertNull(bean3.getPeriod());
    assertNull(bean3.getAnniversary());

    List<SomePeriodBean> anniversaryList =
        Ebean.find(SomePeriodBean.class)
            .where()
            .eq("anniversary", MonthDay.of(4, 29))
            .eq("period_years", 3)
            .eq("period_months", 4)
            .findList();

    assertEquals(1, anniversaryList.size());

    // must use year 2000 for range predicates
    // ... using 2001 here so not finding anything
    anniversaryList =
        Ebean.find(SomePeriodBean.class)
            .where()
            .gt("anniversary", Date.valueOf(LocalDate.of(2001, 4, 29)))
            .findList();

    assertEquals(0, anniversaryList.size());

    // can use year 2000 for range predicates
    // ... and can use LocalDate to bind
    anniversaryList =
        Ebean.find(SomePeriodBean.class)
            .where()
            .gt("anniversary", LocalDate.of(2000, 4, 22))
            .findList();

    assertEquals(1, anniversaryList.size());

    Ebean.delete(bean);
    Ebean.delete(bean2);
  }
  @Transactional
  public void doSomething(EBasicVer v) {

    EbeanServer server = Ebean.getServer(null);

    inMethodTransaction = server.currentTransaction();

    Transaction t = server.createTransaction();
    SqlUpdate u =
        server.createSqlUpdate("update e_basicver set last_update = last_update+1 where id = ?");
    u.setParameter(1, v.getId());
    int count = server.execute(u, t);
    Assert.assertEquals(1, count);

    t.commit();

    v.setName("some change");
    try {
      Ebean.save(v);
      // never get here
      Assert.assertTrue(false);
    } catch (PersistenceException e) {
      throw e;
    }
  }
  @AccessLevel(level = 2)
  public Result create() {
    Form<ActivityChoice> choiceForm = Form.form(ActivityChoice.class).bindFromRequest();

    if (choiceForm.hasErrors()) {
      return status(
          ErrDefinition.E_ACTIVITY_CHOICE_FORM_HASERROR, Messages.get("activitychoice.failure"));
    }

    try {
      ActivityChoice choice = choiceForm.get();

      choice.id = CodeGenerator.GenerateUUId();

      choice.content = new ActivityContent();
      choice.content.id = choice.id;

      Ebean.save(choice);

      return ok(Json.toJson(choice));
    } catch (Throwable e) {
      return status(
          ErrDefinition.E_ACTIVITY_CHOICE_CREATE_FAILED, Messages.get("activitychoice.failure"));
    }
  }
Esempio n. 9
0
  public static Result loadData() {
    @SuppressWarnings("unchecked")
    Map<String, List<Object>> all = (Map<String, List<Object>>) Yaml.load("initial-data.yml");

    // Insert books first
    Ebean.save(all.get("books"));

    Ebean.save(all.get("chapters"));

    // Insert paragraphs
    Ebean.save(all.get("paragraphs"));

    // Insert sentences
    Ebean.save(all.get("sentences"));

    return ok("");
  }
  @Test
  public void test() {

    Ebean.createUpdate(Permission.class, "delete from Permission").execute();
    Ebean.createUpdate(Tenant.class, "delete from Tenant").execute();
    Ebean.createUpdate(Role.class, "delete from Role").execute();

    Tenant t = new Tenant("tenant");

    Ebean.save(t);

    Permission p1 = new Permission("p1");
    Permission p2 = new Permission("p2");

    Ebean.save(p1);
    Ebean.save(p2);

    Role role1 = new Role("role");
    role1.setTenant(t);

    Set<Permission> permissions = new HashSet<Permission>();
    List<Permission> permsList = Ebean.find(Permission.class).findList();
    permissions.addAll(permsList);

    role1.setPermissions(permissions);

    Ebean.save(role1);

    List<Tenant> tenantList = Ebean.find(Tenant.class).fetch("roles").findList();
    List<Role> roleList = Ebean.find(Role.class).fetch("permissions").findList();
    List<Permission> permissionList = Ebean.find(Permission.class).fetch("roles").findList();

    Assert.assertEquals(1, tenantList.size());
    Assert.assertEquals(2, permissionList.size());
    Assert.assertEquals(1, roleList.size());

    Ebean.delete(role1);

    List<Tenant> tenantList2 = Ebean.find(Tenant.class).fetch("roles").findList();
    List<Role> roleList2 = Ebean.find(Role.class).fetch("permissions").findList();
    List<Permission> permissionList2 = Ebean.find(Permission.class).fetch("roles").findList();

    Assert.assertEquals(0, roleList2.size());
    Assert.assertEquals(1, tenantList2.size());
    Assert.assertEquals(2, permissionList2.size());
  }
Esempio n. 11
0
 public static Result save() {
   Form<FastSubject> fastSubjectForm = Form.form(FastSubject.class).bindFromRequest();
   FastSubject fastSubject = fastSubjectForm.get();
   if (fastSubject.id == null) Ebean.save(fastSubject);
   else Ebean.update(fastSubject);
   FlashMessage.updateSuccess.send();
   return redirect(routes.FastSubjects.edit(fastSubject.id));
 }
 @Test
 public void testGetExpressionCountWithMultipleExpr() throws IOException {
   Assert.assertEquals(0, exprRepo.getExpressionCount(Organization.DEFAULT));
   try (Transaction transaction = Ebean.beginTransaction()) {
     final models.ebean.Expression ebeanExpression1 = TestBeanFactory.createEbeanExpression();
     ebeanExpression1.setUuid(UUID.randomUUID());
     ebeanExpression1.setOrganization(
         models.ebean.Organization.findByOrganization(Organization.DEFAULT));
     Ebean.save(ebeanExpression1);
     final models.ebean.Expression ebeanExpression2 = TestBeanFactory.createEbeanExpression();
     ebeanExpression2.setUuid(UUID.randomUUID());
     ebeanExpression2.setOrganization(
         models.ebean.Organization.findByOrganization(Organization.DEFAULT));
     Ebean.save(ebeanExpression2);
     transaction.commit();
   }
   Assert.assertEquals(2, exprRepo.getExpressionCount(Organization.DEFAULT));
 }
  @Test
  public void test() {

    TWithPreInsert e = new TWithPreInsert();
    e.setTitle("Mister");
    // the perInsert should populate the
    // name with should not be null
    Ebean.save(e);

    // the save worked and name set in preInsert
    Assert.assertNotNull(e.getId());
    Assert.assertNotNull(e.getName());

    TWithPreInsert e1 = Ebean.find(TWithPreInsert.class, e.getId());

    e1.setTitle("Missus");
    Ebean.save(e1);
  }
Esempio n. 14
0
  public void merge(final User otherUser) {
    for (final LinkedAccount acc : otherUser.linkedAccounts) {
      this.linkedAccounts.add(LinkedAccount.create(acc));
    }
    // do all other merging stuff here - like resources, etc.

    // deactivate the merged user that got added to this one
    otherUser.active = false;
    Ebean.save(Arrays.asList(new User[] {otherUser, this}));
  }
  @Test
  public void test_deleteCascading() {

    Permission p1 = new Permission("p1");
    Permission p2 = new Permission("p2");
    Ebean.save(p1);
    Ebean.save(p2);

    Role role1 = new Role("role");

    Set<Permission> permissions = new HashSet<Permission>();
    permissions.add(p2);
    role1.setPermissions(permissions);
    Ebean.save(role1);

    // only deletes as not associated
    Ebean.delete(p1);
    // delete cascades
    Ebean.delete(role1);
  }
Esempio n. 16
0
  @Test
  public void testCasting() {

    Truck t = new Truck();
    t.setCapacity(10d);
    Ebean.save(t);

    Vehicle v = Ebean.find(Vehicle.class, t.getId());
    if (v instanceof Truck) {
      Truck t0 = (Truck) v;
      Assert.assertEquals(Double.valueOf(10d), t0.getCapacity());
      Assert.assertEquals(Double.valueOf(10d), ((Truck) v).getCapacity());
      Assert.assertNotNull(t0.getId());
    } else {
      Assert.assertTrue("v not a Truck?", false);
    }

    VehicleDriver driver = new VehicleDriver();
    driver.setName("Jim");
    driver.setVehicle(v);

    Ebean.save(driver);

    VehicleDriver d1 = Ebean.find(VehicleDriver.class, driver.getId());
    v = d1.getVehicle();
    if (v instanceof Truck) {
      Double capacity = ((Truck) v).getCapacity();
      Assert.assertEquals(Double.valueOf(10d), capacity);
      Assert.assertNotNull(v.getId());
    } else {
      Assert.assertTrue("v not a Truck?", false);
    }

    List<VehicleDriver> list = Ebean.find(VehicleDriver.class).findList();
    for (VehicleDriver vehicleDriver : list) {
      if (vehicleDriver.getVehicle() instanceof Truck) {
        Double capacity = ((Truck) vehicleDriver.getVehicle()).getCapacity();
        Assert.assertEquals(Double.valueOf(10d), capacity);
      }
    }
  }
  @Test
  public void test() {

    LoggedSqlCollector.start();
    Transaction txn = Ebean.beginTransaction();
    try {
      txn.setBatch(PersistBatch.ALL);

      EdParent parent = new EdParent();
      parent.setName("MyComputer");

      EdChild child = new EdChild();
      child.setName("Harddisk 123");
      child.setParent(parent);
      ArrayList<EdChild> children = new ArrayList<EdChild>();
      children.add(child);
      parent.setChildren(children);

      Ebean.save(parent);

      // nothing flushed yet
      List<String> loggedSql0 = LoggedSqlCollector.start();
      assertEquals(0, loggedSql0.size());

      parent.setName("MyDesk");
      Ebean.save(parent);

      // nothing flushed yet
      assertEquals(0, LoggedSqlCollector.start().size());

      Ebean.commitTransaction();

      // insert statements for EdExtendedParent
      List<String> loggedSql2 = LoggedSqlCollector.start();
      assertEquals(2, loggedSql2.size());

    } finally {
      Ebean.endTransaction();
    }
  }
Esempio n. 18
0
    public static void insert(Application app) {
      if (Ebean.find(User.class).findRowCount() == 0) {

        Map<String, List<Object>> all = (Map<String, List<Object>>) Yaml.load("initial-data.yml");

        // Insert users first
        Ebean.save(all.get("users"));

        // Insert tapps
        Ebean.save(all.get("apps"));

        //                // Insert projects
        //                Ebean.save(all.get("projects"));
        //                for(Object project: all.get("projects")) {
        //                    // Insert the project/user relation
        //                    Ebean.saveManyToManyAssociations(project, "members");
        //                }
        //
        //

      }
    }
  @Test
  public void testInsertUpdateDelete() throws IOException {

    String s0 =
        "{\"docId\":18,\"contentId\":\"asd\",\"active\":true,\"contentType\":\"pg-hello\",\"content\":{\"name\":\"rob\",\"age\":45}}";

    Map<String, Object> content = EJson.parseObject(s0);

    EBasicJsonMapJsonB bean = new EBasicJsonMapJsonB();
    bean.setName("one");
    bean.setContent(content);

    Ebean.save(bean);

    EBasicJsonMapJsonB bean1 = Ebean.find(EBasicJsonMapJsonB.class, bean.getId());

    assertEquals(bean.getId(), bean1.getId());
    assertEquals(bean.getName(), bean1.getName());
    assertEquals(bean.getContent().get("contentType"), bean1.getContent().get("contentType"));
    assertEquals(18L, bean1.getContent().get("docId"));

    bean1.setName("just change name");
    Ebean.save(bean1);
  }
  @Test
  public void RawSqlParentFetch() {
    List<Data> exampleData = new ArrayList<>();
    exampleData.add(new Data(0));
    exampleData.add(new Data(1));
    exampleData.add(new Data(2));

    ChildA a = new ChildA(0);
    a.setData(exampleData);
    Ebean.save(a);

    ChildB b = new ChildB(1);
    b.setData(exampleData);
    Ebean.save(b);

    ChildA c = new ChildA(2);
    c.setData(exampleData);
    Ebean.save(c);

    RawSql rawSql =
        RawSqlBuilder.unparsed("select type, id from parent where number > 1")
            .columnMappingIgnore("type")
            .columnMapping("id", "parent.id")
            .create();
    List<ParentAggregate> aggregates =
        Ebean.find(ParentAggregate.class)
            .setRawSql(rawSql)
            .fetch("parent", new FetchConfig().query())
            .findList();
    List<Parent> partial = new ArrayList<>();
    for (ParentAggregate aggregate : aggregates) {
      partial.add(aggregate.parent);
    }
    assertNotNull(partial.get(0).getData());
    assertEquals(partial.get(0).getData().get(0).getNumber().intValue(), 0);
  }
  @Test
  public void testStatelessUpdate() {

    TWithPreInsert e = new TWithPreInsert();
    e.setName("BeanForUpdateTest");
    Ebean.save(e);

    TWithPreInsert bean2 = new TWithPreInsert();
    bean2.setId(e.getId());
    bean2.setName("stateless-update-name");
    bean2.setTitle(null);

    Ebean.update(bean2);

    // title set on preUpdate
    Assert.assertNotNull(bean2.getTitle());
  }
  @Test
  public void testGetForValidId() throws IOException {
    final UUID uuid = UUID.randomUUID();
    Assert.assertFalse(exprRepo.get(uuid, Organization.DEFAULT).isPresent());
    final models.ebean.Expression ebeanExpression = TestBeanFactory.createEbeanExpression();
    ebeanExpression.setUuid(uuid);
    ebeanExpression.setOrganization(
        models.ebean.Organization.findByOrganization(Organization.DEFAULT));
    try (Transaction transaction = Ebean.beginTransaction()) {
      Ebean.save(ebeanExpression);
      transaction.commit();
    }

    final Optional<Expression> expected = exprRepo.get(uuid, Organization.DEFAULT);
    Assert.assertTrue(expected.isPresent());
    Assert.assertTrue(isExpressionEbeanEquivalent(expected.get(), ebeanExpression));
  }
 @Test
 public void addOrUpdateExpressionUpdateCase() throws IOException {
   final UUID uuid = UUID.randomUUID();
   final models.ebean.Organization organization;
   try (Transaction transaction = Ebean.beginTransaction()) {
     final models.ebean.Expression ebeanExpression = TestBeanFactory.createEbeanExpression();
     ebeanExpression.setUuid(uuid);
     organization = ebeanExpression.getOrganization();
     Ebean.save(ebeanExpression);
     transaction.commit();
   }
   final Expression actual =
       TestBeanFactory.createExpressionBuilder().setId(uuid).setCluster("new-cluster").build();
   exprRepo.addOrUpdateExpression(actual, TestBeanFactory.organizationFrom(organization));
   final Expression expected =
       exprRepo.get(uuid, TestBeanFactory.organizationFrom(organization)).get();
   Assert.assertEquals(expected, actual);
 }
  @Test
  public void test() {

    PFile persistentFile = new PFile("test.txt", new PFileContent("test".getBytes()));

    Ebean.save(persistentFile);
    Integer id = persistentFile.getId();
    Integer contentId = persistentFile.getFileContent().getId();

    PFile partialPfile =
        Ebean.find(PFile.class).select("id").where().idEq(persistentFile.getId()).findUnique();

    // should delete file and fileContent
    Ebean.delete(partialPfile);
    System.out.println("finished delete");

    PFile file1 = Ebean.find(PFile.class, id);
    PFileContent content1 = Ebean.find(PFileContent.class, contentId);

    Assert.assertNull(file1);
    Assert.assertNull(content1);
  }
Esempio n. 25
0
  public Result create() {
    Logger.info("enter create");
    Form<ShakeRecord> shakeForm = Form.form(ShakeRecord.class).bindFromRequest();

    if (shakeForm.hasErrors()) {
      Logger.info("form has error");
      return status(ErrDefinition.E_SHAKE_RECORD_FORM_ERROR, Messages.get("shakerecord.failure"));
    }
    DynamicForm form = Form.form().bindFromRequest();

    String userId = form.get("userId");
    String appId = form.get("appId");

    if (null == userId) {
      Logger.info("userId is null");
      return status(ErrDefinition.E_SHAKE_RECORD_CREATE_ERROR, Messages.get("shakerecord.failure"));
    }

    try {
      ShakeRecord shakeRecord = shakeForm.get();

      shakeRecord.id = CodeGenerator.GenerateUUId();
      shakeRecord.shop = Shop.find.byId(shakeRecord.shop_id);
      shakeRecord.account = Account.find.byId(userId);

      shakeRecord.create_time = new Date();

      Ebean.save(shakeRecord);

      Logger.info("save it");
      return ok(Json.toJson(shakeRecord));
    } catch (Throwable e) {
      Logger.info("cannot save");
      Logger.info(e.getMessage());
      return status(ErrDefinition.E_SHAKE_RECORD_CREATE_ERROR, Messages.get("shakerecord.failure"));
    }
  }
Esempio n. 26
0
 @Override
 public void onStart(Application application) {
   if (User.find.findRowCount() == 0) {
     Ebean.save((List) Yaml.load("initial-data.yml"));
   }
 }
Esempio n. 27
0
 public static void create(Official official, ProcessingType processingType) {
   if (processingType.equals(ProcessingType.batch)) ebeanServer.save(official);
   else if (processingType.equals(ProcessingType.online)) Ebean.save(official);
 }
Esempio n. 28
0
  /**
   * Save past race
   *
   * @return
   */
  public static Result save() {
    Form<PastRaceForm> form = form(PastRaceForm.class).bindFromRequest();
    // Is this an update or a creation?
    PastRace pastRace = null;
    boolean isnew = false;
    String raceId = form.field("id").value();
    if (!StringUtils.isEmpty(raceId)) {
      try {
        pastRace = PastRace.find.byId(Long.valueOf(raceId));
      } catch (NumberFormatException n) {
      }
      if (pastRace == null || !pastRace.user.equals(getConnectedUser())) {
        Logger.error("Past race save forbidden");
        return forbidden();
      }
    } else {
      isnew = true;
      pastRace = new PastRace();
      pastRace.dateCreation = new Date();
    }

    // Check date format
    Date date = null;
    if (form.error("date") == null) {
      DateFormat df = new SimpleDateFormat(Messages.get("general.dateformat"));
      try {
        date = df.parse(form.field("date").value());
      } catch (ParseException p) {
        form.reject("date", "general.error.dateformat");
      }
    }

    // Check time
    String hours = form.field("hours").value();
    String minutes = form.field("minutes").value();
    String seconds = form.field("seconds").value();
    if (StringUtils.isEmpty(hours)
        || StringUtils.isEmpty(minutes)
        || StringUtils.isEmpty(seconds)) {
      form.reject("time", "general.error.multiple");
    }

    int timeInSeconds = 0;
    try {
      timeInSeconds += Integer.parseInt(hours) * 3600;
      timeInSeconds += Integer.parseInt(minutes) * 60;
      timeInSeconds += Integer.parseInt(seconds);
    } catch (NumberFormatException n) {
      form.reject("time", "pastrace.error.time");
    }

    if (form.hasErrors()) {
      return badRequest(views.html.user.pastRace.render(form, isnew));
    } else {
      // Save past race
      pastRace.name = form.field("name").value();
      pastRace.date = date;
      pastRace.user = Application.getConnectedUser();
      pastRace.distance = form.field("distance").value();
      pastRace.time = timeInSeconds;
      Ebean.save(pastRace);

      // Redirect to user homepage
      return redirect(
          controllers.user.routes.UserController.index(Application.getConnectedUser().username));
    }
  }
 @Before
 public void setUp() {
   start(fakeApplication(inMemoryDatabase(), fakeGlobal()));
   Ebean.save((List) Yaml.load("test-data.yml"));
 }
Esempio n. 30
0
 @Transactional
 public MethodCallMap save() {
   Ebean.save(this);
   return this;
 }