You can subscribe to this list here.
2006 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(49) |
Sep
(134) |
Oct
(33) |
Nov
(18) |
Dec
(51) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2007 |
Jan
(50) |
Feb
(32) |
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(3) |
Dec
|
2008 |
Jan
|
Feb
|
Mar
(9) |
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2009 |
Jan
(1) |
Feb
(4) |
Mar
(8) |
Apr
(4) |
May
|
Jun
|
Jul
|
Aug
(2) |
Sep
(1) |
Oct
|
Nov
|
Dec
|
2010 |
Jan
(1) |
Feb
|
Mar
(54) |
Apr
(21) |
May
(13) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(9) |
Dec
|
2011 |
Jan
|
Feb
|
Mar
|
Apr
(1) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2012 |
Jan
|
Feb
|
Mar
|
Apr
(1) |
May
|
Jun
|
Jul
|
Aug
(13) |
Sep
|
Oct
|
Nov
|
Dec
|
From: <ma...@us...> - 2012-08-27 14:15:56
|
Revision: 396 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=396&view=rev Author: marchy Date: 2012-08-27 14:15:44 +0000 (Mon, 27 Aug 2012) Log Message: ----------- Improve the error messages Modified Paths: -------------- trunk/utils-excel/src/main/java/net/objectlab/kit/util/excel/Excel.java Modified: trunk/utils-excel/src/main/java/net/objectlab/kit/util/excel/Excel.java =================================================================== --- trunk/utils-excel/src/main/java/net/objectlab/kit/util/excel/Excel.java 2012-08-27 13:05:31 UTC (rev 395) +++ trunk/utils-excel/src/main/java/net/objectlab/kit/util/excel/Excel.java 2012-08-27 14:15:44 UTC (rev 396) @@ -19,6 +19,10 @@ private void init(InputStream inputStream) throws RuntimeException { + if (inputStream == null) { + throw new NullPointerException("inputStream cannot be null"); + } + try { workbook = WorkbookFactory.create(inputStream); } catch (Exception e) { @@ -62,13 +66,17 @@ * @param range either the range of the entire block to be read, or just the * top row of the cells, in which case the method will stop when * the first empty cell is reached in the first column - * @param colTypes An array of data types expected at each column. + * @param columnTypes An array of data types expected at each column. * If this array is shorter than the number of column, then the last * data type is used until the end. So if only one value is given, * then that is used for the entire block. */ - public Object[][] readBlock(String range, Class... colTypes) { + public Object[][] readBlock(String range, Class... columnTypes) { + if (columnTypes == null || columnTypes.length == 0) { + throw new RuntimeException("columnTypes cannot be null / empty"); + } + CellRangeAddress cra = CellRangeAddress.valueOf(range); AreaReference ar = new AreaReference(range); Sheet sheet = workbook.getSheet(ar.getFirstCell().getSheetName()); @@ -93,10 +101,10 @@ for (int colNum = 0; colNum < width; colNum++) { Class colType; - if (colNum < colTypes.length - 1) { - colType = colTypes[colNum]; + if (colNum < columnTypes.length - 1) { + colType = columnTypes[colNum]; } else { - colType = colTypes[colTypes.length - 1]; + colType = columnTypes[columnTypes.length - 1]; } Cell cell = row.getCell(firstColumn + colNum); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-27 13:05:41
|
Revision: 395 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=395&view=rev Author: marchy Date: 2012-08-27 13:05:31 +0000 (Mon, 27 Aug 2012) Log Message: ----------- Correct URL, and formatting Modified Paths: -------------- trunk/utils-excel/pom.xml Modified: trunk/utils-excel/pom.xml =================================================================== --- trunk/utils-excel/pom.xml 2012-08-27 12:57:09 UTC (rev 394) +++ trunk/utils-excel/pom.xml 2012-08-27 13:05:31 UTC (rev 395) @@ -14,8 +14,11 @@ </parent> <name>ObjectLab Kit - Excel Utility</name> - <description>A utility which makes reading ranges, columns and cells from Excel files a breeze. Just use an excel style reference like 'SheetName'!A1:E20</description> - <url>http://</url> + <description> + A utility which makes reading ranges, columns and cells from Excel files a breeze. + Just use an excel style reference like 'SheetName'!A1:E20 + </description> + <url>http://objectlabkit.sourceforge.net/</url> <dependencies> <dependency> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-27 12:57:18
|
Revision: 394 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=394&view=rev Author: marchy Date: 2012-08-27 12:57:09 +0000 (Mon, 27 Aug 2012) Log Message: ----------- [maven-release-plugin] prepare for next development iteration Modified Paths: -------------- trunk/utils-excel/pom.xml Modified: trunk/utils-excel/pom.xml =================================================================== --- trunk/utils-excel/pom.xml 2012-08-27 12:56:52 UTC (rev 393) +++ trunk/utils-excel/pom.xml 2012-08-27 12:57:09 UTC (rev 394) @@ -4,7 +4,7 @@ <groupId>net.objectlab.kit</groupId> <artifactId>utils-excel</artifactId> - <version>1.0</version> + <version>1.1-SNAPSHOT</version> <packaging>jar</packaging> <parent> @@ -45,9 +45,9 @@ </build> <scm> - <connection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/tags/utils-excel-1.0</connection> - <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/tags/utils-excel-1.0</developerConnection> - <url>https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/tags/utils-excel-1.0</url> + <connection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</connection> + <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</developerConnection> + <url>https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</url> </scm> <issueManagement> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-27 12:57:03
|
Revision: 393 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=393&view=rev Author: marchy Date: 2012-08-27 12:56:52 +0000 (Mon, 27 Aug 2012) Log Message: ----------- [maven-release-plugin] copy for tag utils-excel-1.0 Added Paths: ----------- tags/utils-excel-1.0/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-27 12:56:15
|
Revision: 392 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=392&view=rev Author: marchy Date: 2012-08-27 12:56:04 +0000 (Mon, 27 Aug 2012) Log Message: ----------- [maven-release-plugin] prepare release utils-excel-1.0 Modified Paths: -------------- trunk/utils-excel/pom.xml Modified: trunk/utils-excel/pom.xml =================================================================== --- trunk/utils-excel/pom.xml 2012-08-27 12:48:17 UTC (rev 391) +++ trunk/utils-excel/pom.xml 2012-08-27 12:56:04 UTC (rev 392) @@ -4,7 +4,7 @@ <groupId>net.objectlab.kit</groupId> <artifactId>utils-excel</artifactId> - <version>1.0-SNAPSHOT</version> + <version>1.0</version> <packaging>jar</packaging> <parent> @@ -45,9 +45,9 @@ </build> <scm> - <connection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</connection> - <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</developerConnection> - <url>https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</url> + <connection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/tags/utils-excel-1.0</connection> + <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/tags/utils-excel-1.0</developerConnection> + <url>https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/tags/utils-excel-1.0</url> </scm> <issueManagement> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-27 12:48:28
|
Revision: 391 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=391&view=rev Author: marchy Date: 2012-08-27 12:48:17 +0000 (Mon, 27 Aug 2012) Log Message: ----------- Filling out missing details for release, and also removing some which are in parent already Modified Paths: -------------- trunk/utils-excel/pom.xml Modified: trunk/utils-excel/pom.xml =================================================================== --- trunk/utils-excel/pom.xml 2012-08-24 12:35:37 UTC (rev 390) +++ trunk/utils-excel/pom.xml 2012-08-27 12:48:17 UTC (rev 391) @@ -3,12 +3,20 @@ <modelVersion>4.0.0</modelVersion> <groupId>net.objectlab.kit</groupId> - <artifactId>objectlab-utils-excel</artifactId> - <version>1.1-SNAPSHOT</version> + <artifactId>utils-excel</artifactId> + <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> - <name>ObjectLab Kit - Excel Utility</name> + <parent> + <groupId>org.sonatype.oss</groupId> + <artifactId>oss-parent</artifactId> + <version>7</version> + </parent> + <name>ObjectLab Kit - Excel Utility</name> + <description>A utility which makes reading ranges, columns and cells from Excel files a breeze. Just use an excel style reference like 'SheetName'!A1:E20</description> + <url>http://</url> + <dependencies> <dependency> <groupId>org.apache.poi</groupId> @@ -37,7 +45,9 @@ </build> <scm> + <connection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</connection> <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</developerConnection> + <url>https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</url> </scm> <issueManagement> @@ -45,17 +55,4 @@ <url>https://sourceforge.net/tracker/?group_id=175139</url> </issueManagement> - <distributionManagement> - <repository> - <id>sonatype-nexus-staging</id> - <name>Sonatype Nexus Staging Repository</name> - <url>http://oss.sonatype.org/service/local/staging/deploy/maven2/</url> - </repository> - <snapshotRepository> - <id>sonatype-nexus-snapshots</id> - <name>Sonatype Nexus Snapshots Repository</name> - <url>http://oss.sonatype.org/content/repositories/snapshots/</url> - </snapshotRepository> - </distributionManagement> - </project> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-24 12:35:43
|
Revision: 390 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=390&view=rev Author: marchy Date: 2012-08-24 12:35:37 +0000 (Fri, 24 Aug 2012) Log Message: ----------- Undo release, need GPG signed jars. Removed Paths: ------------- tags/objectlab-utils-excel-1.0/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-24 11:11:27
|
Revision: 389 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=389&view=rev Author: marchy Date: 2012-08-24 11:11:17 +0000 (Fri, 24 Aug 2012) Log Message: ----------- [maven-release-plugin] prepare for next development iteration Modified Paths: -------------- trunk/utils-excel/pom.xml Modified: trunk/utils-excel/pom.xml =================================================================== --- trunk/utils-excel/pom.xml 2012-08-24 11:11:02 UTC (rev 388) +++ trunk/utils-excel/pom.xml 2012-08-24 11:11:17 UTC (rev 389) @@ -4,7 +4,7 @@ <groupId>net.objectlab.kit</groupId> <artifactId>objectlab-utils-excel</artifactId> - <version>1.0</version> + <version>1.1-SNAPSHOT</version> <packaging>jar</packaging> <name>ObjectLab Kit - Excel Utility</name> @@ -37,7 +37,7 @@ </build> <scm> - <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/tags/objectlab-utils-excel-1.0</developerConnection> + <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</developerConnection> </scm> <issueManagement> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-24 11:11:08
|
Revision: 388 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=388&view=rev Author: marchy Date: 2012-08-24 11:11:02 +0000 (Fri, 24 Aug 2012) Log Message: ----------- [maven-release-plugin] copy for tag objectlab-utils-excel-1.0 Added Paths: ----------- tags/objectlab-utils-excel-1.0/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-24 11:10:19
|
Revision: 387 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=387&view=rev Author: marchy Date: 2012-08-24 11:10:13 +0000 (Fri, 24 Aug 2012) Log Message: ----------- [maven-release-plugin] prepare release objectlab-utils-excel-1.0 Modified Paths: -------------- trunk/utils-excel/pom.xml Modified: trunk/utils-excel/pom.xml =================================================================== --- trunk/utils-excel/pom.xml 2012-08-24 11:09:32 UTC (rev 386) +++ trunk/utils-excel/pom.xml 2012-08-24 11:10:13 UTC (rev 387) @@ -1,62 +1,61 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <groupId>net.objectlab.kit</groupId> - <artifactId>objectlab-utils-excel</artifactId> - <version>1.0-SNAPSHOT</version> - <packaging>jar</packaging> - - <name>ObjectLab Kit - Excel Utility</name> - - <dependencies> - <dependency> - <groupId>org.apache.poi</groupId> - <artifactId>poi-ooxml</artifactId> - <version>3.8</version> - </dependency> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>4.10</version> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.5</source> - <target>1.5</target> - </configuration> - </plugin> - </plugins> - </build> - - <scm> - <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</developerConnection> - </scm> - - <issueManagement> - <system>sourceforge</system> - <url>https://sourceforge.net/tracker/?group_id=175139</url> - </issueManagement> - - <distributionManagement> - <repository> - <id>sonatype-nexus-staging</id> - <name>Sonatype Nexus Staging Repository</name> - <url>http://oss.sonatype.org/service/local/staging/deploy/maven2/</url> - </repository> - <snapshotRepository> - <id>sonatype-nexus-snapshots</id> - <name>Sonatype Nexus Snapshots Repository</name> - <url>http://oss.sonatype.org/content/repositories/snapshots/</url> - </snapshotRepository> - </distributionManagement> - -</project> +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>net.objectlab.kit</groupId> + <artifactId>objectlab-utils-excel</artifactId> + <version>1.0</version> + <packaging>jar</packaging> + + <name>ObjectLab Kit - Excel Utility</name> + + <dependencies> + <dependency> + <groupId>org.apache.poi</groupId> + <artifactId>poi-ooxml</artifactId> + <version>3.8</version> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.10</version> + <scope>test</scope> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <source>1.5</source> + <target>1.5</target> + </configuration> + </plugin> + </plugins> + </build> + + <scm> + <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/tags/objectlab-utils-excel-1.0</developerConnection> + </scm> + + <issueManagement> + <system>sourceforge</system> + <url>https://sourceforge.net/tracker/?group_id=175139</url> + </issueManagement> + + <distributionManagement> + <repository> + <id>sonatype-nexus-staging</id> + <name>Sonatype Nexus Staging Repository</name> + <url>http://oss.sonatype.org/service/local/staging/deploy/maven2/</url> + </repository> + <snapshotRepository> + <id>sonatype-nexus-snapshots</id> + <name>Sonatype Nexus Snapshots Repository</name> + <url>http://oss.sonatype.org/content/repositories/snapshots/</url> + </snapshotRepository> + </distributionManagement> + +</project> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-24 11:09:38
|
Revision: 386 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=386&view=rev Author: marchy Date: 2012-08-24 11:09:32 +0000 (Fri, 24 Aug 2012) Log Message: ----------- some more tweaks to the pom Modified Paths: -------------- trunk/utils-excel/pom.xml Modified: trunk/utils-excel/pom.xml =================================================================== --- trunk/utils-excel/pom.xml 2012-08-24 10:46:17 UTC (rev 385) +++ trunk/utils-excel/pom.xml 2012-08-24 11:09:32 UTC (rev 386) @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> - <groupId>net.objectlab.kit.util</groupId> - <artifactId>excel</artifactId> + <groupId>net.objectlab.kit</groupId> + <artifactId>objectlab-utils-excel</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> @@ -40,5 +40,23 @@ <scm> <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</developerConnection> </scm> + + <issueManagement> + <system>sourceforge</system> + <url>https://sourceforge.net/tracker/?group_id=175139</url> + </issueManagement> + <distributionManagement> + <repository> + <id>sonatype-nexus-staging</id> + <name>Sonatype Nexus Staging Repository</name> + <url>http://oss.sonatype.org/service/local/staging/deploy/maven2/</url> + </repository> + <snapshotRepository> + <id>sonatype-nexus-snapshots</id> + <name>Sonatype Nexus Snapshots Repository</name> + <url>http://oss.sonatype.org/content/repositories/snapshots/</url> + </snapshotRepository> + </distributionManagement> + </project> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-24 10:46:23
|
Revision: 385 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=385&view=rev Author: marchy Date: 2012-08-24 10:46:17 +0000 (Fri, 24 Aug 2012) Log Message: ----------- Add scm url, preparing for release. Modified Paths: -------------- trunk/utils-excel/pom.xml Modified: trunk/utils-excel/pom.xml =================================================================== --- trunk/utils-excel/pom.xml 2012-08-24 10:41:03 UTC (rev 384) +++ trunk/utils-excel/pom.xml 2012-08-24 10:46:17 UTC (rev 385) @@ -36,5 +36,9 @@ </plugin> </plugins> </build> + + <scm> + <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils-excel/</developerConnection> + </scm> </project> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-08-24 10:41:10
|
Revision: 384 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=384&view=rev Author: marchy Date: 2012-08-24 10:41:03 +0000 (Fri, 24 Aug 2012) Log Message: ----------- Excel gets some tests + upgrade to poi 3.8. Upgrading poi library to latest version 3.8. This required some refactors, but it means that it works with xlsx's now too. Adding tests for read* methods... so I think we're ready to release this module. Modified Paths: -------------- trunk/utils-excel/pom.xml trunk/utils-excel/src/main/java/net/objectlab/kit/util/excel/Excel.java Added Paths: ----------- trunk/utils-excel/src/test/ trunk/utils-excel/src/test/java/ trunk/utils-excel/src/test/java/net.objectlab.kit.util.excel/ trunk/utils-excel/src/test/java/net.objectlab.kit.util.excel/ExcelTest.java trunk/utils-excel/src/test/resources/ trunk/utils-excel/src/test/resources/net/ trunk/utils-excel/src/test/resources/net/objectlab/ trunk/utils-excel/src/test/resources/net/objectlab/kit/ trunk/utils-excel/src/test/resources/net/objectlab/kit/util/ trunk/utils-excel/src/test/resources/net/objectlab/kit/util/excel/ trunk/utils-excel/src/test/resources/net/objectlab/kit/util/excel/Test Workbook.xls trunk/utils-excel/src/test/resources/net/objectlab/kit/util/excel/Test Workbook.xlsx Property Changed: ---------------- trunk/utils-excel/ Property changes on: trunk/utils-excel ___________________________________________________________________ Modified: svn:ignore - target + target .idea *.iml Modified: trunk/utils-excel/pom.xml =================================================================== --- trunk/utils-excel/pom.xml 2012-04-25 15:28:20 UTC (rev 383) +++ trunk/utils-excel/pom.xml 2012-08-24 10:41:03 UTC (rev 384) @@ -13,9 +13,15 @@ <dependencies> <dependency> <groupId>org.apache.poi</groupId> - <artifactId>poi</artifactId> - <version>3.2-FINAL</version> + <artifactId>poi-ooxml</artifactId> + <version>3.8</version> </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.10</version> + <scope>test</scope> + </dependency> </dependencies> <build> Modified: trunk/utils-excel/src/main/java/net/objectlab/kit/util/excel/Excel.java =================================================================== --- trunk/utils-excel/src/main/java/net/objectlab/kit/util/excel/Excel.java 2012-04-25 15:28:20 UTC (rev 383) +++ trunk/utils-excel/src/main/java/net/objectlab/kit/util/excel/Excel.java 2012-08-24 10:41:03 UTC (rev 384) @@ -1,114 +1,106 @@ package net.objectlab.kit.util.excel; -import java.io.FileInputStream; -import java.io.FileNotFoundException; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.AreaReference; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellReference; + import java.io.InputStream; import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; +import java.util.*; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.RangeAddress; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - public class Excel { - private HSSFWorkbook workbook; + private Workbook workbook; - private InputStream inputStream; - - public Excel() { - } - public Excel(InputStream in) { - setInputStream(in); - init(); + init(in); } - public void init() throws RuntimeException { + private void init(InputStream inputStream) throws RuntimeException { - POIFSFileSystem fs; try { - fs = new POIFSFileSystem(inputStream); - workbook = new HSSFWorkbook(fs); + workbook = WorkbookFactory.create(inputStream); } catch (Exception e) { throw new RuntimeException(e); } } - public <E> E readValue(String cellAddress, Class<E> type) { + public <E> E readValueAt(String cellAddress, Class<E> type) { + return readCell(cellAt(cellAddress), type); + } - Object[][] result = readBlock(cellAddress, true, type); - return (E) result[0][0]; + public <E> List<E> readColumn(String rangeOrStartAddress, Class<E> type) { + + Object[][] arr = readBlock(rangeOrStartAddress, type); + + List<E> result = new LinkedList<E>(); + for (int i = 0; i < arr.length; i++) { + result.add((E)arr[i][0]); + } + + return result; } + public String namedRangeToRangeAddress(String namedRange) { + int namedCellIndex = getWorkbook().getNameIndex(namedRange); + Name namedCell = getWorkbook().getNameAt(namedCellIndex); + + return namedCell.getRefersToFormula(); + } + + public Cell cellAt(String cellAddr) { + CellReference cr = new CellReference(cellAddr); + + return workbook + .getSheet(cr.getSheetName()) + .getRow(cr.getRow()) + .getCell((int) cr.getCol()); + } + /** - * - * @param range - * either the range of the entire block to be read, or just the - * top row of the cells, in which case the method will stop when - * the first empty cell is reached in the first column - * @param colTypes - * classes of the result types, per column - * @return 2 dimensional array, containing the data read, cast as per - * colTypes + * @param range either the range of the entire block to be read, or just the + * top row of the cells, in which case the method will stop when + * the first empty cell is reached in the first column + * @param colTypes An array of data types expected at each column. + * If this array is shorter than the number of column, then the last + * data type is used until the end. So if only one value is given, + * then that is used for the entire block. */ public Object[][] readBlock(String range, Class... colTypes) { - return readBlock(range, false, colTypes); - } - - private Object[][] readBlock(String range, boolean oneLiner, Class... colTypes) { + CellRangeAddress cra = CellRangeAddress.valueOf(range); + AreaReference ar = new AreaReference(range); + Sheet sheet = workbook.getSheet(ar.getFirstCell().getSheetName()); - RangeAddress ra = new RangeAddress(range); - HSSFSheet sheet = workbook.getSheet(ra.getSheetName()); + int firstColumn = cra.getFirstColumn(); + int firstRow = cra.getFirstRow(); + int lastRow = cra.getLastRow(); + int height = lastRow - firstRow + 1; + int width = cra.getLastColumn() - firstColumn + 1; - oneLiner = (ra.getHeight() == 1 && oneLiner); - List<Object> result; - if (ra.getHeight() == 1) { + if (height == 1) { result = new LinkedList<Object>(); } else { - result = new ArrayList<Object>(ra.getHeight()); + result = new ArrayList<Object>(height); } - int x = ra.getXPosition(ra.getFromCell()); - int y = ra.getYPosition(ra.getFromCell()); - - Class colType = colTypes[0]; - for (int i = 0; (isMoreToRead(sheet, oneLiner, x, y, i)); i++) { - HSSFRow row = sheet.getRow(y + i - 1); - Object[] resultRow = new Object[ra.getWidth()]; + for (int rowNum = 0; moreDataToRead(sheet, firstColumn, firstRow, lastRow, rowNum); rowNum++) { + Row row = sheet.getRow(firstRow + rowNum); + Object[] resultRow = new Object[width]; result.add(resultRow); - for (int j = 0; j < ra.getWidth(); j++) { - HSSFCell cell = row.getCell((short) (x + j - 1)); + for (int colNum = 0; colNum < width; colNum++) { - if (colTypes.length > j) { - colType = colTypes[j]; + Class colType; + if (colNum < colTypes.length - 1) { + colType = colTypes[colNum]; + } else { + colType = colTypes[colTypes.length - 1]; } - if (colType == Date.class) { - resultRow[j] = cell.getDateCellValue(); - } else if (colType == Calendar.class) { - Calendar cal = Calendar.getInstance(); - cal.setTime(cell.getDateCellValue()); - resultRow[j] = cal; - } else if (colType == Integer.class) { - resultRow[j] = ((Double) cell.getNumericCellValue()).intValue(); - } else if (colType == Double.class) { - resultRow[j] = (Double) cell.getNumericCellValue(); - } else if (colType == BigDecimal.class) { - resultRow[j] = new BigDecimal(String.valueOf(cell.getNumericCellValue())); - } else if (colType == String.class) { - resultRow[j] = cell.getRichStringCellValue().getString(); - } + Cell cell = row.getCell(firstColumn + colNum); + resultRow[colNum] = readCell(cell, colType); } } @@ -116,19 +108,42 @@ return result.toArray(new Object[][] {}); } - private boolean isMoreToRead(HSSFSheet sheet, boolean oneLiner, int x, int y, int i) { + private <E> E readCell(Cell cell, Class<E> colType) { - if (oneLiner) { - return (i < 1); + if (colType == Date.class) { + return (E) cell.getDateCellValue(); + } else if (colType == Calendar.class) { + Calendar cal = Calendar.getInstance(); + cal.setTime(cell.getDateCellValue()); + return (E) cal; + } else if (colType == Integer.class) { + return (E) ((Integer) ((Double) cell.getNumericCellValue()).intValue()); + } else if (colType == Double.class) { + return (E) (Double) cell.getNumericCellValue(); + } else if (colType == BigDecimal.class) { + return (E) new BigDecimal(String.valueOf(cell.getNumericCellValue())); + } else if (colType == String.class) { + return (E) cell.getRichStringCellValue().getString(); + } else { + throw new RuntimeException("Column type not supported: " + colType); } - + + } + + private boolean moreDataToRead(Sheet sheet, int firstColumn, int firstRow, int lastRow, int rowNum) { + + int height = lastRow - firstRow + 1; + if (height > 1 && firstRow + rowNum > lastRow) { + return false; + } + // check if the cell is empty - HSSFRow row = sheet.getRow(y + i - 1); + Row row = sheet.getRow(firstRow + rowNum); if (row == null) { return false; } - - HSSFCell cell = row.getCell((short) (x - 1)); + + Cell cell = row.getCell(firstColumn); if (cell == null) { return false; } @@ -136,49 +151,7 @@ return !(str == null || "".equals(str)); } - public <E> List<E> readColumn(String rangeOrStartAddress, Class<E> type) { - - Object[][] arr = readBlock(rangeOrStartAddress, false, type); - - List<E> result = new LinkedList<E>(); - for (int i = 0; i < arr.length; i++) { - result.add((E)arr[i][0]); - } - - return result; - } - - public String namedRangeToRangeAddress(String namedRange) { - int namedCellIndex = getWorkbook().getNameIndex(namedRange); - HSSFName namedCell = getWorkbook().getNameAt(namedCellIndex); - - return namedCell.getReference(); - } - - public HSSFCell getCell(String cellAddr) { - RangeAddress ra = new RangeAddress(cellAddr); - - return workbook.getSheet(ra.getSheetName()).getRow(ra.getYPosition(ra.getFromCell()) - 1).getCell( - (short) (ra.getXPosition(ra.getFromCell()) - 1)); - } - - public HSSFWorkbook getWorkbook() { + public Workbook getWorkbook() { return workbook; } - - public void setWorkbook(HSSFWorkbook workbook) { - this.workbook = workbook; - } - - public void setInputStream(InputStream inputStream) { - this.inputStream = inputStream; - } - - public void setFilename(String filename) { - try { - inputStream = new FileInputStream(filename); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } } Added: trunk/utils-excel/src/test/java/net.objectlab.kit.util.excel/ExcelTest.java =================================================================== --- trunk/utils-excel/src/test/java/net.objectlab.kit.util.excel/ExcelTest.java (rev 0) +++ trunk/utils-excel/src/test/java/net.objectlab.kit.util.excel/ExcelTest.java 2012-08-24 10:41:03 UTC (rev 384) @@ -0,0 +1,100 @@ +package net.objectlab.kit.util.excel; + + +import org.junit.Before; +import org.junit.Test; + +import java.math.BigDecimal; +import java.util.List; + +import static junit.framework.Assert.assertEquals; + +/** + * @author Marcin Jekot + * @since 2012/08/17 + */ +public class ExcelTest { + + private Excel xls; + private Excel xlsx; + + @Before + public void setUp() { + xls = new Excel(getClass().getResourceAsStream("Test Workbook.xls")); + xlsx = new Excel(getClass().getResourceAsStream("Test Workbook.xlsx")); + } + + @Test + public void shouldReadSingleCell() { + // When + String result = xlsx.readValueAt("'Test Sheet'!C3", String.class); + + // Then + assertEquals("TestA", result); + } + + @Test + public void shouldReadColumn() { + // When + List<String> result = xlsx.readColumn("'Test Sheet'!C3", String.class); + + // Then + assertEquals(9, result.size()); + assertEquals("TestA", result.get(0)); + assertEquals("TestI", result.get(8)); + } + + @Test + public void shouldReadTwoLinesAndStop() { + // When + Object[][] result = xlsx.readBlock("'Test Sheet'!C3:F4", String.class, Integer.class); + + // Then + assertEquals("Number of rows read should be 2", 2, result.length); + assertEquals("Number of columns read should be 4", 4, result[0].length); + assertEquals("Number of columns read should be 4", 4, result[1].length); + } + + @Test + public void shouldReadWholeBlockGivenTopLine() { + // When + Object[][] result = xlsx.readBlock("'Test Sheet'!C3:F3", String.class, Integer.class); + + // Then + assertEquals("Number of rows read should be 9", 9, result.length); + assertEquals("Number of columns read should be 4", 4, result[0].length); + assertEquals("Number of columns read should be 4", 4, result[8].length); + } + + @Test + public void shouldReadARangeOfCellsInXls() { + shouldReadARangeOfCells(xls); + } + + @Test + public void shouldReadARangeOfCellsInXlx() { + shouldReadARangeOfCells(xlsx); + } + + private void shouldReadARangeOfCells(Excel xl) { + // When + Object[][] result = xl.readBlock("'Test Sheet'!C3:F12", String.class, Integer.class, Double.class, BigDecimal.class); + + // Then + final int numberOfRows = 9; + assertEquals(numberOfRows, result.length); + + for (int i = 1; i <= numberOfRows; i++) { + + Object[] data = result[i - 1]; + assertEquals("Test" + Character.toString((char) ('A' + i - 1)), data[0]); + assertEquals(i, data[1]); + + final int decimal = i % 10; + assertEquals(i + decimal / (double) 10, data[2]); + assertEquals(new BigDecimal("" + i + "." + decimal + decimal), data[3]); + + assertEquals(4, data.length); + } + } +} Added: trunk/utils-excel/src/test/resources/net/objectlab/kit/util/excel/Test Workbook.xls =================================================================== (Binary files differ) Property changes on: trunk/utils-excel/src/test/resources/net/objectlab/kit/util/excel/Test Workbook.xls ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/utils-excel/src/test/resources/net/objectlab/kit/util/excel/Test Workbook.xlsx =================================================================== (Binary files differ) Property changes on: trunk/utils-excel/src/test/resources/net/objectlab/kit/util/excel/Test Workbook.xlsx ___________________________________________________________________ Added: svn:mime-type + application/octet-stream This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2012-04-25 15:28:31
|
Revision: 383 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=383&view=rev Author: marchy Date: 2012-04-25 15:28:20 +0000 (Wed, 25 Apr 2012) Log Message: ----------- cleanup and prepare for release Modified Paths: -------------- trunk/utils/pom.xml Removed Paths: ------------- trunk/utils/1.0-cs/ Modified: trunk/utils/pom.xml =================================================================== --- trunk/utils/pom.xml 2011-04-14 21:08:02 UTC (rev 382) +++ trunk/utils/pom.xml 2012-04-25 15:28:20 UTC (rev 383) @@ -55,5 +55,30 @@ </plugin> </plugins> </build> + + <scm> + <connection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils</connection> + <developerConnection>scm:svn:https://objectlabkit.svn.sourceforge.net/svnroot/objectlabkit/trunk/utils</developerConnection> + <url>http://objectlabkit.svn.sourceforge.net/viewvc/objectlabkit/</url> + </scm> + <issueManagement> + <system>sourceforge</system> + <url>https://sourceforge.net/tracker/?group_id=175139</url> + </issueManagement> + + <distributionManagement> + <repository> + <id>sonatype-nexus-staging</id> + <name>Sonatype Nexus Staging Repository</name> + <url>http://oss.sonatype.org/service/local/staging/deploy/maven2/</url> + </repository> + <snapshotRepository> + <id>sonatype-nexus-snapshots</id> + <name>Sonatype Nexus Snapshots Repository</name> + <url>http://oss.sonatype.org/content/repositories/snapshots/</url> + </snapshotRepository> + </distributionManagement> + + </project> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <be...@us...> - 2011-04-14 21:08:09
|
Revision: 382 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=382&view=rev Author: benoitx Date: 2011-04-14 21:08:02 +0000 (Thu, 14 Apr 2011) Log Message: ----------- Adding option to ignore zeros Modified Paths: -------------- trunk/utils/src/main/java/net/objectlab/kit/util/WeightedAverage.java Modified: trunk/utils/src/main/java/net/objectlab/kit/util/WeightedAverage.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/util/WeightedAverage.java 2010-11-22 22:19:10 UTC (rev 381) +++ trunk/utils/src/main/java/net/objectlab/kit/util/WeightedAverage.java 2011-04-14 21:08:02 UTC (rev 382) @@ -44,13 +44,22 @@ private final Total total = new Total(); private final Total totalExpanded = new Total(); private int count = 0; + private final boolean includeZeros; + + public WeightedAverage() { + this.includeZeros = true; + } + + public WeightedAverage(final boolean includeZeros) { + this.includeZeros = includeZeros; + } public BigDecimal getTotal() { return total.getTotal(); } public void add(final BigDecimal value, final BigDecimal weightAsAValue) { - if (BigDecimalUtil.isNotZero(value)) { + if (includeZeros || BigDecimalUtil.isNotZero(value)) { count++; total.add(weightAsAValue); totalExpanded.add(BigDecimalUtil.multiply(value, weightAsAValue)); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <be...@us...> - 2010-11-22 22:19:17
|
Revision: 381 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=381&view=rev Author: benoitx Date: 2010-11-22 22:19:10 +0000 (Mon, 22 Nov 2010) Log Message: ----------- a bit of tidy up. Modified Paths: -------------- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollectionBuilder.java Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java 2010-11-21 16:06:31 UTC (rev 380) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java 2010-11-22 22:19:10 UTC (rev 381) @@ -52,7 +52,7 @@ } public void start() { - if (reloadOnExpiry) { + if (reloadOnExpiry && expiryTimeoutMilliseconds > 0) { // start timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollectionBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollectionBuilder.java 2010-11-21 16:06:31 UTC (rev 380) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollectionBuilder.java 2010-11-22 22:19:10 UTC (rev 381) @@ -15,7 +15,7 @@ public class ReadOnlyExpiringCollectionBuilder { private long expiryTimeoutMilliseconds = -1; private boolean reloadOnExpiry = true; - private boolean reloadWhenExpired = true; + private boolean reloadWhenExpired = false; private boolean loadOnFirstAccess = true; private String id; private TimeProvider timeProvider; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <be...@us...> - 2010-11-21 16:06:37
|
Revision: 380 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=380&view=rev Author: benoitx Date: 2010-11-21 16:06:31 +0000 (Sun, 21 Nov 2010) Log Message: ----------- Added a stop method unit tests to use the time provider mechanism. Modified Paths: -------------- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMap.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSet.java trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapTest.java trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSetTest.java Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java 2010-11-21 15:45:38 UTC (rev 379) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java 2010-11-21 16:06:31 UTC (rev 380) @@ -48,7 +48,7 @@ } protected boolean hasExpired() { - return timeProvider.getCurrentTimeMillis() - lastLoadingTime > expiryTimeoutMilliseconds; + return lastLoadingTime == 0 || timeProvider.getCurrentTimeMillis() - lastLoadingTime > expiryTimeoutMilliseconds; } public void start() { Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMap.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMap.java 2010-11-21 15:45:38 UTC (rev 379) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMap.java 2010-11-21 16:06:31 UTC (rev 380) @@ -23,6 +23,7 @@ setReloadOnExpiry(builder.isReloadOnExpiry()); setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); setReloadWhenExpired(builder.isReloadWhenExpired()); + setTimeProvider(builder.getTimeProvider()); start(); } Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSet.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSet.java 2010-11-21 15:45:38 UTC (rev 379) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSet.java 2010-11-21 16:06:31 UTC (rev 380) @@ -23,6 +23,7 @@ setReloadOnExpiry(builder.isReloadOnExpiry()); setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); setReloadWhenExpired(builder.isReloadWhenExpired()); + setTimeProvider(builder.getTimeProvider()); start(); } Modified: trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapTest.java =================================================================== --- trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapTest.java 2010-11-21 15:45:38 UTC (rev 379) +++ trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapTest.java 2010-11-21 16:06:31 UTC (rev 380) @@ -15,13 +15,15 @@ * @author xhensevalb * */ -public class ReadOnlyExpiringHashMapTest implements MapLoader<String, Integer> { +public class ReadOnlyExpiringHashMapTest implements MapLoader<String, Integer>, TimeProvider { private int reloadCount; + private long time; @Before public void reset() { reloadCount = 0; + time = System.currentTimeMillis(); } @Test @@ -31,6 +33,7 @@ builder.loadOnFirstAccess(true); builder.reloadOnExpiry(false); builder.reloadWhenExpired(false); + builder.timeProvider(this); builder.id("Greetings"); final ReadOnlyExpiringMap<String, Integer> ims = new ReadOnlyExpiringHashMap<String, Integer>(builder); @@ -44,11 +47,10 @@ assertTrue("Correct key", ims.containsKey("Hello")); assertNull("diff key", ims.get("Hi")); assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } + + time += 101; // simulate 101 ms + // second call assertFalse(ims.isEmpty()); assertEquals(2, ims.size()); @@ -57,11 +59,9 @@ assertTrue("Correct key", ims.containsKey("Hello")); assertNull("diff key", ims.get("Hi")); assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } + time += 901; // simulate 901 ms + // should be gone assertTrue(ims.isEmpty()); assertEquals(0, ims.size()); @@ -79,6 +79,7 @@ builder.loadOnFirstAccess(true); builder.reloadOnExpiry(false); builder.reloadWhenExpired(true); + builder.timeProvider(this); builder.id("Greetings"); final ReadOnlyExpiringMap<String, Integer> ims = new ReadOnlyExpiringHashMap<String, Integer>(builder); @@ -92,11 +93,9 @@ assertTrue("Correct key", ims.containsKey("Hello")); assertNull("diff key", ims.get("Hi")); assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } + time += 101; // simulate 101 ms + // second call assertFalse(ims.isEmpty()); assertEquals(2, ims.size()); @@ -105,11 +104,9 @@ assertTrue("Correct key", ims.containsKey("Hello")); assertNull("diff key", ims.get("Hi")); assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } + time += 901; // simulate 901 ms + assertEquals("2) Should not call load until called", 1, reloadCount); // should be gone @@ -129,6 +126,7 @@ builder.loadOnFirstAccess(false); builder.reloadOnExpiry(false); builder.reloadWhenExpired(true); + builder.timeProvider(this); builder.id("Greetings"); final ReadOnlyExpiringMap<String, Integer> ims = new ReadOnlyExpiringHashMap<String, Integer>(builder); @@ -142,11 +140,9 @@ assertTrue("Correct key", ims.containsKey("Hello")); assertNull("diff key", ims.get("Hi")); assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } + time += 101; // simulate 101 ms + // second call assertFalse(ims.isEmpty()); assertEquals(2, ims.size()); @@ -155,11 +151,9 @@ assertTrue("Correct key", ims.containsKey("Hello")); assertNull("diff key", ims.get("Hi")); assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } + time += 901; // simulate 901 ms + assertEquals("2) Should not call load until called", 1, reloadCount); // should be gone @@ -179,6 +173,7 @@ builder.loadOnFirstAccess(false); builder.reloadOnExpiry(true); builder.reloadWhenExpired(false); + builder.timeProvider(this); builder.id("Greetings"); final ReadOnlyExpiringMap<String, Integer> ims = new ReadOnlyExpiringHashMap<String, Integer>(builder); @@ -193,6 +188,8 @@ assertNull("diff key", ims.get("Hi")); assertEquals(Integer.valueOf(2), ims.get("Yo")); + time += 101; // simulate 101 ms + // second call assertFalse(ims.isEmpty()); assertEquals(2, ims.size()); @@ -201,8 +198,11 @@ assertTrue("Correct key", ims.containsKey("Hello")); assertNull("diff key", ims.get("Hi")); assertEquals(Integer.valueOf(2), ims.get("Yo")); + + time += 901; // simulate 901 ms + try { - Thread.sleep(901); + Thread.sleep(1001); } catch (final InterruptedException e) { } @@ -225,4 +225,8 @@ reloadCount++; } + public long getCurrentTimeMillis() { + return time; + } + } Modified: trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSetTest.java =================================================================== --- trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSetTest.java 2010-11-21 15:45:38 UTC (rev 379) +++ trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSetTest.java 2010-11-21 16:06:31 UTC (rev 380) @@ -14,13 +14,15 @@ * @author xhensevalb * */ -public class ReadOnlyExpiringHashSetTest implements SetLoader<String> { +public class ReadOnlyExpiringHashSetTest implements SetLoader<String>, TimeProvider { private int reloadCount; + private long time; @Before public void reset() { reloadCount = 0; + time = System.currentTimeMillis(); } @Test @@ -30,10 +32,10 @@ builder.loadOnFirstAccess(true); builder.reloadOnExpiry(false); builder.reloadWhenExpired(false); + builder.timeProvider(this); builder.id("Greetings"); final ReadOnlyExpiringSet<String> ims = new ReadOnlyExpiringHashSet<String>(builder); - assertEquals("Should not call load until called", 0, reloadCount); assertFalse(ims.isEmpty()); @@ -41,22 +43,18 @@ assertEquals(1, reloadCount); assertFalse("diff key", ims.contains("Hi")); assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } + time += 100; // simulate 100 ms + // second call assertFalse(ims.isEmpty()); assertEquals(1, ims.size()); assertEquals(1, reloadCount); assertFalse("diff key", ims.contains("Hi")); assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } + time += 901; + // should be gone assertTrue(ims.isEmpty()); assertEquals(0, ims.size()); @@ -72,6 +70,7 @@ builder.loadOnFirstAccess(true); builder.reloadOnExpiry(false); builder.reloadWhenExpired(true); + builder.timeProvider(this); builder.id("Greetings"); final ReadOnlyExpiringSet<String> ims = new ReadOnlyExpiringHashSet<String>(builder); @@ -83,10 +82,7 @@ assertEquals(1, reloadCount); assertFalse("diff key", ims.contains("Hi")); assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } + time += 100; // simulate 100 ms // second call assertFalse(ims.isEmpty()); @@ -94,10 +90,7 @@ assertEquals(1, reloadCount); assertFalse("diff key", ims.contains("Hi")); assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } + time += 901; // simulate 901 ms assertEquals("Should NOT have reloaded until called!", 1, reloadCount); @@ -116,6 +109,7 @@ builder.loadOnFirstAccess(false); builder.reloadOnExpiry(false); builder.reloadWhenExpired(true); + builder.timeProvider(this); builder.id("Greetings"); final ReadOnlyExpiringSet<String> ims = new ReadOnlyExpiringHashSet<String>(builder); @@ -123,14 +117,12 @@ assertEquals("Should call load immediately", 1, reloadCount); assertFalse(ims.isEmpty()); + assertEquals(1, reloadCount); assertEquals(1, ims.size()); assertEquals(1, reloadCount); assertFalse("diff key", ims.contains("Hi")); assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } + time += 100; // simulate 100 ms // second call assertFalse(ims.isEmpty()); @@ -138,10 +130,7 @@ assertEquals(1, reloadCount); assertFalse("diff key", ims.contains("Hi")); assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } + time += 901; // simulate 901 ms assertEquals("Should NOT have reloaded until called!", 1, reloadCount); @@ -160,6 +149,7 @@ builder.loadOnFirstAccess(false); builder.reloadOnExpiry(true); builder.reloadWhenExpired(false); // but does not matter + builder.timeProvider(this); builder.id("Greetings"); final ReadOnlyExpiringSet<String> ims = new ReadOnlyExpiringHashSet<String>(builder); @@ -171,20 +161,20 @@ assertEquals(1, reloadCount); assertFalse("diff key", ims.contains("Hi")); assertTrue("Correct key", ims.contains("Hello")); - // try { - // Thread.sleep(101); - // } catch (final InterruptedException e) { - // } + time += 101; + // second call assertFalse(ims.isEmpty()); assertEquals(1, ims.size()); assertEquals(1, reloadCount); assertFalse("diff key", ims.contains("Hi")); assertTrue("Correct key", ims.contains("Hello")); + time += 901; // simulate 901 ms + try { - Thread.sleep(901); - } catch (final InterruptedException e) { + Thread.sleep(1000); // ensure that the timer can catch up. + } catch (InterruptedException e) { } assertEquals("Should have reloaded until called!", 2, reloadCount); @@ -202,4 +192,8 @@ builder.add("Hello"); reloadCount++; } + + public long getCurrentTimeMillis() { + return time; + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <be...@us...> - 2010-11-21 15:45:47
|
Revision: 379 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=379&view=rev Author: benoitx Date: 2010-11-21 15:45:38 +0000 (Sun, 21 Nov 2010) Log Message: ----------- Thanks to Tom Folga for the following suggestions: 1) Should be called ReadOnly not Immutable... 2) Externalize the current time 3) some multithreading suggestions. 4) added stop() Modified Paths: -------------- trunk/utils/pom.xml Added Paths: ----------- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollectionBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMap.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSet.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSetBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringMap.java trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringSet.java trunk/utils/src/main/java/net/objectlab/kit/collections/SystemTimeProvider.java trunk/utils/src/main/java/net/objectlab/kit/collections/TimeProvider.java trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapTest.java trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSetTest.java Removed Paths: ------------- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashMapTest.java trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java Modified: trunk/utils/pom.xml =================================================================== --- trunk/utils/pom.xml 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/pom.xml 2010-11-21 15:45:38 UTC (rev 379) @@ -5,7 +5,7 @@ <groupId>net.objectlab.kit</groupId> <artifactId>objectlab-utils</artifactId> - <version>1.0-cs</version> + <version>1.0-SNAPSHOT</version> <packaging>bundle</packaging> <name>ObjectLab Kit - General Utilities</name> Deleted: trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,104 +0,0 @@ -/** - * - */ -package net.objectlab.kit.collections; - -import java.util.Timer; -import java.util.TimerTask; - -/** - * @author xhensevalb - */ -public abstract class AbstractImmutabeExpiringCollection { - private long expiryTimeoutMilliseconds; - private boolean reloadOnExpiry = true; - private boolean reloadWhenExpired = true; - private boolean loadOnFirstAccess = true; - private long lastLoadingTime; - private String id; - private Timer timer; - - protected void setId(final String id) { - this.id = id; - } - - public String getId() { - return id; - } - - protected void setLastLoadingTime(final long lastLoadingTime) { - this.lastLoadingTime = lastLoadingTime; - } - - public void setExpiryTimeoutMilliseconds(final long milliseconds) { - this.expiryTimeoutMilliseconds = milliseconds; - } - - public void setReloadOnExpiry(final boolean reloadOnExpiry) { - this.reloadOnExpiry = reloadOnExpiry; - } - - public void setLoadOnFirstAccess(final boolean loadOnFirstAccess) { - this.loadOnFirstAccess = loadOnFirstAccess; - } - - public void setReloadWhenExpired(final boolean reloadWhenExpired) { - this.reloadWhenExpired = reloadWhenExpired; - } - - protected boolean hasExpired() { - return System.currentTimeMillis() - lastLoadingTime > expiryTimeoutMilliseconds; - } - - public void start() { - if (reloadOnExpiry) { - // start timer - timer = new Timer(); - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - load(); - } - }, 0, expiryTimeoutMilliseconds); - } - if (!loadOnFirstAccess) { - load(); - } - } - - protected void validateOnAccess() { - if (hasExpired()) { - if (reloadWhenExpired || loadOnFirstAccess && lastLoadingTime == 0) { - load(); - } else { - doClear(); - } - } - } - - private void load() { - doLoad(); - lastLoadingTime = System.currentTimeMillis(); - } - - protected abstract void doLoad(); - - protected abstract void doClear(); - - protected long getExpiryTimeoutMilliseconds() { - return expiryTimeoutMilliseconds; - } - - protected boolean isReloadOnExpiry() { - return reloadOnExpiry; - } - - protected boolean isLoadOnFirstAccess() { - return loadOnFirstAccess; - } - - protected long getLastLoadingTime() { - return lastLoadingTime; - } - -} Copied: trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java (from rev 376, trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java) =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractReadOnlyExpiringCollection.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,121 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Timer; +import java.util.TimerTask; + +/** + * @author xhensevalb + */ +public abstract class AbstractReadOnlyExpiringCollection { + private TimeProvider timeProvider; + private long expiryTimeoutMilliseconds; + private boolean reloadOnExpiry = true; + private boolean reloadWhenExpired = true; + private boolean loadOnFirstAccess = true; + private long lastLoadingTime; + private String id; + private Timer timer; + + protected void setId(final String id) { + this.id = id; + } + + protected void setTimeProvider(final TimeProvider timeProvider) { + this.timeProvider = timeProvider != null ? timeProvider : new SystemTimeProvider(); + } + + public String getId() { + return id; + } + + public void setExpiryTimeoutMilliseconds(final long milliseconds) { + this.expiryTimeoutMilliseconds = milliseconds; + } + + public void setReloadOnExpiry(final boolean reloadOnExpiry) { + this.reloadOnExpiry = reloadOnExpiry; + } + + public void setLoadOnFirstAccess(final boolean loadOnFirstAccess) { + this.loadOnFirstAccess = loadOnFirstAccess; + } + + public void setReloadWhenExpired(final boolean reloadWhenExpired) { + this.reloadWhenExpired = reloadWhenExpired; + } + + protected boolean hasExpired() { + return timeProvider.getCurrentTimeMillis() - lastLoadingTime > expiryTimeoutMilliseconds; + } + + public void start() { + if (reloadOnExpiry) { + // start timer + timer = new Timer(); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + load(); + } + }, 0, expiryTimeoutMilliseconds); + } + if (!loadOnFirstAccess) { + load(); + } + } + + public void stop() { + if (timer != null) { + timer.cancel(); + timer.purge(); + timer = null; + } + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + stop(); + } + + protected void validateOnAccess() { + if (hasExpired()) { + if (reloadWhenExpired || loadOnFirstAccess && lastLoadingTime == 0) { + load(); + } else { + doClear(); + } + } + } + + private synchronized void load() { + if (hasExpired()) { + doLoad(); + lastLoadingTime = timeProvider.getCurrentTimeMillis(); + } + } + + protected abstract void doLoad(); + + protected abstract void doClear(); + + protected long getExpiryTimeoutMilliseconds() { + return expiryTimeoutMilliseconds; + } + + protected boolean isReloadOnExpiry() { + return reloadOnExpiry; + } + + protected boolean isLoadOnFirstAccess() { + return loadOnFirstAccess; + } + + protected long getLastLoadingTime() { + return lastLoadingTime; + } + +} Deleted: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,22 +0,0 @@ -/** - * - */ -package net.objectlab.kit.collections; - -/** - * @author xhensevalb - * - */ -public interface ImmutableExpiringCollection { - void setExpiryTimeoutMilliseconds(long milliseconds); - - void setLoadOnFirstAccess(boolean loadOnFirstAccess); - - void setReloadOnExpiry(boolean loadOnExpiry); - - void setReloadWhenExpired(boolean loadWhenExpired); - - void start(); - - void reload(); -} Deleted: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,74 +0,0 @@ -package net.objectlab.kit.collections; - -import net.objectlab.kit.util.PeriodBuilder; - -/** - * Builder for the immutable classes. - * Default: - * - no time out - * - reload on expiry: true - * - load on first access only (ie not at construction time) - * - * @author xhensevalb - * - */ -public class ImmutableExpiringCollectionBuilder { - private long expiryTimeoutMilliseconds = -1; - private boolean reloadOnExpiry = true; - private boolean reloadWhenExpired = true; - private boolean loadOnFirstAccess = true; - private String id; - - public ImmutableExpiringCollectionBuilder id(final String id) { - this.id = id; - return this; - } - - public ImmutableExpiringCollectionBuilder expiryTimeout(final PeriodBuilder expiryTimeout) { - assert expiryTimeout != null; - if (expiryTimeout != null) { - this.expiryTimeoutMilliseconds = expiryTimeout.calculateMilliseconds(); - } - return this; - } - - public ImmutableExpiringCollectionBuilder expiryTimeoutMilliseconds(final long expiryTimeoutMilliseconds) { - this.expiryTimeoutMilliseconds = expiryTimeoutMilliseconds; - return this; - } - - public ImmutableExpiringCollectionBuilder reloadWhenExpired(final boolean reloadWhenExpired) { - this.reloadWhenExpired = reloadWhenExpired; - return this; - } - - public ImmutableExpiringCollectionBuilder reloadOnExpiry(final boolean loadOnExpiry) { - this.reloadOnExpiry = loadOnExpiry; - return this; - } - - public ImmutableExpiringCollectionBuilder loadOnFirstAccess(final boolean loadOnFirstAccess) { - this.loadOnFirstAccess = loadOnFirstAccess; - return this; - } - - final long getExpiryTimeoutMilliseconds() { - return expiryTimeoutMilliseconds; - } - - final boolean isReloadOnExpiry() { - return reloadOnExpiry; - } - - final boolean isReloadWhenExpired() { - return reloadWhenExpired; - } - - final boolean isLoadOnFirstAccess() { - return loadOnFirstAccess; - } - - final String getId() { - return id; - } -} Deleted: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,100 +0,0 @@ -/** - * - */ -package net.objectlab.kit.collections; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * @author xhensevalb - * - */ -public class ImmutableExpiringHashMap<K, V> extends AbstractImmutabeExpiringCollection implements ImmutableExpiringMap<K, V> { - private Map<K, V> delegate = new HashMap<K, V>(); - private final MapLoader<K, V> loader; - - public ImmutableExpiringHashMap(final ImmutableExpiringHashMapBuilder<K, V> builder) { - loader = builder.getLoader(); - setId(builder.getId()); - setExpiryTimeoutMilliseconds(builder.getExpiryTimeoutMilliseconds()); - setReloadOnExpiry(builder.isReloadOnExpiry()); - setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); - setReloadWhenExpired(builder.isReloadWhenExpired()); - start(); - } - - @Override - protected void doLoad() { - final DefaultMapBuilder<K, V> builder = new DefaultMapBuilder<K, V>(getId()); - loader.load(builder); - delegate = builder.build(); - } - - public void clear() { - throw new IllegalAccessError("Collection is immutable"); - } - - public boolean containsKey(final Object key) { - validateOnAccess(); - return delegate.containsKey(key); - } - - public boolean containsValue(final Object value) { - validateOnAccess(); - return delegate.containsValue(value); - } - - public Set<java.util.Map.Entry<K, V>> entrySet() { - validateOnAccess(); - return delegate.entrySet(); - } - - public V get(final Object key) { - validateOnAccess(); - return delegate.get(key); - } - - public boolean isEmpty() { - validateOnAccess(); - return delegate.isEmpty(); - } - - public Set<K> keySet() { - validateOnAccess(); - return delegate.keySet(); - } - - public V put(final K key, final V value) { - throw new IllegalAccessError("Collection is immutable"); - } - - public void putAll(final Map<? extends K, ? extends V> m) { - throw new IllegalAccessError("Collection is immutable"); - } - - public V remove(final Object key) { - throw new IllegalAccessError("Collection is immutable"); - } - - public int size() { - validateOnAccess(); - return delegate.size(); - } - - public Collection<V> values() { - validateOnAccess(); - return delegate.values(); - } - - @Override - protected void doClear() { - delegate.clear(); - } - - public void reload() { - doLoad(); - } -} Deleted: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,14 +0,0 @@ -package net.objectlab.kit.collections; - -public class ImmutableExpiringHashMapBuilder<K, V> extends ImmutableExpiringCollectionBuilder { - private final MapLoader<K, V> loader; - - public ImmutableExpiringHashMapBuilder(final MapLoader<K, V> loader) { - super(); - this.loader = loader; - } - - final MapLoader<K, V> getLoader() { - return loader; - } -} Deleted: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,104 +0,0 @@ -/** - * - */ -package net.objectlab.kit.collections; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -/** - * @author xhensevalb - * - */ -public class ImmutableExpiringHashSet<T> extends AbstractImmutabeExpiringCollection implements ImmutableExpiringSet<T> { - private final SetLoader<T> loader; - private Set<T> delegate = new HashSet<T>(); - - public ImmutableExpiringHashSet(final ImmutableExpiringHashSetBuilder<T> builder) { - this.loader = builder.getLoader(); - setId(builder.getId()); - setExpiryTimeoutMilliseconds(builder.getExpiryTimeoutMilliseconds()); - setReloadOnExpiry(builder.isReloadOnExpiry()); - setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); - setReloadWhenExpired(builder.isReloadWhenExpired()); - start(); - } - - @Override - protected void doLoad() { - final DefaultSetBuilder<T> builder = new DefaultSetBuilder<T>(getId()); - loader.load(builder); - delegate = builder.build(); - } - - public boolean add(final T e) { - validateOnAccess(); - return delegate.add(e); - } - - public boolean addAll(final Collection<? extends T> c) { - throw new IllegalAccessError("Collection is immutable"); - } - - public void clear() { - throw new IllegalAccessError("Collection is immutable"); - } - - public boolean contains(final Object o) { - validateOnAccess(); - return delegate.contains(o); - } - - public boolean containsAll(final Collection<?> c) { - validateOnAccess(); - return delegate.containsAll(c); - } - - public boolean isEmpty() { - validateOnAccess(); - return delegate.isEmpty(); - } - - public Iterator<T> iterator() { - validateOnAccess(); - return delegate.iterator(); - } - - public boolean remove(final Object o) { - throw new IllegalAccessError("Collection is immutable"); - } - - public boolean removeAll(final Collection<?> c) { - throw new IllegalAccessError("Collection is immutable"); - } - - public boolean retainAll(final Collection<?> c) { - throw new IllegalAccessError("Collection is immutable"); - } - - public int size() { - validateOnAccess(); - return delegate.size(); - } - - public Object[] toArray() { - validateOnAccess(); - return delegate.toArray(); - } - - public <T> T[] toArray(final T[] a) { - validateOnAccess(); - return delegate.toArray(a); - } - - @Override - protected void doClear() { - delegate.clear(); - } - - public void reload() { - doLoad(); - } -} Deleted: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,21 +0,0 @@ -package net.objectlab.kit.collections; - -/** - * The builder in charge of providing the parameters for the Set. - * - * @author xhensevalb - * - * @param <T> - */ -public class ImmutableExpiringHashSetBuilder<T> extends ImmutableExpiringCollectionBuilder { - private final SetLoader<T> loader; - - public ImmutableExpiringHashSetBuilder(final SetLoader<T> loader) { - super(); - this.loader = loader; - } - - final SetLoader<T> getLoader() { - return loader; - } -} Deleted: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,13 +0,0 @@ -/** - * - */ -package net.objectlab.kit.collections; - -import java.util.Map; - -/** - * @author xhensevalb - * - */ -public interface ImmutableExpiringMap<K, V> extends ImmutableExpiringCollection, Map<K, V> { -} Deleted: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,13 +0,0 @@ -/** - * - */ -package net.objectlab.kit.collections; - -import java.util.Set; - -/** - * @author xhensevalb - * - */ -public interface ImmutableExpiringSet<T> extends ImmutableExpiringCollection, Set<T> { -} Copied: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollection.java (from rev 377, trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java) =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollection.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollection.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,23 @@ +/** + * + */ +package net.objectlab.kit.collections; + +/** + * @author xhensevalb + * + */ +public interface ReadOnlyExpiringCollection { + // void setExpiryTimeoutMilliseconds(long milliseconds); + + // void setLoadOnFirstAccess(boolean loadOnFirstAccess); + + // void setReloadOnExpiry(boolean loadOnExpiry); + + // void setReloadWhenExpired(boolean loadWhenExpired); + + // void start(); + void stop(); + + void reload(); +} Copied: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollectionBuilder.java (from rev 376, trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java) =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollectionBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringCollectionBuilder.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,84 @@ +package net.objectlab.kit.collections; + +import net.objectlab.kit.util.PeriodBuilder; + +/** + * Builder for the immutable classes. + * Default: + * - no time out + * - reload on expiry: true + * - load on first access only (ie not at construction time) + * + * @author xhensevalb + * + */ +public class ReadOnlyExpiringCollectionBuilder { + private long expiryTimeoutMilliseconds = -1; + private boolean reloadOnExpiry = true; + private boolean reloadWhenExpired = true; + private boolean loadOnFirstAccess = true; + private String id; + private TimeProvider timeProvider; + + public ReadOnlyExpiringCollectionBuilder timeProvider(final TimeProvider timeProvider) { + this.timeProvider = timeProvider; + return this; + } + + public ReadOnlyExpiringCollectionBuilder id(final String id) { + this.id = id; + return this; + } + + public ReadOnlyExpiringCollectionBuilder expiryTimeout(final PeriodBuilder expiryTimeout) { + assert expiryTimeout != null; + if (expiryTimeout != null) { + this.expiryTimeoutMilliseconds = expiryTimeout.calculateMilliseconds(); + } + return this; + } + + public ReadOnlyExpiringCollectionBuilder expiryTimeoutMilliseconds(final long expiryTimeoutMilliseconds) { + this.expiryTimeoutMilliseconds = expiryTimeoutMilliseconds; + return this; + } + + public ReadOnlyExpiringCollectionBuilder reloadWhenExpired(final boolean reloadWhenExpired) { + this.reloadWhenExpired = reloadWhenExpired; + return this; + } + + public ReadOnlyExpiringCollectionBuilder reloadOnExpiry(final boolean loadOnExpiry) { + this.reloadOnExpiry = loadOnExpiry; + return this; + } + + public ReadOnlyExpiringCollectionBuilder loadOnFirstAccess(final boolean loadOnFirstAccess) { + this.loadOnFirstAccess = loadOnFirstAccess; + return this; + } + + final long getExpiryTimeoutMilliseconds() { + return expiryTimeoutMilliseconds; + } + + final boolean isReloadOnExpiry() { + return reloadOnExpiry; + } + + final boolean isReloadWhenExpired() { + return reloadWhenExpired; + } + + final boolean isLoadOnFirstAccess() { + return loadOnFirstAccess; + } + + final String getId() { + return id; + } + + final TimeProvider getTimeProvider() { + return timeProvider; + } +} Copied: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMap.java (from rev 377, trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java) =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMap.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMap.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,100 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * @author xhensevalb + * + */ +public class ReadOnlyExpiringHashMap<K, V> extends AbstractReadOnlyExpiringCollection implements ReadOnlyExpiringMap<K, V> { + private Map<K, V> delegate = new HashMap<K, V>(); + private final MapLoader<K, V> loader; + + public ReadOnlyExpiringHashMap(final ReadOnlyExpiringHashMapBuilder<K, V> builder) { + loader = builder.getLoader(); + setId(builder.getId()); + setExpiryTimeoutMilliseconds(builder.getExpiryTimeoutMilliseconds()); + setReloadOnExpiry(builder.isReloadOnExpiry()); + setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); + setReloadWhenExpired(builder.isReloadWhenExpired()); + start(); + } + + @Override + protected void doLoad() { + final DefaultMapBuilder<K, V> builder = new DefaultMapBuilder<K, V>(getId()); + loader.load(builder); + delegate = builder.build(); + } + + public void clear() { + throw new UnsupportedOperationException("Collection is immutable"); + } + + public boolean containsKey(final Object key) { + validateOnAccess(); + return delegate.containsKey(key); + } + + public boolean containsValue(final Object value) { + validateOnAccess(); + return delegate.containsValue(value); + } + + public Set<java.util.Map.Entry<K, V>> entrySet() { + validateOnAccess(); + return delegate.entrySet(); + } + + public V get(final Object key) { + validateOnAccess(); + return delegate.get(key); + } + + public boolean isEmpty() { + validateOnAccess(); + return delegate.isEmpty(); + } + + public Set<K> keySet() { + validateOnAccess(); + return delegate.keySet(); + } + + public V put(final K key, final V value) { + throw new UnsupportedOperationException("Collection is immutable"); + } + + public void putAll(final Map<? extends K, ? extends V> m) { + throw new UnsupportedOperationException("Collection is immutable"); + } + + public V remove(final Object key) { + throw new UnsupportedOperationException("Collection is immutable"); + } + + public int size() { + validateOnAccess(); + return delegate.size(); + } + + public Collection<V> values() { + validateOnAccess(); + return delegate.values(); + } + + @Override + protected void doClear() { + delegate.clear(); + } + + public void reload() { + doLoad(); + } +} Copied: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapBuilder.java (from rev 375, trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java) =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapBuilder.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,14 @@ +package net.objectlab.kit.collections; + +public class ReadOnlyExpiringHashMapBuilder<K, V> extends ReadOnlyExpiringCollectionBuilder { + private final MapLoader<K, V> loader; + + public ReadOnlyExpiringHashMapBuilder(final MapLoader<K, V> loader) { + super(); + this.loader = loader; + } + + final MapLoader<K, V> getLoader() { + return loader; + } +} Copied: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSet.java (from rev 377, trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java) =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSet.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSet.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,104 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +/** + * @author xhensevalb + * + */ +public class ReadOnlyExpiringHashSet<T> extends AbstractReadOnlyExpiringCollection implements ReadOnlyExpiringSet<T> { + private final SetLoader<T> loader; + private Set<T> delegate = new HashSet<T>(); + + public ReadOnlyExpiringHashSet(final ReadOnlyExpiringHashSetBuilder<T> builder) { + this.loader = builder.getLoader(); + setId(builder.getId()); + setExpiryTimeoutMilliseconds(builder.getExpiryTimeoutMilliseconds()); + setReloadOnExpiry(builder.isReloadOnExpiry()); + setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); + setReloadWhenExpired(builder.isReloadWhenExpired()); + start(); + } + + @Override + protected void doLoad() { + final DefaultSetBuilder<T> builder = new DefaultSetBuilder<T>(getId()); + loader.load(builder); + delegate = builder.build(); + } + + public boolean add(final T e) { + validateOnAccess(); + return delegate.add(e); + } + + public boolean addAll(final Collection<? extends T> c) { + throw new UnsupportedOperationException("Collection is immutable"); + } + + public void clear() { + throw new UnsupportedOperationException("Collection is immutable"); + } + + public boolean contains(final Object o) { + validateOnAccess(); + return delegate.contains(o); + } + + public boolean containsAll(final Collection<?> c) { + validateOnAccess(); + return delegate.containsAll(c); + } + + public boolean isEmpty() { + validateOnAccess(); + return delegate.isEmpty(); + } + + public Iterator<T> iterator() { + validateOnAccess(); + return delegate.iterator(); + } + + public boolean remove(final Object o) { + throw new UnsupportedOperationException("Collection is immutable"); + } + + public boolean removeAll(final Collection<?> c) { + throw new UnsupportedOperationException("Collection is immutable"); + } + + public boolean retainAll(final Collection<?> c) { + throw new UnsupportedOperationException("Collection is immutable"); + } + + public int size() { + validateOnAccess(); + return delegate.size(); + } + + public Object[] toArray() { + validateOnAccess(); + return delegate.toArray(); + } + + public <T> T[] toArray(final T[] a) { + validateOnAccess(); + return delegate.toArray(a); + } + + @Override + protected void doClear() { + delegate.clear(); + } + + public void reload() { + doLoad(); + } +} Copied: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSetBuilder.java (from rev 376, trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java) =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSetBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringHashSetBuilder.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,21 @@ +package net.objectlab.kit.collections; + +/** + * The builder in charge of providing the parameters for the Set. + * + * @author xhensevalb + * + * @param <T> + */ +public class ReadOnlyExpiringHashSetBuilder<T> extends ReadOnlyExpiringCollectionBuilder { + private final SetLoader<T> loader; + + public ReadOnlyExpiringHashSetBuilder(final SetLoader<T> loader) { + super(); + this.loader = loader; + } + + final SetLoader<T> getLoader() { + return loader; + } +} Copied: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringMap.java (from rev 375, trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java) =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringMap.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringMap.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,13 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Map; + +/** + * @author xhensevalb + * + */ +public interface ReadOnlyExpiringMap<K, V> extends ReadOnlyExpiringCollection, Map<K, V> { +} Copied: trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringSet.java (from rev 375, trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java) =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringSet.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ReadOnlyExpiringSet.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,13 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Set; + +/** + * @author xhensevalb + * + */ +public interface ReadOnlyExpiringSet<T> extends ReadOnlyExpiringCollection, Set<T> { +} Added: trunk/utils/src/main/java/net/objectlab/kit/collections/SystemTimeProvider.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/SystemTimeProvider.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/SystemTimeProvider.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,19 @@ +/** + * + */ +package net.objectlab.kit.collections; + +/** + * @author xhensevalb + * + */ +public class SystemTimeProvider implements TimeProvider { + + /* (non-Javadoc) + * @see net.objectlab.kit.collections.TimeProvider#getCurrentMillis() + */ + public long getCurrentTimeMillis() { + return System.currentTimeMillis(); + } + +} Added: trunk/utils/src/main/java/net/objectlab/kit/collections/TimeProvider.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/TimeProvider.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/TimeProvider.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,12 @@ +/** + * + */ +package net.objectlab.kit.collections; + +/** + * @author xhensevalb + * + */ +public interface TimeProvider { + long getCurrentTimeMillis(); +} Deleted: trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashMapTest.java =================================================================== --- trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashMapTest.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashMapTest.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,228 +0,0 @@ -/** - * - */ -package net.objectlab.kit.collections; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; - -/** - * @author xhensevalb - * - */ -public class ImmutableExpiringHashMapTest implements MapLoader<String, Integer> { - - private int reloadCount; - - @Before - public void reset() { - reloadCount = 0; - } - - @Test - public void basicConstructorNoReload() { - final ImmutableExpiringHashMapBuilder<String, Integer> builder = new ImmutableExpiringHashMapBuilder<String, Integer>(this); - builder.expiryTimeoutMilliseconds(1000); - builder.loadOnFirstAccess(true); - builder.reloadOnExpiry(false); - builder.reloadWhenExpired(false); - builder.id("Greetings"); - - final ImmutableExpiringMap<String, Integer> ims = new ImmutableExpiringHashMap<String, Integer>(builder); - - assertEquals("Should not call load until called", 0, reloadCount); - - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } - - // second call - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } - - // should be gone - assertTrue(ims.isEmpty()); - assertEquals(0, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertFalse("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertNull(ims.get("Yo")); - } - - @Test - public void basicConstructorWithReloadWhenCalled() { - final ImmutableExpiringHashMapBuilder<String, Integer> builder = new ImmutableExpiringHashMapBuilder<String, Integer>(this); - builder.expiryTimeoutMilliseconds(1000); - builder.loadOnFirstAccess(true); - builder.reloadOnExpiry(false); - builder.reloadWhenExpired(true); - builder.id("Greetings"); - - final ImmutableExpiringMap<String, Integer> ims = new ImmutableExpiringHashMap<String, Integer>(builder); - - assertEquals("Should not call load until called", 0, reloadCount); - - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } - - // second call - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } - - assertEquals("2) Should not call load until called", 1, reloadCount); - - // should be gone - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(2, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - } - - @Test - public void basicConstructorWithImmediateLoadAndWhenExpired() { - final ImmutableExpiringHashMapBuilder<String, Integer> builder = new ImmutableExpiringHashMapBuilder<String, Integer>(this); - builder.expiryTimeoutMilliseconds(1000); - builder.loadOnFirstAccess(false); - builder.reloadOnExpiry(false); - builder.reloadWhenExpired(true); - builder.id("Greetings"); - - final ImmutableExpiringMap<String, Integer> ims = new ImmutableExpiringHashMap<String, Integer>(builder); - - assertEquals("Should not call load until called", 1, reloadCount); - - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } - - // second call - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } - - assertEquals("2) Should not call load until called", 1, reloadCount); - - // should be gone - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(2, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - } - - @Test - public void basicConstructorWithReloadOnExpiry() { - final ImmutableExpiringHashMapBuilder<String, Integer> builder = new ImmutableExpiringHashMapBuilder<String, Integer>(this); - builder.expiryTimeoutMilliseconds(1000); - builder.loadOnFirstAccess(false); - builder.reloadOnExpiry(true); - builder.reloadWhenExpired(false); - builder.id("Greetings"); - - final ImmutableExpiringMap<String, Integer> ims = new ImmutableExpiringHashMap<String, Integer>(builder); - - assertEquals("Should not call load until called", 1, reloadCount); - - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - - // second call - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } - - assertEquals("2) Should not call load until called", 2, reloadCount); - - // should be gone - assertFalse(ims.isEmpty()); - assertEquals(2, ims.size()); - assertEquals(2, reloadCount); - assertFalse("diff key", ims.containsKey("Hi")); - assertTrue("Correct key", ims.containsKey("Hello")); - assertNull("diff key", ims.get("Hi")); - assertEquals(Integer.valueOf(2), ims.get("Yo")); - } - - public void load(final MapBuilder<String, Integer> builder) { - assertEquals("Greetings", builder.getId()); - builder.put("Hello", 1); - builder.put("Yo", 2); - reloadCount++; - } - -} Deleted: trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java =================================================================== --- trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java 2010-11-21 12:02:45 UTC (rev 378) +++ trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java 2010-11-21 15:45:38 UTC (rev 379) @@ -1,205 +0,0 @@ -/** - * - */ -package net.objectlab.kit.collections; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; - -/** - * @author xhensevalb - * - */ -public class ImmutableExpiringHashSetTest implements SetLoader<String> { - - private int reloadCount; - - @Before - public void reset() { - reloadCount = 0; - } - - @Test - public void basicConstructorNoReload() { - final ImmutableExpiringHashSetBuilder<String> builder = new ImmutableExpiringHashSetBuilder<String>(this); - builder.expiryTimeoutMilliseconds(1000); - builder.loadOnFirstAccess(true); - builder.reloadOnExpiry(false); - builder.reloadWhenExpired(false); - builder.id("Greetings"); - - final ImmutableExpiringSet<String> ims = new ImmutableExpiringHashSet<String>(builder); - - assertEquals("Should not call load until called", 0, reloadCount); - - assertFalse(ims.isEmpty()); - assertEquals(1, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } - - // second call - assertFalse(ims.isEmpty()); - assertEquals(1, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } - - // should be gone - assertTrue(ims.isEmpty()); - assertEquals(0, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.contains("Hi")); - assertFalse("Correct key", ims.contains("Hello")); - } - - @Test - public void basicConstructorWithReloadWhenCalled() { - final ImmutableExpiringHashSetBuilder<String> builder = new ImmutableExpiringHashSetBuilder<String>(this); - builder.expiryTimeoutMilliseconds(1000); - builder.loadOnFirstAccess(true); - builder.reloadOnExpiry(false); - builder.reloadWhenExpired(true); - builder.id("Greetings"); - - final ImmutableExpiringSet<String> ims = new ImmutableExpiringHashSet<String>(builder); - - assertEquals("Should not call load until called", 0, reloadCount); - - assertFalse(ims.isEmpty()); - assertEquals(1, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } - - // second call - assertFalse(ims.isEmpty()); - assertEquals(1, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } - - assertEquals("Should NOT have reloaded until called!", 1, reloadCount); - - // should be gone - assertFalse(ims.isEmpty()); - assertEquals("Now it should have called the reload", 2, reloadCount); - assertEquals(1, ims.size()); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - } - - @Test - public void basicConstructorWithImmediateLoadAndWhenExpired() { - final ImmutableExpiringHashSetBuilder<String> builder = new ImmutableExpiringHashSetBuilder<String>(this); - builder.expiryTimeoutMilliseconds(1000); - builder.loadOnFirstAccess(false); - builder.reloadOnExpiry(false); - builder.reloadWhenExpired(true); - builder.id("Greetings"); - - final ImmutableExpiringSet<String> ims = new ImmutableExpiringHashSet<String>(builder); - - assertEquals("Should call load immediately", 1, reloadCount); - - assertFalse(ims.isEmpty()); - assertEquals(1, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(101); - } catch (final InterruptedException e) { - } - - // second call - assertFalse(ims.isEmpty()); - assertEquals(1, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } - - assertEquals("Should NOT have reloaded until called!", 1, reloadCount); - - // should be gone - assertFalse(ims.isEmpty()); - assertEquals("Now it should have called the reload", 2, reloadCount); - assertEquals(1, ims.size()); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - } - - @Test - public void basicConstructorWithReloadOnExpiry() { - final ImmutableExpiringHashSetBuilder<String> builder = new ImmutableExpiringHashSetBuilder<String>(this); - builder.expiryTimeoutMilliseconds(1000); - builder.loadOnFirstAccess(false); - builder.reloadOnExpiry(true); - builder.reloadWhenExpired(false); // but does not matter - builder.id("Greetings"); - - final ImmutableExpiringSet<String> ims = new ImmutableExpiringHashSet<String>(builder); - - assertEquals("Should have called load immediately", 1, reloadCount); - - assertFalse(ims.isEmpty()); - assertEquals(1, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - // try { - // Thread.sleep(101); - // } catch (final InterruptedException e) { - // } - - // second call - assertFalse(ims.isEmpty()); - assertEquals(1, ims.size()); - assertEquals(1, reloadCount); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - try { - Thread.sleep(901); - } catch (final InterruptedException e) { - } - - assertEquals("Should have reloaded until called!", 2, reloadCount); - - // should be gone - assertFalse(ims.isEmpty()); - assertEquals("Now it should have called the reload", 2, reloadCount); - assertEquals(1, ims.size()); - assertFalse("diff key", ims.contains("Hi")); - assertTrue("Correct key", ims.contains("Hello")); - } - - public void load(final SetBuilder<String> builder) { - assertEquals("Greetings", builder.getId()); - builder.add("Hello"); - reloadCount++; - } -} Copied: trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapTest.java (from rev 376, trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashMapTest.java) =================================================================== --- trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapTest.java (rev 0) +++ trunk/utils/src/test/java/net/objectlab/kit/collections/ReadOnlyExpiringHashMapTest.java 2010-11-21 15:45:38 UTC (rev 379) @@ -0,0 +1,228 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +/** + * @author xhensevalb + * + */ +public class ReadOnlyExpiringHashMapTest implements MapLoader<String, Integer> { + + private int reloadCount; + + @Before + public void reset() { + reloadCount = 0; + } + + @Test + public void basicConstructorNoReload() { + final ReadOnlyExpiringHashMapBuilder<String, Integer> builder = new ReadOnlyExpiringHashMapBuilder<String, Integer>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(true); + builder.reloadOnExpiry(false); + builder.reloadWhenExpired(false); + builder.id("Greetings"); + + final ReadOnlyExpiringMap<String, Integer> ims = new ReadOnlyExpiringHashMap<String, Integer>(builder); + + assertEquals("Should not call load until called", 0, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(101); + } catch (final InterruptedException e) { + } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + // should be gone + assertTrue(ims.isEmpty()); + assertEquals(0, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertFalse("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertNull(ims.get("Yo")); + } + + @Test + public void basicConstructorWithReloadWhenCalled() { + final ReadOnlyExpiringHashMapBuilder<String, Integer> builder = new ReadOnlyExpiringHashMapBuilder<String, Integer>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(true); + builder.reloadOnExpiry(false); + builder.reloadWhenExpired(true); + builder.id("Greetings"); + + final ReadOnlyExpiringMap<String, Integer> ims = new ReadOnlyExpiringHashMap<String, Integer>(builder); + + assertEquals("Should not call load until called", 0, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(101); + } catch (final InterruptedException e) { + } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + assertEquals("2) Should not call load until called", 1, reloadCount); + + // should be gone + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(2, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + } + + @Test + public void basicConstructorWithImmediateLoadAndWhenExpired() { + final ReadOnlyExpiringHashMapBuilder<String, Integer> builder = new ReadOnlyExpiringHashMapBuilder<String, Integer>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(false); + builder.reloadOnExpiry(false); + builder.reloadWhenExpired(true); + builder.id("Greetings"); + + final ReadOnlyExpiringMap<String, Integer> ims = new ReadOnlyExpiringHashMap<String, Integer>(builder); + + assertEquals("Should not call load until called", 1, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(101); + } catch (final InterruptedException e) { + } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assert... [truncated message content] |
From: <be...@us...> - 2010-11-21 12:02:51
|
Revision: 378 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=378&view=rev Author: benoitx Date: 2010-11-21 12:02:45 +0000 (Sun, 21 Nov 2010) Log Message: ----------- typo Modified Paths: -------------- trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java Modified: trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java =================================================================== --- trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java 2010-11-20 23:58:22 UTC (rev 377) +++ trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java 2010-11-21 12:02:45 UTC (rev 378) @@ -202,5 +202,4 @@ builder.add("Hello"); reloadCount++; } - } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <be...@us...> - 2010-11-20 23:58:31
|
Revision: 377 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=377&view=rev Author: benoitx Date: 2010-11-20 23:58:22 +0000 (Sat, 20 Nov 2010) Log Message: ----------- Add methods to force a reload. Modified Paths: -------------- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java 2010-11-20 22:49:07 UTC (rev 376) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java 2010-11-20 23:58:22 UTC (rev 377) @@ -17,4 +17,6 @@ void setReloadWhenExpired(boolean loadWhenExpired); void start(); + + void reload(); } Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java 2010-11-20 22:49:07 UTC (rev 376) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java 2010-11-20 23:58:22 UTC (rev 377) @@ -93,4 +93,8 @@ protected void doClear() { delegate.clear(); } + + public void reload() { + doLoad(); + } } Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java 2010-11-20 22:49:07 UTC (rev 376) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java 2010-11-20 23:58:22 UTC (rev 377) @@ -97,4 +97,8 @@ protected void doClear() { delegate.clear(); } + + public void reload() { + doLoad(); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <be...@us...> - 2010-11-20 22:49:14
|
Revision: 376 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=376&view=rev Author: benoitx Date: 2010-11-20 22:49:07 +0000 (Sat, 20 Nov 2010) Log Message: ----------- Added Unit Test for the immutable collections with timeout... Modified Paths: -------------- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/MapBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/SetBuilder.java Added Paths: ----------- trunk/utils/src/main/java/net/objectlab/kit/collections/DefaultMapBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/DefaultSetBuilder.java trunk/utils/src/main/java/net/objectlab/kit/util/PeriodBuilder.java trunk/utils/src/test/java/net/objectlab/kit/collections/ trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashMapTest.java trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java 2010-11-05 11:41:20 UTC (rev 375) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java 2010-11-20 22:49:07 UTC (rev 376) @@ -8,15 +8,24 @@ /** * @author xhensevalb - * */ public abstract class AbstractImmutabeExpiringCollection { private long expiryTimeoutMilliseconds; - private boolean loadOnExpiry = true; + private boolean reloadOnExpiry = true; + private boolean reloadWhenExpired = true; private boolean loadOnFirstAccess = true; private long lastLoadingTime; + private String id; private Timer timer; + protected void setId(final String id) { + this.id = id; + } + + public String getId() { + return id; + } + protected void setLastLoadingTime(final long lastLoadingTime) { this.lastLoadingTime = lastLoadingTime; } @@ -25,20 +34,24 @@ this.expiryTimeoutMilliseconds = milliseconds; } - public void setLoadOnExpiry(final boolean loadOnExpiry) { - this.loadOnExpiry = loadOnExpiry; + public void setReloadOnExpiry(final boolean reloadOnExpiry) { + this.reloadOnExpiry = reloadOnExpiry; } public void setLoadOnFirstAccess(final boolean loadOnFirstAccess) { this.loadOnFirstAccess = loadOnFirstAccess; } + public void setReloadWhenExpired(final boolean reloadWhenExpired) { + this.reloadWhenExpired = reloadWhenExpired; + } + protected boolean hasExpired() { return System.currentTimeMillis() - lastLoadingTime > expiryTimeoutMilliseconds; } public void start() { - if (loadOnExpiry) { + if (reloadOnExpiry) { // start timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @@ -55,7 +68,11 @@ protected void validateOnAccess() { if (hasExpired()) { - load(); + if (reloadWhenExpired || loadOnFirstAccess && lastLoadingTime == 0) { + load(); + } else { + doClear(); + } } } @@ -66,12 +83,14 @@ protected abstract void doLoad(); + protected abstract void doClear(); + protected long getExpiryTimeoutMilliseconds() { return expiryTimeoutMilliseconds; } - protected boolean isLoadOnExpiry() { - return loadOnExpiry; + protected boolean isReloadOnExpiry() { + return reloadOnExpiry; } protected boolean isLoadOnFirstAccess() { Added: trunk/utils/src/main/java/net/objectlab/kit/collections/DefaultMapBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/DefaultMapBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/DefaultMapBuilder.java 2010-11-20 22:49:07 UTC (rev 376) @@ -0,0 +1,74 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import net.objectlab.kit.util.Pair; + +/** + * Inspired by the Google Collection builder. + * + * @author Benoit Xhenseval + * + */ +public class DefaultMapBuilder<K, V> implements MapBuilder<K, V> { + private final List<Pair<K, V>> entries = new ArrayList<Pair<K, V>>(); + private final String id; + + public DefaultMapBuilder(final String id) { + this.id = id; + } + + public String getId() { + return id; + } + + /** + * Associates {@code key} with {@code value} in the built map. + */ + public DefaultMapBuilder<K, V> put(final K key, final V value) { + entries.add(new Pair<K, V>(key, value)); + return this; + } + + /** + * Associates all of the given map's keys and values in the built map. + * + * @throws NullPointerException if any key or value in {@code map} is null + */ + public DefaultMapBuilder<K, V> putAll(final Map<? extends K, ? extends V> map) { + for (final Entry<? extends K, ? extends V> entry : map.entrySet()) { + put(entry.getKey(), entry.getValue()); + } + return this; + } + + /** + * Returns a newly-created immutable map. + * + * @throws IllegalArgumentException if duplicate keys were added + */ + public Map<K, V> build() { + return fromEntryList(entries); + } + + private static <K, V> Map<K, V> fromEntryList(final List<Pair<K, V>> entries) { + final int size = entries.size(); + switch (size) { + case 0: + return new HashMap<K, V>(); + default: + final Map<K, V> m = new HashMap<K, V>(); + for (final Pair<K, V> entry : entries) { + m.put(entry.getElement1(), entry.getElement2()); + } + return m; + } + } +} Added: trunk/utils/src/main/java/net/objectlab/kit/collections/DefaultSetBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/DefaultSetBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/DefaultSetBuilder.java 2010-11-20 22:49:07 UTC (rev 376) @@ -0,0 +1,38 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +/** + * @author xhensevalb + * + */ +public class DefaultSetBuilder<T> implements SetBuilder<T> { + private final Set<T> set = new HashSet<T>(); + private final String id; + + public DefaultSetBuilder(final String id) { + super(); + this.id = id; + } + + public String getId() { + return id; + } + + public void add(final T t) { + set.add(t); + } + + public void addAll(final Collection<T> t) { + set.addAll(t); + } + + Set<T> build() { + return new HashSet<T>(set); + } +} Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java 2010-11-05 11:41:20 UTC (rev 375) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java 2010-11-20 22:49:07 UTC (rev 376) @@ -12,7 +12,9 @@ void setLoadOnFirstAccess(boolean loadOnFirstAccess); - void setLoadOnExpiry(boolean loadOnExpiry); + void setReloadOnExpiry(boolean loadOnExpiry); + void setReloadWhenExpired(boolean loadWhenExpired); + void start(); } Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java 2010-11-05 11:41:20 UTC (rev 375) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java 2010-11-20 22:49:07 UTC (rev 376) @@ -1,20 +1,52 @@ package net.objectlab.kit.collections; +import net.objectlab.kit.util.PeriodBuilder; + +/** + * Builder for the immutable classes. + * Default: + * - no time out + * - reload on expiry: true + * - load on first access only (ie not at construction time) + * + * @author xhensevalb + * + */ public class ImmutableExpiringCollectionBuilder { - private long expiryTimeoutMilliseconds; - private boolean loadOnExpiry = true; + private long expiryTimeoutMilliseconds = -1; + private boolean reloadOnExpiry = true; + private boolean reloadWhenExpired = true; private boolean loadOnFirstAccess = true; + private String id; - public ImmutableExpiringCollectionBuilder expiryTimeoutMilliseconds(final long expiryTimeourMilliseconds) { - this.expiryTimeoutMilliseconds = expiryTimeourMilliseconds; + public ImmutableExpiringCollectionBuilder id(final String id) { + this.id = id; return this; } - public ImmutableExpiringCollectionBuilder loadOnExpiry(final boolean loadOnExpiry) { - this.loadOnExpiry = loadOnExpiry; + public ImmutableExpiringCollectionBuilder expiryTimeout(final PeriodBuilder expiryTimeout) { + assert expiryTimeout != null; + if (expiryTimeout != null) { + this.expiryTimeoutMilliseconds = expiryTimeout.calculateMilliseconds(); + } return this; } + public ImmutableExpiringCollectionBuilder expiryTimeoutMilliseconds(final long expiryTimeoutMilliseconds) { + this.expiryTimeoutMilliseconds = expiryTimeoutMilliseconds; + return this; + } + + public ImmutableExpiringCollectionBuilder reloadWhenExpired(final boolean reloadWhenExpired) { + this.reloadWhenExpired = reloadWhenExpired; + return this; + } + + public ImmutableExpiringCollectionBuilder reloadOnExpiry(final boolean loadOnExpiry) { + this.reloadOnExpiry = loadOnExpiry; + return this; + } + public ImmutableExpiringCollectionBuilder loadOnFirstAccess(final boolean loadOnFirstAccess) { this.loadOnFirstAccess = loadOnFirstAccess; return this; @@ -24,12 +56,19 @@ return expiryTimeoutMilliseconds; } - final boolean isLoadOnExpiry() { - return loadOnExpiry; + final boolean isReloadOnExpiry() { + return reloadOnExpiry; } + final boolean isReloadWhenExpired() { + return reloadWhenExpired; + } + final boolean isLoadOnFirstAccess() { return loadOnFirstAccess; } + final String getId() { + return id; + } } Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java 2010-11-05 11:41:20 UTC (rev 375) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java 2010-11-20 22:49:07 UTC (rev 376) @@ -18,15 +18,17 @@ public ImmutableExpiringHashMap(final ImmutableExpiringHashMapBuilder<K, V> builder) { loader = builder.getLoader(); + setId(builder.getId()); setExpiryTimeoutMilliseconds(builder.getExpiryTimeoutMilliseconds()); - setLoadOnExpiry(builder.isLoadOnExpiry()); + setReloadOnExpiry(builder.isReloadOnExpiry()); setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); + setReloadWhenExpired(builder.isReloadWhenExpired()); start(); } @Override protected void doLoad() { - final MapBuilder<K, V> builder = new MapBuilder<K, V>(); + final DefaultMapBuilder<K, V> builder = new DefaultMapBuilder<K, V>(getId()); loader.load(builder); delegate = builder.build(); } @@ -86,4 +88,9 @@ validateOnAccess(); return delegate.values(); } + + @Override + protected void doClear() { + delegate.clear(); + } } Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java 2010-11-05 11:41:20 UTC (rev 375) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java 2010-11-20 22:49:07 UTC (rev 376) @@ -18,15 +18,17 @@ public ImmutableExpiringHashSet(final ImmutableExpiringHashSetBuilder<T> builder) { this.loader = builder.getLoader(); + setId(builder.getId()); setExpiryTimeoutMilliseconds(builder.getExpiryTimeoutMilliseconds()); - setLoadOnExpiry(builder.isLoadOnExpiry()); + setReloadOnExpiry(builder.isReloadOnExpiry()); setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); + setReloadWhenExpired(builder.isReloadWhenExpired()); start(); } @Override protected void doLoad() { - final SetBuilder<T> builder = new SetBuilder<T>(); + final DefaultSetBuilder<T> builder = new DefaultSetBuilder<T>(getId()); loader.load(builder); delegate = builder.build(); } @@ -90,4 +92,9 @@ validateOnAccess(); return delegate.toArray(a); } + + @Override + protected void doClear() { + delegate.clear(); + } } Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java 2010-11-05 11:41:20 UTC (rev 375) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java 2010-11-20 22:49:07 UTC (rev 376) @@ -1,5 +1,12 @@ package net.objectlab.kit.collections; +/** + * The builder in charge of providing the parameters for the Set. + * + * @author xhensevalb + * + * @param <T> + */ public class ImmutableExpiringHashSetBuilder<T> extends ImmutableExpiringCollectionBuilder { private final SetLoader<T> loader; Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/MapBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/MapBuilder.java 2010-11-05 11:41:20 UTC (rev 375) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/MapBuilder.java 2010-11-20 22:49:07 UTC (rev 376) @@ -3,66 +3,26 @@ */ package net.objectlab.kit.collections; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; import java.util.Map; -import java.util.Map.Entry; -import net.objectlab.kit.util.Pair; - /** * Inspired by the Google Collection builder. * * @author Benoit Xhenseval * */ -public class MapBuilder<K, V> { - final List<Pair<K, V>> entries = new ArrayList<Pair<K, V>>(); +public interface MapBuilder<K, V> { + String getId(); - public MapBuilder() { - } - /** * Associates {@code key} with {@code value} in the built map. */ - public MapBuilder<K, V> put(final K key, final V value) { - entries.add(new Pair<K, V>(key, value)); - return this; - } + MapBuilder<K, V> put(K key, V value); /** * Associates all of the given map's keys and values in the built map. * * @throws NullPointerException if any key or value in {@code map} is null */ - public MapBuilder<K, V> putAll(final Map<? extends K, ? extends V> map) { - for (final Entry<? extends K, ? extends V> entry : map.entrySet()) { - put(entry.getKey(), entry.getValue()); - } - return this; - } - - /** - * Returns a newly-created immutable map. - * - * @throws IllegalArgumentException if duplicate keys were added - */ - public Map<K, V> build() { - return fromEntryList(entries); - } - - private static <K, V> Map<K, V> fromEntryList(final List<Pair<K, V>> entries) { - final int size = entries.size(); - switch (size) { - case 0: - return new HashMap<K, V>(); - default: - final Map<K, V> m = new HashMap<K, V>(); - for (final Pair<K, V> entry : entries) { - m.put(entry.getElement1(), entry.getElement2()); - } - return m; - } - } -} + MapBuilder<K, V> putAll(Map<? extends K, ? extends V> map); +} \ No newline at end of file Modified: trunk/utils/src/main/java/net/objectlab/kit/collections/SetBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/SetBuilder.java 2010-11-05 11:41:20 UTC (rev 375) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/SetBuilder.java 2010-11-20 22:49:07 UTC (rev 376) @@ -3,21 +3,16 @@ */ package net.objectlab.kit.collections; -import java.util.HashSet; -import java.util.Set; +import java.util.Collection; /** * @author xhensevalb * */ -public class SetBuilder<T> { - private final Set<T> set = new HashSet<T>(); +public interface SetBuilder<T> { + String getId(); - public void add(final T t) { - set.add(t); - } + void add(final T t); - public Set<T> build() { - return new HashSet<T>(set); - } + void addAll(final Collection<T> t); } Added: trunk/utils/src/main/java/net/objectlab/kit/util/PeriodBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/util/PeriodBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/util/PeriodBuilder.java 2010-11-20 22:49:07 UTC (rev 376) @@ -0,0 +1,60 @@ +/** + * + */ +package net.objectlab.kit.util; + +/** + * A simple helper class that is NOT SCIENTIFIC but accurate enough + * for the mere mortals, to calculate the number of milliseconds to + * be used in say a timer but setup in a easier way... + * @author xhensevalb + * + */ +public class PeriodBuilder { + private int weeks = 0; + private int days = 0; + private int hours = 0; + private int minutes = 0; + private int seconds = 0; + private long milliseconds = 0; + + public long calculateMilliseconds() { + return milliseconds // + + seconds * 1000L // + + minutes * 60L * 1000L // + + hours * 60L * 60L * 1000L // + + days * 24L * 60L * 60L * 1000L // + + weeks * 7L * 24L * 60L * 60L * 1000L // + ; + } + + public PeriodBuilder weeks(final int weeks) { + this.weeks = weeks; + return this; + } + + public PeriodBuilder days(final int days) { + this.days = days; + return this; + } + + public PeriodBuilder hours(final int hours) { + this.hours = hours; + return this; + } + + public PeriodBuilder minutes(final int minutes) { + this.minutes = minutes; + return this; + } + + public PeriodBuilder seconds(final int seconds) { + this.seconds = seconds; + return this; + } + + public PeriodBuilder milliseconds(final int milliseconds) { + this.milliseconds = milliseconds; + return this; + } +} Added: trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashMapTest.java =================================================================== --- trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashMapTest.java (rev 0) +++ trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashMapTest.java 2010-11-20 22:49:07 UTC (rev 376) @@ -0,0 +1,228 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +/** + * @author xhensevalb + * + */ +public class ImmutableExpiringHashMapTest implements MapLoader<String, Integer> { + + private int reloadCount; + + @Before + public void reset() { + reloadCount = 0; + } + + @Test + public void basicConstructorNoReload() { + final ImmutableExpiringHashMapBuilder<String, Integer> builder = new ImmutableExpiringHashMapBuilder<String, Integer>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(true); + builder.reloadOnExpiry(false); + builder.reloadWhenExpired(false); + builder.id("Greetings"); + + final ImmutableExpiringMap<String, Integer> ims = new ImmutableExpiringHashMap<String, Integer>(builder); + + assertEquals("Should not call load until called", 0, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(101); + } catch (final InterruptedException e) { + } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + // should be gone + assertTrue(ims.isEmpty()); + assertEquals(0, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertFalse("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertNull(ims.get("Yo")); + } + + @Test + public void basicConstructorWithReloadWhenCalled() { + final ImmutableExpiringHashMapBuilder<String, Integer> builder = new ImmutableExpiringHashMapBuilder<String, Integer>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(true); + builder.reloadOnExpiry(false); + builder.reloadWhenExpired(true); + builder.id("Greetings"); + + final ImmutableExpiringMap<String, Integer> ims = new ImmutableExpiringHashMap<String, Integer>(builder); + + assertEquals("Should not call load until called", 0, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(101); + } catch (final InterruptedException e) { + } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + assertEquals("2) Should not call load until called", 1, reloadCount); + + // should be gone + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(2, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + } + + @Test + public void basicConstructorWithImmediateLoadAndWhenExpired() { + final ImmutableExpiringHashMapBuilder<String, Integer> builder = new ImmutableExpiringHashMapBuilder<String, Integer>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(false); + builder.reloadOnExpiry(false); + builder.reloadWhenExpired(true); + builder.id("Greetings"); + + final ImmutableExpiringMap<String, Integer> ims = new ImmutableExpiringHashMap<String, Integer>(builder); + + assertEquals("Should not call load until called", 1, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(101); + } catch (final InterruptedException e) { + } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + assertEquals("2) Should not call load until called", 1, reloadCount); + + // should be gone + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(2, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + } + + @Test + public void basicConstructorWithReloadOnExpiry() { + final ImmutableExpiringHashMapBuilder<String, Integer> builder = new ImmutableExpiringHashMapBuilder<String, Integer>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(false); + builder.reloadOnExpiry(true); + builder.reloadWhenExpired(false); + builder.id("Greetings"); + + final ImmutableExpiringMap<String, Integer> ims = new ImmutableExpiringHashMap<String, Integer>(builder); + + assertEquals("Should not call load until called", 1, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + + // second call + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + assertEquals("2) Should not call load until called", 2, reloadCount); + + // should be gone + assertFalse(ims.isEmpty()); + assertEquals(2, ims.size()); + assertEquals(2, reloadCount); + assertFalse("diff key", ims.containsKey("Hi")); + assertTrue("Correct key", ims.containsKey("Hello")); + assertNull("diff key", ims.get("Hi")); + assertEquals(Integer.valueOf(2), ims.get("Yo")); + } + + public void load(final MapBuilder<String, Integer> builder) { + assertEquals("Greetings", builder.getId()); + builder.put("Hello", 1); + builder.put("Yo", 2); + reloadCount++; + } + +} Added: trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java =================================================================== --- trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java (rev 0) +++ trunk/utils/src/test/java/net/objectlab/kit/collections/ImmutableExpiringHashSetTest.java 2010-11-20 22:49:07 UTC (rev 376) @@ -0,0 +1,206 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +/** + * @author xhensevalb + * + */ +public class ImmutableExpiringHashSetTest implements SetLoader<String> { + + private int reloadCount; + + @Before + public void reset() { + reloadCount = 0; + } + + @Test + public void basicConstructorNoReload() { + final ImmutableExpiringHashSetBuilder<String> builder = new ImmutableExpiringHashSetBuilder<String>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(true); + builder.reloadOnExpiry(false); + builder.reloadWhenExpired(false); + builder.id("Greetings"); + + final ImmutableExpiringSet<String> ims = new ImmutableExpiringHashSet<String>(builder); + + assertEquals("Should not call load until called", 0, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(1, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + try { + Thread.sleep(101); + } catch (final InterruptedException e) { + } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(1, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + // should be gone + assertTrue(ims.isEmpty()); + assertEquals(0, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.contains("Hi")); + assertFalse("Correct key", ims.contains("Hello")); + } + + @Test + public void basicConstructorWithReloadWhenCalled() { + final ImmutableExpiringHashSetBuilder<String> builder = new ImmutableExpiringHashSetBuilder<String>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(true); + builder.reloadOnExpiry(false); + builder.reloadWhenExpired(true); + builder.id("Greetings"); + + final ImmutableExpiringSet<String> ims = new ImmutableExpiringHashSet<String>(builder); + + assertEquals("Should not call load until called", 0, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(1, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + try { + Thread.sleep(101); + } catch (final InterruptedException e) { + } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(1, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + assertEquals("Should NOT have reloaded until called!", 1, reloadCount); + + // should be gone + assertFalse(ims.isEmpty()); + assertEquals("Now it should have called the reload", 2, reloadCount); + assertEquals(1, ims.size()); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + } + + @Test + public void basicConstructorWithImmediateLoadAndWhenExpired() { + final ImmutableExpiringHashSetBuilder<String> builder = new ImmutableExpiringHashSetBuilder<String>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(false); + builder.reloadOnExpiry(false); + builder.reloadWhenExpired(true); + builder.id("Greetings"); + + final ImmutableExpiringSet<String> ims = new ImmutableExpiringHashSet<String>(builder); + + assertEquals("Should call load immediately", 1, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(1, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + try { + Thread.sleep(101); + } catch (final InterruptedException e) { + } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(1, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + assertEquals("Should NOT have reloaded until called!", 1, reloadCount); + + // should be gone + assertFalse(ims.isEmpty()); + assertEquals("Now it should have called the reload", 2, reloadCount); + assertEquals(1, ims.size()); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + } + + @Test + public void basicConstructorWithReloadOnExpiry() { + final ImmutableExpiringHashSetBuilder<String> builder = new ImmutableExpiringHashSetBuilder<String>(this); + builder.expiryTimeoutMilliseconds(1000); + builder.loadOnFirstAccess(false); + builder.reloadOnExpiry(true); + builder.reloadWhenExpired(false); // but does not matter + builder.id("Greetings"); + + final ImmutableExpiringSet<String> ims = new ImmutableExpiringHashSet<String>(builder); + + assertEquals("Should have called load immediately", 1, reloadCount); + + assertFalse(ims.isEmpty()); + assertEquals(1, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + // try { + // Thread.sleep(101); + // } catch (final InterruptedException e) { + // } + + // second call + assertFalse(ims.isEmpty()); + assertEquals(1, ims.size()); + assertEquals(1, reloadCount); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + try { + Thread.sleep(901); + } catch (final InterruptedException e) { + } + + assertEquals("Should have reloaded until called!", 2, reloadCount); + + // should be gone + assertFalse(ims.isEmpty()); + assertEquals("Now it should have called the reload", 2, reloadCount); + assertEquals(1, ims.size()); + assertFalse("diff key", ims.contains("Hi")); + assertTrue("Correct key", ims.contains("Hello")); + } + + public void load(final SetBuilder<String> builder) { + assertEquals("Greetings", builder.getId()); + builder.add("Hello"); + reloadCount++; + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ma...@us...> - 2010-11-05 11:41:29
|
Revision: 375 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=375&view=rev Author: marchy Date: 2010-11-05 11:41:20 +0000 (Fri, 05 Nov 2010) Log Message: ----------- Removing 1.0-cs directory - was this a version incorrectly tagged?? Removed Paths: ------------- trunk/utils/1.0-cs/pom.xml trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/console/ConsoleMenu.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/console/Repeater.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/Average.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/BooleanUtil.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/CaseTreatment.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/CollectionUtil.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/IntegerUtil.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/ObjectHolder.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/ObjectUtil.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/Pair.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/Quadruplet.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/StringUtil.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/Total.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/Triplet.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/Util.java trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/WeightedAverage.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/AverageTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/BigDecimalAssert.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/BigDecimalUtilTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/BooleanUtilTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/CollectionUtilTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/IntegerUtilTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/ObjectHolderTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/ObjectUtilTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/PairTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/QuadrupletTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/StringUtilTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/TotalTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/TripletTest.java trunk/utils/1.0-cs/src/test/java/net/objectlab/kit/util/WeightedAverageTest.java Deleted: trunk/utils/1.0-cs/pom.xml =================================================================== --- trunk/utils/1.0-cs/pom.xml 2010-11-05 11:38:49 UTC (rev 374) +++ trunk/utils/1.0-cs/pom.xml 2010-11-05 11:41:20 UTC (rev 375) @@ -1,59 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <groupId>net.objectlab.kit</groupId> - <artifactId>objectlab-utils</artifactId> - <version>1.0-cs</version> - <packaging>bundle</packaging> - - <name>ObjectLab Kit - General Utilities</name> - - <dependencies> - <dependency> - <groupId>commons-lang</groupId> - <artifactId>commons-lang</artifactId> - <version>2.4</version> - </dependency> - <dependency> - <groupId>joda-time</groupId> - <artifactId>joda-time</artifactId> - <version>1.6</version> - </dependency> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>4.8.1</version> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.5</source> - <target>1.5</target> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.felix</groupId> - <artifactId>maven-bundle-plugin</artifactId> - <extensions>true</extensions> - <configuration> - <instructions> - <Export-Package>net.objectlab.kit.*;version="${pom.version}"</Export-Package> - <Private-Package /> - <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName> - <Bundle-Version>${pom.version}</Bundle-Version> - <Bundle-RequiredExecutionEnvironment>J2SE-1.5</Bundle-RequiredExecutionEnvironment> - </instructions> - </configuration> - </plugin> - </plugins> - </build> - -</project> Deleted: trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/console/ConsoleMenu.java =================================================================== --- trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/console/ConsoleMenu.java 2010-11-05 11:38:49 UTC (rev 374) +++ trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/console/ConsoleMenu.java 2010-11-05 11:41:20 UTC (rev 375) @@ -1,465 +0,0 @@ -/* - * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. - * - * Based in London, we are world leaders in the design and development - * of bespoke applications for the securities financing markets. - * - * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a> - * ___ _ _ _ _ _ - * / _ \| |__ (_) ___ ___| |_| | __ _| |__ - * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ - * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | - * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ - * |__/ - * - * www.ObjectLab.co.uk - * - * $Id: AbstractDateCalculator.java 309 2010-03-23 21:01:49Z marchy $ - * - * Copyright 2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package net.objectlab.kit.console; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.lang.reflect.Method; -import java.math.BigDecimal; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.apache.commons.lang.StringUtils; -import org.joda.time.LocalDate; - -/** - * @author Benoit Xhenseval - * - */ -public class ConsoleMenu { - private static final int EXIT_CODE = 0; - - private static final int SCREEN_COLUMNS = 110; - - private static final int COL = 10; - - private static final PrintStream OUT = System.out; - - // ~ Instance fields - // ------------------------------------------------------------------------------------------------ - - private final List<String> menu = new ArrayList<String>(); - - private final List<String> methods = new ArrayList<String>(); - - private final List<Boolean> askForRepeat = new ArrayList<Boolean>(); - - private final Repeater target; - - private int screenColumns = SCREEN_COLUMNS; - - // ~ Constructors - // --------------------------------------------------------------------------------------------------- - - /** - * @param containingObject - * the object that will be called back once an option is chosen - * in the menu - */ - public ConsoleMenu(final Repeater containingObject) { - target = containingObject; - } - - // ~ Methods - // -------------------------------------------------------------------------------------------------------- - - /** - * add an entry in the menu, sequentially - * - * @param menuDisplay - * how the entry will be displayed in the menu - * @param methodName - * name of the public method - * @parem askForRepeat call back for repeat - */ - public void addMenuItem(final String menuDisplay, final String methodName, final boolean repeat) { - menu.add(menuDisplay); - methods.add(methodName); - askForRepeat.add(Boolean.valueOf(repeat)); - } - - public void setScreenColumns(final int width) { - screenColumns = width; - } - - /** - * display the menu, the application goes into a loop which provides the - * menu and fires the entries selected. It automatically adds an entry to - * exit. - */ - public void displayMenu() { - while (true) { - ConsoleMenu.println(""); - ConsoleMenu.println("Menu Options"); - - final int size = menu.size(); - - displayMenu(size); - - int opt = -1; - - do { - opt = ConsoleMenu.getInt("Enter your choice:", -1); - } while (((opt <= 0) || (opt > methods.size())) && (opt != EXIT_CODE)); - - if (opt == EXIT_CODE) { - ConsoleMenu.println("Exiting menu"); - try { - final Method meth = target.getClass().getMethod("tearDown", new Class[0]); - if (meth != null) { - meth.invoke(target, new Object[0]); - } - } catch (final Exception e) { - e.printStackTrace(); - } - - return; - } - - // now call the method - final String method = methods.get(opt - 1); - final Boolean repeat = askForRepeat.get(opt - 1); - - try { - final Method meth = target.getClass().getMethod(method, new Class[0]); - if (repeat) { - target.repeat(meth); - } else { - meth.invoke(target, new Object[0]); - } - } catch (final Exception e) { - e.printStackTrace(); - } - } - } - - private void displayMenu(final int size) { - for (int i = 0; i < (size / 2); i++) { - final StringBuffer line = new StringBuffer(); - final String col1 = menu.get(i); - - if ((i + 1) < COL) { - line.append(" "); - } - - final int pos = i + 1; - line.append(" ").append(pos).append(") ").append(col1); - - while (line.length() < (screenColumns / 2)) { - line.append(" "); - } - - if ((i + (size / 2)) < size) { - final String col2 = menu.get(i + (size / 2)); - final int position = i + 1 + (size / 2); - line.append(" ").append(position).append(") ").append(col2); - } - - ConsoleMenu.println(line.toString()); - } - - if (size % 2 != 0) { - final StringBuffer line = new StringBuffer(); - final String col1 = menu.get(size - 1); - - if (size < COL) { - line.append(" "); - } - - line.append(" ").append(size).append(") ").append(col1); - - while (line.length() < (screenColumns / 2)) { - line.append(" "); - } - - line.append(" ").append(EXIT_CODE).append(") ").append("Exit"); - ConsoleMenu.println(line.toString()); - } else { - ConsoleMenu.println(" " + EXIT_CODE + ") Exit"); - } - } - - /** - * Gets an int from the System.in - * - * @param title - * for the command line - * @return int as entered by the user of the console app - */ - public static int getInt(final String title, final int defaultValue) { - int opt = -1; - - do { - try { - final String val = ConsoleMenu.getString(title + " (default:" + defaultValue + ")"); - if (val.length() == 0) { - opt = defaultValue; - } else { - opt = Integer.parseInt(val); - } - } catch (final NumberFormatException e) { - opt = -1; - } - } while (opt == -1); - - return opt; - } - - /** - * Gets a boolean from the System.in - * - * @param title - * for the command line - * @return boolean as selected by the user of the console app - */ - public static boolean getBoolean(final String title, final boolean defaultValue) { - final String val = ConsoleMenu.selectOne(title, new String[] { "Yes", "No" }, new String[] { Boolean.TRUE.toString(), Boolean.FALSE.toString() }, - defaultValue ? 1 : 2); - - return Boolean.valueOf(val); - } - - /** - * Gets an BigDecimal from the System.in - * - * @param title - * for the command line - * @return int as entered by the user of the console app - */ - public static BigDecimal getBigDecimal(final String title, final BigDecimal defaultValue) { - BigDecimal opt = null; - - do { - try { - final String val = ConsoleMenu.getString(title + " (default:" + defaultValue + ")"); - if (val.length() == 0) { - opt = defaultValue; - } else { - opt = new BigDecimal(val); - } - } catch (final NumberFormatException e) { - opt = null; - } - } while (opt == null && defaultValue != null); - - return opt; - } - - public static Date getDate(final String title, final Date defaultValue) { - final SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy"); - final String date = ConsoleMenu.getString(title + "(dd-MM-yyyy" + (defaultValue != null ? ", default:" + fmt.format(defaultValue) : "") + ")"); - try { - if (date == null || date.length() == 0) { - return defaultValue; - } - return fmt.parse(date); - } catch (final ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; - } - - public static LocalDate getYMD(final String title, final LocalDate defaultValue) { - final Date dateStr = ConsoleMenu.getDate(title, (defaultValue != null ? defaultValue.toDateMidnight().toDate() : null)); - if (dateStr != null) { - return new LocalDate(dateStr); - } - return null; - } - - /** - * Gets a String from the System.in - * - * @param msg - * for the command line - * @return String as entered by the user of the console app - */ - public static String getString(final String msg) { - ConsoleMenu.print(msg); - - BufferedReader bufReader = null; - String opt = null; - - try { - bufReader = new BufferedReader(new InputStreamReader(System.in)); - opt = bufReader.readLine(); - } catch (final IOException ex) { - ex.printStackTrace(); - System.exit(1); - } - - return opt; - } - - /** - * Gets a String from the System.in - * - * @param msg - * for the command line - * @return String as entered by the user of the console app - */ - public static String getString(final String msg, final String defaultVal) { - String s = getString(msg + "(default:" + defaultVal + "):"); - if (StringUtils.isBlank(s)) { - s = defaultVal; - } - - return s; - } - - /** - * Generates a menu with a list of options and return the value selected. - * - * @param title - * for the command line - * @param optionNames - * name for each option - * @param optionValues - * value for each option - * @return String as selected by the user of the console app - */ - public static String selectOne(final String title, final String[] optionNames, final String[] optionValues, final int defaultOption) { - if (optionNames.length != optionValues.length) { - throw new IllegalArgumentException("option names and values must have same length"); - } - - ConsoleMenu.println("Please chose " + title + " (default:" + defaultOption + ")"); - - for (int i = 0; i < optionNames.length; i++) { - ConsoleMenu.println(i + 1 + ") " + optionNames[i]); - } - - int choice = 0; - - do { - choice = ConsoleMenu.getInt("Your Choice 1-" + optionNames.length + ": ", defaultOption); - } while ((choice <= 0) || (choice > optionNames.length)); - - return optionValues[choice - 1]; - } - - /** - * @param prompt - * The prompt to display to the user. - * @return The password as entered by the user. - */ - public static String getPassword(final String prompt) { - try { - // password holder - final StringBuffer password = new StringBuffer(); - final PasswordHidingThread maskingthread = new PasswordHidingThread(prompt); - final Thread thread = new Thread(maskingthread); - thread.start(); - - // block until enter is pressed - while (true) { - char c = (char) System.in.read(); - - // assume enter pressed, stop masking - maskingthread.stopMasking(); - - if (c == '\r') { - c = (char) System.in.read(); - - if (c == '\n') { - break; - } - continue; - } else if (c == '\n') { - break; - } else { - // store the password - password.append(c); - } - } - - return password.toString(); - } catch (final IOException e) { - e.printStackTrace(); - } - - return null; - } - - // ~ Inner Classes - // -------------------------------------------------------------------------------------------------- - - /** - * This class attempts to erase characters echoed to the console. - */ - static class PasswordHidingThread extends Thread { - private boolean stop = false; - - private final String prompt; - - /** - * @param prompt - * The prompt displayed to the user - */ - public PasswordHidingThread(final String prompt) { - this.prompt = prompt; - } - - /** - * Begin masking until asked to stop. - */ - @Override - public void run() { - while (!stop) { - try { - // attempt masking at this rate - Thread.sleep(1); - } catch (final InterruptedException iex) { - iex.printStackTrace(); - } - - if (!stop) { - ConsoleMenu.print("\r" + prompt + " \r" + prompt); - } - - System.out.flush(); - } - } - - /** - * Instruct the thread to stop masking. - */ - public void stopMasking() { - this.stop = true; - } - } - - private static void println(final String txt) { - OUT.println(txt); - } - - private static void print(final String txt) { - OUT.print(txt); - } -} Deleted: trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/console/Repeater.java =================================================================== --- trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/console/Repeater.java 2010-11-05 11:38:49 UTC (rev 374) +++ trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/console/Repeater.java 2010-11-05 11:41:20 UTC (rev 375) @@ -1,39 +0,0 @@ -/* - * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. - * - * Based in London, we are world leaders in the design and development - * of bespoke applications for the securities financing markets. - * - * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a> - * ___ _ _ _ _ _ - * / _ \| |__ (_) ___ ___| |_| | __ _| |__ - * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ - * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | - * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ - * |__/ - * - * www.ObjectLab.co.uk - * - * $Id: AbstractDateCalculator.java 309 2010-03-23 21:01:49Z marchy $ - * - * Copyright 2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package net.objectlab.kit.console; - -import java.lang.reflect.Method; - -public interface Repeater { - void repeat(Method target); -} Deleted: trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/Average.java =================================================================== --- trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/Average.java 2010-11-05 11:38:49 UTC (rev 374) +++ trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/Average.java 2010-11-05 11:41:20 UTC (rev 375) @@ -1,80 +0,0 @@ -/* - * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. - * - * Based in London, we are world leaders in the design and development - * of bespoke applications for the securities financing markets. - * - * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a> - * ___ _ _ _ _ _ - * / _ \| |__ (_) ___ ___| |_| | __ _| |__ - * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ - * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | - * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ - * |__/ - * - * www.ObjectLab.co.uk - * - * $Id: AbstractDateCalculator.java 309 2010-03-23 21:01:49Z marchy $ - * - * Copyright 2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package net.objectlab.kit.util; - -import java.io.Serializable; -import java.math.BigDecimal; - -/** - * @author Benoit - * - */ -public final class Average implements Serializable { - private static final long serialVersionUID = 4630559777899225672L; - private Total sum = new Total(); - private int count = 0; - - public Average() { - } - - public Average(final BigDecimal start) { - sum = new Total(start); - } - - public Average(final int scale) { - final BigDecimal bd = new BigDecimal(0); - sum = new Total(bd.setScale(scale)); - } - - public void add(final BigDecimal val) { - sum.add(val); - count++; - } - - public BigDecimal getTotal() { - return sum.getTotal(); - } - - public int getDataPoints() { - return count; - } - - public BigDecimal getAverage() { - return BigDecimalUtil.divide(getTotal(), new BigDecimal(count), BigDecimal.ROUND_HALF_UP); - } - - @Override - public String toString() { - return StringUtil.concatWithSpaces("Total:", getTotal(), "Points", getDataPoints(), "Avg:", getAverage()); - } -} Deleted: trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java =================================================================== --- trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java 2010-11-05 11:38:49 UTC (rev 374) +++ trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java 2010-11-05 11:41:20 UTC (rev 375) @@ -1,693 +0,0 @@ -/* - * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. - * - * Based in London, we are world leaders in the design and development - * of bespoke applications for the securities financing markets. - * - * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a> - * ___ _ _ _ _ _ - * / _ \| |__ (_) ___ ___| |_| | __ _| |__ - * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ - * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | - * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ - * |__/ - * - * www.ObjectLab.co.uk - * - * $Id: AbstractDateCalculator.java 309 2010-03-23 21:01:49Z marchy $ - * - * Copyright 2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package net.objectlab.kit.util; - -import java.math.BigDecimal; -import java.text.NumberFormat; - -/** - * @author Benoit Xhenseval - * - */ -public final class BigDecimalUtil { - private static final double ROUNDING_UP_FLOAT = 0.5d; - private static final int MAX_SCALE_FOR_INVERSE = 20; - private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(); - - private BigDecimalUtil() { - } - - /** - * Return the inverse of value, using scale - */ - public static BigDecimal inverse(final BigDecimal value, final int scale) { - if (isNotZero(value)) { - return BigDecimal.ONE.divide(value, scale, BigDecimal.ROUND_HALF_UP); - } - return null; - } - - /** - * Return the inverse of value - */ - public static BigDecimal inverse(final BigDecimal value) { - if (isNotZero(value)) { - return BigDecimal.ONE.setScale(MAX_SCALE_FOR_INVERSE).divide(value, BigDecimal.ROUND_HALF_UP); - } - return null; - } - - /** - * @return true if value !=null and <> 0. - */ - public static boolean isNotZero(final BigDecimal value) { - return value != null && value.signum() != 0; - } - - /** - * @return true if value !=null and 0. - */ - public static boolean isZero(final BigDecimal value) { - return value != null && value.signum() == 0; - } - - /** - * @return true if value !=null and <0. - */ - public static boolean isNegative(final BigDecimal value) { - return value != null && value.signum() == -1; - } - - /** - * @return true if value !=null and >0. - */ - public static boolean isStrictlyPositive(final BigDecimal value) { - return value != null && value.signum() == 1; - } - - /** - * @return true if value ==null OR 0. - */ - public static boolean isNullOrZero(final BigDecimal value) { - return value == null || value.signum() == 0; - } - - /** - * @return true if val1 == val2 (ignoring scale and null are treated as 0) - */ - public static boolean isSameValue(final BigDecimal val1, final BigDecimal val2) { - return val1 == null && val2 == null || val1 != null && val2 != null && val1.compareTo(val2) == 0; - } - - /** - * @return true if val1 == val2 (ignoring scale and null are treated as 0) - */ - public static boolean isSameValueTreatNullAsZero(final BigDecimal val1, final BigDecimal val2) { - return val1 == null && val2 == null || signum(val1) == 0 && signum(val2) == 0 || val1 != null && val2 != null && val1.compareTo(val2) == 0; - } - - /** - * Add 2 BigDecimal safely (i.e. handles nulls) - */ - private static BigDecimal doAdd(final BigDecimal v1, final BigDecimal v2) { - BigDecimal total = v1; - if (v1 != null && v2 != null) { - total = v1.add(v2); - } else if (v2 != null) { - total = v2; - } - return total; - } - - /** - * Add n BigDecimal safely (i.e. handles nulls) - */ - public static BigDecimal add(final BigDecimal start, final BigDecimal... values) { - BigDecimal total = start != null ? start : BigDecimal.ZERO; - if (values != null) { - for (final BigDecimal v : values) { - total = doAdd(total, v); - } - } - return total; - } - - /** - * Subtract n BigDecimal safely (i.e. handles nulls), returns 0 - */ - public static BigDecimal subtract(final BigDecimal start, final BigDecimal... values) { - BigDecimal total = start != null ? start : BigDecimal.ZERO; - if (values != null) { - for (final BigDecimal v : values) { - total = doSubtract(total, v); - } - } - return total; - } - - /** - * Subtract 2 BigDecimal safely (i.e. handles nulls) v1 - v2 - */ - private static BigDecimal doSubtract(final BigDecimal v1, final BigDecimal v2) { - BigDecimal diff = v1; - if (v1 != null && v2 != null) { - diff = v1.subtract(v2); - } else if (v2 != null) { - diff = v2.negate(); - } - return diff; - } - - /** - * @return numerator / denominator if they are not null and the denominator is not zero, it returns null otherwise. - */ - public static BigDecimal divide(final BigDecimal numerator, final BigDecimal denominator, final int rounding) { - BigDecimal diff = null; - if (numerator != null && isNotZero(denominator)) { - diff = numerator.divide(denominator, rounding); - } - return diff; - } - - public static BigDecimal calculateWeight(final BigDecimal value, final BigDecimal total) { - return BigDecimalUtil - .setScale(BigDecimalUtil.divide(BigDecimalUtil.setScale(value, 9), BigDecimalUtil.setScale(total, 9), BigDecimal.ROUND_HALF_UP), 9); - } - - /** - * @return numerator / denominator if they are not null and the denominator is not zero, it returns null otherwise. - */ - public static BigDecimal divide(final int numeratorScale, final BigDecimal numerator, final BigDecimal denominator, final int rounding) { - BigDecimal diff = null; - if (numerator != null && isNotZero(denominator)) { - diff = numerator.setScale(numeratorScale).divide(denominator, rounding); - } - return diff; - } - - /** - * @return numerator / denominator if they are not null and the denominator is not zero, it returns null otherwise. - */ - public static BigDecimal divide(final BigDecimal numerator, final BigDecimal denominator, final int scale, final int rounding) { - BigDecimal diff = null; - if (numerator != null && isNotZero(denominator)) { - diff = numerator.divide(denominator, rounding); - } - return BigDecimalUtil.setScale(diff, scale, rounding); - } - - public static BigDecimal multiply(final BigDecimal value, final BigDecimal multiplicand) { - BigDecimal diff = null; - if (value != null && multiplicand != null) { - diff = value.multiply(multiplicand); - } - return diff; - } - - public static BigDecimal multiply(final BigDecimal value, final BigDecimal... multiplicand) { - BigDecimal diff = null; - if (value != null && multiplicand != null) { - diff = value; - for (final BigDecimal bd : multiplicand) { - if (bd != null) { - diff = diff.multiply(bd); - } - } - } - return diff; - } - - /** - * Returns the ABS of the value, handles null. - */ - public static BigDecimal abs(final BigDecimal value) { - return value != null ? value.abs() : null; - } - - /** - * Returns the negate of the value, handles null. - */ - public static BigDecimal negate(final BigDecimal value) { - return value != null ? value.negate() : null; - } - - /** - * Returns the negate of the value if condition is true, handles null. - */ - public static BigDecimal negateIfTrue(final boolean condition, final BigDecimal value) { - return condition ? negate(value) : value; - } - - /** - * @return false if the ABS value match! - */ - public static boolean isNotSameAbsValue(final BigDecimal v1, final BigDecimal v2) { - return !isSameAbsValue(v1, v2); - } - - /** - * @return false if the value match! - */ - public static boolean isNotSameValue(final BigDecimal v1, final BigDecimal v2) { - return !isSameValue(v1, v2); - } - - /** - * @return true if the ABS value match! - */ - public static boolean isSameAbsValue(final BigDecimal v1, final BigDecimal v2) { - return isSameValue(abs(v1), abs(v2)); - } - - /** - * @return 1 if v1 > v2 or v2==null and v2!=null - * @return 0 if v1 == v2 or v1==null and v2==null - * @return -1 if v1 < v2 or v1==null and v2!=null - */ - public static int compareTo(final BigDecimal v1, final BigDecimal v2) { - int ret = 1; - if (v1 != null && v2 != null) { - ret = v1.compareTo(v2); - } else if (v1 == null && v2 == null) { - ret = 0; - } else if (v1 == null) { - ret = -1; - } - return ret; - } - - /** - * @return true if the ABS(v1) > ABS(v2) - */ - public static int absCompareTo(final BigDecimal v1, final BigDecimal v2) { - return compareTo(abs(v1), abs(v2)); - } - - /** - * @return true if the ABS( ABS(v1) - ABS(v2) ) - */ - public static BigDecimal absDiff(final BigDecimal v1, final BigDecimal v2) { - return abs(doSubtract(abs(v1), abs(v2))); - } - - /** - * Safe shift (check for null), shift RIGHT if shift>0. - */ - public static BigDecimal movePoint(final BigDecimal v1, final int shift) { - return v1 == null ? null : v1.movePointRight(shift); - } - - /** - * returns a new BigDecimal with correct scale after being round to n dec places. - * - * @param bd value - * @param numberOfDecPlaces number of dec place to round to - * @param finalScale final scale of result (typically numberOfDecPlaces < finalScale); - * @return new bd or null - */ - public static BigDecimal roundTo(final BigDecimal bd, final int numberOfDecPlaces, final int finalScale) { - return setScale(setScale(bd, numberOfDecPlaces, BigDecimal.ROUND_HALF_UP), finalScale); - } - - /** - * returns a new BigDecimal with correct scale. - * - * @param bd - * @return new bd or null - */ - public static BigDecimal setScale(final BigDecimal bd, final int scale) { - return setScale(bd, scale, BigDecimal.ROUND_HALF_UP); - } - - /** - * returns a new BigDecimal with correct Scale. - * - * @param bd - * @return new bd or null - */ - public static BigDecimal setScale(final BigDecimal bd, final Integer scale) { - return setScale(bd, scale, BigDecimal.ROUND_HALF_UP); - } - - /** - * returns a new BigDecimal with correct Scales.PERCENT_SCALE. This is used - * by the table renderer. - * - * @param bd - * @return new bd or null - */ - public static BigDecimal setScale(final BigDecimal bd, final Integer scale, final int rounding) { - if (bd != null && scale != null) { - return bd.setScale(scale, rounding); - } - return null; - } - - /** - * If value is null return 0 otherwise the signum(). - * @param value - * @return - */ - public static int signum(final BigDecimal value) { - return value == null ? 0 : value.signum(); - } - - /** - * @return true if both v1/v2 are null or same sign. - */ - public static boolean isSameSignum(final BigDecimal v1, final BigDecimal v2) { - return signum(v1) == signum(v2); - } - - /** - * @return true if both v1.signum() != v2.signum() and NOT zero. - */ - public static boolean hasSignedFlippedAndNotZero(final BigDecimal v1, final BigDecimal v2) { - final int v1Sign = signum(v1); - final int v2Sign = signum(v2); - return v1Sign != v2Sign && v1Sign != 0 && v2Sign != 0; - } - - /** - * @return true if v1.signum() != v2.signum(). - */ - public static boolean hasSignedChanged(final BigDecimal v1, final BigDecimal v2) { - return signum(v1) != signum(v2); - } - - /** - * @param bd - * @param lowerLimit - * @param upperLimit - * @return true if outside the range - */ - public static boolean isOutsideRange(final BigDecimal bd, final BigDecimal lowerLimit, final BigDecimal upperLimit) { - // TODO Auto-generated method stub - return !isInsideInclusiveRange(bd, lowerLimit, upperLimit); - } - - /** - * @param bd - * @param lowerLimit - * @param upperLimit - * @return true if inside the inclusive range - */ - public static boolean isInsideInclusiveRange(final BigDecimal bd, final BigDecimal lowerLimit, final BigDecimal upperLimit) { - return ObjectUtil.noneNull(bd, lowerLimit, upperLimit) && bd.compareTo(lowerLimit) >= 0 && bd.compareTo(upperLimit) <= 0; - } - - /** - * @return o1 if not null, otherwise fallBack - */ - public static BigDecimal assignNonNull(final BigDecimal o1, final BigDecimal fallBack) { - return o1 != null ? o1 : fallBack; - } - - /** - * Calculate the weight of the constituent and add it to the running weighted value. - * runningWeightedVal + valueToAdd * weightForValueToAdd / totalWeight - * @param runningWeightedVal - * @param valueToAdd - * @param weightForValueToAdd - * @param totalWeight - * @return - */ - public static BigDecimal addWeightedConstituent(final BigDecimal runningWeightedVal, final BigDecimal valueToAdd, final BigDecimal weightForValueToAdd, - final BigDecimal totalWeight) { - return BigDecimalUtil.doAdd(runningWeightedVal, BigDecimalUtil.divide(BigDecimalUtil.multiply(valueToAdd, BigDecimalUtil.abs(weightForValueToAdd)), - BigDecimalUtil.abs(totalWeight), BigDecimal.ROUND_HALF_UP)); - } - - /** - * @return true if all values are either null or zero - */ - public static boolean allNullOrZero(final BigDecimal... values) { - for (final BigDecimal bd : values) { - if (!isNullOrZero(bd)) { - return false; - } - } - return true; - } - - /** - * return a Number formatted or empty string if null. - * @param bd - */ - public static String format(final BigDecimal bd) { - return bd != null ? NUMBER_FORMAT.format(bd) : ""; - } - - /** - * return a Number formatted or empty string if null. - * @param bd - */ - public static String percentFormat(final BigDecimal bd) { - return bd != null ? NUMBER_FORMAT.format(bd.movePointRight(2)) : ""; - } - - /** - * true if ABS((startValue-newValue)/startValue) <= abs(thresholdPercent) - * @param startValue - * @param newValue - * @param thresholdPercent - * @return - */ - public static boolean movedInsideThresholdPercentage(final BigDecimal startValue, final BigDecimal newValue, final BigDecimal thresholdPercent) { - return !movedStrictlyOutsideThresholdPercentage(startValue, newValue, thresholdPercent); - } - - /** - * true if ABS((startValue-newValue)/startValue) > abs(thresholdPercent) - * @param startValue - * @param newValue - * @param thresholdPercent - * @return - */ - public static boolean movedStrictlyOutsideThresholdPercentage(final BigDecimal startValue, final BigDecimal newValue, final BigDecimal thresholdPercent) { - final BigDecimal s = BigDecimalUtil.setScale(startValue, 10); - final BigDecimal n = BigDecimalUtil.setScale(newValue, 10); - final BigDecimal diff = BigDecimalUtil.divide(BigDecimalUtil.doSubtract(s, n), s, BigDecimal.ROUND_HALF_UP); - // diff = BigDecimalUtil.safeAbsDiff(diff, MagicNumbers.ONE); - - return BigDecimalUtil.absCompareTo(diff, thresholdPercent) > 0; - } - - private static double roundUp(final double n, final int p) { - double retval; - - if (Double.isNaN(n) || Double.isInfinite(n)) { - retval = Double.NaN; - } else { - if (p != 0) { - final double temp = Math.pow(10, p); - final double nat = Math.abs(n * temp); - - retval = sign(n) * (nat == (long) nat ? nat / temp : Math.round(nat + ROUNDING_UP_FLOAT) / temp); - } else { - final double na = Math.abs(n); - retval = sign(n) * (na == (long) na ? na : (long) na + 1); - } - } - - return retval; - } - - /** - * Returns a value rounded to p digits after decimal. - * If p is negative, then the number is rounded to - * places to the left of the decimal point. eg. - * 10.23 rounded to -1 will give: 10. If p is zero, - * the returned value is rounded to the nearest integral - * value. - * <p>If n is negative, the resulting value is obtained - * as the round-up value of absolute value of n multiplied - * by the sign value of n (@see MathX.sign(double d)). - * Thus, -0.8 rounded-down to p=0 will give 0 not -1. - * <p>If n is NaN, returned value is NaN. - * @param n - * @param p - * @return - */ - private static double roundDown(final double n, final int p) { - double retval; - - if (Double.isNaN(n) || Double.isInfinite(n)) { - retval = Double.NaN; - } else { - if (p != 0) { - final double temp = Math.pow(10, p); - retval = sign(n) * Math.round(Math.abs(n) * temp - ROUNDING_UP_FLOAT) / temp; - } else { - retval = (long) n; - } - } - - return retval; - } - - private static short sign(final double d) { - return (short) (d == 0 ? 0 : d < 0 ? -1 : 1); - } - - /** - * Returns a value rounded-up to p digits after decimal. - * If p is negative, then the number is rounded to - * places to the left of the decimal point. eg. - * 10.23 rounded to -1 will give: 20. If p is zero, - * the returned value is rounded to the nearest integral - * value. - * <p>If n is negative, the resulting value is obtained - * as the round-up value of absolute value of n multiplied - * by the sign value of n (@see MathX.sign(double d)). - * Thus, -0.2 rounded-up to p=0 will give -1 not 0. - * <p>If n is NaN, returned value is NaN. - * @param n - * @param p - * @return - */ - public static BigDecimal roundUp(final BigDecimal n, final int p) { - if (n == null) { - return null; - } - final int scale = n.scale(); - return BigDecimalUtil.setScale(new BigDecimal(roundUp(n.doubleValue(), p)), scale); - } - - /** - * Returns a value rounded to p digits after decimal. - * If p is negative, then the number is rounded to - * places to the left of the decimal point. eg. - * 10.23 rounded to -1 will give: 10. If p is zero, - * the returned value is rounded to the nearest integral - * value. - * <p>If n is negative, the resulting value is obtained - * as the round-up value of absolute value of n multiplied - * by the sign value of n (@see MathX.sign(double d)). - * Thus, -0.8 rounded-down to p=0 will give 0 not -1. - * <p>If n is NaN, returned value is NaN. - * @param n - * @param p - * @return - */ - public static BigDecimal roundDown(final BigDecimal n, final int p) { - if (n == null) { - return null; - } - final int scale = n.scale(); - return BigDecimalUtil.setScale(new BigDecimal(roundDown(n.doubleValue(), p)), scale); - } - - public static BigDecimal roundUpForIncrement(final BigDecimal n, final BigDecimal increment) { - if (n == null) { - return null; - } - final int scale = n.scale(); - final int p = (int) (increment != null ? -Math.log10(increment.abs().doubleValue()) : 0); - return BigDecimalUtil.setScale(new BigDecimal(roundUp(n.doubleValue(), p)), scale); - } - - public static BigDecimal roundDownForIncrement(final BigDecimal n, final BigDecimal increment) { - if (n == null) { - return null; - } - final int p = (int) (increment != null ? -Math.log10(increment.abs().doubleValue()) : 0); - final int scale = n.scale(); - return BigDecimalUtil.setScale(new BigDecimal(roundDown(n.doubleValue(), p)), scale); - } - - /** - * Return minimum if the value is < minimum. - */ - public static BigDecimal ensureMin(final BigDecimal minimum, final BigDecimal value) { - return BigDecimalUtil.compareTo(minimum, value) == 1 ? minimum : value; - } - - /** - * Return a negative amount based on amount. - */ - public static BigDecimal forceNegative(final BigDecimal amount) { - return BigDecimalUtil.negate(BigDecimalUtil.abs(amount)); - } - - /** - * Return a negative amount based on amount if true, otherwise return the ABS. - */ - public static BigDecimal forceNegativeIfTrue(final boolean condition, final BigDecimal amount) { - return condition ? BigDecimalUtil.negate(BigDecimalUtil.abs(amount)) : BigDecimalUtil.abs(amount); - } - - /** - * @return return the min amount - */ - public static BigDecimal min(final BigDecimal v1, final BigDecimal v2) { - if (v1 == null) { - return v2; - } else if (v2 == null) { - return v1; - } - return v1.compareTo(v2) <= 0 ? v1 : v2; - } - - /** - * @return return the max amount - */ - public static BigDecimal max(final BigDecimal... v1) { - if (v1 == null) { - return null; - } - BigDecimal max = null; - for (final BigDecimal bd : v1) { - max = BigDecimalUtil.compareTo(max, bd) >= 0 ? max : bd; - } - return max; - } - - /** - * Move by 2 DEC place to the left and take the long value, this - * takes care of values like 0.18 in fractions. - */ - public static long longForFraction(final BigDecimal v) { - if (v == null) { - return 0L; - } - return BigDecimalUtil.movePoint(v, 2).longValue(); - } - - /** - * @return true if abs(abs(v1)-abs(v2)) < abs(threshold) - */ - public static boolean isDiffMoreThanAbsThreshold(final BigDecimal v1, final BigDecimal v2, final BigDecimal threshold) { - final BigDecimal diff = BigDecimalUtil.absDiff(v1, v2); - return BigDecimalUtil.compareTo(diff, BigDecimalUtil.abs(threshold)) > 0; - } - - public static double doubleValue(final BigDecimal val) { - return val != null ? val.doubleValue() : 0.0; - } - - /** - * @return true if value !=null and <=0. - */ - public static boolean isZeroOrLess(final BigDecimal value) { - return value != null && value.signum() <= 0; - } - - /** - * Return the decimal part of the value. - * @param val - */ - public static BigDecimal decimalPart(final BigDecimal val) { - return BigDecimalUtil.subtract(val, val.setScale(0, BigDecimal.ROUND_DOWN)); - } -} Deleted: trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/BooleanUtil.java =================================================================== --- trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/BooleanUtil.java 2010-11-05 11:38:49 UTC (rev 374) +++ trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/BooleanUtil.java 2010-11-05 11:41:20 UTC (rev 375) @@ -1,61 +0,0 @@ -/* - * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. - * - * Based in London, we are world leaders in the design and development - * of bespoke applications for the securities financing markets. - * - * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a> - * ___ _ _ _ _ _ - * / _ \| |__ (_) ___ ___| |_| | __ _| |__ - * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ - * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | - * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ - * |__/ - * - * www.ObjectLab.co.uk - * - * $Id: AbstractDateCalculator.java 309 2010-03-23 21:01:49Z marchy $ - * - * Copyright 2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package net.objectlab.kit.util; - -public final class BooleanUtil { - private BooleanUtil() { - } - - public static boolean isTrueOrNull(final Boolean b) { - return b == null ? true : b; - } - - public static boolean isFalseOrNull(final Boolean b) { - return b == null ? true : !b; - } - - public static boolean isTrue(final Boolean b) { - return b == null ? false : b; - } - - /** - * @return true if string is Y,y,YES,yes,TRUE,true,T,t - */ - public static boolean isTrue(final String str) { - return str == null ? false : StringUtil.equalsAnyIgnoreCase(StringUtil.trim(str), "yes", "y", "TRUE", "t"); - } - - public static boolean isFalse(final Boolean b) { - return b == null ? false : !b; - } -} Deleted: trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/CaseTreatment.java =================================================================== --- trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/CaseTreatment.java 2010-11-05 11:38:49 UTC (rev 374) +++ trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/CaseTreatment.java 2010-11-05 11:41:20 UTC (rev 375) @@ -1,37 +0,0 @@ -/* - * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. - * - * Based in London, we are world leaders in the design and development - * of bespoke applications for the securities financing markets. - * - * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a> - * ___ _ _ _ _ _ - * / _ \| |__ (_) ___ ___| |_| | __ _| |__ - * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ - * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | - * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ - * |__/ - * - * www.ObjectLab.co.uk - * - * $Id: AbstractDateCalculator.java 309 2010-03-23 21:01:49Z marchy $ - * - * Copyright 2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package net.objectlab.kit.util; - -public enum CaseTreatment { - UPPER_CASE, LOWER_CASE, UNCHANGED -} \ No newline at end of file Deleted: trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/CollectionUtil.java =================================================================== --- trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/CollectionUtil.java 2010-11-05 11:38:49 UTC (rev 374) +++ trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/CollectionUtil.java 2010-11-05 11:41:20 UTC (rev 375) @@ -1,130 +0,0 @@ -/* - * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. - * - * Based in London, we are world leaders in the design and development - * of bespoke applications for the securities financing markets. - * - * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a> - * ___ _ _ _ _ _ - * / _ \| |__ (_) ___ ___| |_| | __ _| |__ - * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ - * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | - * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ - * |__/ - * - * www.ObjectLab.co.uk - * - * $Id: AbstractDateCalculator.java 309 2010-03-23 21:01:49Z marchy $ - * - * Copyright 2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package net.objectlab.kit.util; - -import java.util.Collection; - -/** - * @author Benoit Xhenseval - * - */ -public final class CollectionUtil { - private CollectionUtil() { - } - - /** - * @return true if collection null or empty. - */ - public static boolean isEmpty(final Collection<?> col) { - return col == null || col.isEmpty(); - } - - /** - * @return true if collection not empty (null safe). - */ - public static boolean isNotEmpty(final Collection<?> col) { - return col != null && !col.isEmpty(); - } - - /** - * @return true if collection has only 1 item (null safe). - */ - public static boolean hasOneItem(final Collection<?> col) { - return col != null && col.size() == 1; - } - - /** - * @return true if array not empty (null safe). - */ - public static boolean isNotEmpty(final Object[] array) { - return array != null && array.length > 0; - } - - /** - * @return size of collection if not null, otherwise 0. - */ - public static int size(final Collection<?> col) { - return col != null ? col.size() : 0; - } - - /** - * @return true if collection is not null and contains the items - */ - public static boolean contains(final Collection<?> collection, final Object item) { - return collection != null && collection.contains(item) ? true : false; - } - - /** - * @return true if collection is not null and contains the items - */ - public static boolean containsAny(final Collection<?> collection, final Object... items) { - if (collection != null) { - for (final Object item : items) { - final boolean b = collection.contains(item); - if (b) { - return true; - } - } - } - return false; - } - - /** - * @return true if none of the collections are empty or null - */ - public static boolean noneEmpty(final Collection... collections) { - if (collections == null) { - return false; - } - for (final Collection col : collections) { - if (isEmpty(col)) { - return false; - } - } - return true; - } - - public static boolean sameContent(final Collection c1, final Collection c2) { - if (c1 == c2 || (isEmpty(c2) && isEmpty(c1))) { - return true; - } - boolean same = false; - if (c1 != null && c2 != null) { - same = c1.size() == c2.size(); - if (same) { - same = c1.equals(c2); - } - } - return same; - } -} Deleted: trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/IntegerUtil.java =================================================================== --- trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/IntegerUtil.java 2010-11-05 11:38:49 UTC (rev 374) +++ trunk/utils/1.0-cs/src/main/java/net/objectlab/kit/util/IntegerUtil.java 2010-11-05 11:41:20 UTC (rev 375) @@ -1,123 +0,0 @@ -/* - * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. - * - * Based in London, we are world leaders in the design and development - * of bespoke applications for the securities financing markets. - * - * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a> - * ___ _ _ _ _ _ - * / _ \| |__ (_) ___ ___| |_| | __ _| |__ - * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ - * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | - * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ - * |__/ - * - * www.ObjectLab.co.uk - * - * $Id: AbstractDateCalculator.java 309 2010-03-23 21:01:49Z marchy $ - * - * Copyright 2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package net.objectlab.kit.util; - -/** - * @author Benoit Xhenseval - * - */ -public final class IntegerUtil { - private IntegerUtil() { - } - - /** - * @return true if value !=null and <> 0. - */ - public static boolean isNotZero(final Integer value) { - return value != null && value.intValue() != 0; - } - - /** - * @return true if value !=null and 0. - */ - public static boolean ... [truncated message content] |
From: <ma...@us...> - 2010-11-05 11:38:55
|
Revision: 374 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=374&view=rev Author: marchy Date: 2010-11-05 11:38:49 +0000 (Fri, 05 Nov 2010) Log Message: ----------- Checking in Expiring Map for Benoit - he had problems with SVN Added Paths: ----------- trunk/utils/src/main/java/net/objectlab/kit/collections/ trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java trunk/utils/src/main/java/net/objectlab/kit/collections/MapBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/MapLoader.java trunk/utils/src/main/java/net/objectlab/kit/collections/SetBuilder.java trunk/utils/src/main/java/net/objectlab/kit/collections/SetLoader.java Added: trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,85 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Timer; +import java.util.TimerTask; + +/** + * @author xhensevalb + * + */ +public abstract class AbstractImmutabeExpiringCollection { + private long expiryTimeoutMilliseconds; + private boolean loadOnExpiry = true; + private boolean loadOnFirstAccess = true; + private long lastLoadingTime; + private Timer timer; + + protected void setLastLoadingTime(final long lastLoadingTime) { + this.lastLoadingTime = lastLoadingTime; + } + + public void setExpiryTimeoutMilliseconds(final long milliseconds) { + this.expiryTimeoutMilliseconds = milliseconds; + } + + public void setLoadOnExpiry(final boolean loadOnExpiry) { + this.loadOnExpiry = loadOnExpiry; + } + + public void setLoadOnFirstAccess(final boolean loadOnFirstAccess) { + this.loadOnFirstAccess = loadOnFirstAccess; + } + + protected boolean hasExpired() { + return System.currentTimeMillis() - lastLoadingTime > expiryTimeoutMilliseconds; + } + + public void start() { + if (loadOnExpiry) { + // start timer + timer = new Timer(); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + load(); + } + }, 0, expiryTimeoutMilliseconds); + } + if (!loadOnFirstAccess) { + load(); + } + } + + protected void validateOnAccess() { + if (hasExpired()) { + load(); + } + } + + private void load() { + doLoad(); + lastLoadingTime = System.currentTimeMillis(); + } + + protected abstract void doLoad(); + + protected long getExpiryTimeoutMilliseconds() { + return expiryTimeoutMilliseconds; + } + + protected boolean isLoadOnExpiry() { + return loadOnExpiry; + } + + protected boolean isLoadOnFirstAccess() { + return loadOnFirstAccess; + } + + protected long getLastLoadingTime() { + return lastLoadingTime; + } + +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/AbstractImmutabeExpiringCollection.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,18 @@ +/** + * + */ +package net.objectlab.kit.collections; + +/** + * @author xhensevalb + * + */ +public interface ImmutableExpiringCollection { + void setExpiryTimeoutMilliseconds(long milliseconds); + + void setLoadOnFirstAccess(boolean loadOnFirstAccess); + + void setLoadOnExpiry(boolean loadOnExpiry); + + void start(); +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollection.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,35 @@ +package net.objectlab.kit.collections; + +public class ImmutableExpiringCollectionBuilder { + private long expiryTimeoutMilliseconds; + private boolean loadOnExpiry = true; + private boolean loadOnFirstAccess = true; + + public ImmutableExpiringCollectionBuilder expiryTimeoutMilliseconds(final long expiryTimeourMilliseconds) { + this.expiryTimeoutMilliseconds = expiryTimeourMilliseconds; + return this; + } + + public ImmutableExpiringCollectionBuilder loadOnExpiry(final boolean loadOnExpiry) { + this.loadOnExpiry = loadOnExpiry; + return this; + } + + public ImmutableExpiringCollectionBuilder loadOnFirstAccess(final boolean loadOnFirstAccess) { + this.loadOnFirstAccess = loadOnFirstAccess; + return this; + } + + final long getExpiryTimeoutMilliseconds() { + return expiryTimeoutMilliseconds; + } + + final boolean isLoadOnExpiry() { + return loadOnExpiry; + } + + final boolean isLoadOnFirstAccess() { + return loadOnFirstAccess; + } + +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringCollectionBuilder.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,89 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * @author xhensevalb + * + */ +public class ImmutableExpiringHashMap<K, V> extends AbstractImmutabeExpiringCollection implements ImmutableExpiringMap<K, V> { + private Map<K, V> delegate = new HashMap<K, V>(); + private final MapLoader<K, V> loader; + + public ImmutableExpiringHashMap(final ImmutableExpiringHashMapBuilder<K, V> builder) { + loader = builder.getLoader(); + setExpiryTimeoutMilliseconds(builder.getExpiryTimeoutMilliseconds()); + setLoadOnExpiry(builder.isLoadOnExpiry()); + setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); + start(); + } + + @Override + protected void doLoad() { + final MapBuilder<K, V> builder = new MapBuilder<K, V>(); + loader.load(builder); + delegate = builder.build(); + } + + public void clear() { + throw new IllegalAccessError("Collection is immutable"); + } + + public boolean containsKey(final Object key) { + validateOnAccess(); + return delegate.containsKey(key); + } + + public boolean containsValue(final Object value) { + validateOnAccess(); + return delegate.containsValue(value); + } + + public Set<java.util.Map.Entry<K, V>> entrySet() { + validateOnAccess(); + return delegate.entrySet(); + } + + public V get(final Object key) { + validateOnAccess(); + return delegate.get(key); + } + + public boolean isEmpty() { + validateOnAccess(); + return delegate.isEmpty(); + } + + public Set<K> keySet() { + validateOnAccess(); + return delegate.keySet(); + } + + public V put(final K key, final V value) { + throw new IllegalAccessError("Collection is immutable"); + } + + public void putAll(final Map<? extends K, ? extends V> m) { + throw new IllegalAccessError("Collection is immutable"); + } + + public V remove(final Object key) { + throw new IllegalAccessError("Collection is immutable"); + } + + public int size() { + validateOnAccess(); + return delegate.size(); + } + + public Collection<V> values() { + validateOnAccess(); + return delegate.values(); + } +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMap.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,14 @@ +package net.objectlab.kit.collections; + +public class ImmutableExpiringHashMapBuilder<K, V> extends ImmutableExpiringCollectionBuilder { + private final MapLoader<K, V> loader; + + public ImmutableExpiringHashMapBuilder(final MapLoader<K, V> loader) { + super(); + this.loader = loader; + } + + final MapLoader<K, V> getLoader() { + return loader; + } +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashMapBuilder.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,93 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +/** + * @author xhensevalb + * + */ +public class ImmutableExpiringHashSet<T> extends AbstractImmutabeExpiringCollection implements ImmutableExpiringSet<T> { + private final SetLoader<T> loader; + private Set<T> delegate = new HashSet<T>(); + + public ImmutableExpiringHashSet(final ImmutableExpiringHashSetBuilder<T> builder) { + this.loader = builder.getLoader(); + setExpiryTimeoutMilliseconds(builder.getExpiryTimeoutMilliseconds()); + setLoadOnExpiry(builder.isLoadOnExpiry()); + setLoadOnFirstAccess(builder.isLoadOnFirstAccess()); + start(); + } + + @Override + protected void doLoad() { + final SetBuilder<T> builder = new SetBuilder<T>(); + loader.load(builder); + delegate = builder.build(); + } + + public boolean add(final T e) { + validateOnAccess(); + return delegate.add(e); + } + + public boolean addAll(final Collection<? extends T> c) { + throw new IllegalAccessError("Collection is immutable"); + } + + public void clear() { + throw new IllegalAccessError("Collection is immutable"); + } + + public boolean contains(final Object o) { + validateOnAccess(); + return delegate.contains(o); + } + + public boolean containsAll(final Collection<?> c) { + validateOnAccess(); + return delegate.containsAll(c); + } + + public boolean isEmpty() { + validateOnAccess(); + return delegate.isEmpty(); + } + + public Iterator<T> iterator() { + validateOnAccess(); + return delegate.iterator(); + } + + public boolean remove(final Object o) { + throw new IllegalAccessError("Collection is immutable"); + } + + public boolean removeAll(final Collection<?> c) { + throw new IllegalAccessError("Collection is immutable"); + } + + public boolean retainAll(final Collection<?> c) { + throw new IllegalAccessError("Collection is immutable"); + } + + public int size() { + validateOnAccess(); + return delegate.size(); + } + + public Object[] toArray() { + validateOnAccess(); + return delegate.toArray(); + } + + public <T> T[] toArray(final T[] a) { + validateOnAccess(); + return delegate.toArray(a); + } +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSet.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,14 @@ +package net.objectlab.kit.collections; + +public class ImmutableExpiringHashSetBuilder<T> extends ImmutableExpiringCollectionBuilder { + private final SetLoader<T> loader; + + public ImmutableExpiringHashSetBuilder(final SetLoader<T> loader) { + super(); + this.loader = loader; + } + + final SetLoader<T> getLoader() { + return loader; + } +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringHashSetBuilder.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,13 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Map; + +/** + * @author xhensevalb + * + */ +public interface ImmutableExpiringMap<K, V> extends ImmutableExpiringCollection, Map<K, V> { +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringMap.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,13 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.Set; + +/** + * @author xhensevalb + * + */ +public interface ImmutableExpiringSet<T> extends ImmutableExpiringCollection, Set<T> { +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/ImmutableExpiringSet.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/MapBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/MapBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/MapBuilder.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,68 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import net.objectlab.kit.util.Pair; + +/** + * Inspired by the Google Collection builder. + * + * @author Benoit Xhenseval + * + */ +public class MapBuilder<K, V> { + final List<Pair<K, V>> entries = new ArrayList<Pair<K, V>>(); + + public MapBuilder() { + } + + /** + * Associates {@code key} with {@code value} in the built map. + */ + public MapBuilder<K, V> put(final K key, final V value) { + entries.add(new Pair<K, V>(key, value)); + return this; + } + + /** + * Associates all of the given map's keys and values in the built map. + * + * @throws NullPointerException if any key or value in {@code map} is null + */ + public MapBuilder<K, V> putAll(final Map<? extends K, ? extends V> map) { + for (final Entry<? extends K, ? extends V> entry : map.entrySet()) { + put(entry.getKey(), entry.getValue()); + } + return this; + } + + /** + * Returns a newly-created immutable map. + * + * @throws IllegalArgumentException if duplicate keys were added + */ + public Map<K, V> build() { + return fromEntryList(entries); + } + + private static <K, V> Map<K, V> fromEntryList(final List<Pair<K, V>> entries) { + final int size = entries.size(); + switch (size) { + case 0: + return new HashMap<K, V>(); + default: + final Map<K, V> m = new HashMap<K, V>(); + for (final Pair<K, V> entry : entries) { + m.put(entry.getElement1(), entry.getElement2()); + } + return m; + } + } +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/MapBuilder.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/MapLoader.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/MapLoader.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/MapLoader.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,12 @@ +/** + * + */ +package net.objectlab.kit.collections; + +/** + * Whenever the map needs to be reloaded, it will call the loader. + * @author Benoit Xhenseval + */ +public interface MapLoader<K, V> { + void load(MapBuilder<K, V> builder); +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/MapLoader.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/SetBuilder.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/SetBuilder.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/SetBuilder.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,23 @@ +/** + * + */ +package net.objectlab.kit.collections; + +import java.util.HashSet; +import java.util.Set; + +/** + * @author xhensevalb + * + */ +public class SetBuilder<T> { + private final Set<T> set = new HashSet<T>(); + + public void add(final T t) { + set.add(t); + } + + public Set<T> build() { + return new HashSet<T>(set); + } +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/SetBuilder.java ___________________________________________________________________ Added: svn:executable + * Added: trunk/utils/src/main/java/net/objectlab/kit/collections/SetLoader.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/collections/SetLoader.java (rev 0) +++ trunk/utils/src/main/java/net/objectlab/kit/collections/SetLoader.java 2010-11-05 11:38:49 UTC (rev 374) @@ -0,0 +1,12 @@ +/** + * + */ +package net.objectlab.kit.collections; + +/** + * Whenever the set needs to be reloaded, it will call the loader. + * + */ +public interface SetLoader<T> { + void load(SetBuilder<T> builder); +} Property changes on: trunk/utils/src/main/java/net/objectlab/kit/collections/SetLoader.java ___________________________________________________________________ Added: svn:executable + * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <be...@us...> - 2010-11-01 21:32:03
|
Revision: 373 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=373&view=rev Author: benoitx Date: 2010-11-01 21:31:56 +0000 (Mon, 01 Nov 2010) Log Message: ----------- test SVN Modified Paths: -------------- trunk/utils/src/main/java/net/objectlab/kit/util/Util.java Modified: trunk/utils/src/main/java/net/objectlab/kit/util/Util.java =================================================================== --- trunk/utils/src/main/java/net/objectlab/kit/util/Util.java 2010-05-19 20:19:38 UTC (rev 372) +++ trunk/utils/src/main/java/net/objectlab/kit/util/Util.java 2010-11-01 21:31:56 UTC (rev 373) @@ -132,7 +132,6 @@ final PrintWriter out = new PrintWriter(sout); Util.listAllThreads(out); out.flush(); - return sout.toString(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <be...@us...> - 2010-05-19 20:19:43
|
Revision: 372 http://objectlabkit.svn.sourceforge.net/objectlabkit/?rev=372&view=rev Author: benoitx Date: 2010-05-19 20:19:38 +0000 (Wed, 19 May 2010) Log Message: ----------- Ready quick release for CS. Added Paths: ----------- trunk/utils/1.0-cs/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |