http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/cayenne-server/src/test/java/org/apache/cayenne/query/SelectQueryIT.java ---------------------------------------------------------------------- diff --git a/cayenne-server/src/test/java/org/apache/cayenne/query/SelectQueryIT.java b/cayenne-server/src/test/java/org/apache/cayenne/query/SelectQueryIT.java index 9a1717c..b526b3b 100644 --- a/cayenne-server/src/test/java/org/apache/cayenne/query/SelectQueryIT.java +++ b/cayenne-server/src/test/java/org/apache/cayenne/query/SelectQueryIT.java @@ -537,9 +537,8 @@ public class SelectQueryIT extends ServerCase { createArtistsDataSet(); SelectQuery<Artist> q1 = new SelectQuery<Artist>(Artist.class); - ResultIterator<Artist> it = q1.iterator(context); - try { + try (ResultIterator<Artist> it = q1.iterator(context);) { int count = 0; for (@SuppressWarnings("unused") @@ -548,8 +547,6 @@ public class SelectQueryIT extends ServerCase { } assertEquals(20, count); - } finally { - it.close(); } } @@ -558,9 +555,8 @@ public class SelectQueryIT extends ServerCase { createArtistsDataSet(); SelectQuery<Artist> q1 = new SelectQuery<Artist>(Artist.class); - ResultBatchIterator<Artist> it = q1.batchIterator(context, 5); - try { + try (ResultBatchIterator<Artist> it = q1.batchIterator(context, 5);) { int count = 0; for (List<Artist> artistList : it) { @@ -569,8 +565,6 @@ public class SelectQueryIT extends ServerCase { } assertEquals(4, count); - } finally { - it.close(); } }
http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/cayenne-server/src/test/java/org/apache/cayenne/resource/FilesystemResourceLocatorTest.java ---------------------------------------------------------------------- diff --git a/cayenne-server/src/test/java/org/apache/cayenne/resource/FilesystemResourceLocatorTest.java b/cayenne-server/src/test/java/org/apache/cayenne/resource/FilesystemResourceLocatorTest.java index bdbeaad..b24f7e4 100644 --- a/cayenne-server/src/test/java/org/apache/cayenne/resource/FilesystemResourceLocatorTest.java +++ b/cayenne-server/src/test/java/org/apache/cayenne/resource/FilesystemResourceLocatorTest.java @@ -32,78 +32,76 @@ import static org.junit.Assert.assertNotNull; public class FilesystemResourceLocatorTest { - @Test - public void testArrayConstructor() { - FilesystemResourceLocator l1 = new FilesystemResourceLocator(); - assertEquals(1, l1.roots.length); - assertEquals(System.getProperty("user.dir"), l1.roots[0].getPath()); - - File base = FileUtil.baseTestDirectory(); - File f1 = new File(base, "f1"); - File f2 = new File(new File(base, "f2"), "f3"); - - FilesystemResourceLocator l2 = new FilesystemResourceLocator(f1, f2); - assertEquals(2, l2.roots.length); - assertEquals(base, l2.roots[0]); - assertEquals(new File(base, "f2"), l2.roots[1]); - } - - @Test - public void testCollectionConstructor() { - FilesystemResourceLocator l1 = new FilesystemResourceLocator(Collections - .<File> emptyList()); - assertEquals(1, l1.roots.length); - assertEquals(System.getProperty("user.dir"), l1.roots[0].getPath()); - - File base = FileUtil.baseTestDirectory(); - File f1 = new File(base, "f1"); - File f2 = new File(new File(base, "f2"), "f3"); - - FilesystemResourceLocator l2 = new FilesystemResourceLocator(Arrays - .asList(f1, f2)); - assertEquals(2, l2.roots.length); - assertEquals(base, l2.roots[0]); - assertEquals(new File(base, "f2"), l2.roots[1]); - } - - @Test - public void testFindResources() throws Exception { - - File base = new File(FileUtil.baseTestDirectory(), getClass().getName()); - File root1 = new File(base, "r1"); - File root2 = new File(base, "r2"); - - root1.mkdirs(); - root2.mkdirs(); - - FilesystemResourceLocator locator = new FilesystemResourceLocator(root1, root2); - Collection<Resource> resources1 = locator.findResources("x.txt"); - assertNotNull(resources1); - assertEquals(0, resources1.size()); - - File f1 = new File(root1, "x.txt"); - touch(f1); - - Collection<Resource> resources2 = locator.findResources("x.txt"); - assertNotNull(resources2); - assertEquals(1, resources2.size()); - assertEquals(f1.toURL(), resources2.iterator().next().getURL()); - - File f2 = new File(root2, "x.txt"); - touch(f2); - - Collection<Resource> resources3 = locator.findResources("x.txt"); - assertNotNull(resources3); - assertEquals(2, resources3.size()); - - Resource[] resources3a = resources3.toArray(new Resource[2]); - assertEquals(f1.toURL(), resources3a[0].getURL()); - assertEquals(f2.toURL(), resources3a[1].getURL()); - } - - private void touch(File f) throws Exception { - FileOutputStream out = new FileOutputStream(f); - out.write('a'); - out.close(); - } + @Test + public void testArrayConstructor() { + FilesystemResourceLocator l1 = new FilesystemResourceLocator(); + assertEquals(1, l1.roots.length); + assertEquals(System.getProperty("user.dir"), l1.roots[0].getPath()); + + File base = FileUtil.baseTestDirectory(); + File f1 = new File(base, "f1"); + File f2 = new File(new File(base, "f2"), "f3"); + + FilesystemResourceLocator l2 = new FilesystemResourceLocator(f1, f2); + assertEquals(2, l2.roots.length); + assertEquals(base, l2.roots[0]); + assertEquals(new File(base, "f2"), l2.roots[1]); + } + + @Test + public void testCollectionConstructor() { + FilesystemResourceLocator l1 = new FilesystemResourceLocator(Collections.<File> emptyList()); + assertEquals(1, l1.roots.length); + assertEquals(System.getProperty("user.dir"), l1.roots[0].getPath()); + + File base = FileUtil.baseTestDirectory(); + File f1 = new File(base, "f1"); + File f2 = new File(new File(base, "f2"), "f3"); + + FilesystemResourceLocator l2 = new FilesystemResourceLocator(Arrays.asList(f1, f2)); + assertEquals(2, l2.roots.length); + assertEquals(base, l2.roots[0]); + assertEquals(new File(base, "f2"), l2.roots[1]); + } + + @Test + public void testFindResources() throws Exception { + + File base = new File(FileUtil.baseTestDirectory(), getClass().getName()); + File root1 = new File(base, "r1"); + File root2 = new File(base, "r2"); + + root1.mkdirs(); + root2.mkdirs(); + + FilesystemResourceLocator locator = new FilesystemResourceLocator(root1, root2); + Collection<Resource> resources1 = locator.findResources("x.txt"); + assertNotNull(resources1); + assertEquals(0, resources1.size()); + + File f1 = new File(root1, "x.txt"); + touch(f1); + + Collection<Resource> resources2 = locator.findResources("x.txt"); + assertNotNull(resources2); + assertEquals(1, resources2.size()); + assertEquals(f1.toURL(), resources2.iterator().next().getURL()); + + File f2 = new File(root2, "x.txt"); + touch(f2); + + Collection<Resource> resources3 = locator.findResources("x.txt"); + assertNotNull(resources3); + assertEquals(2, resources3.size()); + + Resource[] resources3a = resources3.toArray(new Resource[2]); + assertEquals(f1.toURL(), resources3a[0].getURL()); + assertEquals(f2.toURL(), resources3a[1].getURL()); + } + + private void touch(File f) throws Exception { + try (FileOutputStream out = new FileOutputStream(f);) { + out.write('a'); + } + } } http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/cayenne-server/src/test/java/org/apache/cayenne/unit/HSQLProcedures.java ---------------------------------------------------------------------- diff --git a/cayenne-server/src/test/java/org/apache/cayenne/unit/HSQLProcedures.java b/cayenne-server/src/test/java/org/apache/cayenne/unit/HSQLProcedures.java index 5dda854..707b4c9 100644 --- a/cayenne-server/src/test/java/org/apache/cayenne/unit/HSQLProcedures.java +++ b/cayenne-server/src/test/java/org/apache/cayenne/unit/HSQLProcedures.java @@ -28,38 +28,30 @@ import java.sql.SQLException; */ public class HSQLProcedures { - public static void cayenne_tst_upd_proc(Connection c, int paintingPrice) - throws SQLException { - - PreparedStatement st = c - .prepareStatement("UPDATE PAINTING SET ESTIMATED_PRICE = ESTIMATED_PRICE * 2 " - + "WHERE ESTIMATED_PRICE < ?"); - - st.setInt(1, paintingPrice); - st.execute(); - st.close(); - } - - public static void cayenne_tst_select_proc( - Connection c, - String name, - int paintingPrice) throws SQLException { - - PreparedStatement st = c - .prepareStatement("UPDATE PAINTING SET ESTIMATED_PRICE = ESTIMATED_PRICE * 2 " - + "WHERE ESTIMATED_PRICE < ?"); - - st.setInt(1, paintingPrice); - st.execute(); - st.close(); - - PreparedStatement select = c - .prepareStatement("SELECT DISTINCT A.ARTIST_ID, A.ARTIST_NAME, A.DATE_OF_BIRTH" - + " FROM ARTIST A, PAINTING P" - + " WHERE A.ARTIST_ID = P.ARTIST_ID AND" - + " A.ARTIST_NAME = ?" - + " ORDER BY A.ARTIST_ID"); - select.setString(1, name); - select.executeQuery(); - } + public static void cayenne_tst_upd_proc(Connection c, int paintingPrice) throws SQLException { + + try (PreparedStatement st = c.prepareStatement("UPDATE PAINTING SET ESTIMATED_PRICE = ESTIMATED_PRICE * 2 " + + "WHERE ESTIMATED_PRICE < ?");) { + st.setInt(1, paintingPrice); + st.execute(); + } + } + + public static void cayenne_tst_select_proc(Connection c, String name, int paintingPrice) throws SQLException { + + try (PreparedStatement st = c.prepareStatement("UPDATE PAINTING SET ESTIMATED_PRICE = ESTIMATED_PRICE * 2 " + + "WHERE ESTIMATED_PRICE < ?");) { + + st.setInt(1, paintingPrice); + st.execute(); + } + + try (PreparedStatement select = c + .prepareStatement("SELECT DISTINCT A.ARTIST_ID, A.ARTIST_NAME, A.DATE_OF_BIRTH" + + " FROM ARTIST A, PAINTING P" + " WHERE A.ARTIST_ID = P.ARTIST_ID AND" + " A.ARTIST_NAME = ?" + + " ORDER BY A.ARTIST_ID");) { + select.setString(1, name); + select.executeQuery(); + } + } } http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/cayenne-server/src/test/java/org/apache/cayenne/unit/SybaseUnitDbAdapter.java ---------------------------------------------------------------------- diff --git a/cayenne-server/src/test/java/org/apache/cayenne/unit/SybaseUnitDbAdapter.java b/cayenne-server/src/test/java/org/apache/cayenne/unit/SybaseUnitDbAdapter.java index 559ca4d..ae1ad4f 100644 --- a/cayenne-server/src/test/java/org/apache/cayenne/unit/SybaseUnitDbAdapter.java +++ b/cayenne-server/src/test/java/org/apache/cayenne/unit/SybaseUnitDbAdapter.java @@ -36,133 +36,128 @@ import java.util.List; */ public class SybaseUnitDbAdapter extends UnitDbAdapter { - public SybaseUnitDbAdapter(DbAdapter adapter) { - super(adapter); - } - - public String getIdentifiersStartQuote() { - return "["; - } - - public String getIdentifiersEndQuote() { - return "]"; - } - - @Override - public boolean supportsStoredProcedures() { - return true; - } - - @Override - public void createdTables(Connection con, DataMap map) throws Exception { - Procedure proc = map.getProcedure("cayenne_tst_select_proc"); - if (proc != null && proc.getDataMap() == map) { - executeDDL(con, "sybase", "create-select-sp.sql"); - executeDDL(con, "sybase", "create-update-sp.sql"); - executeDDL(con, "sybase", "create-update-sp2.sql"); - executeDDL(con, "sybase", "create-out-sp.sql"); - } - } - - @Override - public void willCreateTables(Connection con, DataMap map) throws Exception { - - // Sybase does not support NULLable BIT columns... - DbEntity e = map.getDbEntity("PRIMITIVES_TEST"); - if (e != null) { - e.getAttribute("BOOLEAN_COLUMN").setMandatory(true); - } - DbEntity e1 = map.getDbEntity("INHERITANCE_SUB_ENTITY3"); - if (e1 != null) { - e1.getAttribute("SUBENTITY_BOOL_ATTR").setMandatory(true); - } - DbEntity e2 = map.getDbEntity("MT_TABLE_BOOL"); - if (e2 != null) { - e2.getAttribute("BOOLEAN_COLUMN").setMandatory(true); - } - DbEntity e3 = map.getDbEntity("QUALIFIED1"); - if (e3 != null) { - e3.getAttribute("DELETED").setMandatory(true); - } - - DbEntity e4 = map.getDbEntity("QUALIFIED2"); - if (e4 != null) { - e4.getAttribute("DELETED").setMandatory(true); - } - - DbEntity e5 = map.getDbEntity("Painting"); - if (e5 != null) { - if (e5.getAttribute("NEWCOL2") != null) { - e5.getAttribute("DELETED").setMandatory(true); - } - } - - DbEntity e6 = map.getDbEntity("SOFT_TEST"); - if (e6 != null) { - e6.getAttribute("DELETED").setMandatory(true); - } - - } - - @Override - public void willDropTables(Connection con, DataMap map, Collection tablesToDrop) throws Exception { - - Iterator it = tablesToDrop.iterator(); - while (it.hasNext()) { - dropConstraints(con, (String) it.next()); - } - - dropProcedures(con, map); - } - - protected void dropProcedures(Connection con, DataMap map) throws Exception { - Procedure proc = map.getProcedure("cayenne_tst_select_proc"); - if (proc != null && proc.getDataMap() == map) { - executeDDL(con, "sybase", "drop-select-sp.sql"); - executeDDL(con, "sybase", "drop-update-sp.sql"); - executeDDL(con, "sybase", "drop-update-sp2.sql"); - executeDDL(con, "sybase", "drop-out-sp.sql"); - } - } - - protected void dropConstraints(Connection con, String tableName) throws Exception { - List names = new ArrayList(3); - Statement select = con.createStatement(); - - try { - ResultSet rs = select.executeQuery("SELECT t0.name " - + "FROM sysobjects t0, sysconstraints t1, sysobjects t2 " - + "WHERE t0.id = t1.constrid and t1.tableid = t2.id and t2.name = '" + tableName + "'"); - try { - - while (rs.next()) { - names.add(rs.getString("name")); - } - } finally { - rs.close(); - } - } finally { - select.close(); - } - - for (Object name : names) { - executeDDL(con, "alter table " + tableName + " drop constraint " + name); - } - } - - @Override - public boolean supportsLobs() { - return true; - } - - @Override - public boolean handlesNullVsEmptyLOBs() { - // TODO Sybase handling of this must be fixed - return false; - } - - @Override - public boolean supportsNullBoolean() { - return false; - } + public SybaseUnitDbAdapter(DbAdapter adapter) { + super(adapter); + } + + public String getIdentifiersStartQuote() { + return "["; + } + + public String getIdentifiersEndQuote() { + return "]"; + } + + @Override + public boolean supportsStoredProcedures() { + return true; + } + + @Override + public void createdTables(Connection con, DataMap map) throws Exception { + Procedure proc = map.getProcedure("cayenne_tst_select_proc"); + if (proc != null && proc.getDataMap() == map) { + executeDDL(con, "sybase", "create-select-sp.sql"); + executeDDL(con, "sybase", "create-update-sp.sql"); + executeDDL(con, "sybase", "create-update-sp2.sql"); + executeDDL(con, "sybase", "create-out-sp.sql"); + } + } + + @Override + public void willCreateTables(Connection con, DataMap map) throws Exception { + + // Sybase does not support NULLable BIT columns... + DbEntity e = map.getDbEntity("PRIMITIVES_TEST"); + if (e != null) { + e.getAttribute("BOOLEAN_COLUMN").setMandatory(true); + } + DbEntity e1 = map.getDbEntity("INHERITANCE_SUB_ENTITY3"); + if (e1 != null) { + e1.getAttribute("SUBENTITY_BOOL_ATTR").setMandatory(true); + } + DbEntity e2 = map.getDbEntity("MT_TABLE_BOOL"); + if (e2 != null) { + e2.getAttribute("BOOLEAN_COLUMN").setMandatory(true); + } + DbEntity e3 = map.getDbEntity("QUALIFIED1"); + if (e3 != null) { + e3.getAttribute("DELETED").setMandatory(true); + } + + DbEntity e4 = map.getDbEntity("QUALIFIED2"); + if (e4 != null) { + e4.getAttribute("DELETED").setMandatory(true); + } + + DbEntity e5 = map.getDbEntity("Painting"); + if (e5 != null) { + if (e5.getAttribute("NEWCOL2") != null) { + e5.getAttribute("DELETED").setMandatory(true); + } + } + + DbEntity e6 = map.getDbEntity("SOFT_TEST"); + if (e6 != null) { + e6.getAttribute("DELETED").setMandatory(true); + } + + } + + @Override + public void willDropTables(Connection con, DataMap map, Collection tablesToDrop) throws Exception { + + Iterator it = tablesToDrop.iterator(); + while (it.hasNext()) { + dropConstraints(con, (String) it.next()); + } + + dropProcedures(con, map); + } + + protected void dropProcedures(Connection con, DataMap map) throws Exception { + Procedure proc = map.getProcedure("cayenne_tst_select_proc"); + if (proc != null && proc.getDataMap() == map) { + executeDDL(con, "sybase", "drop-select-sp.sql"); + executeDDL(con, "sybase", "drop-update-sp.sql"); + executeDDL(con, "sybase", "drop-update-sp2.sql"); + executeDDL(con, "sybase", "drop-out-sp.sql"); + } + } + + protected void dropConstraints(Connection con, String tableName) throws Exception { + List<String> names = new ArrayList<>(3); + + try (Statement select = con.createStatement();) { + + try (ResultSet rs = select.executeQuery("SELECT t0.name " + + "FROM sysobjects t0, sysconstraints t1, sysobjects t2 " + + "WHERE t0.id = t1.constrid and t1.tableid = t2.id and t2.name = '" + tableName + "'");) { + + while (rs.next()) { + names.add(rs.getString("name")); + } + } + } + + for (String name : names) { + executeDDL(con, "alter table " + tableName + " drop constraint " + name); + } + } + + @Override + public boolean supportsLobs() { + return true; + } + + @Override + public boolean handlesNullVsEmptyLOBs() { + // TODO Sybase handling of this must be fixed + return false; + } + + @Override + public boolean supportsNullBoolean() { + return false; + } } http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/cayenne-server/src/test/java/org/apache/cayenne/unit/di/server/SchemaBuilder.java ---------------------------------------------------------------------- diff --git a/cayenne-server/src/test/java/org/apache/cayenne/unit/di/server/SchemaBuilder.java b/cayenne-server/src/test/java/org/apache/cayenne/unit/di/server/SchemaBuilder.java index f397168..8cba086 100644 --- a/cayenne-server/src/test/java/org/apache/cayenne/unit/di/server/SchemaBuilder.java +++ b/cayenne-server/src/test/java/org/apache/cayenne/unit/di/server/SchemaBuilder.java @@ -62,325 +62,328 @@ import java.util.ListIterator; */ public class SchemaBuilder { - private static Log logger = LogFactory.getLog(SchemaBuilder.class); - - public static final String CONNECTION_NAME_KEY = "cayenneTestConnection"; - public static final String DEFAULT_CONNECTION_KEY = "internal_embedded_datasource"; - - public static final String SKIP_SCHEMA_KEY = "cayenne.test.schema.skip"; - - private static String[] MAPS_REQUIRING_SCHEMA_SETUP = {"testmap.map.xml", "compound.map.xml", "misc-types.map.xml", "things.map.xml", "numeric-types.map.xml", "binary-pk.map.xml", "no-pk.map.xml", - "lob.map.xml", "date-time.map.xml", "enum.map.xml", "extended-type.map.xml", "generated.map.xml", "mixed-persistence-strategy.map.xml", "people.map.xml", "primitive.map.xml", "inheritance.map.xml", - "locking.map.xml", "soft-delete.map.xml", "empty.map.xml", "relationships.map.xml", "relationships-activity.map.xml", "relationships-delete-rules.map.xml", - "relationships-collection-to-many.map.xml", "relationships-child-master.map.xml", "relationships-clob.map.xml", - "relationships-flattened.map.xml", "relationships-set-to-many.map.xml", "relationships-to-many-fk.map.xml", "relationships-to-one-fk.map.xml", "return-types.map.xml", "uuid.map.xml", - "multi-tier.map.xml", "persistent.map.xml", "reflexive.map.xml", "delete-rules.map.xml", "lifecycles.map.xml", - "map-to-many.map.xml", "toone.map.xml", "meaningful-pk.map.xml", "table-primitives.map.xml", - "generic.map.xml", "map-db1.map.xml", "map-db2.map.xml", "embeddable.map.xml", "qualified.map.xml", - "quoted-identifiers.map.xml", "inheritance-single-table1.map.xml", "inheritance-vertical.map.xml", - "oneway-rels.map.xml", "unsupported-distinct-types.map.xml", "array-type.map.xml" }; - - // hardcoded dependent entities that should be excluded - // if LOBs are not supported - private static final String[] EXTRA_EXCLUDED_FOR_NO_LOB = new String[] { "CLOB_DETAIL" }; - - private ServerCaseDataSourceFactory dataSourceFactory; - private UnitDbAdapter unitDbAdapter; - private DbAdapter dbAdapter; - private DataDomain domain; - private JdbcEventLogger jdbcEventLogger; - - public SchemaBuilder(@Inject ServerCaseDataSourceFactory dataSourceFactory, @Inject UnitDbAdapter unitDbAdapter, - @Inject DbAdapter dbAdapter, @Inject JdbcEventLogger jdbcEventLogger) { - this.dataSourceFactory = dataSourceFactory; - this.unitDbAdapter = unitDbAdapter; - this.dbAdapter = dbAdapter; - this.jdbcEventLogger = jdbcEventLogger; - } - - /** - * Completely rebuilds test schema. - */ - // TODO - this method changes the internal state of the object ... refactor - public void rebuildSchema() { - - if ("true".equalsIgnoreCase(System.getProperty(SKIP_SCHEMA_KEY))) { - logger.info("skipping schema generation... "); - return; - } - - // generate schema combining all DataMaps that require schema support. - // Schema generation is done like that instead of per DataMap on demand - // to avoid conflicts when dropping and generating PK objects. - - DataMap[] maps = new DataMap[MAPS_REQUIRING_SCHEMA_SETUP.length]; - - for (int i = 0; i < maps.length; i++) { - InputStream stream = getClass().getClassLoader().getResourceAsStream(MAPS_REQUIRING_SCHEMA_SETUP[i]); - InputSource in = new InputSource(stream); - in.setSystemId(MAPS_REQUIRING_SCHEMA_SETUP[i]); - maps[i] = new MapLoader().loadDataMap(in); - } - - this.domain = new DataDomain("temp"); - domain.setEventManager(new DefaultEventManager(2)); - domain.setEntitySorter(new AshwoodEntitySorter()); - domain.setQueryCache(new MapQueryCache(50)); - - try { - for (DataMap map : maps) { - initNode(map); - } - - dropSchema(); - dropPKSupport(); - createSchema(); - createPKSupport(); - } catch (Exception e) { - throw new RuntimeException("Error rebuilding schema", e); - } - } - - private void initNode(DataMap map) throws Exception { - - DataNode node = new DataNode(map.getName()); - node.setJdbcEventLogger(jdbcEventLogger); - node.setAdapter(dbAdapter); - node.setDataSource(dataSourceFactory.getSharedDataSource()); - - // setup test extended types - node.getAdapter().getExtendedTypes().registerType(new StringET1ExtendedType()); - - // tweak mapping with a delegate - for (Procedure proc : map.getProcedures()) { - unitDbAdapter.tweakProcedure(proc); - } - - node.addDataMap(map); - - node.setSchemaUpdateStrategy(new SkipSchemaUpdateStrategy()); - node.setRowReaderFactory(new DefaultRowReaderFactory()); - node.setBatchTranslatorFactory(new DefaultBatchTranslatorFactory()); - node.setSelectTranslatorFactory(new DefaultSelectTranslatorFactory()); - domain.addNode(node); - } - - /** Drops all test tables. */ - private void dropSchema() throws Exception { - for (DataNode node : domain.getDataNodes()) { - dropSchema(node, node.getDataMaps().iterator().next()); - } - } - - /** - * Creates all test tables in the database. - */ - private void createSchema() throws Exception { - for (DataNode node : domain.getDataNodes()) { - createSchema(node, node.getDataMaps().iterator().next()); - } - } - - public void dropPKSupport() throws Exception { - for (DataNode node : domain.getDataNodes()) { - dropPKSupport(node, node.getDataMaps().iterator().next()); - } - } - - /** - * Creates primary key support for all node DbEntities. Will use its - * facilities provided by DbAdapter to generate any necessary database - * objects and data for primary key support. - */ - public void createPKSupport() throws Exception { - for (DataNode node : domain.getDataNodes()) { - createPKSupport(node, node.getDataMaps().iterator().next()); - } - } - - /** - * Helper method that orders DbEntities to satisfy referential constraints - * and returns an ordered list. - */ - private List<DbEntity> dbEntitiesInInsertOrder(DataNode node, DataMap map) { - List<DbEntity> entities = new ArrayList<DbEntity>(map.getDbEntities()); - - dbEntitiesFilter(entities); - - domain.getEntitySorter().sortDbEntities(entities, false); - return entities; - } - - protected List<DbEntity> dbEntitiesInDeleteOrder(DataMap dataMap) { - DataMap map = domain.getDataMap(dataMap.getName()); - List<DbEntity> entities = new ArrayList<DbEntity>(map.getDbEntities()); - - dbEntitiesFilter(entities); - - domain.getEntitySorter().sortDbEntities(entities, true); - return entities; - } - - private void dbEntitiesFilter(List<DbEntity> entities) { - // filter various unsupported tests... - - // LOBs - boolean excludeLOB = !unitDbAdapter.supportsLobs(); - boolean excludeBinPK = !unitDbAdapter.supportsBinaryPK(); - if (excludeLOB || excludeBinPK) { - - List<DbEntity> filtered = new ArrayList<DbEntity>(); - - for (DbEntity ent : entities) { - - // check for LOB attributes - if (excludeLOB) { - if (Arrays.binarySearch(EXTRA_EXCLUDED_FOR_NO_LOB, ent.getName()) >= 0) { - continue; - } - - boolean hasLob = false; - for (final DbAttribute attr : ent.getAttributes()) { - if (attr.getType() == Types.BLOB || attr.getType() == Types.CLOB) { - hasLob = true; - break; - } - } - - if (hasLob) { - continue; - } - } - - // check for BIN PK - if (excludeBinPK) { - boolean skip = false; - for (final DbAttribute attr : ent.getAttributes()) { - // check for BIN PK or FK to BIN Pk - if (attr.getType() == Types.BINARY || attr.getType() == Types.VARBINARY - || attr.getType() == Types.LONGVARBINARY) { - - if (attr.isPrimaryKey() || attr.isForeignKey()) { - skip = true; - break; - } - } - } - - if (skip) { - continue; - } - } - - filtered.add(ent); - } - - entities = filtered; - } - } - - private void dropSchema(DataNode node, DataMap map) throws Exception { - Connection conn = dataSourceFactory.getSharedDataSource().getConnection(); - List<DbEntity> list = dbEntitiesInInsertOrder(node, map); - - try { - DatabaseMetaData md = conn.getMetaData(); - ResultSet tables = md.getTables(null, null, "%", null); - List<String> allTables = new ArrayList<String>(); - - while (tables.next()) { - // 'toUpperCase' is needed since most databases - // are case insensitive, and some will convert names to lower - // case - // (PostgreSQL) - String name = tables.getString("TABLE_NAME"); - if (name != null) - allTables.add(name.toUpperCase()); - } - tables.close(); - - unitDbAdapter.willDropTables(conn, map, allTables); - - // drop all tables in the map - Statement stmt = conn.createStatement(); - - ListIterator<DbEntity> it = list.listIterator(list.size()); - while (it.hasPrevious()) { - DbEntity ent = it.previous(); - if (!allTables.contains(ent.getName().toUpperCase())) { - continue; - } - - for (String dropSql : node.getAdapter().dropTableStatements(ent)) { - try { - logger.info(dropSql); - stmt.execute(dropSql); - } catch (SQLException sqe) { - logger.warn("Can't drop table " + ent.getName() + ", ignoring...", sqe); - } - } - } - - unitDbAdapter.droppedTables(conn, map); - } finally { - conn.close(); - } - - } - - private void dropPKSupport(DataNode node, DataMap map) throws Exception { - List<DbEntity> filteredEntities = dbEntitiesInInsertOrder(node, map); - node.getAdapter().getPkGenerator().dropAutoPk(node, filteredEntities); - } - - private void createPKSupport(DataNode node, DataMap map) throws Exception { - List<DbEntity> filteredEntities = dbEntitiesInInsertOrder(node, map); - node.getAdapter().getPkGenerator().createAutoPk(node, filteredEntities); - } - - private void createSchema(DataNode node, DataMap map) throws Exception { - Connection conn = dataSourceFactory.getSharedDataSource().getConnection(); - - try { - unitDbAdapter.willCreateTables(conn, map); - Statement stmt = conn.createStatement(); - - for (String query : tableCreateQueries(node, map)) { - logger.info(query); - stmt.execute(query); - } - unitDbAdapter.createdTables(conn, map); - } finally { - conn.close(); - } - } - - /** - * Returns iterator of preprocessed table create queries. - */ - private Collection<String> tableCreateQueries(DataNode node, DataMap map) throws Exception { - DbAdapter adapter = node.getAdapter(); - DbGenerator gen = new DbGenerator(adapter, map, null, domain, jdbcEventLogger); - - List<DbEntity> orderedEnts = dbEntitiesInInsertOrder(node, map); - List<String> queries = new ArrayList<String>(); - - // table definitions - for (DbEntity ent : orderedEnts) { - queries.add(adapter.createTable(ent)); - } - - // FK constraints - for (DbEntity ent : orderedEnts) { - if (!unitDbAdapter.supportsFKConstraints(ent)) { - continue; - } - - List<String> qs = gen.createConstraintsQueries(ent); - queries.addAll(qs); - } - - return queries; - } + private static Log logger = LogFactory.getLog(SchemaBuilder.class); + + public static final String CONNECTION_NAME_KEY = "cayenneTestConnection"; + public static final String DEFAULT_CONNECTION_KEY = "internal_embedded_datasource"; + + public static final String SKIP_SCHEMA_KEY = "cayenne.test.schema.skip"; + + private static String[] MAPS_REQUIRING_SCHEMA_SETUP = { "testmap.map.xml", "compound.map.xml", + "misc-types.map.xml", "things.map.xml", "numeric-types.map.xml", "binary-pk.map.xml", "no-pk.map.xml", + "lob.map.xml", "date-time.map.xml", "enum.map.xml", "extended-type.map.xml", "generated.map.xml", + "mixed-persistence-strategy.map.xml", "people.map.xml", "primitive.map.xml", "inheritance.map.xml", + "locking.map.xml", "soft-delete.map.xml", "empty.map.xml", "relationships.map.xml", + "relationships-activity.map.xml", "relationships-delete-rules.map.xml", + "relationships-collection-to-many.map.xml", "relationships-child-master.map.xml", + "relationships-clob.map.xml", "relationships-flattened.map.xml", "relationships-set-to-many.map.xml", + "relationships-to-many-fk.map.xml", "relationships-to-one-fk.map.xml", "return-types.map.xml", + "uuid.map.xml", "multi-tier.map.xml", "persistent.map.xml", "reflexive.map.xml", "delete-rules.map.xml", + "lifecycles.map.xml", "map-to-many.map.xml", "toone.map.xml", "meaningful-pk.map.xml", + "table-primitives.map.xml", "generic.map.xml", "map-db1.map.xml", "map-db2.map.xml", "embeddable.map.xml", + "qualified.map.xml", "quoted-identifiers.map.xml", "inheritance-single-table1.map.xml", + "inheritance-vertical.map.xml", "oneway-rels.map.xml", "unsupported-distinct-types.map.xml", + "array-type.map.xml" }; + + // hardcoded dependent entities that should be excluded + // if LOBs are not supported + private static final String[] EXTRA_EXCLUDED_FOR_NO_LOB = new String[] { "CLOB_DETAIL" }; + + private ServerCaseDataSourceFactory dataSourceFactory; + private UnitDbAdapter unitDbAdapter; + private DbAdapter dbAdapter; + private DataDomain domain; + private JdbcEventLogger jdbcEventLogger; + + public SchemaBuilder(@Inject ServerCaseDataSourceFactory dataSourceFactory, @Inject UnitDbAdapter unitDbAdapter, + @Inject DbAdapter dbAdapter, @Inject JdbcEventLogger jdbcEventLogger) { + this.dataSourceFactory = dataSourceFactory; + this.unitDbAdapter = unitDbAdapter; + this.dbAdapter = dbAdapter; + this.jdbcEventLogger = jdbcEventLogger; + } + + /** + * Completely rebuilds test schema. + */ + // TODO - this method changes the internal state of the object ... refactor + public void rebuildSchema() { + + if ("true".equalsIgnoreCase(System.getProperty(SKIP_SCHEMA_KEY))) { + logger.info("skipping schema generation... "); + return; + } + + // generate schema combining all DataMaps that require schema support. + // Schema generation is done like that instead of per DataMap on demand + // to avoid conflicts when dropping and generating PK objects. + + DataMap[] maps = new DataMap[MAPS_REQUIRING_SCHEMA_SETUP.length]; + + for (int i = 0; i < maps.length; i++) { + InputStream stream = getClass().getClassLoader().getResourceAsStream(MAPS_REQUIRING_SCHEMA_SETUP[i]); + InputSource in = new InputSource(stream); + in.setSystemId(MAPS_REQUIRING_SCHEMA_SETUP[i]); + maps[i] = new MapLoader().loadDataMap(in); + } + + this.domain = new DataDomain("temp"); + domain.setEventManager(new DefaultEventManager(2)); + domain.setEntitySorter(new AshwoodEntitySorter()); + domain.setQueryCache(new MapQueryCache(50)); + + try { + for (DataMap map : maps) { + initNode(map); + } + + dropSchema(); + dropPKSupport(); + createSchema(); + createPKSupport(); + } catch (Exception e) { + throw new RuntimeException("Error rebuilding schema", e); + } + } + + private void initNode(DataMap map) throws Exception { + + DataNode node = new DataNode(map.getName()); + node.setJdbcEventLogger(jdbcEventLogger); + node.setAdapter(dbAdapter); + node.setDataSource(dataSourceFactory.getSharedDataSource()); + + // setup test extended types + node.getAdapter().getExtendedTypes().registerType(new StringET1ExtendedType()); + + // tweak mapping with a delegate + for (Procedure proc : map.getProcedures()) { + unitDbAdapter.tweakProcedure(proc); + } + + node.addDataMap(map); + + node.setSchemaUpdateStrategy(new SkipSchemaUpdateStrategy()); + node.setRowReaderFactory(new DefaultRowReaderFactory()); + node.setBatchTranslatorFactory(new DefaultBatchTranslatorFactory()); + node.setSelectTranslatorFactory(new DefaultSelectTranslatorFactory()); + domain.addNode(node); + } + + /** Drops all test tables. */ + private void dropSchema() throws Exception { + for (DataNode node : domain.getDataNodes()) { + dropSchema(node, node.getDataMaps().iterator().next()); + } + } + + /** + * Creates all test tables in the database. + */ + private void createSchema() throws Exception { + for (DataNode node : domain.getDataNodes()) { + createSchema(node, node.getDataMaps().iterator().next()); + } + } + + public void dropPKSupport() throws Exception { + for (DataNode node : domain.getDataNodes()) { + dropPKSupport(node, node.getDataMaps().iterator().next()); + } + } + + /** + * Creates primary key support for all node DbEntities. Will use its + * facilities provided by DbAdapter to generate any necessary database + * objects and data for primary key support. + */ + public void createPKSupport() throws Exception { + for (DataNode node : domain.getDataNodes()) { + createPKSupport(node, node.getDataMaps().iterator().next()); + } + } + + /** + * Helper method that orders DbEntities to satisfy referential constraints + * and returns an ordered list. + */ + private List<DbEntity> dbEntitiesInInsertOrder(DataNode node, DataMap map) { + List<DbEntity> entities = new ArrayList<DbEntity>(map.getDbEntities()); + + dbEntitiesFilter(entities); + + domain.getEntitySorter().sortDbEntities(entities, false); + return entities; + } + + protected List<DbEntity> dbEntitiesInDeleteOrder(DataMap dataMap) { + DataMap map = domain.getDataMap(dataMap.getName()); + List<DbEntity> entities = new ArrayList<DbEntity>(map.getDbEntities()); + + dbEntitiesFilter(entities); + + domain.getEntitySorter().sortDbEntities(entities, true); + return entities; + } + + private void dbEntitiesFilter(List<DbEntity> entities) { + // filter various unsupported tests... + + // LOBs + boolean excludeLOB = !unitDbAdapter.supportsLobs(); + boolean excludeBinPK = !unitDbAdapter.supportsBinaryPK(); + if (excludeLOB || excludeBinPK) { + + List<DbEntity> filtered = new ArrayList<DbEntity>(); + + for (DbEntity ent : entities) { + + // check for LOB attributes + if (excludeLOB) { + if (Arrays.binarySearch(EXTRA_EXCLUDED_FOR_NO_LOB, ent.getName()) >= 0) { + continue; + } + + boolean hasLob = false; + for (final DbAttribute attr : ent.getAttributes()) { + if (attr.getType() == Types.BLOB || attr.getType() == Types.CLOB) { + hasLob = true; + break; + } + } + + if (hasLob) { + continue; + } + } + + // check for BIN PK + if (excludeBinPK) { + boolean skip = false; + for (final DbAttribute attr : ent.getAttributes()) { + // check for BIN PK or FK to BIN Pk + if (attr.getType() == Types.BINARY || attr.getType() == Types.VARBINARY + || attr.getType() == Types.LONGVARBINARY) { + + if (attr.isPrimaryKey() || attr.isForeignKey()) { + skip = true; + break; + } + } + } + + if (skip) { + continue; + } + } + + filtered.add(ent); + } + + entities = filtered; + } + } + + private void dropSchema(DataNode node, DataMap map) throws Exception { + + List<DbEntity> list = dbEntitiesInInsertOrder(node, map); + + try (Connection conn = dataSourceFactory.getSharedDataSource().getConnection();) { + + DatabaseMetaData md = conn.getMetaData(); + List<String> allTables = new ArrayList<String>(); + + try (ResultSet tables = md.getTables(null, null, "%", null)) { + while (tables.next()) { + // 'toUpperCase' is needed since most databases + // are case insensitive, and some will convert names to + // lower + // case + // (PostgreSQL) + String name = tables.getString("TABLE_NAME"); + if (name != null) + allTables.add(name.toUpperCase()); + } + } + + unitDbAdapter.willDropTables(conn, map, allTables); + + // drop all tables in the map + try (Statement stmt = conn.createStatement();) { + + ListIterator<DbEntity> it = list.listIterator(list.size()); + while (it.hasPrevious()) { + DbEntity ent = it.previous(); + if (!allTables.contains(ent.getName().toUpperCase())) { + continue; + } + + for (String dropSql : node.getAdapter().dropTableStatements(ent)) { + try { + logger.info(dropSql); + stmt.execute(dropSql); + } catch (SQLException sqe) { + logger.warn("Can't drop table " + ent.getName() + ", ignoring...", sqe); + } + } + } + } + + unitDbAdapter.droppedTables(conn, map); + } + } + + private void dropPKSupport(DataNode node, DataMap map) throws Exception { + List<DbEntity> filteredEntities = dbEntitiesInInsertOrder(node, map); + node.getAdapter().getPkGenerator().dropAutoPk(node, filteredEntities); + } + + private void createPKSupport(DataNode node, DataMap map) throws Exception { + List<DbEntity> filteredEntities = dbEntitiesInInsertOrder(node, map); + node.getAdapter().getPkGenerator().createAutoPk(node, filteredEntities); + } + + private void createSchema(DataNode node, DataMap map) throws Exception { + + try (Connection conn = dataSourceFactory.getSharedDataSource().getConnection();) { + unitDbAdapter.willCreateTables(conn, map); + try (Statement stmt = conn.createStatement();) { + + for (String query : tableCreateQueries(node, map)) { + logger.info(query); + stmt.execute(query); + } + } + unitDbAdapter.createdTables(conn, map); + } + } + + /** + * Returns iterator of preprocessed table create queries. + */ + private Collection<String> tableCreateQueries(DataNode node, DataMap map) throws Exception { + DbAdapter adapter = node.getAdapter(); + DbGenerator gen = new DbGenerator(adapter, map, null, domain, jdbcEventLogger); + + List<DbEntity> orderedEnts = dbEntitiesInInsertOrder(node, map); + List<String> queries = new ArrayList<String>(); + + // table definitions + for (DbEntity ent : orderedEnts) { + queries.add(adapter.createTable(ent)); + } + + // FK constraints + for (DbEntity ent : orderedEnts) { + if (!unitDbAdapter.supportsFKConstraints(ent)) { + continue; + } + + List<String> qs = gen.createConstraintsQueries(ent); + queries.addAll(qs); + } + + return queries; + } } http://git-wip-us.apache.org/repos/asf/cayenne/blob/26d8434d/cayenne-server/src/test/java/org/apache/cayenne/util/UtilTest.java ---------------------------------------------------------------------- diff --git a/cayenne-server/src/test/java/org/apache/cayenne/util/UtilTest.java b/cayenne-server/src/test/java/org/apache/cayenne/util/UtilTest.java index 40e3d4b..2db6987 100644 --- a/cayenne-server/src/test/java/org/apache/cayenne/util/UtilTest.java +++ b/cayenne-server/src/test/java/org/apache/cayenne/util/UtilTest.java @@ -37,278 +37,262 @@ import static org.junit.Assert.fail; public class UtilTest { - private File fTmpFileInCurrentDir; - private String fTmpFileName; - private File fTmpFileCopy; - - @Before - public void setUp() throws Exception { - fTmpFileName = "." + File.separator + System.currentTimeMillis() + ".tmp"; - - fTmpFileInCurrentDir = new File(fTmpFileName); - - // right some garbage to the temp file, so that it is not empty - FileWriter fout = new FileWriter(fTmpFileInCurrentDir); - fout.write("This is total garbage.."); - fout.close(); - - fTmpFileCopy = new File(fTmpFileName + ".copy"); - } - - @After - public void tearDown() throws Exception { - if (!fTmpFileInCurrentDir.delete()) - throw new Exception("Error deleting temporary file: " + fTmpFileInCurrentDir); - - if (fTmpFileCopy.exists() && !fTmpFileCopy.delete()) - throw new Exception("Error deleting temporary file: " + fTmpFileCopy); - - } - - @Test - public void testGetJavaClass() throws Exception { - assertEquals(byte.class.getName(), Util.getJavaClass("byte").getName()); - assertEquals(byte[].class.getName(), Util.getJavaClass("byte[]").getName()); - assertEquals(String[].class.getName(), Util - .getJavaClass("java.lang.String[]") - .getName()); - assertEquals( - new UtilTest[0].getClass().getName(), - Util.getJavaClass(getClass().getName() + "[]").getName()); - } - - @Test - public void testToMap() { - Object[] keys = new Object[] { - "a", "b" - }; - Object[] values = new Object[] { - "1", "2" - }; - - Map<Object, Object> map = Util.toMap(keys, values); - assertEquals(2, map.size()); - assertEquals("1", map.get("a")); - assertEquals("2", map.get("b")); - - // check that map is mutable - map.put("c", "3"); - - // check that two null maps work - Map<Object, Object> emptyMap = Util.toMap(null, new Object[0]); - assertTrue(emptyMap.isEmpty()); - emptyMap.put("key1", "value1"); - - // check arrays with different sizes - Object[] values2 = new Object[] { - "1" - }; - try { - Util.toMap(keys, values2); - fail("must have thrown"); - } - catch (IllegalArgumentException e) { - // expected - } - } - - @Test - public void testStripLineBreaks() { - - // no breaks - assertEquals( - "PnMusdkams34 H AnYtk M", - Util.stripLineBreaks("PnMusdkams34 H AnYtk M", 'A')); - - // Windows - assertEquals( - "TyusdsdsdQaAbAc", - Util.stripLineBreaks("TyusdsdsdQa\r\nb\r\nc", 'A')); - - // Mac - assertEquals("aBbBc", Util.stripLineBreaks("a\rb\rc", 'B')); - - // UNIX - assertEquals("aCbCc", Util.stripLineBreaks("a\nb\nc", 'C')); - } - - @Test - public void testCloneViaSerialization() throws Exception { - // need a special subclass of Object to make "clone" method public - MockSerializable o1 = new MockSerializable(); - Object o2 = Util.cloneViaSerialization(o1); - assertEquals(o1, o2); - assertTrue(o1 != o2); - } - - @Test - public void testPackagePath1() throws Exception { - String expectedPath = "org/apache/cayenne/util"; - assertEquals(expectedPath, Util.getPackagePath(UtilTest.class.getName())); - } - - @Test - public void testPackagePath2() throws Exception { - // inner class - class TmpTest extends Object { - } - - String expectedPath = "org/apache/cayenne/util"; - assertEquals(expectedPath, Util.getPackagePath(TmpTest.class.getName())); - } - - @Test - public void testPackagePath3() throws Exception { - assertEquals("", Util.getPackagePath("ClassWithNoPackage")); - } - - @Test - public void testIsEmptyString1() throws Exception { - assertTrue(Util.isEmptyString("")); - } - - @Test - public void testIsEmptyString2() throws Exception { - assertFalse(Util.isEmptyString(" ")); - } - - @Test - public void testIsEmptyString3() throws Exception { - assertTrue(Util.isEmptyString(null)); - } - - @Test - public void testBackslashFix() throws Exception { - String strBefore = "abcd\\12345\\"; - String strAfter = "abcd/12345/"; - assertEquals(strAfter, Util.substBackslashes(strBefore)); - } - - @Test - public void testNullSafeEquals() throws Exception { - // need a special subclass of Object to make "clone" method public - class CloneableObject implements Cloneable { - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - - // for the purpose of this test - // all objects of this class considered equal - // (since they carry no state) - return obj.getClass() == this.getClass(); - } - } - - CloneableObject o1 = new CloneableObject(); - Object o2 = new Object(); - Object o3 = o1.clone(); - - assertTrue(o3.equals(o1)); - assertTrue(Util.nullSafeEquals(o1, o1)); - assertFalse(Util.nullSafeEquals(o1, o2)); - assertTrue(Util.nullSafeEquals(o1, o3)); - assertFalse(Util.nullSafeEquals(o1, null)); - assertFalse(Util.nullSafeEquals(null, o1)); - assertTrue(Util.nullSafeEquals(null, null)); - } - - @Test - public void testExtractFileExtension1() throws Exception { - String fullName = "n.ext"; - assertEquals("ext", Util.extractFileExtension(fullName)); - } - - @Test - public void testExtractFileExtension2() throws Exception { - String fullName = "n"; - assertNull(Util.extractFileExtension(fullName)); - } - - @Test - public void testExtractFileExtension3() throws Exception { - String fullName = ".ext"; - assertNull(Util.extractFileExtension(fullName)); - } - - @Test - public void testStripFileExtension1() throws Exception { - String fullName = "n.ext"; - assertEquals("n", Util.stripFileExtension(fullName)); - } - - @Test - public void testStripFileExtension2() throws Exception { - String fullName = "n"; - assertEquals("n", Util.stripFileExtension(fullName)); - } - - @Test - public void testStripFileExtension3() throws Exception { - String fullName = ".ext"; - assertEquals(".ext", Util.stripFileExtension(fullName)); - } - - @Test - public void testEncodeXmlAttribute1() throws Exception { - String unencoded = "normalstring"; - assertEquals(unencoded, Util.encodeXmlAttribute(unencoded)); - } - - @Test - public void testEncodeXmlAttribute2() throws Exception { - String unencoded = "<a>"; - assertEquals("<a>", Util.encodeXmlAttribute(unencoded)); - } - - @Test - public void testEncodeXmlAttribute3() throws Exception { - String unencoded = "a&b"; - assertEquals("a&b", Util.encodeXmlAttribute(unencoded)); - } - - @Test - public void testUnwindException1() throws Exception { - Throwable e = new Throwable(); - assertSame(e, Util.unwindException(e)); - } - - @Test - public void testUnwindException2() throws Exception { - CayenneException e = new CayenneException(); - assertSame(e, Util.unwindException(e)); - } - - @Test - public void testUnwindException3() throws Exception { - Throwable root = new Throwable(); - CayenneException e = new CayenneException(root); - assertSame(root, Util.unwindException(e)); - } - - @Test - public void testPrettyTrim1() throws Exception { - // size is too short, must throw - try { - Util.prettyTrim("abc", 4); - } - catch (IllegalArgumentException ex) { - // expected - } - } - - @Test - public void testPrettyTrim2() throws Exception { - assertEquals("123", Util.prettyTrim("123", 6)); - assertEquals("123456", Util.prettyTrim("123456", 6)); - assertEquals("1...67", Util.prettyTrim("1234567", 6)); - assertEquals("1...78", Util.prettyTrim("12345678", 6)); - } + private File fTmpFileInCurrentDir; + private String fTmpFileName; + private File fTmpFileCopy; + + @Before + public void setUp() throws Exception { + fTmpFileName = "." + File.separator + System.currentTimeMillis() + ".tmp"; + + fTmpFileInCurrentDir = new File(fTmpFileName); + + // right some garbage to the temp file, so that it is not empty + try (FileWriter fout = new FileWriter(fTmpFileInCurrentDir)) { + fout.write("This is total garbage.."); + } + + fTmpFileCopy = new File(fTmpFileName + ".copy"); + } + + @After + public void tearDown() throws Exception { + if (!fTmpFileInCurrentDir.delete()) + throw new Exception("Error deleting temporary file: " + fTmpFileInCurrentDir); + + if (fTmpFileCopy.exists() && !fTmpFileCopy.delete()) + throw new Exception("Error deleting temporary file: " + fTmpFileCopy); + + } + + @Test + public void testGetJavaClass() throws Exception { + assertEquals(byte.class.getName(), Util.getJavaClass("byte").getName()); + assertEquals(byte[].class.getName(), Util.getJavaClass("byte[]").getName()); + assertEquals(String[].class.getName(), Util.getJavaClass("java.lang.String[]").getName()); + assertEquals(new UtilTest[0].getClass().getName(), Util.getJavaClass(getClass().getName() + "[]").getName()); + } + + @Test + public void testToMap() { + Object[] keys = new Object[] { "a", "b" }; + Object[] values = new Object[] { "1", "2" }; + + Map<Object, Object> map = Util.toMap(keys, values); + assertEquals(2, map.size()); + assertEquals("1", map.get("a")); + assertEquals("2", map.get("b")); + + // check that map is mutable + map.put("c", "3"); + + // check that two null maps work + Map<Object, Object> emptyMap = Util.toMap(null, new Object[0]); + assertTrue(emptyMap.isEmpty()); + emptyMap.put("key1", "value1"); + + // check arrays with different sizes + Object[] values2 = new Object[] { "1" }; + try { + Util.toMap(keys, values2); + fail("must have thrown"); + } catch (IllegalArgumentException e) { + // expected + } + } + + @Test + public void testStripLineBreaks() { + + // no breaks + assertEquals("PnMusdkams34 H AnYtk M", Util.stripLineBreaks("PnMusdkams34 H AnYtk M", 'A')); + + // Windows + assertEquals("TyusdsdsdQaAbAc", Util.stripLineBreaks("TyusdsdsdQa\r\nb\r\nc", 'A')); + + // Mac + assertEquals("aBbBc", Util.stripLineBreaks("a\rb\rc", 'B')); + + // UNIX + assertEquals("aCbCc", Util.stripLineBreaks("a\nb\nc", 'C')); + } + + @Test + public void testCloneViaSerialization() throws Exception { + // need a special subclass of Object to make "clone" method public + MockSerializable o1 = new MockSerializable(); + Object o2 = Util.cloneViaSerialization(o1); + assertEquals(o1, o2); + assertTrue(o1 != o2); + } + + @Test + public void testPackagePath1() throws Exception { + String expectedPath = "org/apache/cayenne/util"; + assertEquals(expectedPath, Util.getPackagePath(UtilTest.class.getName())); + } + + @Test + public void testPackagePath2() throws Exception { + // inner class + class TmpTest extends Object { + } + + String expectedPath = "org/apache/cayenne/util"; + assertEquals(expectedPath, Util.getPackagePath(TmpTest.class.getName())); + } + + @Test + public void testPackagePath3() throws Exception { + assertEquals("", Util.getPackagePath("ClassWithNoPackage")); + } + + @Test + public void testIsEmptyString1() throws Exception { + assertTrue(Util.isEmptyString("")); + } + + @Test + public void testIsEmptyString2() throws Exception { + assertFalse(Util.isEmptyString(" ")); + } + + @Test + public void testIsEmptyString3() throws Exception { + assertTrue(Util.isEmptyString(null)); + } + + @Test + public void testBackslashFix() throws Exception { + String strBefore = "abcd\\12345\\"; + String strAfter = "abcd/12345/"; + assertEquals(strAfter, Util.substBackslashes(strBefore)); + } + + @Test + public void testNullSafeEquals() throws Exception { + // need a special subclass of Object to make "clone" method public + class CloneableObject implements Cloneable { + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + + // for the purpose of this test + // all objects of this class considered equal + // (since they carry no state) + return obj.getClass() == this.getClass(); + } + } + + CloneableObject o1 = new CloneableObject(); + Object o2 = new Object(); + Object o3 = o1.clone(); + + assertTrue(o3.equals(o1)); + assertTrue(Util.nullSafeEquals(o1, o1)); + assertFalse(Util.nullSafeEquals(o1, o2)); + assertTrue(Util.nullSafeEquals(o1, o3)); + assertFalse(Util.nullSafeEquals(o1, null)); + assertFalse(Util.nullSafeEquals(null, o1)); + assertTrue(Util.nullSafeEquals(null, null)); + } + + @Test + public void testExtractFileExtension1() throws Exception { + String fullName = "n.ext"; + assertEquals("ext", Util.extractFileExtension(fullName)); + } + + @Test + public void testExtractFileExtension2() throws Exception { + String fullName = "n"; + assertNull(Util.extractFileExtension(fullName)); + } + + @Test + public void testExtractFileExtension3() throws Exception { + String fullName = ".ext"; + assertNull(Util.extractFileExtension(fullName)); + } + + @Test + public void testStripFileExtension1() throws Exception { + String fullName = "n.ext"; + assertEquals("n", Util.stripFileExtension(fullName)); + } + + @Test + public void testStripFileExtension2() throws Exception { + String fullName = "n"; + assertEquals("n", Util.stripFileExtension(fullName)); + } + + @Test + public void testStripFileExtension3() throws Exception { + String fullName = ".ext"; + assertEquals(".ext", Util.stripFileExtension(fullName)); + } + + @Test + public void testEncodeXmlAttribute1() throws Exception { + String unencoded = "normalstring"; + assertEquals(unencoded, Util.encodeXmlAttribute(unencoded)); + } + + @Test + public void testEncodeXmlAttribute2() throws Exception { + String unencoded = "<a>"; + assertEquals("<a>", Util.encodeXmlAttribute(unencoded)); + } + + @Test + public void testEncodeXmlAttribute3() throws Exception { + String unencoded = "a&b"; + assertEquals("a&b", Util.encodeXmlAttribute(unencoded)); + } + + @Test + public void testUnwindException1() throws Exception { + Throwable e = new Throwable(); + assertSame(e, Util.unwindException(e)); + } + + @Test + public void testUnwindException2() throws Exception { + CayenneException e = new CayenneException(); + assertSame(e, Util.unwindException(e)); + } + + @Test + public void testUnwindException3() throws Exception { + Throwable root = new Throwable(); + CayenneException e = new CayenneException(root); + assertSame(root, Util.unwindException(e)); + } + + @Test + public void testPrettyTrim1() throws Exception { + // size is too short, must throw + try { + Util.prettyTrim("abc", 4); + } catch (IllegalArgumentException ex) { + // expected + } + } + + @Test + public void testPrettyTrim2() throws Exception { + assertEquals("123", Util.prettyTrim("123", 6)); + assertEquals("123456", Util.prettyTrim("123456", 6)); + assertEquals("1...67", Util.prettyTrim("1234567", 6)); + assertEquals("1...78", Util.prettyTrim("12345678", 6)); + } }
