http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/itests/cayenne-tools-itest/src/test/java/org/apache/cayenne/tools/CayenneGeneratorIntegrationTest.java ---------------------------------------------------------------------- diff --git a/itests/cayenne-tools-itest/src/test/java/org/apache/cayenne/tools/CayenneGeneratorIntegrationTest.java b/itests/cayenne-tools-itest/src/test/java/org/apache/cayenne/tools/CayenneGeneratorIntegrationTest.java index c58d3d0..dfb9d8f 100644 --- a/itests/cayenne-tools-itest/src/test/java/org/apache/cayenne/tools/CayenneGeneratorIntegrationTest.java +++ b/itests/cayenne-tools-itest/src/test/java/org/apache/cayenne/tools/CayenneGeneratorIntegrationTest.java @@ -147,16 +147,11 @@ public class CayenneGeneratorIntegrationTest { } private void assertContents(File f, String className, String packageName, String extendsName) throws Exception { - - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f))); - - try { + + try(BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f)))) { assertPackage(in, packageName); assertClass(in, className, extendsName); - } finally { - in.close(); - } - + } } private void assertPackage(BufferedReader in, String packageName) throws Exception {
http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/action/ImportDataMapAction.java ---------------------------------------------------------------------- diff --git a/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/action/ImportDataMapAction.java b/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/action/ImportDataMapAction.java index 4b5e2fe..4466ce4 100644 --- a/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/action/ImportDataMapAction.java +++ b/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/action/ImportDataMapAction.java @@ -22,7 +22,6 @@ package org.apache.cayenne.modeler.action; import java.awt.Frame; import java.awt.event.ActionEvent; import java.io.File; -import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -44,105 +43,90 @@ import org.apache.commons.logging.LogFactory; import org.xml.sax.InputSource; /** - * Modeler action that imports a DataMap into a project from an arbitrary location. + * Modeler action that imports a DataMap into a project from an arbitrary + * location. * * @since 1.1 */ public class ImportDataMapAction extends CayenneAction { - private static Log logObj = LogFactory.getLog(ImportDataMapAction.class); - - public static String getActionName() { - return "Import DataMap"; - } - - public ImportDataMapAction(Application application) { - super(getActionName(), application); - } - - public void performAction(ActionEvent e) { - importDataMap(); - } - - protected void importDataMap() { - File dataMapFile = selectDataMap(Application.getFrame()); - if (dataMapFile == null) { - return; - } - - DataMap newMap; - - try { - - URL url = dataMapFile.toURI().toURL(); - - InputStream in = url.openStream(); - - try { - InputSource inSrc = new InputSource(in); - inSrc.setSystemId(dataMapFile.getAbsolutePath()); - newMap = new MapLoader().loadDataMap(inSrc); - } - finally { - try { - in.close(); - } - catch (IOException ioex) { - } - } - - DataChannelDescriptor domain = (DataChannelDescriptor) getProjectController() - .getProject() - .getRootNode(); - - if (newMap.getName() != null) { - newMap.setName(DefaultUniqueNameGenerator.generate(NameCheckers.dataMap, domain, newMap.getName())); - } - else { - newMap.setName(DefaultUniqueNameGenerator.generate(NameCheckers.dataMap, domain)); - } - - Resource baseResource = domain.getConfigurationSource(); - - if (baseResource != null) { - Resource dataMapResource = baseResource.getRelativeResource(newMap.getName()); - newMap.setConfigurationSource(dataMapResource); - } - - getProjectController().addDataMap(this, newMap); - } - catch (Exception ex) { - logObj.info("Error importing DataMap.", ex); - JOptionPane.showMessageDialog( - Application.getFrame(), - "Error reading DataMap: " + ex.getMessage(), - "Can't Open DataMap", - JOptionPane.OK_OPTION); - } - } - - protected File selectDataMap(Frame f) { - - // find start directory in preferences - FSPath lastDir = getApplication().getFrameController().getLastDirectory(); - - // configure dialog - JFileChooser chooser = new JFileChooser(); - chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - lastDir.updateChooser(chooser); - - chooser.addChoosableFileFilter(FileFilters.getDataMapFilter()); - - int status = chooser.showDialog(f, "Select DataMap"); - if (status == JFileChooser.APPROVE_OPTION) { - File file = chooser.getSelectedFile(); - - // save to preferences... - lastDir.updateFromChooser(chooser); - - return file; - } - - return null; - } + private static Log logObj = LogFactory.getLog(ImportDataMapAction.class); + + public static String getActionName() { + return "Import DataMap"; + } + + public ImportDataMapAction(Application application) { + super(getActionName(), application); + } + + public void performAction(ActionEvent e) { + importDataMap(); + } + + protected void importDataMap() { + File dataMapFile = selectDataMap(Application.getFrame()); + if (dataMapFile == null) { + return; + } + + DataMap newMap; + + try { + + URL url = dataMapFile.toURI().toURL(); + + try (InputStream in = url.openStream();) { + InputSource inSrc = new InputSource(in); + inSrc.setSystemId(dataMapFile.getAbsolutePath()); + newMap = new MapLoader().loadDataMap(inSrc); + } + + DataChannelDescriptor domain = (DataChannelDescriptor) getProjectController().getProject().getRootNode(); + + if (newMap.getName() != null) { + newMap.setName(DefaultUniqueNameGenerator.generate(NameCheckers.dataMap, domain, newMap.getName())); + } else { + newMap.setName(DefaultUniqueNameGenerator.generate(NameCheckers.dataMap, domain)); + } + + Resource baseResource = domain.getConfigurationSource(); + + if (baseResource != null) { + Resource dataMapResource = baseResource.getRelativeResource(newMap.getName()); + newMap.setConfigurationSource(dataMapResource); + } + + getProjectController().addDataMap(this, newMap); + } catch (Exception ex) { + logObj.info("Error importing DataMap.", ex); + JOptionPane.showMessageDialog(Application.getFrame(), "Error reading DataMap: " + ex.getMessage(), + "Can't Open DataMap", JOptionPane.OK_OPTION); + } + } + + protected File selectDataMap(Frame f) { + + // find start directory in preferences + FSPath lastDir = getApplication().getFrameController().getLastDirectory(); + + // configure dialog + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + lastDir.updateChooser(chooser); + + chooser.addChoosableFileFilter(FileFilters.getDataMapFilter()); + + int status = chooser.showDialog(f, "Select DataMap"); + if (status == JFileChooser.APPROVE_OPTION) { + File file = chooser.getSelectedFile(); + + // save to preferences... + lastDir.updateFromChooser(chooser); + + return file; + } + + return null; + } } http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/db/DataSourceWizard.java ---------------------------------------------------------------------- diff --git a/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/db/DataSourceWizard.java b/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/db/DataSourceWizard.java index f5060cb..3ca4a9f 100644 --- a/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/db/DataSourceWizard.java +++ b/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/db/DataSourceWizard.java @@ -37,201 +37,188 @@ import org.apache.cayenne.swing.BindingBuilder; import org.apache.cayenne.swing.ObjectBinding; /** - * A subclass of ConnectionWizard that tests configured DataSource, but does not keep an - * open connection. + * A subclass of ConnectionWizard that tests configured DataSource, but does not + * keep an open connection. * */ public class DataSourceWizard extends CayenneController { - protected DataSourceWizardView view; - - protected DBConnectionInfo altDataSource; - protected String altDataSourceKey; - protected ObjectBinding dataSourceBinding; - protected Map dataSources; - - protected String dataSourceKey; - - // this object is a clone of an object selected from the dropdown, as we need to allow - // local temporary modifications - protected DBConnectionInfo connectionInfo; - - protected boolean canceled; - - public DataSourceWizard(CayenneController parent, String title, - String altDataSourceKey, DBConnectionInfo altDataSource) { - super(parent); - - this.view = createView(); - this.view.setTitle(title); - this.altDataSource = altDataSource; - this.altDataSourceKey = altDataSourceKey; - this.connectionInfo = new DBConnectionInfo(); - - initBindings(); - } - - /** - * Creates swing dialog for this wizard - */ - protected DataSourceWizardView createView() { - return new DataSourceWizardView(this); - } - - protected void initBindings() { - BindingBuilder builder = new BindingBuilder( - getApplication().getBindingFactory(), - this); - - dataSourceBinding = builder.bindToComboSelection( - view.getDataSources(), - "dataSourceKey"); - - builder.bindToAction(view.getCancelButton(), "cancelAction()"); - builder.bindToAction(view.getOkButton(), "okAction()"); - builder.bindToAction(view.getConfigButton(), "dataSourceConfigAction()"); - } - - public String getDataSourceKey() { - return dataSourceKey; - } - - public void setDataSourceKey(String dataSourceKey) { - this.dataSourceKey = dataSourceKey; - - // update a clone object that will be used to obtain connection... - DBConnectionInfo currentInfo = (DBConnectionInfo) dataSources.get(dataSourceKey); - if (currentInfo != null) { - currentInfo.copyTo(connectionInfo); - } - else { - connectionInfo = new DBConnectionInfo(); - } - - view.getConnectionInfo().setConnectionInfo(connectionInfo); - } - - /** - * Main action method that pops up a dialog asking for user selection. Returns true if - * the selection was confirmed, false - if canceled. - */ - public boolean startupAction() { - this.canceled = true; - - refreshDataSources(); - - view.pack(); - view.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); - view.setModal(true); - makeCloseableOnEscape(); - centerView(); - view.setVisible(true); - - return !canceled; - } - - public DBConnectionInfo getConnectionInfo() { - return connectionInfo; - } - - /** - * Tests that the entered information is valid and can be used to open a conneciton. - * Does not store the open connection. - */ - public void okAction() { - DBConnectionInfo info = getConnectionInfo(); - ClassLoadingService classLoader = getApplication().getClassLoadingService(); - - // try making an adapter... - try { - info.makeAdapter(classLoader); - } - catch (Throwable th) { - reportError("DbAdapter Error", th); - return; - } - - // doing connection testing... - // attempt opening the connection, and close it right away - try { - Connection connection = info.makeDataSource(classLoader).getConnection(); - try { - connection.close(); - } - catch (SQLException ex) { - // ignore close error - } - } - catch (Throwable th) { - reportError("Connection Error", th); - return; - } - - // set success flag, and unblock the caller... - canceled = false; - view.dispose(); - } - - public void cancelAction() { - canceled = true; - view.dispose(); - } - - /** - * Opens preferences panel to allow configuration of DataSource presets. - */ - public void dataSourceConfigAction() { - PreferenceDialog prefs = new PreferenceDialog(this); - prefs.showDataSourceEditorAction(dataSourceKey); - refreshDataSources(); - } - - public Component getView() { - return view; - } - - protected void refreshDataSources() { - this.dataSources = getApplication() - .getCayenneProjectPreferences() - .getDetailObject(DBConnectionInfo.class) - .getChildrenPreferences(); - - // 1.2 migration fix - update data source adapter names - Iterator it = dataSources.values().iterator(); - - final String _12package = "org.objectstyle.cayenne."; - while (it.hasNext()) { - DBConnectionInfo info = (DBConnectionInfo) it.next(); - if (info.getDbAdapter() != null && info.getDbAdapter().startsWith(_12package)) { - info.setDbAdapter("org.apache.cayenne." - + info.getDbAdapter().substring(_12package.length())); - - // info.getObjectContext().commitChanges(); - } - } - - if (altDataSourceKey != null - && !dataSources.containsKey(altDataSourceKey) - && altDataSource != null) { - dataSources.put(altDataSourceKey, altDataSource); - } - - Object[] keys = dataSources.keySet().toArray(); - Arrays.sort(keys); - view.getDataSources().setModel(new DefaultComboBoxModel(keys)); - - if (getDataSourceKey() == null) { - String key = null; - - if (altDataSourceKey != null) { - key = altDataSourceKey; - } - else if (keys.length > 0) { - key = keys[0].toString(); - } - - setDataSourceKey(key); - dataSourceBinding.updateView(); - } - } + protected DataSourceWizardView view; + + protected DBConnectionInfo altDataSource; + protected String altDataSourceKey; + protected ObjectBinding dataSourceBinding; + protected Map dataSources; + + protected String dataSourceKey; + + // this object is a clone of an object selected from the dropdown, as we + // need to allow + // local temporary modifications + protected DBConnectionInfo connectionInfo; + + protected boolean canceled; + + public DataSourceWizard(CayenneController parent, String title, String altDataSourceKey, + DBConnectionInfo altDataSource) { + super(parent); + + this.view = createView(); + this.view.setTitle(title); + this.altDataSource = altDataSource; + this.altDataSourceKey = altDataSourceKey; + this.connectionInfo = new DBConnectionInfo(); + + initBindings(); + } + + /** + * Creates swing dialog for this wizard + */ + protected DataSourceWizardView createView() { + return new DataSourceWizardView(this); + } + + protected void initBindings() { + BindingBuilder builder = new BindingBuilder(getApplication().getBindingFactory(), this); + + dataSourceBinding = builder.bindToComboSelection(view.getDataSources(), "dataSourceKey"); + + builder.bindToAction(view.getCancelButton(), "cancelAction()"); + builder.bindToAction(view.getOkButton(), "okAction()"); + builder.bindToAction(view.getConfigButton(), "dataSourceConfigAction()"); + } + + public String getDataSourceKey() { + return dataSourceKey; + } + + public void setDataSourceKey(String dataSourceKey) { + this.dataSourceKey = dataSourceKey; + + // update a clone object that will be used to obtain connection... + DBConnectionInfo currentInfo = (DBConnectionInfo) dataSources.get(dataSourceKey); + if (currentInfo != null) { + currentInfo.copyTo(connectionInfo); + } else { + connectionInfo = new DBConnectionInfo(); + } + + view.getConnectionInfo().setConnectionInfo(connectionInfo); + } + + /** + * Main action method that pops up a dialog asking for user selection. + * Returns true if the selection was confirmed, false - if canceled. + */ + public boolean startupAction() { + this.canceled = true; + + refreshDataSources(); + + view.pack(); + view.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + view.setModal(true); + makeCloseableOnEscape(); + centerView(); + view.setVisible(true); + + return !canceled; + } + + public DBConnectionInfo getConnectionInfo() { + return connectionInfo; + } + + /** + * Tests that the entered information is valid and can be used to open a + * conneciton. Does not store the open connection. + */ + public void okAction() { + DBConnectionInfo info = getConnectionInfo(); + ClassLoadingService classLoader = getApplication().getClassLoadingService(); + + // try making an adapter... + try { + info.makeAdapter(classLoader); + } catch (Throwable th) { + reportError("DbAdapter Error", th); + return; + } + + // doing connection testing... + // attempt opening the connection, and close it right away + try { + + try (Connection connection = info.makeDataSource(classLoader).getConnection();) { + // + } catch (SQLException ex) { + // ignore close error + } + } catch (Throwable th) { + reportError("Connection Error", th); + return; + } + + // set success flag, and unblock the caller... + canceled = false; + view.dispose(); + } + + public void cancelAction() { + canceled = true; + view.dispose(); + } + + /** + * Opens preferences panel to allow configuration of DataSource presets. + */ + public void dataSourceConfigAction() { + PreferenceDialog prefs = new PreferenceDialog(this); + prefs.showDataSourceEditorAction(dataSourceKey); + refreshDataSources(); + } + + public Component getView() { + return view; + } + + protected void refreshDataSources() { + this.dataSources = getApplication().getCayenneProjectPreferences().getDetailObject(DBConnectionInfo.class) + .getChildrenPreferences(); + + // 1.2 migration fix - update data source adapter names + Iterator it = dataSources.values().iterator(); + + final String _12package = "org.objectstyle.cayenne."; + while (it.hasNext()) { + DBConnectionInfo info = (DBConnectionInfo) it.next(); + if (info.getDbAdapter() != null && info.getDbAdapter().startsWith(_12package)) { + info.setDbAdapter("org.apache.cayenne." + info.getDbAdapter().substring(_12package.length())); + + // info.getObjectContext().commitChanges(); + } + } + + if (altDataSourceKey != null && !dataSources.containsKey(altDataSourceKey) && altDataSource != null) { + dataSources.put(altDataSourceKey, altDataSource); + } + + Object[] keys = dataSources.keySet().toArray(); + Arrays.sort(keys); + view.getDataSources().setModel(new DefaultComboBoxModel(keys)); + + if (getDataSourceKey() == null) { + String key = null; + + if (altDataSourceKey != null) { + key = altDataSourceKey; + } else if (keys.length > 0) { + key = keys[0].toString(); + } + + setDataSourceKey(key); + dataSourceBinding.updateView(); + } + } } http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/pref/DataSourcePreferences.java ---------------------------------------------------------------------- diff --git a/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/pref/DataSourcePreferences.java b/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/pref/DataSourcePreferences.java index e10d373..19c031c 100644 --- a/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/pref/DataSourcePreferences.java +++ b/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/dialog/pref/DataSourcePreferences.java @@ -271,10 +271,10 @@ public class DataSourcePreferences extends CayenneController { // connect via Cayenne DriverDataSource - it addresses some driver // issues... - Connection c = new DriverDataSource(driver, currentDataSource.getUrl(), currentDataSource.getUserName(), - currentDataSource.getPassword()).getConnection(); - try { - c.close(); + + try (Connection c = new DriverDataSource(driver, currentDataSource.getUrl(), + currentDataSource.getUserName(), currentDataSource.getPassword()).getConnection();) { + // do nothing... } catch (SQLException e) { // i guess we can ignore this... } http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/graph/action/SaveAsImageAction.java ---------------------------------------------------------------------- diff --git a/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/graph/action/SaveAsImageAction.java b/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/graph/action/SaveAsImageAction.java index 5815e6d..18d285a 100644 --- a/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/graph/action/SaveAsImageAction.java +++ b/modeler/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/graph/action/SaveAsImageAction.java @@ -41,68 +41,60 @@ import org.jgraph.JGraph; * Action for saving graph as image */ public class SaveAsImageAction extends CayenneAction { - private static final Log logObj = LogFactory.getLog(SaveAsImageAction.class); - - private final DataDomainGraphTab dataDomainGraphTab; - - public SaveAsImageAction(DataDomainGraphTab dataDomainGraphTab, Application application) { - super("Save As Image", application); - this.dataDomainGraphTab = dataDomainGraphTab; - setEnabled(true); - } - - @Override - public String getIconName() { - return "icon-save-as-image.png"; - } - - @Override - public void performAction(ActionEvent e) { - // find start directory in preferences - FSPath lastDir = getApplication().getFrameController().getLastDirectory(); - - // configure dialog - JFileChooser chooser = new JFileChooser(); - chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - lastDir.updateChooser(chooser); - - chooser.setAcceptAllFileFilterUsed(false); - - String ext = "png"; - chooser.addChoosableFileFilter(FileFilters.getExtensionFileFilter(ext, "PNG Images")); - - int status = chooser.showSaveDialog(Application.getFrame()); - if (status == JFileChooser.APPROVE_OPTION) { - lastDir.updateFromChooser(chooser); - - String path = chooser.getSelectedFile().getPath(); - if (!path.endsWith("." + ext)) { - path += "." + ext; - } - - try { - OutputStream out = new FileOutputStream(path); - - JGraph graph = dataDomainGraphTab.getGraph(); - BufferedImage img = graph.getImage(null, 0); - - try { - ImageIO.write(img, ext, out); - out.flush(); - } - finally { - out.close(); - } - } - catch (IOException ex) { - logObj.error("Could not save image", ex); - JOptionPane.showMessageDialog( - Application.getFrame(), - "Could not save image.", - "Error saving image", - JOptionPane.ERROR_MESSAGE - ); - } - } - } + private static final Log logObj = LogFactory.getLog(SaveAsImageAction.class); + + private final DataDomainGraphTab dataDomainGraphTab; + + public SaveAsImageAction(DataDomainGraphTab dataDomainGraphTab, Application application) { + super("Save As Image", application); + this.dataDomainGraphTab = dataDomainGraphTab; + setEnabled(true); + } + + @Override + public String getIconName() { + return "icon-save-as-image.png"; + } + + @Override + public void performAction(ActionEvent e) { + // find start directory in preferences + FSPath lastDir = getApplication().getFrameController().getLastDirectory(); + + // configure dialog + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + lastDir.updateChooser(chooser); + + chooser.setAcceptAllFileFilterUsed(false); + + String ext = "png"; + chooser.addChoosableFileFilter(FileFilters.getExtensionFileFilter(ext, "PNG Images")); + + int status = chooser.showSaveDialog(Application.getFrame()); + if (status == JFileChooser.APPROVE_OPTION) { + lastDir.updateFromChooser(chooser); + + String path = chooser.getSelectedFile().getPath(); + if (!path.endsWith("." + ext)) { + path += "." + ext; + } + + try { + + JGraph graph = dataDomainGraphTab.getGraph(); + BufferedImage img = graph.getImage(null, 0); + + try (OutputStream out = new FileOutputStream(path);) { + ImageIO.write(img, ext, out); + out.flush(); + } + + } catch (IOException ex) { + logObj.error("Could not save image", ex); + JOptionPane.showMessageDialog(Application.getFrame(), "Could not save image.", "Error saving image", + JOptionPane.ERROR_MESSAGE); + } + } + } } \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/modeler/cayenne-wocompat/src/main/java/org/apache/cayenne/wocompat/EOModelHelper.java ---------------------------------------------------------------------- diff --git a/modeler/cayenne-wocompat/src/main/java/org/apache/cayenne/wocompat/EOModelHelper.java b/modeler/cayenne-wocompat/src/main/java/org/apache/cayenne/wocompat/EOModelHelper.java index 1925eaf..b78b068 100644 --- a/modeler/cayenne-wocompat/src/main/java/org/apache/cayenne/wocompat/EOModelHelper.java +++ b/modeler/cayenne-wocompat/src/main/java/org/apache/cayenne/wocompat/EOModelHelper.java @@ -36,428 +36,403 @@ import org.apache.cayenne.wocompat.parser.Parser; import org.apache.commons.collections.IteratorUtils; /** - * Helper class used by EOModelProcessor. EOModelHelper loads an EOModel from the - * specified location and gives its users access to the untyped EOModel information. + * Helper class used by EOModelProcessor. EOModelHelper loads an EOModel from + * the specified location and gives its users access to the untyped EOModel + * information. */ public class EOModelHelper { - private Parser plistParser = new Parser(); - protected URL modelUrl; - protected Map entityIndex; - protected Map entityClassIndex; - protected Map entityQueryIndex; - protected Map entityClientClassIndex; - protected DataMap dataMap; - private Map prototypeValues; - - /** - * Creates helper instance and tries to locate EOModel and load index file. - * - * @deprecated since 4.0, use {@link #EOModelHelper(URL)}. - */ - @Deprecated - public EOModelHelper(String path) throws Exception { - this(new File(path).toURI().toURL()); - } - - public EOModelHelper(URL modelUrl) throws Exception { - - this.modelUrl = modelUrl; - this.dataMap = new DataMap(findModelName(modelUrl.toExternalForm())); - - // load index file - List modelIndex = (List) loadModelIndex().get("entities"); - - // load entity indices - entityIndex = new HashMap(); - entityClassIndex = new HashMap(); - entityClientClassIndex = new HashMap(); - entityQueryIndex = new HashMap(); - - Iterator it = modelIndex.iterator(); - while (it.hasNext()) { - Map info = (Map) it.next(); - String name = (String) info.get("name"); - - entityIndex.put(name, loadEntityIndex(name)); - entityQueryIndex.put(name, loadQueryIndex(name)); - entityClassIndex.put(name, info.get("className")); - Map entityPlistMap = entityPListMap(name); - - // get client class information - Map internalInfo = (Map) entityPlistMap.get("internalInfo"); - - if (internalInfo != null) { - String clientClassName = (String) internalInfo - .get("_javaClientClassName"); - entityClientClassIndex.put(name, clientClassName); - } - } - - it = modelIndex.iterator(); - while (it.hasNext()) { - Map info = (Map) it.next(); - String name = (String) info.get("name"); - Map entityPlistMap = entityPListMap(name); - List classProperties = (List) entityPlistMap.get("classProperties"); - if (classProperties == null) { - classProperties = Collections.EMPTY_LIST; - } - - // get client class information - Map internalInfo = (Map) entityPlistMap.get("internalInfo"); - - List clientClassProperties = (internalInfo != null) ? (List) internalInfo - .get("_clientClassPropertyNames") : null; - - // guard against no internal info and no client class properties - if (clientClassProperties == null) { - clientClassProperties = Collections.EMPTY_LIST; - } - - // there is a bug in EOModeler it sometimes keeps outdated properties in - // the client property list. This removes them - clientClassProperties.retainAll(classProperties); - - // remove all properties from the entity properties that are already defined - // in - // a potential parent class. - String parentEntity = (String) entityPlistMap.get("parent"); - while (parentEntity != null) { - Map parentEntityPListMap = entityPListMap(parentEntity); - List parentClassProps = (List) parentEntityPListMap - .get("classProperties"); - classProperties.removeAll(parentClassProps); - // get client class information of parent - Map parentInternalInfo = (Map) parentEntityPListMap.get("internalInfo"); - - if (parentInternalInfo != null) { - List parentClientClassProps = (List) parentInternalInfo - .get("_clientClassPropertyNames"); - clientClassProperties.removeAll(parentClientClassProps); - } - - parentEntity = (String) parentEntityPListMap.get("parent"); - } - - // put back processed properties to the map - entityPlistMap.put("classProperties", classProperties); - // add client classes directly for easier access - entityPlistMap.put("clientClassProperties", clientClassProperties); - } - } - - /** - * Performs Objective C data types conversion to Java types. - * - * @since 1.1 - * @return String representation for Java type corresponding to String representation - * of Objective C type. - */ - public String javaTypeForEOModelerType(String valueClassName, String valueType) { - if (valueClassName == null) { - return null; - } - - if (valueClassName.equals("NSString")) { - return String.class.getName(); - } - - if (valueClassName.equals("NSNumber")) { - Class numericClass = numericAttributeClass(valueType); - return (numericClass != null) ? numericClass.getName() : Number.class - .getName(); - } - - if (valueClassName.equals("NSCalendarDate")) - return "java.sql.Timestamp"; - - if (valueClassName.equals("NSDecimalNumber")) { - Class numericClass = numericAttributeClass(valueType); - return (numericClass != null) ? numericClass.getName() : BigDecimal.class - .getName(); - } - - if (valueClassName.equals("NSData")) - return "byte[]"; - - // don't know what the class is mapped to... - // do some minimum sanity check and use as is - try { - return Class.forName(valueClassName).getName(); - } - catch (ClassNotFoundException aClassNotFoundException) { - try { - return Class.forName("java.lang." + valueClassName).getName(); - } - catch (ClassNotFoundException anotherClassNotFoundException) { - try { - return Class.forName("java.util." + valueClassName).getName(); - } - catch (ClassNotFoundException yetAnotherClassNotFoundException) { - try { - return ClassLoader - .getSystemClassLoader() - .loadClass(valueClassName) - .getName(); - } - catch (ClassNotFoundException e) { - // likely a custom class - return valueClassName; - } - } - } - } - } - - /** - * @since 1.1 - */ - // TODO: create a lookup map, maybe XML-loaded... - protected Class numericAttributeClass(String valueType) { - if (valueType == null) { - return null; - } - else if ("b".equals(valueType)) { - return Byte.class; - } - else if ("s".equals(valueType)) { - return Short.class; - } - else if ("i".equals(valueType)) { - return Integer.class; - } - else if ("l".equals(valueType)) { - return Long.class; - } - else if ("f".equals(valueType)) { - return Float.class; - } - else if ("d".equals(valueType)) { - return Double.class; - } - else if ("B".equals(valueType)) { - return BigDecimal.class; - } - else if ("c".equals(valueType)) { - return Boolean.class; - } - else { - return null; - } - } - - /** Returns a DataMap associated with this helper. */ - public DataMap getDataMap() { - return dataMap; - } - - /** Returns EOModel location as URL. */ - public URL getModelUrl() { - return modelUrl; - } - - /** - * Returns an iterator of model names. - */ - public Iterator modelNames() { - return entityClassIndex.keySet().iterator(); - } - - /** - * Returns a list of model entity names. - * - * @since 1.1 - */ - public List modelNamesAsList() { - return new ArrayList(entityClassIndex.keySet()); - } - - public Map getPrototypeAttributeMapFor(String aPrototypeAttributeName) { - if (prototypeValues == null) { - - Map eoPrototypesEntityMap = this.entityPListMap("EOPrototypes"); - - // no prototypes - if (eoPrototypesEntityMap == null) { - prototypeValues = Collections.EMPTY_MAP; - } - else { - List eoPrototypeAttributes = (List) eoPrototypesEntityMap - .get("attributes"); - - prototypeValues = new HashMap(); - Iterator it = eoPrototypeAttributes.iterator(); - while (it.hasNext()) { - Map attrMap = (Map) it.next(); - - String attrName = (String) attrMap.get("name"); - - // TODO: why are we copying the original map? can we just use it as - // is? - Map prototypeAttrMap = new HashMap(); - prototypeValues.put(attrName, prototypeAttrMap); - - prototypeAttrMap.put("name", attrMap.get("name")); - prototypeAttrMap.put("prototypeName", attrMap.get("prototypeName")); - prototypeAttrMap.put("columnName", attrMap.get("columnName")); - prototypeAttrMap.put("valueClassName", attrMap.get("valueClassName")); - prototypeAttrMap.put("width", attrMap.get("width")); - prototypeAttrMap.put("allowsNull", attrMap.get("allowsNull")); - prototypeAttrMap.put("scale", attrMap.get("scale")); - prototypeAttrMap.put("valueType", attrMap.get("valueType")); - } - } - } - - Map aMap = (Map) prototypeValues.get(aPrototypeAttributeName); - if (null == aMap) - aMap = Collections.EMPTY_MAP; - - return aMap; - } - - /** Returns an info map for the entity called <code>entityName</code>. */ - public Map entityPListMap(String entityName) { - return (Map) entityIndex.get(entityName); - } - - /** - * Returns the iterator over EOFetchSpecification names for a given entity. - * - * @since 1.1 - */ - public Iterator queryNames(String entityName) { - Map queryPlist = (Map) entityQueryIndex.get(entityName); - if (queryPlist == null || queryPlist.isEmpty()) { - return IteratorUtils.EMPTY_ITERATOR; - } - - return queryPlist.keySet().iterator(); - } - - /** - * Returns a map containing EOFetchSpecification information for entity name and query - * name. Returns null if no such query is found. - * - * @since 1.1 - */ - public Map queryPListMap(String entityName, String queryName) { - Map queryPlist = (Map) entityQueryIndex.get(entityName); - if (queryPlist == null || queryPlist.isEmpty()) { - return null; - } - - return (Map) queryPlist.get(queryName); - } - - public String entityClass(String entityName, boolean getClientClass) { - if (getClientClass) { - return (String) entityClientClassIndex.get(entityName); - } - else { - return (String) entityClassIndex.get(entityName); - } - } - - /** Loads EOModel index and returns it as a map. */ - protected Map loadModelIndex() throws Exception { - InputStream indexIn = openIndexStream(); - try { - plistParser.ReInit(indexIn); - return (Map) plistParser.propertyList(); - } - finally { - indexIn.close(); - } - } - - /** - * Loads EOEntity information and returns it as a map. - */ - protected Map loadEntityIndex(String entityName) throws Exception { - InputStream entIn = openEntityStream(entityName); - try { - plistParser.ReInit(entIn); - return (Map) plistParser.propertyList(); - } - finally { - entIn.close(); - } - } - - /** - * Loads EOFetchSpecification information and returns it as a map. - */ - protected Map loadQueryIndex(String entityName) throws Exception { - InputStream queryIn = null; - - // catch file open exceptions since not all entities have query files.... - try { - queryIn = openQueryStream(entityName); - } - catch (IOException ioex) { - return Collections.EMPTY_MAP; - } - - try { - plistParser.ReInit(queryIn); - return (Map) plistParser.propertyList(); - } - finally { - queryIn.close(); - } - } - - /** Returns EOModel name based on its path. */ - protected String findModelName(String path) { - // strip trailing slashes - if (path.endsWith("/") || path.endsWith("\\")) { - path = path.substring(0, path.length() - 1); - } - - // strip path components - int i1 = path.lastIndexOf("/"); - int i2 = path.lastIndexOf("\\"); - int i = (i1 > i2) ? i1 : i2; - if (i >= 0) { - path = path.substring(i + 1); - } - - // strip .eomodeld suffix - if (path.endsWith(".eomodeld")) { - path = path.substring(0, path.length() - ".eomodeld".length()); - } - - return path; - } - - /** - * Returns InputStream to read an EOModel index file. - */ - protected InputStream openIndexStream() throws Exception { - return new URL(modelUrl, "index.eomodeld").openStream(); - } - - /** - * Returns InputStream to read an EOEntity plist file. - * - * @param entityName name of EOEntity to be loaded. - * @return InputStream to read an EOEntity plist file or null if - * <code>entityname.plist</code> file can not be located. - */ - protected InputStream openEntityStream(String entityName) throws Exception { - return new URL(modelUrl, entityName + ".plist").openStream(); - } - - /** - * Returns InputStream to read an EOFetchSpecification plist file. - * - * @param entityName name of EOEntity to be loaded. - * @return InputStream to read an EOEntity plist file or null if - * <code>entityname.plist</code> file can not be located. - */ - protected InputStream openQueryStream(String entityName) throws Exception { - return new URL(modelUrl, entityName + ".fspec").openStream(); - } + private Parser plistParser = new Parser(); + protected URL modelUrl; + protected Map entityIndex; + protected Map entityClassIndex; + protected Map entityQueryIndex; + protected Map entityClientClassIndex; + protected DataMap dataMap; + private Map prototypeValues; + + /** + * Creates helper instance and tries to locate EOModel and load index file. + * + * @deprecated since 4.0, use {@link #EOModelHelper(URL)}. + */ + @Deprecated + public EOModelHelper(String path) throws Exception { + this(new File(path).toURI().toURL()); + } + + public EOModelHelper(URL modelUrl) throws Exception { + + this.modelUrl = modelUrl; + this.dataMap = new DataMap(findModelName(modelUrl.toExternalForm())); + + // load index file + List modelIndex = (List) loadModelIndex().get("entities"); + + // load entity indices + entityIndex = new HashMap(); + entityClassIndex = new HashMap(); + entityClientClassIndex = new HashMap(); + entityQueryIndex = new HashMap(); + + Iterator it = modelIndex.iterator(); + while (it.hasNext()) { + Map info = (Map) it.next(); + String name = (String) info.get("name"); + + entityIndex.put(name, loadEntityIndex(name)); + entityQueryIndex.put(name, loadQueryIndex(name)); + entityClassIndex.put(name, info.get("className")); + Map entityPlistMap = entityPListMap(name); + + // get client class information + Map internalInfo = (Map) entityPlistMap.get("internalInfo"); + + if (internalInfo != null) { + String clientClassName = (String) internalInfo.get("_javaClientClassName"); + entityClientClassIndex.put(name, clientClassName); + } + } + + it = modelIndex.iterator(); + while (it.hasNext()) { + Map info = (Map) it.next(); + String name = (String) info.get("name"); + Map entityPlistMap = entityPListMap(name); + List classProperties = (List) entityPlistMap.get("classProperties"); + if (classProperties == null) { + classProperties = Collections.EMPTY_LIST; + } + + // get client class information + Map internalInfo = (Map) entityPlistMap.get("internalInfo"); + + List clientClassProperties = (internalInfo != null) ? (List) internalInfo.get("_clientClassPropertyNames") + : null; + + // guard against no internal info and no client class properties + if (clientClassProperties == null) { + clientClassProperties = Collections.EMPTY_LIST; + } + + // there is a bug in EOModeler it sometimes keeps outdated + // properties in + // the client property list. This removes them + clientClassProperties.retainAll(classProperties); + + // remove all properties from the entity properties that are already + // defined + // in + // a potential parent class. + String parentEntity = (String) entityPlistMap.get("parent"); + while (parentEntity != null) { + Map parentEntityPListMap = entityPListMap(parentEntity); + List parentClassProps = (List) parentEntityPListMap.get("classProperties"); + classProperties.removeAll(parentClassProps); + // get client class information of parent + Map parentInternalInfo = (Map) parentEntityPListMap.get("internalInfo"); + + if (parentInternalInfo != null) { + List parentClientClassProps = (List) parentInternalInfo.get("_clientClassPropertyNames"); + clientClassProperties.removeAll(parentClientClassProps); + } + + parentEntity = (String) parentEntityPListMap.get("parent"); + } + + // put back processed properties to the map + entityPlistMap.put("classProperties", classProperties); + // add client classes directly for easier access + entityPlistMap.put("clientClassProperties", clientClassProperties); + } + } + + /** + * Performs Objective C data types conversion to Java types. + * + * @since 1.1 + * @return String representation for Java type corresponding to String + * representation of Objective C type. + */ + public String javaTypeForEOModelerType(String valueClassName, String valueType) { + if (valueClassName == null) { + return null; + } + + if (valueClassName.equals("NSString")) { + return String.class.getName(); + } + + if (valueClassName.equals("NSNumber")) { + Class numericClass = numericAttributeClass(valueType); + return (numericClass != null) ? numericClass.getName() : Number.class.getName(); + } + + if (valueClassName.equals("NSCalendarDate")) + return "java.sql.Timestamp"; + + if (valueClassName.equals("NSDecimalNumber")) { + Class numericClass = numericAttributeClass(valueType); + return (numericClass != null) ? numericClass.getName() : BigDecimal.class.getName(); + } + + if (valueClassName.equals("NSData")) + return "byte[]"; + + // don't know what the class is mapped to... + // do some minimum sanity check and use as is + try { + return Class.forName(valueClassName).getName(); + } catch (ClassNotFoundException aClassNotFoundException) { + try { + return Class.forName("java.lang." + valueClassName).getName(); + } catch (ClassNotFoundException anotherClassNotFoundException) { + try { + return Class.forName("java.util." + valueClassName).getName(); + } catch (ClassNotFoundException yetAnotherClassNotFoundException) { + try { + return ClassLoader.getSystemClassLoader().loadClass(valueClassName).getName(); + } catch (ClassNotFoundException e) { + // likely a custom class + return valueClassName; + } + } + } + } + } + + /** + * @since 1.1 + */ + // TODO: create a lookup map, maybe XML-loaded... + protected Class numericAttributeClass(String valueType) { + if (valueType == null) { + return null; + } else if ("b".equals(valueType)) { + return Byte.class; + } else if ("s".equals(valueType)) { + return Short.class; + } else if ("i".equals(valueType)) { + return Integer.class; + } else if ("l".equals(valueType)) { + return Long.class; + } else if ("f".equals(valueType)) { + return Float.class; + } else if ("d".equals(valueType)) { + return Double.class; + } else if ("B".equals(valueType)) { + return BigDecimal.class; + } else if ("c".equals(valueType)) { + return Boolean.class; + } else { + return null; + } + } + + /** Returns a DataMap associated with this helper. */ + public DataMap getDataMap() { + return dataMap; + } + + /** Returns EOModel location as URL. */ + public URL getModelUrl() { + return modelUrl; + } + + /** + * Returns an iterator of model names. + */ + public Iterator modelNames() { + return entityClassIndex.keySet().iterator(); + } + + /** + * Returns a list of model entity names. + * + * @since 1.1 + */ + public List modelNamesAsList() { + return new ArrayList(entityClassIndex.keySet()); + } + + public Map getPrototypeAttributeMapFor(String aPrototypeAttributeName) { + if (prototypeValues == null) { + + Map eoPrototypesEntityMap = this.entityPListMap("EOPrototypes"); + + // no prototypes + if (eoPrototypesEntityMap == null) { + prototypeValues = Collections.EMPTY_MAP; + } else { + List eoPrototypeAttributes = (List) eoPrototypesEntityMap.get("attributes"); + + prototypeValues = new HashMap(); + Iterator it = eoPrototypeAttributes.iterator(); + while (it.hasNext()) { + Map attrMap = (Map) it.next(); + + String attrName = (String) attrMap.get("name"); + + // TODO: why are we copying the original map? can we just + // use it as + // is? + Map prototypeAttrMap = new HashMap(); + prototypeValues.put(attrName, prototypeAttrMap); + + prototypeAttrMap.put("name", attrMap.get("name")); + prototypeAttrMap.put("prototypeName", attrMap.get("prototypeName")); + prototypeAttrMap.put("columnName", attrMap.get("columnName")); + prototypeAttrMap.put("valueClassName", attrMap.get("valueClassName")); + prototypeAttrMap.put("width", attrMap.get("width")); + prototypeAttrMap.put("allowsNull", attrMap.get("allowsNull")); + prototypeAttrMap.put("scale", attrMap.get("scale")); + prototypeAttrMap.put("valueType", attrMap.get("valueType")); + } + } + } + + Map aMap = (Map) prototypeValues.get(aPrototypeAttributeName); + if (null == aMap) + aMap = Collections.EMPTY_MAP; + + return aMap; + } + + /** Returns an info map for the entity called <code>entityName</code>. */ + public Map entityPListMap(String entityName) { + return (Map) entityIndex.get(entityName); + } + + /** + * Returns the iterator over EOFetchSpecification names for a given entity. + * + * @since 1.1 + */ + public Iterator queryNames(String entityName) { + Map queryPlist = (Map) entityQueryIndex.get(entityName); + if (queryPlist == null || queryPlist.isEmpty()) { + return IteratorUtils.EMPTY_ITERATOR; + } + + return queryPlist.keySet().iterator(); + } + + /** + * Returns a map containing EOFetchSpecification information for entity name + * and query name. Returns null if no such query is found. + * + * @since 1.1 + */ + public Map queryPListMap(String entityName, String queryName) { + Map queryPlist = (Map) entityQueryIndex.get(entityName); + if (queryPlist == null || queryPlist.isEmpty()) { + return null; + } + + return (Map) queryPlist.get(queryName); + } + + public String entityClass(String entityName, boolean getClientClass) { + if (getClientClass) { + return (String) entityClientClassIndex.get(entityName); + } else { + return (String) entityClassIndex.get(entityName); + } + } + + /** Loads EOModel index and returns it as a map. */ + protected Map loadModelIndex() throws Exception { + + try (InputStream indexIn = openIndexStream();) { + plistParser.ReInit(indexIn); + return (Map) plistParser.propertyList(); + } + } + + /** + * Loads EOEntity information and returns it as a map. + */ + protected Map loadEntityIndex(String entityName) throws Exception { + + try (InputStream entIn = openEntityStream(entityName);) { + plistParser.ReInit(entIn); + return (Map) plistParser.propertyList(); + } + } + + /** + * Loads EOFetchSpecification information and returns it as a map. + */ + protected Map loadQueryIndex(String entityName) throws Exception { + InputStream queryIn = null; + + // catch file open exceptions since not all entities have query + // files.... + try { + queryIn = openQueryStream(entityName); + } catch (IOException ioex) { + return Collections.EMPTY_MAP; + } + + try { + plistParser.ReInit(queryIn); + return (Map) plistParser.propertyList(); + } finally { + queryIn.close(); + } + } + + /** Returns EOModel name based on its path. */ + protected String findModelName(String path) { + // strip trailing slashes + if (path.endsWith("/") || path.endsWith("\\")) { + path = path.substring(0, path.length() - 1); + } + + // strip path components + int i1 = path.lastIndexOf("/"); + int i2 = path.lastIndexOf("\\"); + int i = (i1 > i2) ? i1 : i2; + if (i >= 0) { + path = path.substring(i + 1); + } + + // strip .eomodeld suffix + if (path.endsWith(".eomodeld")) { + path = path.substring(0, path.length() - ".eomodeld".length()); + } + + return path; + } + + /** + * Returns InputStream to read an EOModel index file. + */ + protected InputStream openIndexStream() throws Exception { + return new URL(modelUrl, "index.eomodeld").openStream(); + } + + /** + * Returns InputStream to read an EOEntity plist file. + * + * @param entityName + * name of EOEntity to be loaded. + * @return InputStream to read an EOEntity plist file or null if + * <code>entityname.plist</code> file can not be located. + */ + protected InputStream openEntityStream(String entityName) throws Exception { + return new URL(modelUrl, entityName + ".plist").openStream(); + } + + /** + * Returns InputStream to read an EOFetchSpecification plist file. + * + * @param entityName + * name of EOEntity to be loaded. + * @return InputStream to read an EOEntity plist file or null if + * <code>entityname.plist</code> file can not be located. + */ + protected InputStream openQueryStream(String entityName) throws Exception { + return new URL(modelUrl, entityName + ".fspec").openStream(); + } }
