diff options
Diffstat (limited to 'jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse')
28 files changed, 0 insertions, 8133 deletions
diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/EntityGenTools.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/EntityGenTools.java deleted file mode 100644 index 058490ea15..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/EntityGenTools.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - -import java.util.Collection; -import org.eclipse.jpt.utility.internal.NameTools; -import org.eclipse.jpt.utility.internal.StringTools; - -/** - * Utility methods for entity generation. - */ -public class EntityGenTools { - - /** - * Convert the specified (database) identifier to a unique "Java style" - * class name. - * @see #convertToUniqueJavaStyleIdentifier(String, boolean, Collection) - */ - public static String convertToUniqueJavaStyleClassName(String identifier, Collection<String> classNames) { - return convertToUniqueJavaStyleIdentifier(identifier, true, classNames); - } - - /** - * Convert the specified (database) identifier to a unique "Java style" - * attribute (field/property) name. - * @see #convertToUniqueJavaStyleIdentifier(String, boolean, Collection) - */ - public static String convertToUniqueJavaStyleAttributeName(String identifier, Collection<String> attributeNames) { - return convertToUniqueJavaStyleIdentifier(identifier, false, attributeNames); - } - - /** - * Convert the specified (database) identifier to a unique "Java style" - * identifier: - * - if the identifier is all-caps, convert underscores to "camel case" - * - if the identifier is not all-caps, leave it unchanged (except, possibly, for the first letter) - * - convert to a legal Java identifier - * - eliminate illegal characters - * - if the result is a reserved word, modify it slightly - * If the result is already one of the specified existing identifiers - * (ignoring case so we don't have filename collisions on Windows), - * modify it slightly again. - * "FOO" => "Foo" or "foo" - * "FOO_BAR" => "FooBar" or "fooBar" - * "PACKAGE" => "Package" or "package_" - */ - public static String convertToUniqueJavaStyleIdentifier(String identifier, boolean capitalizeFirstLetter, Collection<String> identifiers) { - String result = identifier; - if (StringTools.stringIsUppercase(result)) { - // leave mixed case identifiers alone? - result = StringTools.convertUnderscoresToCamelCase(result, capitalizeFirstLetter); - } else { - result = capitalizeFirstLetter ? StringTools.capitalize(result) : StringTools.uncapitalize(result); - } - result = NameTools.convertToJavaIdentifier(result); - // assume that converting to a unique name will not result in a Java reserved word - // (since no Java reserved words end with a number) - result = NameTools.uniqueNameForIgnoreCase(result, identifiers); - return result; - } - - - // ********** constructor ********** - - /** - * Suppress default constructor, ensuring non-instantiability. - */ - private EntityGenTools() { - super(); - throw new UnsupportedOperationException(); - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/EntityGenerator.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/EntityGenerator.java deleted file mode 100644 index 17fa171bd0..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/EntityGenerator.java +++ /dev/null @@ -1,1779 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.StringWriter; -import java.lang.reflect.Modifier; -import java.text.Collator; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.SubMonitor; -import org.eclipse.jdt.core.IJavaModelStatusConstants; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.utility.JavaType; -import org.eclipse.jpt.utility.internal.BooleanHolder; -import org.eclipse.jpt.utility.internal.IndentingPrintWriter; -import org.eclipse.jpt.utility.internal.NameTools; -import org.eclipse.jpt.utility.internal.StringTools; -import org.eclipse.jpt.utility.internal.iterators.FilteringIterator; -import org.eclipse.osgi.util.NLS; - -// TODO format generated code per preferences -// TODO organize generated imports per preferences -/** - * This generator will generate an entity for a table. - */ -public class EntityGenerator { - final Config config; - private final IPackageFragment packageFragment; - private final GenTable genTable; - private final String entityClassName; - private final String pkClassName; - - - // ********** public API ********** - - static void generateEntity( - Config config, - IPackageFragment packageFragment, - GenTable genTable, - IProgressMonitor progressMonitor - ) { - if ((config == null) || (packageFragment == null) || (genTable == null)) { - throw new NullPointerException(); - } - new EntityGenerator(config, packageFragment, genTable).generateEntity(progressMonitor); - } - - - // ********** constructor/initialization ********** - - private EntityGenerator(Config config, IPackageFragment packageFragment, GenTable genTable) { - super(); - this.config = config; - this.packageFragment = packageFragment; - this.genTable = genTable; - this.entityClassName = this.fullyQualify(this.getEntityName()); - this.pkClassName = this.entityClassName + '.' + config.getPrimaryKeyMemberClassName(); - } - - - // ********** code gen ********** - - private void generateEntity(IProgressMonitor progressMonitor) { - try { - this.generateEntity_(progressMonitor); - } catch (JavaModelException ex) { - throw new RuntimeException(ex); - } - } - - private void generateEntity_(IProgressMonitor progressMonitor) throws JavaModelException { - SubMonitor sm = SubMonitor.convert(progressMonitor, this.buildTaskName(), 100); - String fileName = this.getEntityName() + ".java"; //$NON-NLS-1$ - String source = this.buildSource(); - sm.worked(20); - try { - this.packageFragment.createCompilationUnit(fileName, source, false, sm.newChild(40)); - } catch (JavaModelException ex) { - if (ex.getJavaModelStatus().getCode() == IJavaModelStatusConstants.NAME_COLLISION) { - if (this.config.getOverwriteConfirmer().overwrite(this.entityClassName)) { - this.packageFragment.createCompilationUnit(fileName, source, true, sm.newChild(40)); - } - } else { - throw ex; - } - } - sm.setWorkRemaining(0); - } - - private String buildTaskName() { - return NLS.bind(JptGenMessages.EntityGenerator_taskName, this.getEntityName()); - } - - /** - * build the "body" source first; then build the "package" and "imports" source - * and concatenate the "body" source to it - */ - private String buildSource() { - // build the body source first so we can gather up the import statements - BodySource bodySource = this.buildBodySource(); - - StringWriter sw = new StringWriter(bodySource.length() + 2000); - PrintWriter pw = new PrintWriter(sw); - this.printPackageAndImportsOn(pw, bodySource); - pw.print(bodySource.getSource()); - return sw.toString(); - } - - private BodySource buildBodySource() { - EntitySourceWriter pw = new EntitySourceWriter(this.getPackageName(), this.entityClassName); - this.printBodySourceOn(pw); - return pw; - } - - private void printBodySourceOn(EntitySourceWriter pw) { - this.printClassDeclarationOn(pw); - - pw.indent(); - this.printEntityPrimaryKeyFieldsOn(pw); - this.printEntityNonPrimaryKeyBasicFieldsOn(pw); - this.printEntityManyToOneFieldsOn(pw); - this.printEntityOneToManyFieldsOn(pw); - this.printEntityOwnedManyToManyFieldsOn(pw); - this.printEntityNonOwnedManyToManyFieldsOn(pw); - this.printSerialVersionUIDFieldOn(pw); - pw.println(); - - this.printZeroArgumentConstructorOn(this.getEntityName(), this.config.getMethodVisibilityClause(), pw); - if (this.config.propertyAccessType() || this.config.generateGettersAndSetters()) { - this.printEntityPrimaryKeyPropertiesOn(pw); - this.printEntityNonPrimaryKeyBasicPropertiesOn(pw); - this.printEntityManyToOnePropertiesOn(pw); - this.printEntityOneToManyPropertiesOn(pw); - this.printEntityOwnedManyToManyPropertiesOn(pw); - this.printEntityNonOwnedManyToManyPropertiesOn(pw); - } - - if (this.primaryKeyClassIsRequired()) { - this.printPrimaryKeyClassOn(pw); - } - pw.undent(); - - pw.print('}'); - pw.println(); // EOF - } - - - // ********** class declaration ********** - - private void printClassDeclarationOn(EntitySourceWriter pw) { - this.printEntityAnnotationOn(pw); - this.printTableAnnotationOn(pw); - this.printIdClassAnnotationOn(pw); - - pw.print("public class "); //$NON-NLS-1$ - pw.printTypeDeclaration(this.entityClassName); - if (config.serializable()) { - pw.print(" implements "); //$NON-NLS-1$ - pw.printTypeDeclaration(Serializable.class.getName()); - } - pw.print(" {"); //$NON-NLS-1$ - pw.println(); - } - - private void printEntityAnnotationOn(EntitySourceWriter pw) { - pw.printAnnotation(JPA.ENTITY); - pw.println(); - } - - private void printTableAnnotationOn(EntitySourceWriter pw) { - String tableName = this.config.getDatabaseAnnotationNameBuilder().buildTableAnnotationName(this.getEntityName(), this.getTable()); - if (tableName == null) { - return; // the default table name is OK - } - pw.printAnnotation(JPA.TABLE); - pw.print("(name="); //$NON-NLS-1$ - pw.printStringLiteral(tableName); - pw.print(')'); - pw.println(); - } - - private void printIdClassAnnotationOn(EntitySourceWriter pw) { - if (this.primaryKeyClassIsRequired() && this.config.generateIdClassForCompoundPK()) { - pw.printAnnotation(JPA.ID_CLASS); - pw.print('('); - pw.printTypeDeclaration(this.pkClassName); - pw.print(".class)"); //$NON-NLS-1$ - pw.println(); - } - } - - - // ********** primary key fields ********** - - private void printEntityPrimaryKeyFieldsOn(EntitySourceWriter pw) { - if (this.primaryKeyClassIsRequired() && this.config.generateEmbeddedIdForCompoundPK()) { - this.printEntityEmbeddedIdPrimaryKeyFieldOn(pw); - } else { - this.printEntityReadOnlyPrimaryKeyFieldsOn(pw); - this.printEntityWritablePrimaryKeyFieldsOn(pw); - } - } - - private void printEntityEmbeddedIdPrimaryKeyFieldOn(EntitySourceWriter pw) { - if (this.config.fieldAccessType()) { - pw.printAnnotation(JPA.EMBEDDED_ID); - pw.println(); - } - this.printFieldOn(this.genTable.getAttributeNameForEmbeddedId(), this.pkClassName, pw); - } - - private void printEntityReadOnlyPrimaryKeyFieldsOn(EntitySourceWriter pw) { - this.printPrimaryKeyFieldsOn(pw, true, true); // true=read-only; true=print ID annotation on fields - } - - private void printEntityWritablePrimaryKeyFieldsOn(EntitySourceWriter pw) { - this.printPrimaryKeyFieldsOn(pw, false, true); // false=writable; true=print ID annotation on fields - } - - private void printPrimaryKeyFieldsOn(EntitySourceWriter pw, boolean readOnly, boolean printIdAnnotation) { - for (Iterator<Column> stream = this.primaryKeyColumns(readOnly); stream.hasNext(); ) { - this.printPrimaryKeyFieldOn(stream.next(), pw, readOnly, printIdAnnotation); - } - } - - private Iterator<Column> primaryKeyColumns(boolean readOnly) { - return readOnly ? this.genTable.readOnlyPrimaryKeyColumns() : this.genTable.writablePrimaryKeyColumns(); - } - - // TODO if the field's type is java.util/sql.Date, it needs @Temporal(DATE) - // TODO if the primary key is auto-generated, the field must be an integral type - private void printPrimaryKeyFieldOn(Column column, EntitySourceWriter pw, boolean readOnly, boolean printIdAnnotation) { - String fieldName = this.genTable.getAttributeNameFor(column); - if (this.config.fieldAccessType()) { - if (printIdAnnotation) { - pw.printAnnotation(JPA.ID); - pw.println(); - } - String columnName = this.config.getDatabaseAnnotationNameBuilder().buildColumnAnnotationName(fieldName, column); - if (readOnly) { - this.printReadOnlyColumnAnnotationOn(columnName, pw); - } else { - this.printColumnAnnotationOn(columnName, pw); - } - } - this.printFieldOn(fieldName, column.getPrimaryKeyJavaTypeDeclaration(), pw); - } - - private void printReadOnlyColumnAnnotationOn(String columnName, EntitySourceWriter pw) { - pw.printAnnotation(JPA.COLUMN); - pw.print('('); - if (columnName != null) { - pw.print("name="); //$NON-NLS-1$ - pw.printStringLiteral(columnName); - pw.print(", "); //$NON-NLS-1$ - } - pw.print("insertable=false, updatable=false)"); //$NON-NLS-1$ - pw.println(); - } - - - // ********** basic fields ********** - - private void printEntityNonPrimaryKeyBasicFieldsOn(EntitySourceWriter pw) { - for (Iterator<Column> stream = this.genTable.nonPrimaryKeyBasicColumns(); stream.hasNext(); ) { - this.printEntityNonPrimaryKeyBasicFieldOn(stream.next(), pw); - } - } - - private void printEntityNonPrimaryKeyBasicFieldOn(Column column, EntitySourceWriter pw) { - String fieldName = this.genTable.getAttributeNameFor(column); - if (this.config.fieldAccessType()) { - String columnName = this.config.getDatabaseAnnotationNameBuilder().buildColumnAnnotationName(fieldName, column); - this.printColumnAnnotationOn(columnName, pw); - } - if (column.isLOB()) { - pw.printAnnotation(JPA.LOB); - pw.println(); - } - this.printFieldOn(fieldName, column.getJavaTypeDeclaration(), pw); - } - - private void printColumnAnnotationOn(String columnName, EntitySourceWriter pw) { - if (columnName != null) { // the column name is null if the default is OK - pw.printAnnotation(JPA.COLUMN); - pw.print("(name="); //$NON-NLS-1$ - pw.printStringLiteral(columnName); - pw.print(')'); - pw.println(); - } - } - - - // ********** many-to-one fields ********** - - private void printEntityManyToOneFieldsOn(EntitySourceWriter pw) { - for (Iterator<ManyToOneRelation> stream = this.genTable.manyToOneRelations(); stream.hasNext(); ) { - this.printEntityManyToOneFieldOn(stream.next(), pw); - } - } - - private void printEntityManyToOneFieldOn(ManyToOneRelation relation, EntitySourceWriter pw) { - String fieldName = this.genTable.getAttributeNameFor(relation); - if (this.config.fieldAccessType()) { - this.printManyToOneAnnotationOn(fieldName, relation, pw); - } - this.printFieldOn(fieldName, this.fullyQualify(relation.getReferencedEntityName()), pw); - } - - private void printManyToOneAnnotationOn(String attributeName, ManyToOneRelation relation, EntitySourceWriter pw) { - pw.printAnnotation(JPA.MANY_TO_ONE); - pw.println(); - ForeignKey foreignKey = relation.getForeignKey(); - if (foreignKey.referencesSingleColumnPrimaryKey()) { - // if the FK references a single-column PK, 'referencedColumnName' is not required - String joinColumnName = this.config.getDatabaseAnnotationNameBuilder().buildJoinColumnAnnotationName(attributeName, foreignKey); - if (joinColumnName == null) { - // no JoinColumn annotation needed: the default 'name' and 'referencedColumnName' work - } else { - // there is only a single join column here (just not the default name) - this.printJoinColumnAnnotationOn(joinColumnName, null, pw); - pw.println(); - } - } else { - this.printManyToOneJoinColumnsAnnotationOn(foreignKey, pw); - } - } - - private void printManyToOneJoinColumnsAnnotationOn(ForeignKey foreignKey, EntitySourceWriter pw) { - if (foreignKey.columnPairsSize() > 1) { - pw.printAnnotation(JPA.JOIN_COLUMNS); - pw.print("({"); //$NON-NLS-1$ - pw.println(); - pw.indent(); - } - this.printJoinColumnAnnotationsOn(foreignKey, pw); - if (foreignKey.columnPairsSize() > 1) { - pw.undent(); - pw.println(); - pw.print("})"); //$NON-NLS-1$ - } - pw.println(); - } - - private void printJoinColumnAnnotationsOn(ForeignKey foreignKey, EntitySourceWriter pw) { - for (Iterator<ForeignKey.ColumnPair> stream = foreignKey.columnPairs(); stream.hasNext(); ) { - this.printJoinColumnAnnotationOn(stream.next(), pw); - if (stream.hasNext()) { - pw.println(','); - } - } - } - - private void printJoinColumnAnnotationOn(ForeignKey.ColumnPair columnPair, EntitySourceWriter pw) { - this.printJoinColumnAnnotationOn( - this.config.getDatabaseAnnotationNameBuilder().buildJoinColumnAnnotationName(columnPair.getBaseColumn()), - this.config.getDatabaseAnnotationNameBuilder().buildJoinColumnAnnotationName(columnPair.getReferencedColumn()), - pw - ); - } - - /** - * 'baseColumnName' cannot be null; - * 'referencedColumnName' is null when the default is applicable (i.e. the - * referenced column is the single-column primary key column of the - * referenced table) - */ - private void printJoinColumnAnnotationOn(String baseColumnName, String referencedColumnName, EntitySourceWriter pw) { - pw.printAnnotation(JPA.JOIN_COLUMN); - pw.print("(name="); //$NON-NLS-1$ - pw.printStringLiteral(baseColumnName); - - if (referencedColumnName != null) { - pw.print(", referencedColumnName="); //$NON-NLS-1$ - pw.printStringLiteral(referencedColumnName); - } - - pw.print(')'); - } - - - // ********** one-to-many fields ********** - - private void printEntityOneToManyFieldsOn(EntitySourceWriter pw) { - for (Iterator<OneToManyRelation> stream = this.genTable.oneToManyRelations(); stream.hasNext(); ) { - this.printEntityOneToManyFieldOn(stream.next(), pw); - } - } - - private void printEntityOneToManyFieldOn(OneToManyRelation relation, EntitySourceWriter pw) { - String fieldName = this.genTable.getAttributeNameFor(relation); - if (this.config.fieldAccessType()) { - this.printOneToManyAnnotationOn(relation, pw); - } - this.printCollectionFieldOn(fieldName, this.fullyQualify(relation.getReferencedEntityName()), pw); - } - - private void printOneToManyAnnotationOn(OneToManyRelation relation, EntitySourceWriter pw) { - pw.printAnnotation(JPA.ONE_TO_MANY); - pw.print("(mappedBy=\""); //$NON-NLS-1$ - pw.print(relation.getMappedBy()); - pw.print("\")"); //$NON-NLS-1$ - pw.println(); - } - - - // ********** owned many-to-many fields ********** - - private void printEntityOwnedManyToManyFieldsOn(EntitySourceWriter pw) { - for (Iterator<ManyToManyRelation> stream = this.genTable.ownedManyToManyRelations(); stream.hasNext(); ) { - this.printEntityOwnedManyToManyFieldOn(stream.next(), pw); - } - } - - private void printEntityOwnedManyToManyFieldOn(ManyToManyRelation relation, EntitySourceWriter pw) { - String fieldName = this.genTable.getAttributeNameForOwned(relation); - if (this.config.fieldAccessType()) { - this.printOwnedManyToManyAnnotationOn(fieldName, relation, pw); - } - this.printCollectionFieldOn(fieldName, this.fullyQualify(relation.getNonOwningEntityName()), pw); - } - - /** - * only print the JoinTable annotation if one or more of the - * [generated] elements is not defaulted: - * name - * joinColumns - * inverseJoinColumns - * thus the need for the 'printJoinTableAnnotation' flag - */ - private void printOwnedManyToManyAnnotationOn(String attributeName, ManyToManyRelation relation, EntitySourceWriter pw) { - pw.printAnnotation(JPA.MANY_TO_MANY); - pw.println(); - BooleanHolder printJoinTableAnnotation = new BooleanHolder(true); - - if ( ! relation.joinTableNameIsDefault()) { // db-only test - no need to delegate to platform? - printJoinTableAnnotation.setFalse(); - pw.printAnnotation(JPA.JOIN_TABLE); - pw.print("(name="); //$NON-NLS-1$ - pw.printStringLiteral(this.config.getDatabaseAnnotationNameBuilder().buildJoinTableAnnotationName(relation.getJoinGenTable().getTable())); - } - - this.printJoinTableJoinColumnAnnotationsOn( - "joinColumns", //$NON-NLS-1$ - attributeName, - relation.getOwningForeignKey(), - printJoinTableAnnotation, - pw - ); - - this.printJoinTableJoinColumnAnnotationsOn( - "inverseJoinColumns", //$NON-NLS-1$ - relation.getNonOwningGenTable().getAttributeNameForNonOwned(relation), - relation.getNonOwningForeignKey(), - printJoinTableAnnotation, - pw - ); - - if (printJoinTableAnnotation.isFalse()) { - pw.print(')'); - pw.println(); - } - } - - /** - * 'elementName' is either "joinColumns" or "inverseJoinColumns" - */ - private void printJoinTableJoinColumnAnnotationsOn(String elementName, String attributeName, ForeignKey foreignKey, BooleanHolder printJoinTableAnnotation, EntitySourceWriter pw) { - // we have to pre-calculate whether either 'name' and/or 'referencedColumnName' - // is required because they are wrapped by the JoinTable annotation and we - // need to print the JoinTable annotation first (if it hasn't already been printed) - boolean printRef = ! foreignKey.referencesSingleColumnPrimaryKey(); - // if 'referencedColumnName' is required, 'name' is also required (i.e. it cannot be defaulted); - // but we will calculate it later [1], since there could be multiple join columns - String joinColumnName = (printRef) ? - null // 'joinColumnName' is not used - : - this.config.getDatabaseAnnotationNameBuilder().buildJoinColumnAnnotationName(attributeName, foreignKey); - boolean printBase = (printRef || (joinColumnName != null)); - if (printBase || printRef) { - if (printJoinTableAnnotation.isTrue()) { - printJoinTableAnnotation.setFalse(); - pw.printAnnotation(JPA.JOIN_TABLE); - pw.print('('); - } else { - pw.print(','); - } - pw.println(); - pw.indent(); - if (printRef) { - // if 'printRef' is true, 'joinColumnName' will always be "IGNORED" (so we ignore it) - this.printJoinTableJoinColumnAnnotationsOn(elementName, foreignKey, pw); // [1] - } else { - // if the FK references a single-column PK, 'referencedColumnName' is not required - if (printBase) { - // there is only a single join column here (just not the default name) - pw.print(elementName); - pw.print('='); - this.printJoinColumnAnnotationOn(joinColumnName, null, pw); - } else { - // no JoinColumn annotation needed: the default 'name' and 'referencedColumnName' work - } - } - pw.undent(); - } - } - - /** - * 'elementName' is either "joinColumns" or "inverseJoinColumns" - */ - private void printJoinTableJoinColumnAnnotationsOn(String elementName, ForeignKey foreignKey, EntitySourceWriter pw) { - pw.print(elementName); - pw.print('='); - if (foreignKey.columnPairsSize() > 1) { - pw.print('{'); - pw.println(); - pw.indent(); - } - this.printJoinColumnAnnotationsOn(foreignKey, pw); - if (foreignKey.columnPairsSize() > 1) { - pw.undent(); - pw.println(); - pw.print('}'); - pw.println(); - } - } - - - // ********** non-owned many-to-many fields ********** - - private void printEntityNonOwnedManyToManyFieldsOn(EntitySourceWriter pw) { - for (Iterator<ManyToManyRelation> stream = this.genTable.nonOwnedManyToManyRelations(); stream.hasNext(); ) { - this.printEntityNonOwnedManyToManyFieldOn(stream.next(), pw); - } - } - - private void printEntityNonOwnedManyToManyFieldOn(ManyToManyRelation relation, EntitySourceWriter pw) { - String fieldName = this.genTable.getAttributeNameForNonOwned(relation); - if (this.config.fieldAccessType()) { - this.printNonOwnedManyToManyAnnotationOn(relation, pw); - } - this.printCollectionFieldOn(fieldName, this.fullyQualify(relation.getOwningEntityName()), pw); - } - - private void printNonOwnedManyToManyAnnotationOn(ManyToManyRelation relation, EntitySourceWriter pw) { - pw.printAnnotation(JPA.MANY_TO_MANY); - pw.print("(mappedBy=\""); //$NON-NLS-1$ - pw.print(relation.getMappedBy()); - pw.print("\")"); //$NON-NLS-1$ - pw.println(); - } - - - // ********** misc ********** - - private void printSerialVersionUIDFieldOn(EntitySourceWriter pw) { - if (this.config.generateSerialVersionUID()) { - pw.print("private static final long serialVersionUID = 1L;"); //$NON-NLS-1$ - pw.println(); - } - } - - private void printZeroArgumentConstructorOn(String ctorName, String visibility, EntitySourceWriter pw) { - if (this.config.generateDefaultConstructor()) { - pw.printVisibility(visibility); - pw.print(ctorName); - pw.print("() {"); //$NON-NLS-1$ - pw.println(); - pw.indent(); - pw.println("super();"); //$NON-NLS-1$ - pw.undent(); - pw.print('}'); - pw.println(); - pw.println(); - } - } - - - // ********** primary key properties ********** - - private void printEntityPrimaryKeyPropertiesOn(EntitySourceWriter pw) { - if (this.primaryKeyClassIsRequired() && this.config.generateEmbeddedIdForCompoundPK()) { - this.printEntityEmbeddedIdPrimaryKeyPropertyOn(pw); - } else { - this.printEntityReadOnlyPrimaryKeyPropertiesOn(pw); - this.printEntityWritablePrimaryKeyPropertiesOn(pw); - } - } - - private void printEntityEmbeddedIdPrimaryKeyPropertyOn(EntitySourceWriter pw) { - if (this.config.propertyAccessType()) { - pw.printAnnotation(JPA.EMBEDDED_ID); - pw.println(); - } - this.printPropertyOn(this.genTable.getAttributeNameForEmbeddedId(), this.pkClassName, pw); - } - - private void printEntityReadOnlyPrimaryKeyPropertiesOn(EntitySourceWriter pw) { - this.printPrimaryKeyPropertiesOn(pw, true, true); // true=read-only; true=print ID annotation on getters - } - - private void printEntityWritablePrimaryKeyPropertiesOn(EntitySourceWriter pw) { - this.printPrimaryKeyPropertiesOn(pw, false, true); // false=writable; true=print ID annotation on getters - } - - private void printPrimaryKeyPropertiesOn(EntitySourceWriter pw, boolean readOnly, boolean printIdAnnotation) { - for (Iterator<Column> stream = this.primaryKeyColumns(readOnly); stream.hasNext(); ) { - this.printPrimaryKeyPropertyOn(stream.next(), pw, readOnly, printIdAnnotation); - } - } - - // TODO if the property's type is java.util/sql.Date, it needs @Temporal(DATE) - // TODO if the primary key is auto-generated, the property must be an integral type - private void printPrimaryKeyPropertyOn(Column column, EntitySourceWriter pw, boolean readOnly, boolean printIdAnnotation) { - String propertyName = this.genTable.getAttributeNameFor(column); - if (this.config.propertyAccessType()) { - if (printIdAnnotation) { - pw.printAnnotation(JPA.ID); - pw.println(); - } - String columnName = this.config.getDatabaseAnnotationNameBuilder().buildColumnAnnotationName(propertyName, column); - if (readOnly) { - this.printReadOnlyColumnAnnotationOn(columnName, pw); - } else { - this.printColumnAnnotationOn(columnName, pw); - } - } - this.printPropertyOn(propertyName, column.getPrimaryKeyJavaTypeDeclaration(), pw); - } - - - // ********** basic properties ********** - - private void printEntityNonPrimaryKeyBasicPropertiesOn(EntitySourceWriter pw) { - for (Iterator<Column> stream = this.genTable.nonPrimaryKeyBasicColumns(); stream.hasNext(); ) { - this.printEntityNonPrimaryKeyBasicPropertyOn(stream.next(), pw); - } - } - - private void printEntityNonPrimaryKeyBasicPropertyOn(Column column, EntitySourceWriter pw) { - String propertyName = this.genTable.getAttributeNameFor(column); - if (this.config.propertyAccessType()) { - String columnName = this.config.getDatabaseAnnotationNameBuilder().buildColumnAnnotationName(propertyName, column); - this.printColumnAnnotationOn(columnName, pw); - } - this.printPropertyOn(propertyName, column.getJavaTypeDeclaration(), pw); - } - - - // ********** many-to-one properties ********** - - private void printEntityManyToOnePropertiesOn(EntitySourceWriter pw) { - for (Iterator<ManyToOneRelation> stream = this.genTable.manyToOneRelations(); stream.hasNext(); ) { - this.printEntityManyToOnePropertyOn(stream.next(), pw); - } - } - - private void printEntityManyToOnePropertyOn(ManyToOneRelation relation, EntitySourceWriter pw) { - String propertyName = this.genTable.getAttributeNameFor(relation); - if (this.config.propertyAccessType()) { - this.printManyToOneAnnotationOn(propertyName, relation, pw); - } - String typeDeclaration = this.fullyQualify(relation.getReferencedEntityName()); - this.printPropertyOn(propertyName, typeDeclaration, pw); - } - - - // ********** one-to-many properties ********** - - private void printEntityOneToManyPropertiesOn(EntitySourceWriter pw) { - for (Iterator<OneToManyRelation> stream = this.genTable.oneToManyRelations(); stream.hasNext(); ) { - this.printEntityOneToManyPropertyOn(stream.next(), pw); - } - } - - private void printEntityOneToManyPropertyOn(OneToManyRelation relation, EntitySourceWriter pw) { - String propertyName = this.genTable.getAttributeNameFor(relation); - if (this.config.propertyAccessType()) { - this.printOneToManyAnnotationOn(relation, pw); - } - String elementTypeDeclaration = this.fullyQualify(relation.getReferencedEntityName()); - this.printCollectionPropertyOn(propertyName, elementTypeDeclaration, pw); - } - - - // ********** owned many-to-many properties ********** - - private void printEntityOwnedManyToManyPropertiesOn(EntitySourceWriter pw) { - for (Iterator<ManyToManyRelation> stream = this.genTable.ownedManyToManyRelations(); stream.hasNext(); ) { - this.printEntityOwnedManyToManyPropertyOn(stream.next(), pw); - } - } - - private void printEntityOwnedManyToManyPropertyOn(ManyToManyRelation relation, EntitySourceWriter pw) { - String propertyName = this.genTable.getAttributeNameForOwned(relation); - if (this.config.propertyAccessType()) { - this.printOwnedManyToManyAnnotationOn(propertyName, relation, pw); - } - String elementTypeDeclaration = this.fullyQualify(relation.getNonOwningEntityName()); - this.printCollectionPropertyOn(propertyName, elementTypeDeclaration, pw); - } - - - // ********** non-owned many-to-many properties ********** - - private void printEntityNonOwnedManyToManyPropertiesOn(EntitySourceWriter pw) { - for (Iterator<ManyToManyRelation> stream = this.genTable.nonOwnedManyToManyRelations(); stream.hasNext(); ) { - this.printEntityNonOwnedManyToManyPropertyOn(stream.next(), pw); - } - } - - private void printEntityNonOwnedManyToManyPropertyOn(ManyToManyRelation relation, EntitySourceWriter pw) { - String propertyName = this.genTable.getAttributeNameForNonOwned(relation); - if (this.config.propertyAccessType()) { - this.printNonOwnedManyToManyAnnotationOn(relation, pw); - } - String elementTypeDeclaration = this.fullyQualify(relation.getOwningEntityName()); - this.printCollectionPropertyOn(propertyName, elementTypeDeclaration, pw); - } - - - // ********** compound primary key class ********** - - private void printPrimaryKeyClassOn(EntitySourceWriter pw) { - pw.println(); - if (this.config.generateEmbeddedIdForCompoundPK()) { - pw.printAnnotation(JPA.EMBEDDABLE); - pw.println(); - } - pw.print("public static class "); //$NON-NLS-1$ - pw.print(this.config.getPrimaryKeyMemberClassName()); - pw.print(" implements "); //$NON-NLS-1$ - pw.printTypeDeclaration(Serializable.class.getName()); - pw.print(" {"); //$NON-NLS-1$ - pw.println(); - - pw.indent(); - if (this.config.generateEmbeddedIdForCompoundPK()) { - this.printEmbeddableReadOnlyPrimaryKeyFieldsOn(pw); - this.printEmbeddableWritablePrimaryKeyFieldsOn(pw); - } else { - this.printIdFieldsOn(pw); - } - this.printSerialVersionUIDFieldOn(pw); - pw.println(); - this.printZeroArgumentConstructorOn(this.config.getPrimaryKeyMemberClassName(), "public", pw); //$NON-NLS-1$ - - if (this.config.propertyAccessType() || this.config.generateGettersAndSetters()) { - if (this.config.generateEmbeddedIdForCompoundPK()) { - this.printEmbeddableReadOnlyPrimaryKeyPropertiesOn(pw); - this.printEmbeddableWritablePrimaryKeyPropertiesOn(pw); - } else { - this.printIdPropertiesOn(pw); - } - } - - this.printPrimaryKeyEqualsMethodOn(this.config.getPrimaryKeyMemberClassName(), this.getTable().primaryKeyColumns(), pw); - this.printPrimaryKeyHashCodeMethodOn(this.getTable().primaryKeyColumns(), pw); - pw.undent(); - - pw.print('}'); - pw.println(); - pw.println(); - } - - - // ********** compound primary key class fields ********** - - private void printEmbeddableReadOnlyPrimaryKeyFieldsOn(EntitySourceWriter pw) { - this.printPrimaryKeyFieldsOn(pw, true, false); // true=read-only; false=do not print ID annotation on fields - } - - private void printEmbeddableWritablePrimaryKeyFieldsOn(EntitySourceWriter pw) { - this.printPrimaryKeyFieldsOn(pw, false, false); // false=writable; false=do not print ID annotation on fields - } - - private void printIdFieldsOn(EntitySourceWriter pw) { - for (Iterator<Column> stream = this.getTable().primaryKeyColumns(); stream.hasNext(); ) { - this.printIdFieldOn(stream.next(), pw); - } - } - - private void printIdFieldOn(Column column, EntitySourceWriter pw) { - this.printFieldOn(this.genTable.getAttributeNameFor(column), column.getPrimaryKeyJavaTypeDeclaration(), pw); - } - - - // ********** compound primary key class properties ********** - - private void printEmbeddableReadOnlyPrimaryKeyPropertiesOn(EntitySourceWriter pw) { - this.printPrimaryKeyPropertiesOn(pw, true, false); // true=read-only; false=do not print ID annotation on getters - } - - private void printEmbeddableWritablePrimaryKeyPropertiesOn(EntitySourceWriter pw) { - this.printPrimaryKeyPropertiesOn(pw, false, false); // false=writable; false=do not print ID annotation on getters - } - - private void printIdPropertiesOn(EntitySourceWriter pw) { - for (Iterator<Column> stream = this.getTable().primaryKeyColumns(); stream.hasNext(); ) { - this.printIdPropertyOn(stream.next(), pw); - } - } - - private void printIdPropertyOn(Column column, EntitySourceWriter pw) { - this.printPropertyOn(this.genTable.getAttributeNameFor(column), column.getPrimaryKeyJavaTypeDeclaration(), pw); - } - - - // ********** compound primary key class equals ********** - - private void printPrimaryKeyEqualsMethodOn(String className, Iterator<Column> columns, EntitySourceWriter pw) { - pw.printAnnotation("java.lang.Override"); //$NON-NLS-1$ - pw.println(); - - pw.println("public boolean equals(Object o) {"); //$NON-NLS-1$ - pw.indent(); - pw.println("if (o == this) {"); //$NON-NLS-1$ - pw.indent(); - pw.println("return true;"); //$NON-NLS-1$ - pw.undent(); - pw.print('}'); - pw.println(); - - pw.print("if ( ! (o instanceof "); //$NON-NLS-1$ - pw.print(className); - pw.print(")) {"); //$NON-NLS-1$ - pw.println(); - pw.indent(); - pw.println("return false;"); //$NON-NLS-1$ - pw.undent(); - pw.print('}'); - pw.println(); - - pw.print(className); - pw.print(" other = ("); //$NON-NLS-1$ - pw.print(className); - pw.print(") o;"); //$NON-NLS-1$ - pw.println(); - - pw.print("return "); //$NON-NLS-1$ - pw.indent(); - while (columns.hasNext()) { - this.printPrimaryKeyEqualsClauseOn(columns.next(), pw); - if (columns.hasNext()) { - pw.println(); - pw.print("&& "); //$NON-NLS-1$ - } - } - pw.print(';'); - pw.println(); - pw.undent(); - pw.undent(); - pw.print('}'); - pw.println(); - pw.println(); - } - - private void printPrimaryKeyEqualsClauseOn(Column column, EntitySourceWriter pw) { - String fieldName = this.genTable.getAttributeNameFor(column); - JavaType javaType = column.getPrimaryKeyJavaType(); - if (javaType.isPrimitive()) { - this.printPrimitiveEqualsClauseOn(fieldName, pw); - } else { - this.printReferenceEqualsClauseOn(fieldName, pw); - } - } - - private void printPrimitiveEqualsClauseOn(String fieldName, EntitySourceWriter pw) { - pw.print("(this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(" == other."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(')'); - } - - private void printReferenceEqualsClauseOn(String fieldName, EntitySourceWriter pw) { - pw.print("this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(".equals(other."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(')'); - } - - - // ********** compound primary key class hash code ********** - - private void printPrimaryKeyHashCodeMethodOn(Iterator<Column> columns, EntitySourceWriter pw) { - pw.printAnnotation("java.lang.Override"); //$NON-NLS-1$ - pw.println(); - - pw.println("public int hashCode() {"); //$NON-NLS-1$ - pw.indent(); - pw.println("final int prime = 31;"); //$NON-NLS-1$ - pw.println("int hash = 17;"); //$NON-NLS-1$ - while (columns.hasNext()) { - pw.print("hash = hash * prime + "); //$NON-NLS-1$ - this.printPrimaryKeyHashCodeClauseOn(columns.next(), pw); - pw.print(';'); - pw.println(); - } - pw.println("return hash;"); //$NON-NLS-1$ - pw.undent(); - pw.print('}'); - pw.println(); - pw.println(); - } - - private void printPrimaryKeyHashCodeClauseOn(Column column, EntitySourceWriter pw) { - String fieldName = this.genTable.getAttributeNameFor(column); - JavaType javaType = column.getPrimaryKeyJavaType(); - if (javaType.isPrimitive()) { - this.printPrimitiveHashCodeClauseOn(javaType.getElementTypeName(), fieldName, pw); - } else { - this.printReferenceHashCodeClauseOn(fieldName, pw); - } - } - - private void printPrimitiveHashCodeClauseOn(String primitiveName, String fieldName, EntitySourceWriter pw) { - if (primitiveName.equals("int")) { //$NON-NLS-1$ - // this.value - pw.print("this."); //$NON-NLS-1$ - pw.print(fieldName); - } else if (primitiveName.equals("short") //$NON-NLS-1$ - || primitiveName.equals("byte") //$NON-NLS-1$ - || primitiveName.equals("char")) { //$NON-NLS-1$ - // ((int) this.value) - explicit cast - pw.print("((int) this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(')'); - } else if (primitiveName.equals("long")) { // cribbed from Long#hashCode() //$NON-NLS-1$ - // ((int) (this.value ^ (this.value >>> 32))) - pw.print("((int) (this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(" ^ (this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(" >>> 32)))"); //$NON-NLS-1$ - } else if (primitiveName.equals("float")) { // cribbed from Float#hashCode() //$NON-NLS-1$ - // java.lang.Float.floatToIntBits(this.value) - pw.printTypeDeclaration("java.lang.Float"); //$NON-NLS-1$ - pw.print(".floatToIntBits(this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(')'); - } else if (primitiveName.equals("double")) { // cribbed from Double#hashCode() //$NON-NLS-1$ - // ((int) (java.lang.Double.doubleToLongBits(this.value) ^ (java.lang.Double.doubleToLongBits(this.value) >>> 32))) - pw.print("((int) ("); //$NON-NLS-1$ - pw.printTypeDeclaration("java.lang.Double"); //$NON-NLS-1$ - pw.print(".doubleToLongBits(this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(") ^ ("); //$NON-NLS-1$ - pw.printTypeDeclaration("java.lang.Double"); //$NON-NLS-1$ - pw.print(".doubleToLongBits(this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(") >>> 32)))"); //$NON-NLS-1$ - } else if (primitiveName.equals("boolean")) { //$NON-NLS-1$ - // (this.value ? 1 : 0) - pw.print("(this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(" ? 1 : 0)"); //$NON-NLS-1$ - } else { - throw new IllegalArgumentException(primitiveName); - } - } - - private void printReferenceHashCodeClauseOn(String fieldName, EntitySourceWriter pw) { - pw.print("this."); //$NON-NLS-1$ - pw.print(fieldName); - pw.print(".hashCode()"); //$NON-NLS-1$ - } - - - // ********** package and imports ********** - - private void printPackageAndImportsOn(PrintWriter pw, BodySource bodySource) { - if (this.getPackageName().length() != 0) { - pw.print("package "); //$NON-NLS-1$ - pw.print(this.getPackageName()); - pw.print(';'); - pw.println(); - pw.println(); - } - - for (Iterator<Map.Entry<String, String>> stream = bodySource.importEntries(); stream.hasNext(); ) { - Map.Entry<String, String> entry = stream.next(); - pw.print("import "); //$NON-NLS-1$ - pw.print(entry.getValue()); // package - pw.print('.'); - pw.print(entry.getKey()); // short class name - pw.print(';'); - pw.println(); - } - pw.println(); - } - - - // ********** fields ********** - - /** - * visibility is set in the config - */ - private void printFieldOn(String fieldName, String typeDeclaration, EntitySourceWriter pw) { - pw.printField( - fieldName, - typeDeclaration, - this.config.getFieldVisibilityClause() - ); - } - - /** - * visibility and collection type are set in the config - */ - private void printCollectionFieldOn(String fieldName, String elementTypeDeclaration, EntitySourceWriter pw) { - pw.printParameterizedField( - fieldName, - this.config.getCollectionTypeName(), - elementTypeDeclaration, - this.config.getFieldVisibilityClause() - ); - } - - - // ********** properties ********** - - /** - * visibility is set in the config - */ - private void printPropertyOn(String propertyName, String typeDeclaration, EntitySourceWriter pw) { - pw.printGetterAndSetter( - propertyName, - typeDeclaration, - this.config.getMethodVisibilityClause() - ); - } - - /** - * visibility and collection type are set in the config - */ - private void printCollectionPropertyOn(String propertyName, String elementTypeDeclaration, EntitySourceWriter pw) { - pw.printCollectionGetterAndSetter( - propertyName, - this.config.getCollectionTypeName(), - elementTypeDeclaration, - this.config.getMethodVisibilityClause() - ); - } - - - // ********** convenience methods ********** - - private String getPackageName() { - return this.packageFragment.getElementName(); - } - - private Table getTable() { - return this.genTable.getTable(); - } - - private String getEntityName() { - return this.genTable.getEntityName(); - } - - private boolean primaryKeyClassIsRequired() { - return this.getTable().primaryKeyColumnsSize() > 1; - } - - private String fullyQualify(String shortClassName) { - String pkg = this.getPackageName(); - return (pkg.length() == 0) ? shortClassName : pkg + '.' + shortClassName; - } - - @Override - public String toString() { - return StringTools.buildToStringFor(this, this.genTable.getName() + " => " + this.entityClassName); //$NON-NLS-1$ - } - - - // ********** source writer ********** - - private interface BodySource { - - /** - * return a sorted set of map entries; the key is the short class name, - * the value is the package name - */ - Iterator<Map.Entry<String, String>> importEntries(); - - /** - * return the body source code - */ - String getSource(); - - /** - * return the length of the body source code - */ - int length(); - - } - - /** - * Extend IndentingPrintWriter with some methods that facilitate building - * class source code. - */ - private static class EntitySourceWriter extends IndentingPrintWriter implements BodySource { - final String packageName; - final String className; - // key = short class name; value = package name - private final Map<String, String> imports = new HashMap<String, String>(); - - EntitySourceWriter(String packageName, String className) { - super(new StringWriter(20000)); - this.packageName = packageName; - this.className = className; - } - - /** - * Convert the specified string to a String Literal and print it, - * adding the surrounding double-quotes and escaping characters - * as necessary. - */ - void printStringLiteral(String string) { - StringTools.convertToJavaStringLiteralOn(string, this); - } - - void printVisibility(String visibilityModifier) { - if (visibilityModifier.length() != 0) { - this.print(visibilityModifier); - this.print(' '); - } - } - - void printAnnotation(String annotationName) { - this.print('@'); - this.printTypeDeclaration(annotationName); - } - - void printTypeDeclaration(String typeDeclaration) { - this.print(this.buildImportedTypeDeclaration(typeDeclaration)); - } - - /** - * Return the specified class's "imported" name. - * The class declaration must be of the form: - * "int" - * "int[]" (not "[I") - * "java.lang.Object" - * "java.lang.Object[]" (not "[Ljava.lang.Object;") - * "java.util.Map.Entry" (not "java.util.Map$Entry") - * "java.util.Map.Entry[][]" (not "[[Ljava.util.Map$Entry;") - */ - private String buildImportedTypeDeclaration(String typeDeclaration) { - if (this.typeDeclarationIsMemberClass(typeDeclaration)) { - // no need for an import, just return the partially-qualified name - return this.buildMemberClassTypeDeclaration(typeDeclaration); - } - int last = typeDeclaration.lastIndexOf('.'); - String pkg = (last == -1) ? "" : typeDeclaration.substring(0, last); //$NON-NLS-1$ - String shortTypeDeclaration = typeDeclaration.substring(last + 1); - String shortElementTypeName = shortTypeDeclaration; - while (shortElementTypeName.endsWith("[]")) { //$NON-NLS-1$ - shortElementTypeName = shortElementTypeName.substring(0, shortElementTypeName.length() - 2); - } - String prev = this.imports.get(shortElementTypeName); - if (prev == null) { - // this is the first class with this short element type name - this.imports.put(shortElementTypeName, pkg); - return shortTypeDeclaration; - } - if (prev.equals(pkg)) { - // this element type has already been imported - return shortTypeDeclaration; - } - // another class with the same short element type name has been - // previously imported, so this one must be used fully-qualified - return typeDeclaration; - } - - /** - * e.g. "foo.bar.Employee.PK" will return true - */ - private boolean typeDeclarationIsMemberClass(String typeDeclaration) { - return (typeDeclaration.length() > this.className.length()) - && typeDeclaration.startsWith(this.className) - && (typeDeclaration.charAt(this.className.length()) == '.'); - } - - /** - * e.g. "foo.bar.Employee.PK" will return "Employee.PK" - * this prevents collisions with other imported classes (e.g. "joo.jar.PK") - */ - private String buildMemberClassTypeDeclaration(String typeDeclaration) { - int index = this.packageName.length(); - if (index != 0) { - index++; // bump past the '.' - } - return typeDeclaration.substring(index); - } - - private Iterator<Map.Entry<String, String>> sortedImportEntries() { - TreeSet<Map.Entry<String, String>> sortedImports = new TreeSet<Map.Entry<String, String>>(this.buildImportEntriesComparator()); - sortedImports.addAll(this.imports.entrySet()); - return sortedImports.iterator(); - } - - private Comparator<Map.Entry<String, String>> buildImportEntriesComparator() { - return new Comparator<Map.Entry<String, String>>() { - public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) { - Collator collator = Collator.getInstance(); - int pkg = collator.compare(e1.getValue(), e2.getValue()); - return (pkg == 0) ? collator.compare(e1.getKey(), e2.getKey()) : pkg; - } - }; - } - - void printField(String fieldName, String typeDeclaration, String visibility) { - this.printVisibility(visibility); - this.printTypeDeclaration(typeDeclaration); - this.print(' '); - this.print(fieldName); - this.print(';'); - this.println(); - this.println(); - } - - void printParameterizedField(String fieldName, String typeDeclaration, String parameterTypeDeclaration, String visibility) { - this.printVisibility(visibility); - this.printTypeDeclaration(typeDeclaration); - this.print('<'); - this.printTypeDeclaration(parameterTypeDeclaration); - this.print('>'); - this.print(' '); - this.print(fieldName); - this.print(';'); - this.println(); - this.println(); - } - - void printGetterAndSetter(String propertyName, String typeDeclaration, String visibility) { - this.printGetter(propertyName, typeDeclaration, visibility); - this.println(); - this.println(); - - this.printSetter(propertyName, typeDeclaration, visibility); - this.println(); - this.println(); - } - - private void printGetter(String propertyName, String typeDeclaration, String visibility) { - this.printVisibility(visibility); - this.printTypeDeclaration(typeDeclaration); - this.print(' '); - this.print(typeDeclaration.equals("boolean") ? "is" : "get"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - this.print(StringTools.capitalize(propertyName)); - this.print("() {"); //$NON-NLS-1$ - this.println(); - - this.indent(); - this.print("return this."); //$NON-NLS-1$ - this.print(propertyName); - this.print(';'); - this.println(); - this.undent(); - - this.print('}'); - } - - private void printSetter(String propertyName, String typeDeclaration, String visibility) { - this.printVisibility(visibility); - this.print("void set"); //$NON-NLS-1$ - this.print(StringTools.capitalize(propertyName)); - this.print('('); - this.printTypeDeclaration(typeDeclaration); - this.print(' '); - this.print(propertyName); - this.print(") {"); //$NON-NLS-1$ - this.println(); - - this.indent(); - this.print("this."); //$NON-NLS-1$ - this.print(propertyName); - this.print(" = "); //$NON-NLS-1$ - this.print(propertyName); - this.print(';'); - this.println(); - this.undent(); - - this.print('}'); - } - - void printCollectionGetterAndSetter(String propertyName, String collectionTypeDeclaration, String elementTypeDeclaration, String visibility) { - this.printCollectionGetter(propertyName, collectionTypeDeclaration, elementTypeDeclaration, visibility); - this.println(); - this.println(); - - this.printCollectionSetter(propertyName, collectionTypeDeclaration, elementTypeDeclaration, visibility); - this.println(); - this.println(); - } - - private void printCollectionGetter(String propertyName, String collectionTypeDeclaration, String elementTypeDeclaration, String visibility) { - this.printVisibility(visibility); - this.printTypeDeclaration(collectionTypeDeclaration); - this.print('<'); - this.printTypeDeclaration(elementTypeDeclaration); - this.print("> get"); //$NON-NLS-1$ - this.print(StringTools.capitalize(propertyName)); - this.print("() {"); //$NON-NLS-1$ - this.println(); - - this.indent(); - this.print("return this."); //$NON-NLS-1$ - this.print(propertyName); - this.print(';'); - this.println(); - this.undent(); - - this.print('}'); - } - - private void printCollectionSetter(String propertyName, String collectionTypeDeclaration, String elementTypeDeclaration, String visibility) { - this.printVisibility(visibility); - this.print("void set"); //$NON-NLS-1$ - this.print(StringTools.capitalize(propertyName)); - this.print('('); - this.printTypeDeclaration(collectionTypeDeclaration); - this.print('<'); - this.printTypeDeclaration(elementTypeDeclaration); - this.print('>'); - this.print(' '); - this.print(propertyName); - this.print(") {"); //$NON-NLS-1$ - this.println(); - - this.indent(); - this.print("this."); //$NON-NLS-1$ - this.print(propertyName); - this.print(" = "); //$NON-NLS-1$ - this.print(propertyName); - this.print(';'); - this.println(); - this.undent(); - - this.print('}'); - } - - - // ********** BodySource implementation ********** - - public Iterator<Map.Entry<String, String>> importEntries() { - return new FilteringIterator<Map.Entry<String, String>, Map.Entry<String, String>>(this.sortedImportEntries()) { - @Override - protected boolean accept(Map.Entry<String, String> next) { - String pkg = next.getValue(); - if (pkg.equals("") //$NON-NLS-1$ - || pkg.equals("java.lang") //$NON-NLS-1$ - || pkg.equals(EntitySourceWriter.this.packageName)) { - return false; - } - return true; - } - }; - } - - public String getSource() { - return this.out.toString(); - } - - public int length() { - return ((StringWriter) this.out).getBuffer().length(); - } - - } - - - // ********** config ********** - - public static class Config { - private boolean convertToJavaStyleIdentifiers = true; - - private boolean propertyAccessType = false; // as opposed to "field" - - private String collectionTypeName = Set.class.getName(); - private String collectionAttributeNameSuffix = "Collection"; // e.g. "private Set<Foo> fooCollection" //$NON-NLS-1$ - - private int fieldVisibility = Modifier.PRIVATE; - private int methodVisibility = Modifier.PUBLIC; - - private boolean generateGettersAndSetters = true; - private boolean generateDefaultConstructor = true; - - private boolean serializable = true; - private boolean generateSerialVersionUID = true; - - private boolean generateEmbeddedIdForCompoundPK = true; // as opposed to IdClass - private String embeddedIdAttributeName = "pk"; //$NON-NLS-1$ - private String primaryKeyMemberClassName = "PK"; //$NON-NLS-1$ - - /** - * key = table - * value = entity name - */ - private HashMap<Table, String> tables = new HashMap<Table, String>(); - - private DatabaseAnnotationNameBuilder databaseAnnotationNameBuilder = DatabaseAnnotationNameBuilder.Default.INSTANCE; - - private OverwriteConfirmer overwriteConfirmer = OverwriteConfirmer.Never.INSTANCE; - - public static final int PRIVATE = 0; - public static final int PACKAGE = 1; - public static final int PROTECTED = 2; - public static final int PUBLIC = 3; - - - public boolean convertToJavaStyleIdentifiers() { - return this.convertToJavaStyleIdentifiers; - } - public void setConvertToJavaStyleIdentifiers(boolean convertToJavaStyleIdentifiers) { - this.convertToJavaStyleIdentifiers = convertToJavaStyleIdentifiers; - } - - public boolean propertyAccessType() { - return this.propertyAccessType; - } - public void setPropertyAccessType(boolean propertyAccessType) { - this.propertyAccessType = propertyAccessType; - } - - public boolean fieldAccessType() { - return ! this.propertyAccessType; - } - public void setFieldAccessType(boolean fieldAccessType) { - this.propertyAccessType = ! fieldAccessType; - } - - public String getCollectionTypeName() { - return this.collectionTypeName; - } - public void setCollectionTypeName(String collectionTypeName) { - this.checkRequiredString(collectionTypeName, "collection type name is required"); //$NON-NLS-1$ - this.collectionTypeName = collectionTypeName; - } - - public String getCollectionAttributeNameSuffix() { - return this.collectionAttributeNameSuffix; - } - public void setCollectionAttributeNameSuffix(String collectionAttributeNameSuffix) { - this.collectionAttributeNameSuffix = collectionAttributeNameSuffix; - } - - public int getFieldVisibility() { - return this.fieldVisibility; - } - /** entity fields cannot be 'public' */ - public void setFieldVisibility(int fieldVisibility) { - switch (fieldVisibility) { - case PRIVATE: - case PACKAGE: - case PROTECTED: - this.fieldVisibility = fieldVisibility; - break; - default: - throw new IllegalArgumentException("invalid field visibility: " + fieldVisibility); //$NON-NLS-1$ - } - } - String getFieldVisibilityClause() { - switch (this.fieldVisibility) { - case PRIVATE: - return "private"; //$NON-NLS-1$ - case PACKAGE: - return ""; //$NON-NLS-1$ - case PROTECTED: - return "protected"; //$NON-NLS-1$ - default: - throw new IllegalStateException("invalid field visibility: " + this.fieldVisibility); //$NON-NLS-1$ - } - } - - public int getMethodVisibility() { - return this.methodVisibility; - } - /** entity properties must be 'public' or 'protected' */ - public void setMethodVisibility(int methodVisibility) { - switch (methodVisibility) { - case PROTECTED: - case PUBLIC: - this.methodVisibility = methodVisibility; - break; - default: - throw new IllegalArgumentException("invalid method visibility: " + methodVisibility); //$NON-NLS-1$ - } - } - String getMethodVisibilityClause() { - switch (this.methodVisibility) { - case PROTECTED: - return "protected"; //$NON-NLS-1$ - case PUBLIC: - return "public"; //$NON-NLS-1$ - default: - throw new IllegalStateException("invalid method visibility: " + this.methodVisibility); //$NON-NLS-1$ - } - } - - public boolean generateGettersAndSetters() { - return this.generateGettersAndSetters; - } - public void setGenerateGettersAndSetters(boolean generateGettersAndSetters) { - this.generateGettersAndSetters = generateGettersAndSetters; - } - - public boolean generateDefaultConstructor() { - return this.generateDefaultConstructor; - } - public void setGenerateDefaultConstructor(boolean generateDefaultConstructor) { - this.generateDefaultConstructor = generateDefaultConstructor; - } - - public boolean serializable() { - return this.serializable; - } - public void setSerializable(boolean serializable) { - this.serializable = serializable; - } - - public boolean generateSerialVersionUID() { - return this.generateSerialVersionUID; - } - public void setGenerateSerialVersionUID(boolean generateSerialVersionUID) { - this.generateSerialVersionUID = generateSerialVersionUID; - } - - public boolean generateEmbeddedIdForCompoundPK() { - return this.generateEmbeddedIdForCompoundPK; - } - public void setGenerateEmbeddedIdForCompoundPK(boolean generateEmbeddedIdForCompoundPK) { - this.generateEmbeddedIdForCompoundPK = generateEmbeddedIdForCompoundPK; - } - - public boolean generateIdClassForCompoundPK() { - return ! this.generateEmbeddedIdForCompoundPK; - } - public void setGenerateIdClassForCompoundPK(boolean generateIdClassForCompoundPK) { - this.generateEmbeddedIdForCompoundPK = ! generateIdClassForCompoundPK; - } - - public String getEmbeddedIdAttributeName() { - return this.embeddedIdAttributeName; - } - public void setEmbeddedIdAttributeName(String embeddedIdAttributeName) { - this.checkRequiredString(embeddedIdAttributeName, "EmbeddedId attribute name is required"); //$NON-NLS-1$ - this.embeddedIdAttributeName = embeddedIdAttributeName; - } - - public String getPrimaryKeyMemberClassName() { - return this.primaryKeyMemberClassName; - } - public void setPrimaryKeyMemberClassName(String primaryKeyMemberClassName) { - this.checkRequiredString(primaryKeyMemberClassName, "primary key member class name is required"); //$NON-NLS-1$ - this.primaryKeyMemberClassName = primaryKeyMemberClassName; - } - - String getEntityName(Table table) { - return this.tables.get(table); - } - Iterator<Table> tables() { - return this.tables.keySet().iterator(); - } - int tablesSize() { - return this.tables.size(); - } - public void addTable(Table table, String entityName) { - if (table == null) { - throw new NullPointerException("table is required"); //$NON-NLS-1$ - } - this.checkRequiredString(entityName, "entity name is required"); //$NON-NLS-1$ - if (this.tables.containsKey(table)) { - throw new IllegalArgumentException("duplicate table: " + table.getName()); //$NON-NLS-1$ - } - if (this.tables.values().contains(entityName)) { - throw new IllegalArgumentException("duplicate entity name: " + entityName); //$NON-NLS-1$ - } - if ( ! NameTools.stringConsistsOfJavaIdentifierCharacters(entityName)) { - throw new IllegalArgumentException("entity name is not a valid Java identifier: " + entityName); //$NON-NLS-1$ - } - if (NameTools.JAVA_RESERVED_WORDS_SET.contains(entityName)) { - throw new IllegalArgumentException("entity name is a Java reserved word: " + entityName); //$NON-NLS-1$ - } - this.tables.put(table, entityName); - } - - public DatabaseAnnotationNameBuilder getDatabaseAnnotationNameBuilder() { - return this.databaseAnnotationNameBuilder; - } - public void setDatabaseAnnotationNameBuilder(DatabaseAnnotationNameBuilder databaseAnnotationNameBuilder) { - if (databaseAnnotationNameBuilder == null) { - throw new NullPointerException("database annotation name builder is required"); //$NON-NLS-1$ - } - this.databaseAnnotationNameBuilder = databaseAnnotationNameBuilder; - } - - public OverwriteConfirmer getOverwriteConfirmer() { - return this.overwriteConfirmer; - } - public void setOverwriteConfirmer(OverwriteConfirmer overwriteConfirmer) { - if (overwriteConfirmer == null) { - throw new NullPointerException("overwrite confirmer is required"); //$NON-NLS-1$ - } - this.overwriteConfirmer = overwriteConfirmer; - } - - private void checkRequiredString(String string, String message) { - if ((string == null) || (string.length() == 0)) { - throw new IllegalArgumentException(message); - } - } - - } - - - // ********** overwrite confirmer ********** - - public static interface OverwriteConfirmer { - /** - * Return whether the entity generator should overwrite the specified - * file. - */ - boolean overwrite(String className); - - - final class Always implements OverwriteConfirmer { - public static final OverwriteConfirmer INSTANCE = new Always(); - public static OverwriteConfirmer instance() { - return INSTANCE; - } - // ensure single instance - private Always() { - super(); - } - // everything will be overwritten - public boolean overwrite(String arg0) { - return true; - } - @Override - public String toString() { - return "OverwriteConfirmer.Always"; //$NON-NLS-1$ - } - } - - - final class Never implements OverwriteConfirmer { - public static final OverwriteConfirmer INSTANCE = new Never(); - public static OverwriteConfirmer instance() { - return INSTANCE; - } - // ensure single instance - private Never() { - super(); - } - // nothing will be overwritten - public boolean overwrite(String arg0) { - return false; - } - @Override - public String toString() { - return "OverwriteConfirmer.Never"; //$NON-NLS-1$ - } - } - - } - - - // ********** annotation name builder ********** - - /** - * Provide a pluggable way to determine whether and how the entity generator - * prints the names of various database objects. - */ - public static interface DatabaseAnnotationNameBuilder { - - /** - * Given the name of an entity and the table to which it is mapped, - * build and return a string to be used as the value for the entity's - * Table annotation's 'name' element. Return null if the entity - * maps to the table by default. - */ - String buildTableAnnotationName(String entityName, Table table); - - /** - * Given the name of an attribute (field or property) and the column - * to which it is mapped, - * build and return a string to be used as the value for the attribute's - * Column annotation's 'name' element. Return null if the attribute - * maps to the column by default. - */ - String buildColumnAnnotationName(String attributeName, Column column); - - /** - * Given the name of an attribute (field or property) and the - * many-to-one or many-to-many foreign key to which it is mapped, - * build and return a string to be used as the value for the attribute's - * JoinColumn annotation's 'name' element. Return null if the attribute - * maps to the join column by default. - * The specified foreign key consists of a single column pair whose - * referenced column is the single-column primary key of the foreign - * key's referenced table. - */ - String buildJoinColumnAnnotationName(String attributeName, ForeignKey foreignKey); - - /** - * Build and return a string to be used as the value for a JoinColumn - * annotation's 'name' or 'referencedColumnName' element. - * This is called for many-to-one and many-to-many mappings when - * the default join column name and/or referenced column name are/is - * not applicable. - * @see buildJoinColumnAnnotationName(String, ForeignKey) - */ - String buildJoinColumnAnnotationName(Column column); - - /** - * Build and return a string to be used as the value for a JoinTable - * annotation's 'name' element. - * This is called for many-to-many mappings when the default - * join table name is not applicable. - */ - String buildJoinTableAnnotationName(Table table); - - - /** - * The default implementation simple returns the database object's name, - * unaltered. - */ - final class Default implements DatabaseAnnotationNameBuilder { - public static final DatabaseAnnotationNameBuilder INSTANCE = new Default(); - public static DatabaseAnnotationNameBuilder instance() { - return INSTANCE; - } - // ensure single instance - private Default() { - super(); - } - public String buildTableAnnotationName(String entityName, Table table) { - return table.getName(); - } - public String buildColumnAnnotationName(String attributeName, Column column) { - return column.getName(); - } - public String buildJoinColumnAnnotationName(String attributeName, ForeignKey foreignKey) { - return foreignKey.getColumnPair().getBaseColumn().getName(); - } - public String buildJoinColumnAnnotationName(Column column) { - return column.getName(); - } - public String buildJoinTableAnnotationName(Table table) { - return table.getName(); - } - @Override - public String toString() { - return "DatabaseAnnotationNameBuilder.Default"; //$NON-NLS-1$ - } - } - - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/GenScope.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/GenScope.java deleted file mode 100644 index 4e524e6f68..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/GenScope.java +++ /dev/null @@ -1,186 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.SubMonitor; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.utility.internal.CollectionTools; -import org.eclipse.jpt.utility.internal.StringTools; -import org.eclipse.jpt.utility.internal.iterators.FilteringIterator; - -/** - * Build a GenTable for each db.Table passed in. - * Determine all the relations among the tables in the scope: - * many-to-many - * many-to-one - * one-to-many - * Make a first pass to determine each entity table's Java attribute names, - * because we will need them on subsequent passes. - */ -class GenScope { - private final EntityGenerator.Config entityConfig; - private final HashMap<Table, GenTable> genTables; - - - // ********** construction/initialization ********** - - GenScope(EntityGenerator.Config entityConfig, IProgressMonitor progressMonitor) { - super(); - this.entityConfig = entityConfig; - this.genTables = new HashMap<Table, GenTable>(entityConfig.tablesSize()); - SubMonitor sm = SubMonitor.convert(progressMonitor, JptGenMessages.GenScope_taskName, 4); - - this.buildGenTables(); - sm.worked(1); - this.checkCanceled(sm); - - this.buildManyToManyRelations(); - sm.worked(1); - this.checkCanceled(sm); - - this.buildManyToOneRelations(); // this will also build the corresponding one-to-many relations - sm.worked(1); - this.checkCanceled(sm); - - this.buildAttributeNames(); - sm.worked(1); - this.checkCanceled(sm); - } - - private void buildGenTables() { - for (Iterator<Table> stream = entityConfig.tables(); stream.hasNext(); ) { - Table table = stream.next(); - this.genTables.put(table, new GenTable(this, table)); - } - } - - /** - * find all the "join" tables - */ - private void buildManyToManyRelations() { - for (Iterator<GenTable> stream = this.genTables(); stream.hasNext(); ) { - stream.next().buildJoinTableRelation(); - } - - // revert any "join" table that is referenced by another table back to an "entity" table - HashSet<GenTable> referencedGenTables = this.buildReferencedGenTables(); - for (Iterator<GenTable> stream = this.joinGenTables(); stream.hasNext(); ) { - GenTable joinGenTable = stream.next(); - if (referencedGenTables.contains(joinGenTable)) { - joinGenTable.clearJoinTableRelation(); - } - } - } - - /** - * find all the many-to-one and corresponding one-to-many relations - */ - private void buildManyToOneRelations() { - for (Iterator<GenTable> stream = this.entityGenTables(); stream.hasNext(); ) { - stream.next().buildManyToOneRelations(); - } - } - - /** - * determine all the Java attribute names up-front because we will - * need them for things like 'mappedBy' annotation elements - */ - private void buildAttributeNames() { - for (Iterator<GenTable> stream = this.entityGenTables(); stream.hasNext(); ) { - stream.next().buildAttributeNames(); - } - } - - - // ********** package API ********** - - EntityGenerator.Config getEntityConfig() { - return this.entityConfig; - } - - /** - * return only the gen tables that are suitable for generating - * entities (i.e. exclude the "join" tables) - */ - Iterator<GenTable> entityGenTables() { - return new FilteringIterator<GenTable, GenTable>(this.genTables()) { - @Override - protected boolean accept(GenTable genTable) { - return ! genTable.isJoinTable(); - } - }; - } - - int entityTablesSize() { - return CollectionTools.size(this.entityGenTables()); - } - - /** - * return the gen table corresponding to the specified db table; - * return null if the gen table is not "in-scope" (e.g. a db foreign key - * might have a reference to a db table that was not included in the - * scope, so we won't have a corresponding gen table) - */ - GenTable getGenTable(Table table) { - return this.genTables.get(table); - } - - - // ********** internal methods ********** - - private Iterator<GenTable> genTables() { - return this.genTables.values().iterator(); - } - - private int genTablesSize() { - return this.genTables.size(); - } - - /** - * return only the "join" gen tables - */ - private Iterator<GenTable> joinGenTables() { - return new FilteringIterator<GenTable, GenTable>(this.genTables()) { - @Override - protected boolean accept(GenTable genTable) { - return genTable.isJoinTable(); - } - }; - } - - /** - * build a set of the gen tables that are referenced by other gen tables - * in the scope - */ - private HashSet<GenTable> buildReferencedGenTables() { - HashSet<GenTable> referencedGenTables = new HashSet<GenTable>(this.genTablesSize()); - for (Iterator<GenTable> stream = this.genTables(); stream.hasNext(); ) { - stream.next().addReferencedGenTablesTo(referencedGenTables); - } - return referencedGenTables; - } - - private void checkCanceled(IProgressMonitor progressMonitor) { - if (progressMonitor.isCanceled()) { - throw new OperationCanceledException(); - } - } - - @Override - public String toString() { - return StringTools.buildToStringFor(this, this.genTables); - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/GenTable.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/GenTable.java deleted file mode 100644 index c7fcb29f4c..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/GenTable.java +++ /dev/null @@ -1,377 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.utility.internal.CollectionTools; -import org.eclipse.jpt.utility.internal.NameTools; -import org.eclipse.jpt.utility.internal.StringTools; -import org.eclipse.jpt.utility.internal.iterators.FilteringIterator; - -/** - * associate a table with the various relations that will be used when - * generating the entity corresponding to the table - */ -class GenTable { - private final GenScope scope; - private final Table table; - - // these relations cannot be built until after we have built all the scope's tables - private ManyToManyRelation joinTableRelation; - private final ArrayList<ManyToManyRelation> ownedManyToManyRelations = new ArrayList<ManyToManyRelation>(); - private final ArrayList<ManyToManyRelation> nonOwnedManyToManyRelations = new ArrayList<ManyToManyRelation>(); - private final ArrayList<ManyToOneRelation> manyToOneRelations = new ArrayList<ManyToOneRelation>(); - private final ArrayList<OneToManyRelation> oneToManyRelations = new ArrayList<OneToManyRelation>(); - private final HashSet<Column> foreignKeyColumns = new HashSet<Column>(); - - private final HashSet<String> attributeNames = new HashSet<String>(); - private String attributeNameForEmbeddedId; - private final HashMap<Column, String> basicAttributeNames = new HashMap<Column, String>(); - private final HashMap<ManyToOneRelation, String> manyToOneAttributeNames = new HashMap<ManyToOneRelation, String>(); - private final HashMap<OneToManyRelation, String> oneToManyAttributeNames = new HashMap<OneToManyRelation, String>(); - private final HashMap<ManyToManyRelation, String> ownedManyToManyAttributeNames = new HashMap<ManyToManyRelation, String>(); - private final HashMap<ManyToManyRelation, String> nonOwnedManyToManyAttributeNames = new HashMap<ManyToManyRelation, String>(); - - - // ********** construction/initialization ********** - - GenTable(GenScope scope, Table table) { - super(); - this.scope = scope; - this.table = table; - } - - - // ********** package API ********** - - EntityGenerator.Config getEntityConfig() { - return this.scope.getEntityConfig(); - } - - /** - * examples: - * GenTable(FOO) => "FOO_COLLECTION" - * GenTable(foo) => "fooCollection" - * GenTable(Foo) => "FooCollection" - */ - String getCollectionAttributeName() { - String name = this.getName(); - String suffix = this.getEntityConfig().getCollectionAttributeNameSuffix(); - if (StringTools.stringIsUppercase(name)) { // hmmm ~bjv - suffix = '_' + suffix.toUpperCase(); - } - return name + suffix; - } - - /** - * determine whether the table is a "join" table within the table's scope; - * this can be removed, later, if we find another table references the, - * seemingly, join table - * @see #clearJoinTableRelation() (and callers) - */ - void buildJoinTableRelation() { - if ( ! this.table.isPossibleJoinTable()) { - return; // the table must have exactly 2 foreign keys - } - ForeignKey owningFK = this.table.getJoinTableOwningForeignKey(); - GenTable owningGenTable = this.scope.getGenTable(owningFK.getReferencedTable()); - if (owningGenTable == null) { - return; // both tables must be in the scope - } - ForeignKey nonOwningFK = this.table.getJoinTableNonOwningForeignKey(); - GenTable nonOwningGenTable = this.scope.getGenTable(nonOwningFK.getReferencedTable()); - if (nonOwningGenTable == null) { - return; // both tables must be in the scope - } - this.joinTableRelation = new ManyToManyRelation( - this, - owningFK, - owningGenTable, - nonOwningFK, - nonOwningGenTable - ); - } - - /** - * used by the scope to figure out whether "join" tables should be - * converted to "entity" tables - */ - void addReferencedGenTablesTo(Set<GenTable> referencedTables) { - for (Iterator<ForeignKey> stream = this.table.foreignKeys(); stream.hasNext(); ) { - ForeignKey fk = stream.next(); - GenTable genTable = this.scope.getGenTable(fk.getReferencedTable()); - if (genTable != null) { - referencedTables.add(genTable); - } - } - } - - /** - * the scope clears the join table relation if there are any references - * to the join table from other tables in the scope - */ - void clearJoinTableRelation() { - this.joinTableRelation.clear(); - this.joinTableRelation = null; - } - - /** - * find "in-scope" foreign keys - */ - void buildManyToOneRelations() { - for (Iterator<ForeignKey> stream = this.table.foreignKeys(); stream.hasNext(); ) { - ForeignKey fk = stream.next(); - GenTable referencedGenTable = this.scope.getGenTable(fk.getReferencedTable()); - if (referencedGenTable != null) { - this.manyToOneRelations.add(new ManyToOneRelation(this, fk, referencedGenTable)); - } - } - } - - /** - * now that all the relations are in place, we can configure the Java - * attribute names - */ - void buildAttributeNames() { - this.buildAttributeNameForEmbeddedId(); - - // gather up all the table's columns... - Set<Column> columns = CollectionTools.set(this.table.columns(), this.table.columnsSize()); - // ...remove the columns that belong exclusively to many-to-one foreign keys... - this.buildManyToOneAttributeNames(columns); - // ...and use the remaining columns to generate "basic" attribute names - this.buildBasicAttributeNames(columns); - - this.buildOneToManyAttributeNames(); - this.buildOwnedManyToManyAttributeNames(); - this.buildNonOwnedManyToManyAttributeNames(); - } - - /** - * return the columns that are part of the table's primary key - * but are also part of an "in-scope" foreign key - */ - Iterator<Column> readOnlyPrimaryKeyColumns() { - return new FilteringIterator<Column, Column>(this.table.primaryKeyColumns()) { - @Override - protected boolean accept(Column pkColumn) { - return pkColumn.isPartOfForeignKey(); - } - }; - } - - /** - * return the columns that are part of the table's primary key - * but are NOT part of any "in-scope" foreign key - */ - Iterator<Column> writablePrimaryKeyColumns() { - return new FilteringIterator<Column, Column>(this.table.primaryKeyColumns()) { - @Override - protected boolean accept(Column pkColumn) { - return ! pkColumn.isPartOfForeignKey(); - } - }; - } - - /** - * return the columns that NEITHER part of the table's primary key - * NOR part of any foreign key - */ - Iterator<Column> nonPrimaryKeyBasicColumns() { - return new FilteringIterator<Column, Column>(this.table.columns()) { - @Override - protected boolean accept(Column column) { - return ! (column.isPartOfPrimaryKey() || column.isPartOfForeignKey()); - } - }; - } - - Table getTable() { - return this.table; - } - - String getEntityName() { - return this.getEntityConfig().getEntityName(this.table); - } - - boolean isJoinTable() { - return this.joinTableRelation != null; - } - - void addOwnedManyToManyRelation(ManyToManyRelation relation) { - this.ownedManyToManyRelations.add(relation); - } - - void removeOwnedManyToManyRelation(ManyToManyRelation relation) { - this.ownedManyToManyRelations.remove(relation); - } - - void addNonOwnedManyToManyRelation(ManyToManyRelation relation) { - this.nonOwnedManyToManyRelations.add(relation); - } - - void removeNonOwnedManyToManyRelation(ManyToManyRelation relation) { - this.nonOwnedManyToManyRelations.remove(relation); - } - - void addOneToManyRelation(OneToManyRelation relation) { - this.oneToManyRelations.add(relation); - } - - Iterator<ManyToOneRelation> manyToOneRelations() { - return this.manyToOneRelations.iterator(); - } - - Iterator<OneToManyRelation> oneToManyRelations() { - return this.oneToManyRelations.iterator(); - } - - Iterator<ManyToManyRelation> ownedManyToManyRelations() { - return this.ownedManyToManyRelations.iterator(); - } - - Iterator<ManyToManyRelation> nonOwnedManyToManyRelations() { - return this.nonOwnedManyToManyRelations.iterator(); - } - - /** - * this will return null if we don't want an embedded id attribute - */ - String getAttributeNameForEmbeddedId() { - return this.attributeNameForEmbeddedId; - } - - String getAttributeNameFor(Column column) { - return this.basicAttributeNames.get(column); - } - - String getAttributeNameFor(ManyToOneRelation relation) { - return this.manyToOneAttributeNames.get(relation); - } - - String getAttributeNameFor(OneToManyRelation relation) { - return this.oneToManyAttributeNames.get(relation); - } - - String getAttributeNameForOwned(ManyToManyRelation relation) { - return this.ownedManyToManyAttributeNames.get(relation); - } - - String getAttributeNameForNonOwned(ManyToManyRelation relation) { - return this.nonOwnedManyToManyAttributeNames.get(relation); - } - - String getName() { - return this.table.getName(); - } - - boolean joinTableNameIsDefault() { - return this.table.joinTableNameIsDefault(); - } - - - // ********** internal API ********** - - /** - * if we are going to generate an EmbeddedId attribute, add its name to - * 'attributeNames' so we don't collide with it later, when generating - * attribute names for the columns etc. - */ - private void buildAttributeNameForEmbeddedId() { - if ((this.table.primaryKeyColumnsSize() > 1) && this.getEntityConfig().generateEmbeddedIdForCompoundPK()) { - this.attributeNameForEmbeddedId = this.configureAttributeName(this.getEntityConfig().getEmbeddedIdAttributeName()); - } - } - - /** - * While we are figuring out the names for the m:1 attributes, remove from the - * specified set of columns the columns that are only part of the foreign keys - * (leaving the remaining columns for basic attributes). - * Store the calculated names so we can get them back later, when we - * are generating source. - */ - private void buildManyToOneAttributeNames(Set<Column> columns) { - for (ManyToOneRelation relation : this.manyToOneRelations) { - CollectionTools.removeAll(columns, relation.getForeignKey().nonPrimaryKeyBaseColumns()); - CollectionTools.addAll(this.foreignKeyColumns, relation.getForeignKey().baseColumns()); - String attributeName = this.configureAttributeName(relation.getAttributeName()); - relation.setMappedBy(attributeName); - this.manyToOneAttributeNames.put(relation, attributeName); - } - } - - /** - * Build a unique attribute name for the specified "basic" columns, - * checking for name collisions. - * Store the calculated names so we can get them back later, when we - * are generating source. - */ - private void buildBasicAttributeNames(Set<Column> columns) { - for (Column column : columns) { - String attributeName = this.configureAttributeName(column.getName()); - this.basicAttributeNames.put(column, attributeName); - } - } - - private void buildOneToManyAttributeNames() { - for (OneToManyRelation relation : this.oneToManyRelations) { - String attributeName = this.configureAttributeName(relation.getAttributeName()); - this.oneToManyAttributeNames.put(relation, attributeName); - } - } - - private void buildOwnedManyToManyAttributeNames() { - for (ManyToManyRelation relation : this.ownedManyToManyRelations) { - String attributeName = this.configureAttributeName(relation.getOwnedAttributeName()); - relation.setMappedBy(attributeName); - this.ownedManyToManyAttributeNames.put(relation, attributeName); - } - } - - private void buildNonOwnedManyToManyAttributeNames() { - for (ManyToManyRelation relation : this.nonOwnedManyToManyRelations) { - String attributeName = this.configureAttributeName(relation.getNonOwnedAttributeName()); - this.nonOwnedManyToManyAttributeNames.put(relation, attributeName); - } - } - - /** - * Convert the specified attribute name to something unique for the entity, - * converting it to something Java-like if the config flag is set. - * Store the calculated name to prevent future name collisions. - */ - private String configureAttributeName(String attributeName) { - String result = attributeName; - if (this.getEntityConfig().convertToJavaStyleIdentifiers()) { - result = EntityGenTools.convertToUniqueJavaStyleAttributeName(result, this.attributeNames); - } else { - // first, convert the attribute name to a legal Java identifier - result = NameTools.convertToJavaIdentifier(result); - // then make sure it's unique - result = NameTools.uniqueNameForIgnoreCase(attributeName, this.attributeNames); - } - this.attributeNames.add(result); - return result; - } - - @Override - public String toString() { - return StringTools.buildToStringFor(this, this.table); - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/JPA.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/JPA.java deleted file mode 100644 index 59a042af87..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/JPA.java +++ /dev/null @@ -1,301 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - - -/** - * JPA Java-related stuff (annotations etc.) - * - * Provisional API: This interface is part of an interim API that is still - * under development and expected to change significantly before reaching - * stability. It is available at this early stage to solicit feedback from - * pioneering adopters on the understanding that any code that uses this API - * will almost certainly be broken (repeatedly) as the API evolves. - */ -@SuppressWarnings("nls") -public interface JPA { - - // JPA package - String PACKAGE = "javax.persistence"; - String PACKAGE_ = PACKAGE + '.'; - - - // ********** API ********** - - // JPA annotations - String ASSOCIATION_OVERRIDE = PACKAGE_ + "AssociationOverride"; - String ASSOCIATION_OVERRIDE__NAME = "name"; - String ASSOCIATION_OVERRIDE__JOIN_COLUMNS = "joinColumns"; - String ASSOCIATION_OVERRIDES = PACKAGE_ + "AssociationOverrides"; - String ASSOCIATION_OVERRIDES__VALUE = "value"; - String ATTRIBUTE_OVERRIDE = PACKAGE_ + "AttributeOverride"; - String ATTRIBUTE_OVERRIDE__NAME = "name"; - String ATTRIBUTE_OVERRIDE__COLUMN = "column"; - String ATTRIBUTE_OVERRIDES = PACKAGE_ + "AttributeOverrides"; - String ATTRIBUTE_OVERRIDES__VALUE = "value"; - String BASIC = PACKAGE_ + "Basic"; - String BASIC__FETCH = "fetch"; - String BASIC__OPTIONAL = "optional"; - String COLUMN = PACKAGE_ + "Column"; - String COLUMN__NAME = "name"; - String COLUMN__UNIQUE = "unique"; - String COLUMN__NULLABLE = "nullable"; - String COLUMN__INSERTABLE = "insertable"; - String COLUMN__UPDATABLE = "updatable"; - String COLUMN__COLUMN_DEFINITION = "columnDefinition"; - String COLUMN__TABLE = "table"; - String COLUMN__LENGTH = "length"; - String COLUMN__PRECISION = "precision"; - String COLUMN__SCALE = "scale"; - String COLUMN_RESULT = PACKAGE_ + "ColumnResult"; - String COLUMN_RESULT__NAME = "name"; - String DISCRIMINATOR_COLUMN = PACKAGE_ + "DiscriminatorColumn"; - String DISCRIMINATOR_COLUMN__NAME = "name"; - String DISCRIMINATOR_COLUMN__DISCRIMINATOR_TYPE = "discriminatorType"; - String DISCRIMINATOR_COLUMN__COLUMN_DEFINITION = "columnDefinition"; - String DISCRIMINATOR_COLUMN__LENGTH = "length"; - String DISCRIMINATOR_VALUE = PACKAGE_ + "DiscriminatorValue"; - String DISCRIMINATOR_VALUE__VALUE = "value"; - String EMBEDDABLE = PACKAGE_ + "Embeddable"; - String EMBEDDED = PACKAGE_ + "Embedded"; - String EMBEDDED_ID = PACKAGE_ + "EmbeddedId"; - String ENTITY = PACKAGE_ + "Entity"; - String ENTITY__NAME = "name"; - String ENTITY_LISTENERS = PACKAGE_ + "EntityListeners"; - String ENTITY_LISTENERS__VALUE = "value"; - String ENTITY_RESULT = PACKAGE_ + "EntityResult"; - String ENTITY_RESULT__ENTITY_CLASS = "entityClass"; - String ENTITY_RESULT__FIELDS = "fields"; - String ENTITY_RESULT__DISCRIMINATOR_COLUMN = "discriminatorColumn"; - String ENUMERATED = PACKAGE_ + "Enumerated"; - String ENUMERATED__VALUE = "value"; - String EXCLUDE_DEFAULT_LISTENERS = PACKAGE_ + "ExcludeDefaultListeners"; - String EXCLUDE_SUPERCLASS_LISTENERS = PACKAGE_ + "ExcludeSuperclassListeners"; - String FIELD_RESULT = PACKAGE_ + "FieldResult"; - String FIELD_RESULT__NAME = "name"; - String FIELD_RESULT__COLUMN = "column"; - String FLUSH_MODE = PACKAGE_ + "FlushMode"; - String FLUSH_MODE__VALUE = "value"; - String GENERATED_VALUE = PACKAGE_ + "GeneratedValue"; - String GENERATED_VALUE__STRATEGY = "strategy"; - String GENERATED_VALUE__GENERATOR = "generator"; - String ID = PACKAGE_ + "Id"; - String ID_CLASS = PACKAGE_ + "IdClass"; - String ID_CLASS__VALUE = "value"; - String INHERITANCE = PACKAGE_ + "Inheritance"; - String INHERITANCE__STRATEGY = "strategy"; - String JOIN_COLUMN = PACKAGE_ + "JoinColumn"; - String JOIN_COLUMN__NAME = "name"; - String JOIN_COLUMN__REFERENCED_COLUMN_NAME = "referencedColumnName"; - String JOIN_COLUMN__UNIQUE = "unique"; - String JOIN_COLUMN__NULLABLE = "nullable"; - String JOIN_COLUMN__INSERTABLE = "insertable"; - String JOIN_COLUMN__UPDATABLE = "updatable"; - String JOIN_COLUMN__COLUMN_DEFINITION = "columnDefinition"; - String JOIN_COLUMN__TABLE = "table"; - String JOIN_COLUMNS = PACKAGE_ + "JoinColumns"; - String JOIN_COLUMNS__VALUE = "value"; - String JOIN_TABLE = PACKAGE_ + "JoinTable"; - String JOIN_TABLE__NAME = "name"; - String JOIN_TABLE__CATALOG = "catalog"; - String JOIN_TABLE__SCHEMA = "schema"; - String JOIN_TABLE__JOIN_COLUMNS = "joinColumns"; - String JOIN_TABLE__INVERSE_JOIN_COLUMNS = "inverseJoinColumns"; - String JOIN_TABLE__UNIQUE_CONSTRAINTS = "uniqueConstraints"; - String LOB = PACKAGE_ + "Lob"; - String MANY_TO_MANY = PACKAGE_ + "ManyToMany"; - String MANY_TO_MANY__TARGET_ENTITY = "targetEntity"; - String MANY_TO_MANY__CASCADE = "cascade"; - String MANY_TO_MANY__FETCH = "fetch"; - String MANY_TO_MANY__MAPPED_BY = "mappedBy"; - String MANY_TO_ONE = PACKAGE_ + "ManyToOne"; - String MANY_TO_ONE__TARGET_ENTITY = "targetEntity"; - String MANY_TO_ONE__CASCADE = "cascade"; - String MANY_TO_ONE__FETCH = "fetch"; - String MANY_TO_ONE__OPTIONAL = "optional"; - String MAP_KEY = PACKAGE_ + "MapKey"; - String MAP_KEY__NAME = "name"; - String MAPPED_SUPERCLASS = PACKAGE_ + "MappedSuperclass"; - String NAMED_NATIVE_QUERIES = PACKAGE_ + "NamedNativeQueries"; - String NAMED_NATIVE_QUERIES__VALUE = "value"; - String NAMED_NATIVE_QUERY = PACKAGE_ + "NamedNativeQuery"; - String NAMED_NATIVE_QUERY__NAME = "name"; - String NAMED_NATIVE_QUERY__QUERY = "query"; - String NAMED_NATIVE_QUERY__HINTS = "hints"; - String NAMED_NATIVE_QUERY__RESULT_CLASS = "resultClass"; - String NAMED_NATIVE_QUERY__RESULT_SET_MAPPING = "resultSetMapping"; - String NAMED_QUERIES = PACKAGE_ + "NamedQueries"; - String NAMED_QUERIES__VALUE = "value"; - String NAMED_QUERY = PACKAGE_ + "NamedQuery"; - String NAMED_QUERY__NAME = "name"; - String NAMED_QUERY__QUERY = "query"; - String NAMED_QUERY__HINTS = "hints"; - String ONE_TO_MANY = PACKAGE_ + "OneToMany"; - String ONE_TO_MANY__TARGET_ENTITY = "targetEntity"; - String ONE_TO_MANY__CASCADE = "cascade"; - String ONE_TO_MANY__FETCH = "fetch"; - String ONE_TO_MANY__MAPPED_BY = "mappedBy"; - String ONE_TO_ONE = PACKAGE_ + "OneToOne"; - String ONE_TO_ONE__TARGET_ENTITY = "targetEntity"; - String ONE_TO_ONE__CASCADE = "cascade"; - String ONE_TO_ONE__FETCH = "fetch"; - String ONE_TO_ONE__OPTIONAL = "optional"; - String ONE_TO_ONE__MAPPED_BY = "mappedBy"; - String ORDER_BY = PACKAGE_ + "OrderBy"; - String ORDER_BY__VALUE = "value"; - String PERSISTENCE_CONTEXT = PACKAGE_ + "PersistenceContext"; - String PERSISTENCE_CONTEXT__NAME = "name"; - String PERSISTENCE_CONTEXT__UNIT_NAME = "unitName"; - String PERSISTENCE_CONTEXT__TYPE = "type"; - String PERSISTENCE_CONTEXTS = PACKAGE_ + "PersistenceContexts"; - String PERSISTENCE_CONTEXTS__VALUE = "value"; - String PERSISTENCE_UNIT = PACKAGE_ + "XmlPersistenceUnit"; - String PERSISTENCE_UNIT__NAME = "name"; - String PERSISTENCE_UNIT__UNIT_NAME = "unitName"; - String PERSISTENCE_UNITS = PACKAGE_ + "PersistenceUnits"; - String PERSISTENCE_UNITS__VALUE = "value"; - String POST_LOAD = PACKAGE_ + "PostLoad"; - String POST_PERSIST = PACKAGE_ + "PostPersist"; - String POST_REMOVE = PACKAGE_ + "PostRemove"; - String POST_UPDATE = PACKAGE_ + "PostUpdate"; - String PRE_PERSIST = PACKAGE_ + "PrePersist"; - String PRE_REMOVE = PACKAGE_ + "PreRemove"; - String PRE_UPDATE = PACKAGE_ + "PreUpdate"; - String PRIMARY_KEY_JOIN_COLUMN = PACKAGE_ + "PrimaryKeyJoinColumn"; - String PRIMARY_KEY_JOIN_COLUMN__NAME = "name"; - String PRIMARY_KEY_JOIN_COLUMN__REFERENCED_COLUMN_NAME = "referencedColumnName"; - String PRIMARY_KEY_JOIN_COLUMN__COLUMN_DEFINITION = "columnDefinition"; - String PRIMARY_KEY_JOIN_COLUMNS = PACKAGE_ + "PrimaryKeyJoinColumns"; - String PRIMARY_KEY_JOIN_COLUMNS__VALUE = "value"; - String QUERY_HINT = PACKAGE_ + "QueryHint"; - String QUERY_HINT__NAME = "name"; - String QUERY_HINT__VALUE = "value"; - String SECONDARY_TABLE = PACKAGE_ + "SecondaryTable"; - String SECONDARY_TABLE__NAME = "name"; - String SECONDARY_TABLE__CATALOG = "catalog"; - String SECONDARY_TABLE__SCHEMA = "schema"; - String SECONDARY_TABLE__PK_JOIN_COLUMNS = "pkJoinColumns"; - String SECONDARY_TABLE__UNIQUE_CONSTRAINTS = "uniqueConstraints"; - String SECONDARY_TABLES = PACKAGE_ + "SecondaryTables"; - String SECONDARY_TABLES__VALUE = "value"; - String SEQUENCE_GENERATOR = PACKAGE_ + "SequenceGenerator"; - String SEQUENCE_GENERATOR__NAME = "name"; - String SEQUENCE_GENERATOR__SEQUENCE_NAME = "sequenceName"; - String SEQUENCE_GENERATOR__INITIAL_VALUE = "initialValue"; - String SEQUENCE_GENERATOR__ALLOCATION_SIZE = "allocationSize"; - String SQL_RESULT_SET_MAPPING = PACKAGE_ + "SqlResultSetMapping"; - String SQL_RESULT_SET_MAPPING__NAME = "name"; - String SQL_RESULT_SET_MAPPING__ENTITIES = "entities"; - String SQL_RESULT_SET_MAPPING__COLUMNS = "columns"; - String TABLE = PACKAGE_ + "Table"; - String TABLE__NAME = "name"; - String TABLE__CATALOG = "catalog"; - String TABLE__SCHEMA = "schema"; - String TABLE__UNIQUE_CONSTRAINTS = "uniqueConstraints"; - String TABLE_GENERATOR = PACKAGE_ + "TableGenerator"; - String TABLE_GENERATOR__NAME = "name"; - String TABLE_GENERATOR__TABLE = "table"; - String TABLE_GENERATOR__CATALOG = "catalog"; - String TABLE_GENERATOR__SCHEMA = "schema"; - String TABLE_GENERATOR__PK_COLUMN_NAME = "pkColumnName"; - String TABLE_GENERATOR__VALUE_COLUMN_NAME = "valueColumnName"; - String TABLE_GENERATOR__PK_COLUMN_VALUE = "pkColumnValue"; - String TABLE_GENERATOR__INITIAL_VALUE = "initialValue"; - String TABLE_GENERATOR__ALLOCATION_SIZE = "allocationSize"; - String TABLE_GENERATOR__UNIQUE_CONSTRAINTS = "uniqueConstraints"; - String TEMPORAL = PACKAGE_ + "Temporal"; - String TEMPORAL__VALUE = "value"; - String TRANSIENT = PACKAGE_ + "Transient"; - String UNIQUE_CONSTRAINT = PACKAGE_ + "UniqueConstraint"; - String UNIQUE_CONSTRAINT__COLUMN_NAMES = "columnNames"; - String VERSION = PACKAGE_ + "Version"; - - // JPA enums - String GENERATION_TYPE = PACKAGE_ + "GenerationType"; - String GENERATION_TYPE_ = GENERATION_TYPE + '.'; - String GENERATION_TYPE__AUTO = GENERATION_TYPE_ + "AUTO"; - String GENERATION_TYPE__IDENTITY = GENERATION_TYPE_ + "IDENTITY"; - String GENERATION_TYPE__SEQUENCE = GENERATION_TYPE_ + "SEQUENCE"; - String GENERATION_TYPE__TABLE = GENERATION_TYPE_ + "TABLE"; - - String CASCADE_TYPE = PACKAGE_ + "CascadeType"; - String CASCADE_TYPE_ = CASCADE_TYPE + '.'; - String CASCADE_TYPE__ALL = CASCADE_TYPE_ + "ALL"; - String CASCADE_TYPE__MERGE = CASCADE_TYPE_ + "MERGE"; - String CASCADE_TYPE__PERSIST = CASCADE_TYPE_ + "PERSIST"; - String CASCADE_TYPE__REFRESH = CASCADE_TYPE_ + "REFRESH"; - String CASCADE_TYPE__REMOVE = CASCADE_TYPE_ + "REMOVE"; - - String DISCRIMINATOR_TYPE = PACKAGE_ + "DiscriminatorType"; - String DISCRIMINATOR_TYPE_ = DISCRIMINATOR_TYPE + '.'; - String DISCRIMINATOR_TYPE__CHAR = DISCRIMINATOR_TYPE_ + "CHAR"; - String DISCRIMINATOR_TYPE__INTEGER = DISCRIMINATOR_TYPE_ + "INTEGER"; - String DISCRIMINATOR_TYPE__STRING = DISCRIMINATOR_TYPE_ + "STRING"; - - String ENUM_TYPE = PACKAGE_ + "EnumType"; - String ENUM_TYPE_ = ENUM_TYPE + '.'; - String ENUM_TYPE__ORDINAL = ENUM_TYPE_ + "ORDINAL"; - String ENUM_TYPE__STRING = ENUM_TYPE_ + "STRING"; - - String FETCH_TYPE = PACKAGE_ + "FetchType"; - String FETCH_TYPE_ = FETCH_TYPE + '.'; - String FETCH_TYPE__EAGER = FETCH_TYPE_ + "EAGER"; - String FETCH_TYPE__LAZY = FETCH_TYPE_ + "LAZY"; - - String FLUSH_MODE_TYPE = PACKAGE_ + "FlushModeType"; - String FLUSH_MODE_TYPE_ = FLUSH_MODE_TYPE + '.'; - String FLUSH_MODE_TYPE__AUTO = FLUSH_MODE_TYPE_ + "AUTO"; - String FLUSH_MODE_TYPE__COMMIT = FLUSH_MODE_TYPE_ + "COMMIT"; - - String INHERITANCE_TYPE = PACKAGE_ + "InheritanceType"; - String INHERITANCE_TYPE_ = INHERITANCE_TYPE + '.'; - String INHERITANCE_TYPE__JOINED = INHERITANCE_TYPE_ + "JOINED"; - String INHERITANCE_TYPE__SINGLE_TABLE = INHERITANCE_TYPE_ + "SINGLE_TABLE"; - String INHERITANCE_TYPE__TABLE_PER_CLASS = INHERITANCE_TYPE_ + "TABLE_PER_CLASS"; - - String PERSISTENCE_CONTEXT_TYPE = PACKAGE_ + "PersistenceContextType"; - String PERSISTENCE_CONTEXT_TYPE_ = PERSISTENCE_CONTEXT_TYPE + '.'; - String PERSISTENCE_CONTEXT_TYPE__EXTENDED = PERSISTENCE_CONTEXT_TYPE_ + "EXTENDED"; - String PERSISTENCE_CONTEXT_TYPE__TRANSACTION = PERSISTENCE_CONTEXT_TYPE_ + "TRANSACTION"; - - String TEMPORAL_TYPE = PACKAGE_ + "TemporalType"; - String TEMPORAL_TYPE_ = TEMPORAL_TYPE + '.'; - String TEMPORAL_TYPE__DATE = TEMPORAL_TYPE_ + "DATE"; - String TEMPORAL_TYPE__TIME = TEMPORAL_TYPE_ + "TIME"; - String TEMPORAL_TYPE__TIMESTAMP = TEMPORAL_TYPE_ + "TIMESTAMP"; - - // JPA interfaces - String ENTITY_MANAGER = PACKAGE_ + "EntityManager"; - String ENTITY_MANAGER_FACTORY = PACKAGE_ + "EntityManagerFactory"; - String ENTITY_TRANSACTION = PACKAGE_ + "EntityTransaction"; - String INSTRUMENTABLE_CLASS_LOADER = PACKAGE_ + "InstrumentableClassLoader"; - String QUERY = PACKAGE_ + "Query"; - - // JPA classes - String PERSISTENCE = PACKAGE_ + "XmlPersistence"; - - // JPA exceptions - String NON_UNIQUE_RESULT_EXCEPTION = PACKAGE_ + "NonUniqueResultException"; - String OBJECT_NOT_FOUND_EXCEPTION = PACKAGE_ + "ObjectNotFoundException"; - String PERSISTENCE_EXCEPTION = PACKAGE_ + "PersistenceException"; - - - // ********** SPI ********** - - // JPA SPI package - String SPI_PACKAGE = PACKAGE_ + "spi"; - String SPI_PACKAGE_ = SPI_PACKAGE + '.'; - - // JPA SPI interfaces - String ENTITY_MANAGER_FACTORY_PROVIDER = SPI_PACKAGE_ + "EntityManagerFactoryProvider"; - String PERSISTENCE_INFO = SPI_PACKAGE_ + "PersistenceInfo"; - String PERSISTENCE_PROVIDER = SPI_PACKAGE_ + "PersistenceProvider"; - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/JptGenMessages.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/JptGenMessages.java deleted file mode 100644 index b765abd340..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/JptGenMessages.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - -import org.eclipse.osgi.util.NLS; - -/** - * Localized messages used by Dali entity generation. - */ -class JptGenMessages { - - public static String PackageGenerator_taskName; - public static String GenScope_taskName; - public static String EntityGenerator_taskName; - public static String Templates_notFound; - - private static final String BUNDLE_NAME = "jpt_gen"; //$NON-NLS-1$ - private static final Class<?> BUNDLE_CLASS = JptGenMessages.class; - static { - NLS.initializeMessages(BUNDLE_NAME, BUNDLE_CLASS); - } - - private JptGenMessages() { - throw new UnsupportedOperationException(); - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ManyToManyRelation.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ManyToManyRelation.java deleted file mode 100644 index 12631a5bf0..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ManyToManyRelation.java +++ /dev/null @@ -1,111 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.utility.internal.StringTools; - -/** - * This object is shared by the two gen tables that make up the relation. - * Upon construction, 'mappedBy' will be 'null'. The first gen table to be - * used to generate an entity will fill in 'mappedBy' with the appropriate - * attribute (field/property) name. - */ -class ManyToManyRelation { - private final GenTable joinGenTable; - private final ForeignKey owningForeignKey; - private final GenTable owningGenTable; - private final ForeignKey nonOwningForeignKey; - private final GenTable nonOwningGenTable; - private String mappedBy; // set while generating entities - - - ManyToManyRelation( - GenTable joinGenTable, - ForeignKey owningForeignKey, - GenTable owningGenTable, - ForeignKey nonOwningForeignKey, - GenTable nonOwningGenTable - ) { - super(); - this.joinGenTable = joinGenTable; - - this.owningForeignKey = owningForeignKey; - this.owningGenTable = owningGenTable; - owningGenTable.addOwnedManyToManyRelation(this); - - this.nonOwningForeignKey = nonOwningForeignKey; - this.nonOwningGenTable = nonOwningGenTable; - nonOwningGenTable.addNonOwnedManyToManyRelation(this); - } - - GenTable getJoinGenTable() { - return this.joinGenTable; - } - - ForeignKey getOwningForeignKey() { - return this.owningForeignKey; - } - - GenTable getOwningGenTable() { - return this.owningGenTable; - } - - ForeignKey getNonOwningForeignKey() { - return this.nonOwningForeignKey; - } - - GenTable getNonOwningGenTable() { - return this.nonOwningGenTable; - } - - String getOwnedAttributeName() { - return this.nonOwningGenTable.getCollectionAttributeName(); - } - - String getNonOwnedAttributeName() { - return this.owningGenTable.getCollectionAttributeName(); - } - - /** - * the scope clears the join table relation if there are any references - * to the join table - */ - void clear() { - this.owningGenTable.removeOwnedManyToManyRelation(this); - this.nonOwningGenTable.removeNonOwnedManyToManyRelation(this); - } - - String getMappedBy() { - return this.mappedBy; - } - - void setMappedBy(String mappedBy) { - this.mappedBy = mappedBy; - } - - String getOwningEntityName() { - return this.owningGenTable.getEntityName(); - } - - String getNonOwningEntityName() { - return this.nonOwningGenTable.getEntityName(); - } - - boolean joinTableNameIsDefault() { - return this.joinGenTable.joinTableNameIsDefault(); - } - - @Override - public String toString() { - return StringTools.buildToStringFor(this, this.joinGenTable); - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ManyToOneRelation.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ManyToOneRelation.java deleted file mode 100644 index b69e402a06..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ManyToOneRelation.java +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.utility.internal.StringTools; - -/** - * This object is held by the "base" gen table and, indirectly via a - * one-to-many relation, the "referenced" gen table. - * The "mapped by" attribute (field/property) name is set while the - * "base" table is calculating its attribute names. - */ -class ManyToOneRelation { - private final GenTable baseGenTable; // the "many" side (e.g. Detail) - private final ForeignKey foreignKey; - private final GenTable referencedGenTable; // the "one" side (e.g. Master) - private String mappedBy; // set while generating entities; used by partner one-to-many relation - - - ManyToOneRelation( - GenTable baseGenTable, - ForeignKey foreignKey, - GenTable referencedGenTable - ) { - super(); - this.baseGenTable = baseGenTable; - this.foreignKey = foreignKey; - this.referencedGenTable = referencedGenTable; - referencedGenTable.addOneToManyRelation(new OneToManyRelation(this)); - } - - GenTable getBaseGenTable() { - return this.baseGenTable; - } - - ForeignKey getForeignKey() { - return this.foreignKey; - } - - GenTable getReferencedGenTable() { - return this.referencedGenTable; - } - - String getAttributeName() { - return this.foreignKey.getAttributeName(); - } - - String getMappedBy() { - return this.mappedBy; - } - - void setMappedBy(String mappedBy) { - this.mappedBy = mappedBy; - } - - String getBaseEntityName() { - return this.baseGenTable.getEntityName(); - } - - String getReferencedEntityName() { - return this.referencedGenTable.getEntityName(); - } - - String getBaseGenTableCollectionAttributeName() { - return this.baseGenTable.getCollectionAttributeName(); - } - - @Override - public String toString() { - return StringTools.buildToStringFor(this, this.foreignKey); - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/OneToManyRelation.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/OneToManyRelation.java deleted file mode 100644 index 8d832ccd1c..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/OneToManyRelation.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - -import org.eclipse.jpt.utility.internal.StringTools; - -/** - * This object is the inverse of the corresponding many-to-one relation. - */ -class OneToManyRelation { - private final ManyToOneRelation manyToOneRelation; - - - OneToManyRelation(ManyToOneRelation manyToOneRelation) { - super(); - this.manyToOneRelation = manyToOneRelation; - } - - ManyToOneRelation getManyToOneRelation() { - return this.manyToOneRelation; - } - - String getAttributeName() { - return this.manyToOneRelation.getBaseGenTableCollectionAttributeName(); - } - - String getMappedBy() { - return this.manyToOneRelation.getMappedBy(); - } - - String getReferencedEntityName() { - return this.manyToOneRelation.getBaseEntityName(); - } - - @Override - public String toString() { - return StringTools.buildToStringFor(this, this.manyToOneRelation); - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/PackageGenerator.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/PackageGenerator.java deleted file mode 100644 index 0aa0b5ed7e..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/PackageGenerator.java +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal; - -import java.util.Iterator; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.SubMonitor; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jpt.utility.internal.StringTools; - -/** - * This generator will generate a package of entities for a set of tables. - */ -public class PackageGenerator { - private final Config config; - private final EntityGenerator.Config entityConfig; - private final GenScope scope; - - - // ********** public API ********** - - public static void generateEntities( - Config config, - EntityGenerator.Config entityConfig, - IProgressMonitor progressMonitor - ) { - if ((config == null) || (entityConfig == null)) { - throw new NullPointerException(); - } - SubMonitor sm = SubMonitor.convert(progressMonitor, JptGenMessages.PackageGenerator_taskName, 100); - new PackageGenerator(config, entityConfig, sm.newChild(10)).generateEntities(sm.newChild(90)); - } - - - // ********** construction/initialization ********** - - private PackageGenerator( - Config config, - EntityGenerator.Config entityConfig, - IProgressMonitor progressMonitor - ) { - super(); - this.config = config; - this.entityConfig = entityConfig; - this.scope = new GenScope(entityConfig, progressMonitor); - } - - - // ********** generation ********** - - private void generateEntities(IProgressMonitor progressMonitor) { - SubMonitor sm = SubMonitor.convert(progressMonitor, this.scope.entityTablesSize()); - for (Iterator<GenTable> stream = this.scope.entityGenTables(); stream.hasNext(); ) { - this.checkCanceled(sm); - this.generateEntity(stream.next(), sm.newChild(1)); - } - } - - private void generateEntity(GenTable genTable, IProgressMonitor progressMonitor) { - EntityGenerator.generateEntity( - this.entityConfig, - this.config.getPackageFragment(), - genTable, - progressMonitor - ); - } - - private void checkCanceled(IProgressMonitor progressMonitor) { - if (progressMonitor.isCanceled()) { - throw new OperationCanceledException(); - } - } - - @Override - public String toString() { - return StringTools.buildToStringFor(this, this.scope); - } - - - // ********** config ********** - - public static class Config { - private IPackageFragment packageFragment; - - public IPackageFragment getPackageFragment() { - return this.packageFragment; - } - - public void setPackageFragment(IPackageFragment packageFragment) { - this.packageFragment = packageFragment; - } - - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/Association.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/Association.java deleted file mode 100644 index 47cad90794..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/Association.java +++ /dev/null @@ -1,388 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import java.util.List; - -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.gen.internal2.util.StringUtil; - -/** - * Represents an ORM association. - * There are two types of associations: - * <ul><li>simple association: An association between two database tables. - * The <em>referrer</code> table is the one containing the foreign key - * , the <em>referenced</code> table is the other party.<br> - * - * <li>many to many association: An association between two tables joined by - * a <em>join table</em>. - * In the example AUTHOR, BOOK, AUTHOR_BOOK, The referrer and referenced are - * AUTHOR and BOOK, and the join table is AUTHOR_BOOK. - * </ul> - * - */ -public class Association implements java.io.Serializable -{ - private final static long serialVersionUID = 2; - - public static final String MANY_TO_ONE = "many-to-one"; - public static final String MANY_TO_MANY = "many-to-many"; - public static final String ONE_TO_ONE = "one-to-one"; - public static final String ONE_TO_MANY = "one-to-many"; - - public static final String BI_DI = "bi-di"; - public static final String NORMAL_DI = "normal-di"; //referrer->referenced - public static final String OPPOSITE_DI = "opposite-di"; //referenced->referrer - - private transient ORMGenCustomizer mCustomizer; - private String mReferrerTableName; - private String mReferencedTableName; - private String mJoinTableName; - - private List<String> mReferrerColNames; /*String objects*/ - private List<String> mReferencedColNames; /*String objects*/ - private List<String> mReferrerJoinColNames; /*String objects*/ - private List<String> mReferencedJoinColNames; /*String objects*/ - - private transient List<ORMGenColumn> mReferrerCols; /*ORMGenColumn objects*/ - private transient List<ORMGenColumn> mReferencedCols; /*ORMGenColumn objects*/ - private transient List<ORMGenColumn> mReferrerJoinCols; /*ORMGenColumn objects*/ - private transient List<ORMGenColumn> mReferencedJoinCols; /*ORMGenColumn objects*/ - - private String mCardinality; - private String mDirectionality; - private byte mFlags = GENERATED; - - private AssociationRole mReferrerRole; - private AssociationRole mReferencedRole; - - private transient ForeignKey mForeignKey; - - /*constants for mFlags*/ - /*whether the association should be generated*/ - private static final byte GENERATED = 1 << 0; - /*whether the association is custom (i.e is not auto computed from foreign keys relationships).*/ - private static final byte CUSTOM = 1 << 1; - - /** - * The simple association constructor. - * The 2 tables are joined when the values of each column in - * referrerColNames match its corresponding column in referencedColNames. - * - * @param referrerTableName The "foreign key" table. - * @param referrerColNames The column names in the referrer table. - * @param referencedTableName The "primary key" table. - * @param referencedColNames The column names in the referenced table. - */ - public Association(ORMGenCustomizer customizer, String referrerTableName, List<String> referrerColNames - , String referencedTableName, List<String> referencedColNames) { - super(); - - mCustomizer = customizer; - mReferrerTableName = referrerTableName; - mReferencedTableName = referencedTableName; - mReferrerColNames = referrerColNames; - mReferencedColNames = referencedColNames; - - mCardinality = MANY_TO_ONE; - mDirectionality = BI_DI; - - setCustom(true); - } - /** - * The many to many constructor. - * The 2 tables are joined when the values of each column in - * referrerColNames match its corresponding column in referrerJoinColNames - * , and each column in referencedColNames match its corresponding column in referencedJoinColNames. - * - */ - public Association(ORMGenCustomizer customizer, String referrerTableName, List<String> referrerColNames - , String referencedTableName, List<String> referencedColNames - , String joinTableName, List<String> referrerJoinColNames, List<String> referencedJoinColNames) { - super(); - - mCustomizer = customizer; - mReferrerTableName = referrerTableName; - mReferencedTableName = referencedTableName; - mReferrerColNames = referrerColNames; - mReferencedColNames = referencedColNames; - mJoinTableName = joinTableName; - mReferrerJoinColNames = referrerJoinColNames; - mReferencedJoinColNames = referencedJoinColNames; - - mCardinality = MANY_TO_MANY; - mDirectionality = BI_DI; - - setCustom(true); - } - /** - * Empty constructor needed by the deserialization (should not be used otherwise). - */ - public Association() { - } - /** - * Computes the cardinality basedon the forign key definitions. - */ - public void computeCardinality() { - /*by default the association is many-to-one unless the foreign key - * is also the primary key, in which case it is a one-to-one.*/ - mCardinality = MANY_TO_ONE; - - List<ORMGenColumn> referrerCols = getReferrerColumns(); - List<ORMGenColumn> pkCols = getReferrerTable().getPrimaryKeyColumns(); - if (pkCols.size() == referrerCols.size()) { - boolean isFkPk = true; - for (int i = 0, n = pkCols.size(); i < n; ++i) { - if (!((ORMGenColumn)pkCols.get(i)).getName().equals(((ORMGenColumn)referrerCols.get(i)).getName())) { - isFkPk = false; - break; - } - } - if (isFkPk) { - mCardinality = ONE_TO_ONE; - } - } - - setCustom(false); - } - /** - * Called after the asscociations are deserialized to attach - * the customizer object. - */ - protected void restore(ORMGenCustomizer customizer) { - mCustomizer = customizer; - - if (mReferrerRole != null) { - mReferrerRole.restore(this); - } - if (mReferencedRole != null) { - mReferencedRole.restore(this); - } - } - public ORMGenTable getReferrerTable() { - return mCustomizer.getTable(mReferrerTableName); - } - public String getReferrerTableName() { - return mReferrerTableName; - } - public ORMGenTable getReferencedTable() { - return mCustomizer.getTable(mReferencedTableName); - } - public String getReferencedTableName() { - return mReferencedTableName; - } - public ORMGenTable getJoinTable() { - return mCustomizer.getTable(mJoinTableName); - } - public String getJoinTableName() { - return mJoinTableName; - } - /** - * Returns the <code>ORMGenColumn</code> objects for the referrer - * columns. - */ - public List<ORMGenColumn> getReferrerColumns() { - if (mReferrerCols == null) { - ORMGenTable referrerTable = getReferrerTable(); - mReferrerCols = referrerTable.getColumnsByNames(mReferrerColNames); - } - return mReferrerCols; - } - public List<String> getReferrerColumnNames() { - return mReferrerColNames; - } - /** - * Returns the <code>ORMGenColumn</code> objects for the referenced - * columns. - */ - public List<ORMGenColumn> getReferencedColumns() { - if (mReferencedCols == null) { - mReferencedCols = getReferencedTable().getColumnsByNames(mReferencedColNames); - } - return mReferencedCols; - } - public List<String> getReferencedColumnNames() { - return mReferencedColNames; - } - public List<ORMGenColumn> getReferrerJoinColumns() { - if (mReferrerJoinCols == null) { - mReferrerJoinCols = getJoinTable().getColumnsByNames(mReferrerJoinColNames); - } - return mReferrerJoinCols; - } - public List<String> getReferrerJoinColumnNames() { - return mReferrerJoinColNames; - } - public List<ORMGenColumn> getReferencedJoinColumns() { - if (mReferencedJoinCols == null) { - mReferencedJoinCols = getJoinTable().getColumnsByNames(mReferencedJoinColNames); - } - return mReferencedJoinCols; - } - public List<String> getReferencedJoinColumnNames() { - return mReferencedJoinColNames; - } - /** - * Returns the association cardinality, one of {@link #MANY_TO_ONE}|{@link #MANY_TO_MANY} - * |{@link #ONE_TO_ONE}|{@link #ONE_TO_MANY} - */ - public String getCardinality() { - return mCardinality; - } - public void setCardinality(String cardinality) { - assert(cardinality.equals(MANY_TO_ONE) || cardinality.equals(MANY_TO_MANY) || cardinality.equals(ONE_TO_ONE) || cardinality.equals(ONE_TO_MANY)); - mCardinality = cardinality; - } - /** - * Returns the association directionality, one of {@link #BI_DI}|{@link #NORMAL_DI} - * |{@link #OPPOSITE_DI} - */ - public String getDirectionality() { - return mDirectionality; - } - public void setDirectionality(String dir) { - assert(dir.equals(BI_DI) || dir.equals(NORMAL_DI) || dir.equals(OPPOSITE_DI)); - if (!dir.equals(mDirectionality)) { - mDirectionality = dir; - - if (dir.equals(NORMAL_DI)) { - mReferencedRole = null; - } else if (dir.equals(OPPOSITE_DI)) { - mReferrerRole = null; - } - } - } - - /** - * Tests whether this association is bidirectional. - * This is a shortcut for <code>getDirectionality().equals(BI_DI)</code>. - */ - public boolean isBidirectional() { - return mDirectionality.equals(BI_DI); - } - /** - * Returns true of this association should be generated. - */ - public boolean isGenerated() { - return (mFlags & GENERATED) != 0; - } - public void setGenerated(boolean generated) { - if (generated != isGenerated()) { - if (generated) { - mFlags |= GENERATED; - } else { - mFlags &= ~GENERATED; - } - mReferrerRole = mReferencedRole = null; - } - } - /** - * Returns true of this association is custom (i.e is not auto computed from foreign keys relationships). - */ - public boolean isCustom() { - return (mFlags & CUSTOM) != 0; - } - public void setCustom(boolean custom) { - if (custom) { - mFlags |= CUSTOM; - } else { - mFlags &= ~CUSTOM; - } - } - /** - * Returns the association role for the referrer side, or null - * if none (i.e if the directionality does not include it). - */ - public AssociationRole getReferrerRole() { - if (mReferrerRole == null && isGenerated()) { - if (!getDirectionality().equals(OPPOSITE_DI)) { //BI_DI or NORMAL_DI - mReferrerRole = new AssociationRole(this, true/*isReferrerEnd*/); - } - } - return mReferrerRole; - } - /** - * Returns the association role for the referenced side, or null - * if none (i.e if the directionality does not include it). - */ - public AssociationRole getReferencedRole() { - if (mReferencedRole == null && isGenerated()) { - if (!getDirectionality().equals(Association.NORMAL_DI)) { //BI_DI or OPPOSITE_DI - mReferencedRole = new AssociationRole(this, false/*isReferrerEnd*/); - } - } - return mReferencedRole; - } - /** - * Tests whether this association is valid (valid table and column names). - */ - protected boolean isValid(){ - if (!isValidTableAndColumns(mReferrerTableName, mReferrerColNames) - || !isValidTableAndColumns(mReferencedTableName, mReferencedColNames)) { - return false; - } - if (mJoinTableName != null) { - if (!isValidTableAndColumns(mJoinTableName, mReferrerJoinColNames) - || !isValidTableAndColumns(mJoinTableName, mReferencedJoinColNames)) { - return false; - } - } - return true; - } - private boolean isValidTableAndColumns(String tableName, List<String> columnNames) { - ORMGenTable table = mCustomizer.getTable(tableName); - if (table == null) { - return false; - } - for (int i = 0, n = columnNames.size(); i < n; ++i) { - String colName = (String)columnNames.get(i); - if (table.getColumnByName(colName) == null) { - return false; - } - } - return true; - } - - public void setForeignKey(ForeignKey foreignKey) { - this.mForeignKey = foreignKey; - - } - public ForeignKey getForeignKey(){ - return this.mForeignKey; - }; - public boolean equals(Object obj) { - if( this == obj ) - return true; - if( obj instanceof Association ){ - Association association2 = (Association)obj; - if (!this.getReferrerTableName().equals(association2.getReferrerTableName()) - || !this.getReferencedTableName().equals(association2.getReferencedTableName()) - || !StringUtil.equalObjects(this.getJoinTableName(), association2.getJoinTableName()) - || !this.getReferrerColumnNames().equals(association2.getReferrerColumnNames()) - || !this.getReferencedColumnNames().equals(association2.getReferencedColumnNames()) - ) { - return false; - } - /*the 2 association have the same referrer, referenced and join table*/ - //If MTO or OTM association - if (this.getJoinTableName() == null) { - return true; - } - if (this.getReferrerJoinColumnNames().equals(association2.getReferrerJoinColumnNames()) - && this.getReferencedJoinColumnNames().equals(association2.getReferencedJoinColumnNames())) { - return true; - } - } - return false; - } - public String toString(){ - return mReferrerTableName + " " + mCardinality + " " + mReferencedTableName ; - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/AssociationRole.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/AssociationRole.java deleted file mode 100644 index 375a93bbce..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/AssociationRole.java +++ /dev/null @@ -1,273 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import java.util.Iterator; -import java.util.List; - -/** - * Represents an association role (the referrer or referenced role). - * - */ -public class AssociationRole implements java.io.Serializable -{ - private transient Association mAssociation; //transient: see restore - private boolean mIsReferrerRole; - private String mPropertyName; - private String mCascade; - - private final static long serialVersionUID = 1; - - AssociationRole(Association association, boolean isReferrerRole) { - super(); - - mAssociation = association; - mIsReferrerRole = isReferrerRole; - } - - /** - * Empty constructor needed by the deserialization (should not be used otherwise). - */ - public AssociationRole() { - } - - /** - * Called after the asscociations are deserialized to attach - * the customizer object. - */ - protected void restore(Association association) { - mAssociation = association; - } - - public Association getAssociation() { - return mAssociation; - } - - public boolean isReferrerRole() { - return mIsReferrerRole; - } - - /** - * Returns the opposite role or null if the association - * is not bi directional. - */ - public AssociationRole getOppositeRole() { - Association association = getAssociation(); - if (!association.getDirectionality().equals(Association.BI_DI)) { - return null; - } - if (isReferrerRole()) { - return association.getReferencedRole(); - } else { - return association.getReferrerRole(); - } - } - - /** - * Returns the association cardinality, one of {@link #MANY_TO_ONE}|{@link #MANY_TO_MANY} - * |{@link #ONE_TO_ONE}|{@link #ONE_TO_MANY} - */ - public String getCardinality() { - String type = mAssociation.getCardinality(); - if (!mIsReferrerRole) { - if (type.equals(Association.ONE_TO_MANY)) { - type = Association.MANY_TO_ONE; - } else if (type.equals(Association.MANY_TO_ONE)) { - type = Association.ONE_TO_MANY; - } - } - return type; - } - - public ORMGenTable getReferrerTable() { - if (mIsReferrerRole) { - return mAssociation.getReferrerTable(); - } else { - return mAssociation.getReferencedTable(); - } - } - - public List<ORMGenColumn> getReferrerColumns(){ - if (mIsReferrerRole) { - return mAssociation.getReferrerColumns(); - } else { - return mAssociation.getReferencedColumns(); - } - } - - /** - * Returns the referenced column corresponding to a referrer column. - */ - public ORMGenColumn getReferencedColumn(String referrerColumn) { - boolean hasJoinTable = mAssociation.getJoinTable() != null; - List<ORMGenColumn> referrerColumns = getReferrerColumns(); - for (int i = 0, n = referrerColumns.size(); i < n; ++i) { - ORMGenColumn column = referrerColumns.get(i); - if (column.getName().equals(referrerColumn)) { - if (hasJoinTable) { - return getReferrerJoinColumns().get(i); - } else { - return getReferencedColumns().get(i); - } - } - } - assert(false); - return null; - } - - /** - * Returns the referrer column corresponding to a referenced column. - */ - public ORMGenColumn getReferrerColumn(String referencedColumn) { - boolean hasJoinTable = mAssociation.getJoinTable() != null; - List<ORMGenColumn> referencedColumns = getReferencedColumns(); - for (int i = 0, n = referencedColumns.size(); i < n; ++i) { - ORMGenColumn column = referencedColumns.get(i); - if (column.getName().equals(referencedColumn)) { - if (hasJoinTable) { - return getReferencedJoinColumns().get(i); - } else { - return getReferrerColumns().get(i); - } - } - } - assert(false); - return null; - } - - public ORMGenTable getReferencedTable() { - if (mIsReferrerRole) { - return mAssociation.getReferencedTable(); - } else { - return mAssociation.getReferrerTable(); - } - } - - public List<ORMGenColumn> getReferencedColumns() { - if (mIsReferrerRole) { - return mAssociation.getReferencedColumns(); - } else { - return mAssociation.getReferrerColumns(); - } - } - - public List<ORMGenColumn> getReferrerJoinColumns() { - if (mIsReferrerRole) { - return mAssociation.getReferrerJoinColumns(); - } else { - return mAssociation.getReferencedJoinColumns(); - } - } - public List<ORMGenColumn> getReferencedJoinColumns() { - if (mIsReferrerRole) { - return mAssociation.getReferencedJoinColumns(); - } else { - return mAssociation.getReferrerJoinColumns(); - } - } - - /** - * Returns the name that should be used by the generator for - * the property corresponding to this role. - */ - public String getPropertyName() { - if (mPropertyName != null) { //if the user explicitly set it then don't be too smart - return mPropertyName; - } - return getDefaultPropertyName(); - } - - private String getDefaultPropertyName() { - String propName = ""; - ORMGenTable referrerTable = getReferrerTable(); - ORMGenTable referencedTable = getReferencedTable(); - - boolean isSingular = isSingular(); - propName = referencedTable.getVarName(isSingular); - - List<AssociationRole> clashingRoles = new java.util.ArrayList<AssociationRole>(); //roles with our same referrer and referenced tables (i.e would yield the same property name in the same bean) - /*make sure there is no role with the same name.*/ - for (Iterator<AssociationRole> iter = referrerTable.getAssociationRoles().iterator(); iter.hasNext(); ) { - AssociationRole role = iter.next(); - if (role.getReferrerTable().getName().equals(referrerTable.getName()) - && role.getReferencedTable().getName().equals(referencedTable.getName()) - && role.isSingular() == isSingular) { - clashingRoles.add(role); - } - } - if (clashingRoles.size() > 1) { - int index = clashingRoles.indexOf(this); - assert(index >= 0); - propName += index+1; - } - - /*make sure there is no column with the same name.*/ - for (Iterator<ORMGenColumn> iter = referrerTable.getColumns().iterator(); iter.hasNext(); ) { - ORMGenColumn column = iter.next(); - if (column.getPropertyName().equals(propName)) { - String prefix = isSingular ? "Bean" : "Set"; - propName += prefix; - break; - } - } - - return propName; - } - - private boolean isSingular() { - String cardinality = getCardinality(); - return cardinality.equals(Association.ONE_TO_ONE) || cardinality.equals(Association.MANY_TO_ONE); - } - - /** - * Changes the name that should be used by the generator for - * the property corresponding to this role. - * If the argument name is null or empty string then the - * default computed name is used. - */ - public void setPropertyName(String name) { - if (name != null && name.length() == 0) { - name = null; - } - if (name != null && name.equals(getDefaultPropertyName())) { - name = null; - } - mPropertyName = name; - } - - /** - * Returns the cascade value for this role, or null if none. - */ - public String getCascade() { - return mCascade; - } - - public void setCascade(String cascade) { - if (cascade != null && cascade.length() == 0) { - cascade = null; - } - mCascade = cascade; - } - - /** - * Returns a descriptive string used in a comment in the generated - * file (from the Velocity template). - */ - public String getDescription() { - //<!-- $directionality $cardinality association to $referencedClassName --> - String directionality; - if (getAssociation().getDirectionality().equals(Association.BI_DI)) { - directionality = "bi-directional"; - } else { - directionality = "uni-directional"; - } - return directionality + " " + getAssociation().getCardinality() + " association to " + getReferencedTable().getClassName(); - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/BaseEntityGenCustomizer.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/BaseEntityGenCustomizer.java deleted file mode 100644 index c7701bd9e1..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/BaseEntityGenCustomizer.java +++ /dev/null @@ -1,229 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import java.io.File; -import java.util.List; -import java.util.Set; -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.Schema; -import org.eclipse.jpt.gen.internal2.util.DTPUtil; -import org.eclipse.jpt.gen.internal2.util.StringUtil; - -/** - * Default implementation of ORMGenCustomizer according to JPA specification for - * entity generation. - * - * This is used to retrieve/change the properties from the wizard and is also - * passed as a context object to Velocity. - */ -public class BaseEntityGenCustomizer extends ORMGenCustomizer - implements java.io.Serializable -{ - private final static long serialVersionUID = 1; - - /* mapping kinds */ - private static final String BASIC_MAPPING_KIND = "basic"; //$NON-NLS-1$ - private static final String ID_MAPPING_KIND = "id"; //$NON-NLS-1$ - private static final String VERSION_MAPPING_KIND = "version"; //$NON-NLS-1$ - - /* - * the strings for generator names. These appear in a combo box and used by - * the Velocity template processing. - */ - private static final String AUTO_GENERATOR = "auto"; //$NON-NLS-1$ - private static final String NONE_GENERATOR = "none"; //$NON-NLS-1$ - private static final String IDENTITY_GENERATOR = "identity"; //$NON-NLS-1$ - private static final String SEQUENCE_GENERATOR = "sequence"; //$NON-NLS-1$ - private static final String TABLE_GENERATOR = "table"; //$NON-NLS-1$ - - public BaseEntityGenCustomizer() { - super(); - } - - @Override - public void init(File file, Schema schema) { - super.init(file, schema); - } - - // ----------------------------------------- - // ------ ORMGenCustomizer methods - // ----------------------------------------- - @Override - public List<String> getAllIdGenerators() { - List<String> result = new java.util.ArrayList<String>(5); - /* add in the order in which they would appear in the combo */ - result.add(AUTO_GENERATOR); - result.add(IDENTITY_GENERATOR); - result.add(SEQUENCE_GENERATOR); - result.add(TABLE_GENERATOR); - result.add(NONE_GENERATOR); - return result; - } - - @Override - public String getNoIdGenerator() { - return NONE_GENERATOR; - } - - @Override - public String getIdentityIdGenerator() { - return IDENTITY_GENERATOR; - } - - @Override - public Set<String> getSequenceIdGenerators() { - Set<String> result = new java.util.HashSet<String>(3); - result.add(SEQUENCE_GENERATOR); - return result; - } - - @Override - public String getPropertyTypeFromColumn(Column column) { - return DTPUtil.getJavaType(getSchema(), column); - } - - @Override - @SuppressWarnings("nls") - public String[] getAllPropertyTypes() { - /* - * Java primitive types, wrapper of the primitive types , - * java.lang.String, java.math.BigInteger, java.math.BigDecimal, - * java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, - * java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and - * any other type that implements Serializable. - */ - // return in the order that will be used in the combo - return new String[] { - "boolean", - "Boolean", - "byte", - "Byte", - "byte[]", - "char", - "char[]", - "Character", - "Character[]", - "double", - "Double", - "float", - "Float", - "int", - "Integer", - "long", - "Long", - "Object", - "short", - "Short", - "String", - java.math.BigDecimal.class.getName(), - java.math.BigInteger.class.getName(), - java.util.Calendar.class.getName(), - java.util.Date.class.getName(), - java.sql.Date.class.getName(), - java.sql.Time.class.getName(), - java.sql.Timestamp.class.getName() - }; - } - - @Override - public String[] getAllMappingKinds() { - return new String[] { - BASIC_MAPPING_KIND, ID_MAPPING_KIND, VERSION_MAPPING_KIND - }; - } - - /* - * (non-Javadoc) - */ - @Override - public String getBasicMappingKind() { - return BASIC_MAPPING_KIND; - } - - /* - * (non-Javadoc) - */ - @Override - public String getIdMappingKind() { - return ID_MAPPING_KIND; - } - - @Override - public boolean editCascade(AssociationRole role) { - return false; - } - - @Override - protected boolean manySideIsAssociationOwner() { - return true; - } - - // ----------------------------------------- - // ---- Velocity templates methods - // ----------------------------------------- - /** - * Returns the cascades annotation member value, or empty string if none. - * Empty string is returned instead of null because Velocity does not like - * null when used in #set. - */ - public String genCascades(AssociationRole role) { - List<String> cascades = StringUtil.strToList(role.getCascade(), ',', true/* trim */); - if (cascades == null) { - return ""; //$NON-NLS-1$ - } - StringBuffer buffer = new StringBuffer('{'); - for (int i = 0, n = cascades.size(); i < n; ++i) { - String cascade = cascades.get(i); - String enumStr; - if (cascade.equals(TagNames.ALL_CASCADE)) { - enumStr = "CascadeType.ALL"; //$NON-NLS-1$ - } - else if (cascade.equals(TagNames.PERSIST_CASCADE)) { - enumStr = "CascadeType.PERSIST"; //$NON-NLS-1$ - } - else if (cascade.equals(TagNames.MERGE_CASCADE)) { - enumStr = "CascadeType.MERGE"; //$NON-NLS-1$ - } - else if (cascade.equals(TagNames.REMOVE_CASCADE)) { - enumStr = "CascadeType.REMOVE"; //$NON-NLS-1$ - } - else { - assert (cascade.equals(TagNames.REFRESH_CASCADE)); - enumStr = "CascadeType.REFRESH"; //$NON-NLS-1$ - } - if (i != 0) { - buffer.append(", "); //$NON-NLS-1$ - } - buffer.append(enumStr); - } - buffer.append('}'); - return buffer.toString(); - } - - /** - * Returns the fetch type annotation member value, or empty string if none. - * Empty string is returned instead of null because Velocity does not like - * null when used in #set. - */ - @Override - public String genFetch(ORMGenTable table) { - String fetch = table.getDefaultFetch(); - if (fetch == null || ORMGenTable.DEFAULT_FETCH.equals(fetch)) { - return ""; //$NON-NLS-1$ - } - else if (fetch.equals(ORMGenTable.LAZY_FETCH)) { - return "FetchType.LAZY"; //$NON-NLS-1$ - } - else { - return "FetchType.EAGER"; //$NON-NLS-1$ - } - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/DatabaseAnnotationNameBuilder.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/DatabaseAnnotationNameBuilder.java deleted file mode 100644 index bfb70ce8e7..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/DatabaseAnnotationNameBuilder.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.db.Table; - - -/** - * Provide a pluggable way to determine whether and how the entity generator - * prints the names of various database objects. - */ -public interface DatabaseAnnotationNameBuilder { - - /** - * Given the name of an entity and the table to which it is mapped, - * build and return a string to be used as the value for the entity's - * Table annotation's 'name' element. Return null if the entity - * maps to the table by default. - */ - String buildTableAnnotationName(String entityName, Table table); - - /** - * Given the name of an attribute (field or property) and the column - * to which it is mapped, - * build and return a string to be used as the value for the attribute's - * Column annotation's 'name' element. Return null if the attribute - * maps to the column by default. - */ - String buildColumnAnnotationName(String attributeName, Column column); - - /** - * Given the name of an attribute (field or property) and the - * many-to-one or many-to-many foreign key to which it is mapped, - * build and return a string to be used as the value for the attribute's - * JoinColumn annotation's 'name' element. Return null if the attribute - * maps to the join column by default. - * The specified foreign key consists of a single column pair whose - * referenced column is the single-column primary key of the foreign - * key's referenced table. - */ - String buildJoinColumnAnnotationName(String attributeName, ForeignKey foreignKey); - - /** - * Build and return a string to be used as the value for a JoinColumn - * annotation's 'name' or 'referencedColumnName' element. - * This is called for many-to-one and many-to-many mappings when - * the default join column name and/or referenced column name are/is - * not applicable. - * @see buildJoinColumnAnnotationName(String, ForeignKey) - */ - String buildJoinColumnAnnotationName(Column column); - - /** - * Build and return a string to be used as the value for a JoinTable - * annotation's 'name' element. - * This is called for many-to-many mappings when the default - * join table name is not applicable. - */ - String buildJoinTableAnnotationName(Table table); - - - /** - * The default implementation simple returns the database object's name, - * unaltered. - */ - final class Default implements DatabaseAnnotationNameBuilder { - public static final DatabaseAnnotationNameBuilder INSTANCE = new Default(); - public static DatabaseAnnotationNameBuilder instance() { - return INSTANCE; - } - // ensure single instance - private Default() { - super(); - } - public String buildTableAnnotationName(String entityName, Table table) { - return table.getName(); - } - public String buildColumnAnnotationName(String attributeName, Column column) { - return column.getName(); - } - public String buildJoinColumnAnnotationName(String attributeName, ForeignKey foreignKey) { - return foreignKey.getColumnPair().getBaseColumn().getName(); - } - public String buildJoinColumnAnnotationName(Column column) { - return column.getName(); - } - public String buildJoinTableAnnotationName(Table table) { - return table.getName(); - } - @Override - public String toString() { - return "DatabaseAnnotationNameBuilder.Default"; //$NON-NLS-1$ - } - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ForeignKeyInfo.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ForeignKeyInfo.java deleted file mode 100644 index 98e76d61a2..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ForeignKeyInfo.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import java.util.List; - -import org.eclipse.jpt.db.ForeignKey; - -/** - * Represents the metadata for a particular foreign key relationship - * in a relational database schema. - * <p/> - * The referrer column is one which actually contains a foreign - * key constraint, and is equivalent to the "foreign key" column. - * <p/> - * The referenced column is one which a referrer or foreign key - * column references, and is equivalent to the "primary key" column. - * - */ -public class ForeignKeyInfo -{ - private transient ForeignKey mForeignKey ; - private String mName; - private String mReferrerTableName; - private String mReferencedTableName; - private List<String> mReferrerColNames = new java.util.ArrayList<String>(); - private List<String> mReferencedColNames = new java.util.ArrayList<String>(); - - /** - * @param fk The name of the constraint backing - * this foreign key metadata instance. - */ - public ForeignKeyInfo(ForeignKey fk, String referrerTableName, String referencedTableName) { - mForeignKey = fk; - mName = fk.getName(); - mReferrerTableName = referrerTableName; - mReferencedTableName = referencedTableName; - } - /** - * Obtain the constraint name for this foreign key specification. - * The name for a Foreign Key may, as per the JDBC specification, - * be <code>null</code> where the constraint is not named. - * In addition, it may be hardly recognizable to the user, - * particularly for DB/2 constraints. - * - * @return The name of the constraint backing - * this foreign key metadata instance. - */ - public String getName() - { - return mName; - } - - public ForeignKey getForeignKey(){ - return mForeignKey; - } - /** - * Add another pair of foreign key mappings for this foreign key - * definition. - * - * @param referrerColumn The referrer column name for this mapping. - * - * @param referencedColumn The referenced column name for this mapping. - */ - public void addColumnMapping(String referrerColName, String referencedColName) { - mReferrerColNames.add(referrerColName); - mReferencedColNames.add(referencedColName); - } - /** - * Returns the referrer table name of this foreign key - * relationship. - */ - public String getReferrerTableName() { - return mReferrerTableName; - } - /** - * Returns the referrer column names for this - * foreign key. - * The size of this list is always the same as the size of - * the list retured from <code>getReferencedColumnNames</code> - */ - public List<String> getReferrerColumnNames() { - return mReferrerColNames; - } - /** - * Returns the referenced table name of this foreign key - * relationship. - */ - public String getReferencedTableName() { - return mReferencedTableName; - } - /** - * Returns the referenced column names for this - * foreign key. - * The size of this list is always the same as the size of - * the list retured from <code>getReferrerColumnNames</code> - */ - public List<String> getReferencedColumnNames() { - return mReferencedColNames; - } - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - public String toString() { - return "name=" + mName - + ", referrerTable=" + mReferrerTableName - + ", referencedTable=" + mReferencedTableName - + ", referrerColumns=" + mReferrerColNames - + ", referencedColumns=" + mReferencedColNames - ; - } -} - diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/JptGenMessages.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/JptGenMessages.java deleted file mode 100644 index ca3a512c8f..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/JptGenMessages.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import org.eclipse.osgi.util.NLS; - -/** - * Localized messages used by Dali entity generation. - */ -class JptGenMessages { - - public static String PackageGenerator_taskName; - public static String GenScope_taskName; - public static String EntityGenerator_taskName; - public static String Templates_notFound; - public static String Error_Generating_Entities; - - private static final String BUNDLE_NAME = "jpt_gen"; //$NON-NLS-1$ - private static final Class<?> BUNDLE_CLASS = JptGenMessages.class; - static { - NLS.initializeMessages(BUNDLE_NAME, BUNDLE_CLASS); - } - - private JptGenMessages() { - throw new UnsupportedOperationException(); - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/JptGenPlugin.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/JptGenPlugin.java deleted file mode 100644 index 6071ddfadf..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/JptGenPlugin.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.ILog; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.osgi.framework.Bundle; - -public class JptGenPlugin { - public static final String PLUGIN_ID = "org.eclipse.jpt.gen"; - public static void logException ( String msg, Throwable e ) { - Bundle bundle = Platform.getBundle(PLUGIN_ID); - ILog log = Platform.getLog(bundle); - log.log(new Status(IStatus.ERROR, PLUGIN_ID, msg, e )); - } - - public static void logException( CoreException ce ) { - IStatus status = ce.getStatus(); - Bundle bundle = Platform.getBundle(PLUGIN_ID); - ILog log = Platform.getLog(bundle); - log.log(new Status(IStatus.ERROR, PLUGIN_ID, status.getMessage(), ce)); - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ORMGenColumn.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ORMGenColumn.java deleted file mode 100644 index e891f28ca0..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ORMGenColumn.java +++ /dev/null @@ -1,383 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import java.util.Collections; - -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.gen.internal.EntityGenTools; -import org.eclipse.jpt.gen.internal2.util.DTPUtil; -import org.eclipse.jpt.gen.internal2.util.StringUtil; - - -/** - * Represents the ORM generation properties for a database - * column. - * - * <p>This is designed to be created/changed by the generation wizard, - * and generated using Velocity templates. - * The modified properties (if any) are persisted/retrieved using - * <code>ORMGenCustomizer</code>. - * - */ -public class ORMGenColumn -{ - private Table mTable; - private Column mDbColumn; - private ORMGenCustomizer mCustomizer; - private ORMGenTable mGenTable; - private static String JAVA_LANG_PACKAGE = "java.lang."; //$NON-NLS-1$ - - public ORMGenColumn(Column dbColumn, ORMGenCustomizer customizer) { - super(); - - mDbColumn = dbColumn; - mCustomizer = customizer; - mTable = dbColumn.getTable(); - } - - public ORMGenCustomizer getCustomizer() { - return mCustomizer; - } - - public void setGenTable(ORMGenTable ormGenTable) { - mGenTable = ormGenTable; - } - - protected String customized(String propName) { - return getCustomizer().getProperty(propName, mTable.getName(), getName()); - } - - protected boolean customizedBoolean(String propName) { - return getCustomizer().getBooleanProperty(propName, mTable.getName(), getName()); - } - - protected void setCustomized(String propName, String value) { - if (value != null && value.length() == 0) { - value = null; - } - getCustomizer().setProperty(propName, value, mTable.getName(), getName()); - } - - protected void setCustomizedBoolean(String propName, boolean value, boolean defaultValue) { - if (defaultValue == value) { - setCustomized(propName, null); //remove the property - } else { - getCustomizer().setBooleanProperty(propName, value, mTable.getName(), getName()); - } - } - - /** - * Returns the column name. - */ - public String getName() { - String annotationName = this.mCustomizer.getDatabaseAnnotationNameBuilder(). - buildColumnAnnotationName(mDbColumn.getName(), mDbColumn); - return annotationName != null ? annotationName : mDbColumn.getName(); - } - - public String getJoinColumnName(){ - String annotationName = this.mCustomizer.getDatabaseAnnotationNameBuilder(). - buildJoinColumnAnnotationName(mDbColumn); - return annotationName != null ? annotationName : mDbColumn.getName(); - } - - public Column getDbColumn() { - return this.mDbColumn; - } - - /** - * Returns the generated bean property name for the given column. - * Does not return null. - */ - public String getPropertyName() { - String name = customized(PROPERTY_NAME); - if (name == null) { - //name = StringUtil.columnNameToVarName(getName()); - name = EntityGenTools.convertToUniqueJavaStyleAttributeName(getName(), Collections.EMPTY_SET); - } - return name; - } - - public void setPropertyName(String name) { - if (!StringUtil.equalObjects(name, getPropertyName())) { - setCustomized(PROPERTY_NAME, name); - } - } - - /** - * Return true if the values of name element in the @Column is default - * so we can skip generating the annotation - * - * @return true - */ - public boolean isDefault(){ - return isDefaultname() && isUpdateable() && isInsertable(); - } - - /** - * Return true if the values of name element in the @Column is default - * so we can skip generating the annotation - * - * @return true - */ - public boolean isDefaultname(){ - String propName = getPropertyName(); -// String dbColumnName = getName(); -// return propName.equalsIgnoreCase( dbColumnName ); - String annotationName = this.mCustomizer.getDatabaseAnnotationNameBuilder(). - buildColumnAnnotationName(propName, this.mDbColumn ); - return annotationName==null; - } - - - /** - * Returns the column type. - * Does not return null. - */ - public String getPropertyType() { - String type = customized(PROPERTY_TYPE); - if (type == null) { - type = getCustomizer().getPropertyTypeFromColumn( this.mDbColumn ); - } - if( type.startsWith(JAVA_LANG_PACKAGE) ) { - type = type.substring( JAVA_LANG_PACKAGE.length() ); - } - return type; - } - - public String getSimplePropertyType() { - return mGenTable.getSimplifiedColType( getPropertyType() ); - } - - public void setPropertyType(String type) { - if (!StringUtil.equalObjects(type, getPropertyType())) { - setCustomized(PROPERTY_TYPE, type); - } - } - /** - * Returns true if the column type is numeric. - */ - public boolean isNumeric() { - boolean ret = this.mDbColumn.isNumeric(); - return ret; - } - - /** - * Returns the mapping kind, one of {@link #PROPERTY_MAPPING_KIND}|{@link #ID_MAPPING_KIND} - * |{@link #VERSION_MAPPING_KIND}|{@link #TIMESTAMP_MAPPING_KIND}. - * - * This method does not return null (defaults to basic property type). - */ - public String getMappingKind() { - String kind = customized(MAPPING_KIND); - if (kind == null) { - kind = getCustomizer().getBasicMappingKind(); - - if ( this.mDbColumn.isPartOfPrimaryKey() - && DTPUtil.getPrimaryKeyColumnNames( this.mDbColumn.getTable() ).size() == 1) { - kind = getCustomizer().getIdMappingKind(); - } - } - return kind; - } - - public void setMappingKind(String mappingKind) { - if (!StringUtil.equalObjects(mappingKind, getMappingKind())) { - setCustomized(MAPPING_KIND, mappingKind); - } - } - - public boolean isNullable() { - return this.mDbColumn.isNullable(); - } - - public int getSize() { - if ( this.mDbColumn.isNumeric()){ - return mDbColumn.getPrecision(); - } - return mDbColumn.getLength(); - } - - public int getDecimalDigits() { - if ( this.mDbColumn.isNumeric() ){ - return mDbColumn.getScale(); - } - return -1; - } - - public boolean isPrimaryKey() { - return this.mDbColumn.isPartOfPrimaryKey(); - } - - public boolean isPartOfCompositePrimaryKey() { - if ( this.mDbColumn.isPartOfPrimaryKey() ){ - if ( DTPUtil.getPrimaryKeyColumnNames( this.mTable ).size() > 1 ) - return true; - } - return false; - } - - public boolean isForeignKey() { - return this.mDbColumn.isPartOfForeignKey(); - } - - public boolean isUnique() { - return this.mDbColumn.isPartOfUniqueConstraint(); - } - - public String getPropertyDescription() { - return customized(PROPERTY_DESC); - } - - public boolean isDataTypeLOB() { - return this.mDbColumn.isLOB(); - } - - public boolean isNeedMapTemporalType() { - String propertyType = this.getPropertyType(); - return ( propertyType.equals("java.util.Date") || propertyType.equals("java.util.Calendar") ); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public String getTemporalType() { - String defaultType = getCustomizer().getPropertyTypeFromColumn( this.mDbColumn ); - if( defaultType.equals("java.sql.Date")){ //$NON-NLS-1$ - return "DATE"; //$NON-NLS-1$ - }else if( defaultType.equals("java.sql.Time")){ //$NON-NLS-1$ - return "TIME"; //$NON-NLS-1$ - }else { - return "TIMESTAMP"; //$NON-NLS-1$ - } - } - - /** - * Returns the generated property getter scope, one of {@link #PUBLIC_SCOPE}|{@link #PROTECTED_SCOPE} - * |{@link #PRIVATE_SCOPE}. - * This method never returns null (defaults to public). - */ - public String getPropertyGetScope() { - String scope = customized(PROPERTY_GET_SCOPE); - if (scope == null) { - scope = PUBLIC_SCOPE; - } - return scope; - } - - public void setPropertyGetScope(String scope) { - if (!StringUtil.equalObjects(scope, getPropertyGetScope())) { - setCustomized(PROPERTY_GET_SCOPE, scope); - } - } - - /** - * Returns the generated property setter scope, one of {@link #PUBLIC_SCOPE}|{@link #PROTECTED_SCOPE} - * |{@link #PRIVATE_SCOPE}. - * This method never returns null (defaults to public). - */ - public String getPropertySetScope() { - String scope = customized(PROPERTY_SET_SCOPE); - if (scope == null) { - scope = PUBLIC_SCOPE; - } - return scope; - } - - public void setPropertySetScope(String scope) { - if (!StringUtil.equalObjects(scope, getPropertySetScope())) { - setCustomized(PROPERTY_SET_SCOPE, scope); - } - } - - /** - * Returns the generated field member scope, one of {@link #PUBLIC_SCOPE}|{@link #PROTECTED_SCOPE} - * |{@link #PRIVATE_SCOPE}. - * This method never returns null (defaults to private). - */ - public String getFieldScope() { - String scope = customized(FIELD_SCOPE); - if (scope == null) { - scope = PRIVATE_SCOPE; - } - return scope; - } - - /** - * Returns true if this column should be used in the - * <code>equals</code> method implementation. - */ - public boolean isUseInEquals() { - return customizedBoolean(USE_IN_EQUALS) || isPrimaryKey(); - } - - public void setUseInEquals(boolean value) { - setCustomizedBoolean(USE_IN_EQUALS, value, false); - } - - /** - * Returns true if this column should be used in the - * <code>toString</code> method implementation. - */ - public boolean isUseInToString() { - return customizedBoolean(USE_IN_TO_STRING) || isPrimaryKey(); - } - - public void setUseInToString(boolean value) { - setCustomizedBoolean(USE_IN_TO_STRING, value, false); - } - - public boolean isUpdateable() { - return !"false".equals(customized(UPDATEABLE)); //defaults to true //$NON-NLS-1$ - } - - public void setUpdateable(boolean value) { - setCustomizedBoolean(UPDATEABLE, value, true); - } - - public boolean isInsertable() { - return !"false".equals(customized(INSERTABLE)); //defaults to true //$NON-NLS-1$ - } - - public void setInsertable(boolean value) { - setCustomizedBoolean(INSERTABLE, value, true); - } - - public boolean isGenerated() { - return !"false".equals(customized(GENERATED)); //defaults to true //$NON-NLS-1$ - } - - public void setGenerated(boolean value) { - setCustomizedBoolean(GENERATED, value, true); - } - - @Override - public String toString() { - return "name=" + getName() + "; type=" + getPropertyType() ; //$NON-NLS-1$ //$NON-NLS-2$ - } - - /*get/set and field scopes*/ - public static final String PUBLIC_SCOPE = "public"; //$NON-NLS-1$ - public static final String PROTECTED_SCOPE = "protected"; //$NON-NLS-1$ - public static final String PRIVATE_SCOPE = "private"; //$NON-NLS-1$ - - /*customization properties*/ - private static final String PROPERTY_NAME = "propertyName"; //$NON-NLS-1$ - protected static final String PROPERTY_TYPE = "propertyType"; //$NON-NLS-1$ - protected static final String MAPPING_KIND = "mappingKind"; //$NON-NLS-1$ - private static final String PROPERTY_DESC = "propertyDesc"; //$NON-NLS-1$ - private static final String PROPERTY_GET_SCOPE = "propertyGetScope"; //$NON-NLS-1$ - private static final String PROPERTY_SET_SCOPE = "propertySetScope"; //$NON-NLS-1$ - private static final String FIELD_SCOPE = "fieldScope"; //$NON-NLS-1$ - private static final String USE_IN_EQUALS = "useInEquals"; //$NON-NLS-1$ - private static final String USE_IN_TO_STRING = "useInToString"; //$NON-NLS-1$ - private static final String UPDATEABLE = "updateable"; //$NON-NLS-1$ - private static final String INSERTABLE = "insertable"; //$NON-NLS-1$ - private static final String GENERATED = "genProperty"; //$NON-NLS-1$ -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ORMGenCustomizer.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ORMGenCustomizer.java deleted file mode 100644 index 9d510a5df9..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ORMGenCustomizer.java +++ /dev/null @@ -1,788 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.db.Schema; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.gen.internal2.util.DTPUtil; -import org.eclipse.jpt.gen.internal2.util.FileUtil; -import org.eclipse.jpt.gen.internal2.util.StringUtil; - -/** - * Contains the information used to customize the database schema to ORM entity - * generation. - * - * <p>The customization settings are mainly exposed in the form of - * properties. There are no assumptions in this class about the meaning of the - * property names. Properties can be associated to specific tables and table - * columns, or globally for any table and/or column. - * - * <p>Subclass can implement the sets of abstract methods to provide ORM vendor - * specific properties. - * - */ -public abstract class ORMGenCustomizer implements java.io.Serializable -{ - private final static long serialVersionUID = 1; - - /** - * A value passed for the table name argument to get/setProperty - * indicating that the value applies to any table. - */ - public static final String ANY_TABLE = "__anyTable__"; - public static final String GENERATE_DDL_ANNOTATION = "generateDDLAnnotations"; - /*the string used in the property name in mProps to indicate - * a null table value.*/ - private static final String NULL_TABLE = ""; - /*the string used in the property name in mProps to indicate - * a null column value.*/ - private static final String NULL_COLUMN = ""; - - /*This version number is written in the header of the customization stream - * and read at de-serialization time, if it is different then the file is invalidated. - */ - private static final int FILE_VERSION = 2; - - private static final String UPDATE_CONFIG_FILE = "updateConfigFile"; - - private transient Schema mSchema; - private transient File mFile; - - private List<String> mTableNames; - /*key: table name, value: ORMGenTable object.*/ - private transient Map<String , ORMGenTable> mTables; - /*the <code>Association</code> objects sorted by their "from" - * table name. Includes all association derived from foreign keys - * in user selected tables. Since some of the foreign keys may point to table - * user does not select, this list may be different from mValidAssociations - */ - private List<Association> mAssociations; - /* - * List of valid associations within the user selected tables - */ - private transient List<Association> mValidAssociations; - private transient boolean mInvalidForeignAssociations; - - /*the property name is in the form $tableName.$columnName.$propertyName. - * Where tableName could be NULL_TABLE or ANY_TABLE - * and columnName could be NULL_COLUMN*/ - private Map<String, String> mProps = new java.util.HashMap<String, String>(); - - private transient DatabaseAnnotationNameBuilder databaseAnnotationNameBuilder = DatabaseAnnotationNameBuilder.Default.INSTANCE; - - //----------------------------------------- - //---- abstract methods - //----------------------------------------- - /** - * Returns all the primary key generator schemes. - * This can return any strings as far as the Velocity template - * processor understand them. - */ - public abstract List<String> getAllIdGenerators(); - /** - * Returns the string representing the developer-assigned id generator. - * This can return any strings as far as the Velocity template - * processor understand them. - */ - public abstract String getNoIdGenerator(); - /** - * Returns the string representing the identity id generator. - * This can return any strings as far as the Velocity template - * processor understand them. - */ - public abstract String getIdentityIdGenerator(); - /** - * Returns the strings representing the sequence generators. - * This can return any strings as far as the Velocity template - * processor understand them. - */ - public abstract Set<String> getSequenceIdGenerators(); - /** - * Returns a property type from the given database column. - * This can return any strings as far as the Velocity template - * processor understand them. - */ - public abstract String getPropertyTypeFromColumn(Column column) ; - /** - * Returns all the strings representing property types. - * This can return any strings as far as the Velocity template - * processor understand them. - */ - public abstract String[] getAllPropertyTypes(); - /** - * Returns all the strings representing property mapping kinds. - * This can return any strings as far as the Velocity template - * processor understand them. - */ - public abstract String[] getAllMappingKinds(); - /** - * Returns the basic (default) property mapping kind. - * This can return any strings as far as the Velocity template - * processor understand them. - */ - public abstract String getBasicMappingKind(); - /** - * Returns the id (primary key) property mapping kind. - * This can return any strings as far as the Velocity template - * processor understand them. - */ - public abstract String getIdMappingKind(); - /** - * Interacts with the user to edit the cascade of the given - * role. - * This method should also call <code>AssociationRole.setCascade</code>. - * - * @return false if the user interaction is cancelled. - */ - public abstract boolean editCascade(AssociationRole role); - - //----------------------------------------- - //----------------------------------------- - - /** - * @param file The file that contains the customization settings. - * The file is created if necessary when the <code>save</code> - * method is called. - */ - public void init( File file, Schema schema) { - this.mSchema = schema; - mFile = file; - - if (!file.exists()) { - setProperty(ORMGenTable.DEFAULT_FETCH, ORMGenTable.DEFAULT_FETCH, ORMGenCustomizer.ANY_TABLE, null); - return; - } - InputStream istream = null; - ObjectInputStream ois = null; - try - { - //read it in a file first to speedup deserialization - byte[] bytes = FileUtil.readFile(file); - istream = new ByteArrayInputStream(bytes); - ois = new ObjectInputStream(istream); - - FileHeader header = (FileHeader)ois.readObject(); - if (header.mVersion == FILE_VERSION) { - ORMGenCustomizer customizer = (ORMGenCustomizer)ois.readObject(); - restore(customizer); - } - } catch (Exception ex) { - System.out.println("***ORMGenCustomizer.load failed "+file+": " + ex); - } - finally - { - if (ois != null) - { - try - { - ois.close(); - } catch (IOException e) { - } - } - - if (istream != null) - { - try - { - istream.close(); - } catch (IOException e) { - } - } - } - } - - public File getFile(){ - return this.mFile; - } - - public void setSchema(Schema schema){ - this.mSchema = schema; - } - - public Schema getSchema(){ - return mSchema; - } - - /** - * Empty constructor needed by the deserialization. - */ - public ORMGenCustomizer() { - super(); - } - - /** - * Saves the customization file. - * The file is created if necessary. - */ - public void save() throws IOException { - //System.out.println("---ORMGenCustomizer.save: " + mFile); - if (!mFile.exists() && !mFile.createNewFile()) { - return; - } - java.io.FileOutputStream fos = null; - java.io.ObjectOutputStream oos = null; - boolean deleteIt = true; - try { - fos = new java.io.FileOutputStream(mFile); - oos = new java.io.ObjectOutputStream(fos); - FileHeader header = new FileHeader(); - oos.writeObject(header); - oos.writeObject(this); - deleteIt = false; - } catch (Exception ex) { - //deleteIt is true, so the cache is not saved. - CoreException ce = new CoreException(new Status(IStatus.ERROR, JptGenPlugin.PLUGIN_ID, - "Unable to save the ORMGenCustomizer file: "+mFile,ex)); - JptGenPlugin.logException( ce ); - } finally { - try { - if (oos!=null) oos.close(); - if (fos!=null) fos.close(); - if (deleteIt) { - mFile.delete(); - } - } catch (java.io.IOException ex2) {} - } - } - - public DatabaseAnnotationNameBuilder getDatabaseAnnotationNameBuilder() { - return this.databaseAnnotationNameBuilder; - } - public void setDatabaseAnnotationNameBuilder(DatabaseAnnotationNameBuilder databaseAnnotationNameBuilder) { - if (databaseAnnotationNameBuilder == null) { - throw new NullPointerException("database annotation name builder is required"); //$NON-NLS-1$ - } - this.databaseAnnotationNameBuilder = databaseAnnotationNameBuilder; - } - - /** - * Returns {@link #GENERATE_DDL_ANNOTATION} indicating whether - * the optional DDL parameters like length, nullable, unqiue, etc should be generated - * in @Column annotation. - * defaults to false. - */ - public boolean isGenerateDDLAnnotations() { - return "true".equals(getProperty(GENERATE_DDL_ANNOTATION, ANY_TABLE, null)); //defaults to false - } - - /** - * Returns a property value. - */ - public String getProperty(String propertyName, String tableName, String colName) { - String key = getPropKey(propertyName, tableName, colName); - String value = mProps.get(key); - /*if the key does not exist and it is a table property then - * get the default table property.*/ - if (value == null && tableName != null && colName == null && !tableName.equals(ANY_TABLE)) { - value = getProperty(propertyName, ANY_TABLE, colName); - } - return value; - } - /** - * Changes a property value. - * - * @param value The new value, could be null. - */ - public void setProperty(String propertyName, String value, String tableName, String colName) { - String key = getPropKey(propertyName, tableName, colName); - if (value != null) { - mProps.put(key, value); - } else { - mProps.remove(key); - } - } - /** - * Same as {@link #getProperty(String, String, String)} but - * converts the value to boolean. - */ - public boolean getBooleanProperty(String propertyName, String tableName, String colName) { - String value = getProperty(propertyName, tableName, colName); - return "true".equals(value); - } - /** - * Changes a table boolean property value. - */ - public void setBooleanProperty(String propertyName, boolean value, String tableName, String colName) { - setProperty(propertyName, value ? "true" : "false", tableName, colName); - } - /** - * Returns the names of the tables to generate. - */ - @SuppressWarnings("unchecked") - public List<String> getTableNames() { - return mTableNames != null ? mTableNames : java.util.Collections.EMPTY_LIST; - } - - /** - * Returns the fetch type annotation member value, or empty string - * if none. - * Empty string is returned instead of null because Velocity does not like null - * when used in #set. - */ - public String genFetch(ORMGenTable table) { - return ""; - } - /** - * Called when the table user selection is changed in the - * generation wizard. - */ - public void setTableNames(List<String> tableNames) { - mTableNames = tableNames; - mTables = null; - mValidAssociations = null; //recompute - mInvalidForeignAssociations = true; //make sure foreign associations from newly added tables are computed. - } - /** - * Returns the table names to be generated. - * This might be different from <code>getTableNames</code> if there - * are many-to-many join tables and are not contributing - * in any other associations. - */ - public List<String> getGenTableNames() { - List<String> names = getTableNames(); - List<String> result = new java.util.ArrayList<String>(names.size()); - - /*filter out join tables*/ - List<Association> associations = getAssociations(); - for (Iterator<String> tableNamesIter = names.iterator(); tableNamesIter.hasNext(); ) { - String tableName = tableNamesIter.next(); - boolean isValid = true; - - for (Iterator<Association> assocIter = associations.iterator(); assocIter.hasNext(); ) { - Association association = assocIter.next(); - if (!association.isGenerated()) { - continue; - } - if (tableName.equals(association.getReferrerTableName()) - || tableName.equals(association.getReferencedTableName())) { - isValid = true; - break; - } - if (tableName.equals(association.getJoinTableName())) { - isValid = false; - } - } - if (isValid) { - result.add(tableName); - } - } - return result; - } - /** - * Returns an <code>ORMGenTable</code> object given its name, or - * null if none. - */ - public ORMGenTable getTable(String tableName) { - if (mTables == null) { - mTables = new java.util.HashMap<String, ORMGenTable>(mTableNames.size()); - } - - if(mTableNames!=null && mSchema!=null){ - for (Iterator<String> iter = mTableNames.iterator(); iter.hasNext(); ) { - String name = iter.next(); - Table dbTable = mSchema.getTableNamed( name ); - if (dbTable != null) { - mTables.put(name, createGenTable(dbTable)); - } - } - } - return mTables.get(tableName); - } - /** - * Returns the <code>Association</code> objects sorted by their "from" - * table name. - */ - public List<Association> getAssociations(){ - return getAssociations(true/*validOnly*/); - } - /** - * Adds the given association. - */ - public void addAssociation(Association association) { - getAssociations(false/*validOnly*/).add(association); - if (mValidAssociations != null) { - mValidAssociations.add(association); - } - - } - /** - * Deletes the given association. - */ - public void deleteAssociation(Association association) { - boolean removed = getAssociations(false/*validOnly*/).remove(association); - assert(removed); - - if (mValidAssociations != null) { - removed = mValidAssociations.remove(association); - assert(removed); - } - } - /** - * Returns true if an association similar to the given association - * already exists. - * This is decided based only on the association tables and columns. - */ - public boolean similarAssociationExists(Association association) { - try { - for (Iterator<Association> iter = getAssociations(false/*validOnly*/).iterator(); iter.hasNext(); ) { - Association association2 = iter.next(); - if (!association.getReferrerTableName().equals(association2.getReferrerTableName()) - || !association.getReferencedTableName().equals(association2.getReferencedTableName()) - || !StringUtil.equalObjects(association.getJoinTableName(), association2.getJoinTableName()) - || !association.getReferrerColumnNames().equals(association2.getReferrerColumnNames()) - || !association.getReferencedColumnNames().equals(association2.getReferencedColumnNames()) - ) { - continue; - } - /*the 2 association have the same referrer, referenced and join table*/ - if (association.getJoinTableName() == null) { - return true; - } - if (association.getReferrerJoinColumnNames().equals(association2.getReferrerJoinColumnNames()) - && association.getReferencedJoinColumnNames().equals(association2.getReferencedJoinColumnNames())) { - return true; - } - } - } catch (Exception e) { - return false; - } - return false; - } - /** - * Creates the <code>ORMGenTable</code> instance. - */ - public ORMGenTable createGenTable(Table dbTable) { - return new ORMGenTable(dbTable, this); - } - /** - * Creates the <code>ORMGenColumn</code> instance. - */ - protected ORMGenColumn createGenColumn(Column dbCol) { - return new ORMGenColumn(dbCol, this); - } - /** - * Returns true of the underlying persistence specs require the "many" side - * of an association to be the owner (like EJB3). - */ - protected boolean manySideIsAssociationOwner() { - return false; - } - public boolean isUpdateConfigFile() { - return !"false".equals(getProperty(UPDATE_CONFIG_FILE, null, null)); //defaults to true - } - public void setUpdateConfigFile(boolean value) { - if (value) { //default is true - setProperty(UPDATE_CONFIG_FILE, null, null, null); //remove it - } else { - setBooleanProperty(UPDATE_CONFIG_FILE, value, null, null); - } - } - - //----------------------------------------- - //---- Velocity templates methods - //----------------------------------------- - /** - * Returns a getter method name given a property name. - */ - public String propertyGetter(String propertyName) { - return "get"+StringUtil.initUpper(propertyName); - } - /** - * Returns a setter method name given a property name. - */ - public String propertySetter(String propertyName) { - return "set"+StringUtil.initUpper(propertyName); - } - public String quote(String s) { - return StringUtil.quote(s, '"'); - } - public String quote(boolean b) { - return quote(String.valueOf(b)); - } - public String quote(int i) { - return quote(String.valueOf(i)); - } - /** - * Appends an annotation member name and value to an existing annotation. - * - * @param s The annotation members string. - * - * @param memberValue The member value, if null or empty strings then - * nothing is appened. - * - * @param whether to double quote the member value. - */ - public String appendAnnotation(String s, String memberName, String memberValue, boolean quote) { - if (memberValue == null || memberValue.length() == 0) { - return s; - } - StringBuffer buffer = new StringBuffer(s); - if (buffer.length() != 0) { - buffer.append(", "); - } - buffer.append(memberName); - buffer.append('='); - if (quote) { - buffer.append('"'); - } - buffer.append(memberValue); - if (quote) { - buffer.append('"'); - } - return buffer.toString(); - } - public boolean isJDK1_5() { - return true; - } - - //----------------------------------------- - //---- private methods - //----------------------------------------- - /** - * Restores the customization settings from the given - * (persisted) customizer. - */ - private void restore(ORMGenCustomizer customizer) { - mTableNames = customizer.mTableNames; - mAssociations = customizer.mAssociations; - mProps = customizer.mProps; - if( mSchema == null ) - return; - - /*remove invalid table names*/ - for (int i = mTableNames.size()-1; i >= 0; --i) { - String tableName = mTableNames.get(i); - if (mSchema.getTableNamed( tableName) == null) { - mTableNames.remove(i); - } - } - if( mAssociations!=null ){ - /*restore the associations*/ - for (Iterator<Association> iter = mAssociations.iterator(); iter.hasNext(); ) { - Association association = iter.next(); - association.restore(this); - } - /*add the foreign keys associations just in case the tables changed since - * the last time the state was persisted. Pass checkExisting true so that the - * associations restored above are not overwritten.*/ - addForeignKeyAssociations(true/*checkExisting*/); - } - } - /** - * Returns the key in mProps corresponding to the specified - * propertyName, table and column. - */ - private String getPropKey(String propertyName, String tableName, String colName) { - if (tableName == null) { - tableName = NULL_TABLE; - } - if (colName == null) { - colName = NULL_COLUMN; - } - return tableName + '.' + colName + '.' + propertyName; - } - /** - * Returns the associations that are valid for the - * current tables. - */ - private List<Association> getAssociations(boolean validOnly){ - if (mAssociations == null) { - mAssociations = new java.util.ArrayList<Association>(); - - addForeignKeyAssociations(false/*checkExisting*/); - } else if (mInvalidForeignAssociations) { - mInvalidForeignAssociations = false; - - addForeignKeyAssociations(true/*checkExisting*/); - } - List<Association> associations; - if (validOnly) { - if (mValidAssociations == null) { - /*filter out the invalid associations*/ - mValidAssociations = new ArrayList<Association>(mAssociations.size()); - for (int i = 0, n = mAssociations.size(); i < n; ++i) { - Association association = mAssociations.get(i); - if (association.isValid()) { - mValidAssociations.add(association); - } - } - } - associations = mValidAssociations; - } else { - associations = mAssociations; - } - return associations; - } - private void addForeignKeyAssociations(boolean checkExisting) { - List<String> tableNames = getTableNames(); - for (Iterator<String> iter = tableNames.iterator(); iter.hasNext(); ) { - ORMGenTable table = getTable(iter.next()); - addForeignKeyAssociations(table, checkExisting); - } - } - private void addForeignKeyAssociations(ORMGenTable table, boolean checkExisting) { - if(table==null) - return; - - - List<ForeignKeyInfo> fKeys = null; - - try{ - fKeys = DTPUtil.getForeignKeys(table.getDbTable()); - }catch(Exception ise){ - //workaround Dali bug for now - return; - } - - if( fKeys.size()==0 ) - return; - - List<Association> addedAssociations = new java.util.ArrayList<Association>(); - for (Iterator<ForeignKeyInfo> iter = fKeys.iterator(); iter.hasNext(); ) { - ForeignKeyInfo fki = iter.next(); - ORMGenTable referencedTable = getTable(fki.getReferencedTableName()); - if (referencedTable == null) { - continue; - } - Association association = new Association(this, table.getName(), fki.getReferrerColumnNames() - , referencedTable.getName(), fki.getReferencedColumnNames()); - association.computeCardinality(); - //Defer the check of similarAssociationExists after computeManyToMany() - //otherwise the MTM association will not computed correctly in some cases. - //if (checkExisting && similarAssociationExists(association)) { - // continue; - //} - addedAssociations.add(association); - } - - Association m2m = computeManyToMany(table, addedAssociations); - if (m2m != null) { - /*do not generate the 2 many-to-one*/ - addedAssociations.clear(); - addedAssociations.add(0, m2m); - } - //remove the association if already existing - Iterator<Association> it = addedAssociations.iterator(); - while( it.hasNext() ){ - Association newAssociation = it.next(); - for( Association association : mAssociations ){ - if( newAssociation.equals( association )){ - it.remove(); - } - } - } - mAssociations.addAll(addedAssociations); - } - private Association computeManyToMany(ORMGenTable table, List<Association> addedAssociations) { - /** many-to-many associations if: - * - addedAssociations contains 2 many-to-one associations - * - tables t1 and t2 does NOT have to be different( for self-MTM-self situation) - * - <code>table</code> contains only the foreign key columns. - * - * Note: following restrictions have been removed: - * -table has only two columns - * -t1 and t2 must be different - * -the primary key of <code>table</code> is the concatenation of its foreign - * keys to t1 and t2.*/ - - if (addedAssociations.size() != 2) { - return null; - } - - //MTM table should have two MTO relations to orginal tables - Association assoc1 = addedAssociations.get(0); - Association assoc2 = addedAssociations.get(1); - if (assoc1.getCardinality() != Association.MANY_TO_ONE - || assoc2.getCardinality() != Association.MANY_TO_ONE) { - return null; - } - - //MTM table should only include foreign key columns - for( ORMGenColumn col : table.getColumns()){ - if( !col.isForeignKey()) - return null; - } - - - ORMGenTable t1 = assoc1.getReferencedTable(); - ORMGenTable t2 = assoc2.getReferencedTable(); - - if( t1.getName().equals(table.getName()) || t2.getName().equals(table.getName()) ) { - return null; - } - - //Make a guess which table is the owning side of the MTM relation - //See https://bugs.eclipse.org/bugs/show_bug.cgi?id=268445 - //Logic borrowed from DTPTableWrapper.getJoinTableOwningForeignKey() - if( !table.getName().equals(t1.getName() + "_" + t2.getName() ) ) { - //swap t1 and t2 - ORMGenTable t3 = t1; - t1=t2; - t2=t3; - //swap assoc1 and assoc2 - Association assoc3=assoc1; - assoc1=assoc2; - assoc2=assoc3; - } - -//Commented out because the assumption is too restrictive: -//this check will prevent generating MTM mapping table not having -//primary key defined -// List pkNames = DTPUtil.getPrimaryKeyColumnNames(table.getDbTable()); -// if (pkNames.size() != table.getColumnNames().size()) { -// return null; -// } -// List fkNames = new java.util.ArrayList(assoc1.getReferrerColumnNames()); //clone because we modify by addAll below -// fkNames.addAll(assoc2.getReferrerColumnNames()); -// if (!CollectionUtil.equalsIgnoreOrder(pkNames, fkNames)) { -// return null; -// } - Association m2m = new Association(this, t1.getName()/*referrerTableName*/, assoc1.getReferencedColumnNames()/*referrerColNames*/ - , t2.getName()/*referencedTableName*/, assoc2.getReferencedColumnNames()/*referencedColNames*/ - , table.getName(), assoc1.getReferrerColumnNames()/*referrerJoinColNames*/, assoc2.getReferrerColumnNames()/*referencedJoinColNames*/); - m2m.setCustom(false); - return m2m; - } - - //--------------------------------------------------- - //---- FileHeader class ----------------------------- - //--------------------------------------------------- - /** - * The header of the customization file. - */ - private static class FileHeader implements java.io.Serializable - { - private static final long serialVersionUID = 1L; - /** - * Should be argument-less because it is used in - * the de-serialization process. - */ - public FileHeader() { - mVersion = FILE_VERSION; - } - int mVersion; - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ORMGenTable.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ORMGenTable.java deleted file mode 100644 index b7e03fe433..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/ORMGenTable.java +++ /dev/null @@ -1,1039 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.gen.internal.EntityGenTools; -import org.eclipse.jpt.gen.internal2.util.DTPUtil; -import org.eclipse.jpt.gen.internal2.util.StringUtil; -import org.eclipse.jpt.utility.JavaType; - -/** - * Represents the ORM generation properties for a database table. - * - * <p> - * This is designed to be created/changed by the generation wizard, and - * generated using Velocity templates. The modified properties (if any) are - * persisted/retrieved using <code>ORMGenCustomizer</code>. - * - */ -public class ORMGenTable -{ - private ORMGenCustomizer mCustomizer; - private List<ORMGenColumn> mColumns; - private Table mDbTable; - private HashMap<String, String> columnTypesMap = null; - /** - * @param table - * The database table or null if this table is used to get/set - * the default table properties (properties that apply to all - * tables unless overriden). - */ - public ORMGenTable(Table table, ORMGenCustomizer customizer) { - super(); - mDbTable = table; - mCustomizer = customizer; - } - - public ORMGenCustomizer getCustomizer() { - return mCustomizer; - } - - /** - * Returns true if this table is is used to get/set the default table - * properties. - */ - public boolean isDefaultsTable() { - return mDbTable == null; - } - - protected String customized(String propName) { - return getCustomizer().getProperty(propName, getName(), null); - } - - protected boolean customizedBoolean(String propName) { - return getCustomizer().getBooleanProperty(propName, getName(), null); - } - - protected void setCustomized(String propName, String value) { - if (value != null && value.length() == 0) { - value = null; - } - getCustomizer().setProperty(propName, value, getName(), null); - } - - protected void setCustomizedBoolean(String propName, boolean value, boolean defaultValue) { - if (defaultValue == value) { - setCustomized(propName, null); // remove the property - } - else { - getCustomizer().setBooleanProperty(propName, value, getName(), null); - } - } - - public Table getDbTable() { - return mDbTable; - } - - /** - * Returns the table name. - */ - public String getName() { - if (mDbTable == null) - return ORMGenCustomizer.ANY_TABLE; - return mDbTable.getName(); - } - - public String getJoinTableAnnotationName() { - if (mDbTable == null) - return ORMGenCustomizer.ANY_TABLE; - String annotationName = this.mCustomizer.getDatabaseAnnotationNameBuilder().buildJoinTableAnnotationName(mDbTable); - return annotationName != null ? annotationName : mDbTable.getName(); - } - - /** - * Returns the database schema containing the table. - */ - public String getSchema() { - if (DTPUtil.isDefaultSchema(mDbTable) || mDbTable.getSchema()==null) - return ""; //$NON-NLS-1$ - String schemaName = mDbTable.getSchema().getName(); - return schemaName; - } - - public void setSourceFolder(String srcFolder){ - setCustomized(SRC_FOLDER, srcFolder); - } - - public String getSourceFolder(){ - String srcFolder = customized(SRC_FOLDER); - return srcFolder == null ? "" : srcFolder; - } - - public String getImportStatements(){ - buildColumnTypesMap(); - Collection<String> packages = columnTypesMap.keySet(); - StringBuilder ret = new StringBuilder(); - for ( String s : packages ) { - ret.append( "import " + s + ";\n"); //$NON-NLS-1$ - } - - List<AssociationRole> associationRoles = getAssociationRoles(); - for ( AssociationRole role : associationRoles ) { - if ( role.getCardinality().equals( Association.ONE_TO_MANY ) - || role.getCardinality().equals( Association.MANY_TO_MANY ) ) { - ret.append( "import " + getDefaultCollectionType() + ";\n"); //$NON-NLS-1$ - break; - } - } - - return ret.toString(); - } - - /** - * Construct import statements for types from javax.persistence package - * @return - */ - private String getJavaxPersistenceImportStatements() { - StringBuilder ret = new StringBuilder(); - ret.append( "import javax.persistence.Entity;\n"); //$NON-NLS-1$ - //TODO: only if @Columns is needed - ret.append( "import javax.persistence.Column;\n");//$NON-NLS-1$ - //TODO: only if there is @Id - ret.append( "import javax.persistence.Id;\n");//$NON-NLS-1$ - if( !this.isDefaultname() ) - ret.append( "import javax.persistence.Table;\n");//$NON-NLS-1$ - if( this.isCompositeKey() ) - ret.append( "import javax.persistence.EmbeddedId;\n"); //$NON-NLS-1$ - // append javax.persistence package imports - HashSet<String> jpaImports = new HashSet<String>(); - List<AssociationRole> associationRoles = getAssociationRoles(); - for( AssociationRole role : associationRoles ){ - if( role.getCardinality().equals( Association.ONE_TO_ONE ) ){ - jpaImports.add( "import javax.persistence.OneToOne;" );//$NON-NLS-1$ - }else{ - if( role.getCardinality().equals( Association.ONE_TO_MANY ) ){ - jpaImports.add( "import javax.persistence.OneToMany;\n" );//$NON-NLS-1$ - }else if( role.getCardinality().equals( Association.MANY_TO_ONE ) ){ - jpaImports.add( "import javax.persistence.ManyToOne;\n" );//$NON-NLS-1$ - jpaImports.add( "import javax.persistence.JoinColumn;\n" ); //$NON-NLS-1$ - }else if( role.getCardinality().equals( Association.MANY_TO_MANY ) ){ - jpaImports.add( "import javax.persistence.ManyToMany;\n" );//$NON-NLS-1$ - jpaImports.add( "import javax.persistence.JoinTable;\n" );//$NON-NLS-1$ - jpaImports.add( "import javax.persistence.JoinColumns;\n");//$NON-NLS-1$ - jpaImports.add( "import javax.persistence.JoinColumn;\n" );//$NON-NLS-1$ - } - } - } - for( String s: jpaImports){ - ret.append(s); - } - return ret.toString(); - } - - public HashMap<String, String> buildColumnTypesMap(){ - if ( columnTypesMap != null) { - return columnTypesMap; - } - columnTypesMap = new HashMap<String, String>(); - for ( ORMGenColumn col : this.getColumns() ) { - String type = col.getPropertyType(); - if ( !col.isPartOfCompositePrimaryKey() - && !col.isForeignKey() - && !type.startsWith("java.lang") && type.indexOf('.')>0 ) { - String simpleType= type.substring( type.lastIndexOf('.')+1 ); - columnTypesMap.put(type, simpleType); - } - } - return columnTypesMap; - } - - public String getSimplifiedColType(String fqtn ) { - HashMap<String, String> map = buildColumnTypesMap(); - String typeName = map.get(fqtn); - if ( typeName != null ) { - return typeName; - } - return fqtn; - } - - /** - * Sets the package for the generated class (empty string for the default - * package) - */ - public void setPackage(String pkg) { - getCustomizer().setProperty(PACKAGE, pkg, getName(), null); - // not calling setCustomized so that empty strings do not get nulled out. - } - - /** - * Returns the Java package (empty string for the default package). - */ - public String getPackage() { - String packageName = customized(PACKAGE); - return packageName == null ? "" : packageName; //$NON-NLS-1$ - } - - /** - * Returns the generated Java class name (not qualified). - */ - public String getClassName() { - String name = customized(CLASS_NAME); - if (name == null) { - // name = StringUtil.tableNameToVarName(getName()); - // name = StringUtil.initUpper(name); - name = EntityGenTools.convertToUniqueJavaStyleClassName(getName(), new ArrayList<String>()); - name = StringUtil.singularise(name); - } - return name; - } - - public void setClassName(String className) { - /* - * if the class name is the same as the (possibly computed) class name - * then nothing to do - */ - if (!StringUtil.equalObjects(className, getClassName())) { - setCustomized(CLASS_NAME, className); - } - } - - /** - * Returns a name suitable to be used as a variable or class name. This is - * computed based on the table name. - * - * @param singular - * Whether the name should be singular or plural. - */ - public String getVarName(boolean singular) { - String name = StringUtil.tableNameToVarName(getName()); - if (singular) { - name = StringUtil.singularise(name); - } - else { - name = StringUtil.pluralise(name); - } - return name; - } - - /** - * Returns the fully qualified generated Java class name. - */ - public String getQualifiedClassName() { - return qualify(getClassName()); - } - - /** - * Returns the composite key Java class name (not qualified). - */ - public String getCompositeKeyClassName() { - String name = customized(COMPOSITE_KEY_CLASS_NAME); - if (name == null) { - name = getClassName() + "PK"; //$NON-NLS-1$ - } - return name; - } - - /** - * Returns the fully qualified composite key Java class name. - */ - public String getQualifiedCompositeKeyClassName() { - return qualify(getCompositeKeyClassName()); - } - - /** - * Returns the composite key property name. - */ - public String getCompositeKeyPropertyName() { - return "id"; //$NON-NLS-1$ - } - - /** - * Returns the <code>ORMGenColumn</code> objects to be generated for this - * table. - */ - public List<ORMGenColumn> getColumns() { - if (mColumns == null) { - mColumns = new ArrayList<ORMGenColumn>(); - Iterator<Column> cols = mDbTable.columns(); - while (cols.hasNext()) { - Column c = cols.next(); - ORMGenColumn genColumn = getCustomizer().createGenColumn(c); - genColumn.setGenTable(this); - mColumns.add(genColumn); - } - } - return mColumns; - } - - public List<String> getColumnNames() { - Iterator<Column> cols = mDbTable.columns(); - List<String> ret = new ArrayList<String>(); - while (cols.hasNext()) { - Column c = cols.next(); - ret.add(c.getName()); - } - return ret; - } - - /** - * Returns the <code>ORMGenColumn</code> objects representing the table's - * primary key. - */ - public List<ORMGenColumn> getPrimaryKeyColumns() { - List<Column> dbCols = DTPUtil.getPrimaryKeyColumns(mDbTable); - List<ORMGenColumn> ret = new ArrayList<ORMGenColumn>(); - for (Column dbCol : dbCols) { - ret.add(new ORMGenColumn(dbCol, this.mCustomizer)); - } - return ret; - } - - /** - * Returns the primary key column or null if there is no or many primary key - * columns. - */ - public ORMGenColumn getPrimaryKeyColumn() { - ORMGenColumn pkCol = null; - List<ORMGenColumn> pkColumns = getPrimaryKeyColumns(); - if (pkColumns.size() == 1) { - // Column dbCol = (Column)pkColumns.get(0); - pkCol = pkColumns.get(0); // (ORMGenColumn) - // mCustomizer.createGenColumn(dbCol); - } - else { - /* - * if no pk column then look for the first column with id mapping - * kind. This is so that the wizard can be used with tables not - * having primary keys. - */ - List<ORMGenColumn> columns = getColumns(); - for (int i = 0, n = columns.size(); i < n; ++i) { - ORMGenColumn column = columns.get(i); - if (column.getMappingKind().equals(mCustomizer.getIdMappingKind())) { - pkCol = column; - break; - } - } - } - return pkCol; - } - - /** - * Returns true if there is more than 1 pk column. - */ - public boolean isCompositeKey() { - return DTPUtil.getPrimaryKeyColumnNames(mDbTable).size() > 1; - } - - /** - * Returns the <code>ORMGenColumn</code> objects for the the columns that - * are not part of any association. - * - * @param genOnly - * Whether to include only the columns marked for generation. - * - * @param includePk - * Whether to include the primary kley column(s). - * - * @param includeInherited - * Whether to include the columns associated with Java properties - * that exist in the super class (if any). - */ - public List<ORMGenColumn> getSimpleColumns(boolean genOnly, boolean includePk, boolean includeInherited) { - List<ORMGenColumn> result = new java.util.ArrayList<ORMGenColumn>(); - List<ORMGenColumn> columns = getColumns(); - List<AssociationRole> roles = getAssociationRoles(); - for (int i = 0, n = columns.size(); i < n; ++i) { - ORMGenColumn column = columns.get(i); - if (genOnly && !column.isGenerated()) { - continue; - } - if (column.isPrimaryKey()) { - if (!includePk || isCompositeKey()) { - continue; - } else { - result.add(0, column); - continue; - } - } - else if (isColumnInAsscociation(column, roles)) { - continue; - } - result.add(column); - } - return result; - } - - public List<ORMGenColumn> getSimpleColumns() { - return getSimpleColumns(true/* genOnly */, true/* includePk */, true/* includeInherited */); - } - - /** - * Returns false if the given column should be generated with false - * updatable/insertable. This is the case when the column is mapped more - * than once, this usually happen with columns in composite keys and - * many-to-one associations. - * - * <br> - * Note that for Hibernate the column param is null because the - * insert/update attributes are specified for the many-to-one tag itself - * instead of the nested column tags (bogus obviously). - */ - public boolean isColumnUpdateInsert(AssociationRole role, ORMGenColumn column) { - if (column == null) { - for (Iterator<ORMGenColumn> iter = role.getReferrerColumns().iterator(); iter.hasNext();) { - ORMGenColumn c = iter.next(); - if (!isColumnUpdateInsert(role, c)) { - return false; - } - } - return true; - } - if (column.isPrimaryKey()) { - return false; - } - /* - * should look if there are multiple associations using the same column - * and return false, but this is probably an unusual case. - */ - return true; - } - - /** - * Returns the <code>ORMGenColumn</code> objects corresponding to the given - * column names. - */ - public List<ORMGenColumn> getColumnsByNames(List<String> names) { - List<ORMGenColumn> result = new java.util.ArrayList<ORMGenColumn>(); - for (String name : names) { - ORMGenColumn column = getColumnByName(name); - assert (column != null); - if (column != null) { - result.add(column); - } - } - return result; - } - - /** - * Returns the columns having the given name, or null if none. - */ - public ORMGenColumn getColumnByName(String name) { - List<ORMGenColumn> columns = getColumns(); - for (int i = 0, n = columns.size(); i < n; ++i) { - ORMGenColumn column = columns.get(i); - if (column.getName().equals(name)) { - return column; - } - } - return null; - } - - /** - * Returns the <code>AssociationRole</code> objects for this table. Only the - * association marked for generation are returned. - */ - public List<AssociationRole> getAssociationRoles() { - /* - * this is not cached intentionally because invalidating the cache with - * wizard changes is kinda tricky. - */ - List<AssociationRole> associationRoles = new ArrayList<AssociationRole>(); - String name = getName(); - List<Association> associations = mCustomizer.getAssociations(); - for (Iterator<Association> iter = associations.iterator(); iter.hasNext();) { - Association association = iter.next(); - if (!association.isGenerated()) { - continue; - } - /* - * check both referrerand referenced because an association could be - * from-to the same table (employee/manager) - */ - if (association.getReferrerTable().getName().equals(name)) { - AssociationRole role = association.getReferrerRole(); - if (role != null) { - associationRoles.add(role); - } - } - if (association.getReferencedTable().getName().equals(name)) { - AssociationRole role = association.getReferencedRole(); - if (role != null) { - associationRoles.add(role); - } - } - } - return associationRoles; - } - - public String getClassDescription() { - return customized(CLASS_DESC); - } - - /** - * Returns the generated class scope, one of {@link #PUBLIC_SCOPE}| - * {@link #PROTECTED_SCOPE} |{@link #PRIVATE_SCOPE}. This method never - * returns null (defaults to public). - */ - public String getClassScope() { - String scope = customized(CLASS_SCOPE); - if (scope == null) { - scope = PUBLIC_SCOPE; - } - return scope; - } - - public String getExtends() { - return customized(EXTENDS); - } - - public void setExtends(String baseClass) { - setCustomized(EXTENDS, baseClass); - } - - public List<String> getImplements() { - String str = customized(IMPLEMENTS); - List<String> result = StringUtil.strToList(str, ',', true/* trim */); - if (result == null) { - result = Collections.emptyList(); - } - return result; - } - - public void setImplements(List<String> interfaces) { - setCustomized(IMPLEMENTS, StringUtil.listToStr(interfaces, ',')); - } - - /** - * Returns the string that should be generated in the Java class for extends - * and implements. - */ - public String generateExtendsImplements() { - StringBuffer buffer = new StringBuffer(); - String extendsClass = getExtends(); - if (extendsClass != null && !extendsClass.equals("java.lang.Object") && !extendsClass.equals("Object")) { - buffer.append("extends " + simplifyClassName(extendsClass)); - } - buffer.append("implements Serializable"); // assuming that the Java - // file template imports the - // java.io.Serializable - for (Iterator<String> iter = getImplements().iterator(); iter.hasNext();) { - buffer.append(", " + simplifyClassName(iter.next())); - } - return buffer.toString(); - } - - private String simplifyClassName(String fullClassName) { - final String JAVA_LANG = "java.lang."; - if (fullClassName.startsWith(JAVA_LANG)) { - return fullClassName.substring(JAVA_LANG.length()); - } - String pkg = StringUtil.getPackageName(fullClassName); - if (pkg != null && StringUtil.equalObjects(pkg, getPackage())) { - return StringUtil.getClassName(fullClassName); - } - return fullClassName; - } - - /** - * Returns the id generator scheme (assigned, sequence, etc). Does not - * return null, defaults to "assigned" or "identity" depending on whether - * the table has an identity column. - */ - public String getIdGenerator() { - String generator = customized(ID_GENERATOR); - String noneGenerator = getCustomizer().getNoIdGenerator(); - if (!isDefaultsTable()) { - /* - * This is done mainly because there might be cases where some - * tables have autoinctement pk and others are assigned. In this - * case this makes it so that it is possible to have a "none" - * default value that is interpreted depending on the case. - */ - if (generator == null || generator.equals(noneGenerator)) { - ORMGenColumn pkColumn = getPrimaryKeyColumn(); - if (pkColumn != null && DTPUtil.isAutoIncrement(pkColumn.getDbColumn())) { - generator = getCustomizer().getIdentityIdGenerator(); - } - } - } - if (generator == null) { - generator = noneGenerator; - } - return generator; - } - - /** - * Changes the id generator scheme (assigned, sequence, etc). - */ - public void setIdGenerator(String scheme) { - setCustomized(ID_GENERATOR, scheme); - } - - /** - * Returns the sequence name for the given table, or null if none (makes - * sense only when the scheme is native, sequence, ..). - */ - public String getSequence() { - return customized(SEQUENCE); - } - - public void setSequence(String name) { - setCustomized(SEQUENCE, name); - } - - /** - * Returns the sequence name after replacing the ${table} and ${pk} by their - * values, or null if none. - */ - public String getFormattedSequence() { - String sequence = getSequence(); - if (sequence != null) { - /* resolve the ${table} and ${pk} patterns */ - sequence = StringUtil.strReplace(sequence, TABLE_SEQ_PATTERN, getName()); - if (sequence.indexOf(PK_SEQ_PATTERN) >= 0) { - List<String> pkNames = DTPUtil.getPrimaryKeyColumnNames(getDbTable()); - String pkName = null; - if (pkNames.size() > 0) { - pkName = pkNames.get(0); - } - sequence = StringUtil.strReplace(sequence, PK_SEQ_PATTERN, pkName); - } - } - return sequence != null ? sequence.toUpperCase() : ""; - } - - public boolean isImplementEquals() { - return !"true".equals(customized(IMPLEMENT_EQUALS)); // defaults to - // false - } - - public void setImplementEquals(boolean value) { - setCustomizedBoolean(IMPLEMENT_EQUALS, value, true); - } - - /** - * Returns true if there is any column participating in equals/hashcode. - */ - public boolean hasColumnsInEquals() { - List<ORMGenColumn> columns = getSimpleColumns(); - for (int i = 0, n = columns.size(); i < n; ++i) { - ORMGenColumn column = columns.get(i); - if (column.isUseInEquals()) { - return true; - } - } - return false; - } - - /** - * Returns {@link #GENERATE_DDL_ANNOTATION} indicating whether the optional - * DDL parameters like length, nullable, unqiue, etc should be generated in @Column - * annotation. defaults to false. - */ - public boolean isGenerateDDLAnnotations() { - return "true".equals(customized(ORMGenCustomizer.GENERATE_DDL_ANNOTATION)); // defaults - // to - // false - } - - public void setGenerateDDLAnnotations(boolean generate) { - setCustomizedBoolean(ORMGenCustomizer.GENERATE_DDL_ANNOTATION, generate, false); - } - - /** - * Returns one of {@link #PROPERTY_ACCESS}|{@link #FIELD_ACCESS} indicating - * how the entity properties are mapped. Does not return null (defaults to - * {@link #FIELD_ACCESS}). - */ - public String getAccess() { - String name = customized(ACCESS); - if (name == null) { - name = FIELD_ACCESS; - } - return name; - } - - public void setAccess(String access) { - assert (access == null || access.equals(PROPERTY_ACCESS) || access.equals(FIELD_ACCESS)); - if (!StringUtil.equalObjects(access, getAccess())) { - setCustomized(ACCESS, access); - } - } - - /** - * Returns one of {@link #LAZY_FETCH}|{@link #EAGER_FETCH} indicating how - * the table associations are feched. Returns null if the provider defaults - * should be used. - */ - public String getDefaultFetch() { - return customized(DEFAULT_FETCH); - } - - public void setDefaultFetch(String fetch) { - assert (fetch == null || fetch.equals(LAZY_FETCH) || fetch.equals(EAGER_FETCH)); - setCustomized(DEFAULT_FETCH, fetch); - } - - public String[] getSupportedCollectionTypes() { - return new String[] { - SET_COLLECTION_TYPE, LIST_COLLECTION_TYPE - }; - } - - /** - * Returns one of {@link #LIST_COLLECTION_TYPE}|{@link #SET_COLLECTION_TYPE} - * indicating the Java type (full class name) used for properties of - * collection types. This does not return null (defaults to list). - */ - public String getDefaultCollectionType() { - String cType = customized(DEFAULT_COLLECTION_TYPE); - if (cType == null) { - cType = SET_COLLECTION_TYPE; - } - return cType; - } - - public String getSimpleCollectionType(){ - String type = getDefaultCollectionType(); - return type.substring( type.lastIndexOf('.') +1 ); - } - - public void setDefaultCollectionType(String cType) { - assert (cType.equals(LIST_COLLECTION_TYPE) || cType.equals(SET_COLLECTION_TYPE)); - setCustomized(DEFAULT_COLLECTION_TYPE, cType); - } - - /** - * Returns true if the primary key is compound and any of its columns should - * be included in the <code>equals</code> method implementation. - */ - public boolean isCompoundKeyUseInEquals() { - if (isCompositeKey()) { - for (Iterator<ORMGenColumn> iter = getPrimaryKeyColumns().iterator(); iter.hasNext();) { - ORMGenColumn column = iter.next(); - if (column.isUseInEquals()) { - return true; - } - } - } - return false; - } - - public boolean isRoleUseInEquals(AssociationRole role) { - for (Iterator<ORMGenColumn> iter = role.getReferrerColumns().iterator(); iter.hasNext();) { - ORMGenColumn column = iter.next(); - if (column.isUseInEquals()) { - return true; - } - } - return false; - } - - /** - * Return true if the values of name element in the @Table is default so we - * can skip generating the annotation - * - * @return true - */ - public boolean isDefaultname() { - String entityName = getClassName(); - String annotationName = this.mCustomizer.getDatabaseAnnotationNameBuilder().buildTableAnnotationName(entityName, mDbTable); - return annotationName == null; - } - - /** - * Qualifies a class name if there is a package. - */ - private String qualify(String className) { - String pkg = getPackage(); - if (pkg != null && pkg.length() != 0) { - className = pkg + '.' + className; - } - return className; - } - - /** - * Returns true if the given column is part of any association. - */ - private boolean isColumnInAsscociation(ORMGenColumn column, List<AssociationRole> roles) { - for (int i = 0, n = roles.size(); i < n; ++i) { - AssociationRole role = roles.get(i); - List<ORMGenColumn> cols = role.getReferrerColumns(); - for (ORMGenColumn col : cols) { - if (col.getName().equals(column.getName())) { - return true; - } - } - } - return false; - } - - /** - * Print the clause to be used in the generated equals() method - * - * @return String - */ - public String getPrimaryKeyEqualsClause() { - StringBuilder buf = new StringBuilder(); - Iterator<ORMGenColumn> columns = this.getPrimaryKeyColumns().iterator(); - while (columns.hasNext()) { - this.printPrimaryKeyEqualsClauseOn(columns.next(), buf); - if (columns.hasNext()) { - buf.append("\n"); - buf.append("\t\t\t"); - buf.append("&& "); - } - } - buf.append(";"); - return buf.toString(); - } - - private void printPrimaryKeyEqualsClauseOn(ORMGenColumn column, StringBuilder buf) { - String fieldName = column.getPropertyName(); - JavaType javaType = column.getDbColumn().getPrimaryKeyJavaType(); - if (javaType.isPrimitive()) { - this.printPrimitiveEqualsClauseOn(fieldName, buf); - } - else { - this.printReferenceEqualsClauseOn(fieldName, buf); - } - } - - private void printPrimitiveEqualsClauseOn(String fieldName, StringBuilder buf) { - buf.append("(this."); - buf.append(fieldName); - buf.append(" == castOther."); - buf.append(fieldName); - buf.append(')'); - } - - private void printReferenceEqualsClauseOn(String fieldName, StringBuilder buf) { - buf.append("this."); - buf.append(fieldName); - buf.append(".equals(castOther."); - buf.append(fieldName); - buf.append(')'); - } - - /** - * Print the clause to be used in the generated hasCode() method - * - * @return String - */ - public String getPrimaryKeyHashCodeClause() { - StringBuilder buf = new StringBuilder(); - Iterator<ORMGenColumn> columns = this.getPrimaryKeyColumns().iterator(); - while (columns.hasNext()) { - buf.append("hash = hash * prime + "); - this.printPrimaryKeyHashCodeClauseOn(columns.next(), buf); - buf.append(';'); - buf.append('\n'); - buf.append("\t\t"); - } - return buf.toString(); - } - - private void printPrimaryKeyHashCodeClauseOn(ORMGenColumn column, StringBuilder buf) { - String fieldName = column.getPropertyName(); - JavaType javaType = column.getDbColumn().getPrimaryKeyJavaType(); - if (javaType.isPrimitive()) { - this.printPrimitiveHashCodeClauseOn(javaType.getElementTypeName(), fieldName, buf); - } - else { - this.printReferenceHashCodeClauseOn(fieldName, buf); - } - } - - private void printPrimitiveHashCodeClauseOn(String primitiveName, String fieldName, StringBuilder buf) { - if (primitiveName.equals("int")) { - // this.value - buf.append("this."); - buf.append(fieldName); - } - else if (primitiveName.equals("short") || primitiveName.equals("byte") || primitiveName.equals("char")) { // explicit - // cast - // ((int) this.value) - buf.append("((int) this."); - buf.append(fieldName); - buf.append(')'); - } - else if (primitiveName.equals("long")) { // cribbed from Long#hashCode() - // ((int) (this.value ^ (this.value >>> 32))) - buf.append("((int) (this."); - buf.append(fieldName); - buf.append(" ^ (this."); - buf.append(fieldName); - buf.append(" >>> 32)))"); - } - else if (primitiveName.equals("float")) { // cribbed from - // Float#hashCode() - // java.lang.Float.floatToIntBits(this.value) - buf.append("java.lang.Float"); - buf.append(".floatToIntBits(this."); - buf.append(fieldName); - buf.append(')'); - } - else if (primitiveName.equals("double")) { // cribbed from - // Double#hashCode() - // ((int) (java.lang.Double.doubleToLongBits(this.value) ^ - // (java.lang.Double.doubleToLongBits(this.value) >>> 32))) - buf.append("((int) ("); - buf.append("java.lang.Double"); - buf.append(".doubleToLongBits(this."); - buf.append(fieldName); - buf.append(") ^ ("); - buf.append("java.lang.Double"); - buf.append(".doubleToLongBits(this."); - buf.append(fieldName); - buf.append(") >>> 32)))"); - } - else if (primitiveName.equals("boolean")) { - // (this.value ? 1 : 0) - buf.append("(this."); - buf.append(fieldName); - buf.append(" ? 1 : 0)"); - } - else { - throw new IllegalArgumentException(primitiveName); - } - } - - private void printReferenceHashCodeClauseOn(String fieldName, StringBuilder buf) { - buf.append("this."); - buf.append(fieldName); - buf.append(".hashCode()"); - } - - @Override - public String toString() { - return "name=" + this.getName() + "; columns=" + Arrays.toString(this.getColumnNames().toArray()); - } - - /* class scopes */ - public static final String PUBLIC_SCOPE = "public"; - - public static final String PROTECTED_SCOPE = "protected"; - - public static final String PRIVATE_SCOPE = "private"; - - /* access constants. Note that these strings are used in the ui */ - public static final String PROPERTY_ACCESS = "property"; - - public static final String FIELD_ACCESS = "field"; - - /* - * default fech constants. Note that these strings are used in the gen - * velocity templates. - */ - public static final String DEFAULT_FETCH = "defaultFetch"; - - public static final String LAZY_FETCH = "lazy"; - - public static final String EAGER_FETCH = "eager"; - - /* - * default collection type constants. Note that these strings are used in - * the gen velocity templates. - */ - public static final String LIST_COLLECTION_TYPE = "java.util.List"; - - public static final String SET_COLLECTION_TYPE = "java.util.Set"; - - /** - * The pattern replaced by the table name in the id generator sequence name - * param. - */ - public static final String TABLE_SEQ_PATTERN = "$table"; - - /** - * The pattern replaced by the primary key in the id generator sequence name - * param. - */ - public static final String PK_SEQ_PATTERN = "$pk"; - - /* customization properties */ - private static final String PACKAGE = "package"; - - private static final String SRC_FOLDER = "srcFolder"; - - private static final String CLASS_NAME = "className"; - - private static final String CLASS_DESC = "classDesc"; - - private static final String CLASS_SCOPE = "classScope"; - - private static final String EXTENDS = "extends"; - - private static final String IMPLEMENTS = "implements"; - - private static final String ID_GENERATOR = "idGenerator"; - - private static final String SEQUENCE = "sequence"; - - private static final String COMPOSITE_KEY_CLASS_NAME = "compositeKeyClassName"; - - private static final String IMPLEMENT_EQUALS = "implementEquals"; - - private static final String ACCESS = "access"; - - private static final String DEFAULT_COLLECTION_TYPE = "defaultCollectionType"; -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/OverwriteConfirmer.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/OverwriteConfirmer.java deleted file mode 100644 index 8e9d7e1dcb..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/OverwriteConfirmer.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -public interface OverwriteConfirmer { - /** - * Return whether the entity generator should overwrite the specified - * file. - */ - boolean overwrite(String className); - - - final class Always implements OverwriteConfirmer { - public static final OverwriteConfirmer INSTANCE = new Always(); - public static OverwriteConfirmer instance() { - return INSTANCE; - } - // ensure single instance - private Always() { - super(); - } - // everything will be overwritten - public boolean overwrite(String arg0) { - return true; - } - @Override - public String toString() { - return "OverwriteConfirmer.Always"; //$NON-NLS-1$ - } - } - - - final class Never implements OverwriteConfirmer { - public static final OverwriteConfirmer INSTANCE = new Never(); - public static OverwriteConfirmer instance() { - return INSTANCE; - } - // ensure single instance - private Never() { - super(); - } - // nothing will be overwritten - public boolean overwrite(String arg0) { - return false; - } - @Override - public String toString() { - return "OverwriteConfirmer.Never"; //$NON-NLS-1$ - } - } - -}
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/PackageGenerator2.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/PackageGenerator2.java deleted file mode 100644 index 4b1699d031..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/PackageGenerator2.java +++ /dev/null @@ -1,292 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ - -package org.eclipse.jpt.gen.internal2; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.net.URL; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.runtime.log.JdkLogChute; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.FileLocator; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubMonitor; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jpt.gen.internal2.util.CompilationUnitModifier; -import org.eclipse.jpt.gen.internal2.util.FileUtil; -import org.eclipse.jpt.gen.internal2.util.UrlUtil; -import org.eclipse.osgi.util.NLS; -import org.osgi.framework.Bundle; - -/** - * This generator will generate a package of entities for a set of tables. - */ -public class PackageGenerator2 { - - private static final String LOGGER_NAME = "org.eclipse.jpt.entities.gen.log"; //$NON-NLS-1$ - private IJavaProject javaProject; - private ORMGenCustomizer customizer ; - private static OverwriteConfirmer overwriteConfirmer = null; - - static public void setOverwriteConfirmer(OverwriteConfirmer confirmer){ - overwriteConfirmer = confirmer; - } - /** - * @param customizer - * @param synchronizePersistenceXml - * @param copyJdbcDrive - * @throws Exception - */ - static public void generate(IJavaProject jpaProject, ORMGenCustomizer customizer, IProgressMonitor monitor ) throws CoreException { - PackageGenerator2 generator = new PackageGenerator2(); - generator.setProject(jpaProject); - generator.setCustomizer(customizer); - - try { - generator.doGenerate( monitor); - } catch (Exception e) { - throw new CoreException(new Status(IStatus.ERROR, JptGenPlugin.PLUGIN_ID, JptGenMessages.Error_Generating_Entities, e)); - } - } - - private Object getCustomizer() { - return this.customizer; - } - - private void setCustomizer(ORMGenCustomizer customizer2) { - this.customizer = customizer2; - } - - private void setProject(IJavaProject proj ){ - this.javaProject = proj; - } - - protected void doGenerate( IProgressMonitor monitor ) throws Exception { - generateInternal( monitor ); - } - - protected void generateInternal( IProgressMonitor progress) throws Exception { - File templDir = prepareTemplatesFolder(); - - List<String> genClasses = new java.util.ArrayList<String>(); - List<String> tableNames = customizer.getGenTableNames(); - - /* .java per table, persistence.xml, refresh package folder */ - String taskName = NLS.bind(JptGenMessages.EntityGenerator_taskName, "Total "+ tableNames.size() + 2);//$NON-NLS-1$ - progress.beginTask(taskName, tableNames.size() + 2); - - - for (Iterator<String> iter = tableNames.iterator(); iter.hasNext();) { - String tableName = iter.next(); - ORMGenTable table = customizer.getTable(tableName); - - String className = table.getQualifiedClassName(); - - generateClass(table, templDir.getAbsolutePath(), progress); - progress.worked(1); - - genClasses.add( className ); - /* - * add the composite key class to persistence.xml because some - * JPA provider(e.g. Kodo) requires it. Hibernate doesn't seem to care). - */ - if (table.isCompositeKey()) { - genClasses.add(table.getQualifiedCompositeKeyClassName()); - } - } - progress.done(); - } - - private File prepareTemplatesFolder() throws IOException, Exception, - CoreException { - //Prepare the Velocity template folder: - //If the plug-in is packaged as a JAR, we need extract the template - //folder into the plug-in state location. This is required by Velocity - //since we use included templates. - Bundle bundle = Platform.getBundle(JptGenPlugin.PLUGIN_ID); - String templatesPath = "templates/entities/"; //$NON-NLS-1$ - Path path = new Path( templatesPath); - URL url = FileLocator.find(bundle, path, null); - if ( url ==null ) { - throw new CoreException(new Status(IStatus.ERROR, JptGenPlugin.PLUGIN_ID, JptGenMessages.Templates_notFound + " "+ JptGenPlugin.PLUGIN_ID + "/" + templatesPath) );//$NON-NLS-1$ - } - URL templUrl = FileLocator.resolve(url); - - //Have this check so that the code would work in both PDE and JARed plug-in at runtime - File templDir = null; - if( UrlUtil.isJarUrl(templUrl) ){ - templDir = FileUtil.extractFilesFromBundle( templUrl, bundle, templatesPath ); - }else{ - templDir = UrlUtil.getUrlFile(templUrl); - } - - - if (templDir==null || !templDir.exists()) { - throw new CoreException(new Status(IStatus.ERROR, JptGenPlugin.PLUGIN_ID, JptGenMessages.Templates_notFound + " "+ JptGenPlugin.PLUGIN_ID ) );//$NON-NLS-1$ - } - return templDir; - } - - /** - * Saves/Creates the .java file corresponding to a database table - * with the given content. - * - * @param templDir The velocity template file directory. It is assumed - * that this directory contains the 2 files <em>main.java.vm</em> - * and <em>pk.java.vm</em> - * @param progress - */ - protected void generateClass(ORMGenTable table, String templateDirPath, IProgressMonitor monitor) throws Exception { - - String subTaskName = NLS.bind(JptGenMessages.EntityGenerator_taskName, table.getName()); - SubMonitor sm = SubMonitor.convert(monitor, subTaskName, 100); - - try{ - IFolder javaPackageFolder = getJavaPackageFolder(table, monitor); - IFile javaFile = javaPackageFolder.getFile( table.getClassName() + ".java"); //$NON-NLS-1$ - - if( javaFile.exists() ){ - if( overwriteConfirmer!=null && !overwriteConfirmer.overwrite(javaFile.getName()) ) - return; - } - //JdkLogChute in this version of Velocity not allow to set log level - //Workaround by preset the log level before Velocity is initialized - Logger logger = Logger.getLogger( LOGGER_NAME ); - logger.setLevel( Level.SEVERE ); - - Properties vep = new Properties(); - vep.setProperty("file.resource.loader.path", templateDirPath); //$NON-NLS-1$ - vep.setProperty( JdkLogChute.RUNTIME_LOG_JDK_LOGGER, LOGGER_NAME ); - VelocityEngine ve = new VelocityEngine(); - ve.init(vep); - sm.worked(20); - - generateJavaFile(table, javaFile, ve, "main.java.vm", true/*isDomainClass*/, monitor); //$NON-NLS-1$ - sm.worked(80); - - if (table.isCompositeKey()) { - IFile compositeKeyFile = javaPackageFolder.getFile( table.getCompositeKeyClassName()+".java"); //$NON-NLS-1$ - generateJavaFile(table, compositeKeyFile, ve, "pk.java.vm", false/*isDomainClass*/, monitor ); //$NON-NLS-1$ - } - - javaFile.refreshLocal(1, new NullProgressMonitor()); - - } catch(Throwable e){ - CoreException ce = new CoreException(new Status(IStatus.ERROR, JptGenPlugin.PLUGIN_ID, JptGenMessages.Templates_notFound + "" + JptGenPlugin.PLUGIN_ID , e) );//$NON-NLS-1$ - JptGenPlugin.logException( ce ); - } - sm.setWorkRemaining(0); - } - - private void generateJavaFile(ORMGenTable table, IFile javaFile, VelocityEngine ve - , String templateName, boolean isDomainClass, IProgressMonitor monitor) throws Exception { - VelocityContext context = new VelocityContext(); - context.put("table", table); //$NON-NLS-1$ - context.put("customizer", getCustomizer()); //$NON-NLS-1$ - - StringWriter w = new StringWriter(); - ve.mergeTemplate(templateName, context, w); - - String fileContent = w.toString(); - if (javaFile.exists()) { - if (isDomainClass) { - updateExistingDomainClass(table.getQualifiedClassName(), javaFile, fileContent); - } else { - javaFile.setContents(new ByteArrayInputStream(fileContent.getBytes()), true, true, monitor ); - } - } else { - createFile(javaFile, new ByteArrayInputStream(fileContent.getBytes())); - } - } - - - /** - * Updates the (existing) Java file corresponding to the given class. - * - * @param className The qualified class name. - * - * @param javaFile The existing Java file of the class to update. - * - * @param fileContent The new file content. - */ - protected void updateExistingDomainClass(String className, IFile javaFile, String fileContent) throws Exception { - /*use CompilationUnitModifier instead of calling WideEnv.getEnv().setFileContent - * so that if the unit is up to date if it is used before file change - * notifications are delivered (see EJB3ImportSchemaWizard.updateExistingDomainClass for example)*/ - IJavaProject project = javaProject.getJavaProject(); - CompilationUnitModifier modifier = new CompilationUnitModifier(project, className); - modifier.setJavaSource(fileContent); - modifier.save(); - } - - public void createFile(IFile file, java.io.InputStream contents) throws CoreException { - file.create(contents, false, null/*monitor*/); - } - - public IFolder getJavaPackageFolder(ORMGenTable table, IProgressMonitor monitor) throws CoreException { - IPackageFragmentRoot root = getDefaultJavaSrouceLocation ( javaProject , table.getSourceFolder()) ; - String packageName = table.getPackage(); - if( packageName==null ) packageName =""; - IPackageFragment packageFragment = root.getPackageFragment(packageName); - if( !packageFragment.exists()){ - root.createPackageFragment(packageName, true, monitor); - } - return (IFolder)packageFragment.getResource(); - } - - private IPackageFragmentRoot getDefaultJavaSrouceLocation(IJavaProject jproject, String sourceFolder){ - IPackageFragmentRoot defaultSrcPath = null; - if (jproject != null) { - try { - if (jproject.exists()) { - IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots(); - for (int i= 0; i < roots.length; i++) { - if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE ){ - if( i == 0 ) - defaultSrcPath = roots[i]; - String path = roots[i].getPath().toString(); - if( path.equals( "/"+sourceFolder )) { - return roots[i] ; - } - } - } - } - } catch (JavaModelException e) { - JptGenPlugin.logException(e); - } - } - return defaultSrcPath; - } - - - // ********** annotation name builder ********** - - -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/TagNames.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/TagNames.java deleted file mode 100644 index 92a60fed77..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/TagNames.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2; - -/** - * TODO: merge with JPA class ? - * The JPA mapping tag and attribute names. - * - */ -public class TagNames -{ - public static final String BASIC_TAG = "basic"; - public static final String CASCADE_TAG = "cascade"; - public static final String COLUMN_TAG = "column"; - public static final String EMBEDDED_TAG = "embedded"; - public static final String EMBEDDED_ID_TAG = "embedded-id"; - public static final String GENERATED_VALUE_TAG = "generated-value"; - public static final String ID_TAG = "id"; - public static final String ID_CLASS_TAG = "id"; - public static final String JOIN_COLUMN_TAG = "join-column"; - public static final String INVERSE_JOIN_COLUMN_TAG = "inverse-join-column"; - public static final String LOB_TAG = "lob"; - public static final String MANY_TO_MANY_TAG = "many-to-many"; - public static final String MANY_TO_ONE_TAG = "many-to-one"; - public static final String MAPPED_BY_TAG = "mapped-by"; - public static final String ONE_TO_MANY_TAG = "one-to-many"; - public static final String ONE_TO_ONE_TAG = "one-to-one"; - public static final String PK_JOIN_COLUMN_TAG = "primary-key-join-column"; - public static final String TABLE_TAG = "table"; - public static final String VERSION_TAG = "version"; - public static final String JOIN_TABLE_TAG = "join-table"; - - /*cascade tags*/ - public static final String ALL_CASCADE = "all"; - public static final String PERSIST_CASCADE = "persist"; - public static final String MERGE_CASCADE = "merge"; - public static final String REMOVE_CASCADE = "remove"; - public static final String REFRESH_CASCADE = "refresh"; -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/CompilationUnitModifier.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/CompilationUnitModifier.java deleted file mode 100644 index 04cf6366ba..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/CompilationUnitModifier.java +++ /dev/null @@ -1,131 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2.util; - -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTParser; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jface.text.Document; -import org.eclipse.text.edits.TextEdit; - - -/** - * Performs the grunt work needed for modifying a compilation - * unit and performs the modified compilation unit save. - * - * The typical usage is as follows: - * <ol><li>Create an instance. - * - * <li>Modify the compilation unit using AST operations performed - * on the node returned by {@link #getCompilationUnitNode()}. - * Alternatively you can call <code>setJavaSource</code> to change the entire source code. - * - * <li>Call the {@link #save()} method. - * - */ -public class CompilationUnitModifier -{ - private IJavaProject mProject; - private ICompilationUnit mCompilationUnit; - private CompilationUnit mCompilationUnitNode; - private Document mDocument; - - public CompilationUnitModifier(IJavaProject project, String className) throws Exception { - super(); - - mProject = project; - - IType type = project.findType(className); - if (type == null) { - throw new Exception("The class " + className + " does not exist."); - } - mCompilationUnit = type.getCompilationUnit(); - if (mCompilationUnit == null) { - throw new Exception("The source code for " + className + " does not exist."); - } - } - public CompilationUnitModifier(IJavaProject project, ICompilationUnit cu) throws Exception { - super(); - - mProject = project; - mCompilationUnit = cu; - } - public CompilationUnitModifier(IJavaProject project, ICompilationUnit cu, CompilationUnit cuNode) throws Exception { - super(); - - mProject = project; - mCompilationUnit = cu; - mCompilationUnitNode = cuNode; - - getCompilationUnitNode(); //to create mDocument (the caller in this case does not have to call getCompilationUnitNode) - } - public ICompilationUnit getCompilationUnit() { - return mCompilationUnit; - } - /** - * Returns the compilation unit node that should be used for - * tyhe modification AST operations. - */ - public CompilationUnit getCompilationUnitNode() { - if (mCompilationUnitNode == null) { - ASTParser c = ASTParser.newParser(AST.JLS3); - c.setSource(mCompilationUnit); - c.setResolveBindings(true); - mCompilationUnitNode = (CompilationUnit)c.createAST(null); - } - if (mDocument == null) { - try { - mDocument = new Document(mCompilationUnit.getBuffer().getContents()); - } catch (JavaModelException e) { - e.printStackTrace(); - } - - mCompilationUnitNode.recordModifications(); - } - - return mCompilationUnitNode; - } - /** - * Changes the entire Java source code of the compilation unit. - */ - public void setJavaSource(String newSource) { - try { - mCompilationUnit.getBuffer().setContents(newSource); - } catch (JavaModelException e) { - e.printStackTrace(); - } - } - /** - * Saves the compilation unit modifications. - */ - public void save() throws Exception { - if (mCompilationUnitNode != null) { - assert(mDocument != null); //see getCompilationUnitNode - - //computation of the text edits - TextEdit edits = mCompilationUnitNode.rewrite(mDocument, mProject.getOptions(true)); - //computation of the new source code - edits.apply(mDocument); - String newSource = mDocument.get(); - // update of the compilation unit - mCompilationUnit.getBuffer().setContents(newSource); - } - - if (mCompilationUnit.isWorkingCopy()) { - mCompilationUnit.commitWorkingCopy(true/*force*/, null/*monitor*/); - } else { - mCompilationUnit.save(null/*monitor*/, true/*force*/); - } - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/DTPUtil.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/DTPUtil.java deleted file mode 100644 index bc93da0cb9..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/DTPUtil.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2.util; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.db.Schema; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.db.ForeignKey.ColumnPair; -import org.eclipse.jpt.gen.internal2.ForeignKeyInfo; - -/** - * Collection of utility methods to access DTP and other jpt.db APIs - * - */ -public class DTPUtil { - - /** - * Return list of the pk names - * @param dbTable - * @return - */ - public static List<String> getPrimaryKeyColumnNames(Table dbTable ) { - Iterator<Column> pkColumns = dbTable.primaryKeyColumns(); - ArrayList<String> ret = new ArrayList<String>(); - while( pkColumns.hasNext() ){ - ret.add( pkColumns.next().getName() ); - } - return ret; - } - - /** - * - * @param dbTable - * @return - */ - public static List<Column> getPrimaryKeyColumns(Table dbTable ) { - Iterator<Column> pkColumns = dbTable.primaryKeyColumns(); - ArrayList<Column> ret = new ArrayList<Column>(); - while( pkColumns.hasNext() ){ - ret.add( pkColumns.next() ); - } - return ret; - } - - public static boolean isAutoIncrement(Column c){ - //@ TODO - //Blocked by DTP bug - //https://bugs.eclipse.org/bugs/show_bug.cgi?id=250023 - //The Dali bug is - //https://bugs.eclipse.org/bugs/show_bug.cgi?id=249658 - // - return false; - } - - /** - * Return list of fk - * @param dbTable - * @return - */ - public static List<ForeignKeyInfo> getForeignKeys(Table dbTable) { - List<ForeignKeyInfo> ret = new ArrayList<ForeignKeyInfo>(); - if(dbTable!=null){ - Iterator<ForeignKey> fks = dbTable.foreignKeys(); - while( fks.hasNext() ){ - ForeignKey fk = fks.next(); - Iterator<ColumnPair> columnPaires = fk.columnPairs(); - ForeignKeyInfo fkInfo = null; - while( columnPaires.hasNext() ){ - ColumnPair columnPair = columnPaires.next(); - if( fkInfo == null){ - String tableName = dbTable.getName(); - String referencedTableName = ""; - Table referencedTable = fk.getReferencedTable(); - referencedTableName = referencedTable.getName(); - fkInfo = new ForeignKeyInfo(fk, tableName, referencedTableName ); - } - String baseColName = columnPair.getBaseColumn().getName(); - String referencedColName = columnPair.getReferencedColumn().getName(); - fkInfo.addColumnMapping( baseColName, referencedColName ); - } - if( fkInfo !=null ) - ret.add( fkInfo ); - } - } - return ret; - } - - public static String getJavaType(Schema schema, Column dbColumn) { - if( isPrimaryKey(dbColumn) ) - return dbColumn.getPrimaryKeyJavaTypeDeclaration(); - return dbColumn.getJavaTypeDeclaration(); - } - - public static boolean isPrimaryKey(Column dbColumn){ - Table dbTable = dbColumn.getTable(); - Iterator<Column> pkColumns = dbTable.primaryKeyColumns(); - while( pkColumns.hasNext() ){ - if( pkColumns.next().equals( dbColumn )){ - return true; - } - } - return false; - } - - public static boolean isDefaultSchema(Table dbTable){ - String schemaName = dbTable.getSchema().getName(); - Schema defaultSchema = dbTable.getSchema().getConnectionProfile().getDatabase().getDefaultSchema(); - return defaultSchema.getName() == schemaName; - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/FileUtil.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/FileUtil.java deleted file mode 100644 index ddbb6777c1..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/FileUtil.java +++ /dev/null @@ -1,218 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2.util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.jar.JarInputStream; -import java.util.jar.Manifest; -import java.util.zip.ZipEntry; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.osgi.service.datalocation.Location; -import org.osgi.framework.Bundle; - -/** - * Collections of utility methods handling files. - * - */ -public class FileUtil -{ - - private static String DELETE_FOLDER_ERR = "The directory %s could not be deleted."; - private static String DELETE_FILE_ERR = "The file %s could not be deleted."; - private static String FILE_READONLY_ERR = "The file %s could not be modified because write access is denied.\nPlease make sure that the file is not marked as readonly in the file system."; - - public static void deleteFolder(File folder) - throws IOException - { - File[] files = folder.listFiles(); - //empty the folder first (java.io.file.delete requires it empty) - if (files != null) { - for (int i = 0; i < files.length; ++i) { - File f = files[i]; - if (f.isDirectory()) - deleteFolder(f); - else - deletePath(f); - } - } - deletePath(folder); - } - - public static void deletePath(File f) - throws IOException - { - if (!f.delete()) { - String msgId = f.isDirectory() ? DELETE_FOLDER_ERR : DELETE_FILE_ERR; - throw new IOException( String.format(msgId,f.getPath())); - } - } - - public static byte[] readFile(File src) - throws IOException - { - java.io.FileInputStream fin = new java.io.FileInputStream(src); - try { - long fileLen = src.length(); - if (fileLen > Integer.MAX_VALUE) - throw new IOException("file length too big to be read by FileUtil.readFile: " + fileLen); - - byte[] bytes = new byte[(int)fileLen]; - fin.read(bytes); - return bytes; - } - finally { - fin.close(); - } - } - - public static void writeFile(File dest, byte[] bytes) - throws IOException - { - if (dest.exists() && !dest.canWrite()) - throw new IOException( FILE_READONLY_ERR ); //throw with a clear error because otherwise FileOutputStream throws FileNotFoundException! - java.io.FileOutputStream fout = new java.io.FileOutputStream(dest.getPath(), false/*append*/); - try { - fout.write(bytes); - } - finally { - fout.flush(); - fout.close(); - } - } - - /** - * Returns the url for a file. - * This basically the same as file.toUrl() but without the non-sense exception. - */ - public static URL getFileUrl(File file) { - try { - return file.toURI().toURL(); - } catch (MalformedURLException e) { - return null; //should not happen as file.toURL() does not really throw an exception - } - } - - public static void setFileContent(File file, java.io.InputStream contents) throws java.io.IOException { - Path path = new Path(file.getAbsolutePath()); - try { - IFile iFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path); - if (iFile == null) { - throw new IOException("The path " + file + " does not seem to be a valid file path."); - } - iFile.setContents(contents, true/*force*/, true/*keepHistory*/, null/*monitor*/); - } catch (CoreException ex) { - throw new IOException(ex.getMessage()); - } - } - - /** - * Extract the contents of a Jar archive to the specified destination. - */ - public static void unjar(InputStream in, File dest) throws IOException { - if (!dest.exists()) { - dest.mkdirs(); - } - if (!dest.isDirectory()) { - throw new IOException("Destination must be a directory.");//$NON-NLS-1$ - } - JarInputStream jin = new JarInputStream(in); - byte[] buffer = new byte[1024]; - - ZipEntry entry = jin.getNextEntry(); - while (entry != null) { - String fileName = entry.getName(); - if (fileName.charAt(fileName.length() - 1) == '/') { - fileName = fileName.substring(0, fileName.length() - 1); - } - if (fileName.charAt(0) == '/') { - fileName = fileName.substring(1); - } - if (File.separatorChar != '/') { - fileName = fileName.replace('/', File.separatorChar); - } - File file = new File(dest, fileName); - if (entry.isDirectory()) { - // make sure the directory exists - file.mkdirs(); - jin.closeEntry(); - } else { - // make sure the directory exists - File parent = file.getParentFile(); - if (parent != null && !parent.exists()) { - parent.mkdirs(); - } - - // dump the file - OutputStream out = new FileOutputStream(file); - int len = 0; - while ((len = jin.read(buffer, 0, buffer.length)) != -1) { - out.write(buffer, 0, len); - } - out.flush(); - out.close(); - jin.closeEntry(); - file.setLastModified(entry.getTime()); - } - entry = jin.getNextEntry(); - } - /* Explicitly write out the META-INF/MANIFEST.MF so that any headers such - as the Class-Path are seen for the unpackaged jar - */ - Manifest mf = jin.getManifest(); - if (mf != null) { - File file = new File(dest, "META-INF/MANIFEST.MF");//$NON-NLS-1$ - File parent = file.getParentFile(); - if (parent.exists() == false) { - parent.mkdirs(); - } - OutputStream out = new FileOutputStream(file); - mf.write(out); - out.flush(); - out.close(); - } - jin.close(); - } - - //Used to Unzip the a specific folder packed inside a plug-in bundle to the plug-in state location - public static File extractFilesFromBundle( URL url, Bundle bundle, String path ) throws Exception { - URL jarUrl = UrlUtil.getJarFileUrl(url); - File jarFile = new File(jarUrl.getFile() ); - Location configLocation = Platform.getConfigurationLocation(); - String pluginId = bundle.getSymbolicName(); - File configFolder = new File( configLocation.getURL().getFile(), pluginId); - File templDir = new File( configFolder, path ); - if( !templDir.exists() ){ - FileUtil.unjar( new FileInputStream( jarFile ), configFolder ); - //Delete un-related files and folders - File[] files = configFolder.listFiles(); - for( File f : files ){ - if( f.isFile() ) - f.delete(); - else if( templDir.getPath().indexOf( f.getPath() ) !=0 ){ - FileUtil.deleteFolder(f); - } - } - } - return templDir ; - } -} - diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/StringUtil.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/StringUtil.java deleted file mode 100644 index 2574eedf09..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/StringUtil.java +++ /dev/null @@ -1,648 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.gen.internal2.util; - -import java.beans.Introspector; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -public class StringUtil -{ - /** - * Pads a string by adding a sequence of an arbitrary character at the beginning. - * @param padChar The character to be used for padding. - * @param len The desired length after padding. - * @return The padded string. For example if <code>str</code> is "f4e" and <code>padChar</code> is '0' - * and <code>len</code> is 6 then this method returns "000f4e" - */ - public static String padLeft(String str, char padChar, int len) { - if(str == null) { - return null; - } - int strLen = str.length(); - if (strLen < len) { - StringBuffer buffer = new StringBuffer(len); - int count = len-strLen; - for (int i = 0; i < count; ++i) - buffer.append(padChar); - buffer.append(str); - str = buffer.toString(); - } - return str; - } - /** - * Inserts a given character at the beginning and at the end of the specified string. - * For example if the string is <tt>extreme</tt> and the char is <tt>'</tt> then - * the returned string is <tt>'exterme'</tt>. - */ - public static String quote(String str, char c) { - assert(str != null); - StringBuffer buffer = new StringBuffer(str.length()+2); - buffer.append(c); - buffer.append(str); - buffer.append(c); - return buffer.toString(); - } - public static String doubleQuote(String str) { - return quote(str, '"'); - } - /** - * Removes the first and last single or double quotes (if they exist). - */ - public static String unquote(String quoted) { - if (quoted != null && quoted.length() >= 2){ - int len = quoted.length(); - char firstChar = quoted.charAt(0); - char lastChar = quoted.charAt(len-1); - if (firstChar == lastChar && (firstChar == '\'' || firstChar == '"')) { - return quoted.substring(1, len-1); - } - } - return quoted; - } - /** - * Truncates a string and adds "..." in the result string. - * If the string length is less or equal to the max len then - * the original string is returned. - */ - public static String truncate(String s, int maxLen) { - if (s == null) { - return null; - } - int len = s.length(); - if (len > maxLen) { - int segmentLen = maxLen/2; - s = s.substring(0, segmentLen) + "..." + s.substring(len-segmentLen); - } - return s; - } - /** - * Returns a string containing the same character repeated. - */ - public static String repeat(char c, int count) { - StringBuffer buffer = new StringBuffer(count); - for (int i = 0; i < count; ++i) { - buffer.append(c); - } - return buffer.toString(); - } - /** - * Returns the given string unless it is emtpty where it returns null. - */ - public static String nullIfEmpty(String s) { - if (s != null && s.length() == 0) { - s = null; - } - return s; - } - /** - * Returns a string containing the same characters as the argument string - * except that the control characters are replaced by the their hex code. - * For example if the string is "ab\nc" the returned string is "ab{0xA}c". - */ - public static String getVisibleString(String s) { - if (s == null) - return null; - int len = s.length(); - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < len; ++i) { - char c = s.charAt(i); - if (c <= 0x1F || (c == 0x20 && (i == 0 || i == len-1))) { - buffer.append("(0x" + Integer.toHexString((int)c).toUpperCase() + ")"); - } - else buffer.append(c); - } - return buffer.toString(); - } - /** - * Replaces a portion of string. - * @param str The original string. - * @param offset The offset in the original string where the replace starts - * @param len The replace length the original string - * @param replaceStr The replacement string - */ - public static String strReplace(String str, int offset, int len, String replaceStr) { - StringBuffer buffer = new StringBuffer(str.length()-len+replaceStr.length()); - buffer.append(str.substring(0, offset)); - buffer.append(replaceStr); - buffer.append(str.substring(offset+len)); - - return buffer.toString(); - } - public static String strReplace(String str, String pattern, String replaceStr) - { - if(str == null) { - return null; - } - if(pattern == null || pattern.equals("")) { - return str; - } - int index = str.indexOf(pattern); - if (index < 0) - return str; - - if (replaceStr == null) - replaceStr = ""; - return str.substring(0, index) + replaceStr + str.substring(index + pattern.length()); - } - public static String strReplaceAll(String str, String pattern, String replaceStr) - { - if(str == null) { - return null; - } - if (replaceStr == null) - replaceStr = ""; - if(pattern == null || pattern.equals("")) { - return str; - } - int index = str.indexOf(pattern); - while (index >= 0) { - str = str.substring(0, index) + replaceStr + str.substring(index + pattern.length()); - index = str.indexOf(pattern, index+replaceStr.length()); - } - return str; - } - public static String strInsert(String str, int index, String insertStr) - { - return str.substring(0, index) - + insertStr - + str.substring(index); - } - /** - * Tokenize the specified string into a <code>List</code> of - * words. - * If the string specified is <code>null</code> or empty, this - * method will return <code>null</code>. - * - * @param s The string to tokenize into a <code>List</code>. - * @param sep The separator character to use to split - * the string. - * @param trim If <code>true</code>, run <code>trim</code> on - * each element in the result <code>List</code>. - * - * @return A <code>List</code> containing all tokenized words - * in the parameter string. - * Each element is of type <code>String</code>. - */ - public static List<String> strToList(String s, char sep, boolean trim) - { - //ex: if sep is ';' then s should be someting like "Red;Black" - if (s == null || s.length() == 0) - return null; - - ArrayList<String> result = new ArrayList<String>(); - - char delimiters[] = {sep}; - java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(s, new String(delimiters), true/*returnDelimiters*/); - String lastTok=null; - while (tokenizer.hasMoreTokens()) { - String tok = tokenizer.nextToken(); - if (tok.length()==1 && tok.charAt(0)==sep){//delimiter - if (tok.equals(lastTok)||lastTok==null/*first element is empty*/) - result.add(""); - } - else{ - if (trim) - tok = tok.trim(); - result.add(tok); - } - lastTok=tok; - } - if(lastTok.length()==1 && lastTok.charAt(0)==sep)//last element is empty - result.add(""); - result.trimToSize(); - return result; - } - public static List<String> strToList(String s, char sep) - { - return strToList(s, sep, false/*trim*/); - } - - @SuppressWarnings("unchecked") - public static String listToStr(Collection a, char sep) - { - return listToStr(a, String.valueOf(sep)); - } - - public static String listToStr(Collection<Object> a, String sep) { - //reverse of strToList - if (a == null) - return null; - int count = a.size(); - if (count == 0) - return null; - - StringBuffer buffer = null; - for (Iterator<Object> iter = a.iterator(); iter.hasNext(); ) - { - Object obj = iter.next(); - if (obj == null) - continue; - - if (buffer == null) - buffer = new StringBuffer(); - else - buffer.append(sep); - if (obj instanceof String) - buffer.append((String)obj); - else - buffer.append(obj); - } - return (buffer != null) ? buffer.toString() : null; - } - /** - * Convert the text of a String into a Map of Strings, where each - * key and value in the Map is of type String. - * - * @param s The string to be converted to a Map. - * @param sep1 The separator between keys and their - * values. - * @param sep2 The separator between key-value pairs. - * - * @return The string converted to a Map. - */ - public static java.util.Map<String, String> strToMap(String s, char sep1, char sep2) - { - return strToMap(s, sep1, sep2, false/*lowercaseKeys*/); - } - /** - * Convert the text of a String into a Map of Strings, where each - * key and value in the Map is of type String. - * This form also allows you to specify that all keys will be - * converted to lower-case before adding to the Map. - * - * @param s The string to be converted to a Map. - * @param sep1 The separator between keys and their - * values. - * @param sep2 The separator between key-value pairs. - * @param lowercaseKeys - * Whether to convert keys to lower case - * before adding to the Map. - * - * @return The string converted to a Map. - */ - public static java.util.Map<String, String> strToMap(String s, char sep1, char sep2, boolean lowercaseKeys) - { - //ex: if sep1 is ':' and sep2 is ',' then s should be something like "color:Red,size:XL" - - if (s == null || s.length() == 0) { - return Collections.emptyMap(); - } - - java.util.List<String> a = strToList(s, sep2); - if (a == null) { - return Collections.emptyMap(); - } - - java.util.HashMap<String, String> hm = new java.util.HashMap<String, String>(); - int count = a.size(); - for (int i = 0; i < count; ++i) - { - String s2 = (String)a.get(i); //ex: color:Red - int pos = s2.indexOf(sep1); - if (pos >= 0) - { - String name = s2.substring(0, pos); - String val = s2.substring(pos+1); - if (lowercaseKeys) - name = name.toLowerCase(); - hm.put(name, val); - } - } - return hm; - } - - @SuppressWarnings("unchecked") - public static String mapToStr(java.util.Map hm, char sep1, char sep2) - //reverse of strToMap - { - if (hm == null || hm.isEmpty()) - return null; - - StringBuffer buffer = new StringBuffer(); - java.util.Iterator<java.util.Map.Entry> iter = hm.entrySet().iterator(); - while (iter.hasNext()) { - java.util.Map.Entry entry = (java.util.Map.Entry)iter.next(); - buffer.append(entry.getKey()); - buffer.append(sep1); - buffer.append(entry.getValue()); - if (iter.hasNext()) { - buffer.append(sep2); - } - } - return buffer.toString(); - } - /** - * Perform a <em>case insensitive</em> comparison between - * the string representations of two objects. - * - * @param obj1 The first object to compare. - * @param obj2 The second object to compare. - * - * @return <code>true</code> if both objects have the - * same case-insensitive string representation. - */ - public static boolean compareAsStrings(Object obj1, Object obj2) - { - if (obj1 == null || obj2 == null) - return obj1 == obj2; - - String s1, s2; - if (obj1 instanceof String) { - s1 = (String)obj1; - } else { - s1 = obj1.toString(); - } - if (obj2 instanceof String) { - s2 = (String)obj2; - } - else { - s2 = obj2.toString(); - } - - return s1.equalsIgnoreCase(s2); - } - /** - * Tests whether a string starts with any of a list of strings. - */ - public static boolean startsWithAny(String s, List<String> prefixes) { - int count = prefixes.size(); - for (int i = 0; i < count; ++i) { - if (s.startsWith((String)prefixes.get(i))) { - return true; - } - } - return false; - } - /** - * Returns the argument string with the first char upper-case. - */ - public static String initUpper(String str) { - if (str == null || str.length() == 0) { - return str; - } - return Character.toUpperCase(str.charAt(0)) + str.substring(1); - } - /** - * Returns the argument string with the first char lower-case. - */ - public static String initLower(String str) { - if (str == null || str.length() == 0) { - return str; - } - return Character.toLowerCase(str.charAt(0)) + str.substring(1); - } - /** - * Tests whether all characters in the given string are upper - * case. - */ - public static boolean isUpperCase(String s) { - return s.toUpperCase().equals(s); - } - /** - * Returns the first non-white char index starting from the - * specified index. - */ - public static int skipWhiteSpaces(String str, int index) { - int len = str.length(); - while (index < len) { - if (!Character.isWhitespace(str.charAt(index))) { - break; - } - ++index; - } - return index; - } - /** - * Collapses consecutive white spaces into one space. - */ - public static String collapseWhiteSpaces(String str){ - String result=null; - if (str!=null){ - StringBuffer buffer=new StringBuffer(); - boolean isInWhiteSpace=false; - for (int i=0;i<str.length();i++){ - char c=str.charAt(i); - if (Character.isWhitespace(c)){ - isInWhiteSpace=true; - } - else { - if (isInWhiteSpace) - buffer.append(" "); - isInWhiteSpace=false; - buffer.append(c); - } - } - result=buffer.toString(); - } - return result; - } - - /** - * Utility methods used to convert DB object names to - * appropriate Java type and field name - */ - public static String pluralise(String name) { - String result = name; - if (name.length() == 1) { - result += 's'; - } else if (!seemsPluralised(name)) { - String lower = name.toLowerCase(); - if (!lower.endsWith("data")) { //orderData --> orderDatas is dumb - char secondLast = lower.charAt(name.length() - 2); - if (!isVowel(secondLast) && lower.endsWith("y")) { - // city, body etc --> cities, bodies - result = name.substring(0, name.length() - 1) + "ies"; - } else if (lower.endsWith("ch") || lower.endsWith("s")) { - // switch --> switches or bus --> buses - result = name + "es"; - } else { - result = name + "s"; - } - } - } - return result; - } - - public static String singularise(String name) { - String result = name; - if (seemsPluralised(name)) { - String lower = name.toLowerCase(); - if (lower.endsWith("ies")) { - // cities --> city - result = name.substring(0, name.length() - 3) + "y"; - } else if (lower.endsWith("ches") || lower.endsWith("ses")) { - // switches --> switch or buses --> bus - result = name.substring(0, name.length() - 2); - } else if (lower.endsWith("s")) { - // customers --> customer - result = name.substring(0, name.length() - 1); - } - } - return result; - } - private final static boolean isVowel(char c) { - boolean vowel = false; - vowel |= c == 'a'; - vowel |= c == 'e'; - vowel |= c == 'i'; - vowel |= c == 'o'; - vowel |= c == 'u'; - vowel |= c == 'y'; - return vowel; - } - private static boolean seemsPluralised(String name) { - name = name.toLowerCase(); - boolean pluralised = false; - pluralised |= name.endsWith("es"); - pluralised |= name.endsWith("s"); - pluralised &= !(name.endsWith("ss") || name.endsWith("us")); - return pluralised; - } - - /** - * Returns the package name of a class name. - * For example if given <code>oracle.util.ObjectUtil</code> it would return - * <code>oracle.util</code>. If the class is not in a package then null is returned. - */ - public static String getPackageName(String className) { - if(className == null) { - return null; - } - int lastDotIndex = className.lastIndexOf('.'); - if (lastDotIndex < 0) - return null; - return className.substring(0, lastDotIndex); - } - /** - * Returns the class name given a full class name. - * For example if given <code>oracle.util.ObjectUtil</code> it would return - * <code>ObjectUtil</code> - */ - public static String getClassName(String fullClassName) { - if(fullClassName == null) { - return null; - } - int lastDotIndex = fullClassName.lastIndexOf('.'); - if (lastDotIndex < 0) - return fullClassName; - return fullClassName.substring(lastDotIndex+1); - } - - - /** - * Converts a database column name to a Java variable name (<em>first letter - * not capitalized</em>). - */ - public static String columnNameToVarName(String columnName) { - return dbNameToVarName(columnName); - } - /** - * Converts a database table name to a Java variable name (<em>first letter - * not capitalized</em>). - */ - public static String tableNameToVarName(String tableName) { - return dbNameToVarName(tableName); - } - /** - * Converts a database name (table or column) to a java name (<em>first letter - * not capitalized</em>). employee_name or employee-name -> employeeName - */ - private static String dbNameToVarName(String s) { - if ("".equals(s)) { - return s; - } - StringBuffer result = new StringBuffer(); - - boolean capitalize = true; - boolean lastCapital = false; - boolean lastDecapitalized = false; - String p = null; - for (int i = 0; i < s.length(); i++) { - String c = s.substring(i, i + 1); - if ("_".equals(c) || " ".equals(c)) { - capitalize = true; - continue; - } - - if (c.toUpperCase().equals(c)) { - if (lastDecapitalized && !lastCapital) { - capitalize = true; - } - lastCapital = true; - } else { - lastCapital = false; - } - - if (capitalize) { - if (p == null || !p.equals("_")) { - result.append(c.toUpperCase()); - capitalize = false; - p = c; - } else { - result.append(c.toLowerCase()); - capitalize = false; - p = c; - } - } else { - result.append(c.toLowerCase()); - lastDecapitalized = true; - p = c; - } - - } - /*this was using StringUtil.initLower. Changed to Introspector.decapitalize so that - * it returns the correct bean property name when called from columnNameToVarName. - * This is necessary because otherwise URL would be uRL which would cause - * an "The property uRL is undefined for the type xx" error because - * Introspector.getBeanInfo (used by JavaTypeIntrospector) returns - * the property name as URL.*/ - String resultStr = Introspector.decapitalize(result.toString()); - if (resultStr.equals("class")) { - // "class" is illegal becauseOf Object.getClass() clash - resultStr = "clazz"; - } - return resultStr; - } - - /** - * Compare two objects. If both String, ignore case - * @param o1 - * @param o2 - * @param ignoreCaseIfStr - * @return - */ - public static boolean equalObjects(Object o1, Object o2, boolean ignoreCaseIfStr) - { - if (o1 == o2) { - return true; - } - boolean result; - if (o1 == null || o2 == null) { - return false; //we already checked o1 == o2 above - } - if (ignoreCaseIfStr && o1 instanceof String && o2 instanceof String) - result = ((String)o1).equalsIgnoreCase((String)o2); - else - result = o1.equals(o2); - - return result; - } - - public static boolean equalObjects(Object o1, Object o2) - { - return equalObjects(o1, o2, false/*ignoreCaseIfStr*/); - } - -} - diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/UrlUtil.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/UrlUtil.java deleted file mode 100644 index e09759695a..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal2/util/UrlUtil.java +++ /dev/null @@ -1,125 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ - -package org.eclipse.jpt.gen.internal2.util; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - -import org.eclipse.core.runtime.FileLocator; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.osgi.framework.Bundle; - -/** - * Collections of utility methods handling URLs. - * - */ -public class UrlUtil -{ - /** - * The <code>file</code> string indicating a url file protocol. - */ - public static final String FILE_PROTOCOL = "file"; - /** - * The <code>file</code> string indicating a url http protocol. - */ - public static final String HTTP_PROTOCOL = "http"; - /** - * The <code>file</code> string indicating a url http protocol. - */ - public static final String HTTPS_PROTOCOL = "https"; - /** - * The <code>file</code> string indicating a url file protocol. - */ - public static final String JAR_PROTOCOL = "jar"; - - - /** - * Returns true if the specified url is to a file, i.e its protocol is <code>file</code>. - */ - public static boolean isFileUrl(URL url) { - return url != null && FILE_PROTOCOL.equals(url.getProtocol()); - } - /** - * Returns true if the specified url is to a jar, i.e its protocol is <code>jar</code>. - * For example <code>jar:file:/C:/testapps/example/WEB-INF/lib/struts.jar!/META-INF/tlds/struts-bean.tld</code>. - */ - public static boolean isJarUrl(URL url) { - return url != null && JAR_PROTOCOL.equals(url.getProtocol()); - } - /** - * Returns true if the specified url protocol is http. - */ - public static boolean isHttpUrl(URL url) { - String protocol = url.getProtocol(); - return url != null && (HTTP_PROTOCOL.equals(protocol) || HTTPS_PROTOCOL.equals(protocol)); - } - /** - * Returns the <code>File</code> corresponding to a url, or null if the url - * protocol is not file. - */ - public static java.io.File getUrlFile(URL url) { - if (isFileUrl(url) && !isJarUrl( url ) ){ - File ret = new java.io.File(url.getFile()); - return ret ; - } - return null; - } - - - /** - * Returns the url to a jar file given a url to a file inside - * the jar. - * For example if given - * <code>jar:file:/C:/testapps/example/WEB-INF/lib/struts.jar!/META-INF/tlds/struts-bean.tld</code> - * this method returns <code>file:/C:/testapps/example/WEB-INF/lib/struts.jar</code>. - * - * <p>Returns null if the given url is not recognized as a url to a file - * inside a jar. - */ - public static URL getJarFileUrl(URL url) { - if (!isJarUrl(url)) { - return null; - } - String file = url.getFile(); //file:/C:/testapps/example/WEB-INF/lib/struts.jar!/META-INF/tlds/struts-bean.tld - int index = file.indexOf('!'); - if (index < 0) { - return null; - } - String jarFileUrlStr = file.substring(0, index); - try { - return new URL(jarFileUrlStr); - } catch (MalformedURLException e) { - return null; - } - } - - public static boolean isRemote(String url){ - return url.startsWith("http:")||url.startsWith("https:")||url.startsWith("www."); - } - - public static File getTemplateFolder(String plugId , String strPath ){ - Bundle bundle = Platform.getBundle( plugId ); - Path path = new Path( strPath ); - URL url = FileLocator.find(bundle, path, null); - try { - URL templUrl; - templUrl = FileLocator.resolve(url); - File templDir = UrlUtil.getUrlFile(templUrl); - return templDir ; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } -} |