From: Mathieu Baudier Date: Tue, 25 Nov 2014 12:31:10 +0000 (+0000) Subject: New project conventions X-Git-Tag: argeo-commons-2.1.30~533 X-Git-Url: https://git.argeo.org/?a=commitdiff_plain;h=eebaa683a3c470ad22a5eaa5c32f816a2ea2cbbb;p=lgpl%2Fargeo-commons.git New project conventions git-svn-id: https://svn.argeo.org/commons/trunk@7515 4cfe0d0a-d680-48aa-b62c-e0a02a3f76cc --- diff --git a/org.argeo.util/.classpath b/org.argeo.util/.classpath index 8499fd0fa..91d2c42e5 100644 --- a/org.argeo.util/.classpath +++ b/org.argeo.util/.classpath @@ -1,10 +1,10 @@ - - - - - - - + + + + + diff --git a/org.argeo.util/bnd.bnd b/org.argeo.util/bnd.bnd new file mode 100644 index 000000000..e69de29bb diff --git a/org.argeo.util/build.properties b/org.argeo.util/build.properties deleted file mode 100644 index fcffb0f5e..000000000 --- a/org.argeo.util/build.properties +++ /dev/null @@ -1,6 +0,0 @@ -source.. = src/main/java/,\ - src/test/resources/,\ - src/test/java/ -bin.includes = META-INF/,\ - . -additional.bundles = junit diff --git a/org.argeo.util/ext/test/org/argeo/util/CsvParserEncodingTestCase.java b/org.argeo.util/ext/test/org/argeo/util/CsvParserEncodingTestCase.java new file mode 100644 index 000000000..111a8738c --- /dev/null +++ b/org.argeo.util/ext/test/org/argeo/util/CsvParserEncodingTestCase.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.List; + +import junit.framework.TestCase; + +public class CsvParserEncodingTestCase extends TestCase { + + private String iso = "ISO-8859-1"; + private String utf8 = "UTF-8"; + + public void testParse() throws Exception { + + String xml = new String("áéíóúñ,éééé"); + byte[] utfBytes = xml.getBytes(utf8); + byte[] isoBytes = xml.getBytes(iso); + + InputStream inUtf = new ByteArrayInputStream(utfBytes); + InputStream inIso = new ByteArrayInputStream(isoBytes); + + CsvParser csvParser = new CsvParser() { + protected void processLine(Integer lineNumber, List header, + List tokens) { + assertEquals(header.size(), tokens.size()); + assertEquals(2, tokens.size()); + assertEquals("áéíóúñ", tokens.get(0)); + assertEquals("éééé", tokens.get(1)); + } + }; + + csvParser.parse(inUtf, utf8); + inUtf.close(); + csvParser.parse(inIso, iso); + inIso.close(); + } +} diff --git a/org.argeo.util/ext/test/org/argeo/util/CsvParserParseFileTest.java b/org.argeo.util/ext/test/org/argeo/util/CsvParserParseFileTest.java new file mode 100644 index 000000000..a937ee7c7 --- /dev/null +++ b/org.argeo.util/ext/test/org/argeo/util/CsvParserParseFileTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +public class CsvParserParseFileTest extends TestCase { + public void testParse() throws Exception { + + final Map> lines = new HashMap>(); + InputStream in = getClass().getResourceAsStream( + "/org/argeo/util/ReferenceFile.csv"); + CsvParserWithLinesAsMap parser = new CsvParserWithLinesAsMap() { + protected void processLine(Integer lineNumber, + Map line) { + lines.put(lineNumber, line); + } + }; + + parser.parse(in); + in.close(); + + assertEquals(5, lines.size()); + } + +} diff --git a/org.argeo.util/ext/test/org/argeo/util/CsvParserTestCase.java b/org.argeo.util/ext/test/org/argeo/util/CsvParserTestCase.java new file mode 100644 index 000000000..02e8d1b59 --- /dev/null +++ b/org.argeo.util/ext/test/org/argeo/util/CsvParserTestCase.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.List; + +import junit.framework.TestCase; + +public class CsvParserTestCase extends TestCase { + public void testParse() throws Exception { + String toParse = "Header1,\"Header\n2\",Header3,\"Header4\"\n" + + "Col1,\"Col\n2\",Col3,\"\"\"Col4\"\"\"\n" + + "Col1,\"Col\n2\",Col3,\"\"\"Col4\"\"\"\n" + + "Col1,\"Col\n2\",Col3,\"\"\"Col4\"\"\"\n"; + + InputStream in = new ByteArrayInputStream(toParse.getBytes()); + + CsvParser csvParser = new CsvParser() { + protected void processLine(Integer lineNumber, List header, + List tokens) { + assertEquals(header.size(), tokens.size()); + assertEquals(4, tokens.size()); + assertEquals("Col1", tokens.get(0)); + assertEquals("Col\n2", tokens.get(1)); + assertEquals("Col3", tokens.get(2)); + assertEquals("\"Col4\"", tokens.get(3)); + } + }; + + csvParser.parse(in); + in.close(); + } + +} diff --git a/org.argeo.util/ext/test/org/argeo/util/CsvParserWithQuotedSeparatorTest.java b/org.argeo.util/ext/test/org/argeo/util/CsvParserWithQuotedSeparatorTest.java new file mode 100644 index 000000000..d4131a046 --- /dev/null +++ b/org.argeo.util/ext/test/org/argeo/util/CsvParserWithQuotedSeparatorTest.java @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +public class CsvParserWithQuotedSeparatorTest extends TestCase { + public void testSimpleParse() throws Exception { + String toParse = "Header1,\"Header2\",Header3,\"Header4\"\n" + + "\"Col1, Col2\",\"Col\n2\",Col3,\"\"\"Col4\"\"\"\n"; + + InputStream in = new ByteArrayInputStream(toParse.getBytes()); + + CsvParser csvParser = new CsvParser() { + protected void processLine(Integer lineNumber, List header, + List tokens) { + assertEquals(header.size(), tokens.size()); + assertEquals(4, tokens.size()); + assertEquals("Col1, Col2", tokens.get(0)); + } + }; + // System.out.println(toParse); + csvParser.parse(in); + in.close(); + + } + + public void testParseFile() throws Exception { + + final Map> lines = new HashMap>(); + InputStream in = getClass().getResourceAsStream( + "/org/argeo/util/ReferenceFile.csv"); + + CsvParserWithLinesAsMap parser = new CsvParserWithLinesAsMap() { + protected void processLine(Integer lineNumber, + Map line) { + // System.out.println("processing line #" + lineNumber); + lines.put(lineNumber, line); + } + }; + + parser.parse(in); + in.close(); + + Map line = lines.get(2); + assertEquals(",,,,", line.get("Coma testing")); + line = lines.get(3); + assertEquals(",, ,,", line.get("Coma testing")); + line = lines.get(4); + assertEquals("module1, module2", line.get("Coma testing")); + line = lines.get(5); + assertEquals("module1,module2", line.get("Coma testing")); + line = lines.get(6); + assertEquals(",module1,module2, \nmodule3, module4", + line.get("Coma testing")); + assertEquals(5, lines.size()); + + } +} diff --git a/org.argeo.util/ext/test/org/argeo/util/CsvWriterTestCase.java b/org.argeo.util/ext/test/org/argeo/util/CsvWriterTestCase.java new file mode 100644 index 000000000..26b356def --- /dev/null +++ b/org.argeo.util/ext/test/org/argeo/util/CsvWriterTestCase.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +public class CsvWriterTestCase extends TestCase { + public void testWrite() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + final CsvWriter csvWriter = new CsvWriter(out); + + String[] header = { "Header1", "Header 2", "Header,3", "Header\n4", + "Header\"5\"" }; + String[] line1 = { "Value1", "Value 2", "Value,3", "Value\n4", + "Value\"5\"" }; + csvWriter.writeLine(Arrays.asList(header)); + csvWriter.writeLine(Arrays.asList(line1)); + + String reference = "Header1,Header 2,\"Header,3\",\"Header\n4\",\"Header\"\"5\"\"\"\n" + + "Value1,Value 2,\"Value,3\",\"Value\n4\",\"Value\"\"5\"\"\"\n"; + String written = new String(out.toByteArray()); + assertEquals(reference, written); + out.close(); + System.out.println(written); + + final List allTokens = new ArrayList(); + CsvParser csvParser = new CsvParser() { + protected void processLine(Integer lineNumber, List header, + List tokens) { + if (lineNumber == 2) + allTokens.addAll(header); + allTokens.addAll(tokens); + } + }; + ByteArrayInputStream in = new ByteArrayInputStream(written.getBytes()); + csvParser.parse(in); + in.close(); + List allTokensRef = new ArrayList(); + allTokensRef.addAll(Arrays.asList(header)); + allTokensRef.addAll(Arrays.asList(line1)); + + assertEquals(allTokensRef.size(), allTokens.size()); + for (int i = 0; i < allTokensRef.size(); i++) + assertEquals(allTokensRef.get(i), allTokens.get(i)); + } + +} diff --git a/org.argeo.util/ext/test/org/argeo/util/ReferenceFile.csv b/org.argeo.util/ext/test/org/argeo/util/ReferenceFile.csv new file mode 100644 index 000000000..351453d10 --- /dev/null +++ b/org.argeo.util/ext/test/org/argeo/util/ReferenceFile.csv @@ -0,0 +1,37 @@ +"ID","A long Text","Name","Other","Number","Reference","Target","Date","Update","Language","ID Ref","Weird chars","line feeds","after line feed","Empty column","Status comment","Comments","Empty","Coma testing" +"AK251","Everything & with some line feed + more “some” quote","Marge S.",,78.6,"A1155222221111268515131",,12/12/12,03/12/08,,9821308500721,"%%%ùù","ao","Nothing special",,,"Some very usefull comment",,",,,," +"AG254","same","Roger “wallace” Big","15 – JI",78.5,"A1155222221111268515131","next milestone",12/12/12,03/12/08,"_fr (French - France)",9812309500953,"***µ”","a + + + + +o","after line feed",,"Do the job",,,",, ,," +"FG211","Very long text with some bullets. +1 first +2 second +3. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long","Father & Son","15 – JI",15.4,"A1155222221111268515131","next milestone",12/12/12,03/12/08,"_fr (French - France)",9812309500952,"///","a + + + + + + +o","module1,module2",,"Be fast",,,"module1, module2" +"RRT152","Very long text with some bullets. +1 first +2 second +3. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long","Another $$","15 – JI",12.3,"A1155222221111268515131","next milestone",12/12/12,03/12/08,"_fr (French - France)",9812309500950,"---","a + +o + + +","module1,module2",,,,,"module1,module2" +"YU121","Another use case : “blank line” + +After the blank.","nothing with brackets( )","15 – JI",15.2,"A1155222221111268515131",,12/12/12,03/12/08,"_fr (French - France)",9812309500925,",;:?./","ao"," + + + +After line feed again",,,,,",module1,module2, +module3, module4" diff --git a/org.argeo.util/ext/test/org/argeo/util/TestParse-ISO.csv b/org.argeo.util/ext/test/org/argeo/util/TestParse-ISO.csv new file mode 100644 index 000000000..0bec61111 --- /dev/null +++ b/org.argeo.util/ext/test/org/argeo/util/TestParse-ISO.csv @@ -0,0 +1,8 @@ +"Date d'imputation","N° de compte","Code journal","Pièce interne","Pièce externe","Libellé d'écriture","Débit","Crédit","Lettrage","Quantité","Code analytique","Date d'échéance","Date d'imputation origine","Code journal origine","Mode de règlement","Date début de période","Date fin de période" +26.01.2010,"101300","BQ","BQ01.10",,"Depot société en formation",,"3.000,00",,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"101300","BQ","BQ01.10",,"Depot société en formation",,"7.000,00",,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"411OPEN","BQ","BQ01.10",,"Vir Client ",,"2.508,00","A",,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"455100","BQ","BQ01.10",,"Bankomat Raiffeise","250,00",,,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"512101","BQ","BQ01.10",,"Extrait bancaire 01.10","12.250,55",,,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"627800","BQ","BQ01.10",,"Envoi de chequier","2,30",,,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"627800","BQ","BQ01.10",,"Frais d'expedition","5,15",,,,," ",26.01.2010,"BQ"," "," "," " diff --git a/org.argeo.util/ext/test/org/argeo/util/TestParse-UTF-8.csv b/org.argeo.util/ext/test/org/argeo/util/TestParse-UTF-8.csv new file mode 100644 index 000000000..0bec61111 --- /dev/null +++ b/org.argeo.util/ext/test/org/argeo/util/TestParse-UTF-8.csv @@ -0,0 +1,8 @@ +"Date d'imputation","N° de compte","Code journal","Pièce interne","Pièce externe","Libellé d'écriture","Débit","Crédit","Lettrage","Quantité","Code analytique","Date d'échéance","Date d'imputation origine","Code journal origine","Mode de règlement","Date début de période","Date fin de période" +26.01.2010,"101300","BQ","BQ01.10",,"Depot société en formation",,"3.000,00",,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"101300","BQ","BQ01.10",,"Depot société en formation",,"7.000,00",,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"411OPEN","BQ","BQ01.10",,"Vir Client ",,"2.508,00","A",,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"455100","BQ","BQ01.10",,"Bankomat Raiffeise","250,00",,,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"512101","BQ","BQ01.10",,"Extrait bancaire 01.10","12.250,55",,,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"627800","BQ","BQ01.10",,"Envoi de chequier","2,30",,,,," ",26.01.2010,"BQ"," "," "," " +26.01.2010,"627800","BQ","BQ01.10",,"Frais d'expedition","5,15",,,,," ",26.01.2010,"BQ"," "," "," " diff --git a/org.argeo.util/ext/test/org/argeo/util/ThroughputTest.java b/org.argeo.util/ext/test/org/argeo/util/ThroughputTest.java new file mode 100644 index 000000000..fc8007efd --- /dev/null +++ b/org.argeo.util/ext/test/org/argeo/util/ThroughputTest.java @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import junit.framework.TestCase; + +public class ThroughputTest extends TestCase { + public void testParse() { + Throughput t; + t = new Throughput("3.54/s"); + assertEquals(3.54d, t.getValue()); + assertEquals(Throughput.Unit.s, t.getUnit()); + assertEquals(282l, (long) t.asMsPeriod()); + + t = new Throughput("35698.2569/h"); + assertEquals(Throughput.Unit.h, t.getUnit()); + assertEquals(101l, (long) t.asMsPeriod()); + } +} diff --git a/org.argeo.util/src/main/java/org/argeo/ArgeoException.java b/org.argeo.util/src/main/java/org/argeo/ArgeoException.java deleted file mode 100644 index 9cf918667..000000000 --- a/org.argeo.util/src/main/java/org/argeo/ArgeoException.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo; - -/** Argeo Commons specific exception. */ -public class ArgeoException extends RuntimeException { - private static final long serialVersionUID = 1L; - - /** Creates an exception with a message. */ - public ArgeoException(String message) { - super(message); - } - - /** Creates an exception with a message and a root cause. */ - public ArgeoException(String message, Throwable e) { - super(message, e); - } - - /** - * Chain the messages of all causes (one per line, starts with a line - * return) without all the stack - */ - public static String chainCausesMessages(Throwable t) { - StringBuffer buf = new StringBuffer(); - chainCauseMessage(buf, t); - return buf.toString(); - } - - /** Recursive chaining of messages */ - private static void chainCauseMessage(StringBuffer buf, Throwable t) { - buf.append('\n').append(' ').append(t.getClass().getCanonicalName()) - .append(": ").append(t.getMessage()); - if (t.getCause() != null) - chainCauseMessage(buf, t.getCause()); - } -} diff --git a/org.argeo.util/src/main/java/org/argeo/ArgeoLogListener.java b/org.argeo.util/src/main/java/org/argeo/ArgeoLogListener.java deleted file mode 100644 index bac8a9820..000000000 --- a/org.argeo.util/src/main/java/org/argeo/ArgeoLogListener.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo; - -/** Framework agnostic interface for log notifications */ -public interface ArgeoLogListener { - /** - * Appends a log - * - * @param username - * authentified user, null for anonymous - * @param level - * INFO, DEBUG, WARN, etc. (logging framework specific) - * @param category - * hierarchy (logging framework specific) - * @param thread - * name of the thread which logged this message - * @param msg - * any object as long as its toString() method returns the - * message - * @param the - * exception in log4j ThrowableStrRep format - */ - public void appendLog(String username, Long timestamp, String level, - String category, String thread, Object msg, String[] exception); -} diff --git a/org.argeo.util/src/main/java/org/argeo/ArgeoLogger.java b/org.argeo.util/src/main/java/org/argeo/ArgeoLogger.java deleted file mode 100644 index 0657c29dd..000000000 --- a/org.argeo.util/src/main/java/org/argeo/ArgeoLogger.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo; - -/** - * Logging framework agnostic identifying a logging service, to which one can - * register - */ -public interface ArgeoLogger { - /** - * Register for events by threads with the same authentication (or all - * threads if admin) - */ - public void register(ArgeoLogListener listener, - Integer numberOfPreviousEvents); - - /** - * For admin use only: register for all users - * - * @param listener - * the log listener - * @param numberOfPreviousEvents - * the number of previous events to notify - * @param everything - * if true even anonymous is logged - */ - public void registerForAll(ArgeoLogListener listener, - Integer numberOfPreviousEvents, boolean everything); - - public void unregister(ArgeoLogListener listener); - - public void unregisterForAll(ArgeoLogListener listener); -} diff --git a/org.argeo.util/src/main/java/org/argeo/ArgeoMonitor.java b/org.argeo.util/src/main/java/org/argeo/ArgeoMonitor.java deleted file mode 100644 index 9ef23cc8b..000000000 --- a/org.argeo.util/src/main/java/org/argeo/ArgeoMonitor.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo; - -/** - * Simple monitor abstraction. Inspired by Eclipse IProgressMOnitor, but without - * dependency to it. - */ -public interface ArgeoMonitor { - /** - * Constant indicating an unknown amount of work. - */ - public final static int UNKNOWN = -1; - - /** - * Notifies that the main task is beginning. This must only be called once - * on a given progress monitor instance. - * - * @param name - * the name (or description) of the main task - * @param totalWork - * the total number of work units into which the main task is - * been subdivided. If the value is UNKNOWN the - * implementation is free to indicate progress in a way which - * doesn't require the total number of work units in advance. - */ - public void beginTask(String name, int totalWork); - - /** - * Notifies that the work is done; that is, either the main task is - * completed or the user canceled it. This method may be called more than - * once (implementations should be prepared to handle this case). - */ - public void done(); - - /** - * Returns whether cancelation of current operation has been requested. - * Long-running operations should poll to see if cancelation has been - * requested. - * - * @return true if cancellation has been requested, and - * false otherwise - * @see #setCanceled(boolean) - */ - public boolean isCanceled(); - - /** - * Sets the cancel state to the given value. - * - * @param value - * true indicates that cancelation has been - * requested (but not necessarily acknowledged); - * false clears this flag - * @see #isCanceled() - */ - public void setCanceled(boolean value); - - /** - * Sets the task name to the given value. This method is used to restore the - * task label after a nested operation was executed. Normally there is no - * need for clients to call this method. - * - * @param name - * the name (or description) of the main task - * @see #beginTask(java.lang.String, int) - */ - public void setTaskName(String name); - - /** - * Notifies that a subtask of the main task is beginning. Subtasks are - * optional; the main task might not have subtasks. - * - * @param name - * the name (or description) of the subtask - */ - public void subTask(String name); - - /** - * Notifies that a given number of work unit of the main task has been - * completed. Note that this amount represents an installment, as opposed to - * a cumulative amount of work done to date. - * - * @param work - * a non-negative number of work units just completed - */ - public void worked(int work); - -} diff --git a/org.argeo.util/src/main/java/org/argeo/OperatingSystem.java b/org.argeo.util/src/main/java/org/argeo/OperatingSystem.java deleted file mode 100644 index 697c86c51..000000000 --- a/org.argeo.util/src/main/java/org/argeo/OperatingSystem.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo; - -/** The current operating system. */ -public class OperatingSystem { - public final static int NIX = 1; - public final static int WINDOWS = 2; - public final static int SOLARIS = 3; - - public final static int os; - static { - String osName = System.getProperty("os.name"); - if (osName.startsWith("Win")) - os = WINDOWS; - else if (osName.startsWith("Solaris")) - os = SOLARIS; - else - os = NIX; - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/StreamUtils.java b/org.argeo.util/src/main/java/org/argeo/StreamUtils.java deleted file mode 100644 index 39caaddda..000000000 --- a/org.argeo.util/src/main/java/org/argeo/StreamUtils.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; - -/** Utilities to be used when APache COmmons IO is not available. */ -public class StreamUtils { - private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; - - /* - * APACHE COMMONS IO (inspired) - */ - - /** @return the number of bytes */ - public static Long copy(InputStream in, OutputStream out) - throws IOException { - Long count = 0l; - byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; - while (true) { - int length = in.read(buf); - if (length < 0) - break; - out.write(buf, 0, length); - count = count + length; - } - return count; - } - - /** @return the number of chars */ - public static Long copy(Reader in, Writer out) throws IOException { - Long count = 0l; - char[] buf = new char[DEFAULT_BUFFER_SIZE]; - while (true) { - int length = in.read(buf); - if (length < 0) - break; - out.write(buf, 0, length); - count = count + length; - } - return count; - } - - public static void closeQuietly(InputStream in) { - if (in != null) - try { - in.close(); - } catch (Exception e) { - // - } - } - - public static void closeQuietly(OutputStream out) { - if (out != null) - try { - out.close(); - } catch (Exception e) { - // - } - } - - public static void closeQuietly(Reader in) { - if (in != null) - try { - in.close(); - } catch (Exception e) { - // - } - } - - public static void closeQuietly(Writer out) { - if (out != null) - try { - out.close(); - } catch (Exception e) { - // - } - } - - /* - * APACHE COMMONS CODEC (forked) - */ - /** - * Used to build output as Hex - */ - private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - - /** - * Used to build output as Hex - */ - private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - - /** - * Converts an array of bytes into a String representing the hexadecimal - * values of each byte in order. The returned String will be double the - * length of the passed array, as it takes two characters to represent any - * given byte. - * - * @param data - * a byte[] to convert to Hex characters - * @return A String containing hexadecimal characters - * @since 1.4 - */ - public static String encodeHexString(byte[] data) { - return new String(encodeHex(data)); - } - - /** - * Converts an array of bytes into an array of characters representing the - * hexadecimal values of each byte in order. The returned array will be - * double the length of the passed array, as it takes two characters to - * represent any given byte. - * - * @param data - * a byte[] to convert to Hex characters - * @return A char[] containing hexadecimal characters - */ - public static char[] encodeHex(byte[] data) { - return encodeHex(data, true); - } - - /** - * Converts an array of bytes into an array of characters representing the - * hexadecimal values of each byte in order. The returned array will be - * double the length of the passed array, as it takes two characters to - * represent any given byte. - * - * @param data - * a byte[] to convert to Hex characters - * @param toLowerCase - * true converts to lowercase, false to - * uppercase - * @return A char[] containing hexadecimal characters - * @since 1.4 - */ - public static char[] encodeHex(byte[] data, boolean toLowerCase) { - return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); - } - - /** - * Converts an array of bytes into an array of characters representing the - * hexadecimal values of each byte in order. The returned array will be - * double the length of the passed array, as it takes two characters to - * represent any given byte. - * - * @param data - * a byte[] to convert to Hex characters - * @param toDigits - * the output alphabet - * @return A char[] containing hexadecimal characters - * @since 1.4 - */ - protected static char[] encodeHex(byte[] data, char[] toDigits) { - int l = data.length; - char[] out = new char[l << 1]; - // two characters form the hex value. - for (int i = 0, j = 0; i < l; i++) { - out[j++] = toDigits[(0xF0 & data[i]) >>> 4]; - out[j++] = toDigits[0x0F & data[i]]; - } - return out; - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/CsvParser.java b/org.argeo.util/src/main/java/org/argeo/util/CsvParser.java deleted file mode 100644 index 7680b3267..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/CsvParser.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.argeo.ArgeoException; -import org.argeo.StreamUtils; - -/** - * Parses a CSV file interpreting the first line as a header. The - * {@link #parse(InputStream)} method and the setters are synchronized so that - * the object cannot be modified when parsing. - */ -public abstract class CsvParser { - private char separator = ','; - private char quote = '\"'; - - private Boolean noHeader = false; - private Boolean strictLineAsLongAsHeader = true; - - /** - * Actually process a parsed line. If - * {@link #setStrictLineAsLongAsHeader(Boolean)} is true (default) the - * header and the tokens are guaranteed to have the same size. - * - * @param lineNumber - * the current line number, starts at 1 (the header, if header - * processing is enabled, the first line otherwise) - * @param header - * the read-only header or null if {@link #setNoHeader(Boolean)} - * is true (default is false) - * @param tokens - * the parsed tokens - */ - protected abstract void processLine(Integer lineNumber, - List header, List tokens); - - /** - * Parses the CSV file (stream is closed at the end) - */ - public synchronized void parse(InputStream in) { - parse(in, null); - } - - /** - * Parses the CSV file (stream is closed at the end) - */ - public synchronized void parse(InputStream in, String encoding) { - BufferedReader reader = null; - Integer lineCount = 0; - try { - if (encoding == null) - reader = new BufferedReader(new InputStreamReader(in)); - else - reader = new BufferedReader(new InputStreamReader(in, encoding)); - List header = null; - if (!noHeader) { - String headerStr = reader.readLine(); - if (headerStr == null)// empty file - return; - lineCount++; - header = new ArrayList(); - StringBuffer currStr = new StringBuffer(""); - Boolean wasInquote = false; - while (parseLine(headerStr, header, currStr, wasInquote)) { - headerStr = reader.readLine(); - if (headerStr == null) - break; - wasInquote = true; - } - header = Collections.unmodifiableList(header); - } - - String line = null; - lines: while ((line = reader.readLine()) != null) { - line = preProcessLine(line); - if (line == null) { - // skip line - continue lines; - } - lineCount++; - List tokens = new ArrayList(); - StringBuffer currStr = new StringBuffer(""); - Boolean wasInquote = false; - sublines: while (parseLine(line, tokens, currStr, wasInquote)) { - line = reader.readLine(); - if (line == null) - break sublines; - wasInquote = true; - } - if (!noHeader && strictLineAsLongAsHeader) { - int headerSize = header.size(); - int tokenSize = tokens.size(); - if (tokenSize == 1 && line.trim().equals("")) - continue lines;// empty line - if (headerSize != tokenSize) { - throw new ArgeoException("Token size " + tokenSize - + " is different from header size " - + headerSize + " at line " + lineCount - + ", line: " + line + ", header: " + header - + ", tokens: " + tokens); - } - } - processLine(lineCount, header, tokens); - } - } catch (ArgeoException e) { - throw e; - } catch (IOException e) { - throw new ArgeoException("Cannot parse CSV file (line: " - + lineCount + ")", e); - } finally { - StreamUtils.closeQuietly(reader); - } - } - - /** - * Called before each (logical) line is processed, giving a change to modify - * it (typically for cleaning dirty files). To be overridden, return the - * line unchanged by default. Skip the line if 'null' is returned. - */ - protected String preProcessLine(String line) { - return line; - } - - /** - * Parses a line character by character for performance purpose - * - * @return whether to continue parsing this line - */ - protected Boolean parseLine(String str, List tokens, - StringBuffer currStr, Boolean wasInquote) { - // List tokens = new ArrayList(); - - // System.out.println("#LINE: " + str); - - if (wasInquote) - currStr.append('\n'); - - char[] arr = str.toCharArray(); - boolean inQuote = wasInquote; - // StringBuffer currStr = new StringBuffer(""); - for (int i = 0; i < arr.length; i++) { - char c = arr[i]; - if (c == separator) { - if (!inQuote) { - tokens.add(currStr.toString()); - // System.out.println("# TOKEN: " + currStr); - currStr.delete(0, currStr.length()); - } else { - // we don't remove separator that are in a quoted substring - // System.out - // .println("IN QUOTE, got a separator: [" + c + "]"); - currStr.append(c); - } - } else if (c == quote) { - if (inQuote && (i + 1) < arr.length && arr[i + 1] == quote) { - // case of double quote - currStr.append(quote); - i++; - } else {// standard - inQuote = inQuote ? false : true; - } - } else { - currStr.append(c); - } - } - - if (!inQuote) { - tokens.add(currStr.toString()); - // System.out.println("# TOKEN: " + currStr); - } - // if (inQuote) - // throw new ArgeoException("Missing quote at the end of the line " - // + str + " (parsed: " + tokens + ")"); - if (inQuote) - return true; - else - return false; - // return tokens; - } - - public char getSeparator() { - return separator; - } - - public synchronized void setSeparator(char separator) { - this.separator = separator; - } - - public char getQuote() { - return quote; - } - - public synchronized void setQuote(char quote) { - this.quote = quote; - } - - public Boolean getNoHeader() { - return noHeader; - } - - public synchronized void setNoHeader(Boolean noHeader) { - this.noHeader = noHeader; - } - - public Boolean getStrictLineAsLongAsHeader() { - return strictLineAsLongAsHeader; - } - - public synchronized void setStrictLineAsLongAsHeader( - Boolean strictLineAsLongAsHeader) { - this.strictLineAsLongAsHeader = strictLineAsLongAsHeader; - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/CsvParserWithLinesAsMap.java b/org.argeo.util/src/main/java/org/argeo/util/CsvParserWithLinesAsMap.java deleted file mode 100644 index e7baabbf0..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/CsvParserWithLinesAsMap.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.argeo.ArgeoException; - -/** - * CSV parser allowing to process lines as maps whose keys are the header - * fields. - */ -public abstract class CsvParserWithLinesAsMap extends CsvParser { - - /** - * Actually processes a line. - * - * @param lineNumber - * the current line number, starts at 1 (the header, if header - * processing is enabled, the first lien otherwise) - * @param line - * the parsed tokens as a map whose keys are the header fields - */ - protected abstract void processLine(Integer lineNumber, - Map line); - - protected final void processLine(Integer lineNumber, List header, - List tokens) { - if (header == null) - throw new ArgeoException("Only CSV with header is supported"); - Map line = new HashMap(); - for (int i = 0; i < header.size(); i++) { - String key = header.get(i); - String value = null; - if (i < tokens.size()) - value = tokens.get(i); - line.put(key, value); - } - processLine(lineNumber, line); - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/CsvWriter.java b/org.argeo.util/src/main/java/org/argeo/util/CsvWriter.java deleted file mode 100644 index d90f47412..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/CsvWriter.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.util.Iterator; -import java.util.List; - -import org.argeo.ArgeoException; - -/** Write in CSV format. */ -public class CsvWriter { - private final Writer out; - - private char separator = ','; - private char quote = '\"'; - - /** - * Creates a CSV writer. - * - * @param out - * the stream to write to. Caller is responsible for closing it. - */ - public CsvWriter(OutputStream out) { - this.out = new OutputStreamWriter(out); - } - - /** - * Creates a CSV writer. - * - * @param out - * the stream to write to. Caller is responsible for closing it. - */ - public CsvWriter(OutputStream out, String encoding) { - try { - this.out = new OutputStreamWriter(out, encoding); - } catch (UnsupportedEncodingException e) { - throw new ArgeoException("Cannot initialize CSV writer", e); - } - } - - /** - * Write a CSV line. Also used to write a header if needed (this is - * transparent for the CSV writer): simply call it first, before writing the - * lines. - */ - public void writeLine(List tokens) { - try { - Iterator it = tokens.iterator(); - while (it.hasNext()) { - writeToken(it.next().toString()); - if (it.hasNext()) - out.write(separator); - } - out.write('\n'); - out.flush(); - } catch (IOException e) { - throw new ArgeoException("Could not write " + tokens, e); - } - } - - /** - * Write a CSV line. Also used to write a header if needed (this is - * transparent for the CSV writer): simply call it first, before writing the - * lines. - */ - public void writeLine(Object[] tokens) { - try { - for (int i = 0; i < tokens.length; i++) { - if (tokens[i] == null) { - // TODO configure how to deal with null - writeToken(""); - } else { - writeToken(tokens[i].toString()); - } - if (i != (tokens.length - 1)) - out.write(separator); - } - out.write('\n'); - out.flush(); - } catch (IOException e) { - throw new ArgeoException("Could not write " + tokens, e); - } - } - - protected void writeToken(String token) throws IOException { - // +2 for possible quotes, another +2 assuming there would be an already - // quoted string where quotes needs to be duplicated - // another +2 for safety - // we don't want to increase buffer size while writing - StringBuffer buf = new StringBuffer(token.length() + 6); - char[] arr = token.toCharArray(); - boolean shouldQuote = false; - for (char c : arr) { - if (!shouldQuote) { - if (c == separator) - shouldQuote = true; - if (c == '\n') - shouldQuote = true; - } - - if (c == quote) { - shouldQuote = true; - // duplicate quote - buf.append(quote); - } - - // generic case - buf.append(c); - } - - if (shouldQuote == true) - out.write(quote); - out.write(buf.toString()); - if (shouldQuote == true) - out.write(quote); - } - - public void setSeparator(char separator) { - this.separator = separator; - } - - public void setQuote(char quote) { - this.quote = quote; - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/LocaleCallback.java b/org.argeo.util/src/main/java/org/argeo/util/LocaleCallback.java deleted file mode 100644 index 60bf4c40f..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/LocaleCallback.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -import javax.security.auth.callback.Callback; - -/** Choose in a list of locales */ -public class LocaleCallback implements Callback { - private List availableLocales = new ArrayList(); - - private Integer selectedIndex = null; - private Integer defaultIndex = null; - private String prompt = "Language"; - - public LocaleCallback(Integer defaultIndex, List availableLocales) { - this.availableLocales = Collections - .unmodifiableList(new ArrayList(availableLocales)); - this.defaultIndex = defaultIndex; - this.selectedIndex = defaultIndex; - } - - /** - * Convenience constructor based on a comma separated list of iso codes (en, - * en_US, fr_CA, etc.). Default selection is default locale. - */ - public LocaleCallback(String locales) { - if (locales == null || locales.trim().equals("")) - return; - String[] codes = locales.split(","); - for (int i = 0; i < codes.length; i++) { - String code = codes[i]; - // variant not supported - int indexUnd = code.indexOf("_"); - Locale locale; - if (indexUnd > 0) { - String language = code.substring(0, indexUnd); - String country = code.substring(indexUnd + 1); - locale = new Locale(language, country); - } else { - locale = new Locale(code); - } - availableLocales.add(locale); - if (locale.equals(Locale.getDefault())) - defaultIndex = i; - } - - if (defaultIndex == null) - defaultIndex = 0; - - this.selectedIndex = defaultIndex; - } - - public String[] getSupportedLocalesLabels() { - String[] labels = new String[availableLocales.size()]; - for (int i = 0; i < availableLocales.size(); i++) { - Locale locale = availableLocales.get(i); - if (locale.getCountry().equals("")) - labels[i] = locale.getDisplayLanguage(locale) + " [" - + locale.getLanguage() + "]"; - else - labels[i] = locale.getDisplayLanguage(locale) + " (" - + locale.getDisplayCountry(locale) + ") [" - + locale.getLanguage() + "_" + locale.getCountry() - + "]"; - - } - return labels; - } - - public Locale getSelectedLocale() { - if (selectedIndex == null) - return null; - return availableLocales.get(selectedIndex); - } - - public void setSelectedIndex(Integer selectedIndex) { - this.selectedIndex = selectedIndex; - } - - public Integer getDefaultIndex() { - return defaultIndex; - } - - public String getPrompt() { - // TODO localize it? - return prompt; - } - - public void setPrompt(String prompt) { - this.prompt = prompt; - } - - public List getAvailableLocales() { - return availableLocales; - } - - public static void main(String[] args) { - for (String isoL : Locale.getISOLanguages()) { - Locale locale = new Locale(isoL); - System.out.println(isoL + "\t" + locale.getDisplayLanguage() + "\t" - + locale.getDisplayLanguage(locale)); - } - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/LocaleUtils.java b/org.argeo.util/src/main/java/org/argeo/util/LocaleUtils.java deleted file mode 100644 index bc04afa75..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/LocaleUtils.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.util.Locale; - -import org.argeo.ArgeoException; - -/** Utilities around internationalization. */ -public class LocaleUtils { - /** - * The locale of the current thread and its children. Allows to deal with - * internationalisation as a cross cutting aspect. Never null. - */ - public final static InheritableThreadLocal threadLocale = new InheritableThreadLocal() { - @Override - protected Locale initialValue() { - return Locale.getDefault(); - } - - @Override - public void set(Locale value) { - if (value == null) - throw new ArgeoException("Thread local cannot be null."); - super.set(value); - } - - }; -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/Throughput.java b/org.argeo.util/src/main/java/org/argeo/util/Throughput.java deleted file mode 100644 index d081189e2..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/Throughput.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -import org.argeo.ArgeoException; - -public class Throughput { - private final static NumberFormat usNumberFormat = NumberFormat - .getInstance(Locale.US); - - public enum Unit { - s, m, h, d - } - - private final Double value; - private final Unit unit; - - public Throughput(Double value, Unit unit) { - this.value = value; - this.unit = unit; - } - - public Throughput(Long periodMs, Long count, Unit unit) { - if (unit.equals(Unit.s)) - value = ((double) count * 1000d) / periodMs; - else if (unit.equals(Unit.m)) - value = ((double) count * 60d * 1000d) / periodMs; - else if (unit.equals(Unit.h)) - value = ((double) count * 60d * 60d * 1000d) / periodMs; - else if (unit.equals(Unit.d)) - value = ((double) count * 24d * 60d * 60d * 1000d) / periodMs; - else - throw new ArgeoException("Unsupported unit " + unit); - this.unit = unit; - } - - public Throughput(Double value, String unitStr) { - this(value, Unit.valueOf(unitStr)); - } - - public Throughput(String def) { - int index = def.indexOf('/'); - if (def.length() < 3 || index <= 0 || index != def.length() - 2) - throw new ArgeoException(def + " no a proper throughput definition" - + " (should be /, e.g. 3.54/s or 1500/h"); - String valueStr = def.substring(0, index); - String unitStr = def.substring(index + 1); - try { - this.value = usNumberFormat.parse(valueStr).doubleValue(); - } catch (ParseException e) { - throw new ArgeoException("Cannot parse " + valueStr - + " as a number.", e); - } - this.unit = Unit.valueOf(unitStr); - } - - public Long asMsPeriod() { - if (unit.equals(Unit.s)) - return Math.round(1000d / value); - else if (unit.equals(Unit.m)) - return Math.round((60d * 1000d) / value); - else if (unit.equals(Unit.h)) - return Math.round((60d * 60d * 1000d) / value); - else if (unit.equals(Unit.d)) - return Math.round((24d * 60d * 60d * 1000d) / value); - else - throw new ArgeoException("Unsupported unit " + unit); - } - - @Override - public String toString() { - return usNumberFormat.format(value) + '/' + unit; - } - - public Double getValue() { - return value; - } - - public Unit getUnit() { - return unit; - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/ThroughputEditor.java b/org.argeo.util/src/main/java/org/argeo/util/ThroughputEditor.java deleted file mode 100644 index 4ebf26b81..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/ThroughputEditor.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.beans.PropertyEditorSupport; - -public class ThroughputEditor extends PropertyEditorSupport { - - @Override - public String getAsText() { - return getValue().toString(); - } - - @Override - public void setAsText(String text) throws IllegalArgumentException { - setValue(new Throughput(text)); - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/security/DigestUtils.java b/org.argeo.util/src/main/java/org/argeo/util/security/DigestUtils.java deleted file mode 100644 index b6aae6fd4..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/security/DigestUtils.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.security; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import org.argeo.ArgeoException; -import org.argeo.StreamUtils; - -/** Utilities around cryptographic digests */ -public class DigestUtils { - private static Boolean debug = true; - // TODO: make it writable - private final static Integer byteBufferCapacity = 100 * 1024;// 100 KB - - public static String digest(String algorithm, byte[] bytes) { - try { - MessageDigest digest = MessageDigest.getInstance(algorithm); - digest.update(bytes); - byte[] checksum = digest.digest(); - String res = StreamUtils.encodeHexString(checksum); - return res; - } catch (Exception e) { - throw new ArgeoException("Cannot digest with algorithm " - + algorithm, e); - } - } - - public static String digest(String algorithm, InputStream in) { - try { - MessageDigest digest = MessageDigest.getInstance(algorithm); - // ReadableByteChannel channel = Channels.newChannel(in); - // ByteBuffer bb = ByteBuffer.allocateDirect(byteBufferCapacity); - // while (channel.read(bb) > 0) - // digest.update(bb); - byte[] buffer = new byte[byteBufferCapacity]; - int read = 0; - while ((read = in.read(buffer)) > 0) { - digest.update(buffer, 0, read); - } - - byte[] checksum = digest.digest(); - String res = StreamUtils.encodeHexString(checksum); - return res; - } catch (Exception e) { - throw new ArgeoException("Cannot digest with algorithm " - + algorithm, e); - } finally { - StreamUtils.closeQuietly(in); - } - } - - public static String digest(String algorithm, File file) { - FileInputStream fis = null; - FileChannel fc = null; - try { - fis = new FileInputStream(file); - fc = fis.getChannel(); - - // Get the file's size and then map it into memory - int sz = (int) fc.size(); - ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); - return digest(algorithm, bb); - } catch (IOException e) { - throw new ArgeoException("Cannot digest " + file - + " with algorithm " + algorithm, e); - } finally { - StreamUtils.closeQuietly(fis); - if (fc.isOpen()) - try { - fc.close(); - } catch (IOException e) { - // silent - } - } - } - - protected static String digest(String algorithm, ByteBuffer bb) { - long begin = System.currentTimeMillis(); - try { - MessageDigest digest = MessageDigest.getInstance(algorithm); - digest.update(bb); - byte[] checksum = digest.digest(); - String res = StreamUtils.encodeHexString(checksum); - long end = System.currentTimeMillis(); - if (debug) - System.out.println((end - begin) + " ms / " - + ((end - begin) / 1000) + " s"); - return res; - } catch (NoSuchAlgorithmException e) { - throw new ArgeoException("Cannot digest with algorithm " - + algorithm, e); - } - } - - public static void main(String[] args) { - File file; - if (args.length > 0) - file = new File(args[0]); - else { - System.err.println("Usage: []" - + " (see http://java.sun.com/j2se/1.5.0/" - + "docs/guide/security/CryptoSpec.html#AppA)"); - return; - } - - if (args.length > 1) { - String algorithm = args[1]; - System.out.println(digest(algorithm, file)); - } else { - String algorithm = "MD5"; - System.out.println(algorithm + ": " + digest(algorithm, file)); - algorithm = "SHA"; - System.out.println(algorithm + ": " + digest(algorithm, file)); - algorithm = "SHA-256"; - System.out.println(algorithm + ": " + digest(algorithm, file)); - algorithm = "SHA-512"; - System.out.println(algorithm + ": " + digest(algorithm, file)); - } - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/security/Keyring.java b/org.argeo.util/src/main/java/org/argeo/util/security/Keyring.java deleted file mode 100644 index 10dbabd49..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/security/Keyring.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.security; - -import java.io.InputStream; - -/** - * Access to private (typically encrypted) data. The keyring is responsible for - * retrieving the necessary credentials. Experimental. This API may - * change. - */ -public interface Keyring { - public void changePassword(char[] oldPassword, char[] newPassword); - - /** - * Returns the confidential information as chars. Must ask for it if it is - * not stored. - */ - public char[] getAsChars(String path); - - /** - * Returns the confidential information as a stream. Must ask for it if it - * is not stored. - */ - public InputStream getAsStream(String path); - - public void set(String path, char[] arr); - - public void set(String path, InputStream in); -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/security/SimplePrincipal.java b/org.argeo.util/src/main/java/org/argeo/util/security/SimplePrincipal.java deleted file mode 100644 index c7a4daf12..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/security/SimplePrincipal.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.security; - -import java.security.Principal; - -import org.argeo.ArgeoException; - -/** Canonical implementation of a {@link Principal} */ -public class SimplePrincipal implements Principal { - private final String name; - - public SimplePrincipal(String name) { - if (name == null) - throw new ArgeoException("Principal name cannot be null"); - this.name = name; - } - - public String getName() { - return name; - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - return name.equals(obj.toString()); - } - - @Override - protected Object clone() throws CloneNotSupportedException { - return new SimplePrincipal(name); - } - - @Override - public String toString() { - return name; - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/tabular/ArrayTabularRow.java b/org.argeo.util/src/main/java/org/argeo/util/tabular/ArrayTabularRow.java deleted file mode 100644 index b1672e94c..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/tabular/ArrayTabularRow.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.tabular; - -import java.util.List; - -/** Minimal tabular row wrapping an {@link Object} array */ -public class ArrayTabularRow implements TabularRow { - private final Object[] arr; - - public ArrayTabularRow(List objs) { - this.arr = objs.toArray(); - } - - public Object get(Integer col) { - return arr[col]; - } - - public int size() { - return arr.length; - } - - public Object[] toArray() { - return arr; - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/tabular/CsvTabularWriter.java b/org.argeo.util/src/main/java/org/argeo/util/tabular/CsvTabularWriter.java deleted file mode 100644 index 8f5c52dca..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/tabular/CsvTabularWriter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.tabular; - -import java.io.OutputStream; - -import org.argeo.util.CsvWriter; - -/** Write tabular content in a stream as CSV. Wraps a {@link CsvWriter}. */ -public class CsvTabularWriter implements TabularWriter { - private CsvWriter csvWriter; - - public CsvTabularWriter(OutputStream out) { - this.csvWriter = new CsvWriter(out); - } - - public void appendRow(Object[] row) { - csvWriter.writeLine(row); - } - - public void close() { - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularColumn.java b/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularColumn.java deleted file mode 100644 index a5ee32f27..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularColumn.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.tabular; - -/** The column in a tabular content */ -public class TabularColumn { - private String name; - /** - * JCR types, see - * http://www.day.com/maven/javax.jcr/javadocs/jcr-2.0/index.html - * ?javax/jcr/PropertyType.html - */ - private Integer type; - - /** column with default type */ - public TabularColumn(String name) { - super(); - this.name = name; - } - - public TabularColumn(String name, Integer type) { - super(); - this.name = name; - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getType() { - return type; - } - - public void setType(Integer type) { - this.type = type; - } - -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularContent.java b/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularContent.java deleted file mode 100644 index a2da86668..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularContent.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.tabular; - -import java.util.List; - -/** - * Content organized as a table, possibly with headers. Only JCR types are - * supported even though there is not direct dependency on JCR. - */ -public interface TabularContent { - /** The headers of this table or null is none available. */ - public List getColumns(); - - public TabularRowIterator read(); -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularRow.java b/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularRow.java deleted file mode 100644 index 05b8a40a9..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularRow.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.tabular; - -/** A row of tabular data */ -public interface TabularRow { - /** The value at this column index */ - public Object get(Integer col); - - /** The raw objects (direct references) */ - public Object[] toArray(); - - /** Number of columns */ - public int size(); -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularRowIterator.java b/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularRowIterator.java deleted file mode 100644 index 043463dd7..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularRowIterator.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.tabular; - -import java.util.Iterator; - -/** Navigation of rows */ -public interface TabularRowIterator extends Iterator { - /** - * Current row number, has to be incremented by each call to next() ; starts at 0, will - * therefore be 1 for the first row returned. - */ - public Long getCurrentRowNumber(); -} diff --git a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularWriter.java b/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularWriter.java deleted file mode 100644 index 20d6519fa..000000000 --- a/org.argeo.util/src/main/java/org/argeo/util/tabular/TabularWriter.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util.tabular; - - -/** Write to a tabular content */ -public interface TabularWriter { - /** Append a new row of data */ - public void appendRow(Object[] row); - - /** Finish persisting data and release resources */ - public void close(); -} diff --git a/org.argeo.util/src/org/argeo/ArgeoException.java b/org.argeo.util/src/org/argeo/ArgeoException.java new file mode 100644 index 000000000..9cf918667 --- /dev/null +++ b/org.argeo.util/src/org/argeo/ArgeoException.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo; + +/** Argeo Commons specific exception. */ +public class ArgeoException extends RuntimeException { + private static final long serialVersionUID = 1L; + + /** Creates an exception with a message. */ + public ArgeoException(String message) { + super(message); + } + + /** Creates an exception with a message and a root cause. */ + public ArgeoException(String message, Throwable e) { + super(message, e); + } + + /** + * Chain the messages of all causes (one per line, starts with a line + * return) without all the stack + */ + public static String chainCausesMessages(Throwable t) { + StringBuffer buf = new StringBuffer(); + chainCauseMessage(buf, t); + return buf.toString(); + } + + /** Recursive chaining of messages */ + private static void chainCauseMessage(StringBuffer buf, Throwable t) { + buf.append('\n').append(' ').append(t.getClass().getCanonicalName()) + .append(": ").append(t.getMessage()); + if (t.getCause() != null) + chainCauseMessage(buf, t.getCause()); + } +} diff --git a/org.argeo.util/src/org/argeo/ArgeoLogListener.java b/org.argeo.util/src/org/argeo/ArgeoLogListener.java new file mode 100644 index 000000000..bac8a9820 --- /dev/null +++ b/org.argeo.util/src/org/argeo/ArgeoLogListener.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo; + +/** Framework agnostic interface for log notifications */ +public interface ArgeoLogListener { + /** + * Appends a log + * + * @param username + * authentified user, null for anonymous + * @param level + * INFO, DEBUG, WARN, etc. (logging framework specific) + * @param category + * hierarchy (logging framework specific) + * @param thread + * name of the thread which logged this message + * @param msg + * any object as long as its toString() method returns the + * message + * @param the + * exception in log4j ThrowableStrRep format + */ + public void appendLog(String username, Long timestamp, String level, + String category, String thread, Object msg, String[] exception); +} diff --git a/org.argeo.util/src/org/argeo/ArgeoLogger.java b/org.argeo.util/src/org/argeo/ArgeoLogger.java new file mode 100644 index 000000000..0657c29dd --- /dev/null +++ b/org.argeo.util/src/org/argeo/ArgeoLogger.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo; + +/** + * Logging framework agnostic identifying a logging service, to which one can + * register + */ +public interface ArgeoLogger { + /** + * Register for events by threads with the same authentication (or all + * threads if admin) + */ + public void register(ArgeoLogListener listener, + Integer numberOfPreviousEvents); + + /** + * For admin use only: register for all users + * + * @param listener + * the log listener + * @param numberOfPreviousEvents + * the number of previous events to notify + * @param everything + * if true even anonymous is logged + */ + public void registerForAll(ArgeoLogListener listener, + Integer numberOfPreviousEvents, boolean everything); + + public void unregister(ArgeoLogListener listener); + + public void unregisterForAll(ArgeoLogListener listener); +} diff --git a/org.argeo.util/src/org/argeo/ArgeoMonitor.java b/org.argeo.util/src/org/argeo/ArgeoMonitor.java new file mode 100644 index 000000000..9ef23cc8b --- /dev/null +++ b/org.argeo.util/src/org/argeo/ArgeoMonitor.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo; + +/** + * Simple monitor abstraction. Inspired by Eclipse IProgressMOnitor, but without + * dependency to it. + */ +public interface ArgeoMonitor { + /** + * Constant indicating an unknown amount of work. + */ + public final static int UNKNOWN = -1; + + /** + * Notifies that the main task is beginning. This must only be called once + * on a given progress monitor instance. + * + * @param name + * the name (or description) of the main task + * @param totalWork + * the total number of work units into which the main task is + * been subdivided. If the value is UNKNOWN the + * implementation is free to indicate progress in a way which + * doesn't require the total number of work units in advance. + */ + public void beginTask(String name, int totalWork); + + /** + * Notifies that the work is done; that is, either the main task is + * completed or the user canceled it. This method may be called more than + * once (implementations should be prepared to handle this case). + */ + public void done(); + + /** + * Returns whether cancelation of current operation has been requested. + * Long-running operations should poll to see if cancelation has been + * requested. + * + * @return true if cancellation has been requested, and + * false otherwise + * @see #setCanceled(boolean) + */ + public boolean isCanceled(); + + /** + * Sets the cancel state to the given value. + * + * @param value + * true indicates that cancelation has been + * requested (but not necessarily acknowledged); + * false clears this flag + * @see #isCanceled() + */ + public void setCanceled(boolean value); + + /** + * Sets the task name to the given value. This method is used to restore the + * task label after a nested operation was executed. Normally there is no + * need for clients to call this method. + * + * @param name + * the name (or description) of the main task + * @see #beginTask(java.lang.String, int) + */ + public void setTaskName(String name); + + /** + * Notifies that a subtask of the main task is beginning. Subtasks are + * optional; the main task might not have subtasks. + * + * @param name + * the name (or description) of the subtask + */ + public void subTask(String name); + + /** + * Notifies that a given number of work unit of the main task has been + * completed. Note that this amount represents an installment, as opposed to + * a cumulative amount of work done to date. + * + * @param work + * a non-negative number of work units just completed + */ + public void worked(int work); + +} diff --git a/org.argeo.util/src/org/argeo/OperatingSystem.java b/org.argeo.util/src/org/argeo/OperatingSystem.java new file mode 100644 index 000000000..697c86c51 --- /dev/null +++ b/org.argeo.util/src/org/argeo/OperatingSystem.java @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo; + +/** The current operating system. */ +public class OperatingSystem { + public final static int NIX = 1; + public final static int WINDOWS = 2; + public final static int SOLARIS = 3; + + public final static int os; + static { + String osName = System.getProperty("os.name"); + if (osName.startsWith("Win")) + os = WINDOWS; + else if (osName.startsWith("Solaris")) + os = SOLARIS; + else + os = NIX; + } + +} diff --git a/org.argeo.util/src/org/argeo/StreamUtils.java b/org.argeo.util/src/org/argeo/StreamUtils.java new file mode 100644 index 000000000..39caaddda --- /dev/null +++ b/org.argeo.util/src/org/argeo/StreamUtils.java @@ -0,0 +1,183 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; + +/** Utilities to be used when APache COmmons IO is not available. */ +public class StreamUtils { + private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; + + /* + * APACHE COMMONS IO (inspired) + */ + + /** @return the number of bytes */ + public static Long copy(InputStream in, OutputStream out) + throws IOException { + Long count = 0l; + byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; + while (true) { + int length = in.read(buf); + if (length < 0) + break; + out.write(buf, 0, length); + count = count + length; + } + return count; + } + + /** @return the number of chars */ + public static Long copy(Reader in, Writer out) throws IOException { + Long count = 0l; + char[] buf = new char[DEFAULT_BUFFER_SIZE]; + while (true) { + int length = in.read(buf); + if (length < 0) + break; + out.write(buf, 0, length); + count = count + length; + } + return count; + } + + public static void closeQuietly(InputStream in) { + if (in != null) + try { + in.close(); + } catch (Exception e) { + // + } + } + + public static void closeQuietly(OutputStream out) { + if (out != null) + try { + out.close(); + } catch (Exception e) { + // + } + } + + public static void closeQuietly(Reader in) { + if (in != null) + try { + in.close(); + } catch (Exception e) { + // + } + } + + public static void closeQuietly(Writer out) { + if (out != null) + try { + out.close(); + } catch (Exception e) { + // + } + } + + /* + * APACHE COMMONS CODEC (forked) + */ + /** + * Used to build output as Hex + */ + private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + + /** + * Used to build output as Hex + */ + private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + + /** + * Converts an array of bytes into a String representing the hexadecimal + * values of each byte in order. The returned String will be double the + * length of the passed array, as it takes two characters to represent any + * given byte. + * + * @param data + * a byte[] to convert to Hex characters + * @return A String containing hexadecimal characters + * @since 1.4 + */ + public static String encodeHexString(byte[] data) { + return new String(encodeHex(data)); + } + + /** + * Converts an array of bytes into an array of characters representing the + * hexadecimal values of each byte in order. The returned array will be + * double the length of the passed array, as it takes two characters to + * represent any given byte. + * + * @param data + * a byte[] to convert to Hex characters + * @return A char[] containing hexadecimal characters + */ + public static char[] encodeHex(byte[] data) { + return encodeHex(data, true); + } + + /** + * Converts an array of bytes into an array of characters representing the + * hexadecimal values of each byte in order. The returned array will be + * double the length of the passed array, as it takes two characters to + * represent any given byte. + * + * @param data + * a byte[] to convert to Hex characters + * @param toLowerCase + * true converts to lowercase, false to + * uppercase + * @return A char[] containing hexadecimal characters + * @since 1.4 + */ + public static char[] encodeHex(byte[] data, boolean toLowerCase) { + return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); + } + + /** + * Converts an array of bytes into an array of characters representing the + * hexadecimal values of each byte in order. The returned array will be + * double the length of the passed array, as it takes two characters to + * represent any given byte. + * + * @param data + * a byte[] to convert to Hex characters + * @param toDigits + * the output alphabet + * @return A char[] containing hexadecimal characters + * @since 1.4 + */ + protected static char[] encodeHex(byte[] data, char[] toDigits) { + int l = data.length; + char[] out = new char[l << 1]; + // two characters form the hex value. + for (int i = 0, j = 0; i < l; i++) { + out[j++] = toDigits[(0xF0 & data[i]) >>> 4]; + out[j++] = toDigits[0x0F & data[i]]; + } + return out; + } + +} diff --git a/org.argeo.util/src/org/argeo/util/CsvParser.java b/org.argeo.util/src/org/argeo/util/CsvParser.java new file mode 100644 index 000000000..7680b3267 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/CsvParser.java @@ -0,0 +1,235 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.argeo.ArgeoException; +import org.argeo.StreamUtils; + +/** + * Parses a CSV file interpreting the first line as a header. The + * {@link #parse(InputStream)} method and the setters are synchronized so that + * the object cannot be modified when parsing. + */ +public abstract class CsvParser { + private char separator = ','; + private char quote = '\"'; + + private Boolean noHeader = false; + private Boolean strictLineAsLongAsHeader = true; + + /** + * Actually process a parsed line. If + * {@link #setStrictLineAsLongAsHeader(Boolean)} is true (default) the + * header and the tokens are guaranteed to have the same size. + * + * @param lineNumber + * the current line number, starts at 1 (the header, if header + * processing is enabled, the first line otherwise) + * @param header + * the read-only header or null if {@link #setNoHeader(Boolean)} + * is true (default is false) + * @param tokens + * the parsed tokens + */ + protected abstract void processLine(Integer lineNumber, + List header, List tokens); + + /** + * Parses the CSV file (stream is closed at the end) + */ + public synchronized void parse(InputStream in) { + parse(in, null); + } + + /** + * Parses the CSV file (stream is closed at the end) + */ + public synchronized void parse(InputStream in, String encoding) { + BufferedReader reader = null; + Integer lineCount = 0; + try { + if (encoding == null) + reader = new BufferedReader(new InputStreamReader(in)); + else + reader = new BufferedReader(new InputStreamReader(in, encoding)); + List header = null; + if (!noHeader) { + String headerStr = reader.readLine(); + if (headerStr == null)// empty file + return; + lineCount++; + header = new ArrayList(); + StringBuffer currStr = new StringBuffer(""); + Boolean wasInquote = false; + while (parseLine(headerStr, header, currStr, wasInquote)) { + headerStr = reader.readLine(); + if (headerStr == null) + break; + wasInquote = true; + } + header = Collections.unmodifiableList(header); + } + + String line = null; + lines: while ((line = reader.readLine()) != null) { + line = preProcessLine(line); + if (line == null) { + // skip line + continue lines; + } + lineCount++; + List tokens = new ArrayList(); + StringBuffer currStr = new StringBuffer(""); + Boolean wasInquote = false; + sublines: while (parseLine(line, tokens, currStr, wasInquote)) { + line = reader.readLine(); + if (line == null) + break sublines; + wasInquote = true; + } + if (!noHeader && strictLineAsLongAsHeader) { + int headerSize = header.size(); + int tokenSize = tokens.size(); + if (tokenSize == 1 && line.trim().equals("")) + continue lines;// empty line + if (headerSize != tokenSize) { + throw new ArgeoException("Token size " + tokenSize + + " is different from header size " + + headerSize + " at line " + lineCount + + ", line: " + line + ", header: " + header + + ", tokens: " + tokens); + } + } + processLine(lineCount, header, tokens); + } + } catch (ArgeoException e) { + throw e; + } catch (IOException e) { + throw new ArgeoException("Cannot parse CSV file (line: " + + lineCount + ")", e); + } finally { + StreamUtils.closeQuietly(reader); + } + } + + /** + * Called before each (logical) line is processed, giving a change to modify + * it (typically for cleaning dirty files). To be overridden, return the + * line unchanged by default. Skip the line if 'null' is returned. + */ + protected String preProcessLine(String line) { + return line; + } + + /** + * Parses a line character by character for performance purpose + * + * @return whether to continue parsing this line + */ + protected Boolean parseLine(String str, List tokens, + StringBuffer currStr, Boolean wasInquote) { + // List tokens = new ArrayList(); + + // System.out.println("#LINE: " + str); + + if (wasInquote) + currStr.append('\n'); + + char[] arr = str.toCharArray(); + boolean inQuote = wasInquote; + // StringBuffer currStr = new StringBuffer(""); + for (int i = 0; i < arr.length; i++) { + char c = arr[i]; + if (c == separator) { + if (!inQuote) { + tokens.add(currStr.toString()); + // System.out.println("# TOKEN: " + currStr); + currStr.delete(0, currStr.length()); + } else { + // we don't remove separator that are in a quoted substring + // System.out + // .println("IN QUOTE, got a separator: [" + c + "]"); + currStr.append(c); + } + } else if (c == quote) { + if (inQuote && (i + 1) < arr.length && arr[i + 1] == quote) { + // case of double quote + currStr.append(quote); + i++; + } else {// standard + inQuote = inQuote ? false : true; + } + } else { + currStr.append(c); + } + } + + if (!inQuote) { + tokens.add(currStr.toString()); + // System.out.println("# TOKEN: " + currStr); + } + // if (inQuote) + // throw new ArgeoException("Missing quote at the end of the line " + // + str + " (parsed: " + tokens + ")"); + if (inQuote) + return true; + else + return false; + // return tokens; + } + + public char getSeparator() { + return separator; + } + + public synchronized void setSeparator(char separator) { + this.separator = separator; + } + + public char getQuote() { + return quote; + } + + public synchronized void setQuote(char quote) { + this.quote = quote; + } + + public Boolean getNoHeader() { + return noHeader; + } + + public synchronized void setNoHeader(Boolean noHeader) { + this.noHeader = noHeader; + } + + public Boolean getStrictLineAsLongAsHeader() { + return strictLineAsLongAsHeader; + } + + public synchronized void setStrictLineAsLongAsHeader( + Boolean strictLineAsLongAsHeader) { + this.strictLineAsLongAsHeader = strictLineAsLongAsHeader; + } + +} diff --git a/org.argeo.util/src/org/argeo/util/CsvParserWithLinesAsMap.java b/org.argeo.util/src/org/argeo/util/CsvParserWithLinesAsMap.java new file mode 100644 index 000000000..e7baabbf0 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/CsvParserWithLinesAsMap.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.argeo.ArgeoException; + +/** + * CSV parser allowing to process lines as maps whose keys are the header + * fields. + */ +public abstract class CsvParserWithLinesAsMap extends CsvParser { + + /** + * Actually processes a line. + * + * @param lineNumber + * the current line number, starts at 1 (the header, if header + * processing is enabled, the first lien otherwise) + * @param line + * the parsed tokens as a map whose keys are the header fields + */ + protected abstract void processLine(Integer lineNumber, + Map line); + + protected final void processLine(Integer lineNumber, List header, + List tokens) { + if (header == null) + throw new ArgeoException("Only CSV with header is supported"); + Map line = new HashMap(); + for (int i = 0; i < header.size(); i++) { + String key = header.get(i); + String value = null; + if (i < tokens.size()) + value = tokens.get(i); + line.put(key, value); + } + processLine(lineNumber, line); + } + +} diff --git a/org.argeo.util/src/org/argeo/util/CsvWriter.java b/org.argeo.util/src/org/argeo/util/CsvWriter.java new file mode 100644 index 000000000..d90f47412 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/CsvWriter.java @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.util.Iterator; +import java.util.List; + +import org.argeo.ArgeoException; + +/** Write in CSV format. */ +public class CsvWriter { + private final Writer out; + + private char separator = ','; + private char quote = '\"'; + + /** + * Creates a CSV writer. + * + * @param out + * the stream to write to. Caller is responsible for closing it. + */ + public CsvWriter(OutputStream out) { + this.out = new OutputStreamWriter(out); + } + + /** + * Creates a CSV writer. + * + * @param out + * the stream to write to. Caller is responsible for closing it. + */ + public CsvWriter(OutputStream out, String encoding) { + try { + this.out = new OutputStreamWriter(out, encoding); + } catch (UnsupportedEncodingException e) { + throw new ArgeoException("Cannot initialize CSV writer", e); + } + } + + /** + * Write a CSV line. Also used to write a header if needed (this is + * transparent for the CSV writer): simply call it first, before writing the + * lines. + */ + public void writeLine(List tokens) { + try { + Iterator it = tokens.iterator(); + while (it.hasNext()) { + writeToken(it.next().toString()); + if (it.hasNext()) + out.write(separator); + } + out.write('\n'); + out.flush(); + } catch (IOException e) { + throw new ArgeoException("Could not write " + tokens, e); + } + } + + /** + * Write a CSV line. Also used to write a header if needed (this is + * transparent for the CSV writer): simply call it first, before writing the + * lines. + */ + public void writeLine(Object[] tokens) { + try { + for (int i = 0; i < tokens.length; i++) { + if (tokens[i] == null) { + // TODO configure how to deal with null + writeToken(""); + } else { + writeToken(tokens[i].toString()); + } + if (i != (tokens.length - 1)) + out.write(separator); + } + out.write('\n'); + out.flush(); + } catch (IOException e) { + throw new ArgeoException("Could not write " + tokens, e); + } + } + + protected void writeToken(String token) throws IOException { + // +2 for possible quotes, another +2 assuming there would be an already + // quoted string where quotes needs to be duplicated + // another +2 for safety + // we don't want to increase buffer size while writing + StringBuffer buf = new StringBuffer(token.length() + 6); + char[] arr = token.toCharArray(); + boolean shouldQuote = false; + for (char c : arr) { + if (!shouldQuote) { + if (c == separator) + shouldQuote = true; + if (c == '\n') + shouldQuote = true; + } + + if (c == quote) { + shouldQuote = true; + // duplicate quote + buf.append(quote); + } + + // generic case + buf.append(c); + } + + if (shouldQuote == true) + out.write(quote); + out.write(buf.toString()); + if (shouldQuote == true) + out.write(quote); + } + + public void setSeparator(char separator) { + this.separator = separator; + } + + public void setQuote(char quote) { + this.quote = quote; + } + +} diff --git a/org.argeo.util/src/org/argeo/util/LocaleCallback.java b/org.argeo.util/src/org/argeo/util/LocaleCallback.java new file mode 100644 index 000000000..60bf4c40f --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/LocaleCallback.java @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +import javax.security.auth.callback.Callback; + +/** Choose in a list of locales */ +public class LocaleCallback implements Callback { + private List availableLocales = new ArrayList(); + + private Integer selectedIndex = null; + private Integer defaultIndex = null; + private String prompt = "Language"; + + public LocaleCallback(Integer defaultIndex, List availableLocales) { + this.availableLocales = Collections + .unmodifiableList(new ArrayList(availableLocales)); + this.defaultIndex = defaultIndex; + this.selectedIndex = defaultIndex; + } + + /** + * Convenience constructor based on a comma separated list of iso codes (en, + * en_US, fr_CA, etc.). Default selection is default locale. + */ + public LocaleCallback(String locales) { + if (locales == null || locales.trim().equals("")) + return; + String[] codes = locales.split(","); + for (int i = 0; i < codes.length; i++) { + String code = codes[i]; + // variant not supported + int indexUnd = code.indexOf("_"); + Locale locale; + if (indexUnd > 0) { + String language = code.substring(0, indexUnd); + String country = code.substring(indexUnd + 1); + locale = new Locale(language, country); + } else { + locale = new Locale(code); + } + availableLocales.add(locale); + if (locale.equals(Locale.getDefault())) + defaultIndex = i; + } + + if (defaultIndex == null) + defaultIndex = 0; + + this.selectedIndex = defaultIndex; + } + + public String[] getSupportedLocalesLabels() { + String[] labels = new String[availableLocales.size()]; + for (int i = 0; i < availableLocales.size(); i++) { + Locale locale = availableLocales.get(i); + if (locale.getCountry().equals("")) + labels[i] = locale.getDisplayLanguage(locale) + " [" + + locale.getLanguage() + "]"; + else + labels[i] = locale.getDisplayLanguage(locale) + " (" + + locale.getDisplayCountry(locale) + ") [" + + locale.getLanguage() + "_" + locale.getCountry() + + "]"; + + } + return labels; + } + + public Locale getSelectedLocale() { + if (selectedIndex == null) + return null; + return availableLocales.get(selectedIndex); + } + + public void setSelectedIndex(Integer selectedIndex) { + this.selectedIndex = selectedIndex; + } + + public Integer getDefaultIndex() { + return defaultIndex; + } + + public String getPrompt() { + // TODO localize it? + return prompt; + } + + public void setPrompt(String prompt) { + this.prompt = prompt; + } + + public List getAvailableLocales() { + return availableLocales; + } + + public static void main(String[] args) { + for (String isoL : Locale.getISOLanguages()) { + Locale locale = new Locale(isoL); + System.out.println(isoL + "\t" + locale.getDisplayLanguage() + "\t" + + locale.getDisplayLanguage(locale)); + } + } + +} diff --git a/org.argeo.util/src/org/argeo/util/LocaleUtils.java b/org.argeo.util/src/org/argeo/util/LocaleUtils.java new file mode 100644 index 000000000..bc04afa75 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/LocaleUtils.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.util.Locale; + +import org.argeo.ArgeoException; + +/** Utilities around internationalization. */ +public class LocaleUtils { + /** + * The locale of the current thread and its children. Allows to deal with + * internationalisation as a cross cutting aspect. Never null. + */ + public final static InheritableThreadLocal threadLocale = new InheritableThreadLocal() { + @Override + protected Locale initialValue() { + return Locale.getDefault(); + } + + @Override + public void set(Locale value) { + if (value == null) + throw new ArgeoException("Thread local cannot be null."); + super.set(value); + } + + }; +} diff --git a/org.argeo.util/src/org/argeo/util/Throughput.java b/org.argeo.util/src/org/argeo/util/Throughput.java new file mode 100644 index 000000000..d081189e2 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/Throughput.java @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.Locale; + +import org.argeo.ArgeoException; + +public class Throughput { + private final static NumberFormat usNumberFormat = NumberFormat + .getInstance(Locale.US); + + public enum Unit { + s, m, h, d + } + + private final Double value; + private final Unit unit; + + public Throughput(Double value, Unit unit) { + this.value = value; + this.unit = unit; + } + + public Throughput(Long periodMs, Long count, Unit unit) { + if (unit.equals(Unit.s)) + value = ((double) count * 1000d) / periodMs; + else if (unit.equals(Unit.m)) + value = ((double) count * 60d * 1000d) / periodMs; + else if (unit.equals(Unit.h)) + value = ((double) count * 60d * 60d * 1000d) / periodMs; + else if (unit.equals(Unit.d)) + value = ((double) count * 24d * 60d * 60d * 1000d) / periodMs; + else + throw new ArgeoException("Unsupported unit " + unit); + this.unit = unit; + } + + public Throughput(Double value, String unitStr) { + this(value, Unit.valueOf(unitStr)); + } + + public Throughput(String def) { + int index = def.indexOf('/'); + if (def.length() < 3 || index <= 0 || index != def.length() - 2) + throw new ArgeoException(def + " no a proper throughput definition" + + " (should be /, e.g. 3.54/s or 1500/h"); + String valueStr = def.substring(0, index); + String unitStr = def.substring(index + 1); + try { + this.value = usNumberFormat.parse(valueStr).doubleValue(); + } catch (ParseException e) { + throw new ArgeoException("Cannot parse " + valueStr + + " as a number.", e); + } + this.unit = Unit.valueOf(unitStr); + } + + public Long asMsPeriod() { + if (unit.equals(Unit.s)) + return Math.round(1000d / value); + else if (unit.equals(Unit.m)) + return Math.round((60d * 1000d) / value); + else if (unit.equals(Unit.h)) + return Math.round((60d * 60d * 1000d) / value); + else if (unit.equals(Unit.d)) + return Math.round((24d * 60d * 60d * 1000d) / value); + else + throw new ArgeoException("Unsupported unit " + unit); + } + + @Override + public String toString() { + return usNumberFormat.format(value) + '/' + unit; + } + + public Double getValue() { + return value; + } + + public Unit getUnit() { + return unit; + } + +} diff --git a/org.argeo.util/src/org/argeo/util/ThroughputEditor.java b/org.argeo.util/src/org/argeo/util/ThroughputEditor.java new file mode 100644 index 000000000..4ebf26b81 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/ThroughputEditor.java @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util; + +import java.beans.PropertyEditorSupport; + +public class ThroughputEditor extends PropertyEditorSupport { + + @Override + public String getAsText() { + return getValue().toString(); + } + + @Override + public void setAsText(String text) throws IllegalArgumentException { + setValue(new Throughput(text)); + } + +} diff --git a/org.argeo.util/src/org/argeo/util/security/DigestUtils.java b/org.argeo.util/src/org/argeo/util/security/DigestUtils.java new file mode 100644 index 000000000..b6aae6fd4 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/security/DigestUtils.java @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.security; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import org.argeo.ArgeoException; +import org.argeo.StreamUtils; + +/** Utilities around cryptographic digests */ +public class DigestUtils { + private static Boolean debug = true; + // TODO: make it writable + private final static Integer byteBufferCapacity = 100 * 1024;// 100 KB + + public static String digest(String algorithm, byte[] bytes) { + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); + digest.update(bytes); + byte[] checksum = digest.digest(); + String res = StreamUtils.encodeHexString(checksum); + return res; + } catch (Exception e) { + throw new ArgeoException("Cannot digest with algorithm " + + algorithm, e); + } + } + + public static String digest(String algorithm, InputStream in) { + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); + // ReadableByteChannel channel = Channels.newChannel(in); + // ByteBuffer bb = ByteBuffer.allocateDirect(byteBufferCapacity); + // while (channel.read(bb) > 0) + // digest.update(bb); + byte[] buffer = new byte[byteBufferCapacity]; + int read = 0; + while ((read = in.read(buffer)) > 0) { + digest.update(buffer, 0, read); + } + + byte[] checksum = digest.digest(); + String res = StreamUtils.encodeHexString(checksum); + return res; + } catch (Exception e) { + throw new ArgeoException("Cannot digest with algorithm " + + algorithm, e); + } finally { + StreamUtils.closeQuietly(in); + } + } + + public static String digest(String algorithm, File file) { + FileInputStream fis = null; + FileChannel fc = null; + try { + fis = new FileInputStream(file); + fc = fis.getChannel(); + + // Get the file's size and then map it into memory + int sz = (int) fc.size(); + ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); + return digest(algorithm, bb); + } catch (IOException e) { + throw new ArgeoException("Cannot digest " + file + + " with algorithm " + algorithm, e); + } finally { + StreamUtils.closeQuietly(fis); + if (fc.isOpen()) + try { + fc.close(); + } catch (IOException e) { + // silent + } + } + } + + protected static String digest(String algorithm, ByteBuffer bb) { + long begin = System.currentTimeMillis(); + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); + digest.update(bb); + byte[] checksum = digest.digest(); + String res = StreamUtils.encodeHexString(checksum); + long end = System.currentTimeMillis(); + if (debug) + System.out.println((end - begin) + " ms / " + + ((end - begin) / 1000) + " s"); + return res; + } catch (NoSuchAlgorithmException e) { + throw new ArgeoException("Cannot digest with algorithm " + + algorithm, e); + } + } + + public static void main(String[] args) { + File file; + if (args.length > 0) + file = new File(args[0]); + else { + System.err.println("Usage: []" + + " (see http://java.sun.com/j2se/1.5.0/" + + "docs/guide/security/CryptoSpec.html#AppA)"); + return; + } + + if (args.length > 1) { + String algorithm = args[1]; + System.out.println(digest(algorithm, file)); + } else { + String algorithm = "MD5"; + System.out.println(algorithm + ": " + digest(algorithm, file)); + algorithm = "SHA"; + System.out.println(algorithm + ": " + digest(algorithm, file)); + algorithm = "SHA-256"; + System.out.println(algorithm + ": " + digest(algorithm, file)); + algorithm = "SHA-512"; + System.out.println(algorithm + ": " + digest(algorithm, file)); + } + } + +} diff --git a/org.argeo.util/src/org/argeo/util/security/Keyring.java b/org.argeo.util/src/org/argeo/util/security/Keyring.java new file mode 100644 index 000000000..10dbabd49 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/security/Keyring.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.security; + +import java.io.InputStream; + +/** + * Access to private (typically encrypted) data. The keyring is responsible for + * retrieving the necessary credentials. Experimental. This API may + * change. + */ +public interface Keyring { + public void changePassword(char[] oldPassword, char[] newPassword); + + /** + * Returns the confidential information as chars. Must ask for it if it is + * not stored. + */ + public char[] getAsChars(String path); + + /** + * Returns the confidential information as a stream. Must ask for it if it + * is not stored. + */ + public InputStream getAsStream(String path); + + public void set(String path, char[] arr); + + public void set(String path, InputStream in); +} diff --git a/org.argeo.util/src/org/argeo/util/security/SimplePrincipal.java b/org.argeo.util/src/org/argeo/util/security/SimplePrincipal.java new file mode 100644 index 000000000..c7a4daf12 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/security/SimplePrincipal.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.security; + +import java.security.Principal; + +import org.argeo.ArgeoException; + +/** Canonical implementation of a {@link Principal} */ +public class SimplePrincipal implements Principal { + private final String name; + + public SimplePrincipal(String name) { + if (name == null) + throw new ArgeoException("Principal name cannot be null"); + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + return name.equals(obj.toString()); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + return new SimplePrincipal(name); + } + + @Override + public String toString() { + return name; + } + +} diff --git a/org.argeo.util/src/org/argeo/util/tabular/ArrayTabularRow.java b/org.argeo.util/src/org/argeo/util/tabular/ArrayTabularRow.java new file mode 100644 index 000000000..b1672e94c --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/tabular/ArrayTabularRow.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.tabular; + +import java.util.List; + +/** Minimal tabular row wrapping an {@link Object} array */ +public class ArrayTabularRow implements TabularRow { + private final Object[] arr; + + public ArrayTabularRow(List objs) { + this.arr = objs.toArray(); + } + + public Object get(Integer col) { + return arr[col]; + } + + public int size() { + return arr.length; + } + + public Object[] toArray() { + return arr; + } + +} diff --git a/org.argeo.util/src/org/argeo/util/tabular/CsvTabularWriter.java b/org.argeo.util/src/org/argeo/util/tabular/CsvTabularWriter.java new file mode 100644 index 000000000..8f5c52dca --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/tabular/CsvTabularWriter.java @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.tabular; + +import java.io.OutputStream; + +import org.argeo.util.CsvWriter; + +/** Write tabular content in a stream as CSV. Wraps a {@link CsvWriter}. */ +public class CsvTabularWriter implements TabularWriter { + private CsvWriter csvWriter; + + public CsvTabularWriter(OutputStream out) { + this.csvWriter = new CsvWriter(out); + } + + public void appendRow(Object[] row) { + csvWriter.writeLine(row); + } + + public void close() { + } + +} diff --git a/org.argeo.util/src/org/argeo/util/tabular/TabularColumn.java b/org.argeo.util/src/org/argeo/util/tabular/TabularColumn.java new file mode 100644 index 000000000..a5ee32f27 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/tabular/TabularColumn.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.tabular; + +/** The column in a tabular content */ +public class TabularColumn { + private String name; + /** + * JCR types, see + * http://www.day.com/maven/javax.jcr/javadocs/jcr-2.0/index.html + * ?javax/jcr/PropertyType.html + */ + private Integer type; + + /** column with default type */ + public TabularColumn(String name) { + super(); + this.name = name; + } + + public TabularColumn(String name, Integer type) { + super(); + this.name = name; + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getType() { + return type; + } + + public void setType(Integer type) { + this.type = type; + } + +} diff --git a/org.argeo.util/src/org/argeo/util/tabular/TabularContent.java b/org.argeo.util/src/org/argeo/util/tabular/TabularContent.java new file mode 100644 index 000000000..a2da86668 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/tabular/TabularContent.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.tabular; + +import java.util.List; + +/** + * Content organized as a table, possibly with headers. Only JCR types are + * supported even though there is not direct dependency on JCR. + */ +public interface TabularContent { + /** The headers of this table or null is none available. */ + public List getColumns(); + + public TabularRowIterator read(); +} diff --git a/org.argeo.util/src/org/argeo/util/tabular/TabularRow.java b/org.argeo.util/src/org/argeo/util/tabular/TabularRow.java new file mode 100644 index 000000000..05b8a40a9 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/tabular/TabularRow.java @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.tabular; + +/** A row of tabular data */ +public interface TabularRow { + /** The value at this column index */ + public Object get(Integer col); + + /** The raw objects (direct references) */ + public Object[] toArray(); + + /** Number of columns */ + public int size(); +} diff --git a/org.argeo.util/src/org/argeo/util/tabular/TabularRowIterator.java b/org.argeo.util/src/org/argeo/util/tabular/TabularRowIterator.java new file mode 100644 index 000000000..043463dd7 --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/tabular/TabularRowIterator.java @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.tabular; + +import java.util.Iterator; + +/** Navigation of rows */ +public interface TabularRowIterator extends Iterator { + /** + * Current row number, has to be incremented by each call to next() ; starts at 0, will + * therefore be 1 for the first row returned. + */ + public Long getCurrentRowNumber(); +} diff --git a/org.argeo.util/src/org/argeo/util/tabular/TabularWriter.java b/org.argeo.util/src/org/argeo/util/tabular/TabularWriter.java new file mode 100644 index 000000000..20d6519fa --- /dev/null +++ b/org.argeo.util/src/org/argeo/util/tabular/TabularWriter.java @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * 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 org.argeo.util.tabular; + + +/** Write to a tabular content */ +public interface TabularWriter { + /** Append a new row of data */ + public void appendRow(Object[] row); + + /** Finish persisting data and release resources */ + public void close(); +} diff --git a/org.argeo.util/src/test/java/org/argeo/util/CsvParserEncodingTestCase.java b/org.argeo.util/src/test/java/org/argeo/util/CsvParserEncodingTestCase.java deleted file mode 100644 index 111a8738c..000000000 --- a/org.argeo.util/src/test/java/org/argeo/util/CsvParserEncodingTestCase.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.List; - -import junit.framework.TestCase; - -public class CsvParserEncodingTestCase extends TestCase { - - private String iso = "ISO-8859-1"; - private String utf8 = "UTF-8"; - - public void testParse() throws Exception { - - String xml = new String("áéíóúñ,éééé"); - byte[] utfBytes = xml.getBytes(utf8); - byte[] isoBytes = xml.getBytes(iso); - - InputStream inUtf = new ByteArrayInputStream(utfBytes); - InputStream inIso = new ByteArrayInputStream(isoBytes); - - CsvParser csvParser = new CsvParser() { - protected void processLine(Integer lineNumber, List header, - List tokens) { - assertEquals(header.size(), tokens.size()); - assertEquals(2, tokens.size()); - assertEquals("áéíóúñ", tokens.get(0)); - assertEquals("éééé", tokens.get(1)); - } - }; - - csvParser.parse(inUtf, utf8); - inUtf.close(); - csvParser.parse(inIso, iso); - inIso.close(); - } -} diff --git a/org.argeo.util/src/test/java/org/argeo/util/CsvParserParseFileTest.java b/org.argeo.util/src/test/java/org/argeo/util/CsvParserParseFileTest.java deleted file mode 100644 index a937ee7c7..000000000 --- a/org.argeo.util/src/test/java/org/argeo/util/CsvParserParseFileTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -public class CsvParserParseFileTest extends TestCase { - public void testParse() throws Exception { - - final Map> lines = new HashMap>(); - InputStream in = getClass().getResourceAsStream( - "/org/argeo/util/ReferenceFile.csv"); - CsvParserWithLinesAsMap parser = new CsvParserWithLinesAsMap() { - protected void processLine(Integer lineNumber, - Map line) { - lines.put(lineNumber, line); - } - }; - - parser.parse(in); - in.close(); - - assertEquals(5, lines.size()); - } - -} diff --git a/org.argeo.util/src/test/java/org/argeo/util/CsvParserTestCase.java b/org.argeo.util/src/test/java/org/argeo/util/CsvParserTestCase.java deleted file mode 100644 index 02e8d1b59..000000000 --- a/org.argeo.util/src/test/java/org/argeo/util/CsvParserTestCase.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.List; - -import junit.framework.TestCase; - -public class CsvParserTestCase extends TestCase { - public void testParse() throws Exception { - String toParse = "Header1,\"Header\n2\",Header3,\"Header4\"\n" - + "Col1,\"Col\n2\",Col3,\"\"\"Col4\"\"\"\n" - + "Col1,\"Col\n2\",Col3,\"\"\"Col4\"\"\"\n" - + "Col1,\"Col\n2\",Col3,\"\"\"Col4\"\"\"\n"; - - InputStream in = new ByteArrayInputStream(toParse.getBytes()); - - CsvParser csvParser = new CsvParser() { - protected void processLine(Integer lineNumber, List header, - List tokens) { - assertEquals(header.size(), tokens.size()); - assertEquals(4, tokens.size()); - assertEquals("Col1", tokens.get(0)); - assertEquals("Col\n2", tokens.get(1)); - assertEquals("Col3", tokens.get(2)); - assertEquals("\"Col4\"", tokens.get(3)); - } - }; - - csvParser.parse(in); - in.close(); - } - -} diff --git a/org.argeo.util/src/test/java/org/argeo/util/CsvParserWithQuotedSeparatorTest.java b/org.argeo.util/src/test/java/org/argeo/util/CsvParserWithQuotedSeparatorTest.java deleted file mode 100644 index d4131a046..000000000 --- a/org.argeo.util/src/test/java/org/argeo/util/CsvParserWithQuotedSeparatorTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import junit.framework.TestCase; - -public class CsvParserWithQuotedSeparatorTest extends TestCase { - public void testSimpleParse() throws Exception { - String toParse = "Header1,\"Header2\",Header3,\"Header4\"\n" - + "\"Col1, Col2\",\"Col\n2\",Col3,\"\"\"Col4\"\"\"\n"; - - InputStream in = new ByteArrayInputStream(toParse.getBytes()); - - CsvParser csvParser = new CsvParser() { - protected void processLine(Integer lineNumber, List header, - List tokens) { - assertEquals(header.size(), tokens.size()); - assertEquals(4, tokens.size()); - assertEquals("Col1, Col2", tokens.get(0)); - } - }; - // System.out.println(toParse); - csvParser.parse(in); - in.close(); - - } - - public void testParseFile() throws Exception { - - final Map> lines = new HashMap>(); - InputStream in = getClass().getResourceAsStream( - "/org/argeo/util/ReferenceFile.csv"); - - CsvParserWithLinesAsMap parser = new CsvParserWithLinesAsMap() { - protected void processLine(Integer lineNumber, - Map line) { - // System.out.println("processing line #" + lineNumber); - lines.put(lineNumber, line); - } - }; - - parser.parse(in); - in.close(); - - Map line = lines.get(2); - assertEquals(",,,,", line.get("Coma testing")); - line = lines.get(3); - assertEquals(",, ,,", line.get("Coma testing")); - line = lines.get(4); - assertEquals("module1, module2", line.get("Coma testing")); - line = lines.get(5); - assertEquals("module1,module2", line.get("Coma testing")); - line = lines.get(6); - assertEquals(",module1,module2, \nmodule3, module4", - line.get("Coma testing")); - assertEquals(5, lines.size()); - - } -} diff --git a/org.argeo.util/src/test/java/org/argeo/util/CsvWriterTestCase.java b/org.argeo.util/src/test/java/org/argeo/util/CsvWriterTestCase.java deleted file mode 100644 index 26b356def..000000000 --- a/org.argeo.util/src/test/java/org/argeo/util/CsvWriterTestCase.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import junit.framework.TestCase; - -public class CsvWriterTestCase extends TestCase { - public void testWrite() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - final CsvWriter csvWriter = new CsvWriter(out); - - String[] header = { "Header1", "Header 2", "Header,3", "Header\n4", - "Header\"5\"" }; - String[] line1 = { "Value1", "Value 2", "Value,3", "Value\n4", - "Value\"5\"" }; - csvWriter.writeLine(Arrays.asList(header)); - csvWriter.writeLine(Arrays.asList(line1)); - - String reference = "Header1,Header 2,\"Header,3\",\"Header\n4\",\"Header\"\"5\"\"\"\n" - + "Value1,Value 2,\"Value,3\",\"Value\n4\",\"Value\"\"5\"\"\"\n"; - String written = new String(out.toByteArray()); - assertEquals(reference, written); - out.close(); - System.out.println(written); - - final List allTokens = new ArrayList(); - CsvParser csvParser = new CsvParser() { - protected void processLine(Integer lineNumber, List header, - List tokens) { - if (lineNumber == 2) - allTokens.addAll(header); - allTokens.addAll(tokens); - } - }; - ByteArrayInputStream in = new ByteArrayInputStream(written.getBytes()); - csvParser.parse(in); - in.close(); - List allTokensRef = new ArrayList(); - allTokensRef.addAll(Arrays.asList(header)); - allTokensRef.addAll(Arrays.asList(line1)); - - assertEquals(allTokensRef.size(), allTokens.size()); - for (int i = 0; i < allTokensRef.size(); i++) - assertEquals(allTokensRef.get(i), allTokens.get(i)); - } - -} diff --git a/org.argeo.util/src/test/java/org/argeo/util/ThroughputTest.java b/org.argeo.util/src/test/java/org/argeo/util/ThroughputTest.java deleted file mode 100644 index fc8007efd..000000000 --- a/org.argeo.util/src/test/java/org/argeo/util/ThroughputTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * 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 org.argeo.util; - -import junit.framework.TestCase; - -public class ThroughputTest extends TestCase { - public void testParse() { - Throughput t; - t = new Throughput("3.54/s"); - assertEquals(3.54d, t.getValue()); - assertEquals(Throughput.Unit.s, t.getUnit()); - assertEquals(282l, (long) t.asMsPeriod()); - - t = new Throughput("35698.2569/h"); - assertEquals(Throughput.Unit.h, t.getUnit()); - assertEquals(101l, (long) t.asMsPeriod()); - } -} diff --git a/org.argeo.util/src/test/resources/org/argeo/util/ReferenceFile.csv b/org.argeo.util/src/test/resources/org/argeo/util/ReferenceFile.csv deleted file mode 100644 index 351453d10..000000000 --- a/org.argeo.util/src/test/resources/org/argeo/util/ReferenceFile.csv +++ /dev/null @@ -1,37 +0,0 @@ -"ID","A long Text","Name","Other","Number","Reference","Target","Date","Update","Language","ID Ref","Weird chars","line feeds","after line feed","Empty column","Status comment","Comments","Empty","Coma testing" -"AK251","Everything & with some line feed - more “some” quote","Marge S.",,78.6,"A1155222221111268515131",,12/12/12,03/12/08,,9821308500721,"%%%ùù","ao","Nothing special",,,"Some very usefull comment",,",,,," -"AG254","same","Roger “wallace” Big","15 – JI",78.5,"A1155222221111268515131","next milestone",12/12/12,03/12/08,"_fr (French - France)",9812309500953,"***µ”","a - - - - -o","after line feed",,"Do the job",,,",, ,," -"FG211","Very long text with some bullets. -1 first -2 second -3. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long","Father & Son","15 – JI",15.4,"A1155222221111268515131","next milestone",12/12/12,03/12/08,"_fr (French - France)",9812309500952,"///","a - - - - - - -o","module1,module2",,"Be fast",,,"module1, module2" -"RRT152","Very long text with some bullets. -1 first -2 second -3. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long. some more very very very long","Another $$","15 – JI",12.3,"A1155222221111268515131","next milestone",12/12/12,03/12/08,"_fr (French - France)",9812309500950,"---","a - -o - - -","module1,module2",,,,,"module1,module2" -"YU121","Another use case : “blank line” - -After the blank.","nothing with brackets( )","15 – JI",15.2,"A1155222221111268515131",,12/12/12,03/12/08,"_fr (French - France)",9812309500925,",;:?./","ao"," - - - -After line feed again",,,,,",module1,module2, -module3, module4" diff --git a/org.argeo.util/src/test/resources/org/argeo/util/TestParse-ISO.csv b/org.argeo.util/src/test/resources/org/argeo/util/TestParse-ISO.csv deleted file mode 100644 index 0bec61111..000000000 --- a/org.argeo.util/src/test/resources/org/argeo/util/TestParse-ISO.csv +++ /dev/null @@ -1,8 +0,0 @@ -"Date d'imputation","N° de compte","Code journal","Pièce interne","Pièce externe","Libellé d'écriture","Débit","Crédit","Lettrage","Quantité","Code analytique","Date d'échéance","Date d'imputation origine","Code journal origine","Mode de règlement","Date début de période","Date fin de période" -26.01.2010,"101300","BQ","BQ01.10",,"Depot société en formation",,"3.000,00",,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"101300","BQ","BQ01.10",,"Depot société en formation",,"7.000,00",,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"411OPEN","BQ","BQ01.10",,"Vir Client ",,"2.508,00","A",,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"455100","BQ","BQ01.10",,"Bankomat Raiffeise","250,00",,,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"512101","BQ","BQ01.10",,"Extrait bancaire 01.10","12.250,55",,,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"627800","BQ","BQ01.10",,"Envoi de chequier","2,30",,,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"627800","BQ","BQ01.10",,"Frais d'expedition","5,15",,,,," ",26.01.2010,"BQ"," "," "," " diff --git a/org.argeo.util/src/test/resources/org/argeo/util/TestParse-UTF-8.csv b/org.argeo.util/src/test/resources/org/argeo/util/TestParse-UTF-8.csv deleted file mode 100644 index 0bec61111..000000000 --- a/org.argeo.util/src/test/resources/org/argeo/util/TestParse-UTF-8.csv +++ /dev/null @@ -1,8 +0,0 @@ -"Date d'imputation","N° de compte","Code journal","Pièce interne","Pièce externe","Libellé d'écriture","Débit","Crédit","Lettrage","Quantité","Code analytique","Date d'échéance","Date d'imputation origine","Code journal origine","Mode de règlement","Date début de période","Date fin de période" -26.01.2010,"101300","BQ","BQ01.10",,"Depot société en formation",,"3.000,00",,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"101300","BQ","BQ01.10",,"Depot société en formation",,"7.000,00",,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"411OPEN","BQ","BQ01.10",,"Vir Client ",,"2.508,00","A",,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"455100","BQ","BQ01.10",,"Bankomat Raiffeise","250,00",,,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"512101","BQ","BQ01.10",,"Extrait bancaire 01.10","12.250,55",,,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"627800","BQ","BQ01.10",,"Envoi de chequier","2,30",,,,," ",26.01.2010,"BQ"," "," "," " -26.01.2010,"627800","BQ","BQ01.10",,"Frais d'expedition","5,15",,,,," ",26.01.2010,"BQ"," "," "," "