示例#1
0
  public void execute() throws MojoExecutionException, MojoFailureException {

    Log logger = new MavenLogger(this);

    DbImportConfiguration config = toParameters();
    config.setLogger(logger);
    Injector injector = DIBootstrap.createInjector(new ToolsModule(logger), new DbImportModule());

    validateDbImportConfiguration(config, injector);

    try {
      injector.getInstance(DbImportAction.class).execute(config);
    } catch (Exception ex) {
      Throwable th = Util.unwindException(ex);

      String message = "Error importing database schema";

      if (th.getLocalizedMessage() != null) {
        message += ": " + th.getLocalizedMessage();
      }

      getLog().error(message);
      throw new MojoExecutionException(message, th);
    }
  }
示例#2
0
    @Override
    boolean objectsAreEqual(Object object, Object objectInTheList) {
      if (object == null && objectInTheList == null) {
        return true;
      }

      if (object != null && objectInTheList != null) {

        Map<?, ?> id = (Map<?, ?>) objectInTheList;
        Map<?, ?> map = (Map<?, ?>) object;

        if (id.size() != map.size()) {
          return false;
        }

        // id must be a subset of this map
        for (Map.Entry<?, ?> entry : id.entrySet()) {
          Object key = entry.getKey();
          Object value = entry.getValue();
          if (!Util.nullSafeEquals(value, map.get(key))) {
            return false;
          }
        }

        return true;
      }

      return false;
    }
  /** Initializes Query name from string. */
  void setQueryName(String newName) {
    if (newName != null && newName.trim().length() == 0) {
      newName = null;
    }

    AbstractQuery query = getQuery();

    if (query == null) {
      return;
    }

    if (Util.nullSafeEquals(newName, query.getName())) {
      return;
    }

    if (newName == null) {
      throw new ValidationException("SelectQuery name is required.");
    }

    DataMap map = mediator.getCurrentDataMap();
    Query matchingQuery = map.getQuery(newName);

    if (matchingQuery == null) {
      // completely new name, set new name for entity
      QueryEvent e = new QueryEvent(this, query, query.getName());
      ProjectUtil.setQueryName(map, query, newName);
      mediator.fireQueryEvent(e);
    } else if (matchingQuery != query) {
      // there is a query with the same name
      throw new ValidationException(
          "There is another query named '" + newName + "'. Use a different name.");
    }
  }
  public void testSerializeResolver() throws Exception {

    DataContext deserializedContext = Util.cloneViaSerialization(context);

    assertNotNull(deserializedContext.getEntityResolver());
    assertSame(context.getEntityResolver(), deserializedContext.getEntityResolver());
  }
  public void testSerializeChannel() throws Exception {

    DataContext deserializedContext = Util.cloneViaSerialization(context);

    assertNotNull(deserializedContext.getChannel());
    assertSame(context.getChannel(), deserializedContext.getChannel());
  }
  public void testSerializeCommitted() throws Exception {

    Artist artist = (Artist) context.newObject("Artist");
    artist.setArtistName("artist1");
    assertNotNull(artist.getObjectId());
    context.commitChanges();

    DataContext deserializedContext = Util.cloneViaSerialization(context);

    assertSame(context.getParentDataDomain(), deserializedContext.getParentDataDomain());

    // there should be only one object registered
    Artist deserializedArtist =
        (Artist) deserializedContext.getObjectStore().getObjectIterator().next();

    assertNotNull(deserializedArtist);

    // deserialized as hollow...
    assertEquals(PersistenceState.HOLLOW, deserializedArtist.getPersistenceState());
    assertFalse(deserializedArtist.getObjectId().isTemporary());
    assertEquals("artist1", deserializedArtist.getArtistName());
    assertSame(deserializedContext, deserializedArtist.getObjectContext());

    // test that to-many relationships are initialized
    List<?> paintings = deserializedArtist.getPaintingArray();
    assertNotNull(paintings);
    assertEquals(0, paintings.size());
  }
  /**
   * Method to create and check an expression
   *
   * @param text String to be converted as Expression
   * @return Expression if a new expression was created, null otherwise.
   * @throws ValidationException if <code>text</code> can't be converted
   */
  Expression createQualifier(String text) throws ValidationException {
    SelectQuery query = getQuery();
    if (query == null) {
      return null;
    }

    ExpressionConvertor convertor = new ExpressionConvertor();
    try {
      String oldQualifier = convertor.valueAsString(query.getQualifier());
      if (!Util.nullSafeEquals(oldQualifier, text)) {
        Expression exp = (Expression) convertor.stringAsValue(text);

        /** Advanced checking. See CAY-888 #1 */
        if (query.getRoot() instanceof Entity) {
          checkExpression((Entity) query.getRoot(), exp);
        }

        return exp;
      }

      return null;
    } catch (IllegalArgumentException ex) {
      // unparsable qualifier
      throw new ValidationException(ex.getMessage());
    }
  }
  public void testSerializeNestedChannel() throws Exception {

    ObjectContext child = runtime.newContext(context);

    ObjectContext deserializedContext = Util.cloneViaSerialization(child);

    assertNotNull(deserializedContext.getChannel());
    assertNotNull(deserializedContext.getEntityResolver());
  }
示例#9
0
  /**
   * Returns Java class of persistent objects described by this entity. For generic entities with no
   * class specified explicitly, default DataMap superclass is used, and if it is not set -
   * CayenneDataObject is used. Casts any thrown exceptions into CayenneRuntimeException.
   *
   * @since 1.2
   * @deprecated since 4.0 this method based on statically defined class loading algorithm is not
   *     going to work in environments like OSGi. {@link AdhocObjectFactory} should be used as it
   *     can provide the environment-specific class loading policy.
   */
  @Deprecated
  public Class<?> getJavaClass() {
    String name = getJavaClassName();

    try {
      return Util.getJavaClass(name);
    } catch (ClassNotFoundException e) {
      throw new CayenneRuntimeException(
          "Failed to doLoad class " + name + ": " + e.getMessage(), e);
    }
  }
示例#10
0
  /** @deprecated since 4.0 as class loading should not happen here. */
  @Deprecated
  public PasswordEncoding getPasswordEncoder() {
    try {
      return (PasswordEncoding) Util.getJavaClass(getPasswordEncoderClass()).newInstance();
    } catch (InstantiationException e) {; // Swallow it -- no need to throw/etc.
    } catch (IllegalAccessException e) {; // Swallow it -- no need to throw/etc.
    } catch (ClassNotFoundException e) {; // Swallow it -- no need to throw/etc.
    } catch (DIRuntimeException e) {; // Swallow it -- no need to throw/etc.
    }

    logger.error("Failed to obtain specified Password Encoder '" + getPasswordEncoderClass() + "'");
    return null;
  }
  public void testSerializeNew() throws Exception {

    Artist artist = (Artist) context.newObject("Artist");
    artist.setArtistName("artist1");
    assertNotNull(artist.getObjectId());

    DataContext deserializedContext = Util.cloneViaSerialization(context);
    assertSame(context.getParentDataDomain(), deserializedContext.getParentDataDomain());

    // there should be only one object registered
    Artist deserializedArtist =
        (Artist) deserializedContext.getObjectStore().getObjectIterator().next();

    assertNotNull(deserializedArtist);
    assertEquals(PersistenceState.NEW, deserializedArtist.getPersistenceState());
    assertTrue(deserializedArtist.getObjectId().isTemporary());
    assertEquals("artist1", deserializedArtist.getArtistName());
    assertSame(deserializedContext, deserializedArtist.getObjectContext());
  }
