Exemplo n.º 1
0
  public static void main(String[] args) {
    ServerRuntime cayenneRuntime =
        new ServerRuntime("cayenne-CESDomain.xml", new CayenneExtrasModule());
    //        ServerRuntime cayenneRuntime = new ServerRuntime("cayenne-CESDomain.xml");
    ObjectContext context = cayenneRuntime.getContext();

    LineItem li = context.newObject(LineItem.class);
    Item i = context.newObject(Item.class);
    CostElement ce1 = context.newObject(CostElement.class);
    CostElement ce2 = context.newObject(CostElement.class);
    CostElement ce3 = context.newObject(CostElement.class);
    BudgetYear by1 = context.newObject(BudgetYear.class);
    BudgetYear by2 = context.newObject(BudgetYear.class);
    BudgetYear by3 = context.newObject(BudgetYear.class);

    li.addToItems(i);
    i.addToCostElements(ce1);
    ce1.addToCostElements(ce2);
    ce2.addToCostElements(ce3);
    ce3.setQuantity(by1);
    ce3.setTotalCost(by2);
    ce3.setUnitCost(by3);
    by1.setLineItem(li);
    by2.setLineItem(li);
    by3.setLineItem(li);

    //        ce2.setItem(i);
    //        ce3.setItem(i);

    context.commitChanges();

    context.deleteObject(li);

    context.commitChanges();
  }
