diff options
Diffstat (limited to 'jpa/plugins/org.eclipse.jpt.gen')
39 files changed, 0 insertions, 5806 deletions
diff --git a/jpa/plugins/org.eclipse.jpt.gen/.classpath b/jpa/plugins/org.eclipse.jpt.gen/.classpath deleted file mode 100644 index 8f257414e6..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/.classpath +++ /dev/null @@ -1,8 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="src" path="src"/> - <classpathentry kind="src" path="property_files"/> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="output" path="bin"/> -</classpath> diff --git a/jpa/plugins/org.eclipse.jpt.gen/.cvsignore b/jpa/plugins/org.eclipse.jpt.gen/.cvsignore deleted file mode 100644 index a196dd7686..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/.cvsignore +++ /dev/null @@ -1,6 +0,0 @@ -bin -@dot -temp.folder -build.xml -javaCompiler...args -javaCompiler...args.*
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/.project b/jpa/plugins/org.eclipse.jpt.gen/.project deleted file mode 100644 index ef2d5088ee..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/.project +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.jpt.gen</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.jdt.core.javabuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.ManifestBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.SchemaBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> diff --git a/jpa/plugins/org.eclipse.jpt.gen/.settings/org.eclipse.core.resources.prefs b/jpa/plugins/org.eclipse.jpt.gen/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 1f15ff2b4b..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,3 +0,0 @@ -#Tue Jan 15 11:12:07 EST 2008 -eclipse.preferences.version=1 -encoding/<project>=ISO-8859-1 diff --git a/jpa/plugins/org.eclipse.jpt.gen/.settings/org.eclipse.jdt.core.prefs b/jpa/plugins/org.eclipse.jpt.gen/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 3e1d50ad46..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,7 +0,0 @@ -#Sun May 27 14:28:54 EDT 2007 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/jpa/plugins/org.eclipse.jpt.gen/META-INF/MANIFEST.MF b/jpa/plugins/org.eclipse.jpt.gen/META-INF/MANIFEST.MF deleted file mode 100644 index 998af2bcd1..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/META-INF/MANIFEST.MF +++ /dev/null @@ -1,25 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: %pluginName -Bundle-Vendor: %providerName -Bundle-SymbolicName: org.eclipse.jpt.gen -Bundle-Version: 1.3.100.qualifier -Bundle-Localization: plugin -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.eclipse.jpt.gen.internal;x-friends:="org.eclipse.jpt.ui", - org.eclipse.jpt.gen.internal.util;x-friends:="org.eclipse.jpt.ui" -Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)", - org.eclipse.jdt.core;bundle-version="[3.4.0,4.0.0)", - org.eclipse.jpt.utility;bundle-version="[1.2.0,2.0.0)", - org.eclipse.jpt.db;bundle-version="[1.2.0,2.0.0)", - org.eclipse.jpt.core;bundle-version="[2.2.0,2.4.0)", - org.eclipse.core.resources;bundle-version="[3.4.0,4.0.0)", - org.eclipse.jface.text;bundle-version="[3.4.0,4.0.0)", - org.apache.commons.collections;bundle-version="3.2.0", - org.apache.commons.lang;bundle-version="2.1.0", - org.apache.oro;bundle-version="2.0.8", - org.apache.velocity;bundle-version="1.5.0", - org.jdom;bundle-version="1.0.0", - org.eclipse.wst.common.emf;bundle-version="[1.2.0,2.0.0)", - org.eclipse.emf.ecore.xmi;bundle-version="[2.5.0,3.0.0)" -Import-Package: com.ibm.icu.text;version="4.0.1" diff --git a/jpa/plugins/org.eclipse.jpt.gen/about.html b/jpa/plugins/org.eclipse.jpt.gen/about.html deleted file mode 100644 index be534ba44f..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/about.html +++ /dev/null @@ -1,34 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> -<HTML> - -<head> -<title>About</title> -<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1"> -</head> - -<BODY lang="EN-US"> - -<H3>About This Content</H3> - -<P>May 02, 2008</P> - -<H3>License</H3> - -<P>The Eclipse Foundation makes available all content in this plug-in -("Content"). Unless otherwise indicated below, the Content is provided to you -under the terms and conditions of the Eclipse Public License Version 1.0 -("EPL"). A copy of the EPL is available at -<A href="http://www.eclipse.org/org/documents/epl-v10.php">http://www.eclipse.org/org/documents/epl-v10.php</A>. -For purposes of the EPL, "Program" will mean the Content.</P> - -<P>If you did not receive this Content directly from the Eclipse Foundation, the -Content is being redistributed by another party ("Redistributor") and different -terms and conditions may apply to your use of any object code in the Content. -Check the Redistributor's license that was provided with the Content. If no such -license exists, contact the Redistributor. Unless otherwise indicated below, the -terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at -<A href="http://www.eclipse.org/">http://www.eclipse.org/</A>.</P> - -</BODY> -</HTML> diff --git a/jpa/plugins/org.eclipse.jpt.gen/build.properties b/jpa/plugins/org.eclipse.jpt.gen/build.properties deleted file mode 100644 index 4fe875d02e..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/build.properties +++ /dev/null @@ -1,18 +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 -################################################################################ -source.. = src/,\ - property_files/ -output.. = bin/ -bin.includes = .,\ - META-INF/,\ - about.html,\ - plugin.properties,\ - templates/ -jars.compile.order = . diff --git a/jpa/plugins/org.eclipse.jpt.gen/component.xml b/jpa/plugins/org.eclipse.jpt.gen/component.xml deleted file mode 100644 index 88034446f9..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/component.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Copyright (c) 2007, 2010 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 - --> - -<component xmlns="http://eclipse.org/wtp/releng/tools/component-model" name="org.eclipse.jpt.gen"><description url=""></description><component-depends unrestricted="true"></component-depends><plugin id="org.eclipse.jpt.gen" fragment="false"/></component>
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/plugin.properties b/jpa/plugins/org.eclipse.jpt.gen/plugin.properties deleted file mode 100644 index 9537a25a08..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/plugin.properties +++ /dev/null @@ -1,23 +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 -################################################################################ -# ==================================================================== -# To code developer: -# Do NOT change the properties between this line and the -# "%%% END OF TRANSLATED PROPERTIES %%%" line. -# Make a new property name, append to the end of the file and change -# the code to use the new property. -# ==================================================================== - -# ==================================================================== -# %%% END OF TRANSLATED PROPERTIES %%% -# ==================================================================== - -pluginName = Dali Java Persistence Tools - Entity Gen -providerName = Eclipse Web Tools Platform diff --git a/jpa/plugins/org.eclipse.jpt.gen/property_files/jpt_gen.properties b/jpa/plugins/org.eclipse.jpt.gen/property_files/jpt_gen.properties deleted file mode 100644 index db907a2472..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/property_files/jpt_gen.properties +++ /dev/null @@ -1,20 +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 -################################################################################ - -PackageGenerator_taskName=Generate Entities -GenScope_taskName=Build Database Model -EntityGenerator_taskName=Generate Entity: {0} -Error_Generating_Entities = Error Generating Entities - -Delete_Folder_Error = "The directory {0} could not be deleted." -Delete_File_Error = "The file {0} could not be deleted." -File_Read_Only_Error= "The file {0} could not be modified because write access is denied.\nPlease make sure that the file is not marked as readonly in the file system." - -Templates_notFound = Unable to find JPA entities generation templates in plugin
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/Association.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/Association.java deleted file mode 100644 index 535a5a6820..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/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.internal; - -import java.util.List; - -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.gen.internal.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/internal/AssociationRole.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/AssociationRole.java deleted file mode 100644 index f6654fb7a8..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/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.internal; - -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/internal/BaseEntityGenCustomizer.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/BaseEntityGenCustomizer.java deleted file mode 100644 index a1931ec99c..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/BaseEntityGenCustomizer.java +++ /dev/null @@ -1,230 +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.internal; - -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.internal.util.DTPUtil; -import org.eclipse.jpt.gen.internal.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(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(); - buffer.append( '{' ); - 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/internal/DatabaseAnnotationNameBuilder.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/DatabaseAnnotationNameBuilder.java deleted file mode 100644 index 2794256063..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/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.internal; - -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/internal/JptGenMessages.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/JptGenMessages.java deleted file mode 100644 index d505f8d6c1..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/JptGenMessages.java +++ /dev/null @@ -1,38 +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.internal; - -import org.eclipse.osgi.util.NLS; - -/** - * Localized messages used by Dali entity generation. - */ -public 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; - public static String Delete_Folder_Error; - public static String Delete_File_Error; - public static String File_Read_Only_Error; - - 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/JptGenPlugin.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/JptGenPlugin.java deleted file mode 100644 index 3540c2050d..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/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.internal; - -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/internal/ORMGenColumn.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ORMGenColumn.java deleted file mode 100644 index 336c9eb1b2..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ORMGenColumn.java +++ /dev/null @@ -1,415 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 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.Collections; -import java.util.Iterator; - -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.gen.internal.util.EntityGenTools; -import org.eclipse.jpt.gen.internal.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.<String>emptySet()); - } - 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; - } - - /** - * Return true if the values of name element in the @Column is default - * so we can skip generating the annotation - * - * @return true - */ - public boolean isDefaultJoinColumnName(String associationRolePropName){ - if( !this.mDbColumn.isPartOfForeignKey()){ - return false; - } - - Iterable<ForeignKey> it = mDbColumn.getTable().getForeignKeys(); - Iterator<ForeignKey> i = it.iterator(); - while( i.hasNext() ){ - ForeignKey fk = i.next(); - Column c = fk.getBaseColumns().iterator().next(); - if( c.equals( this.mDbColumn ) ){ - try{ - String annotationName = this.mCustomizer.getDatabaseAnnotationNameBuilder(). - buildJoinColumnAnnotationName(associationRolePropName, fk ); - return annotationName==null; - }catch(Exception e){ - //catch the case that referenced table has multiple primary key columns - return false; - } - } - } - return false; - } - - - /** - * 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() ); - } - if( type.equals("java.sql.Date")){ //$NON-NLS-1$ - type = "java.util.Date"; //$NON-NLS-1$ - } - - 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() - && this.mDbColumn.getTable().getPrimaryKeyColumnsSize() == 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() { - return this.mDbColumn.isPartOfPrimaryKey() && - this.mTable.getPrimaryKeyColumnsSize() > 1; - } - - 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/internal/ORMGenCustomizer.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ORMGenCustomizer.java deleted file mode 100644 index 907acb5b90..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ORMGenCustomizer.java +++ /dev/null @@ -1,820 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 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.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -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.Schema; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.gen.internal.util.DTPUtil; -import org.eclipse.jpt.gen.internal.util.FileUtil; -import org.eclipse.jpt.gen.internal.util.ForeignKeyInfo; -import org.eclipse.jpt.gen.internal.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; - - private boolean mUpdatePersistenceXml = true; - - //----------------------------------------- - //---- 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) { - JptGenPlugin.logException("***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; - mUpdatePersistenceXml = customizer.mUpdatePersistenceXml; - 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*/); - // sort on restore - sortAssociations( mAssociations ); - } - } - /** - * 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(); - break; - } - } - } - 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; - } - - private void sortAssociations( List< Association > list ) { - Collections.sort( list, new Comparator< Association >() { - public int compare( Association lhs, Association rhs ) { - // sort by referrer table name first... - int test = lhs.getReferrerTableName().compareTo( rhs.getReferrerTableName() ); - if( test != 0 ) - return test; - // then by referenced table name... - test = lhs.getReferencedTableName().compareTo( rhs.getReferencedTableName() ); - if( test != 0 ) - return test; - // if referrer and referenced tables are the same, they should - // appear next to each other - return 0; - } - } ); - } - public boolean shouldUpdatePersistenceXml() { - return mUpdatePersistenceXml; - } - public void setShouldUpdatePersistenceXml(boolean updatePersistenceXml) { - this.mUpdatePersistenceXml = updatePersistenceXml; - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ORMGenTable.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ORMGenTable.java deleted file mode 100644 index aebdda5e69..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/ORMGenTable.java +++ /dev/null @@ -1,1031 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 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.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.util.DTPUtil; -import org.eclipse.jpt.gen.internal.util.EntityGenTools; -import org.eclipse.jpt.gen.internal.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>(); - for (Column c : mDbTable.getColumns()) { - ORMGenColumn genColumn = getCustomizer().createGenColumn(c); - genColumn.setGenTable(this); - mColumns.add(genColumn); - } - } - return mColumns; - } - - public List<String> getColumnNames() { - List<String> ret = new ArrayList<String>(); - for (Column c : mDbTable.getColumns()) { - ret.add(c.getName()); - } - return ret; - } - - /** - * Returns the <code>ORMGenColumn</code> objects representing the table's - * primary key. - */ - public List<ORMGenColumn> getPrimaryKeyColumns() { - List<ORMGenColumn> ret = new ArrayList<ORMGenColumn>(); - for (Column column : mDbTable.getPrimaryKeyColumns()) { - ret.add(new ORMGenColumn(column, 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 mDbTable.getPrimaryKeyColumnsSize() > 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) + " "); //fix for bug 278626 - } - 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) { - Iterator<Column> pkCols = getDbTable().getPrimaryKeyColumns().iterator(); - String pkName = pkCols.hasNext() ? pkCols.next().getName() : null; - 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/internal/OverwriteConfirmer.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/OverwriteConfirmer.java deleted file mode 100644 index 86bf27d306..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/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.internal; - -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/internal/PackageGenerator.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/PackageGenerator.java deleted file mode 100644 index 90489abfa0..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/PackageGenerator.java +++ /dev/null @@ -1,335 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 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.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.core.JpaProject; -import org.eclipse.jpt.core.context.persistence.ClassRef; -import org.eclipse.jpt.core.context.persistence.Persistence; -import org.eclipse.jpt.core.context.persistence.PersistenceUnit; -import org.eclipse.jpt.core.resource.xml.JpaXmlResource; -import org.eclipse.jpt.gen.internal.util.CompilationUnitModifier; -import org.eclipse.jpt.gen.internal.util.FileUtil; -import org.eclipse.jpt.gen.internal.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 PackageGenerator { - - private static final String LOGGER_NAME = "org.eclipse.jpt.entities.gen.log"; //$NON-NLS-1$ - private JpaProject jpaProject; - 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(JpaProject jpaProject, ORMGenCustomizer customizer, IProgressMonitor monitor ) throws CoreException { - PackageGenerator generator = new PackageGenerator(); - 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(JpaProject proj ){ - this.jpaProject = 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 = this.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()); - } - } - - //update persistence.xml - if (this.customizer.shouldUpdatePersistenceXml()) { - updatePersistenceXml(genClasses); - } - progress.done(); - } - - private void updatePersistenceXml(final List<String> genClasses) { - JpaXmlResource resource = jpaProject.getPersistenceXmlResource(); - if (resource == null) { - //the resource would only be null if the persistence.xml file had an invalid content type, - //do not attempt to update - return; - } - - resource.modify(new Runnable() { - public void run() { - Persistence persistence = jpaProject.getRootContextNode().getPersistenceXml().getPersistence(); - if (persistence == null) { - // invalid content, do not attempt to update - return; - } - PersistenceUnit persistenceUnit; - // create a persistence unit if one doesn't already exist - if (persistence.persistenceUnitsSize() == 0) { - persistenceUnit = persistence.addPersistenceUnit(); - persistenceUnit.setName(jpaProject.getName()); - } else { - // we only support one persistence unit - take the first one - persistenceUnit = persistence.persistenceUnits().next(); - } - for (Iterator<String> stream = genClasses.iterator(); stream.hasNext();) { - String className = stream.next(); - if (!persistenceUnit.mappingFileRefsContaining(className).hasNext() && !persistenceUnit.specifiesPersistentType(className)) { - ClassRef classRef = persistenceUnit.addSpecifiedClassRef(); - classRef.setClassName(className); - } - } - } - }); - } - - 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 = jpaProject.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 = getDefaultJavaSourceLocation(getJavaProject(), 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 IJavaProject getJavaProject(){ - return this.jpaProject.getJavaProject(); - } - - private IPackageFragmentRoot getDefaultJavaSourceLocation(IJavaProject jproject, String sourceFolder){ - IPackageFragmentRoot defaultSrcPath = null; - if (jproject != null && jproject.exists()) { - try { - IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots(); - for (int i = 0; i < roots.length; i++) { - if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE ){ - if (defaultSrcPath == null) { - defaultSrcPath = roots[i]; - } - String path = roots[i].getPath().toString(); - if (path.equals('/' + sourceFolder)) { - return roots[i] ; - } - } - } - } catch (JavaModelException e) { - JptGenPlugin.logException(e); - } - } - return defaultSrcPath; - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/TagNames.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/TagNames.java deleted file mode 100644 index 2b6533a97e..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/TagNames.java +++ /dev/null @@ -1,46 +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.internal; - -/** - * 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/internal/util/CompilationUnitModifier.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/CompilationUnitModifier.java deleted file mode 100644 index 586f01b672..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/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.internal.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/internal/util/DTPUtil.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/DTPUtil.java deleted file mode 100644 index b4a71f982c..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/DTPUtil.java +++ /dev/null @@ -1,80 +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.internal.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; - -/** - * Collection of utility methods to access DTP and other jpt.db APIs - * - */ -public class DTPUtil { - - 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){ - for (ForeignKey fk : dbTable.getForeignKeys()) { - Iterator<ColumnPair> columnPaires = fk.getColumnPairs().iterator(); - 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(Column dbColumn) { - return dbColumn.isPartOfPrimaryKey() ? - dbColumn.getPrimaryKeyJavaTypeDeclaration() : - dbColumn.getJavaTypeDeclaration(); - } - - 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/internal/util/EntityGenTools.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/EntityGenTools.java deleted file mode 100644 index 81e2563e01..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/EntityGenTools.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2010 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.util; - -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) || StringTools.stringIsLowercase(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/util/FileUtil.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/FileUtil.java deleted file mode 100644 index 890b846166..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/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.internal.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.jpt.gen.internal.JptGenMessages; - -import org.eclipse.osgi.service.datalocation.Location; -import org.eclipse.osgi.util.NLS; -import org.osgi.framework.Bundle; - -/** - * Collections of utility methods handling files. - * - */ -public class FileUtil -{ - - 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() ? JptGenMessages.Delete_Folder_Error : JptGenMessages.Delete_File_Error; - throw new IOException( NLS.bind(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( NLS.bind(JptGenMessages.File_Read_Only_Error, dest.getPath())); //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/internal/util/ForeignKeyInfo.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/ForeignKeyInfo.java deleted file mode 100644 index 75e91e9de3..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/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.internal.util; - -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/internal/util/StringUtil.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/StringUtil.java deleted file mode 100644 index ee45e06fba..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/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.internal.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/internal/util/UrlUtil.java b/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/util/UrlUtil.java deleted file mode 100644 index c2ef8f87ce..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/src/org/eclipse/jpt/gen/internal/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.internal.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; - } -} diff --git a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/column.vm b/jpa/plugins/org.eclipse.jpt.gen/templates/entities/column.vm deleted file mode 100644 index 5d1f13c98d..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/column.vm +++ /dev/null @@ -1,54 +0,0 @@ -##included template. Generates the @Column annotation. -##Assumes that the context has a "column" and a "table" object -##generate annotation only the parameters for the column NOT default -##and the generateDLLAnnotation property is not set on the table -###------------------------------------------------ -#macro( append $members $parameters ) -#if( $members == "") -#set( $members = $parameters ) -#else -#set( $members = "$members, $parameters" ) -#end -#end -###------------------------------------------------ -#if ( $column.dataTypeLOB) - @Lob() -#end -#if ( $column.needMapTemporalType) - @Temporal( TemporalType.$column.temporalType) -#end -#set ($members = "") -#if ( !$column.default || $customizer.generateDDLAnnotations ) -#if ( !${column.defaultname} ) -#append($members "name=$customizer.quote($column.name)" ) -#end -#if (!$column.insertable) -#append(${members} "insertable=false") -#end -#if (!$column.updateable) -#append(${members} "updatable=false") -#end -#end -#if( $customizer.generateDDLAnnotations ) -#if ($column.unique) -#append($members "unique=true") -#end -#if (!$column.nullable) -#append($members "nullable=false") -#end -#if ($column.size > 0) -#if ($column.numeric) -#append($members "precision=$column.size") -#if ($column.decimalDigits != 0 && $column.decimalDigits != -1) -#append($members "scale=$column.decimalDigits") -#end -#else -#if ( !$column.dataTypeLOB) -#append($members "length=$column.size") -#end -#end -#end -#end -#if( $members !="" ) - @Column($members) -#end diff --git a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/join.vm b/jpa/plugins/org.eclipse.jpt.gen/templates/entities/join.vm deleted file mode 100644 index 531e4d91be..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/join.vm +++ /dev/null @@ -1,80 +0,0 @@ -##included template. Generates the @JoinTable, @JoinColumn or @JoinColumns annotation. -##Assumes that the context has a "role" object representing the generated AssociationRole -## -##macro joinColumn uses $column, $referencedColumn -#macro (joinColumn $column $referencedColumn) -#set ($members = "name=$customizer.quote($column.joinColumnName)") -#if( !$referencedColumn.primaryKey || $referencedColumn.partOfCompositePrimaryKey ) -#set ($members = "$members, referencedColumnName=$customizer.quote($referencedColumn.name)") -#end -#if( $customizer.generateDDLAnnotations ) -#if ($column.unique && !$column.primaryKey) -#set ($members = "$members, unique=true") -#end -#if (!$column.nullable) -#set ($members = "$members, nullable=false") -#end -#end -#if ($customizer.generateDDLAnnotations && !$role.association.joinTable && !$role.referrerTable.isColumnUpdateInsert($role, $column)) -#set ($members = "$members, insertable=false, updatable=false") -#end -@JoinColumn($members)#end -## -## -## -#if ($role.association.joinTable) -#set ($joinTable = $role.association.joinTable) - @JoinTable( - name="${joinTable.joinTableAnnotationName}" - , joinColumns={ -#foreach ($column in $role.referrerColumns) -#set ($referencedColumn = $role.getReferencedColumn(${column.name})) -##$referencedColumn is the column in the join table - #joinColumn($referencedColumn $column) -#if ($velocityCount < $role.referrerColumns.size() ) -, -#end -#end - - } - , inverseJoinColumns={ -#foreach ($column in $role.referencedColumns) -#set ($referencedColumn = $role.getReferrerColumn(${column.name})) -##$referencedColumn is the column in the join table - #joinColumn($referencedColumn $column) -#if ($velocityCount < $role.referencedColumns.size() ) -, -#end -#end - - } - ) -#else -#if ($role.referrerColumns.size() == 1) -#set ($column = $role.referrerColumns.get(0)) -#set ($referencedColumn = $role.getReferencedColumn(${column.name})) -#set ($referencedTableName = $role.getReferencedTable().getName() ) -#set( $referencedTablePkName = $role.getReferencedTable().getPrimaryKeyColumn().name ) -#set( $computedJoinColumnName = "${role.propertyName}_${referencedTablePkName}" ) -#set( $isDefaultJoinColumnName = $column.isDefaultJoinColumnName( ${role.propertyName}) ) -#if( ! $isDefaultJoinColumnName ) - #joinColumn($column $referencedColumn) - -#elseif( $customizer.generateDDLAnnotations ) - #joinColumn($column $referencedColumn) - -#end -#else - @JoinColumns({ -#foreach ($column in $role.referrerColumns) -#set ($referencedColumn = $role.getReferencedColumn(${column.name})) - #joinColumn($column $referencedColumn) -#if ($velocityCount < $role.referrerColumns.size() ) -, -#else - -#end -#end - }) -#end -#end
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/main.java.vm b/jpa/plugins/org.eclipse.jpt.gen/templates/entities/main.java.vm deleted file mode 100644 index 6f50a76f48..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/main.java.vm +++ /dev/null @@ -1,134 +0,0 @@ -#if ($table.package != "") -package ${table.package}; -#end - -import java.io.Serializable; -import javax.persistence.*; -${table.importStatements} - -/** - * The persistent class for the ${table.name} database table. - * - */ -@Entity -#if( !${table.defaultname} || $customizer.generateDDLAnnotations) -@Table(name="${table.name}") -#end -public class ${table.className} ${table.generateExtendsImplements()} { - private static final long serialVersionUID = 1L; -##### -##### fields -##### -#if ($table.compositeKey) -#if ($table.access == "field") - - @EmbeddedId -#end - private ${table.compositeKeyClassName} ${table.compositeKeyPropertyName}; -#end -#foreach ($column in $table.getSimpleColumns(true, true, false)) -#if ($table.access == "field") - -#parse("mappingKind.vm") -#parse("column.vm") -#end - ${column.fieldScope} ${column.simplePropertyType} ${column.propertyName}; -#end -#foreach ($role in $table.associationRoles) -##### -##### field annotations -##### -#if ($table.access == "field") - - //${role.description} -#if ($role.cardinality == "many-to-one") -#parse("manyToOne.vm") -#elseif ($role.cardinality == "many-to-many") -#parse("manyToMany.vm") -#elseif ($role.cardinality == "one-to-many") -#parse("oneToMany.vm") -#elseif ($role.cardinality == "one-to-one") -#parse("oneToOne.vm") -#end -#end -##### -##### field declaration -##### -#if ($role.cardinality == "many-to-one" || $role.cardinality == "one-to-one") -#set ($propertyType = ${role.referencedTable.className}) -#elseif ($role.cardinality == "many-to-many" || $role.cardinality == "one-to-many") -#set ($propertyType = "${role.referencedTable.simpleCollectionType}<${role.referencedTable.className}>") -#end - private $propertyType $role.propertyName; -#end - - public ${table.className}() { - } - -##### -##### simple properties getters and setters -##### -#if ($table.compositeKey) -#if ($table.access == "property") - - @EmbeddedId -#end - public $table.compositeKeyClassName $customizer.propertyGetter($table.compositeKeyPropertyName)() { - return this.${table.compositeKeyPropertyName}; - } - - public void $customizer.propertySetter($table.compositeKeyPropertyName)($table.compositeKeyClassName $table.compositeKeyPropertyName) { - this.${table.compositeKeyPropertyName} = ${table.compositeKeyPropertyName}; - } - -#end -#foreach ($column in $table.getSimpleColumns(true, true, false)) -#if ($table.access == "property") - -#parse("mappingKind.vm") -#parse("column.vm") -#end - $column.propertyGetScope $column.simplePropertyType $customizer.propertyGetter($column.propertyName)() { - return this.${column.propertyName}; - } - - $column.propertySetScope void $customizer.propertySetter($column.propertyName)($column.simplePropertyType $column.propertyName) { - this.${column.propertyName} = ${column.propertyName}; - } - -#end -##### -##### associations getters and setters -##### -#foreach ($role in $table.associationRoles) -#if ($table.access == "property") - - //${role.description} -#if ($role.cardinality == "many-to-one") -#parse("manyToOne.vm") -#elseif ($role.cardinality == "many-to-many") -#parse("manyToMany.vm") -#elseif ($role.cardinality == "one-to-many") -#parse("oneToMany.vm") -#elseif ($role.cardinality == "one-to-one") -#parse("oneToOne.vm") -#end -#end -## -#if ($role.cardinality == "many-to-one" || $role.cardinality == "one-to-one") -#set ($propertyType = $role.referencedTable.className) -#elseif ($role.cardinality == "many-to-many" || $role.cardinality == "one-to-many") -#set ($propertyType = "${role.referencedTable.simpleCollectionType}<${role.referencedTable.className}>") -#end - public $propertyType $customizer.propertyGetter($role.propertyName)() { - return this.${role.propertyName}; - } - - public void ${customizer.propertySetter($role.propertyName)}($propertyType $role.propertyName) { - this.${role.propertyName} = $role.propertyName; - } - -## -#end -## -}
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/manyToMany.vm b/jpa/plugins/org.eclipse.jpt.gen/templates/entities/manyToMany.vm deleted file mode 100644 index e482aa31c3..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/manyToMany.vm +++ /dev/null @@ -1,26 +0,0 @@ -##included template. Generates the @ManyToMany annotation. -##Assumes that the context has a "role" object representing the generated AssociationRole -## -#if ($role.association.bidirectional && !$role.isReferrerRole())##the owning side (either side for many-to-many) -#set ($members = $customizer.appendAnnotation("", "mappedBy", $role.oppositeRole.propertyName, true)) -#set ($members = $customizer.appendAnnotation($members, "cascade", $customizer.genCascades($role), false)) -#if($customizer.genFetch($role.referrerTable)!="" && $customizer.genFetch($role.referrerTable)!="FetchType.LAZY") -#set ($members = $customizer.appendAnnotation($members, "fetch", $customizer.genFetch($role.referrerTable), false)) -#end -#if($members!="") - @ManyToMany($members) -#else - @ManyToMany -#end -#else -#set ($members = $customizer.appendAnnotation("", "cascade", $customizer.genCascades($role), false)) -#if($customizer.genFetch($role.referrerTable)!="" && $customizer.genFetch($role.referrerTable)!="FetchType.LAZY") -#set ($members = $customizer.appendAnnotation($members, "fetch", $customizer.genFetch($role.referrerTable), false)) -#end -#if($members!="") - @ManyToMany($members) -#else - @ManyToMany -#end -#parse("join.vm") -#end
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/manyToOne.vm b/jpa/plugins/org.eclipse.jpt.gen/templates/entities/manyToOne.vm deleted file mode 100644 index 7d279bbd6b..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/manyToOne.vm +++ /dev/null @@ -1,13 +0,0 @@ -##included template. Generates the @ManyToOne annotation. -##Assumes that the context has a "role" object representing the generated AssociationRole -## -#set ($members = $customizer.appendAnnotation("", "cascade", $customizer.genCascades($role), false)) -#if( $customizer.genFetch($role.referrerTable)!= "" && $customizer.genFetch($role.referrerTable)!= "FetchType.EAGER") -#set ($members = $customizer.appendAnnotation($members, "fetch", $customizer.genFetch($role.referrerTable), false)) -#end -#if($members!="") - @ManyToOne($members) -#else - @ManyToOne -#end -#parse("join.vm")
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/mappingKind.vm b/jpa/plugins/org.eclipse.jpt.gen/templates/entities/mappingKind.vm deleted file mode 100644 index 80ad057233..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/mappingKind.vm +++ /dev/null @@ -1,34 +0,0 @@ -##included template. Generates the @Basic, @Id, @Version annotations. -##Assumes that the context has a "column" object -## -#set ($mappingKind = $column.mappingKind) -#if ($mappingKind == "id") - @Id -#set ($idGenerator = $table.idGenerator) -#if ($idGenerator == "auto") -#set ($generationType = "GenerationType.AUTO") -#elseif ($idGenerator == "identity") -#set ($generationType = "GenerationType.IDENTITY") -#elseif ($idGenerator == "sequence") -#set ($generationType = "GenerationType.SEQUENCE") -#elseif ($idGenerator == "table") -#set ($generationType = "GenerationType.TABLE") -#else -#set ($generationType = "") -#end -#if ($idGenerator == "sequence" ) -#set ($generatorName = "${table.name.toUpperCase()}_${column.propertyName.toUpperCase()}_GENERATOR") -#if( $table.formattedSequence != "" ) - @SequenceGenerator(name="$generatorName", sequenceName="$table.formattedSequence") -#else - @SequenceGenerator(name="$generatorName" ) -#end - @GeneratedValue(strategy=$generationType, generator="$generatorName") -#elseif ($generationType != "") - @GeneratedValue(strategy=$generationType) -#end -#elseif ($mappingKind == "version") - @Version -#else -##DEFAULT is @Basic, no need to generate -#end
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/oneToMany.vm b/jpa/plugins/org.eclipse.jpt.gen/templates/entities/oneToMany.vm deleted file mode 100644 index 46f15cbec9..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/oneToMany.vm +++ /dev/null @@ -1,18 +0,0 @@ -##included template. Generates the @OneToMany annotation. -##Assumes that the context has a "role" object representing the generated AssociationRole -## -#if ($role.association.bidirectional) -#set ($members = $customizer.appendAnnotation("", "mappedBy", $role.oppositeRole.propertyName, true)) -#set ($members = $customizer.appendAnnotation($members, "cascade", $customizer.genCascades($role), false)) -#if($customizer.genFetch($role.referrerTable)!="" && $customizer.genFetch($role.referrerTable) !="FetchType.LAZY") -#set ($members = $customizer.appendAnnotation($members, "fetch", $customizer.genFetch($role.referrerTable), false)) -#end - @OneToMany($members) -#else -#set ($members = $customizer.appendAnnotation("", "cascade", $customizer.genCascades($role), false)) -#if($customizer.genFetch($role.referrerTable)!="" && $customizer.genFetch($role.referrerTable) !="FetchType.LAZY") -#set ($members = $customizer.appendAnnotation($members, "fetch", $customizer.genFetch($role.referrerTable), false)) -#end - @OneToMany($members) -#parse("join.vm") -#end
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/oneToOne.vm b/jpa/plugins/org.eclipse.jpt.gen/templates/entities/oneToOne.vm deleted file mode 100644 index 7bd7519a96..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/oneToOne.vm +++ /dev/null @@ -1,22 +0,0 @@ -##included template. Generates the @OneToOne annotation. -##Assumes that the context has a "role" object representing the generated AssociationRole -## -#if ($role.association.bidirectional && !$role.isReferrerRole())##the owning side (either side for one-to-one) -#set ($members = $customizer.appendAnnotation("", "mappedBy", $role.oppositeRole.propertyName, true)) -#set ($members = $customizer.appendAnnotation($members, "cascade", $customizer.genCascades($role), false)) -#if( $customizer.genFetch($role.referrerTable)!="" && $customizer.genFetch($role.referrerTable)!="FetchType.EAGER" ) -#set ($members = $customizer.appendAnnotation($members, "fetch", $customizer.genFetch($role.referrerTable), false)) -#end - @OneToOne($members) -#else -#set ($members = $customizer.appendAnnotation("", "cascade", $customizer.genCascades($role), false)) -#if( $customizer.genFetch($role.referrerTable)!="" && $customizer.genFetch($role.referrerTable)!="FetchType.EAGER" ) -#set ($members = $customizer.appendAnnotation($members, "fetch", $customizer.genFetch($role.referrerTable), false)) -#end -#if($members!="") - @OneToOne($members) -#else - @OneToOne -#end -#parse("join.vm") -#end
\ No newline at end of file diff --git a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/pk.java.vm b/jpa/plugins/org.eclipse.jpt.gen/templates/entities/pk.java.vm deleted file mode 100644 index 1831098585..0000000000 --- a/jpa/plugins/org.eclipse.jpt.gen/templates/entities/pk.java.vm +++ /dev/null @@ -1,66 +0,0 @@ -#if ($table.package != "") -package ${table.package}; -#end - -import java.io.Serializable; -import javax.persistence.*; - -/** - * The primary key class for the ${table.name} database table. - * - */ -@Embeddable -public class ${table.compositeKeyClassName} implements Serializable { - //default serial version id, required for serializable classes. - private static final long serialVersionUID = 1L; -##### -##### fields -##### -#foreach ($column in $table.primaryKeyColumns) -#if ($table.access == "field") - -#parse("column.vm") -#end - ${column.fieldScope} ${column.propertyType} ${column.propertyName}; -#end - - public ${table.compositeKeyClassName}() { - } -##### -##### simple properties getters and setters -##### -#foreach ($column in $table.primaryKeyColumns) -#if ($table.access == "property") - -#parse("column.vm") -#end - $column.propertyGetScope $column.propertyType $customizer.propertyGetter($column.propertyName)() { - return this.${column.propertyName}; - } - $column.propertySetScope void $customizer.propertySetter($column.propertyName)($column.propertyType $column.propertyName) { - this.${column.propertyName} = ${column.propertyName}; - } -#end -## -## equals/hashCode - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof ${table.compositeKeyClassName})) { - return false; - } - ${table.compositeKeyClassName} castOther = (${table.compositeKeyClassName})other; - return - ${table.primaryKeyEqualsClause} - - } - - public int hashCode() { - final int prime = 31; - int hash = 17; - ${table.primaryKeyHashCodeClause} - return hash; - } -}
\ No newline at end of file |