示例#12
0
    @Override
    boolean replacesObject(Object object, Object objectInTheList) {

      Map<?, ?> id = (Map<?, ?>) objectInTheList;
      if (id.size() > idWidth) {
        return false;
      }

      // id must be a subset of this map
      Map<?, ?> map = (Map<?, ?>) object;
      for (Map.Entry<?, ?> entry : id.entrySet()) {
        Object key = entry.getKey();
        Object value = entry.getValue();
        if (!Util.nullSafeEquals(value, map.get(key))) {
          return false;
        }
      }

      return true;
    }
  public void testSerializeWithLocalCache() throws Exception {

    createSingleArtistDataSet();

    // manually assemble a DataContext with local cache....
    DataDomain domain = context.getParentDataDomain();
    DataRowStore snapshotCache =
        new DataRowStore(domain.getName(), domain.getProperties(), domain.getEventManager());

    Map<Object, Persistent> map = new HashMap<Object, Persistent>();

    DataContext localCacheContext = new DataContext(domain, new ObjectStore(snapshotCache, map));
    localCacheContext.setValidatingObjectsOnCommit(domain.isValidatingObjectsOnCommit());
    localCacheContext.setUsingSharedSnapshotCache(false);

    assertNotSame(
        domain.getSharedSnapshotCache(), localCacheContext.getObjectStore().getDataRowCache());

    DataContext deserializedContext = Util.cloneViaSerialization(localCacheContext);

    assertNotSame(localCacheContext, deserializedContext);
    assertNotSame(localCacheContext.getObjectStore(), deserializedContext.getObjectStore());

    assertSame(localCacheContext.getParentDataDomain(), deserializedContext.getParentDataDomain());
    assertNotSame(
        localCacheContext.getObjectStore().getDataRowCache(),
        deserializedContext.getObjectStore().getDataRowCache());
    assertNotSame(
        deserializedContext.getParentDataDomain().getSharedSnapshotCache(),
        deserializedContext.getObjectStore().getDataRowCache());

    Artist a = Cayenne.objectForPK(deserializedContext, Artist.class, 33001);
    assertNotNull(a);
    a.setArtistName(a.getArtistName() + "___");

    // this blows per CAY-796
    deserializedContext.commitChanges();
  }
  public void testSerializeModified() throws Exception {

    Artist artist = (Artist) context.newObject("Artist");
    artist.setArtistName("artist1");
    assertNotNull(artist.getObjectId());
    context.commitChanges();
    artist.setArtistName("artist2");

    DataContext deserializedContext = Util.cloneViaSerialization(context);

    assertSame(context.getParentDataDomain(), deserializedContext.getParentDataDomain());

    // there should be only one object registered
    Artist deserializedArtist =
        (Artist) deserializedContext.getObjectStore().getObjectIterator().next();

    assertNotNull(deserializedArtist);

    // deserialized as hollow...
    assertEquals(PersistenceState.MODIFIED, deserializedArtist.getPersistenceState());
    assertFalse(deserializedArtist.getObjectId().isTemporary());
    assertEquals("artist2", deserializedArtist.getArtistName());
    assertSame(deserializedContext, deserializedArtist.getObjectContext());
  }
  public void testSerializeWithSharedCache() throws Exception {

    createSingleArtistDataSet();

    DataContext deserializedContext = Util.cloneViaSerialization(context);

    assertNotSame(context, deserializedContext);
    assertNotSame(context.getObjectStore(), deserializedContext.getObjectStore());
    assertSame(context.getParentDataDomain(), deserializedContext.getParentDataDomain());
    assertSame(
        context.getObjectStore().getDataRowCache(),
        deserializedContext.getObjectStore().getDataRowCache());
    assertSame(
        deserializedContext.getParentDataDomain().getSharedSnapshotCache(),
        deserializedContext.getObjectStore().getDataRowCache());

    assertNotNull(deserializedContext.getEntityResolver());
    assertSame(context.getEntityResolver(), deserializedContext.getEntityResolver());

    Artist a = Cayenne.objectForPK(deserializedContext, Artist.class, 33001);
    assertNotNull(a);
    a.setArtistName(a.getArtistName() + "___");
    deserializedContext.commitChanges();
  }
  protected void initBindings() {

    // bind actions
    BindingBuilder builder = new BindingBuilder(getApplication().getBindingFactory(), this);

    builder.bindToAction(view.getGenerationMode(), "updateModeAction()");

    CayenneProjectPreferences cayPrPref = application.getCayenneProjectPreferences();

    this.preferences =
        (PreferenceDetail)
            cayPrPref.getProjectDetailObject(
                PreferenceDetail.class, getViewPreferences().node("controller"));

    if (Util.isEmptyString(preferences.getProperty("mode"))) {
      preferences.setProperty("mode", STANDARD_OBJECTS_MODE);
    }

    builder
        .bindToComboSelection(view.getGenerationMode(), "preferences.property['mode']")
        .updateView();

    updateModeAction();
  }
示例#17
0
  /**
   * Prints itself as XML to the provided XMLEncoder.
   *
   * @since 1.1
   */
  @Override
  public void encodeAsXML(XMLEncoder encoder) {
    encoder.print("<obj-entity name=\"");
    encoder.print(getName());

    // additionally validate that superentity exists
    if (getSuperEntityName() != null && getSuperEntity() != null) {
      encoder.print("\" superEntityName=\"");
      encoder.print(getSuperEntityName());
    }

    if (isAbstract()) {
      encoder.print("\" abstract=\"true");
    }

    if (isServerOnly()) {
      encoder.print("\" serverOnly=\"true");
    }

    if (getClassName() != null) {
      encoder.print("\" className=\"");
      encoder.print(getClassName());
    }

    if (getClientClassName() != null) {
      encoder.print("\" clientClassName=\"");
      encoder.print(getClientClassName());
    }

    if (isReadOnly()) {
      encoder.print("\" readOnly=\"true");
    }

    if (getDeclaredLockType() == LOCK_TYPE_OPTIMISTIC) {
      encoder.print("\" lock-type=\"optimistic");
    }

    if (getDbEntityName() != null && getDbEntity() != null) {

      // not writing DbEntity name if sub entity has same DbEntity
      // as super entity, see CAY-1477
      if (!(getSuperEntity() != null && getSuperEntity().getDbEntity() == getDbEntity())) {
        encoder.print("\" dbEntityName=\"");
        encoder.print(Util.encodeXmlAttribute(getDbEntityName()));
      }
    }

    if (getSuperEntityName() == null && getSuperClassName() != null) {
      encoder.print("\" superClassName=\"");
      encoder.print(getSuperClassName());
    }

    if (getSuperEntityName() == null && getClientSuperClassName() != null) {
      encoder.print("\" clientSuperClassName=\"");
      encoder.print(getClientSuperClassName());
    }

    // deprecated
    if (isExcludingSuperclassListeners()) {
      encoder.print("\" exclude-superclass-listeners=\"true");
    }

    // deprecated
    if (isExcludingDefaultListeners()) {
      encoder.print("\" exclude-default-listeners=\"true");
    }

    encoder.println("\">");
    encoder.indent(1);

    if (qualifier != null) {
      encoder.print("<qualifier>");
      qualifier.encodeAsXML(encoder);
      encoder.println("</qualifier>");
    }

    // store attributes
    encoder.print(getDeclaredAttributes());

    for (Map.Entry<String, String> override : attributeOverrides.entrySet()) {
      encoder.print("<attribute-override name=\"" + override.getKey() + '\"');
      encoder.print(" db-attribute-path=\"");
      encoder.print(Util.encodeXmlAttribute(override.getValue()));
      encoder.print('\"');
      encoder.println("/>");
    }

    // deprecated
    // write entity listeners
    for (EntityListener entityListener : entityListeners) {
      entityListener.encodeAsXML(encoder);
    }

    // write entity-level callbacks
    getCallbackMap().encodeCallbacksAsXML(encoder);

    encoder.indent(-1);
    encoder.println("</obj-entity>");
  }
示例#18
0
  /**
   * Synchronizes with the parent channel, performing a flush or a commit.
   *
   * @since 1.2
   */
  GraphDiff flushToParent(boolean cascade) {

    if (this.getChannel() == null) {
      throw new CayenneRuntimeException("Cannot commit changes - channel is not set.");
    }

    int syncType = cascade ? DataChannel.FLUSH_CASCADE_SYNC : DataChannel.FLUSH_NOCASCADE_SYNC;

    ObjectStore objectStore = getObjectStore();
    GraphDiff parentChanges = null;

    // prevent multiple commits occurring simultaneously
    synchronized (objectStore) {
      ObjectStoreGraphDiff changes = objectStore.getChanges();
      boolean noop =
          isValidatingObjectsOnCommit() ? changes.validateAndCheckNoop() : changes.isNoop();

      if (noop) {
        // need to clear phantom changes
        objectStore.postprocessAfterPhantomCommit();
      } else {

        try {
          parentChanges = getChannel().onSync(this, changes, syncType);

          // note that this is a hack resulting from a fix to
          // CAY-766... To
          // support
          // valid object state in PostPersist callback,
          // 'postprocessAfterCommit' is
          // invoked by DataDomain.onSync(..). Unless the parent is
          // DataContext,
          // and
          // this method is not invoked!! As a result, PostPersist
          // will contain
          // temp
          // ObjectIds in nested contexts and perm ones in flat
          // contexts.
          // Pending better callback design .....
          if (objectStore.hasChanges()) {
            objectStore.postprocessAfterCommit(parentChanges);
          }

          // this event is caught by peer nested DataContexts to
          // synchronize the
          // state
          fireDataChannelCommitted(this, changes);
        }
        // "catch" is needed to unwrap OptimisticLockExceptions
        catch (CayenneRuntimeException ex) {
          Throwable unwound = Util.unwindException(ex);

          if (unwound instanceof CayenneRuntimeException) {
            throw (CayenneRuntimeException) unwound;
          } else {
            throw new CayenneRuntimeException("Commit Exception", unwound);
          }
        }
      }

      // merge changes from parent as well as changes caused by lifecycle
      // event
      // callbacks/listeners...

      CompoundDiff diff = new CompoundDiff();

      diff.addAll(objectStore.getLifecycleEventInducedChanges());
      if (parentChanges != null) {
        diff.add(parentChanges);
      }

      // this event is caught by child DataContexts to update temporary
      // ObjectIds with permanent
      if (!diff.isNoop()) {
        fireDataChannelCommitted(getChannel(), diff);
      }

      return diff;
    }
  }
示例#19
0
  @Override
  public boolean equals(Object obj) {

    if (obj == this) {
      return true;
    }

    if (obj == null) {
      return false;
    }

    if (obj.getClass() != this.getClass()) {
      return false;
    }

    DataSourceInfo dsi = (DataSourceInfo) obj;

    if (!Util.nullSafeEquals(this.userName, dsi.userName)) {
      return false;
    }

    if (!Util.nullSafeEquals(this.password, dsi.password)) {
      return false;
    }

    if (!Util.nullSafeEquals(this.jdbcDriver, dsi.jdbcDriver)) {
      return false;
    }

    if (!Util.nullSafeEquals(this.dataSourceUrl, dsi.dataSourceUrl)) {
      return false;
    }

    if (!Util.nullSafeEquals(this.adapterClassName, dsi.adapterClassName)) {
      return false;
    }

    if (this.minConnections != dsi.minConnections) {
      return false;
    }

    if (this.maxConnections != dsi.maxConnections) {
      return false;
    }

    if (!Util.nullSafeEquals(this.passwordEncoderClass, dsi.passwordEncoderClass)) {
      return false;
    }

    if (!Util.nullSafeEquals(this.passwordEncoderKey, dsi.passwordEncoderKey)) {
      return false;
    }

    if (!Util.nullSafeEquals(this.passwordSourceFilename, dsi.passwordSourceFilename)) {
      return false;
    }

    if (!Util.nullSafeEquals(this.passwordSourceModel, dsi.passwordSourceModel)) {
      return false;
    }

    if (!Util.nullSafeEquals(this.passwordSourceUrl, dsi.passwordSourceUrl)) {
      return false;
    }

    if (!Util.nullSafeEquals(this.passwordLocation, dsi.passwordLocation)) {
      return false;
    }

    return true;
  }