Exemplo n.º 2
0
  public final void validate(T object) {
    ObjectContext workDc = object.getObjectContext(); // .createChildDataContext();
    T obj = (T) workDc.localObject(object.getObjectId(), object);

    Set<DataObject> toDelete = new HashSet<DataObject>();
    try {
      if (!fakes.isEmpty()) {
        // Simulation des fakes
        for (String prop : fakes.keySet()) {
          if (obj.readProperty(prop) != null) continue;
          DataObject value = (DataObject) workDc.newObject(fakes.get(prop));
          obj.setToOneTarget(prop, value, false);
          toDelete.add(value);
        }
      }
      // Validation
      validateImpl(obj);
    } finally {
      // Annulation des modifs
      if (!fakes.isEmpty()) {
        // Suppression des fakes
        for (String prop : fakes.keySet()) {
          DataObject value = (DataObject) obj.readProperty(prop);
          if (!toDelete.contains(value)) continue;
          workDc.deleteObject(value);
        }
      }
    }
    // childDc.rollbackChangesLocally();
  }
  public void testSerializeNestedChannel() throws Exception {

    ObjectContext child = runtime.newContext(context);

    ObjectContext deserializedContext = Util.cloneViaSerialization(child);

    assertNotNull(deserializedContext.getChannel());
    assertNotNull(deserializedContext.getEntityResolver());
  }
  @Test
  public void testCommitLog() throws SQLException {
    Auditable2 a1 = context.newObject(Auditable2.class);
    a1.setCharProperty1("yy");
    a1.setCharProperty2("zz");

    Auditable2 a2 = context.newObject(Auditable2.class);
    a2.setCharProperty1("yy");
    a2.setCharProperty2("zz");
    context.commitChanges();

    List<Object[]> logs = auditLog.selectAll();
    assertEquals(2, logs.size());
  }
  public void test() {
    SelectQuery query = new SelectQuery(Artist.class);
    query.setStatementFetchSize(10);

    assertEquals(10, query.getMetaData(context.getEntityResolver()).getStatementFetchSize());
    context.performQuery(query);

    SQLTemplate template = new SQLTemplate(Artist.class, "SELECT ARTIST_ID FROM ARTIST");
    template.setStatementFetchSize(10);

    assertEquals(10, template.getMetaData(context.getEntityResolver()).getStatementFetchSize());
    context.performQuery(template);

    EJBQLQuery ejbql = new EJBQLQuery("select a from Artist a");
    ejbql.setStatementFetchSize(10);

    assertEquals(10, ejbql.getMetaData(context.getEntityResolver()).getStatementFetchSize());
    context.performQuery(ejbql);

    ObjectId id = new ObjectId("Artist", Artist.ARTIST_ID_PK_COLUMN, 1);
    RelationshipQuery relationshipQuery =
        new RelationshipQuery(id, Artist.PAINTING_ARRAY_PROPERTY, true);
    relationshipQuery.setStatementFetchSize(10);

    assertEquals(
        10, relationshipQuery.getMetaData(context.getEntityResolver()).getStatementFetchSize());
    context.performQuery(relationshipQuery);
  }
  @Test
  public void testEncoder_FilterNoMatch() throws IOException {

    filters.add(
        new EncoderFilter() {

          @Override
          public boolean matches(ClientEntity<?> clientEntity) {
            return false;
          }

          @Override
          public boolean encode(
              String propertyName, Object object, JsonGenerator out, Encoder delegate)
              throws IOException {

            fail("Non matching filter was not supposed to be invoked");
            return false;
          }

          @Override
          public boolean willEncode(String propertyName, Object object, Encoder delegate) {
            fail("Non matching filter was not supposed to be invoked");
            return false;
          }
        });

    ClientEntity<E2> descriptor = getClientEntity(E2.class);
    descriptor.setIdIncluded(true);

    DataResponse<E2> builder = DataResponse.forType(E2.class).withClientEntity(descriptor);
    encoderService.makeEncoder(builder);

    ObjectContext context = cayenneService.newContext();
    E2 e21 = new E2();
    e21.setObjectId(new ObjectId("E2", E2.ID_PK_COLUMN, 7));
    e21.setName("XYZ");
    e21.setAddress("bla bla street");
    context.registerNewObject(e21);

    builder.getEncoder().encode(null, Collections.singletonList(e21), mock(JsonGenerator.class));
  }
  @Test
  public void testGetRootEncoder_ExcludedRelationshipAttributes() throws IOException {
    ClientEntity<E3> e3Descriptor = getClientEntity(E3.class);
    e3Descriptor.setIdIncluded(true);
    e3Descriptor.getAttributes().add(E3.NAME.getName());

    ClientEntity<E2> descriptor = getClientEntity(E2.class);
    descriptor.setIdIncluded(true);
    descriptor.getRelationships().put(E2.E3S.getName(), e3Descriptor);

    ObjectContext context = cayenneService.newContext();
    E2 e2 = new E2();
    e2.setObjectId(new ObjectId("E2", E2.ID_PK_COLUMN, 7));
    e2.setName("XYZ");
    e2.setAddress("bla bla street");
    context.registerNewObject(e2);

    E3 e31 = new E3();
    e31.setObjectId(new ObjectId("E3", E3.ID_PK_COLUMN, 5));
    e31.setName("31");
    e31.setPhoneNumber("+12345678");
    context.registerNewObject(e31);
    e2.addToE3s(e31);

    E3 e32 = new E3();
    e32.setObjectId(new ObjectId("E3", E3.ID_PK_COLUMN, 6));
    e32.setName("32");
    e31.setPhoneNumber("+87654321");
    context.registerNewObject(e32);
    e2.addToE3s(e32);

    DataResponse<E2> builder =
        DataResponse.forType(E2.class)
            .withClientEntity(descriptor)
            .withObjects(Collections.singletonList(e2));
    encoderService.makeEncoder(builder);

    assertEquals(
        "[{\"id\":7,\"e3s\":[{\"id\":5,\"name\":\"31\"},{\"id\":6,\"name\":\"32\"}]}]",
        toJson(builder));
  }
  public void testOrderByPath() throws Exception {
    createTwoArtistsTwoPaintings();

    String ejbql1 = "SELECT p FROM Painting p ORDER BY p.toArtist.artistName ASC";
    EJBQLQuery query1 = new EJBQLQuery(ejbql1);

    List<?> results1 = context.performQuery(query1);
    assertEquals(2, results1.size());

    assertEquals(33005, Cayenne.intPKForObject((Persistent) results1.get(0)));
    assertEquals(33006, Cayenne.intPKForObject((Persistent) results1.get(1)));

    String ejbql2 = "SELECT p FROM Painting p ORDER BY p.toArtist.artistName DESC";
    EJBQLQuery query2 = new EJBQLQuery(ejbql2);

    List<?> results2 = context.performQuery(query2);
    assertEquals(2, results2.size());

    assertEquals(33006, Cayenne.intPKForObject((Persistent) results2.get(0)));
    assertEquals(33005, Cayenne.intPKForObject((Persistent) results2.get(1)));
  }
  public void testOrderByMultiple() throws Exception {
    createFourPaintings();

    String ejbql1 = "SELECT p FROM Painting p ORDER BY p.paintingTitle DESC, p.estimatedPrice DESC";
    EJBQLQuery query1 = new EJBQLQuery(ejbql1);

    List<?> results1 = context.performQuery(query1);
    assertEquals(4, results1.size());

    assertEquals(33003, Cayenne.intPKForObject((Persistent) results1.get(0)));
    assertEquals(33004, Cayenne.intPKForObject((Persistent) results1.get(1)));
    assertEquals(33002, Cayenne.intPKForObject((Persistent) results1.get(2)));
    assertEquals(33001, Cayenne.intPKForObject((Persistent) results1.get(3)));
  }
  public void testOrderByQualified() throws Exception {
    createThreePaintings();

    String ejbql1 =
        "SELECT p FROM Painting p WHERE p.estimatedPrice > 1000 ORDER BY p.paintingTitle ASC";
    EJBQLQuery query1 = new EJBQLQuery(ejbql1);

    List<?> results1 = context.performQuery(query1);
    assertEquals(2, results1.size());

    assertEquals(33001, Cayenne.intPKForObject((Persistent) results1.get(0)));
    assertEquals(33002, Cayenne.intPKForObject((Persistent) results1.get(1)));

    String ejbql2 =
        "SELECT p FROM Painting p WHERE p.estimatedPrice > 1000 ORDER BY p.estimatedPrice ASC";
    EJBQLQuery query2 = new EJBQLQuery(ejbql2);

    List<?> results2 = context.performQuery(query2);
    assertEquals(2, results2.size());

    assertEquals(33002, Cayenne.intPKForObject((Persistent) results2.get(0)));
    assertEquals(33001, Cayenne.intPKForObject((Persistent) results2.get(1)));
  }
  @Test
  public void testOrdering() throws Exception {

    creatArtistsDataSet();

    SelectQuery query = new SelectQuery("Artist");
    query.addOrdering(Artist.ARTIST_NAME_PROPERTY, SortOrder.ASCENDING);

    query.setFetchLimit(4);

    List<?> results = context.performQuery(query);
    assertEquals(4, results.size());

    assertEquals("a", ((Artist) results.get(0)).getArtistName());
    assertEquals("b", ((Artist) results.get(1)).getArtistName());
    assertEquals("c", ((Artist) results.get(2)).getArtistName());
    assertEquals("d", ((Artist) results.get(3)).getArtistName());
  }
Exemplo n.º 12
0
  @Test
  public void testLocalCache() throws Exception {
    createTwoArtists();

    final Artist[] a3 = new Artist[1];

    assertEquals(
        1,
        interceptor.runWithQueryCounter(
            new UnitTestClosure() {

              @Override
              public void execute() {
                a3[0] = SelectById.query(Artist.class, 3).useLocalCache("g1").selectOne(context);
                assertNotNull(a3[0]);
                assertEquals("artist3", a3[0].getArtistName());
              }
            }));

    interceptor.runWithQueriesBlocked(
        new UnitTestClosure() {

          @Override
          public void execute() {
            Artist a3cached =
                SelectById.query(Artist.class, 3).useLocalCache("g1").selectOne(context);
            assertSame(a3[0], a3cached);
          }
        });

    context.performGenericQuery(new RefreshQuery("g1"));

    assertEquals(
        1,
        interceptor.runWithQueryCounter(
            new UnitTestClosure() {

              @Override
              public void execute() {
                SelectById.query(Artist.class, 3).useLocalCache("g1").selectOne(context);
              }
            }));
  }
Exemplo n.º 13
0
  GraphDiff onSyncNoFilters(
      final ObjectContext originatingContext, final GraphDiff changes, int syncType) {
    DataChannelSyncCallbackAction callbackAction =
        DataChannelSyncCallbackAction.getCallbackAction(
            getEntityResolver().getCallbackRegistry(),
            originatingContext.getGraphManager(),
            changes,
            syncType);

    callbackAction.applyPreCommit();

    GraphDiff result;
    switch (syncType) {
      case DataChannel.ROLLBACK_CASCADE_SYNC:
        result = onSyncRollback(originatingContext);
        break;
        // "cascade" and "no_cascade" are the same from the DataDomain
        // perspective,
        // including transaction handling logic
      case DataChannel.FLUSH_NOCASCADE_SYNC:
      case DataChannel.FLUSH_CASCADE_SYNC:
        result =
            (GraphDiff)
                runInTransaction(
                    new Transformer() {

                      public Object transform(Object input) {
                        return onSyncFlush(originatingContext, changes);
                      }
                    });
        break;
      default:
        throw new CayenneRuntimeException("Invalid synchronization type: " + syncType);
    }

    callbackAction.applyPostCommit();
    return result;
  }
  @Test
  public void testEncoder_FilteredToOne() throws IOException {

    filters.add(
        new EncoderFilter() {

          @Override
          public boolean matches(ClientEntity<?> clientEntity) {
            return true;
          }

          @Override
          public boolean encode(
              String propertyName, Object object, JsonGenerator out, Encoder delegate)
              throws IOException {

            if (object instanceof E2) {
              E2 e2 = (E2) object;
              if (Cayenne.intPKForObject(e2) == 7) {
                return delegate.encode(propertyName, object, out);
              } else {
                return false;
              }
            } else {
              delegate.encode(propertyName, object, out);
              return true;
            }
          }

          @Override
          public boolean willEncode(String propertyName, Object object, Encoder delegate) {
            if (object instanceof E2) {
              E2 e2 = (E2) object;
              if (Cayenne.intPKForObject(e2) == 7) {
                return delegate.willEncode(propertyName, object);
              } else {
                return false;
              }
            } else {
              return delegate.willEncode(propertyName, object);
            }
          }
        });

    ClientEntity<E2> e2Descriptor = getClientEntity(E2.class);
    e2Descriptor.setIdIncluded(true);

    ClientEntity<E3> e3Descriptor = getClientEntity(E3.class);
    e3Descriptor.setIdIncluded(true);
    e3Descriptor.getRelationships().put(E3.E2.getName(), e2Descriptor);

    ObjectContext context = cayenneService.newContext();

    E2 e21 = new E2();
    e21.setObjectId(new ObjectId("E2", E2.ID_PK_COLUMN, 7));
    context.registerNewObject(e21);

    E3 e31 = new E3();
    e31.setObjectId(new ObjectId("E3", E3.ID_PK_COLUMN, 5));
    context.registerNewObject(e31);
    e31.setE2(e21);

    DataResponse<E3> builder =
        DataResponse.forType(E3.class).withClientEntity(e3Descriptor).withObject(e31);

    encoderService.makeEncoder(builder);

    assertEquals("[{\"id\":5,\"e2\":{\"id\":7},\"e2_id\":7}]", toJson(builder));

    E2 e22 = new E2();
    e22.setObjectId(new ObjectId("E2", E2.ID_PK_COLUMN, 8));
    context.registerNewObject(e22);

    E3 e32 = new E3();
    e32.setObjectId(new ObjectId("E3", E3.ID_PK_COLUMN, 6));
    context.registerNewObject(e32);
    e32.setE2(e22);

    builder.withObject(e32);

    assertEquals("[{\"id\":6}]", toJson(builder));
  }
  @Test
  public void testEncoder_FilteredRoots() throws IOException {

    filters.add(
        new EncoderFilter() {

          @Override
          public boolean matches(ClientEntity<?> clientEntity) {
            return true;
          }

          @Override
          public boolean encode(
              String propertyName, Object object, JsonGenerator out, Encoder delegate)
              throws IOException {

            E2 e2 = (E2) object;
            if (Cayenne.intPKForObject(e2) == 7) {
              delegate.encode(propertyName, object, out);
              return true;
            }

            return false;
          }

          @Override
          public boolean willEncode(String propertyName, Object object, Encoder delegate) {
            E2 e2 = (E2) object;
            if (Cayenne.intPKForObject(e2) == 7) {
              delegate.willEncode(propertyName, object);
              return true;
            }

            return false;
          }
        });

    ClientEntity<E2> descriptor = getClientEntity(E2.class);
    descriptor.setIdIncluded(true);

    ObjectContext context = cayenneService.newContext();
    E2 e21 = new E2();
    e21.setObjectId(new ObjectId("E2", E2.ID_PK_COLUMN, 7));
    e21.setName("XYZ");
    e21.setAddress("bla bla street");
    context.registerNewObject(e21);

    DataResponse<E2> builder =
        DataResponse.forType(E2.class).withClientEntity(descriptor).withObject(e21);

    encoderService.makeEncoder(builder);
    assertEquals("[{\"id\":7}]", toJson(builder));

    E2 e22 = new E2();
    e22.setObjectId(new ObjectId("E2", E2.ID_PK_COLUMN, 8));
    e22.setName("XYZ");
    e22.setAddress("bla bla street");
    context.registerNewObject(e22);

    builder.withObject(e22);
    encoderService.makeEncoder(builder);

    assertEquals("[]", toJson(builder));
  }
  /**
   * Create a new {@link EntryType} instance using the specified {@link ObjectContext}.
   *
   * @param context
   * @return Instance of EntryType attached to a valid {@link ObjectContext}
   */
  private EntryType create(ObjectContext context) {

    EntryType entryType = context.newObject(EntryType.class);
    return entryType;
  }