All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.tentackle.maven.wizard.PdoGenerator Maven / Gradle / Ivy

There is a newer version: 21.16.1.0
Show newest version
/*
 * Tentackle - http://www.tentackle.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package org.tentackle.maven.wizard;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

import org.tentackle.bind.Bindable;
import org.tentackle.fx.Fx;
import org.tentackle.model.Entity;
import org.tentackle.model.InheritanceType;
import org.tentackle.model.Model;
import org.tentackle.model.ModelException;
import org.tentackle.validate.ValidationResult;
import org.tentackle.validate.ValidationScopeFactory;
import org.tentackle.validate.scope.InteractiveScope;
import org.tentackle.validate.validator.Changeable;
import org.tentackle.validate.validator.GreaterOrEqual;
import org.tentackle.validate.validator.NotNull;
import org.tentackle.validate.validator.True;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Generator for the PDO files.
 */
public class PdoGenerator extends AbstractGenerator {

  private File statusDir;
  private PdoProfile profile;
  private String entityName;
  private Integer classId;
  private String tableName;
  private Entity superEntity;
  private InheritanceType inheritanceType;
  private String shortDescription;
  private String longDescription;
  private String domainInterface;
  private String persistenceInterface;
  private String domainImplementation;
  private String persistenceImplementation;
  private boolean remoteEnabled;


  /**
   * Sets the status directory.
   *
   * @param statusDir the status dir
   */
  public void setStatusDir(File statusDir) {
    this.statusDir = statusDir;
  }

  /**
   * Creates the PDO files.
   *
   * @return the validation results, empty if okay, never null
   * @throws IOException if file creation failed
   * @throws TemplateException if code generation failed
   */
  public List generate() throws IOException, TemplateException {
    List results = validate(null, ValidationScopeFactory.getInstance().getMandatoryScope());
    results.addAll(validate(null, ValidationScopeFactory.getInstance().getInteractiveScope()));
    if (results.isEmpty()) {
      // configure freemarker
      Configuration cfg = createFreemarkerConfiguration();

      // create freemarker model
      PdoTemplateModel templateModel = new PdoTemplateModel(this);

      // create targets
      List generatedFiles = new ArrayList<>();
      generatedFiles.add(new GeneratedFile(cfg, templateModel,"PdoInterface.ftl",
                         new File(getProfile().getPdoPackageInfo().getPath(), getEntityName() + Constants.JAVA_EXT)));
      generatedFiles.add(new GeneratedFile(cfg, templateModel,"DomainInterface.ftl",
                         new File(getProfile().getDomainPackageInfo().getPath(), getDomainInterface() + Constants.JAVA_EXT)));
      generatedFiles.add(new GeneratedFile(cfg, templateModel,"PersistenceInterface.ftl",
                         new File(getProfile().getPersistencePackageInfo().getPath(), getPersistenceInterface() + Constants.JAVA_EXT)));
      if (getDomainImplementation() != null) {
        generatedFiles.add(new GeneratedFile(cfg, templateModel,"DomainImplementation.ftl",
                           new File(getProfile().getDomainImplPackageInfo().getPath(), getDomainImplementation() + Constants.JAVA_EXT)));
      }
      if (getPersistenceImplementation() != null) {
        generatedFiles.add(new GeneratedFile(cfg, templateModel,"PersistenceImplementation.ftl",
                           new File(getProfile().getPersistenceImplPackageInfo().getPath(), getPersistenceImplementation() + Constants.JAVA_EXT)));
      }

      // genetate targets
      for (GeneratedFile generatedFile: generatedFiles) {
        generatedFile.generate();
      }

      // save class ID status, if any classid created
      if (classId != null) {
        statusDir.mkdirs();
        FileWriter statusWriter = new FileWriter(new File(statusDir, profile.getName() + Constants.CLASSID_EXT));
        try {
          statusWriter.append(Integer.toString(classId + 1));
        }
        finally {
          statusWriter.close();
        }
      }
    }
    return results;
  }


  /**
   * Checks whether entity name is not already used in model.
   *
   * @return true if ok
   */
  public boolean isNewEntity() {
    try {
      return entityName == null || Model.getInstance().getByEntityName(entityName) == null;
    }
    catch (ModelException e) {
      Fx.error("cannot check for duplicate entity", e);
      return true;
    }
  }

  /**
   * Checks whether classID is not already used in model.
   *
   * @return true if ok
   */
  public boolean isNewClassId() {
    if (classId != null && classId > 0) {
      try {
        for (Entity entity : Model.getInstance().getAllEntitites()) {
          if (entity.getClassId() == classId) {
            return false;
          }
        }
      }
      catch (ModelException e) {
        Fx.error("cannot check for duplicate entity", e);
      }
    }
    return true;
  }

  /**
   * Checks whether entity needs a class ID.
   *
   * @return true if class ID necessary
   */
  public boolean isClassIdNecessary() {
    boolean necessary = InheritanceType.NONE == inheritanceType;
    if (!necessary) {
      classId = null;
    }
    return necessary;
  }