示例#20
0
  void setClassName(String newClassName) {
    if (newClassName != null && newClassName.trim().length() == 0) {
      newClassName = null;
    }

    Embeddable embeddable = mediator.getCurrentEmbeddable();

    if (embeddable == null) {
      return;
    }

    if (Util.nullSafeEquals(newClassName, embeddable.getClassName())) {
      return;
    }

    if (newClassName == null) {
      throw new ValidationException("Embeddable name is required.");
    } else if (embeddable.getDataMap().getEmbeddable(newClassName) == null) {

      // if newClassName dupliucates in other DataMaps
      DataChannelDescriptor domain = (DataChannelDescriptor) mediator.getProject().getRootNode();
      if (domain != null) {
        for (DataMap nextMap : domain.getDataMaps()) {
          if (nextMap == embeddable.getDataMap()) {
            continue;
          }

          Embeddable conflictingEmbeddable = nextMap.getEmbeddable(newClassName);
          if (conflictingEmbeddable != null) {
            throw new ValidationException(
                "Duplicate Embeddable name in another DataMap: " + newClassName + ".");
          }
        }
      }

      // completely new name, set new name for embeddable
      EmbeddableEvent e = new EmbeddableEvent(this, embeddable, embeddable.getClassName());
      String oldName = embeddable.getClassName();
      embeddable.setClassName(newClassName);

      mediator.fireEmbeddableEvent(e, mediator.getCurrentDataMap());

      Iterator it =
          ((DataChannelDescriptor) mediator.getProject().getRootNode()).getDataMaps().iterator();
      while (it.hasNext()) {
        DataMap dataMap = (DataMap) it.next();
        Iterator<ObjEntity> ent = dataMap.getObjEntities().iterator();

        while (ent.hasNext()) {

          Collection<ObjAttribute> attr = ent.next().getAttributes();
          Iterator<ObjAttribute> attrIt = attr.iterator();

          while (attrIt.hasNext()) {
            ObjAttribute atribute = attrIt.next();
            if (atribute.getType() == null || atribute.getType().equals(oldName)) {
              atribute.setType(newClassName);
              AttributeEvent ev = new AttributeEvent(this, atribute, atribute.getEntity());
              mediator.fireObjAttributeEvent(ev);
            }
          }
        }
      }

    } else {
      // there is an embeddable with the same name
      throw new ValidationException(
          "There is another embeddable with name '" + newClassName + "'.");
    }
  }
  public void testProcessMessageExceptionSerializability() throws Throwable {

    Map<String, String> map = new HashMap<String, String>();
    ObjectContextFactory factory =
        new ObjectContextFactory() {

          public ObjectContext createContext(DataChannel parent) {
            return null;
          }

          public ObjectContext createContext() {
            return null;
          }
        };
    BaseRemoteService service =
        new BaseRemoteService(factory, map) {

          @Override
          protected ServerSession createServerSession() {
            return new ServerSession(new RemoteSession("a"), null);
          }

          @Override
          protected ServerSession createServerSession(String name) {
            return createServerSession();
          }

          @Override
          protected ServerSession getServerSession() {
            return createServerSession();
          }
        };

    try {
      service.processMessage(
          new QueryMessage(null) {

            @Override
            public Query getQuery() {
              // serializable exception thrown
              throw new CayenneRuntimeException();
            }
          });

      fail("Expected to throw");
    } catch (Exception ex) {
      Util.cloneViaSerialization(ex);
    }

    try {
      service.processMessage(
          new QueryMessage(null) {

            @Override
            public Query getQuery() {
              // non-serializable exception thrown
              throw new MockUnserializableException();
            }
          });

      fail("Expected to throw");
    } catch (Exception ex) {
      Util.cloneViaSerialization(ex);
    }
  }