  /**
   * Checks whether the tablename is not already used in model.
   *
   * @return true if ok
   */
  public boolean isNewTableName() {
    if (tableName != null) {
      try {
        for (Entity entity : Model.getInstance().getAllEntitites()) {
          if (tableName.equalsIgnoreCase(entity.getTableName())) {
            return false;
          }
        }
      }
      catch (ModelException e) {
        Fx.error("cannot check for duplicate entity", e);
      }
    }
    return true;
  }

  /**
   * Checks whether entity needs a tablename.
   *
   * @return true if tablename necessary
   */
  public boolean isTableNameNecessary() {
    boolean necessary = false;
    if (inheritanceType != null) {
      switch (inheritanceType) {
        case NONE:
          necessary = superEntity == null ||
                      superEntity.getInheritanceType().isMappingToNoTable() ||
                      superEntity.getInheritanceType().isMappingToOwnTable();
          break;

        case SINGLE:
          necessary = superEntity == null;
          break;

        case MULTI:
          necessary = true;
          break;
      }
    }
    if (!necessary) {
      tableName = null;
    }
    return necessary;
  }

  /**
   * Checks whether tablename set properly by the user.
   *
   * @return true if set, false if missing
   */
  public Boolean isTableNameValid() {
    return tableName != null && (profile == null || profile.getTablePrefix() == null || !tableName.equals(profile.getTablePrefix())) ?
           Boolean.TRUE : null;   // TRUE != null, null -> @NotNull triggers
  }

  public boolean isInheritanceTypeValid() {
    return InheritanceType.NONE == inheritanceType ||
           superEntity == null ||
           superEntity.getInheritanceType() == inheritanceType;
  }



  // ------------------------------------- model -------------------------------------------------


  @Bindable
  @NotNull
  public PdoProfile getProfile() {
    return profile;
  }

  @Bindable
  public void setProfile(PdoProfile profile) {
    if (isTableNameNecessary()) {
      String oldPrefix = null;
      if (this.profile != null) {
        oldPrefix = this.profile.getTablePrefix();
        if (oldPrefix != null && tableName != null && tableName.startsWith(oldPrefix)) {
          tableName = tableName.substring(oldPrefix.length());
          if (tableName.isEmpty()) {
            tableName = null;
          }
        }
      }
      if (profile != null && profile.getTablePrefix() != null) {
        if (tableName == null) {
          tableName = profile.getTablePrefix();
        }
        else {
          tableName = profile.getTablePrefix() + tableName;
        }
      }
    }

    this.profile = profile;
  }

  @Bindable
  @NotNull(message = "missing entity name")
  @True(value = "$isNewEntity", scope = InteractiveScope.class, message = "entity already exists")
  public String getEntityName() {
    return entityName;
  }

  @Bindable
  public void setEntityName(String entityName) {
    this.entityName = entityName;
    if (entityName == null) {
      domainInterface = null;
      domainImplementation = null;
      persistenceInterface = null;
      persistenceImplementation = null;
    }
    else {
      if (domainInterface == null || domainInterface.endsWith(Constants.DOMAIN_SUFFIX)) {
        domainInterface = entityName + Constants.DOMAIN_SUFFIX;
      }
      if (domainImplementation == null || domainImplementation.endsWith(Constants.DOMAIN_IMPL_SUFFIX)) {
        domainImplementation = entityName + Constants.DOMAIN_IMPL_SUFFIX;
      }
      if (persistenceInterface == null || persistenceInterface.endsWith(Constants.PERSISTENCE_SUFFIX)) {
        persistenceInterface = entityName + Constants.PERSISTENCE_SUFFIX;
      }
      if (persistenceImplementation == null || persistenceImplementation.endsWith(Constants.PERSISTENCE_IMPL_SUFFIX)) {
        persistenceImplementation = entityName + Constants.PERSISTENCE_IMPL_SUFFIX;
      }
    }
  }

  @Bindable
  @True(value = "$isNewClassId", scope = InteractiveScope.class, message = "class ID already in use")
  @Changeable(condition = "$isClassIdNecessary")
  @GreaterOrEqual(value = "100", condition = "$isClassIdNecessary",
                  message = "class IDs below 100 are reserved for tentackle", scope = InteractiveScope.class)
  @NotNull(condition = "$isClassIdNecessary", message = "missing class ID")
  public Integer getClassId() {
    if (isClassIdNecessary()) {
      if (classId == null || classId < profile.getMinClassId() || classId > profile.getMaxClassId()) {
        classId = profile.getMinClassId();
      }
    }
    return classId;
  }

  @Bindable
  public void setClassId(Integer classId) {
    this.classId = classId;
  }

  @Bindable(options = "lc")
  @True(value = "$isNewTableName", scope = InteractiveScope.class, message = "table name already in use")
  @Changeable(condition = "$isTableNameNecessary")
  @NotNull(value = "$isTableNameValid", condition = "$isTableNameNecessary", message = "missing table name")
  public String getTableName() {
    if (isTableNameNecessary() && tableName == null && profile != null && profile.getTablePrefix() != null) {
      tableName = profile.getTablePrefix();
    }
    return tableName;
  }

  @Bindable
  public void setTableName(String tableName) {
    this.tableName = tableName;
  }

  @Bindable
  public Entity getSuperEntity() {
    return superEntity;
  }

  @Bindable
  public void setSuperEntity(Entity superEntity) {
    this.superEntity = superEntity;
  }

  @Bindable
  @NotNull
  @True(value = "$isInheritanceTypeValid", scope = InteractiveScope.class, message = "inheritance type does not match super entity")
  public InheritanceType getInheritanceType() {
    return inheritanceType;
  }

  @Bindable
  public void setInheritanceType(InheritanceType inheritanceType) {
    this.inheritanceType = inheritanceType;
  }

  @Bindable
  @NotNull(message = "missing short description")
  public String getShortDescription() {
    return shortDescription;
  }

  @Bindable
  public void setShortDescription(String shortDescription) {
    this.shortDescription = shortDescription;
  }

  @Bindable
  public String getLongDescription() {
    return longDescription;
  }

  @Bindable
  public void setLongDescription(String longDescription) {
    this.longDescription = longDescription;
  }

  @Bindable
  @NotNull(message = "missing domain interface")
  public String getDomainInterface() {
    return domainInterface;
  }

  @Bindable
  public void setDomainInterface(String domainInterface) {
    this.domainInterface = domainInterface;
  }

  @Bindable
  @NotNull(message = "missing persistence interface")
  public String getPersistenceInterface() {
    return persistenceInterface;
  }

  @Bindable
  public void setPersistenceInterface(String persistenceInterface) {
    this.persistenceInterface = persistenceInterface;
  }

  @Bindable
  public String getDomainImplementation() {
    return domainImplementation;
  }

  @Bindable
  public void setDomainImplementation(String domainImplementation) {
    this.domainImplementation = domainImplementation;
  }

  @Bindable
  public String getPersistenceImplementation() {
    return persistenceImplementation;
  }

  @Bindable
  public void setPersistenceImplementation(String persistenceImplementation) {
    this.persistenceImplementation = persistenceImplementation;
  }

  @Bindable
  public boolean isRemoteEnabled() {
    return remoteEnabled;
  }

  @Bindable
  public void setRemoteEnabled(boolean remoteEnabled) {
    this.remoteEnabled = remoteEnabled;
  }


  /**
   * Gets the name of the parent pdo interface.
   *
   * @return the super interface
   */
  public String getSuperPdoInterface() {
    String superPdoInterface;
    if (superEntity != null) {
      superPdoInterface = superEntity.getName();
    }
    else if (profile.getPdoInterface() != null) {
      superPdoInterface = profile.getPdoInterface();
    }
    else {
      superPdoInterface = "PersistentDomainObject";
    }
    return superPdoInterface;
  }

  /**
   * Gets the name of the parent domain interface.
   *
   * @return the super domain interface
   */
  public String getSuperDomainInterface() {
    String superDomainInterface;
    if (superEntity != null) {
      superDomainInterface = superEntity.getName() + Constants.DOMAIN_SUFFIX;
    }
    else if (profile.getDomainInterface() != null) {
      superDomainInterface = profile.getDomainInterface();
    }
    else {
      superDomainInterface = "DomainObject";
    }
    return superDomainInterface;
  }

  /**
   * Gets the name of the parent persistence interface.
   *
   * @return the super persistence interface
   */
  public String getSuperPersistenceInterface() {
    String superPersistenceInterface;
    if (superEntity != null) {
      superPersistenceInterface = superEntity.getName() + Constants.PERSISTENCE_SUFFIX;
    }
    else if (profile.getPersistenceInterface() != null) {
      superPersistenceInterface = profile.getPersistenceInterface();
    }
    else {
      superPersistenceInterface = "PersistentObject";
    }
    return superPersistenceInterface;
  }

  /**
   * Gets the name of the parent domain class.
   *
   * @return the super domain class
   */
  public String getSuperDomainImplementation() {
    String superDomainImplementation;
    if (superEntity != null) {
      superDomainImplementation = superEntity.getName() + Constants.DOMAIN_IMPL_SUFFIX;
    }
    else if (profile.getDomainImplementation() != null) {
      superDomainImplementation = profile.getDomainImplementation();
    }
    else {
      superDomainImplementation = "AbstractDomainObject";
    }
    return superDomainImplementation;
  }

  /**
   * Gets the name of the parent persistence class.
   *
   * @return the super persistence class
   */
  public String getSuperPersistenceImplementation() {
    String superPersistenceImplementation;
    if (superEntity != null) {
      superPersistenceImplementation = superEntity.getName() + Constants.PERSISTENCE_IMPL_SUFFIX;
    }
    else if (profile.getPersistenceImplementation() != null) {
      superPersistenceImplementation = profile.getPersistenceImplementation();
    }
    else {
      superPersistenceImplementation = "AbstractPersistentObject";
    }
    return superPersistenceImplementation;
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy