diff --git a/.classpath b/.classpath index af2ac2e3c..476da60bc 100644 --- a/.classpath +++ b/.classpath @@ -1,6 +1,10 @@ - + + + + + @@ -83,7 +87,7 @@ - + @@ -443,7 +447,7 @@ - + @@ -528,11 +532,19 @@ - + + + + + + + + + diff --git a/.gitignore b/.gitignore index 0080155c9..a738d596e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,18 @@ + ## Build folders + bin/ build/ -tmp/ target/ +tmp/ + +<<<<<<< HEAD +*.class +*,so +*,si +*,dll +*.o +*.tmp ## Always ignore these *~ @@ -25,7 +35,7 @@ nbproject/private/ *.tmp tmp* log* -.classpath /.externalToolBuilders /.settings /test-output +/target/ diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/.settings/org.eclipse.core.runtime.prefs b/.settings/org.eclipse.core.runtime.prefs new file mode 100644 index 000000000..5a0ad22d2 --- /dev/null +++ b/.settings/org.eclipse.core.runtime.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +line.separator=\n diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component index b220e2de8..e2a00b7e2 100644 --- a/.settings/org.eclipse.wst.common.component +++ b/.settings/org.eclipse.wst.common.component @@ -2,5 +2,7 @@ + + diff --git a/ant.xml b/ant.xml deleted file mode 100644 index 0d82b5391..000000000 --- a/ant.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build.xml b/build.xml new file mode 100644 index 000000000..07919a9d4 --- /dev/null +++ b/build.xml @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ivy.xml b/ivy.xml new file mode 100644 index 000000000..987d9f92c --- /dev/null +++ b/ivy.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/cobertura/asm-tree.jar b/lib/cobertura/asm-tree.jar new file mode 100644 index 000000000..374bc2e9b Binary files /dev/null and b/lib/cobertura/asm-tree.jar differ diff --git a/lib/cobertura/asm.jar b/lib/cobertura/asm.jar new file mode 100644 index 000000000..d44dfd860 Binary files /dev/null and b/lib/cobertura/asm.jar differ diff --git a/lib/cobertura/cobertura.jar b/lib/cobertura/cobertura.jar new file mode 100644 index 000000000..438fe551a Binary files /dev/null and b/lib/cobertura/cobertura.jar differ diff --git a/lib/cobertura/log4j.jar b/lib/cobertura/log4j.jar new file mode 100644 index 000000000..625130719 Binary files /dev/null and b/lib/cobertura/log4j.jar differ diff --git a/lib/cobertura/oro.jar b/lib/cobertura/oro.jar new file mode 100644 index 000000000..23488d260 Binary files /dev/null and b/lib/cobertura/oro.jar differ diff --git a/lib/commons-email-1.2.jar b/lib/commons-email-1.2.jar new file mode 100644 index 000000000..f08597594 Binary files /dev/null and b/lib/commons-email-1.2.jar differ diff --git a/lib/findbugs-2.0.1/lib/annotations.jar b/lib/findbugs-2.0.1/lib/annotations.jar new file mode 100644 index 000000000..8a0204fc2 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/annotations.jar differ diff --git a/lib/findbugs-2.0.1/lib/ant.jar b/lib/findbugs-2.0.1/lib/ant.jar new file mode 100644 index 000000000..f68c9cfc8 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/ant.jar differ diff --git a/lib/findbugs-2.0.1/lib/asm-3.3.jar b/lib/findbugs-2.0.1/lib/asm-3.3.jar new file mode 100644 index 000000000..7638ae058 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/asm-3.3.jar differ diff --git a/lib/findbugs-2.0.1/lib/asm-analysis-3.3.jar b/lib/findbugs-2.0.1/lib/asm-analysis-3.3.jar new file mode 100644 index 000000000..852d98158 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/asm-analysis-3.3.jar differ diff --git a/lib/findbugs-2.0.1/lib/asm-commons-3.3.jar b/lib/findbugs-2.0.1/lib/asm-commons-3.3.jar new file mode 100644 index 000000000..6f9d40fba Binary files /dev/null and b/lib/findbugs-2.0.1/lib/asm-commons-3.3.jar differ diff --git a/lib/findbugs-2.0.1/lib/asm-tree-3.3.jar b/lib/findbugs-2.0.1/lib/asm-tree-3.3.jar new file mode 100644 index 000000000..4a5daa68a Binary files /dev/null and b/lib/findbugs-2.0.1/lib/asm-tree-3.3.jar differ diff --git a/lib/findbugs-2.0.1/lib/asm-util-3.3.jar b/lib/findbugs-2.0.1/lib/asm-util-3.3.jar new file mode 100644 index 000000000..115bcc732 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/asm-util-3.3.jar differ diff --git a/lib/findbugs-2.0.1/lib/asm-xml-3.3.jar b/lib/findbugs-2.0.1/lib/asm-xml-3.3.jar new file mode 100644 index 000000000..61d6a8c21 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/asm-xml-3.3.jar differ diff --git a/lib/findbugs-2.0.1/lib/bcel.jar b/lib/findbugs-2.0.1/lib/bcel.jar new file mode 100644 index 000000000..fef26b13c Binary files /dev/null and b/lib/findbugs-2.0.1/lib/bcel.jar differ diff --git a/lib/findbugs-2.0.1/lib/commons-lang-2.4.jar b/lib/findbugs-2.0.1/lib/commons-lang-2.4.jar new file mode 100644 index 000000000..532939eca Binary files /dev/null and b/lib/findbugs-2.0.1/lib/commons-lang-2.4.jar differ diff --git a/lib/findbugs-2.0.1/lib/dom4j-1.6.1.jar b/lib/findbugs-2.0.1/lib/dom4j-1.6.1.jar new file mode 100644 index 000000000..c8c4dbb92 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/dom4j-1.6.1.jar differ diff --git a/lib/findbugs-2.0.1/lib/findbugs-ant.jar b/lib/findbugs-2.0.1/lib/findbugs-ant.jar new file mode 100644 index 000000000..2128ba85e Binary files /dev/null and b/lib/findbugs-2.0.1/lib/findbugs-ant.jar differ diff --git a/lib/findbugs-2.0.1/lib/findbugs.jar b/lib/findbugs-2.0.1/lib/findbugs.jar new file mode 100644 index 000000000..3201a2650 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/findbugs.jar differ diff --git a/lib/findbugs-2.0.1/lib/jFormatString.jar b/lib/findbugs-2.0.1/lib/jFormatString.jar new file mode 100644 index 000000000..62f6c0260 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/jFormatString.jar differ diff --git a/lib/findbugs-2.0.1/lib/jaxen-1.1.1.jar b/lib/findbugs-2.0.1/lib/jaxen-1.1.1.jar new file mode 100644 index 000000000..b63363113 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/jaxen-1.1.1.jar differ diff --git a/lib/findbugs-2.0.1/lib/jcip-annotations.jar b/lib/findbugs-2.0.1/lib/jcip-annotations.jar new file mode 100644 index 000000000..bb07c0c44 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/jcip-annotations.jar differ diff --git a/lib/findbugs-2.0.1/lib/jdepend-2.9.jar b/lib/findbugs-2.0.1/lib/jdepend-2.9.jar new file mode 100644 index 000000000..1838bbb91 Binary files /dev/null and b/lib/findbugs-2.0.1/lib/jdepend-2.9.jar differ diff --git a/lib/findbugs-2.0.1/lib/jsr305.jar b/lib/findbugs-2.0.1/lib/jsr305.jar new file mode 100644 index 000000000..43807b02f Binary files /dev/null and b/lib/findbugs-2.0.1/lib/jsr305.jar differ diff --git a/lib/findbugs-2.0.1/lib/yjp-controller-api-redist.jar b/lib/findbugs-2.0.1/lib/yjp-controller-api-redist.jar new file mode 100644 index 000000000..490695f8a Binary files /dev/null and b/lib/findbugs-2.0.1/lib/yjp-controller-api-redist.jar differ diff --git a/lib/freemarker.jar b/lib/freemarker.jar index 968c1d314..b13671dac 100644 Binary files a/lib/freemarker.jar and b/lib/freemarker.jar differ diff --git a/lib/keggapi.jar b/lib/keggapi.jar new file mode 100644 index 000000000..a87db3072 Binary files /dev/null and b/lib/keggapi.jar differ diff --git a/lib/mindterm.jar b/lib/mindterm.jar new file mode 100644 index 000000000..f315a3f51 Binary files /dev/null and b/lib/mindterm.jar differ diff --git a/lib/mockito-all-1.9.5.jar b/lib/mockito-all-1.9.5.jar new file mode 100644 index 000000000..00416eb38 Binary files /dev/null and b/lib/mockito-all-1.9.5.jar differ diff --git a/lib/ontocat-0.9.9.1.jar b/lib/ontocat-0.9.9.1.jar new file mode 100644 index 000000000..e1d7bff6c Binary files /dev/null and b/lib/ontocat-0.9.9.1.jar differ diff --git a/lib/org.semanticweb.HermiT.jar b/lib/org.semanticweb.HermiT.jar new file mode 100644 index 000000000..3cd01302d Binary files /dev/null and b/lib/org.semanticweb.HermiT.jar differ diff --git a/lib/selenium-server-standalone-2.19.0.jar b/lib/selenium-server-standalone-2.25.0.jar similarity index 76% rename from lib/selenium-server-standalone-2.19.0.jar rename to lib/selenium-server-standalone-2.25.0.jar index ba7bf2f11..90ee07853 100644 Binary files a/lib/selenium-server-standalone-2.19.0.jar and b/lib/selenium-server-standalone-2.25.0.jar differ diff --git a/lib/simplecaptcha-1.2.1.jar b/lib/simplecaptcha-1.2.1.jar new file mode 100644 index 000000000..9bba7cbe7 Binary files /dev/null and b/lib/simplecaptcha-1.2.1.jar differ diff --git a/pom.xml b/pom.xml index b23669849..56355ea64 100644 --- a/pom.xml +++ b/pom.xml @@ -1,212 +1,232 @@ - - 4.0.0 - - org.molgenis - molgenis - 1.0-SNAPSHOT - jar + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - molgenis + org.molgenis + molgenis + 1.0-SNAPSHOT + jar - - ${project.build.directory}/endorsed - UTF-8 - + molgenis - - - thirdparty-releases - JBoss Thirdparty Releases - https://repository.jboss.org/nexus/content/repositories/thirdparty-releases - - + + ${project.build.directory}/endorsed + UTF-8 + - - - org.hibernate - hibernate-entitymanager - 3.6.9.Final - jar - - - org.hibernate - hibernate-validator - 4.2.0.Final - - - commons-dbcp - commons-dbcp - 1.4 - - - - commons-pool - commons-pool - 20030825.183949 - runtime - + + + org.hibernate + hibernate-entitymanager + 3.6.9.Final + jar + + + org.hibernate + hibernate-validator + 4.2.0.Final + + + commons-dbcp + commons-dbcp + 1.4 + + + + commons-pool + commons-pool + 20030825.183949 + runtime + mysql mysql-connector-java - 5.1.20 + 5.1.20 + provided - hsqldb hsqldb 1.8.0.10 - - - - - - javax.servlet - servlet-api - 2.5 provided - - - - taglibs - standard - 1.1.2 - - - javax.servlet - jstl - 1.2 + + + + + javax.servlet + servlet-api + 2.5 + provided + + + + + taglibs + standard + 1.1.2 + + + javax.servlet + jstl + 1.2 runtime - - - - - commons-lang - commons-lang - 2.6 - - - - commons-fileupload - commons-fileupload - 1.2 - - - - - - - org.quartz-scheduler - quartz - 1.8.6 - - - + - - org.freemarker - freemarker - 2.3.18 - + + + commons-lang + commons-lang + 2.6 + + + commons-fileupload + commons-fileupload + 1.2 + + + org.apache.commons + commons-email + 1.2 + + + commons-io + commons-io + 2.4 + + + + + + org.quartz-scheduler + quartz + 1.8.6 + + + + + + org.freemarker + freemarker + 2.3.18 + + + + + ch.ethz.ganymed + ganymed-ssh2 + build210 + + + + + org.testng + testng + 6.4 + test + + + junit + junit + 4.10 + test + + + org.mockito + mockito-all + 1.8.4 + test + - + + + org.hibernate + hibernate-search + 3.4.1.Final + + + - ch.ethz.ganymed - ganymed-ssh2 - build210 + org.apache.poi + poi + 3.8 + + net.sourceforge.jexcelapi + jxl + 2.6.12 + - - - org.testng - testng - 6.4 - - - - junit - junit - 4.10 - - + + + javatar + javatar + 2.5 + + + + + org.apache.cxf + cxf-bundle-minimal + 2.5.2 + - - - org.hibernate - hibernate-search - 3.4.1.Final - - - - - net.sourceforge.jexcelapi - jxl - 2.6.12 - - - - - javatar - javatar - 2.5 - - - - - org.apache.cxf - cxf-bundle-minimal - 2.5.2 - - - - - xerces - xercesImpl - 2.10.0 - - - - - net.sf.json-lib - json-lib - 2.4 - jdk15 - + + + xerces + xercesImpl + 2.10.0 + + + + + net.sf.json-lib + json-lib + 2.4 + jdk15 + com.google.code.gson gson 2.2 compile - - - - org.apache.ant - ant - 1.8.2 - - - - org.apache.ant - ant-apache-log4j - 1.8.2 - - - - - org.json - json - 20090211 - + + + org.apache.ant + ant + 1.8.2 + + + + org.apache.ant + ant-apache-log4j + 1.8.2 + + + + + org.json + json + 20090211 + @@ -214,14 +234,13 @@ tjws 2.3.4.Final - - - - src - src + - - + + src + test/java + + src/ @@ -229,29 +248,33 @@ **/*.properties **/*.index org/molgenis/framework/ui/res/** - + - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - ${endorsed.dir} - + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + ${endorsed.dir} + + + + maven-surefire-plugin 2.6 @@ -265,33 +288,32 @@ + + org.apache.maven.plugins + maven-dependency-plugin + 2.1 + + + validate + + copy + + + ${endorsed.dir} + true + + + javax + javaee-endorsed-api + 6.0 + jar + + + + + + + + - - org.apache.maven.plugins - maven-dependency-plugin - 2.1 - - - validate - - copy - - - ${endorsed.dir} - true - - - javax - javaee-endorsed-api - 6.0 - jar - - - - - - - - - diff --git a/pom_minimal.xml b/pom_minimal.xml new file mode 100644 index 000000000..58859b4d0 --- /dev/null +++ b/pom_minimal.xml @@ -0,0 +1,302 @@ + + 4.0.0 + + org.molgenis + molgenis + 1.0-SNAPSHOT + jar + + molgenis + + + ${project.build.directory}/endorsed + UTF-8 + + + + + + + org.hibernate + hibernate-entitymanager + 3.6.9.Final + jar + + + org.hibernate + hibernate-validator + 4.2.0.Final + + + commons-dbcp + commons-dbcp + 1.4 + + + + commons-pool + commons-pool + 20030825.183949 + runtime + + + mysql + mysql-connector-java + 5.1.20 + provided + + + hsqldb + hsqldb + 1.8.0.10 + provided + + + + + + javax.servlet + servlet-api + 2.5 + provided + + + + + taglibs + standard + 1.1.2 + + + javax.servlet + jstl + 1.2 + runtime + + + + + commons-lang + commons-lang + 2.6 + + + commons-fileupload + commons-fileupload + 1.2 + + + org.apache.commons + commons-email + 1.2 + + + + + + org.quartz-scheduler + quartz + 1.8.6 + + + + + + org.freemarker + freemarker + 2.3.18 + + + + + ch.ethz.ganymed + ganymed-ssh2 + build210 + + + + + org.testng + testng + 6.4 + test + + + junit + junit + 4.10 + test + + + + + org.hibernate + hibernate-search + 3.4.1.Final + + + + + net.sourceforge.jexcelapi + jxl + 2.6.12 + + + + + javatar + javatar + 2.5 + + + + + org.apache.cxf + cxf-bundle-minimal + 2.5.2 + + + + + xerces + xercesImpl + 2.10.0 + + + + + net.sf.json-lib + json-lib + 2.4 + jdk15 + + + com.google.code.gson + gson + 2.2 + compile + + + + org.apache.ant + ant + 1.8.2 + + + + org.apache.ant + ant-apache-log4j + 1.8.2 + + + + + org.json + json + 20090211 + + + + + org.jboss.resteasy + tjws + 2.3.4.Final + + + + + src + src + + + + + src/ + + **/*.ftl + **/*.properties + **/*.index + org/molgenis/framework/ui/res/** + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + ${endorsed.dir} + + + **/*Test.java + **/Test*.java + + + **/*Test.java + **/Test*.java + + + + + maven-surefire-plugin + 2.6 + + + + **/*ExcelReaderTest.java + **/*PbsTest.java + **/*PlinkTest.java + **/*VcfReaderTest.java + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.1 + + + validate + + copy + + + ${endorsed.dir} + true + + + javax + javaee-endorsed-api + 6.0 + jar + + + + + + + + + + diff --git a/src/org/molgenis/Molgenis.java b/src/org/molgenis/Molgenis.java index 7b1148cd9..49cc207e1 100644 --- a/src/org/molgenis/Molgenis.java +++ b/src/org/molgenis/Molgenis.java @@ -81,7 +81,6 @@ import org.molgenis.generators.server.MolgenisGuiServiceGen; import org.molgenis.generators.server.MolgenisResourceCopyGen; import org.molgenis.generators.server.MolgenisServletContextGen; -import org.molgenis.generators.server.MolgenisServletGen; import org.molgenis.generators.server.RdfApiGen; import org.molgenis.generators.server.RestApiGen; import org.molgenis.generators.server.SoapApiGen; @@ -113,49 +112,53 @@ * * @author Morris Swertz */ -public class Molgenis { - - public static void main(String[] args) { - try { - if (args.length == 1) - { - new Molgenis(args[0]).generate(); - } - else if(args.length == 2) - { - if(args[1].equals("--updatedb")) - { - new Molgenis(args[0]).updateDb(false); - } - else if(args[1].equals("--updatedbfillmeta")) - { - new Molgenis(args[0]).updateDb(true); - } - else - { - throw new Exception("Bad second argument: use either --updatedb or --updatedbfillmeta"); - } - } - else - { - throw new Exception("You have to provide the molgenis.properties file as first argument to generate Molgenis.\n" + - "Alternatively, add the additional argument --updatedb OR --updatedbfillmeta to perform the update database action.\n" + - "The --updatedbfillmeta will also insert the metadata into the database.\n" + - "Your arguments:\n" - + Arrays.toString(args)); - } - } - catch (Exception e) - { - e.printStackTrace(); - } - } - protected transient static final Logger logger = Logger.getLogger("MOLGENIS"); - MolgenisOptions options = null; - Model model = null; - List generators = new ArrayList(); - - public List getGenerators() +public class Molgenis +{ + + public static void main(String[] args) + { + try + { + if (args.length == 1) + { + new Molgenis(args[0]).generate(); + } + else if (args.length == 2) + { + if (args[1].equals("--updatedb")) + { + new Molgenis(args[0]).updateDb(false); + } + else if (args[1].equals("--updatedbfillmeta")) + { + new Molgenis(args[0]).updateDb(true); + } + else + { + throw new Exception("Bad second argument: use either --updatedb or --updatedbfillmeta"); + } + } + else + { + throw new Exception( + "You have to provide the molgenis.properties file as first argument to generate Molgenis.\n" + + "Alternatively, add the additional argument --updatedb OR --updatedbfillmeta to perform the update database action.\n" + + "The --updatedbfillmeta will also insert the metadata into the database.\n" + + "Your arguments:\n" + Arrays.toString(args)); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + protected transient static final Logger logger = Logger.getLogger("MOLGENIS"); + MolgenisOptions options = null; + Model model = null; + List generators = new ArrayList(); + + public List getGenerators() { return generators; } @@ -165,655 +168,789 @@ public void setGenerators(List generators) this.generators = generators; } - public Molgenis(String propertiesFile, Class... generatorsToUse) throws Exception { - this(new MolgenisOptions(propertiesFile), generatorsToUse); - } - - public Molgenis(String propertiesFile) throws Exception { - this(new MolgenisOptions(propertiesFile), new Class[] {}); - } - - public Molgenis() - { - } - - public void init(String propertiesFile, Class... generatorsToUse) throws Exception - { - new Molgenis(new MolgenisOptions(propertiesFile), generatorsToUse); - } - - /** - * Construct a MOLGENIS generator - * - * @param options - * with generator settings - * @param generatorsToUse - * optional list of generator classes to include - * @throws Exception - */ - public Molgenis(MolgenisOptions options, - Class... generatorsToUse) throws Exception { - BasicConfigurator.configure(); - - - - this.loadFieldTypes(); - - this.options = options; - - if(generatorsToUse != null && generatorsToUse.length > 0) { + public Molgenis(String propertiesFile, Class... generatorsToUse) throws Exception + { + this(new MolgenisOptions(propertiesFile), generatorsToUse); + } + + public Molgenis(String propertiesFile) throws Exception + { + this(new MolgenisOptions(propertiesFile), new Class[] + {}); + } + + public Molgenis() + { + } + + public void init(String propertiesFile, Class... generatorsToUse) throws Exception + { + new Molgenis(new MolgenisOptions(propertiesFile), generatorsToUse); + } + + /** + * Construct a MOLGENIS generator + * + * @param options + * with generator settings + * @param generatorsToUse + * optional list of generator classes to include + * @throws Exception + */ + public Molgenis(MolgenisOptions options, Class... generatorsToUse) + throws Exception + { + BasicConfigurator.configure(); + + this.loadFieldTypes(); + + this.options = options; + + if (generatorsToUse != null && generatorsToUse.length > 0) + { this.options.delete_generated_folder = false; } - Logger.getLogger("freemarker.cache").setLevel(Level.INFO); - logger.info("\nMOLGENIS version " + org.molgenis.Version.convertToString()); - logger.info("working dir: " + System.getProperty("user.dir")); - - // clean options - if (!options.output_src.endsWith("/")) { - options.output_src = options.output_src + "/"; - } - if (!options.output_python.endsWith("/")) { - options.output_python = options.output_python + "/"; - } - if (!options.output_cpp.endsWith("/")) { - options.output_cpp = options.output_cpp + "/"; - } - if (!options.output_hand.endsWith("/")) { - options.output_hand = options.output_hand + "/"; - } - - //USED MOLGENIS OPTIONS - generators.add(new UsedMolgenisOptionsGen()); - - // COPY resources - if (options.copy_resources) { - generators.add(new MolgenisResourceCopyGen()); - } - - // DOCUMENTATION - if (options.generate_doc) { - //not used: generators.add(new TableDocGen()); - //not used: generators.add(new EntityModelDocGen()); - generators.add(new DotDocGen()); - generators.add(new FileFormatDocGen()); - generators.add(new DotDocMinimalGen()); - generators.add(new ObjectModelDocGen()); - generators.add(new DotDocModuleDependencyGen()); - //not used: generators.add(new TextUmlGen()); - } else { - logger.info("Skipping documentation ...."); - } - - if (options.generate_cpp) { - generators.add(new CPPCassette()); - } - - // TESTS - if (options.generate_tests) { - generators.add(new TestDatabaseGen()); - generators.add(new TestCsvGen()); - generators.add(new TestDataSetGen()); - } else { - logger.info("Skipping Tests ...."); - } - // DATA - // generators.add(new DataPListGen()); - // generators.add(new ViewTypeGen()); - - - if (options.generate_sql) { - if (options.mapper_implementation.equals(MapperImplementation.JPA)) { - System.out.println("--------------JPAGEN--------------"); - generators.add(new JpaDatabaseGen()); - generators.add(new DataTypeGen()); - generators.add(new JpaMapperGen()); - generators.add(new JDBCMetaDatabaseGen()); - - //generates Entity Listeners - //JpaEntityListenerGen entityListGen = new JpaEntityListenerGen(); - //entityListGen.setHandwritten(true); - //generators.add(entityListGen); - - if (options.generate_persistence) { - generators.add(new PersistenceGen()); - } - - //generators.add(new FillMetadataTablesGen()); - - - } else { - // DATABASE - // mysql.org - if (options.db_driver.equals("com.mysql.jdbc.Driver")) { - generators.add(new MySqlCreateSubclassPerTableGen()); - generators.add(new MySqlAlterSubclassPerTableGen()); - // use multiquery optimization - if (options.mapper_implementation.equals(MapperImplementation.MULTIQUERY)) { - generators.add(new JDBCDatabaseGen()); - generators.add(new DataTypeGen()); - generators.add(new MultiqueryMapperGen()); - } else if (options.mapper_implementation.equals(MapperImplementation.PREPARED_STATEMENT)) { - generators.add(new JDBCDatabaseGen()); - generators.add(new DataTypeGen()); - generators.add(new PStatementMapperGen()); - } - } // hsqldb.org - else if (options.db_driver.equals("oracle.jdbc.driver.OracleDriver")) { - generators.add(new OracleCreateSubclassPerTableGen()); - generators.add(new JDBCDatabaseGen()); - generators.add(new DataTypeGen()); - generators.add(new PStatementMapperGen()); - } - else if (options.db_driver.equals("org.hsqldb.jdbcDriver")) { - logger.info("HsqlDB generators ...."); - generators.add(new JDBCDatabaseGen()); - generators.add(new DataTypeGen()); - generators.add(new HSqlCreateSubclassPerTableGen()); - //generators.add(new MultiqueryMapperGen()); - generators.add(new PStatementMapperGen()); - } // postgresql - else if (options.db_driver.equals("org.postgresql.Driver")) { - generators.add(new PSqlCreateSubclassPerTableGen()); - generators.add(new PStatementMapperGen()); - } // h2database.com, branch of hsqldb? - else if (options.db_driver.equals("org.h2.Driver")) { - generators.add(new HSqlCreateSubclassPerTableGen()); - generators.add(new PStatementMapperGen()); - } // derby, not functional ignore. - else if (options.db_driver.equals("org.apache.derby.jdbc.EmbeddedDriver")) { - generators.add(new DerbyCreateSubclassPerTableGen()); - } else { - logger.warn("Unknown database driver " + options.db_driver); - // System.exit(-1); - } - - // test - generators.add(new JDBCMetaDatabaseGen()); - // SQL - generators.add(new CountPerEntityGen()); - generators.add(new CountPerTableGen()); - generators.add(new FillMetadataTablesGen()); - } - - generators.add(new FillMetadataGen()); - - // authorization - if (!options.auth_loginclass.endsWith("SimpleLogin")) { - generators.add(new MapperSecurityDecoratorGen()); - } - - // decorators - if(options.generate_decorators){ - generators.add(new MapperDecoratorGen()); - } - - // DatabaseFactory - //if (!options.db_driver.equals("org.hsqldb.jdbcDriver")) { - generators.add(new DatabaseFactoryGen()); - //} - } else { - logger.info("SEVERE: Skipping ALL SQL ...."); - } - - - if (options.generate_Python) { - generators.add(new PythonDataTypeGen()); - } else { - logger.info("Skipping Python interface ...."); - } - // generators.add(new HsqlDbGen()); - - // CSV - if (options.generate_csv) { - generators.add(new CsvReaderGen()); - generators.add(new CsvImportByIdGen()); - generators.add(new CsvExportGen()); - generators.add(new CsvImportGen()); - } else { - logger.info("Skipping CSV importers ...."); - } - // generators.add(new CopyMemoryToDatabaseGen()); - // generators.add(new CsvReaderFactoryGen()); - - // XML - // generators.add(new XmlMapperGen()); - - // R - if (options.generate_R) { - generators.add(new REntityGen()); - generators.add(new RMatrixGen()); - generators.add(new RApiGen()); - } else { - logger.info("Skipping R interface ...."); - } - // SCREEN - if (options.generate_MolgenisServlet) { - // SERVER SETTINGS - generators.add(new MolgenisServletContextGen()); - generators.add(new MolgenisContextListenerGen()); - generators.add(new MolgenisServletGen()); - generators.add(new FrontControllerGen()); //will replace MolgenisServlet (service mapping, database & security) - generators.add(new MolgenisGuiServiceGen()); //will replace MolgenisServlet (gui service) - - } else { - logger.info("Skipping MolgenisServlet ...."); - } - - // HTML - if (options.generate_html) { - generators.add(new HtmlFormGen()); - generators.add(new FormControllerGen()); - generators.add(new MenuControllerGen()); - } else { - logger.info("Skipping HTML (HTML,Form,Menu,Tree) ...."); - } - - // SCREEN PLUGIN - if (options.generate_plugins) { - //generators.add(new PluginControllerGen()); - //generators.add(new PluginScreenFTLTemplateGen()); - //generators.add(new PluginScreenJavaTemplateGen()); - - //generators.add(new EasyPluginViewGen()); - generators.add(new EasyPluginControllerGen()); - //generators.add(new EasyPluginModelGen()); - } else { - logger.info("Skipping generation of plugins ...."); - } - - //plugin controllers - always need these to map plugins in the GUI - generators.add(new PluginControllerGen()); - - // SOAP - if (options.generate_soap) { - generators.add(new SoapApiGen()); - } else { - logger.info("Skipping SOAP API ...."); - } - - if (options.generate_rest) { - generators.add(new RestApiGen()); - } else { - logger.info("Skipping SOAP API ...."); - } - - if (options.generate_rdf) { - generators.add(new RdfApiGen()); - } else { - logger.info("Skipping SOAP API ...."); - } - - // Excel - if (options.generate_ExcelImport) { - generators.add(new ExcelReaderGen()); - generators.add(new ExcelImportGen()); - generators.add(new ExcelExportGen()); - generators.add(new ImportWizardExcelPrognosisGen()); - if (!options.generate_csv) { - logger.info("Automatically including the CSV importers needed for Excel import"); - generators.add(new CsvReaderGen()); - generators.add(new CsvImportByIdGen()); - generators.add(new CsvExportGen()); - generators.add(new CsvImportGen()); - } - } else { - logger.info("Skipping Excel importer ...."); - } - // RDF - - - // FIXME add more generators - // FIXME use configuration to add the generators - - // clean out generators - List use = new ArrayList(); - if (!ArrayUtils.isEmpty(generatorsToUse)) { - for (Class c : generatorsToUse) { - use.add(c.newInstance()); - } - generators = use; - } - - logger.debug("\nUsing generators:\n" + toString()); - - // parsing model - model = MolgenisModel.parse(options); - } - - private void loadFieldTypes() { - MolgenisFieldTypes.addType(new BoolField()); - MolgenisFieldTypes.addType(new DateField()); - MolgenisFieldTypes.addType(new DatetimeField()); - MolgenisFieldTypes.addType(new DecimalField()); - MolgenisFieldTypes.addType(new EnumField()); - MolgenisFieldTypes.addType(new FileField()); - MolgenisFieldTypes.addType(new ImageField()); - MolgenisFieldTypes.addType(new HyperlinkField()); - // FieldTypeRegistry.addType(new ListField()); - MolgenisFieldTypes.addType(new LongField()); - MolgenisFieldTypes.addType(new MrefField()); - MolgenisFieldTypes.addType(new NSequenceField()); - MolgenisFieldTypes.addType(new OnoffField()); - MolgenisFieldTypes.addType(new StringField()); - MolgenisFieldTypes.addType(new TextField()); - MolgenisFieldTypes.addType(new XrefField()); - MolgenisFieldTypes.addType(new IntField()); - } - - /** - * Apply all generators on the model - * - * @param model - */ - public void generate() throws Exception { - logger.info("generating ...."); - logger.info("\nUsing options:\n" + options.toString()); - - File generatedFolder = new File(options.output_dir); - if (generatedFolder.exists() && options.delete_generated_folder) { - logger.info("removing previous generated folder " + generatedFolder); - deleteContentOfDirectory(generatedFolder); - } - - List threads = new ArrayList(); - for (final Generator g : generators) { - Runnable runnable = new Runnable() { - - public void run() { - try { - g.generate(model, options); - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } - } - }; - //executor.execute(runnable); - Thread thread = new Thread(runnable); - thread.start(); - threads.add(thread); - } - - //wait for all threads to complete - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException ignore) { - } - } - - logger.info("Generation completed at " + new Date()); - } - - /** - * Deletes the content of directory (path), excluding hidden files like .svn - * @param path of directory to delete - * @return if and only if the content of directory (path) is successfully deleted; false otherwise - */ - static public boolean deleteContentOfDirectory(File path) { - boolean result = true; - if (path.exists()) { - File[] files = path.listFiles(); - for (File f : files) { - if (!f.isHidden()) { - if (f.isDirectory()) { - result &= deleteContentOfDirectory(f); - f.delete(); - } else { - result &= f.delete(); - } - } - } - } - return result; - - } - - /** - * Compile a generated molgenis. - * - * Currently not implemented but is needed for batch generation. Not needed - * if you are generating inside an IDE such as eclipse. - * - * @return true if build is succesfull - * @throws IOException - */ - @Deprecated - public boolean compile() throws IOException { - // reduce loggin - Logger.getLogger("org.apache.tools.ant.UnknownElement").setLevel(Level.ERROR); - Logger.getLogger("org.apache.tools.ant.Target").setLevel(Level.ERROR); - - // run the ant build script - logger.info("Compile ..."); - - File tempdir = new File(options.output_src); - // File tempdir = (File) ses.getAttribute("workingdir"); - - // copy the buildfile from sjabloon - File buildFileSource = new File("sjabloon/build.xml"); - File buildFile = new File(tempdir.getPath() + "/build.xml"); - copyFile(buildFileSource, buildFile); - - // create a new ant project - Project p = new Project(); - p.setUserProperty("ant.file", buildFile.getAbsolutePath()); - p.init(); - - // execute the ant target - ProjectHelper helper = ProjectHelper.getProjectHelper(); - p.addReference("ant.projectHelper", helper); - p.addBuildListener(new Log4jListener()); - helper.parse(p, buildFile); - - p.setProperty("jdbc.driver", "mysql-connector-java-5.1.0-bin.jar"); - p.setProperty("main.class", "MolgenisOnMysqlServer"); - p.executeTarget("createjar"); - logger.info("compilation complete."); - - return true; - } - - private static void copyFile(File src, File dst) throws IOException { - InputStream in = new FileInputStream(src); - OutputStream out = new FileOutputStream(dst); - - // Transfer bytes from in to out - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } - in.close(); - out.close(); - } - - /** - * Parse the model using settings in options - * - * @param options - * @return MOLGENIS model - * @throws Exception - */ -// private void parse() throws Exception { -// MolgenisModel language = new MolgenisModel(); -// model = language.parse(options); -// logger.debug("\nUsing metamodel:\n" + model); -// } - /** - * Load the generated SQL into the database. - * - * Warning: this will overwrite any existing data in the database!. - * - * @throws SQLException - * @throws FileNotFoundException - * @throws IOException - * @throws CmdLineException - */ - public void updateDb() throws SQLException, FileNotFoundException, - IOException { - updateDb(false); - } - - public void updateDb(boolean filldb) throws SQLException, FileNotFoundException, - IOException { - - boolean ask = false; - - // ask for confirmation that the database can be updated - // TODO: Use or throw away! Make a decision. - while (ask) { - logger.info("Are you sure that you want overwrite database " - + options.db_uri - + "?\n All existing data will be overwritten. \nAnswer 'y' or 'n'.\n"); - String answer = ""; - int c; - while ((c = System.in.read()) != 13) { - answer += (char) c; - } - if (answer.trim().equals("y")) { - ask = false; - } else if (answer.equals("n")) { - logger.info("MOLGENIS database update canceled.\n"); - return; - } else { - logger.info("You must answer 'y' or 'n'."); - } - } - - // start loading - BasicDataSource data_src = new BasicDataSource(); - Connection conn = null; - try { - data_src = new BasicDataSource(); - data_src.setDriverClassName(options.db_driver); - data_src.setUsername(options.db_user); - data_src.setPassword(options.db_password); - data_src.setUrl(options.db_uri); - - conn = data_src.getConnection(); - String create_tables_file = options.output_sql + File.separator - + "create_tables.sql"; - logger.debug("using file " + create_tables_file); - // String create_tables_file = "generated" + File.separator + "sql" - // + File.separator + "create_tables.sql"; - - // READ THE FILE - String create_tables_sql = ""; - try { - BufferedReader in = new BufferedReader(new FileReader(create_tables_file)); - String line; - while ((line = in.readLine()) != null) { - create_tables_sql += line + "\n"; - } - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - if (filldb && StringUtils.isNotEmpty(this.options.getAuthLoginclass())) { - String insert_metadata_file = options.output_sql + File.separator + "insert_metadata.sql"; - logger.debug("using file " + insert_metadata_file); - - // READ THE FILE - try { - BufferedReader in = new BufferedReader(new FileReader(insert_metadata_file)); - String line; - while ((line = in.readLine()) != null) { - create_tables_sql += line + "\n"; - } - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - Statement stmt = conn.createStatement(); - boolean error = false; - logger.info("Updating database...."); - int i = 0; - - for (String command : create_tables_sql.split(";")) { - if (command.trim().length() > 0) { - try { - logger.debug(command.trim() + ";"); - stmt.executeUpdate(command.trim() ); - - if (i++ % 10 == 0) { - logger.debug("."); - } - } catch (Exception e) { - error = true; - logger.error("\nERROR executing command: " + command - + ";\n" + e.getMessage()); - } - - } - } - - if (error) { - logger.debug("Errors occurred. Make sure you provided sufficient rights! Inside mysql paste the following, assuming your database is called 'molgenis':" - + "\ncreate database molgenis; " - + "\ngrant all privileges on molgenis.* to molgenis@localhost " - + "identified by 'molgenis';" - + "\nflush privileges;" - + "\nuse molgenis;"); - } - - logger.info("MOLGENIS database updated succesfully"); - } catch (Exception e) { - logger.error(e); - - } finally { - if (conn != null) - { - conn.close(); - } - } - - } - - /** - * Report current settings of the generator. - */ - @Override - public final String toString() { - StringBuffer result = new StringBuffer(); - - // get name, description and padding - Map map = new LinkedHashMap(); - int padding = 0; - for (Generator g : generators) { - // get the name (without common path) - String generatorName = null; - if (g.getClass().getName().indexOf(this.getClass().getPackage().getName()) == 0) { - generatorName = g.getClass().getName().substring(this.getClass().getPackage().getName().length() + 1); - } else { - generatorName = g.getClass().getName(); - } - - // calculate the padding - padding = Math.max(padding, generatorName.length()); - - // add to map - map.put(generatorName, g.getDescription()); - } - - // print - for (Map.Entry entry : map.entrySet()) { - // create padding - String spaces = ""; - for (int i = entry.getKey().toString().length(); i < padding; i++) { - spaces += " "; - } - result.append(entry.getKey() + spaces + " #" + entry.getValue() - + "\n"); - } - return result.toString(); - } - - public MolgenisOptions getMolgenisOptions() { - return this.options; - } + Logger.getLogger("freemarker.cache").setLevel(Level.INFO); + logger.info("\nMOLGENIS version " + org.molgenis.Version.convertToString()); + logger.info("working dir: " + System.getProperty("user.dir")); + + // clean options + if (!options.output_src.endsWith("/")) + { + options.output_src = options.output_src + "/"; + } + if (!options.output_python.endsWith("/")) + { + options.output_python = options.output_python + "/"; + } + if (!options.output_cpp.endsWith("/")) + { + options.output_cpp = options.output_cpp + "/"; + } + if (!options.output_hand.endsWith("/")) + { + options.output_hand = options.output_hand + "/"; + } + + // USED MOLGENIS OPTIONS + generators.add(new UsedMolgenisOptionsGen()); + + // COPY resources + if (options.copy_resources) + { + generators.add(new MolgenisResourceCopyGen()); + } + + // DOCUMENTATION + if (options.generate_doc) + { + // not used: generators.add(new TableDocGen()); + // not used: generators.add(new EntityModelDocGen()); + generators.add(new DotDocGen()); + generators.add(new FileFormatDocGen()); + generators.add(new DotDocMinimalGen()); + generators.add(new ObjectModelDocGen()); + generators.add(new DotDocModuleDependencyGen()); + // not used: generators.add(new TextUmlGen()); + } + else + { + logger.info("Skipping documentation ...."); + } + + if (options.generate_cpp) + { + generators.add(new CPPCassette()); + } + + // TESTS + if (options.generate_tests) + { + generators.add(new TestDatabaseGen()); + generators.add(new TestCsvGen()); + generators.add(new TestDataSetGen()); + } + else + { + logger.info("Skipping Tests ...."); + } + // DATA + // generators.add(new DataPListGen()); + // generators.add(new ViewTypeGen()); + + if (options.generate_sql) + { + if (options.mapper_implementation.equals(MapperImplementation.JPA)) + { + System.out.println("--------------JPAGEN--------------"); + generators.add(new JpaDatabaseGen()); + generators.add(new DataTypeGen()); + generators.add(new JpaMapperGen()); + generators.add(new JDBCMetaDatabaseGen()); + + // generates Entity Listeners + // JpaEntityListenerGen entityListGen = new + // JpaEntityListenerGen(); + // entityListGen.setHandwritten(true); + // generators.add(entityListGen); + + if (options.generate_persistence) + { + generators.add(new PersistenceGen()); + } + + // generators.add(new FillMetadataTablesGen()); + + } + else + { + // DATABASE + // mysql.org + if (options.db_driver.equals("com.mysql.jdbc.Driver")) + { + generators.add(new MySqlCreateSubclassPerTableGen()); + generators.add(new MySqlAlterSubclassPerTableGen()); + // use multiquery optimization + if (options.mapper_implementation.equals(MapperImplementation.MULTIQUERY)) + { + generators.add(new JDBCDatabaseGen()); + generators.add(new DataTypeGen()); + generators.add(new MultiqueryMapperGen()); + } + else if (options.mapper_implementation.equals(MapperImplementation.PREPARED_STATEMENT)) + { + generators.add(new JDBCDatabaseGen()); + generators.add(new DataTypeGen()); + generators.add(new PStatementMapperGen()); + } + } // hsqldb.org + else if (options.db_driver.equals("oracle.jdbc.driver.OracleDriver")) + { + generators.add(new OracleCreateSubclassPerTableGen()); + generators.add(new JDBCDatabaseGen()); + generators.add(new DataTypeGen()); + generators.add(new PStatementMapperGen()); + } + else if (options.db_driver.equals("org.hsqldb.jdbcDriver")) + { + logger.info("HsqlDB generators ...."); + generators.add(new JDBCDatabaseGen()); + generators.add(new DataTypeGen()); + generators.add(new HSqlCreateSubclassPerTableGen()); + // generators.add(new MultiqueryMapperGen()); + generators.add(new PStatementMapperGen()); + } // postgresql + else if (options.db_driver.equals("org.postgresql.Driver")) + { + generators.add(new PSqlCreateSubclassPerTableGen()); + generators.add(new PStatementMapperGen()); + } // h2database.com, branch of hsqldb? + else if (options.db_driver.equals("org.h2.Driver")) + { + generators.add(new HSqlCreateSubclassPerTableGen()); + generators.add(new PStatementMapperGen()); + } // derby, not functional ignore. + else if (options.db_driver.equals("org.apache.derby.jdbc.EmbeddedDriver")) + { + generators.add(new DerbyCreateSubclassPerTableGen()); + } + else + { + logger.warn("Unknown database driver " + options.db_driver); + // System.exit(-1); + } + + // test + generators.add(new JDBCMetaDatabaseGen()); + // SQL + generators.add(new CountPerEntityGen()); + generators.add(new CountPerTableGen()); + generators.add(new FillMetadataTablesGen()); + } + + generators.add(new FillMetadataGen()); + + // authorization + if (!options.auth_loginclass.endsWith("SimpleLogin")) + { + generators.add(new MapperSecurityDecoratorGen()); + } + + // decorators + if (options.generate_decorators) + { + generators.add(new MapperDecoratorGen()); + } + + // DatabaseFactory + // if (!options.db_driver.equals("org.hsqldb.jdbcDriver")) { + generators.add(new DatabaseFactoryGen()); + // } + } + else + { + logger.info("SEVERE: Skipping ALL SQL ...."); + } + + if (options.generate_Python) + { + generators.add(new PythonDataTypeGen()); + } + else + { + logger.info("Skipping Python interface ...."); + } + // generators.add(new HsqlDbGen()); + + // CSV + if (options.generate_csv) + { + generators.add(new CsvReaderGen()); + generators.add(new CsvImportByIdGen()); + generators.add(new CsvExportGen()); + generators.add(new CsvImportGen()); + } + else + { + logger.info("Skipping CSV importers ...."); + } + // generators.add(new CopyMemoryToDatabaseGen()); + // generators.add(new CsvReaderFactoryGen()); + + // XML + // generators.add(new XmlMapperGen()); + + // R + if (options.generate_R) + { + generators.add(new REntityGen()); + generators.add(new RMatrixGen()); + generators.add(new RApiGen()); + } + else + { + logger.info("Skipping R interface ...."); + } + + // always generate frontcontroller + generators.add(new FrontControllerGen()); + + // also generate context (still used?) + generators.add(new MolgenisServletContextGen()); + generators.add(new MolgenisContextListenerGen()); + + // optional: the GUI + if (options.generate_gui) + { + generators.add(new MolgenisGuiServiceGen()); + } + + // HTML + if (options.generate_html) + { + generators.add(new HtmlFormGen()); + generators.add(new FormControllerGen()); + generators.add(new MenuControllerGen()); + } + else + { + logger.info("Skipping HTML (HTML,Form,Menu,Tree) ...."); + } + + // SCREEN PLUGIN + if (options.generate_plugins) + { + // generators.add(new PluginControllerGen()); + // generators.add(new PluginScreenFTLTemplateGen()); + // generators.add(new PluginScreenJavaTemplateGen()); + + // generators.add(new EasyPluginViewGen()); + generators.add(new EasyPluginControllerGen()); + // generators.add(new EasyPluginModelGen()); + } + else + { + logger.info("Skipping generation of plugins ...."); + } + + // plugin controllers - always need these to map plugins in the GUI + generators.add(new PluginControllerGen()); + + // SOAP + if (options.generate_soap) + { + generators.add(new SoapApiGen()); + } + else + { + logger.info("Skipping SOAP API ...."); + } + + if (options.generate_rest) + { + generators.add(new RestApiGen()); + } + else + { + logger.info("Skipping SOAP API ...."); + } + + if (options.generate_rdf) + { + generators.add(new RdfApiGen()); + } + else + { + logger.info("Skipping SOAP API ...."); + } + + // Excel + if (options.generate_ExcelImport) + { + generators.add(new ExcelReaderGen()); + generators.add(new ExcelImportGen()); + generators.add(new ExcelExportGen()); + generators.add(new ImportWizardExcelPrognosisGen()); + if (!options.generate_csv) + { + logger.info("Automatically including the CSV importers needed for Excel import"); + generators.add(new CsvReaderGen()); + generators.add(new CsvImportByIdGen()); + generators.add(new CsvExportGen()); + generators.add(new CsvImportGen()); + } + } + else + { + logger.info("Skipping Excel importer ...."); + } + // RDF + + // FIXME add more generators + // FIXME use configuration to add the generators + + // clean out generators + List use = new ArrayList(); + if (!ArrayUtils.isEmpty(generatorsToUse)) + { + for (Class c : generatorsToUse) + { + use.add(c.newInstance()); + } + generators = use; + } + + logger.debug("\nUsing generators:\n" + toString()); + + // parsing model + model = MolgenisModel.parse(options); + } + + private void loadFieldTypes() + { + MolgenisFieldTypes.addType(new BoolField()); + MolgenisFieldTypes.addType(new DateField()); + MolgenisFieldTypes.addType(new DatetimeField()); + MolgenisFieldTypes.addType(new DecimalField()); + MolgenisFieldTypes.addType(new EnumField()); + MolgenisFieldTypes.addType(new FileField()); + MolgenisFieldTypes.addType(new ImageField()); + MolgenisFieldTypes.addType(new HyperlinkField()); + // FieldTypeRegistry.addType(new ListField()); + MolgenisFieldTypes.addType(new LongField()); + MolgenisFieldTypes.addType(new MrefField()); + MolgenisFieldTypes.addType(new NSequenceField()); + MolgenisFieldTypes.addType(new OnoffField()); + MolgenisFieldTypes.addType(new StringField()); + MolgenisFieldTypes.addType(new TextField()); + MolgenisFieldTypes.addType(new XrefField()); + MolgenisFieldTypes.addType(new IntField()); + } + + /** + * Apply all generators on the model + * + * @param model + */ + public void generate() throws Exception + { + logger.info("generating ...."); + logger.info("\nUsing options:\n" + options.toString()); + + File generatedFolder = new File(options.output_dir); + if (generatedFolder.exists() && options.delete_generated_folder) + { + logger.info("removing previous generated folder " + generatedFolder); + deleteContentOfDirectory(generatedFolder); + } + + List threads = new ArrayList(); + for (final Generator g : generators) + { + Runnable runnable = new Runnable() + { + + public void run() + { + try + { + g.generate(model, options); + } + catch (Exception e) + { + e.printStackTrace(); + System.exit(-1); + } + } + }; + // executor.execute(runnable); + Thread thread = new Thread(runnable); + thread.start(); + threads.add(thread); + } + + // wait for all threads to complete + for (Thread thread : threads) + { + try + { + thread.join(); + } + catch (InterruptedException ignore) + { + } + } + + logger.info("Generation completed at " + new Date()); + } + + /** + * Deletes the content of directory (path), excluding hidden files like .svn + * + * @param path + * of directory to delete + * @return if and only if the content of directory (path) is successfully + * deleted; false otherwise + */ + static public boolean deleteContentOfDirectory(File path) + { + boolean result = true; + if (path.exists()) + { + File[] files = path.listFiles(); + for (File f : files) + { + if (!f.isHidden()) + { + if (f.isDirectory()) + { + result &= deleteContentOfDirectory(f); + f.delete(); + } + else + { + result &= f.delete(); + } + } + } + } + return result; + + } + + /** + * Compile a generated molgenis. + * + * Currently not implemented but is needed for batch generation. Not needed + * if you are generating inside an IDE such as eclipse. + * + * @return true if build is succesfull + * @throws IOException + */ + @Deprecated + public boolean compile() throws IOException + { + // reduce loggin + Logger.getLogger("org.apache.tools.ant.UnknownElement").setLevel(Level.ERROR); + Logger.getLogger("org.apache.tools.ant.Target").setLevel(Level.ERROR); + + // run the ant build script + logger.info("Compile ..."); + + File tempdir = new File(options.output_src); + // File tempdir = (File) ses.getAttribute("workingdir"); + + // copy the buildfile from sjabloon + File buildFileSource = new File("sjabloon/build.xml"); + File buildFile = new File(tempdir.getPath() + "/build.xml"); + copyFile(buildFileSource, buildFile); + + // create a new ant project + Project p = new Project(); + p.setUserProperty("ant.file", buildFile.getAbsolutePath()); + p.init(); + + // execute the ant target + ProjectHelper helper = ProjectHelper.getProjectHelper(); + p.addReference("ant.projectHelper", helper); + p.addBuildListener(new Log4jListener()); + helper.parse(p, buildFile); + + p.setProperty("jdbc.driver", "mysql-connector-java-5.1.0-bin.jar"); + p.setProperty("main.class", "MolgenisOnMysqlServer"); + p.executeTarget("createjar"); + logger.info("compilation complete."); + + return true; + } + + private static void copyFile(File src, File dst) throws IOException + { + InputStream in = new FileInputStream(src); + OutputStream out = new FileOutputStream(dst); + + // Transfer bytes from in to out + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) + { + out.write(buf, 0, len); + } + in.close(); + out.close(); + } + + /** + * Parse the model using settings in options + * + * @param options + * @return MOLGENIS model + * @throws Exception + */ + // private void parse() throws Exception { + // MolgenisModel language = new MolgenisModel(); + // model = language.parse(options); + // logger.debug("\nUsing metamodel:\n" + model); + // } + /** + * Load the generated SQL into the database. + * + * Warning: this will overwrite any existing data in the database!. + * + * @throws SQLException + * @throws FileNotFoundException + * @throws IOException + * @throws CmdLineException + */ + public void updateDb() throws SQLException, FileNotFoundException, IOException + { + updateDb(false); + } + + public void updateDb(boolean filldb) throws SQLException, FileNotFoundException, IOException + { + + boolean ask = false; + + // ask for confirmation that the database can be updated + // TODO: Use or throw away! Make a decision. + while (ask) + { + logger.info("Are you sure that you want overwrite database " + options.db_uri + + "?\n All existing data will be overwritten. \nAnswer 'y' or 'n'.\n"); + StringBuilder answerBuilder = new StringBuilder(); + int c; + while ((c = System.in.read()) != 13) + { + answerBuilder.append((char) c); + } + String answer = answerBuilder.toString().trim(); + if (answer.trim().equals("y")) + { + ask = false; + } + else if (answer.equals("n")) + { + logger.info("MOLGENIS database update canceled.\n"); + return; + } + else + { + logger.info("You must answer 'y' or 'n'."); + } + } + + // start loading + BasicDataSource data_src = new BasicDataSource(); + Statement stmt = null; + Connection conn = null; + try + { + data_src = new BasicDataSource(); + data_src.setDriverClassName(options.db_driver); + data_src.setUsername(options.db_user); + data_src.setPassword(options.db_password); + data_src.setUrl(options.db_uri); + + conn = data_src.getConnection(); + String create_tables_file = options.output_sql + File.separator + "create_tables.sql"; + logger.debug("using file " + create_tables_file); + // String create_tables_file = "generated" + File.separator + "sql" + // + File.separator + "create_tables.sql"; + + // READ THE FILE + StringBuilder create_tables_sqlBuilder = new StringBuilder(); + try + { + BufferedReader in = new BufferedReader(new FileReader(create_tables_file)); + String line; + while ((line = in.readLine()) != null) + { + create_tables_sqlBuilder.append(line).append('\n'); + } + in.close(); + } + catch (IOException e) + { + e.printStackTrace(); + } + + if (filldb && StringUtils.isNotEmpty(this.options.getAuthLoginclass())) + { + String insert_metadata_file = options.output_sql + File.separator + "insert_metadata.sql"; + logger.debug("using file " + insert_metadata_file); + + // READ THE FILE + try + { + BufferedReader in = new BufferedReader(new FileReader(insert_metadata_file)); + String line; + while ((line = in.readLine()) != null) + { + create_tables_sqlBuilder.append(line).append('\n'); + } + in.close(); + } + catch (IOException e) + { + e.printStackTrace(); + } + } + + stmt = conn.createStatement(); + boolean error = false; + logger.info("Updating database...."); + int i = 0; + + String create_tables_sql = create_tables_sqlBuilder.toString(); + for (String command : create_tables_sql.split(";")) + { + if (command.trim().length() > 0) + { + try + { + logger.debug(command.trim() + ";"); + stmt.executeUpdate(command.trim()); + + if (i++ % 10 == 0) + { + logger.debug("."); + } + } + catch (Exception e) + { + error = true; + logger.error("\nERROR executing command: " + command + ";\n" + e.getMessage()); + } + + } + } + + if (error) + { + logger.debug("Errors occurred. Make sure you provided sufficient rights! Inside mysql paste the following, assuming your database is called 'molgenis':" + + "\ncreate database molgenis; " + + "\ngrant all privileges on molgenis.* to molgenis@localhost " + + "identified by 'molgenis';" + + "\nflush privileges;" + "\nuse molgenis;"); + } + + logger.info("MOLGENIS database updated succesfully"); + } + catch (Exception e) + { + logger.error(e); + + } + finally + { + if (stmt != null) + { + try + { + stmt.close(); + } + catch (SQLException e) + { + if (conn != null) + { + conn.close(); + } + } + } + + } + + } + + /** + * Report current settings of the generator. + */ + @Override + public final String toString() + { + StringBuffer result = new StringBuffer(); + + // get name, description and padding + Map map = new LinkedHashMap(); + int padding = 0; + for (Generator g : generators) + { + // get the name (without common path) + String generatorName = null; + if (g.getClass().getName().indexOf(this.getClass().getPackage().getName()) == 0) + { + generatorName = g.getClass().getName().substring(this.getClass().getPackage().getName().length() + 1); + } + else + { + generatorName = g.getClass().getName(); + } + + // calculate the padding + padding = Math.max(padding, generatorName.length()); + + // add to map + map.put(generatorName, g.getDescription()); + } + + // print + for (Map.Entry entry : map.entrySet()) + { + // create padding + String spaces = ""; + for (int i = entry.getKey().toString().length(); i < padding; i++) + { + spaces += " "; + } + result.append(entry.getKey() + spaces + " #" + entry.getValue() + "\n"); + } + return result.toString(); + } + + public MolgenisOptions getMolgenisOptions() + { + return this.options; + } } \ No newline at end of file diff --git a/src/org/molgenis/MolgenisFieldTypes.java b/src/org/molgenis/MolgenisFieldTypes.java index f50db4fa1..ddf5686af 100644 --- a/src/org/molgenis/MolgenisFieldTypes.java +++ b/src/org/molgenis/MolgenisFieldTypes.java @@ -44,7 +44,7 @@ public class MolgenisFieldTypes public enum FieldTypeEnum { - BOOL, CHAR, DATE, DATE_TIME, DECIMAL, ENUM, EMAIL, FILE, FREEMARKER, HEXA, HYPERLINK, IMAGE, INT, LIST, LONG, MREF, NSEQUENCE, ON_OFF, RICHTEXT, STRING, TEXT, XREF, CATEGORICAL, UNKNOWN, + BOOL, CHAR, DATE, DATE_TIME, DECIMAL, ENUM, EMAIL, FILE, FREEMARKER, HEXA, HYPERLINK, IMAGE, INT, LIST, LONG, MREF, NSEQUENCE, ON_OFF, STRING, TEXT, LONGTEXT, XREF, CATEGORICAL, UNKNOWN, RICHTEXT } /** Initialize default field types */ @@ -70,6 +70,7 @@ private static void init() addType(new XrefField()); addType(new IntField()); addType(new RichtextField()); + // addType(new LongTextField()); addType(new FreemarkerField()); init = true; diff --git a/src/org/molgenis/MolgenisOptions.java b/src/org/molgenis/MolgenisOptions.java index 261dc5400..55abb2422 100644 --- a/src/org/molgenis/MolgenisOptions.java +++ b/src/org/molgenis/MolgenisOptions.java @@ -4,6 +4,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; import java.io.Serializable; import java.lang.reflect.Field; import java.util.ArrayList; @@ -11,6 +12,7 @@ import java.util.Map; import java.util.Properties; +import org.apache.commons.io.IOUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.molgenis.framework.ui.html.render.LinkoutRenderDecorator; @@ -41,10 +43,10 @@ public enum MapperImplementation { MULTIQUERY, JPA, PREPARED_STATEMENT, UNKNOWN } - + /** * Possible log4j log targets - * + * */ public enum LogTarget { @@ -53,7 +55,7 @@ public enum LogTarget /** Properties file where this data came from */ private String molgenis_properties = ""; - + /** Password file where passwords are */ private String molgenis_passwd = ""; @@ -159,13 +161,13 @@ public enum LogTarget @Option(name = "generate_persistence", param = Option.Param.STRING, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Expert option: Choosing the JPA persistence unit name from the persistence.xml that is used by molgenis. Default: molgenis") public String jpa_persistenceUnitName = "molgenis"; - + @Option(name = "generate_persistence", param = Option.Param.BOOLEAN, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Expert option: Choosing whether persistence.xml is generated by molgenis (true) or supplied by user (false). Default: true") public boolean generate_persistence = true; - + @Option(name = "hibernate_dialect", param = Option.Param.STRING, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Expert option: Choosing the JPA dialect for persistence.xml. Default: MySQL5Dialect") public String hibernate_dialect = "MySQL5Dialect"; - + @Option(name = "jpa_use_sequence", param = Option.Param.BOOLEAN, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Expert option: Choosing whether sequence are used to generate primary key (true) or auto (false: default)") public boolean jpa_use_sequence = false; @@ -228,8 +230,8 @@ public enum LogTarget @Option(name = "generate_ExcelImport", param = Option.Param.BOOLEAN, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Should Excel file importing be generated. Default: true.") public boolean generate_ExcelImport = true; - @Option(name = "generate_MolgenisServlet", param = Option.Param.BOOLEAN, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Should The molgenisServlet be generated or does the user supply ones own. Default: true.") - public boolean generate_MolgenisServlet = true; + @Option(name = "generate_gui", param = Option.Param.BOOLEAN, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Should the GUI service be generated. Default: true.") + public boolean generate_gui = true; @Option(name = "db_mode", param = Option.Param.STRING, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Which mode should the molgenisServlet use when contacting the dabase. Default: 'servlet'") public String db_mode = "servlet"; @@ -274,25 +276,29 @@ public enum LogTarget // default set to false as partial generation leads to compile problems in // for example molgenis_apps public boolean delete_generated_folder = true; - + @Option(name = "authorizable", param = Option.Param.COLLECTION, type = Option.Type.OPTIONAL_ARGUMENT, usage = "For use in molgenis_apps! Tells the generator on which entities to append an implements='Authorizable'. Default: new ArrayList()") public ArrayList authorizable = new ArrayList(); - + @Option(name = "services", param = Option.Param.COLLECTION, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Register services to the FrontController. (replaces webserver mappings and MolgenisServlet) Default: new ArrayList()") public ArrayList services = new ArrayList(); - @Option(name = "disable_decorators", param = Option.Param.BOOLEAN, type = Option.Type.OPTIONAL_ARGUMENT, usage="disables all decorators for generated test") + @Option(name = "disable_decorators", param = Option.Param.BOOLEAN, type = Option.Type.OPTIONAL_ARGUMENT, usage = "disables all decorators for generated test") public boolean disable_decorators = false; - - @Option(name = "log4j_properties_uri", param = Option.Param.STRING, type = Type.OPTIONAL_ARGUMENT, usage="specify the location of the log4j.properties file that Molgenis should use, if not specified than log_level and log_target properties are used instead") + + @Option(name = "log4j_properties_uri", param = Option.Param.STRING, type = Type.OPTIONAL_ARGUMENT, usage = "specify the location of the log4j.properties file that Molgenis should use, if not specified than log_level and log_target properties are used instead") public String log4j_properties_uri = ""; - - /** The log level of log4j used by your application. Used by FrontController. **/ - @Option(name = "log_level", param = Option.Param.LOG4JLEVEL, type = Option.Type.OPTIONAL_ARGUMENT, usage="Use this log level to initialize log4j. Default: debug") + + /** + * The log level of log4j used by your application. Used by FrontController. + **/ + @Option(name = "log_level", param = Option.Param.LOG4JLEVEL, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Use this log level to initialize log4j. Default: debug") public Level log_level = Level.INFO; - - /** The log level of log4j used by your application. Used by FrontController. **/ - @Option(name = "log_target", param = Option.Param.ENUM, type = Option.Type.OPTIONAL_ARGUMENT, usage="Use this log target to initialize log4j. Default: console") + + /** + * The log level of log4j used by your application. Used by FrontController. + **/ + @Option(name = "log_target", param = Option.Param.ENUM, type = Option.Type.OPTIONAL_ARGUMENT, usage = "Use this log target to initialize log4j. Default: console") public LogTarget log_target = LogTarget.CONSOLE; @Option(name = "hibernate_search_index_base", param = Option.Param.STRING, type = Type.OPTIONAL_ARGUMENT, usage = "Directory where the full text index is created. Default: /tmp/lucene") @@ -366,68 +372,83 @@ public Map getOptionsAsMap() throws Exception * @throws FileNotFoundException * @throws CmdLineException */ - public MolgenisOptions(String propertiesFile) throws FileNotFoundException, - IOException, CmdLineException + public MolgenisOptions(String propertiesFile) throws FileNotFoundException, IOException, CmdLineException { this.molgenis_properties = propertiesFile; Properties props = new Properties(); + InputStream is = null; try { // try to load from local files - props.load(new FileInputStream(propertiesFile.trim())); + is = new FileInputStream(propertiesFile.trim()); + props.load(is); } catch (FileNotFoundException e) { + InputStream is2 = ClassLoader.getSystemResourceAsStream(propertiesFile.trim()); try { // try to load from classpath - props.load(ClassLoader.getSystemResourceAsStream(propertiesFile - .trim())); + props.load(is2); } catch (Exception e2) { - throw new IOException("couldn't find file " - + new File(propertiesFile).getAbsolutePath()); + throw new IOException("couldn't find file " + new File(propertiesFile).getAbsolutePath()); } - + finally + { + IOUtils.closeQuietly(is2); + } + } + finally + { + IOUtils.closeQuietly(is); } CmdLineParser parser = new CmdLineParser(this); parser.parse(props); this.molgenis_properties = propertiesFile; - - //parse passwordfile + + // parse passwordfile String passwordFile = propertiesFile.replace(".properties", ".passwd"); - this.molgenis_passwd= passwordFile; + this.molgenis_passwd = passwordFile; props = new Properties(); + is = null; try { // try to load from local files - props.load(new FileInputStream(passwordFile.trim())); + is = new FileInputStream(passwordFile.trim()); + props.load(is); } catch (FileNotFoundException e) { + InputStream is2 = ClassLoader.getSystemResourceAsStream(passwordFile.trim()); try { // try to load from classpath - props.load(ClassLoader.getSystemResourceAsStream(passwordFile - .trim())); + props.load(is2); } catch (Exception e2) { - //no biggie + // no biggie } - + finally + { + IOUtils.closeQuietly(is2); + } + } + finally + { + IOUtils.closeQuietly(is); } parser = new CmdLineParser(this); parser.parse(props); - - //warn if no password was provided - if("".equals(this.db_password)) - System.err.println("WARNING: db_password was not provided in neither "+propertiesFile +" nor "+passwordFile); - Logger.getLogger(this.getClass().getSimpleName()).debug( - "parsed properties file."); + // warn if no password was provided + if ("".equals(this.db_password)) System.err.println("WARNING: db_password was not provided in neither " + + propertiesFile + " nor " + passwordFile); + + Logger.getLogger(this.getClass().getSimpleName()).debug("parsed properties file."); } /** @@ -445,15 +466,13 @@ public MolgenisOptions(Properties properties) { parser = new CmdLineParser(this); parser.parse(properties); - Logger.getLogger(this.getClass().getSimpleName()).debug( - "parsed properties file."); + Logger.getLogger(this.getClass().getSimpleName()).debug("parsed properties file."); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); - throw new RuntimeException("Cannot find property file: " - + e.getMessage()); + throw new RuntimeException("Cannot find property file: " + e.getMessage()); } } @@ -473,12 +492,14 @@ public String toString() } return ""; } - - public String getHibernateDialect() { + + public String getHibernateDialect() + { return this.hibernate_dialect; } - public String getHibernateSearchIndexBase() { + public String getHibernateSearchIndexBase() + { return this.hibernate_search_index_base; } @@ -644,8 +665,7 @@ public MapperImplementation getMapperImplementation() return mapper_implementation; } - public void setMapperImplementation( - MapperImplementation mapper_implementation) + public void setMapperImplementation(MapperImplementation mapper_implementation) { this.mapper_implementation = mapper_implementation; } @@ -743,6 +763,4 @@ public void setLog4j_properties_uri(String log4j_properties_uri) this.log4j_properties_uri = log4j_properties_uri; } - - } diff --git a/src/org/molgenis/Version.java b/src/org/molgenis/Version.java index 325ee782d..a10cdcbad 100644 --- a/src/org/molgenis/Version.java +++ b/src/org/molgenis/Version.java @@ -14,7 +14,7 @@ * api. */ public class Version -{ +{ // static members /** * The major part of the version, which is changed for major interface @@ -30,18 +30,16 @@ public class Version /** The maintenance part of the version, which is changed for bug-fixes */ public static final int MAINTENANCE = 0; - - /** Flag to indicate that this is a testing release*/ - public static final boolean TESTING = true; + /** Flag to indicate that this is a testing release */ + public static final boolean TESTING = true; // static access methods /** string representation of the version */ public static String convertToString() { - if(!TESTING) - return "" + MAJOR + "." + MINOR + "." + MAINTENANCE ; + if (!TESTING) return "" + MAJOR + "." + MINOR + "." + MAINTENANCE; else - return "" + MAJOR +"."+MINOR +"."+MAINTENANCE +"-testing"; + return "" + MAJOR + "." + MINOR + "." + MAINTENANCE + "-testing"; } } diff --git a/src/org/molgenis/fieldtypes/BoolField.java b/src/org/molgenis/fieldtypes/BoolField.java index d6ed29897..ab284ecea 100644 --- a/src/org/molgenis/fieldtypes/BoolField.java +++ b/src/org/molgenis/fieldtypes/BoolField.java @@ -13,14 +13,14 @@ public String getJavaPropertyType() { return "Boolean"; } - + @Override public String getJavaAssignment(String value) { - if(value == null || value.equals("")) return "null"; - return ""+Boolean.parseBoolean(value.toString()); + if (value == null || value.equals("")) return "null"; + return "" + Boolean.parseBoolean(value.toString()); } - + @Override public String getJavaPropertyDefault() { @@ -32,7 +32,7 @@ public String getMysqlType() throws MolgenisModelException { return "BOOL"; } - + @Override public String getOracleType() throws MolgenisModelException { @@ -44,7 +44,7 @@ public String getHsqlType() { return "INTEGER"; } - + @Override public String getXsdType() { @@ -79,8 +79,9 @@ public Class getJavaType() { return Boolean.class; } - - public Boolean getTypedValue(String value) { + + public Boolean getTypedValue(String value) + { return Boolean.parseBoolean(value); } diff --git a/src/org/molgenis/fieldtypes/CategoricalType.java b/src/org/molgenis/fieldtypes/CategoricalType.java index fa6333578..2bdffc8d6 100644 --- a/src/org/molgenis/fieldtypes/CategoricalType.java +++ b/src/org/molgenis/fieldtypes/CategoricalType.java @@ -112,9 +112,11 @@ public FieldTypeEnum getEnumType() } /** - * @return For a categorical variable type, return the map of value->label pairs. + * @return For a categorical variable type, return the map of value->label + * pairs. */ - public Map getCategoryMapping() { + public Map getCategoryMapping() + { return categoryMapping; } } diff --git a/src/org/molgenis/fieldtypes/CharField.java b/src/org/molgenis/fieldtypes/CharField.java index a36b5da7e..ecd4b3148 100644 --- a/src/org/molgenis/fieldtypes/CharField.java +++ b/src/org/molgenis/fieldtypes/CharField.java @@ -15,10 +15,10 @@ public class CharField extends FieldType @Override public String getJavaAssignment(String value) throws MolgenisModelException { - if(value == null || value.equals("") ) return "null"; - return "\""+value+"\""; + if (value == null || value.equals("")) return "null"; + return "\"" + value + "\""; } - + @Override public String getJavaPropertyDefault() throws MolgenisModelException { @@ -34,20 +34,21 @@ public String getJavaPropertyType() throws MolgenisModelException @Override public String getMysqlType() throws MolgenisModelException { - return "CHAR("+f.getVarCharLength()+")"; + return "CHAR(" + f.getVarCharLength() + ")"; } - + @Override public String getOracleType() throws MolgenisModelException { - return "CHAR("+f.getVarCharLength()+")"; + return "CHAR(" + f.getVarCharLength() + ")"; } @Override public String getHsqlType() throws MolgenisModelException { - return "CHAR("+f.getVarCharLength()+")"; + return "CHAR(" + f.getVarCharLength() + ")"; } + @Override public String getXsdType() throws MolgenisModelException { @@ -61,7 +62,7 @@ public String getFormatString() } @Override - public HtmlInput createInput(String name, String xrefEntityClassName) throws HtmlInputException + public HtmlInput createInput(String name, String xrefEntityClassName) throws HtmlInputException { return new StringInput(name); } @@ -93,7 +94,7 @@ public FieldTypeEnum getEnumType() { return FieldTypeEnum.CHAR; } - + @Override public List getAllowedOperators() { diff --git a/src/org/molgenis/fieldtypes/DateField.java b/src/org/molgenis/fieldtypes/DateField.java index c4868518d..bdcc5914c 100644 --- a/src/org/molgenis/fieldtypes/DateField.java +++ b/src/org/molgenis/fieldtypes/DateField.java @@ -19,19 +19,20 @@ public String getJavaPropertyType() throws MolgenisModelException { return "java.util.Date"; } - + @Override public String getJavaAssignment(String value) { - if(value == null || value.equals("")) return "null"; - return "java.sql.Date.valueOf(\""+value+"\")"; + if (value == null || value.equals("")) return "null"; + return "java.sql.Date.valueOf(\"" + value + "\")"; } - + @Override public String getJavaPropertyDefault() { - if(f.isAuto()) return "new java.sql.Date(new java.util.Date().getTime())"; - else return getJavaAssignment(f.getDefaultValue()); + if (f.isAuto()) return "new java.sql.Date(new java.util.Date().getTime())"; + else + return getJavaAssignment(f.getDefaultValue()); } @Override @@ -39,13 +40,13 @@ public String getMysqlType() throws MolgenisModelException { return "DATE"; } - + @Override public String getOracleType() throws MolgenisModelException { return "DATE"; } - + @Override public String getJavaSetterType() throws MolgenisModelException { @@ -57,6 +58,7 @@ public String getHsqlType() { return "DATE"; } + @Override public String getXsdType() { @@ -80,7 +82,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "time_t"; } - + @Override public String getCppJavaPropertyType() { @@ -101,7 +103,7 @@ public FieldTypeEnum getEnumType() { return FieldTypeEnum.DATE; } - + @Override public List getAllowedOperators() { diff --git a/src/org/molgenis/fieldtypes/DatetimeField.java b/src/org/molgenis/fieldtypes/DatetimeField.java index 4738b16de..fc7452ecf 100644 --- a/src/org/molgenis/fieldtypes/DatetimeField.java +++ b/src/org/molgenis/fieldtypes/DatetimeField.java @@ -19,19 +19,20 @@ public String getJavaPropertyType() throws MolgenisModelException { return "java.util.Date"; } - + @Override public String getJavaAssignment(String value) { - if(value == null || value.equals("")) return "null"; - return "java.sql.Timestamp.valueOf(\""+value+"\")"; + if (value == null || value.equals("")) return "null"; + return "java.sql.Timestamp.valueOf(\"" + value + "\")"; } - + @Override public String getJavaPropertyDefault() { - if(f.isAuto()) return "new java.sql.Date(new java.util.Date().getTime())"; - else return getJavaAssignment(f.getDefaultValue()); + if (f.isAuto()) return "new java.sql.Date(new java.util.Date().getTime())"; + else + return getJavaAssignment(f.getDefaultValue()); } @Override @@ -39,13 +40,13 @@ public String getMysqlType() throws MolgenisModelException { return "DATETIME"; } - + @Override public String getOracleType() throws MolgenisModelException { return "DATE"; } - + @Override public String getXsdType() { @@ -81,7 +82,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "time_t"; } - + @Override public String getCppJavaPropertyType() { @@ -97,12 +98,12 @@ public Date getTypedValue(String value) throws ParseException { return new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(value); } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.DATE_TIME; } - + @Override public List getAllowedOperators() { diff --git a/src/org/molgenis/fieldtypes/DecimalField.java b/src/org/molgenis/fieldtypes/DecimalField.java index e9d01a852..52eea543a 100644 --- a/src/org/molgenis/fieldtypes/DecimalField.java +++ b/src/org/molgenis/fieldtypes/DecimalField.java @@ -22,22 +22,22 @@ public String getJavaPropertyType() @Override public String getJavaAssignment(String value) { - if(value == null || value.equals("") ) return "null"; - return ""+Double.parseDouble(value); + if (value == null || value.equals("")) return "null"; + return "" + Double.parseDouble(value); } - + @Override public String getJavaPropertyDefault() { return getJavaAssignment(f.getDefaultValue()); } - + @Override public String getMysqlType() throws MolgenisModelException { return "DECIMAL(65,30)"; } - + @Override public String getOracleType() throws MolgenisModelException { @@ -49,7 +49,7 @@ public String getHsqlType() { return "DOUBLE"; } - + @Override public String getXsdType() { @@ -89,12 +89,12 @@ public Double getTypedValue(String value) throws ParseException { return Double.parseDouble(value); } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.DECIMAL; } - + @Override public List getAllowedOperators() { diff --git a/src/org/molgenis/fieldtypes/EmailField.java b/src/org/molgenis/fieldtypes/EmailField.java index 035f71848..495fd1452 100644 --- a/src/org/molgenis/fieldtypes/EmailField.java +++ b/src/org/molgenis/fieldtypes/EmailField.java @@ -13,10 +13,10 @@ public class EmailField extends FieldType @Override public String getJavaAssignment(String value) throws MolgenisModelException { - if(value == null || value.equals("") ) return "null"; - return "\""+value+"\""; + if (value == null || value.equals("")) return "null"; + return "\"" + value + "\""; } - + @Override public String getJavaPropertyDefault() throws MolgenisModelException { @@ -34,7 +34,7 @@ public String getMysqlType() throws MolgenisModelException { return "VARCHAR(255)"; } - + @Override public String getOracleType() throws MolgenisModelException { @@ -46,6 +46,7 @@ public String getHsqlType() throws MolgenisModelException { return "VARCHAR(255)"; } + @Override public String getXsdType() throws MolgenisModelException { @@ -69,7 +70,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "string"; } - + @Override public String getCppJavaPropertyType() { @@ -87,7 +88,6 @@ public String getTypedValue(String value) throws ParseException return value; } - public FieldTypeEnum getEnumType() { return FieldTypeEnum.EMAIL; diff --git a/src/org/molgenis/fieldtypes/EnumField.java b/src/org/molgenis/fieldtypes/EnumField.java index 4a603fb26..4e4e2e13e 100644 --- a/src/org/molgenis/fieldtypes/EnumField.java +++ b/src/org/molgenis/fieldtypes/EnumField.java @@ -15,14 +15,14 @@ public String getJavaPropertyType() { return "String"; } - + @Override public String getJavaAssignment(String value) { - if(value == null || value.equals("") ) return "null"; - return "\""+value+"\""; + if (value == null || value.equals("")) return "null"; + return "\"" + value + "\""; } - + @Override public String getJavaPropertyDefault() { @@ -32,21 +32,21 @@ public String getJavaPropertyDefault() @Override public String getMysqlType() throws MolgenisModelException { - return "ENUM("+this.toCsv(f.getEnumOptions())+")"; + return "ENUM(" + this.toCsv(f.getEnumOptions()) + ")"; } - + @Override public String getOracleType() throws MolgenisModelException { return "VARCHAR2(255)"; } - @Override public String getHsqlType() { return "VARCHAR(1024)"; } + @Override public String getXsdType() { @@ -70,7 +70,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "string"; } - + @Override public String getCppJavaPropertyType() { @@ -88,7 +88,7 @@ public Object getTypedValue(String value) throws ParseException { throw new UnsupportedOperationException("Unable to cast enum type"); } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.ENUM; diff --git a/src/org/molgenis/fieldtypes/FieldType.java b/src/org/molgenis/fieldtypes/FieldType.java index 56b3281ed..e3cce2ed8 100644 --- a/src/org/molgenis/fieldtypes/FieldType.java +++ b/src/org/molgenis/fieldtypes/FieldType.java @@ -64,7 +64,7 @@ public String getJavaSetterType() throws MolgenisModelException * @throws MolgenisModelException */ abstract public String getJavaPropertyType() throws MolgenisModelException; - + /** * Product the Java type of this field type. Default: "String". * @@ -80,8 +80,7 @@ public String getJavaSetterType() throws MolgenisModelException * @return default in java code * @throws MolgenisModelException */ - abstract public String getJavaPropertyDefault() - throws MolgenisModelException; + abstract public String getJavaPropertyDefault() throws MolgenisModelException; /** * Produce a valid Java snippet to set a value for field. @@ -89,16 +88,16 @@ abstract public String getJavaPropertyDefault() * @return default in java code * @throws MolgenisModelException */ - public abstract String getJavaAssignment(String value) - throws MolgenisModelException; + public abstract String getJavaAssignment(String value) throws MolgenisModelException; /** * Produce the Java class corresponding to the value + * * @return Java class * @throws MolgenisModelException */ public abstract Class getJavaType() throws MolgenisModelException; - + /** * Produce a valid mysql snippet indicating the mysql type. E.g. "BOOL". * @@ -120,14 +119,14 @@ public abstract String getJavaAssignment(String value) */ public String toCsv(List elements) { - String result = ""; + StringBuilder strBuilder = new StringBuilder(); for (String str : elements) - { - result += ((elements.get(0) == str) ? "" : ",") + "'" + str + "'"; - } + strBuilder.append('\'').append(str).append('\'').append(','); - return result; + if (!elements.isEmpty()) strBuilder.deleteCharAt(strBuilder.length() - 1); + + return strBuilder.toString(); } /** @@ -145,6 +144,7 @@ public void setField(Field f) /** * Get the format string, e.g. '%s' + * * @return */ public abstract String getFormatString(); @@ -154,27 +154,29 @@ public void setField(Field f) */ public String toString() { - return this.getClass().getSimpleName().replace("Field", "") - .toLowerCase(); + return this.getClass().getSimpleName().replace("Field", "").toLowerCase(); } - + public HtmlInput createInput(String name) throws HtmlInputException { return this.createInput(name, null); } - + public abstract HtmlInput createInput(String name, String xrefEntityClassNames) throws HtmlInputException; - //public abstract HtmlInput createInput(String name, Class xrefClass ) throws HtmlInputException; - + + // public abstract HtmlInput createInput(String name, Class xrefClass ) throws HtmlInputException; + public abstract String getCppJavaPropertyType() throws MolgenisModelException; public abstract String getOracleType() throws MolgenisModelException; - + public abstract Object getTypedValue(String value) throws ParseException; - + public abstract MolgenisFieldTypes.FieldTypeEnum getEnumType(); - public List getAllowedOperators() { + public List getAllowedOperators() + { return Arrays.asList("EQUALS", "NOT EQUALS"); } } diff --git a/src/org/molgenis/fieldtypes/FileField.java b/src/org/molgenis/fieldtypes/FileField.java index 0d671d858..e2b247f9b 100644 --- a/src/org/molgenis/fieldtypes/FileField.java +++ b/src/org/molgenis/fieldtypes/FileField.java @@ -16,14 +16,14 @@ public String getJavaPropertyType() { return "String"; } - + @Override public String getJavaAssignment(String value) { - if(value == null || value.equals("")) return "null"; - return "\""+value+"\""; + if (value == null || value.equals("")) return "null"; + return "\"" + value + "\""; } - + @Override public String getJavaPropertyDefault() { @@ -35,7 +35,7 @@ public String getMysqlType() throws MolgenisModelException { return "VARCHAR(1024)"; } - + @Override public String getOracleType() throws MolgenisModelException { @@ -47,6 +47,7 @@ public String getHsqlType() { return "VARCHAR(1024)"; } + @Override public String getXsdType() { @@ -70,7 +71,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "string"; } - + @Override public String getCppJavaPropertyType() { @@ -85,13 +86,16 @@ public Class getJavaType() public File getTypedValue(String value) throws ParseException { File file = new File(value); - if (file.exists()) { + if (file.exists()) + { return file; - } else { + } + else + { throw new ParseException("File " + value + " not found.", 0); } } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.FILE; diff --git a/src/org/molgenis/fieldtypes/HyperlinkField.java b/src/org/molgenis/fieldtypes/HyperlinkField.java index 2164bb860..939b7e1b1 100644 --- a/src/org/molgenis/fieldtypes/HyperlinkField.java +++ b/src/org/molgenis/fieldtypes/HyperlinkField.java @@ -15,26 +15,26 @@ public String getJavaPropertyType() { return "String"; } - + @Override public String getJavaAssignment(String value) { - if(value == null || value.equals("") ) return "null"; - return "\""+value+"\""; + if (value == null || value.equals("")) return "null"; + return "\"" + value + "\""; } - + @Override public String getJavaPropertyDefault() { return getJavaAssignment(f.getDefaultValue()); } - + @Override public String getMysqlType() throws MolgenisModelException { return "VARCHAR(255)"; } - + @Override public String getOracleType() throws MolgenisModelException { @@ -46,6 +46,7 @@ public String getHsqlType() { return "TEXT"; } + @Override public String getXsdType() { @@ -86,7 +87,7 @@ public String getTypedValue(String value) throws ParseException { return value; } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.HYPERLINK; diff --git a/src/org/molgenis/fieldtypes/ImageField.java b/src/org/molgenis/fieldtypes/ImageField.java index 58d46f40c..744a6b745 100644 --- a/src/org/molgenis/fieldtypes/ImageField.java +++ b/src/org/molgenis/fieldtypes/ImageField.java @@ -1,6 +1,5 @@ package org.molgenis.fieldtypes; - public class ImageField extends FileField { } diff --git a/src/org/molgenis/fieldtypes/IntField.java b/src/org/molgenis/fieldtypes/IntField.java index f9e2a035c..14fb94d13 100644 --- a/src/org/molgenis/fieldtypes/IntField.java +++ b/src/org/molgenis/fieldtypes/IntField.java @@ -17,32 +17,32 @@ public String getJavaPropertyType() throws MolgenisModelException { return "Integer"; } - + @Override public String getJavaAssignment(String value) { - if(value == null || value.equals("")) return "null"; - return ""+Integer.parseInt(value); + if (value == null || value.equals("")) return "null"; + return "" + Integer.parseInt(value); } - + @Override public String getJavaPropertyDefault() { return getJavaAssignment(f.getDefaultValue()); } - + @Override public String getMysqlType() throws MolgenisModelException { return "INTEGER"; } - + @Override public String getOracleType() throws MolgenisModelException { return "NUMBER (10,0)"; } - + public String getJavaSetterType() throws MolgenisModelException { return "Int"; @@ -53,6 +53,7 @@ public String getHsqlType() { return "INT"; } + @Override public String getXsdType() { @@ -76,7 +77,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "int"; } - + @Override public String getCppJavaPropertyType() { @@ -92,12 +93,12 @@ public Object getTypedValue(String value) throws ParseException { return Integer.parseInt(value); } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.INT; } - + @Override public List getAllowedOperators() { diff --git a/src/org/molgenis/fieldtypes/ListField.java b/src/org/molgenis/fieldtypes/ListField.java index b9ddd6db0..ca63010f1 100644 --- a/src/org/molgenis/fieldtypes/ListField.java +++ b/src/org/molgenis/fieldtypes/ListField.java @@ -17,33 +17,33 @@ public String getJavaPropertyDefault() throws MolgenisModelException { return "new java.util.ArrayList()"; } - + @Override public String getJavaAssignment(String value) { return "NOT IMPLEMENTED"; } - + @Override public String getJavaPropertyType() { return "java.util.List"; } - + @Override public String getMysqlType() throws MolgenisModelException { - //should never happen? + // should never happen? return "LIST CANNOT BE IN SQL"; } - + @Override public String getOracleType() throws MolgenisModelException { - //should never happen? + // should never happen? return "LIST CANNOT BE IN SQL"; } - + @Override public String getJavaSetterType() throws MolgenisModelException { @@ -55,10 +55,10 @@ public String getHsqlType() { return "LIST CANNOT BE IN SQL"; } - + public String getXsdType() { - return "" ; + return ""; } @Override @@ -81,7 +81,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "vector"; } - + @Override public String getCppJavaPropertyType() { @@ -97,7 +97,7 @@ public java.util.List getTypedValue(String value) throws ParseException { return Arrays.asList(StringUtils.split(value, ",")); } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.LIST; diff --git a/src/org/molgenis/fieldtypes/LongField.java b/src/org/molgenis/fieldtypes/LongField.java index 711e33a8c..7414638af 100644 --- a/src/org/molgenis/fieldtypes/LongField.java +++ b/src/org/molgenis/fieldtypes/LongField.java @@ -21,23 +21,22 @@ public String getJavaPropertyType() @Override public String getJavaAssignment(String value) { - if (value == null || value.equals("") ) return "null"; + if (value == null || value.equals("")) return "null"; return "" + Long.parseLong(value) + "L"; } - @Override public String getJavaPropertyDefault() { return getJavaAssignment(f.getDefaultValue()); } - + @Override public String getMysqlType() throws MolgenisModelException { return "BIGINT"; } - + @Override public String getOracleType() throws MolgenisModelException { @@ -49,6 +48,7 @@ public String getHsqlType() { return "LONG"; } + @Override public String getXsdType() { @@ -72,7 +72,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "long"; } - + @Override public String getCppJavaPropertyType() { @@ -88,12 +88,12 @@ public Long getTypedValue(String value) throws ParseException { return Long.parseLong(value); } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.LONG; } - + @Override public List getAllowedOperators() { diff --git a/src/org/molgenis/fieldtypes/MrefField.java b/src/org/molgenis/fieldtypes/MrefField.java index 532f14d6a..9e90bb903 100644 --- a/src/org/molgenis/fieldtypes/MrefField.java +++ b/src/org/molgenis/fieldtypes/MrefField.java @@ -12,9 +12,12 @@ /** * Many to many reference. * - * Example MOLGENIS DSL, - *

- *
+ * Example MOLGENIS DSL, + * + *
+ * 
+ * 
+ * * This example would in the UI show a seletion box with 'name' elements. */ public class MrefField extends FieldType @@ -24,44 +27,45 @@ public String getJavaAssignment(String value) { return "NOT IMPLEMENTED"; } - + @Override public String getJavaPropertyType() throws MolgenisModelException { - //Entity e_ref = f.getXrefEntity(); + // Entity e_ref = f.getXrefEntity(); Field f_ref = f.getXrefField(); - return "java.util.List<"+getFieldType(f_ref).getJavaPropertyType()+">"; + return "java.util.List<" + getFieldType(f_ref).getJavaPropertyType() + ">"; } - + @Override public String getJavaPropertyDefault() throws MolgenisModelException { - //Entity e_ref = f.getXrefEntity(); + // Entity e_ref = f.getXrefEntity(); Field f_ref = f.getXrefField(); - //if(f.getDefaultValue() == null || f.getDefaultValue() == "") "new java.util.ArrayList<"+getFieldType(f_ref).getJavaPropertyType(f_ref)+">()"; - //FIXME can there be defaults here? - return "new java.util.ArrayList<"+getFieldType(f_ref).getJavaPropertyType()+">()"; + // if(f.getDefaultValue() == null || f.getDefaultValue() == "") + // "new java.util.ArrayList<"+getFieldType(f_ref).getJavaPropertyType(f_ref)+">()"; + // FIXME can there be defaults here? + return "new java.util.ArrayList<" + getFieldType(f_ref).getJavaPropertyType() + ">()"; } - + @Override public String getJavaSetterType() throws MolgenisModelException { - //Entity e_ref = f.getXrefEntity(); + // Entity e_ref = f.getXrefEntity(); Field f_ref = f.getXrefField(); - return "new java.util.ArrayList<"+getFieldType(f_ref).getJavaSetterType()+">()"; + return "new java.util.ArrayList<" + getFieldType(f_ref).getJavaSetterType() + ">()"; } - + @Override public String getMysqlType() throws MolgenisModelException { - //FIXME this function should be never called??? + // FIXME this function should be never called??? return getFieldType(f.getXrefField()).getMysqlType(); } - + @Override public String getOracleType() throws MolgenisModelException { - //FIXME this function should be never called??? + // FIXME this function should be never called??? return getFieldType(f.getXrefField()).getOracleType(); } @@ -70,7 +74,7 @@ public String getHsqlType() throws MolgenisModelException { return getFieldType(f.getXrefField()).getHsqlType(); } - + @Override public String getXsdType() throws MolgenisModelException { @@ -83,35 +87,37 @@ public String getFormatString() return ""; } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings( + { "unchecked", "rawtypes" }) @Override public HtmlInput createInput(String name, String xrefEntityClassName) throws HtmlInputException - { + { try { Class klass = Class.forName(xrefEntityClassName); - + return new MrefInput(name, klass); } catch (ClassNotFoundException e) { throw new HtmlInputException(e); - } + } } - -// @Override -// public HtmlInput createInput(String name, Class xrefEntityClassName) throws HtmlInputException -// { -// return new MrefInput(name, xrefEntityClassName); -// } + + // @Override + // public HtmlInput createInput(String name, Class + // xrefEntityClassName) throws HtmlInputException + // { + // return new MrefInput(name, xrefEntityClassName); + // } @Override public String getCppPropertyType() throws MolgenisModelException { Field f_ref = f.getXrefField(); - return "vector<"+getFieldType(f_ref).getCppPropertyType()+">"; + return "vector<" + getFieldType(f_ref).getCppPropertyType() + ">"; } - + @Override public String getCppJavaPropertyType() throws MolgenisModelException { @@ -128,7 +134,7 @@ public Object getTypedValue(String value) throws ParseException { throw new UnsupportedOperationException("Conversion of MRef not supported."); } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.MREF; diff --git a/src/org/molgenis/fieldtypes/NSequenceField.java b/src/org/molgenis/fieldtypes/NSequenceField.java index 448b86f40..3bf03f69f 100644 --- a/src/org/molgenis/fieldtypes/NSequenceField.java +++ b/src/org/molgenis/fieldtypes/NSequenceField.java @@ -15,40 +15,39 @@ public String getJavaPropertyType() { return "String"; } - + @Override public String getJavaAssignment(String value) { - //FIXME check if it is a valid nsequence - if(value == null || value.equals("") ) return "null"; - return "\""+value+"\""; + // FIXME check if it is a valid nsequence + if (value == null || value.equals("")) return "null"; + return "\"" + value + "\""; } - + @Override public String getJavaPropertyDefault() { return getJavaAssignment(f.getDefaultValue()); } - + @Override public String getMysqlType() throws MolgenisModelException { return "TEXT"; } - + @Override public String getOracleType() throws MolgenisModelException { return "BLOB"; } - @Override public String getHsqlType() throws MolgenisModelException { return "TEXT"; } - + @Override public String getXsdType() throws MolgenisModelException { @@ -63,7 +62,7 @@ public String getFormatString() @Override public HtmlInput createInput(String name, String xrefEntityClassName) throws HtmlInputException - + { return new NsequenceInput(name); } @@ -90,7 +89,7 @@ public Object getTypedValue(String value) throws ParseException { return value; } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.NSEQUENCE; diff --git a/src/org/molgenis/fieldtypes/StringField.java b/src/org/molgenis/fieldtypes/StringField.java index 99dfd3dea..4c1be6a50 100644 --- a/src/org/molgenis/fieldtypes/StringField.java +++ b/src/org/molgenis/fieldtypes/StringField.java @@ -13,10 +13,10 @@ public class StringField extends FieldType @Override public String getJavaAssignment(String value) throws MolgenisModelException { - if(value == null || value.equals("") ) return "null"; - return "\""+value+"\""; + if (value == null || value.equals("")) return "null"; + return "\"" + value + "\""; } - + @Override public String getJavaPropertyDefault() throws MolgenisModelException { @@ -32,20 +32,21 @@ public String getJavaPropertyType() throws MolgenisModelException @Override public String getMysqlType() throws MolgenisModelException { - return "VARCHAR("+f.getVarCharLength()+")"; + return "VARCHAR(" + f.getVarCharLength() + ")"; } - + @Override public String getOracleType() throws MolgenisModelException { - return "VARCHAR2("+f.getVarCharLength()+")"; + return "VARCHAR2(" + f.getVarCharLength() + ")"; } @Override public String getHsqlType() throws MolgenisModelException { - return "VARCHAR("+f.getVarCharLength()+")"; + return "VARCHAR(" + f.getVarCharLength() + ")"; } + @Override public String getXsdType() throws MolgenisModelException { @@ -69,7 +70,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "string"; } - + @Override public String getCppJavaPropertyType() { @@ -87,7 +88,6 @@ public String getTypedValue(String value) throws ParseException return value; } - public FieldTypeEnum getEnumType() { return FieldTypeEnum.STRING; diff --git a/src/org/molgenis/fieldtypes/TextField.java b/src/org/molgenis/fieldtypes/TextField.java index 304f7d145..b14ebc5ed 100644 --- a/src/org/molgenis/fieldtypes/TextField.java +++ b/src/org/molgenis/fieldtypes/TextField.java @@ -13,22 +13,22 @@ public class TextField extends FieldType @Override public String getJavaAssignment(String value) { - if(value == null ||value.equals("") ) return "null"; - return "\""+value+"\""; + if (value == null || value.equals("")) return "null"; + return "\"" + value + "\""; } - + @Override public String getJavaPropertyDefault() { return getJavaAssignment(f.getDefaultValue()); } - + @Override public String getMysqlType() throws MolgenisModelException { return "TEXT"; } - + @Override public String getOracleType() { @@ -39,10 +39,10 @@ public String getOracleType() @Override public String getHsqlType() throws MolgenisModelException { - //these guys don't have TEXT? + // these guys don't have TEXT? return "VARCHAR"; } - + @Override public String getXsdType() throws MolgenisModelException { @@ -73,7 +73,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "string"; } - + @Override public String getCppJavaPropertyType() { diff --git a/src/org/molgenis/fieldtypes/UnknownField.java b/src/org/molgenis/fieldtypes/UnknownField.java index 4a41f31b7..455c2fa53 100644 --- a/src/org/molgenis/fieldtypes/UnknownField.java +++ b/src/org/molgenis/fieldtypes/UnknownField.java @@ -8,8 +8,9 @@ import org.molgenis.model.MolgenisModelException; /** - * This type is used when the field type is not known. - * For example if(MolgenisFieldType.getType(name) instanceof UnknownType( {//handle this bad situation + * This type is used when the field type is not known. For example + * if(MolgenisFieldType.getType(name) instanceof UnknownType( {//handle this bad + * situation */ public class UnknownField extends FieldType { @@ -49,7 +50,7 @@ public String getMysqlType() throws MolgenisModelException { return null; } - + @Override public String getOracleType() throws MolgenisModelException { @@ -73,7 +74,7 @@ public String getCppPropertyType() throws MolgenisModelException { return "void*"; } - + @Override public String getCppJavaPropertyType() { diff --git a/src/org/molgenis/fieldtypes/XrefField.java b/src/org/molgenis/fieldtypes/XrefField.java index 8dbd335cb..4c5df21f9 100644 --- a/src/org/molgenis/fieldtypes/XrefField.java +++ b/src/org/molgenis/fieldtypes/XrefField.java @@ -10,41 +10,41 @@ import org.molgenis.model.elements.Field; import org.molgenis.util.Entity; -public class XrefField extends FieldType -{ +public class XrefField extends FieldType +{ @Override public String getJavaAssignment(String value) { return "NOT IMPLEMENTED"; } - + @Override public String getJavaPropertyType() throws MolgenisModelException { Field f_ref = f.getXrefField(); return getFieldType(f_ref).getJavaPropertyType(); } - + @Override public String getJavaPropertyDefault() { - if(f.getDefaultValue() == null || f.getDefaultValue() == "") return "null"; + if (f.getDefaultValue() == null || f.getDefaultValue().isEmpty()) return "null"; return f.getDefaultValue(); } - + @Override public String getJavaSetterType() throws MolgenisModelException { - + return getFieldType(f.getXrefField()).getJavaSetterType(); } - + @Override public String getMysqlType() throws MolgenisModelException { return getFieldType(f.getXrefField()).getMysqlType(); } - + @Override public String getOracleType() throws MolgenisModelException { @@ -56,7 +56,7 @@ public String getHsqlType() throws MolgenisModelException { return getFieldType(f.getXrefField()).getHsqlType(); } - + public String getXsdType() throws MolgenisModelException { return getFieldType(f.getXrefField()).getXsdType(); @@ -87,7 +87,7 @@ public String getCppPropertyType() throws MolgenisModelException Field f_ref = f.getXrefField(); return getFieldType(f_ref).getCppPropertyType(); } - + @Override public String getCppJavaPropertyType() throws MolgenisModelException { @@ -106,10 +106,10 @@ public Object getTypedValue(String value) throws ParseException { throw new UnsupportedOperationException("Xref conversion not supported."); } - + public FieldTypeEnum getEnumType() { return FieldTypeEnum.XREF; } -} +} \ No newline at end of file diff --git a/src/org/molgenis/framework/db/AbstractDatabase.java b/src/org/molgenis/framework/db/AbstractDatabase.java index 90660bcc0..0f00a3844 100644 --- a/src/org/molgenis/framework/db/AbstractDatabase.java +++ b/src/org/molgenis/framework/db/AbstractDatabase.java @@ -199,7 +199,6 @@ public void executeUpdate(String sql) throws DatabaseException { stmt = con.createStatement(); stmt.executeUpdate(sql); - stmt.close(); } catch (Exception e) { @@ -249,7 +248,7 @@ public int update(List entities, DatabaseAction dbAction, { // get all the value of all keys (composite key) // use an index to hash the entities - String combinedKey = ""; + StringBuilder combinedKeyBuilder = new StringBuilder(); // extract its key values and put in map Map keyValues = new LinkedHashMap(); @@ -260,20 +259,11 @@ public int update(List entities, DatabaseAction dbAction, for (String key : keyNames) { // create a hash that concats all key values into one string - combinedKey += ";" + (entity.get(key) == null ? "" : entity.get(key)); - - // if (entity.get(key) == null || entity.get(key).equals("")) - // { - // if (dbAction.equals(DatabaseAction.UPDATE) || - // dbAction.equals(DatabaseAction.REMOVE)) - // { - // throw new DatabaseException( - // entityName + " is missing key '" + key + "' in line " + - // entity.toString()); - // } - // } + combinedKeyBuilder.append(';'); + if (entity.get(key) != null) { + combinedKeyBuilder.append(entity.get(key)); incompleteKey = false; keyValues.put(key, entity.get(key)); } @@ -286,7 +276,7 @@ public int update(List entities, DatabaseAction dbAction, { keyIndex.add(keyValues); // create the entity index using the hash - entityIndex.put(combinedKey, entity); + entityIndex.put(combinedKeyBuilder.toString(), entity); } else { @@ -343,13 +333,13 @@ public int update(List entities, DatabaseAction dbAction, for (E p : selectForUpdate) { // reconstruct composite key so we can use the entityIndex - String combinedKey = ""; + StringBuilder combinedKeyBuilder = new StringBuilder(); for (String key : keyNames) { - combinedKey += ";" + p.get(key); + combinedKeyBuilder.append(';').append(p.get(key)); } // copy existing from entityIndex to existingEntities - entityIndex.remove(combinedKey); + entityIndex.remove(combinedKeyBuilder.toString()); existingEntities.add(p); } // copy remaining to newEntities diff --git a/src/org/molgenis/framework/db/AbstractMapper.java b/src/org/molgenis/framework/db/AbstractMapper.java index 60d7a09b9..aa5c5df8c 100644 --- a/src/org/molgenis/framework/db/AbstractMapper.java +++ b/src/org/molgenis/framework/db/AbstractMapper.java @@ -23,8 +23,7 @@ public abstract class AbstractMapper implements Mapper public static final int BATCH_SIZE = 500; /** log messages */ - private static transient final Logger logger = Logger - .getLogger(AbstractJDBCMapper.class.getSimpleName()); + private static transient final Logger logger = Logger.getLogger(AbstractJDBCMapper.class.getSimpleName()); public AbstractMapper(Database database) { @@ -57,8 +56,7 @@ public Database getDatabase() * * @throws IOException */ - protected abstract void prepareFileAttachements(List entities, File dir) - throws IOException; + protected abstract void prepareFileAttachements(List entities, File dir) throws IOException; /** * helper method to do some actions after the transaction. For example: @@ -68,8 +66,7 @@ protected abstract void prepareFileAttachements(List entities, File dir) * database) * @throws IOException */ - protected abstract boolean saveFileAttachements(List entities, File dir) - throws IOException; + protected abstract boolean saveFileAttachements(List entities, File dir) throws IOException; /** * translate into sql @@ -77,8 +74,7 @@ protected abstract boolean saveFileAttachements(List entities, File dir) * @throws DatabaseException */ @Override - public abstract int executeAdd(List entities) - throws DatabaseException; + public abstract int executeAdd(List entities) throws DatabaseException; /** * translate into sql @@ -86,15 +82,13 @@ public abstract int executeAdd(List entities) * @throws DatabaseException */ @Override - public abstract int executeUpdate(List entities) - throws DatabaseException; + public abstract int executeUpdate(List entities) throws DatabaseException; /** * translate into sql */ @Override - public abstract int executeRemove(List entities) - throws DatabaseException; + public abstract int executeRemove(List entities) throws DatabaseException; /** * Foreign key values may be only given via the 'label'. This function @@ -104,8 +98,7 @@ public abstract int executeRemove(List entities) * @throws DatabaseException * @throws ParseException */ - public abstract void resolveForeignKeys(List entities) - throws DatabaseException, ParseException; + public abstract void resolveForeignKeys(List entities) throws DatabaseException, ParseException; /** * Helper method for storing multiplicative references. This function should @@ -118,8 +111,7 @@ public abstract void resolveForeignKeys(List entities) * @throws IOException * @throws ParseException */ - public abstract void storeMrefs(List entities) throws DatabaseException, - IOException, ParseException; + public abstract void storeMrefs(List entities) throws DatabaseException, IOException, ParseException; /** * Helper method for removing multiplicative references ('mrefs') @@ -130,12 +122,11 @@ public abstract void storeMrefs(List entities) throws DatabaseException, * @throws DatabaseException * @throws ParseException */ - public abstract void removeMrefs(List entities) throws SQLException, - IOException, DatabaseException, ParseException; + public abstract void removeMrefs(List entities) throws SQLException, IOException, DatabaseException, + ParseException; @Override - public void find(TupleWriter writer, QueryRule... rules) - throws DatabaseException + public void find(TupleWriter writer, QueryRule... rules) throws DatabaseException { this.find(writer, null, rules); } @@ -160,8 +151,7 @@ public int add(List entities) throws DatabaseException if (privateTx) getDatabase().beginTx(); // prepare all file attachments - this.prepareFileAttachements(entities, getDatabase() - .getFilesource()); + this.prepareFileAttachements(entities, getDatabase().getFilesource()); // insert this class in batches for (int i = 0; i < entities.size(); i += BATCH_SIZE) @@ -178,8 +168,7 @@ public int add(List entities) throws DatabaseException this.storeMrefs(entities); // store file attachments and then update the file paths to them - if (this.saveFileAttachements(entities, getDatabase() - .getFilesource())) + if (this.saveFileAttachements(entities, getDatabase().getFilesource())) { this.update(entities); } @@ -187,25 +176,20 @@ public int add(List entities) throws DatabaseException // commit all batches if (privateTx) getDatabase().commitTx(); - logger.info(updatedRows + " " - + this.create().getClass().getSimpleName() - + " objects added"); + logger.info(updatedRows + " " + this.create().getClass().getSimpleName() + " objects added"); return updatedRows; } catch (Exception sqle) { sqle.printStackTrace(); if (privateTx) getDatabase().rollbackTx(); - logger.error("ADD failed on " - + this.create().getClass().getSimpleName() + ": " - + sqle.getMessage()); + logger.error("ADD failed on " + this.create().getClass().getSimpleName() + ": " + sqle.getMessage()); throw new DatabaseException(sqle); } } @Override - public int add(TupleReader reader, TupleWriter writer) - throws DatabaseException + public int add(TupleReader reader, TupleWriter writer) throws DatabaseException { // count affected rows int rowsAffected = 0; @@ -247,9 +231,7 @@ public int add(TupleReader reader, TupleWriter writer) catch (Exception e) { if (privateTx) getDatabase().rollbackTx(); - throw new DatabaseException("add(" - + create().getClass().getSimpleName() + ") failed: " - + e.getMessage(), e); + throw new DatabaseException("add(" + create().getClass().getSimpleName() + ") failed: " + e.getMessage(), e); } return rowsAffected; } @@ -276,8 +258,7 @@ public int update(List entities) throws DatabaseException if (privateTx) getDatabase().beginTx(); // prepare file attachments - this.prepareFileAttachements(entities, getDatabase() - .getFilesource()); + this.prepareFileAttachements(entities, getDatabase().getFilesource()); // update in batches for (int i = 0; i < entities.size(); i += BATCH_SIZE) @@ -286,8 +267,7 @@ public int update(List entities) throws DatabaseException List sublist = entities.subList(i, endindex); // put the files in their place - this.saveFileAttachements(sublist, getDatabase() - .getFilesource()); + this.saveFileAttachements(sublist, getDatabase().getFilesource()); // attempt to resolve foreign keys by label (ie. 'name') this.resolveForeignKeys(sublist); @@ -299,17 +279,14 @@ public int update(List entities) throws DatabaseException if (privateTx) getDatabase().commitTx(); - logger.info(updatedRows + " " - + this.create().getClass().getSimpleName() - + " objects updated"); + logger.info(updatedRows + " " + this.create().getClass().getSimpleName() + " objects updated"); return updatedRows; } catch (Exception sqle) { if (privateTx) getDatabase().rollbackTx(); - throw new DatabaseException("Update(" - + create().getClass().getSimpleName() + ") failed: " + throw new DatabaseException("Update(" + create().getClass().getSimpleName() + ") failed: " + sqle.getMessage(), sqle); } } @@ -343,9 +320,8 @@ public int update(TupleReader reader) throws DatabaseException catch (Exception e) { if (privateTx) getDatabase().rollbackTx(); - throw new DatabaseException("update(" - + create().getClass().getSimpleName() + ") failed: " - + e.getMessage(), e); + throw new DatabaseException( + "update(" + create().getClass().getSimpleName() + ") failed: " + e.getMessage(), e); } return rowsAffected; } @@ -368,8 +344,7 @@ public int remove(List entities) throws DatabaseException if (privateTx) getDatabase().beginTx(); // prepare file attachments - this.prepareFileAttachements(entities, getDatabase() - .getFilesource()); + this.prepareFileAttachements(entities, getDatabase().getFilesource()); // remove in batches for (int i = 0; i < entities.size(); i += BATCH_SIZE) @@ -388,21 +363,16 @@ public int remove(List entities) throws DatabaseException getDatabase().flush(); if (privateTx) getDatabase().commitTx(); - logger.info(updatedRows + " " - + this.create().getClass().getSimpleName() - + " objects removed"); + logger.info(updatedRows + " " + this.create().getClass().getSimpleName() + " objects removed"); return updatedRows; } catch (Exception sqle) { if (privateTx) getDatabase().rollbackTx(); - logger.error("remove failed on " - + this.create().getClass().getSimpleName() + ": " - + sqle.getMessage()); + logger.error("remove failed on " + this.create().getClass().getSimpleName() + ": " + sqle.getMessage()); sqle.printStackTrace(); - throw new DatabaseException("remove(" - + create().getClass().getSimpleName() + ") failed: " + throw new DatabaseException("remove(" + create().getClass().getSimpleName() + ") failed: " + sqle.getMessage(), sqle); } } @@ -432,28 +402,26 @@ public int remove(TupleReader reader) throws DatabaseException catch (Exception e) { if (privateTx) getDatabase().rollbackTx(); - throw new DatabaseException("remove(" - + create().getClass().getSimpleName() + ") failed: " - + e.getMessage(), e); + throw new DatabaseException( + "remove(" + create().getClass().getSimpleName() + ") failed: " + e.getMessage(), e); } return rowsAffected; } @Override - //FIXME: limit argument is never used? - public List toList(TupleReader reader, int limit) - throws DatabaseException + // FIXME: limit argument is never used? + public List toList(TupleReader reader, int limit) throws DatabaseException { - //hack to while over a reader until the result is empty - if(reader.isClosed()) + // hack to while over a reader until the result is empty + if (reader.isClosed()) { return new ArrayList(); } - - final List entities = createList(10); //TODO why 10? + + final List entities = createList(10); // TODO why 10? try { - for (Tuple line : reader) //TODO should limit not be used somehow? + for (Tuple line : reader) // TODO should limit not be used somehow? { E e = create(); e.set(line, false); // parse the tuple diff --git a/src/org/molgenis/framework/db/ConnectionUtil.java b/src/org/molgenis/framework/db/ConnectionUtil.java index 472b06daf..02cadba1a 100644 --- a/src/org/molgenis/framework/db/ConnectionUtil.java +++ b/src/org/molgenis/framework/db/ConnectionUtil.java @@ -6,34 +6,38 @@ import org.molgenis.MolgenisOptions; - - public class ConnectionUtil { - public static Connection createConnection(MolgenisOptions options) { + public static Connection createConnection(MolgenisOptions options) + { try { Class.forName(options.db_driver.trim()).newInstance(); Connection conn = DriverManager.getConnection(options.db_uri.trim(), options.db_user.trim(), options.db_password.trim()); return conn; - }catch (Exception e){ + } + catch (Exception e) + { e.printStackTrace(); } return null; } - - public static Connection createConnection(Properties p) { + + public static Connection createConnection(Properties p) + { try { Class.forName(p.getProperty("db_driver").trim()).newInstance(); Connection conn = DriverManager.getConnection(p.getProperty("db_uri").trim(), p.getProperty("db_user") .trim(), p.getProperty("db_password").trim()); return conn; - }catch (Exception e){ + } + catch (Exception e) + { e.printStackTrace(); } - return null; + return null; } - + } diff --git a/src/org/molgenis/framework/db/CsvToDatabase.java b/src/org/molgenis/framework/db/CsvToDatabase.java index 17dcf057e..73b3cd6b6 100644 --- a/src/org/molgenis/framework/db/CsvToDatabase.java +++ b/src/org/molgenis/framework/db/CsvToDatabase.java @@ -15,119 +15,161 @@ import freemarker.log.Logger; -/**will be moved to generic solution*/ +/** will be moved to generic solution */ -public abstract class CsvToDatabase { +public abstract class CsvToDatabase +{ protected static int BATCH_SIZE = 10000; protected transient final Logger logger = Logger.getLogger(this.getClass().getSimpleName()); - - /**wrapper to use int inside anonymous classes (requires final, so cannot update directly)*/ - //FIXME move to value type elsewhere? - public static class IntegerWrapper { + + /** + * wrapper to use int inside anonymous classes (requires final, so cannot + * update directly) + */ + // FIXME move to value type elsewhere? + public static class IntegerWrapper + { private int value; - - public IntegerWrapper(int value) { + + public IntegerWrapper(int value) + { this.value = value; } - public void set(int value) { + + public void set(int value) + { this.value = value; } - public int get() { + + public int get() + { return this.value; } } - + /** * Imports ${JavaName(entity)} from tab/comma delimited File. - * @param db where data should be imported into - * @param file with the csv values - * @param defaults default values that override the values in the file columns + * + * @param db + * where data should be imported into + * @param file + * with the csv values + * @param defaults + * default values that override the values in the file columns */ - public int importCsv(final Database db, File file, final Tuple defaults) throws DatabaseException, IOException, Exception { - return importCsv(db,file,defaults,DatabaseAction.ADD); + public int importCsv(final Database db, File file, final Tuple defaults) throws DatabaseException, IOException, + Exception + { + return importCsv(db, file, defaults, DatabaseAction.ADD); } - - public int importCsv(Database db, File file, Tuple defaults, DatabaseAction dbAction) throws Exception { - if( file.exists() ) { - logger.info("trying to import "+file); + + public int importCsv(Database db, File file, Tuple defaults, DatabaseAction dbAction) throws Exception + { + if (file.exists()) + { + logger.info("trying to import " + file); CsvReader reader = new CsvFileReader(file); - return this.importCsv(db,reader,defaults,dbAction, reader.getMissingValues()); + return this.importCsv(db, reader, defaults, dbAction, reader.getMissingValues()); } - else { - logger.warn("CsvImport of "+file+" skipped: file doesn't exists"); + else + { + logger.warn("CsvImport of " + file + " skipped: file doesn't exists"); return 0; } } /** * Imports ${JavaName(entity)} from tab/comma delimited File. - * @param db where data should be imported into - * @param file with the csv values - * @param defaults default values that override the values in the file columns - * @param dbAction indicating if data needs to be added, updated, etc - * @param missingValues string that indicates how missing values are specified. E.g. "" or "NA" + * + * @param db + * where data should be imported into + * @param file + * with the csv values + * @param defaults + * default values that override the values in the file columns + * @param dbAction + * indicating if data needs to be added, updated, etc + * @param missingValues + * string that indicates how missing values are specified. E.g. + * "" or "NA" */ - public int importCsv(final Database db, File file, final Tuple defaults, DatabaseAction dbAction, String missingValues) throws DatabaseException, IOException, Exception { - if( file.exists() ) { - logger.info("trying to import "+file); + public int importCsv(final Database db, File file, final Tuple defaults, DatabaseAction dbAction, + String missingValues) throws DatabaseException, IOException, Exception + { + if (file.exists()) + { + logger.info("trying to import " + file); CsvReader reader = new CsvFileReader(file); - return this.importCsv(db,reader,defaults,dbAction, missingValues); + return this.importCsv(db, reader, defaults, dbAction, missingValues); } - else { - logger.warn("CsvImport of "+file+" skipped: file doesn't exists"); + else + { + logger.warn("CsvImport of " + file + " skipped: file doesn't exists"); return 0; } - } - - + } + /** * Imports ${JavaName(entity)} from tab/comma delimited File. */ - public int importCsv(final Database db, CsvReader reader, final Tuple defaults) throws DatabaseException, IOException, Exception { - return importCsv(db,reader,defaults,DatabaseAction.ADD); + public int importCsv(final Database db, CsvReader reader, final Tuple defaults) throws DatabaseException, + IOException, Exception + { + return importCsv(db, reader, defaults, DatabaseAction.ADD); } - - public int importCsv(final Database db, CsvReader reader, final Tuple defaults, DatabaseAction action) throws DatabaseException, IOException, Exception { - return importCsv(db,reader,defaults,DatabaseAction.ADD, reader.getMissingValues()); + + public int importCsv(final Database db, CsvReader reader, final Tuple defaults, DatabaseAction action) + throws DatabaseException, IOException, Exception + { + return importCsv(db, reader, defaults, DatabaseAction.ADD, reader.getMissingValues()); } - public abstract int importCsv(Database db, CsvReader reader, Tuple constants, DatabaseAction action, String missingValues) throws Exception; - - public static class ImportResult { - + public abstract int importCsv(Database db, CsvReader reader, Tuple constants, DatabaseAction action, + String missingValues) throws Exception; + + public static class ImportResult + { + List progressLog; - Map messages; + Map messages; String errorItem; - - public ImportResult() { + + public ImportResult() + { progressLog = new ArrayList(); - messages = new HashMap(); + messages = new HashMap(); errorItem = "no error found"; } - public List getProgressLog() { + public List getProgressLog() + { return progressLog; } - public void setProgressLog(List progressLog) { + public void setProgressLog(List progressLog) + { this.progressLog = progressLog; } - public Map getMessages() { + public Map getMessages() + { return messages; } - public void setMessages(Map messages) { + public void setMessages(Map messages) + { this.messages = messages; } - public String getErrorItem() { + public String getErrorItem() + { return errorItem; } - public void setErrorItem(String errorItem) { + public void setErrorItem(String errorItem) + { this.errorItem = errorItem; } - + } } diff --git a/src/org/molgenis/framework/db/Database.java b/src/org/molgenis/framework/db/Database.java index e2601b62e..037d77e0e 100644 --- a/src/org/molgenis/framework/db/Database.java +++ b/src/org/molgenis/framework/db/Database.java @@ -18,7 +18,6 @@ import java.io.File; import java.sql.Connection; -import java.sql.ResultSet; import java.text.ParseException; import java.util.List; diff --git a/src/org/molgenis/framework/db/DatabaseException.java b/src/org/molgenis/framework/db/DatabaseException.java index 2211f3cd9..73cf92010 100644 --- a/src/org/molgenis/framework/db/DatabaseException.java +++ b/src/org/molgenis/framework/db/DatabaseException.java @@ -1,34 +1,40 @@ package org.molgenis.framework.db; -/** A small class defining a database exception. +/** + * A small class defining a database exception. * * @author ? - * + * */ -public class DatabaseException extends Exception { +public class DatabaseException extends Exception +{ String message = ""; /** * */ private static final long serialVersionUID = 1L; - public DatabaseException(String message) { + public DatabaseException(String message) + { super(message); this.message = message; } - - public DatabaseException(Exception exception) { + + public DatabaseException(Exception exception) + { super(exception); message = exception.getMessage(); } - - public DatabaseException(String message, Exception exception) { + + public DatabaseException(String message, Exception exception) + { super(exception); this.message = message; } - + @Override - public String getMessage() { + public String getMessage() + { return message; } } diff --git a/src/org/molgenis/framework/db/DatabaseMapper.java b/src/org/molgenis/framework/db/DatabaseMapper.java index 816becb1d..c4abb7f6f 100644 --- a/src/org/molgenis/framework/db/DatabaseMapper.java +++ b/src/org/molgenis/framework/db/DatabaseMapper.java @@ -8,13 +8,13 @@ public interface DatabaseMapper { public E create(); - + public int add(List entities) throws DatabaseException; public int update(List entities) throws DatabaseException; - + public int remove(List entities) throws DatabaseException; - + public String getTableFieldName(String field); public FieldType getFieldType(String field); diff --git a/src/org/molgenis/framework/db/ExampleData.java b/src/org/molgenis/framework/db/ExampleData.java index def8c9d86..6f6764ec1 100644 --- a/src/org/molgenis/framework/db/ExampleData.java +++ b/src/org/molgenis/framework/db/ExampleData.java @@ -1,8 +1,8 @@ package org.molgenis.framework.db; /** - * Interface to load example data into a data model. - * Should be used in the context of {@link Database.loadExampleData()}. + * Interface to load example data into a data model. Should be used in the + * context of {@link Database.loadExampleData()}. */ public interface ExampleData { diff --git a/src/org/molgenis/framework/db/Mapper.java b/src/org/molgenis/framework/db/Mapper.java index 92b5a809e..4e0949189 100644 --- a/src/org/molgenis/framework/db/Mapper.java +++ b/src/org/molgenis/framework/db/Mapper.java @@ -16,66 +16,64 @@ public interface Mapper { /** * Get the database this mapper is attached to. + * * @return database */ public Database getDatabase(); public E create(); - + /** Implementation of {@link Database#count(Class, QueryRule...)} */ public int count(QueryRule... rules) throws DatabaseException; - /** Implementation of {@link Database#find(Class, QueryRule...)}*/ + /** Implementation of {@link Database#find(Class, QueryRule...)} */ public List find(QueryRule... rules) throws DatabaseException; - /** Implementation of {@link Database#find(Class, TupleWriter, QueryRule...)}*/ - public void find(TupleWriter writer, QueryRule... rules) - throws DatabaseException; + /** Implementation of {@link Database#find(Class, TupleWriter, QueryRule...)} */ + public void find(TupleWriter writer, QueryRule... rules) throws DatabaseException; - /** Implementation of {@link Database#find(Class, TupleWriter, List, QueryRule...)*/ - public void find(TupleWriter writer, List fieldsToExport, - QueryRule[] rules) throws DatabaseException; + /** + * Implementation of + * + */ + public void find(TupleWriter writer, List fieldsToExport, QueryRule[] rules) throws DatabaseException; /** Implementation of {@link Database#add(Entity)} */ - //public int add(E entity) throws DatabaseException; - + // public int add(E entity) throws DatabaseException; + /** Implementation of {@link Database#add(List)} */ public int add(List entities) throws DatabaseException; - /** Implementation of {@link Database#add(Class, TupleReader, TupleWriter)}*/ - public int add(TupleReader reader, TupleWriter writer) - throws DatabaseException; + /** Implementation of {@link Database#add(Class, TupleReader, TupleWriter)} */ + public int add(TupleReader reader, TupleWriter writer) throws DatabaseException; - /** Implementation of {@link Database#add(Entity)}*/ - //public int update(E entity) throws DatabaseException; - - /** Implementation of {@link Database#update(List)}*/ + /** Implementation of {@link Database#add(Entity)} */ + // public int update(E entity) throws DatabaseException; + + /** Implementation of {@link Database#update(List)} */ public int update(List entities) throws DatabaseException; - /** Implementation of {@link Database#update(TupleReader)}*/ + /** Implementation of {@link Database#update(TupleReader)} */ public int update(TupleReader reader) throws DatabaseException; - /** Implementation of {@link Database#remove(Entity)}*/ - //public int remove(E entity) throws DatabaseException; - - /** Implementation of {@link Database#remove(List)}*/ + /** Implementation of {@link Database#remove(Entity)} */ + // public int remove(E entity) throws DatabaseException; + + /** Implementation of {@link Database#remove(List)} */ public int remove(List entities) throws DatabaseException; - /** Implementation of {@link Database#remove(Class, TupleReader)*/ + /** Implementation of */ public int remove(TupleReader reader) throws DatabaseException; - public List toList(TupleReader reader, int limit) - throws DatabaseException; + public List toList(TupleReader reader, int limit) throws DatabaseException; public String getTableFieldName(String field); public FieldType getFieldType(String field); - public void resolveForeignKeys(List enteties) throws ParseException, - DatabaseException; + public void resolveForeignKeys(List enteties) throws ParseException, DatabaseException; - public String createFindSqlInclRules(QueryRule[] rules) - throws DatabaseException; + public String createFindSqlInclRules(QueryRule[] rules) throws DatabaseException; public E findById(Object id) throws DatabaseException; diff --git a/src/org/molgenis/framework/db/MapperDecorator.java b/src/org/molgenis/framework/db/MapperDecorator.java index d5dc91ff6..9b4287d94 100644 --- a/src/org/molgenis/framework/db/MapperDecorator.java +++ b/src/org/molgenis/framework/db/MapperDecorator.java @@ -48,13 +48,13 @@ public int count(QueryRule... rules) throws DatabaseException } @Override - public List find(QueryRule ...rules) throws DatabaseException + public List find(QueryRule... rules) throws DatabaseException { return mapper.find(rules); } @Override - public void find(TupleWriter writer, QueryRule ...rules) throws DatabaseException + public void find(TupleWriter writer, QueryRule... rules) throws DatabaseException { mapper.find(writer, rules); } @@ -110,8 +110,7 @@ public void find(TupleWriter writer, List fieldsToExport, QueryRule[] ru } @Override - public void resolveForeignKeys(List enteties) throws ParseException, - DatabaseException + public void resolveForeignKeys(List enteties) throws ParseException, DatabaseException { mapper.resolveForeignKeys(enteties); } @@ -122,24 +121,24 @@ public String createFindSqlInclRules(QueryRule[] rules) throws DatabaseException return mapper.createFindSqlInclRules(rules); } -// @Override -// public int add(E entity) throws DatabaseException -// { -// return this.mapper.add(entity); -// } -// -// @Override -// public int update(E entity) throws DatabaseException -// { -// // TODO Auto-generated method stub -// return this.mapper.update(entity); -// } -// -// @Override -// public int remove(E entity) throws DatabaseException -// { -// return this.mapper.remove(entity); -// } + // @Override + // public int add(E entity) throws DatabaseException + // { + // return this.mapper.add(entity); + // } + // + // @Override + // public int update(E entity) throws DatabaseException + // { + // // TODO Auto-generated method stub + // return this.mapper.update(entity); + // } + // + // @Override + // public int remove(E entity) throws DatabaseException + // { + // return this.mapper.remove(entity); + // } @Override public E findById(Object id) throws DatabaseException @@ -179,5 +178,4 @@ public List createList(int i) return this.mapper.createList(i); } - } diff --git a/src/org/molgenis/framework/db/Query.java b/src/org/molgenis/framework/db/Query.java index d648d7a62..cec6e4bd5 100644 --- a/src/org/molgenis/framework/db/Query.java +++ b/src/org/molgenis/framework/db/Query.java @@ -3,9 +3,8 @@ import java.text.ParseException; import java.util.List; -import org.molgenis.util.TupleWriter; import org.molgenis.util.Entity; - +import org.molgenis.util.TupleWriter; /** * Easily build complex QueryRules for Database. @@ -30,7 +29,7 @@ public interface Query { /** Translates a String into a QueryRule and adds it */ - public abstract Query filter( String filter ); + public Query filter(String filter); /** * Shorthand for @@ -39,21 +38,26 @@ public interface Query * 'new QueryRule(field, Operator.EQUALS, value)' * */ - public abstract Query equals( String field, Object value ); - + public Query equals(String field, Object value); + /** * Shorthand for equals + * * @param field * @param value * @return */ - public abstract Query eq( String field, Object value ); - - /** Shorthand for search all fields. Typically translates to 'like' on all textual fields - * @param searchTerms the terms to search on, space seperated + public Query eq(String field, Object value); + + /** + * Shorthand for search all fields. Typically translates to 'like' on all + * textual fields + * + * @param searchTerms + * the terms to search on, space seperated */ - public abstract Query search(String searchTerms) throws DatabaseException; - + public Query search(String searchTerms) throws DatabaseException; + /** * Shorthand for * @@ -61,7 +65,7 @@ public interface Query * 'new QueryRule(field, Operator.IN, objectList)' * */ - public abstract Query in( String field, List objectList ); + public Query in(String field, List objectList); /** * Shorthand for @@ -70,15 +74,16 @@ public interface Query * 'new QueryRule(field, Operator.GREATER, value)' * */ - public abstract Query greater( String field, Object value ); - + public Query greater(String field, Object value); + /** * Shorthand for greater + * * @param field * @param value * @return */ - public abstract Query gt(String field, Object value); + public Query gt(String field, Object value); /** * Shorthand for @@ -87,7 +92,7 @@ public interface Query * 'new QueryRule(field, Operator.GREATER_EQUAL, value)' * */ - public abstract Query greaterOrEqual( String field, Object value ); + public Query greaterOrEqual(String field, Object value); /** * Shorthand for @@ -96,12 +101,12 @@ public interface Query * 'new QueryRule(field, Operator.LESS, value)' * */ - public abstract Query less( String field, Object value ); - + public Query less(String field, Object value); + /** * Shorthand for lessThan */ - public abstract Query lt( String field, Object value ); + public Query lt(String field, Object value); /** * Shorthand for @@ -110,9 +115,8 @@ public interface Query * 'new QueryRule(field, Operator.LESS_EQUAL, value)' * */ - public abstract Query lessOrEqual( String field, Object value ); + public Query lessOrEqual(String field, Object value); - /** * Shorthand for * @@ -120,25 +124,28 @@ public interface Query * 'new QueryRule(field, Operator.LIKE, value)' * */ - public abstract Query like(String field, Object value); - + public Query like(String field, Object value); + /** * Between, inclusive + * * @param field - * @param min minimum valid value - * @param max maximum valid value + * @param min + * minimum valid value + * @param max + * maximum valid value * @return Query */ - public abstract Query between(String field, Object min, Object max); - + public Query between(String field, Object min, Object max); + /** Add the 'or' option on last queryrule */ - public abstract Query or(); - - /** + public Query or(); + + /** * Add the 'and' option on last query rule (default) */ - public abstract Query and(); - + public Query and(); + /** * Shorthand for * @@ -146,7 +153,7 @@ public interface Query * 'new QueryRule(Operator.LAST)' * */ - public abstract Query last(); + public Query last(); /** * Shorthand for @@ -155,7 +162,7 @@ public interface Query * 'new QueryRule(Operator.LIMIT, limit)' * */ - public abstract Query limit( int limit ); + public Query limit(int limit); /** * Shorthand for @@ -164,7 +171,7 @@ public interface Query * 'new QueryRule(Operator.OFFSET, offset)' * */ - public abstract Query offset( int offset ); + public Query offset(int offset); /** * Shorthand for @@ -173,7 +180,7 @@ public interface Query * 'new QueryRule(Operator.ORDER_ASC, orderByField)' * */ - public abstract Query sortASC( String orderByField ); + public Query sortASC(String orderByField); /** * Shorthand for @@ -182,7 +189,7 @@ public interface Query * 'new QueryRule(Operator.ORDER_DESC, orderByField)' * */ - public abstract Query sortDESC( String orderByField ); + public Query sortDESC(String orderByField); /** * Execute the query on a database. @@ -192,34 +199,37 @@ public interface Query * UnsupportedOperationException(). * * @throws DatabaseException - * @throws ParseException + * @throws ParseException */ - public abstract List find() throws DatabaseException; - + public List find() throws DatabaseException; + /** Finder for csv data */ - public abstract void find(TupleWriter writer) throws DatabaseException, ParseException; + public void find(TupleWriter writer) throws DatabaseException, ParseException; + + /** Finder for csv data with added option only export particular fields */ + public void find(TupleWriter writer, List fieldsToExport) throws DatabaseException, ParseException; - /** Finder for csv data with added option only export particular fields*/ - public abstract void find(TupleWriter writer, List fieldsToExport) throws DatabaseException, ParseException; + /** + * Finder for csv data with added option to only skip ids + * + * @throws IllegalAccessException + * @throws InstantiationException + */ + public void find(TupleWriter writer, boolean skipAutoIds) throws DatabaseException, ParseException, + InstantiationException, IllegalAccessException; - /** Finder for csv data with added option to only skip ids - * @throws IllegalAccessException - * @throws InstantiationException */ - public abstract void find(TupleWriter writer, boolean skipAutoIds) throws DatabaseException, ParseException, InstantiationException, IllegalAccessException; - - /** * Execute the query on a database. * * Will return a List of E. * * @param db - * the Database to run this query on. + * the Database to run this query on. * @param klazz - * the Class to run this query on. - * @throws ParseException + * the Class to run this query on. + * @throws ParseException */ - public List find( Database db, Class klazz ) throws DatabaseException, ParseException; + public List find(Database db, Class klazz) throws DatabaseException, ParseException; /** * Execute the query on a database and count the results. @@ -238,39 +248,45 @@ public interface Query * Will return a List of E. * * @param db - * the Database to run this query on. + * the Database to run this query on. * @param klazz - * the Class to run this query on. + * the Class to run this query on. */ - public int count( Database db, Class klazz ) throws DatabaseException; + public int count(Database db, Class klazz) throws DatabaseException; /** Retrieve array of current QueryRules in this query */ - public abstract QueryRule[] getRules(); + public QueryRule[] getRules(); /** Pretty print the query rules */ - public abstract String toString(); + public String toString(); /** Add rules to the query */ - public abstract void addRules( QueryRule... addRules ); + public void addRules(QueryRule... addRules); - /** Set the database to use for this query*/ - public abstract void setDatabase(Database db); + /** Set the database to use for this query */ + public void setDatabase(Database db); - /** Get the database to use for this query*/ - public abstract Database getDatabase(); + /** Get the database to use for this query */ + public Database getDatabase(); /** Create a query based on the non-null values of an example */ public Query example(Entity example); - - public abstract void removeRule(QueryRule ruleToBeRemoved); - /** Produce the sql that would be used to query - * @return - * @throws DatabaseException */ - public abstract String createFindSql() throws DatabaseException; + public void removeRule(QueryRule ruleToBeRemoved); + + /** + * Produce the sql that would be used to query + * + * @return + * @throws DatabaseException + */ + public String createFindSql() throws DatabaseException; - /** Method to create 'where field in (select * from ...)' subquery as condition */ + /** + * Method to create 'where field in (select * from ...)' subquery as + * condition + */ Query subquery(String field, String sql); - + public Query subQuery(SubQueryRule subQueryRule); } \ No newline at end of file diff --git a/src/org/molgenis/framework/db/QueryImp.java b/src/org/molgenis/framework/db/QueryImp.java index 18a745f17..95f56f656 100644 --- a/src/org/molgenis/framework/db/QueryImp.java +++ b/src/org/molgenis/framework/db/QueryImp.java @@ -5,13 +5,14 @@ import java.util.Vector; import org.molgenis.framework.db.QueryRule.Operator; -import org.molgenis.util.TupleWriter; import org.molgenis.util.Entity; +import org.molgenis.util.TupleWriter; /** * Simple implementation of the Query interface. */ -public class QueryImp implements Query { +public class QueryImp implements Query +{ public Class getKlazz() { return klazz; @@ -22,7 +23,8 @@ public Class getKlazz() private Database database; /** Construct a Query that is not bound to a database and entity-type */ - public QueryImp() { + public QueryImp() + { } /** @@ -34,29 +36,32 @@ public QueryImp() { * @param klazz * the Entity class that this Query will filter. */ - public QueryImp(Database db, Class klazz) { + public QueryImp(Database db, Class klazz) + { this.database = db; this.klazz = klazz; } - public QueryImp(Class klazz) { + public QueryImp(Class klazz) + { this.klazz = klazz; } @Override - public Query filter(String filter) { + public Query filter(String filter) + { String[] args = filter.split(" "); // FIXME - this.rules.add(new QueryRule(args[0], QueryRule.Operator - .valueOf(args[1]), args[2])); + this.rules.add(new QueryRule(args[0], QueryRule.Operator.valueOf(args[1]), args[2])); return this; } @Override - public Query equals(String field, Object value) { + public Query equals(String field, Object value) + { rules.add(new QueryRule(field, Operator.EQUALS, value)); return this; } - + @Override public Query search(String searchTerms) { @@ -65,135 +70,158 @@ public Query search(String searchTerms) } @Override - public Query in(String field, List values) { - if (values.size() > 0) { + public Query in(String field, List values) + { + if (values.size() > 0) + { rules.add(new QueryRule(field, Operator.IN, values.toArray())); } return this; } - + @Override public Query subquery(String field, String sql) { rules.add(new QueryRule(field, Operator.IN_SUBQUERY, sql)); return this; - } - - public Query subQuery(SubQueryRule subQueryRule) + } + + public Query subQuery(SubQueryRule subQueryRule) { rules.add(subQueryRule); return this; } - @Override - public Query greater(String field, Object value) { + public Query greater(String field, Object value) + { rules.add(new QueryRule(field, Operator.GREATER, value)); return this; } @Override - public Query greaterOrEqual(String field, Object value) { + public Query greaterOrEqual(String field, Object value) + { rules.add(new QueryRule(field, Operator.GREATER_EQUAL, value)); return this; } @Override - public Query less(String field, Object value) { + public Query less(String field, Object value) + { rules.add(new QueryRule(field, Operator.LESS, value)); return this; } @Override - public Query lessOrEqual(String field, Object value) { + public Query lessOrEqual(String field, Object value) + { rules.add(new QueryRule(field, Operator.LESS_EQUAL, value)); return this; } @Override - public Query between(String field, Object min, Object max) { + public Query between(String field, Object min, Object max) + { return this.lessOrEqual(field, max).greaterOrEqual(field, min); } @Override - public Query like(String field, Object value) { + public Query like(String field, Object value) + { rules.add(new QueryRule(field, Operator.LIKE, value)); return this; } @Override - public Query last() { + public Query last() + { rules.add(new QueryRule(Operator.LAST)); return this; } @Override - public Query or() { + public Query or() + { rules.add(new QueryRule(Operator.OR)); return this; } @Override - public Query and() { + public Query and() + { rules.add(new QueryRule(Operator.AND)); return this; } @Override - public Query limit(int limit) { + public Query limit(int limit) + { rules.add(new QueryRule(QueryRule.Operator.LIMIT, limit)); return this; } @Override - public Query offset(int offset) { + public Query offset(int offset) + { rules.add(new QueryRule(QueryRule.Operator.OFFSET, offset)); return this; } @Override - public Query sortASC(String orderByField) { + public Query sortASC(String orderByField) + { rules.add(new QueryRule(Operator.SORTASC, orderByField)); return this; } @Override - public Query sortDESC(String orderByField) { + public Query sortDESC(String orderByField) + { rules.add(new QueryRule(Operator.SORTDESC, orderByField)); return this; } @Override - public QueryRule[] getRules() { + public QueryRule[] getRules() + { return rules.toArray(new QueryRule[rules.size()]); } @Override - public String toString() { - String result = ""; - for (QueryRule rule : this.getRules()) { - result += rule.toString(); + public String toString() + { + StringBuilder strBuilder = new StringBuilder(); + for (QueryRule rule : this.getRules()) + { + strBuilder.append(rule.toString()); } - return result; + return strBuilder.toString(); } - public void addRules(List addRules) { - if (addRules != null) { + public void addRules(List addRules) + { + if (addRules != null) + { this.addRules(addRules.toArray(new QueryRule[addRules.size()])); } } @Override - public void addRules(QueryRule... addRules) { - for (QueryRule rule : addRules) { + public void addRules(QueryRule... addRules) + { + for (QueryRule rule : addRules) + { // Logger.getLogger("test").debug("added rule " + rule); rules.add(rule); } } @Override - public List find() throws DatabaseException { - if (this.klazz != null && this.database != null) { + public List find() throws DatabaseException + { + if (this.klazz != null && this.database != null) + { return this.find(this.database, this.klazz); } throw new UnsupportedOperationException( @@ -201,13 +229,16 @@ public List find() throws DatabaseException { } @Override - public List find(Database db, Class klazz) throws DatabaseException { + public List find(Database db, Class klazz) throws DatabaseException + { return db.find(klazz, this.getRules()); } @Override - public int count() throws DatabaseException { - if (this.klazz != null && this.database != null) { + public int count() throws DatabaseException + { + if (this.klazz != null && this.database != null) + { return this.count(this.database, this.klazz); } throw new UnsupportedOperationException( @@ -215,58 +246,68 @@ public int count() throws DatabaseException { } @Override - public int count(Database db, Class klazz) throws DatabaseException { + public int count(Database db, Class klazz) throws DatabaseException + { return db.count(klazz, this.getRules()); } @Override - public void find(TupleWriter writer) throws DatabaseException, ParseException { + public void find(TupleWriter writer) throws DatabaseException, ParseException + { find(writer, null); } @Override - public void find(TupleWriter writer, List fieldsToExport) - throws DatabaseException, ParseException { - if (this.klazz != null && this.database != null) { + public void find(TupleWriter writer, List fieldsToExport) throws DatabaseException, ParseException + { + if (this.klazz != null && this.database != null) + { database.find(this.klazz, writer, fieldsToExport, this.getRules()); - } else { + } + else + { throw new UnsupportedOperationException( "Cannot execute this count query because no database and entity is provided. Use count(Database,Class)"); } } @Override - public void find(TupleWriter writer, boolean skipAutoId) - throws DatabaseException, ParseException, InstantiationException, - IllegalAccessException { + public void find(TupleWriter writer, boolean skipAutoId) throws DatabaseException, ParseException, + InstantiationException, IllegalAccessException + { this.find(writer, this.klazz.newInstance().getFields(skipAutoId)); } @Override - public Query eq(String field, Object value) { + public Query eq(String field, Object value) + { return this.equals(field, value); } @Override - public Query gt(String field, Object value) { + public Query gt(String field, Object value) + { return this.greater(field, value); } @Override - public Query lt(String field, Object value) { + public Query lt(String field, Object value) + { return this.less(field, value); } @Override - public Database getDatabase() { + public Database getDatabase() + { return database; } @Override - public void setDatabase(Database db) { + public void setDatabase(Database db) + { this.database = db; } - + @Override public Query example(Entity example) { @@ -283,25 +324,24 @@ public Query example(Entity example) } } return this; - } - + } public void removeRule(QueryRule ruleToBeRemoved) - { - try - { - rules.remove(ruleToBeRemoved); - } - catch(ArrayIndexOutOfBoundsException e) - { - System.out.println("ArrayIndexOutOfBoundsException " + e.getLocalizedMessage()); - } - } + { + try + { + rules.remove(ruleToBeRemoved); + } + catch (ArrayIndexOutOfBoundsException e) + { + System.out.println("ArrayIndexOutOfBoundsException " + e.getLocalizedMessage()); + } + } @Override public String createFindSql() throws DatabaseException { return database.createFindSql(klazz, this.getRules()); - + } } diff --git a/src/org/molgenis/framework/db/QueryJoinRule.java b/src/org/molgenis/framework/db/QueryJoinRule.java index 995496133..80b08787e 100644 --- a/src/org/molgenis/framework/db/QueryJoinRule.java +++ b/src/org/molgenis/framework/db/QueryJoinRule.java @@ -1,13 +1,14 @@ package org.molgenis.framework.db; - -public class QueryJoinRule extends QueryRule { +public class QueryJoinRule extends QueryRule +{ String e1; String e2; String f1; String f2; - public QueryJoinRule(String entity1, String field1, String entity2, String field2) { + public QueryJoinRule(String entity1, String field1, String entity2, String field2) + { super(entity1 + "." + field1, Operator.JOIN, entity2 + "." + field2); e1 = entity1; e2 = entity2; @@ -15,18 +16,21 @@ public QueryJoinRule(String entity1, String field1, String entity2, String field f2 = field2; } - public String getEntity1() { + public String getEntity1() + { return e1; } - public String getEntity2() { + public String getEntity2() + { return e2; } - - public String getField1(){ + + public String getField1() + { return f1; } - + public String getField2() { return f2; @@ -35,13 +39,13 @@ public String getField2() public void setEntity1(String name) { e1 = name; - this.setField(e1+"."+f1); - + this.setField(e1 + "." + f1); + } public void setEntity2(String name) { e2 = name; - this.setValue(e2+"."+f2); + this.setValue(e2 + "." + f2); } } diff --git a/src/org/molgenis/framework/db/QueryRule.java b/src/org/molgenis/framework/db/QueryRule.java index 7b82d8f69..33f3cf786 100644 --- a/src/org/molgenis/framework/db/QueryRule.java +++ b/src/org/molgenis/framework/db/QueryRule.java @@ -10,6 +10,7 @@ package org.molgenis.framework.db; +import java.util.Arrays; import java.util.List; import org.apache.commons.lang.StringUtils; @@ -30,7 +31,8 @@ * @author Richard Scheltema * @author Morris Swertz */ -public class QueryRule implements Cloneable { +public class QueryRule +{ /** The operator being applied to the field and value */ protected Operator operator; @@ -40,25 +42,25 @@ public class QueryRule implements Cloneable { /** The value to compare entries of the field in the database with */ protected Object value = null; - /** Indicate wheter this should evaluate to OR */ - private boolean or = false; // default AND - /** Place to store nested rules */ // FIXME: why not put this in value? private QueryRule[] nestedRules; - public QueryRule() { + public QueryRule() + { } - public QueryRule(QueryRule copy) { + public QueryRule(QueryRule copy) + { operator = copy.operator; field = copy.field; value = copy.value; - or = copy.or; - if (copy.nestedRules != null) { + if (copy.nestedRules != null) + { nestedRules = new QueryRule[copy.nestedRules.length]; - for (int i = 0; i < copy.nestedRules.length; i++) { + for (int i = 0; i < copy.nestedRules.length; i++) + { nestedRules[i] = new QueryRule(copy.nestedRules[i]); } } @@ -67,7 +69,8 @@ public QueryRule(QueryRule copy) { /** * Different types of rules that can be applied. */ - public enum Operator { + public enum Operator + { /** search all fields */ SEARCH("search"), /** 'field' equal to 'value' */ @@ -136,7 +139,8 @@ public enum Operator { * @param name * of the operator */ - Operator(String label) { + Operator(String label) + { this.label = label; } @@ -144,7 +148,8 @@ public enum Operator { * Get the String label of the Operator. */ @Override - public String toString() { + public String toString() + { return label; } } @@ -164,13 +169,14 @@ public String toString() { * @param value * The value. */ - public QueryRule(String field, Operator operator, Object value) { - if (operator == Operator.LIMIT || operator == Operator.OFFSET - || operator == Operator.SORTASC - || operator == Operator.SORTDESC || operator == Operator.LAST - || operator == Operator.AND || operator == Operator.OR) { - throw new IllegalArgumentException("QueryRule(): Operator." - + operator + " cannot be used with two arguments"); + public QueryRule(String field, Operator operator, Object value) + { + if (operator == Operator.LIMIT || operator == Operator.OFFSET || operator == Operator.SORTASC + || operator == Operator.SORTDESC || operator == Operator.LAST || operator == Operator.AND + || operator == Operator.OR) + { + throw new IllegalArgumentException("QueryRule(): Operator." + operator + + " cannot be used with two arguments"); } this.field = field; this.operator = operator; @@ -183,7 +189,8 @@ public QueryRule(String field, Operator operator, Object value) { * @param rules * to be nested. */ - public QueryRule(QueryRule... rules) { + public QueryRule(QueryRule... rules) + { operator = Operator.NESTED; nestedRules = rules; } @@ -195,25 +202,33 @@ public QueryRule(QueryRule... rules) { * @param operator * @param value */ - public QueryRule(Operator operator, Object value) { - if (operator == Operator.LIMIT || operator == Operator.OFFSET - || operator == Operator.SORTASC - || operator == Operator.SORTDESC || operator == Operator.SEARCH) { + public QueryRule(Operator operator, Object value) + { + if (operator == Operator.LIMIT || operator == Operator.OFFSET || operator == Operator.SORTASC + || operator == Operator.SORTDESC || operator == Operator.SEARCH) + { this.operator = operator; this.value = value; - } else { - throw new IllegalArgumentException("QueryRule(): Operator." - + operator + " cannot be used with one argument"); + } + else + { + throw new IllegalArgumentException("QueryRule(): Operator." + operator + + " cannot be used with one argument"); } } - public QueryRule(Operator operator, QueryRule nestedRules) { - if (operator == Operator.NOT || operator == Operator.IN_SUBQUERY) { + public QueryRule(Operator operator, QueryRule nestedRules) + { + if (operator == Operator.NOT || operator == Operator.IN_SUBQUERY) + { this.operator = operator; - this.nestedRules = new QueryRule[] { nestedRules }; - } else { - throw new IllegalArgumentException("QueryRule(): Operator." - + operator + " cannot be used with one argument"); + this.nestedRules = new QueryRule[] + { nestedRules }; + } + else + { + throw new IllegalArgumentException("QueryRule(): Operator." + operator + + " cannot be used with one argument"); } } @@ -221,21 +236,26 @@ public QueryRule(Operator operator, QueryRule nestedRules) { * Specific constructor for rules that don't have a value or field such as * LAST */ - public QueryRule(Operator operator) { - if (operator == Operator.LAST || operator == Operator.AND - || operator == Operator.OR) { + public QueryRule(Operator operator) + { + if (operator == Operator.LAST || operator == Operator.AND || operator == Operator.OR) + { this.operator = operator; - } else { - throw new IllegalArgumentException("QueryRule(): Operator '" - + operator + "' cannot be used without arguments"); + } + else + { + throw new IllegalArgumentException("QueryRule(): Operator '" + operator + + "' cannot be used without arguments"); } } - public QueryRule(List rules) { + public QueryRule(List rules) + { this(rules.toArray(new QueryRule[rules.size()])); } - public QueryRule(String field, Operator equals, String value) { + public QueryRule(String field, Operator equals, String value) + { this(field, equals, (Object) value); } @@ -244,16 +264,19 @@ public QueryRule(String field, Operator equals, String value) { * * @return The field-name. */ - public String getField() { + public String getField() + { return field; } /** * Returns the field-name as a JPA Attribute */ - public String getJpaAttribute() { - if(!StringUtils.isEmpty(field)) { - return field.substring(0,1).toLowerCase() + field.substring(1); + public String getJpaAttribute() + { + if (!StringUtils.isEmpty(field)) + { + return field.substring(0, 1).toLowerCase() + field.substring(1); } return field; } @@ -264,7 +287,8 @@ public String getJpaAttribute() { * @param field * The new field-name. */ - public void setField(String field) { + public void setField(String field) + { this.field = field; } @@ -273,7 +297,8 @@ public void setField(String field) { * * @return The operator. */ - public Operator getOperator() { + public Operator getOperator() + { return operator; } @@ -283,7 +308,8 @@ public Operator getOperator() { * @param operator * The new operator. */ - public void setOperator(Operator operator) { + public void setOperator(Operator operator) + { this.operator = operator; } @@ -292,7 +318,8 @@ public void setOperator(Operator operator) { * * @return The value. */ - public Object getValue() { + public Object getValue() + { return value; } @@ -302,7 +329,8 @@ public Object getValue() { * @param value * The new value. */ - public void setValue(Object value) { + public void setValue(Object value) + { this.value = value; } @@ -311,55 +339,72 @@ public void setValue(Object value) { * * @return Nested rule set */ - public QueryRule[] getNestedRules() { + public QueryRule[] getNestedRules() + { return nestedRules; } - @Override - public boolean equals(Object o) { - if (o != null && o instanceof QueryRule) { - final QueryRule r = (QueryRule) o; - - if (( - // field - r.getField() != null - && r.getField().equals(this.getField()) || r.getField() == this.getField()) - // operator - && (r.getOperator() != null - && r.getOperator().equals(this.getOperator()) || r.getOperator() == this.getOperator()) - // value - && (r.getValue() != null - && r.getValue().equals(this.getValue()) || r.getValue() == this.getValue()) - // nested rules - && (r.getNestedRules() != null - && r.getNestedRules().equals(this.getNestedRules()) || r.getNestedRules() == this.getNestedRules())) { - return true; - } - } - return false; - } - @Override /** * */ - public String toString() { - String result = ""; - if (this.getOperator().equals(Operator.NESTED)) { - result += "("; - - for (final QueryRule rule : this.getNestedRules()) { - result += rule.toString(); + public String toString() + { + StringBuilder strBuilder = new StringBuilder(); + if (this.getOperator().equals(Operator.NESTED)) + { + strBuilder.append('('); + + for (final QueryRule rule : this.getNestedRules()) + { + strBuilder.append(rule.toString()); } - result += ")"; - } else { - result = (this.getField() == null ? "" : (this.getField() + " ")) - + this.getOperator() + (value == null ? "" : " '" + value + "'"); + strBuilder.append(')'); } - return result; + else + { + strBuilder.append(this.getField() == null ? "" : (this.getField() + " ")); + strBuilder.append(this.getOperator()).append(value == null ? "" : " '" + value + "'"); + } + return strBuilder.toString(); } - public static QueryRule eq(String name, Object value) { + public static QueryRule eq(String name, Object value) + { return new QueryRule(name, Operator.EQUALS, value); } + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + ((field == null) ? 0 : field.hashCode()); + result = prime * result + Arrays.hashCode(nestedRules); + result = prime * result + ((operator == null) ? 0 : operator.hashCode()); + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) + { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + QueryRule other = (QueryRule) obj; + if (field == null) + { + if (other.field != null) return false; + } + else if (!field.equals(other.field)) return false; + if (!Arrays.equals(nestedRules, other.nestedRules)) return false; + if (operator != other.operator) return false; + if (value == null) + { + if (other.value != null) return false; + } + else if (!value.equals(other.value)) return false; + return true; + } } diff --git a/src/org/molgenis/framework/db/SubQueryRule.java b/src/org/molgenis/framework/db/SubQueryRule.java index 126e1061d..e8474c1b7 100644 --- a/src/org/molgenis/framework/db/SubQueryRule.java +++ b/src/org/molgenis/framework/db/SubQueryRule.java @@ -9,8 +9,10 @@ public class SubQueryRule extends QueryRule private final Class subQueryFromClass; private final Operator subQueryOperator; private final String subQueryField; - - public SubQueryRule(String fieldName, Operator subQueryOperator, String subQueryField, Class subQueryResultClass, Class subQueryFromClass, QueryRule... subQueryRules) { + + public SubQueryRule(String fieldName, Operator subQueryOperator, String subQueryField, + Class subQueryResultClass, Class subQueryFromClass, QueryRule... subQueryRules) + { super(fieldName, Operator.SUBQUERY, subQueryRules); this.subQueryResultClass = subQueryResultClass; this.subQueryFromClass = subQueryFromClass; @@ -32,15 +34,18 @@ public Operator getSubQueryOperator() { return subQueryOperator; } - - public String getSubQueryField() { + + public String getSubQueryField() + { + return subQueryField; + } + + public String getSubQueryAttributeJpa() + { + if (!StringUtils.isEmpty(subQueryField)) + { + return subQueryField.substring(0, 1).toLowerCase() + subQueryField.substring(1); + } return subQueryField; - } - - public String getSubQueryAttributeJpa() { - if(!StringUtils.isEmpty(subQueryField)) { - return subQueryField.substring(0,1).toLowerCase() + subQueryField.substring(1); - } - return subQueryField; } } diff --git a/src/org/molgenis/framework/db/jdbc/AbstractDataSourceWrapper.java b/src/org/molgenis/framework/db/jdbc/AbstractDataSourceWrapper.java index 7900007a1..2cfe84f7b 100644 --- a/src/org/molgenis/framework/db/jdbc/AbstractDataSourceWrapper.java +++ b/src/org/molgenis/framework/db/jdbc/AbstractDataSourceWrapper.java @@ -12,12 +12,12 @@ public abstract class AbstractDataSourceWrapper implements DataSourceWrapper { private static transient final Logger logger = Logger.getLogger(AbstractDataSourceWrapper.class.getSimpleName()); - + public Connection getConnection() throws NamingException, SQLException { return this.getDataSource().getConnection(); } - + @Override public String getDriverClassName() { @@ -25,9 +25,9 @@ public String getDriverClassName() try { ds = getDataSource(); - if(ds instanceof BasicDataSource) + if (ds instanceof BasicDataSource) { - return ((BasicDataSource)ds).getDriverClassName(); + return ((BasicDataSource) ds).getDriverClassName(); } } catch (NamingException e) @@ -38,28 +38,28 @@ public String getDriverClassName() logger.error("UNKNOWN DRIVER"); return "UNKNOWN"; } - + @Override public int countOpenConnections() throws NamingException { - if(this.getDataSource() instanceof org.apache.commons.dbcp.BasicDataSource) + if (this.getDataSource() instanceof org.apache.commons.dbcp.BasicDataSource) { - return ((org.apache.commons.dbcp.BasicDataSource)this.getDataSource()).getNumActive(); + return ((org.apache.commons.dbcp.BasicDataSource) this.getDataSource()).getNumActive(); } logger.debug(getDataSource().getClass()); return 0; } - + @Override public int getMaxActive() throws NamingException { - if(this.getDataSource() instanceof org.apache.commons.dbcp.BasicDataSource) + if (this.getDataSource() instanceof org.apache.commons.dbcp.BasicDataSource) { - return ((org.apache.commons.dbcp.BasicDataSource)this.getDataSource()).getMaxActive(); + return ((org.apache.commons.dbcp.BasicDataSource) this.getDataSource()).getMaxActive(); } logger.debug(getDataSource().getClass()); return 0; } - + protected abstract DataSource getDataSource() throws NamingException; } diff --git a/src/org/molgenis/framework/db/jdbc/AbstractJDBCMapper.java b/src/org/molgenis/framework/db/jdbc/AbstractJDBCMapper.java index d7690a57b..32109a529 100644 --- a/src/org/molgenis/framework/db/jdbc/AbstractJDBCMapper.java +++ b/src/org/molgenis/framework/db/jdbc/AbstractJDBCMapper.java @@ -696,7 +696,7 @@ else if (rule.getOperator() == QueryRule.Operator.OFFSET) public String createSortSql(boolean reverseSorting, QueryRule rules[]) { // copy parameter into local temp so we can change it - String sort_clause = ""; + StringBuilder sort_clauseBuilder = new StringBuilder(); if (rules != null) { Boolean revSort = reverseSorting; @@ -719,18 +719,19 @@ public String createSortSql(boolean reverseSorting, QueryRule rules[]) || (revSort && rule.getOperator() == Operator.SORTDESC)) { rule.setValue(getTableFieldName(rule.getValue().toString())); - sort_clause += rule.getValue().toString() + " ASC,"; + sort_clauseBuilder.append(rule.getValue().toString()).append(" ASC,"); } else if ((rule.getOperator() == QueryRule.Operator.SORTDESC && !revSort) || (revSort && rule.getOperator() == Operator.SORTASC)) { rule.setValue(getTableFieldName(rule.getValue().toString())); - sort_clause += rule.getValue().toString() + " DESC,"; + sort_clauseBuilder.append(rule.getValue().toString()).append(" DESC,"); } } } - if (sort_clause.length() > 0) return " ORDER BY " + sort_clause.substring(0, sort_clause.lastIndexOf(",")); - return sort_clause; + if (sort_clauseBuilder.length() > 0) return " ORDER BY " + + sort_clauseBuilder.substring(0, sort_clauseBuilder.lastIndexOf(",")); + return sort_clauseBuilder.toString(); } private static boolean omitQuotes(FieldType t) diff --git a/src/org/molgenis/framework/db/jdbc/DataSourceWrapper.java b/src/org/molgenis/framework/db/jdbc/DataSourceWrapper.java index 2aa492772..be2891418 100644 --- a/src/org/molgenis/framework/db/jdbc/DataSourceWrapper.java +++ b/src/org/molgenis/framework/db/jdbc/DataSourceWrapper.java @@ -15,8 +15,8 @@ public interface DataSourceWrapper int getMaxActive() throws NamingException; - //public String getDriverClassName() throws NamingException; - - //public int getNumActive(); - + // public String getDriverClassName() throws NamingException; + + // public int getNumActive(); + } \ No newline at end of file diff --git a/src/org/molgenis/framework/db/jdbc/JDBCDatabase.java b/src/org/molgenis/framework/db/jdbc/JDBCDatabase.java index 1e008c478..989f88d89 100644 --- a/src/org/molgenis/framework/db/jdbc/JDBCDatabase.java +++ b/src/org/molgenis/framework/db/jdbc/JDBCDatabase.java @@ -16,6 +16,7 @@ import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; +import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.molgenis.MolgenisOptions; import org.molgenis.framework.db.AbstractDatabase; @@ -116,8 +117,15 @@ public JDBCDatabase(File propertiesFilePath) throws FileNotFoundException, IOExc { super(); Properties p = new Properties(); - p.load(new FileInputStream(propertiesFilePath)); - + InputStream is = new FileInputStream(propertiesFilePath); + try + { + p.load(is); + } + finally + { + IOUtils.closeQuietly(is); + } BasicDataSource dSource = new BasicDataSource(); dSource.setDriverClassName(p.getProperty("db_driver")); dSource.setUsername(p.getProperty("db_user")); @@ -135,13 +143,27 @@ public JDBCDatabase(String propertiesFilePath) throws FileNotFoundException, IOE { super(); Properties p = new Properties(); + InputStream is = null; try { - p.load(new FileInputStream(propertiesFilePath)); + is = new FileInputStream(propertiesFilePath); + p.load(is); } - catch (Exception e) + catch (IOException e) + { + InputStream is2 = ClassLoader.getSystemResourceAsStream(propertiesFilePath); + try + { + p.load(is2); + } + finally + { + IOUtils.closeQuietly(is2); + } + } + finally { - p.load(ClassLoader.getSystemResourceAsStream(propertiesFilePath)); + IOUtils.closeQuietly(is); } BasicDataSource dSource = new BasicDataSource(); @@ -392,7 +414,7 @@ public void updateTables() @Override public void dropTables() throws DatabaseException { - this.executeSqlFile("/drop_tables.sql"); + // this.executeSqlFile("/drop_tables.sql"); } @Override @@ -408,20 +430,20 @@ private void executeSqlFile(String filename) throws DatabaseException try { conn = this.getConnection(); - String create_tables_sql = ""; + StringBuilder create_tables_sqlBuilder = new StringBuilder(); InputStream fis = this.getClass().getResourceAsStream(filename); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = in.readLine()) != null) { - create_tables_sql += line + "\n"; + create_tables_sqlBuilder.append(line).append('\n'); } in.close(); stmt = conn.createStatement(); int i = 0; - for (String command : create_tables_sql.split(";")) + for (String command : create_tables_sqlBuilder.toString().split(";")) { if (command.trim().length() > 0) { diff --git a/src/org/molgenis/framework/db/jdbc/JDBCQueryGernatorUtil.java b/src/org/molgenis/framework/db/jdbc/JDBCQueryGernatorUtil.java index 64749c5b5..54237a3d7 100644 --- a/src/org/molgenis/framework/db/jdbc/JDBCQueryGernatorUtil.java +++ b/src/org/molgenis/framework/db/jdbc/JDBCQueryGernatorUtil.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.List; + import org.apache.commons.lang.StringEscapeUtils; import org.molgenis.fieldtypes.DecimalField; import org.molgenis.fieldtypes.FieldType; @@ -20,7 +21,8 @@ * * @author */ -public class JDBCQueryGernatorUtil { +public class JDBCQueryGernatorUtil +{ /** * Helper method for creating a where clause from QueryRule...rules. * @@ -44,84 +46,112 @@ public static String createWhereSql(Mapper mapper, boolean isNested, boolean { StringBuilder where_clause = new StringBuilder(""); QueryRule previousRule = new QueryRule(Operator.AND); - if(rules != null){ - for (QueryRule r : rules) + if (rules != null) { - //logger.debug(r); - //skip OR and AND operators - if( r.getOperator().equals(Operator.OR) || r.getOperator().equals(Operator.AND)) - { - previousRule = r; - } - else + for (QueryRule r : rules) { - QueryRule rule = new QueryRule(r); // copy because of side - // effects - // logger.debug(rule); - - // String tablePrefix = ""; - if (mapper != null) { - rule.setField(mapper.getTableFieldName(rule.getField())); - } - - if (rule.getOperator() == Operator.LAST || rule.getOperator() == Operator.LIMIT - || rule.getOperator() == Operator.OFFSET || rule.getOperator() == Operator.SORTASC - || rule.getOperator() == Operator.SORTDESC) + // logger.debug(r); + // skip OR and AND operators + if (r.getOperator().equals(Operator.OR) || r.getOperator().equals(Operator.AND)) { - + previousRule = r; } - else if (rule.getOperator() == QueryRule.Operator.SEARCH) + else { - // naive implementation, should use hibernate search when it comes - // available! - List searchRules = new ArrayList(); + QueryRule rule = new QueryRule(r); // copy because of side + // effects + // logger.debug(rule); + + // String tablePrefix = ""; + if (mapper != null) + { + rule.setField(mapper.getTableFieldName(rule.getField())); + } + + if (rule.getOperator() == Operator.LAST || rule.getOperator() == Operator.LIMIT + || rule.getOperator() == Operator.OFFSET || rule.getOperator() == Operator.SORTASC + || rule.getOperator() == Operator.SORTDESC) + { - try + } + else if (rule.getOperator() == QueryRule.Operator.SEARCH) { - boolean addOr = false; - - // try create big OR filter for all fields and all search elements - // todo: enable string term concat using quotes - for (String term : rule.getValue().toString().split(" ")) + // naive implementation, should use hibernate search + // when it comes + // available! + List searchRules = new ArrayList(); + + try { - List termRules = new ArrayList(); + boolean addOr = false; - // create different query rule depending on type - List fields = mapper.getDatabase().getMetaData() - .getEntity(mapper.create().getClass().getSimpleName()).getAllFields(); - for (Field f : fields) + // try create big OR filter for all fields and all + // search elements + // todo: enable string term concat using quotes + for (String term : rule.getValue().toString().split(" ")) { - if (f.getType() instanceof StringField - || f.getType() instanceof TextField) + List termRules = new ArrayList(); + + // create different query rule depending on type + List fields = mapper.getDatabase().getMetaData() + .getEntity(mapper.create().getClass().getSimpleName()).getAllFields(); + for (Field f : fields) { - termRules.add(new QueryRule(f.getName(), Operator.LIKE, - term.trim())); - termRules.add(new QueryRule(Operator.OR)); + if (f.getType() instanceof StringField || f.getType() instanceof TextField) + { + termRules.add(new QueryRule(f.getName(), Operator.LIKE, term.trim())); + termRules.add(new QueryRule(Operator.OR)); + } } + + // add as big X or Y or Z subquery to our rules + searchRules.add(new QueryRule(termRules)); + if (addOr) searchRules.add(new QueryRule(Operator.OR)); + addOr = true; } - - //add as big X or Y or Z subquery to our rules - searchRules.add(new QueryRule(termRules)); - if(addOr) searchRules.add(new QueryRule(Operator.OR)); - addOr = true; } + catch (Exception e) + { + throw new DatabaseException(e); + } + + // add to rules + where_clause.append("("); + where_clause.append(createWhereSql(mapper, true, false, + searchRules.toArray(new QueryRule[searchRules.size()]))); + where_clause.append(")"); + } - catch (Exception e) + else if (rule.getOperator() == QueryRule.Operator.NESTED + || (rule.getOperator() == QueryRule.Operator.NOT && rule.getNestedRules() != null && rule + .getNestedRules().length > 0)) { - throw new DatabaseException(e); - } + QueryRule[] nestedrules = rule.getNestedRules(); + if (nestedrules.length > 0) + { + if (where_clause.length() > 0) + { + if (previousRule != null && Operator.OR.equals(previousRule.getOperator())) + { + where_clause.append(" OR "); + } + else + { + where_clause.append(" AND "); + } + } - //add to rules - where_clause.append("("); - where_clause.append(createWhereSql(mapper, true, false, searchRules.toArray(new QueryRule[searchRules.size()]))); - where_clause.append(")"); - - } - else if (rule.getOperator() == QueryRule.Operator.NESTED || - (rule.getOperator() == QueryRule.Operator.NOT && rule.getNestedRules() != null && rule.getNestedRules().length > 0) ) - { - QueryRule[] nestedrules = rule.getNestedRules(); - if (nestedrules.length > 0) + if (rule.getOperator() == QueryRule.Operator.NOT) + { + where_clause.append("NOT"); + } + where_clause.append("("); + where_clause.append(createWhereSql(mapper, true, false, nestedrules)); + where_clause.append(")"); + } + } + // experimental: subqery + else if (rule.getOperator() == QueryRule.Operator.IN_SUBQUERY) { if (where_clause.length() > 0) { @@ -134,39 +164,102 @@ else if (rule.getOperator() == QueryRule.Operator.NESTED || where_clause.append(" AND "); } } - - if(rule.getOperator() == QueryRule.Operator.NOT) { - where_clause.append("NOT"); - } - where_clause.append("("); - where_clause.append(createWhereSql(mapper, true, false, nestedrules)); - where_clause.append(")"); + where_clause.append(rule.getField() + " IN(" + rule.getValue() + ")"); } - } - //experimental: subqery - else if (rule.getOperator() == QueryRule.Operator.IN_SUBQUERY) - { - if (where_clause.length() > 0) + else if (rule.getOperator() == QueryRule.Operator.IN) { - if (previousRule != null && Operator.OR.equals(previousRule.getOperator())) - { - where_clause.append(" OR "); - } - else + // only add if nonempty condition??? + if (rule.getValue() == null + || (rule.getValue() instanceof List && ((List) rule.getValue()).size() == 0) + || (rule.getValue() instanceof Object[] && ((Object[]) rule.getValue()).length == 0)) throw new DatabaseException( + "empty 'in' clause for rule " + rule); { - where_clause.append(" AND "); + if (where_clause.length() > 0) + { + if (previousRule != null && Operator.OR.equals(previousRule.getOperator())) + { + where_clause.append(" OR "); + } + else + { + where_clause.append(" AND "); + } + } + + // where_clause.append(tablePrefix + rule.getField() + // + + // " IN("); + where_clause.append(rule.getField() + " IN("); + + Object[] values = new Object[0]; + if (rule.getValue() instanceof List) + { + values = ((List) rule.getValue()).toArray(); + } + else + { + values = (Object[]) rule.getValue(); + } + + for (int i = 0; i < values.length; i++) + { + if (i > 0) where_clause.append(","); + if (mapper != null && omitQuotes(mapper.getFieldType(rule.getField()))) + { + // where_clause.append(values[i] + // .toString()); + where_clause.append("" + escapeSql(values[i]) + ""); + } + else + { + where_clause.append("'" + escapeSql(values[i]) + "'"); + } + } + where_clause.append(") "); } } - where_clause.append(rule.getField() + " IN("+rule.getValue()+")"); - } - else if (rule.getOperator() == QueryRule.Operator.IN) - { - // only add if nonempty condition??? - if (rule.getValue() == null - || (rule.getValue() instanceof List && ((List) rule.getValue()).size() == 0) - || (rule.getValue() instanceof Object[] && ((Object[]) rule.getValue()).length == 0)) throw new DatabaseException( - "empty 'in' clause for rule " + rule); + else + // where clause { + // check validity of the rule + // if(rule.getField() == null || + // columnInfoMap.get(rule.getField()) == null ) + // { + // throw new DatabaseException("Invalid rule: field '"+ + // rule.getField() + "' not known."); + // } + + String operator = ""; + switch (rule.getOperator()) + { + case EQUALS: + operator = "="; + break; + case JOIN: + operator = "="; + break; + case NOT: + operator = "!="; + break; + case LIKE: + operator = "LIKE"; + break; + case LESS: + operator = "<"; + break; + case GREATER: + operator = ">"; + break; + case LESS_EQUAL: + operator = "<="; + break; + case GREATER_EQUAL: + operator = ">="; + break; + } + // if (rule.getField() != "" && operator != "" && + // rule.getValue() != "") + // { if (where_clause.length() > 0) { if (previousRule != null && Operator.OR.equals(previousRule.getOperator())) @@ -178,130 +271,52 @@ else if (rule.getOperator() == QueryRule.Operator.IN) where_clause.append(" AND "); } } + if (Boolean.TRUE.equals(rule.getValue())) rule.setValue("1"); + if (Boolean.FALSE.equals(rule.getValue())) rule.setValue("0"); + Object value = rule.getValue() == null ? "NULL" : escapeSql(rule.getValue()); - // where_clause.append(tablePrefix + rule.getField() + - // " IN("); - where_clause.append(rule.getField() + " IN("); - - Object[] values = new Object[0]; - if (rule.getValue() instanceof List) + if (!value.equals("NULL") && rule.getOperator() == Operator.LIKE + && (mapper == null || !omitQuotes(mapper.getFieldType(rule.getField())))) { - values = ((List) rule.getValue()).toArray(); + if (!value.toString().trim().startsWith("%") && !value.toString().trim().endsWith("%")) + { + value = "%" + value + "%"; + } } - else + + // if + // (omitQuotes(columnInfoMap.get(rule.getField()).getType())) + // where_clause.append(tablePrefix + rule.getField() + + // " " + + // operator + " " + value + ""); + // else + // where_clause.append(tablePrefix + rule.getField() + + // " " + + // operator + " '" + value + "'"); + if (rule.getOperator().equals(Operator.JOIN)) { - values = (Object[]) rule.getValue(); + where_clause.append(rule.getField() + " " + operator + " " + value + ""); } - - for (int i = 0; i < values.length; i++) + else { - if (i > 0) where_clause.append(","); - if (mapper != null && omitQuotes(mapper.getFieldType(rule.getField()))) + if ("NULL".equals(value) && operator.equals("=")) + { + where_clause.append(rule.getField() + " IS NULL"); + } + else if ("NULL".equals(value) && operator.equals("!=")) { - // where_clause.append(values[i] - // .toString()); - where_clause.append("" + escapeSql(values[i]) + ""); + where_clause.append(rule.getField() + " IS NOT NULL"); } else { - where_clause.append("'" + escapeSql(values[i]) + "'"); + where_clause.append(rule.getField() + " " + operator + " '" + value + "'"); } } - where_clause.append(") "); } + previousRule = null; } - else - // where clause - { - // check validity of the rule - // if(rule.getField() == null || - // columnInfoMap.get(rule.getField()) == null ) - // { - // throw new DatabaseException("Invalid rule: field '"+ - // rule.getField() + "' not known."); - // } - - String operator = ""; - switch (rule.getOperator()) - { - case EQUALS: - operator = "="; - break; - case JOIN: - operator = "="; - break; - case NOT: - operator = "!="; - break; - case LIKE: - operator = "LIKE"; - break; - case LESS: - operator = "<"; - break; - case GREATER: - operator = ">"; - break; - case LESS_EQUAL: - operator = "<="; - break; - case GREATER_EQUAL: - operator = ">="; - break; - } - // if (rule.getField() != "" && operator != "" && - // rule.getValue() != "") - // { - if (where_clause.length() > 0) - { - if (previousRule != null && Operator.OR.equals(previousRule.getOperator())) - { - where_clause.append(" OR "); - } - else - { - where_clause.append(" AND "); - } - } - if (Boolean.TRUE.equals(rule.getValue())) rule.setValue("1"); - if (Boolean.FALSE.equals(rule.getValue())) rule.setValue("0"); - Object value = rule.getValue() == null ? "NULL" : escapeSql(rule.getValue()); - - if (!value.equals("NULL") && rule.getOperator() == Operator.LIKE - && (mapper == null || !omitQuotes(mapper.getFieldType(rule.getField())))) - { - if (!value.toString().trim().startsWith("%") && !value.toString().trim().endsWith("%")) - { - value = "%" + value + "%"; - } - } - - // if - // (omitQuotes(columnInfoMap.get(rule.getField()).getType())) - // where_clause.append(tablePrefix + rule.getField() + " " + - // operator + " " + value + ""); - // else - // where_clause.append(tablePrefix + rule.getField() + " " + - // operator + " '" + value + "'"); - if (rule.getOperator().equals(Operator.JOIN)) { - where_clause.append(rule.getField() + " " + operator - + " " + value + ""); - } - else - { - if ("NULL".equals(value) && operator.equals("=")) { - where_clause.append(rule.getField() + " IS NULL"); - } else if ("NULL".equals(value) && operator.equals("!=")) { - where_clause.append(rule.getField() + " IS NOT NULL"); - } else { - where_clause.append(rule.getField() + " " + operator + " '" + value + "'"); - } - } - } - previousRule = null; } } - } String result = where_clause.toString(); if (!isNested && where_clause.length() > 0) result = " WHERE " + result; return result + createSortSql(mapper, rules) + createLimitSql(withOffset, rules); @@ -316,9 +331,10 @@ private static String createSortSql(Mapper mapper, QueryRule... rules) private static boolean omitQuotes(FieldType t) { return t instanceof LongField || t instanceof IntField || t instanceof DecimalField; - - //t.equals(Type.LONG) || t.equals(Type.INT) || t.equals(Type.DECIMAL); -// return t instanceof LongField || t instanceof IntField|| t instanceof DecimalField; + + // t.equals(Type.LONG) || t.equals(Type.INT) || t.equals(Type.DECIMAL); + // return t instanceof LongField || t instanceof IntField|| t instanceof + // DecimalField; } @@ -338,40 +354,42 @@ private static boolean omitQuotes(FieldType t) public static String createSortSql(Mapper mapper, boolean reverseSorting, QueryRule rules[]) { // copy parameter into local temp so we can change it - String sort_clause = ""; - if(rules != null){ - Boolean revSort = reverseSorting; - for (QueryRule rule : rules) + StringBuilder sort_clauseBuilder = new StringBuilder(); + if (rules != null) { - if (rule.getOperator() == Operator.LAST) + Boolean revSort = reverseSorting; + for (QueryRule rule : rules) { - revSort = !revSort; - break; + if (rule.getOperator() == Operator.LAST) + { + revSort = !revSort; + break; + } } - } - - - for (QueryRule r : rules) - { - QueryRule rule = new QueryRule(r); // copy because of sideeffects - // limit clause - if ((rule.getOperator() == Operator.SORTASC && !revSort) - || (revSort && rule.getOperator() == Operator.SORTDESC)) + for (QueryRule r : rules) { - if (mapper != null) rule.setValue(mapper.getTableFieldName(rule.getValue().toString())); - sort_clause += rule.getValue().toString() + " ASC,"; - } - else if ((rule.getOperator() == QueryRule.Operator.SORTDESC && !revSort) - || (revSort && rule.getOperator() == Operator.SORTASC)) - { - if (mapper != null) rule.setValue(mapper.getTableFieldName(rule.getValue().toString())); - sort_clause += rule.getValue().toString() + " DESC,"; + QueryRule rule = new QueryRule(r); // copy because of + // sideeffects + + // limit clause + if ((rule.getOperator() == Operator.SORTASC && !revSort) + || (revSort && rule.getOperator() == Operator.SORTDESC)) + { + if (mapper != null) rule.setValue(mapper.getTableFieldName(rule.getValue().toString())); + sort_clauseBuilder.append(rule.getValue().toString()).append(" ASC,"); + } + else if ((rule.getOperator() == QueryRule.Operator.SORTDESC && !revSort) + || (revSort && rule.getOperator() == Operator.SORTASC)) + { + if (mapper != null) rule.setValue(mapper.getTableFieldName(rule.getValue().toString())); + sort_clauseBuilder.append(rule.getValue().toString()).append(" DESC,"); + } } } - } - if (sort_clause.length() > 0) return " ORDER BY " + sort_clause.substring(0, sort_clause.lastIndexOf(",")); - return sort_clause; + if (sort_clauseBuilder.length() > 0) return " ORDER BY " + + sort_clauseBuilder.substring(0, sort_clauseBuilder.lastIndexOf(",")); + return sort_clauseBuilder.toString(); } /** @@ -388,20 +406,21 @@ public static String createLimitSql(boolean withOffset, QueryRule[] rules) { String limit_clause = ""; String offset_clause = ""; - if(rules != null){ - for (QueryRule rule : rules) + if (rules != null) { - // limit clause - if (rule.getOperator() == QueryRule.Operator.LIMIT) + for (QueryRule rule : rules) { - limit_clause = " LIMIT " + rule.getValue(); - } - else if (rule.getOperator() == QueryRule.Operator.OFFSET) - { - offset_clause = " OFFSET " + rule.getValue(); + // limit clause + if (rule.getOperator() == QueryRule.Operator.LIMIT) + { + limit_clause = " LIMIT " + rule.getValue(); + } + else if (rule.getOperator() == QueryRule.Operator.OFFSET) + { + offset_clause = " OFFSET " + rule.getValue(); + } } } - } if (withOffset || offset_clause.equals("")) return limit_clause + offset_clause; return ""; } @@ -417,12 +436,12 @@ else if (rule.getOperator() == QueryRule.Operator.OFFSET) */ public static String escapeSql(Object value) { - if(value != null && value.toString().contains("Specific diagnosis Mutation")) + if (value != null && value.toString().contains("Specific diagnosis Mutation")) { System.out.println("trouble"); } if (value != null) return StringEscapeUtils.escapeSql(value.toString()); return null; // return sql.toString().replace("'", "''"); - } + } } diff --git a/src/org/molgenis/framework/db/jdbc/JndiDataSourceWrapper.java b/src/org/molgenis/framework/db/jdbc/JndiDataSourceWrapper.java index 3443c3048..0a02c5b02 100644 --- a/src/org/molgenis/framework/db/jdbc/JndiDataSourceWrapper.java +++ b/src/org/molgenis/framework/db/jdbc/JndiDataSourceWrapper.java @@ -14,11 +14,11 @@ public JndiDataSourceWrapper(String jndiPath) } @Override - protected DataSource getDataSource() throws NamingException + protected DataSource getDataSource() throws NamingException { - InitialContext context = new InitialContext(); - DataSource dsource = (DataSource) context.lookup( jndiPath ); - //logger.debug("Getting dataSource"); + InitialContext context = new InitialContext(); + DataSource dsource = (DataSource) context.lookup(jndiPath); + // logger.debug("Getting dataSource"); return dsource; } } diff --git a/src/org/molgenis/framework/db/jdbc/SimpleDataSourceWrapper.java b/src/org/molgenis/framework/db/jdbc/SimpleDataSourceWrapper.java index 9b25574f7..0191db96b 100644 --- a/src/org/molgenis/framework/db/jdbc/SimpleDataSourceWrapper.java +++ b/src/org/molgenis/framework/db/jdbc/SimpleDataSourceWrapper.java @@ -6,18 +6,18 @@ public class SimpleDataSourceWrapper extends AbstractDataSourceWrapper { DataSource dSource; - + public SimpleDataSourceWrapper(DataSource dSource) { if (dSource == null || !(dSource instanceof DataSource)) throw new IllegalArgumentException( - "DataSource cannot be null"); + "DataSource cannot be null"); this.dSource = dSource; } @Override protected DataSource getDataSource() throws NamingException { - //logger.debug("Getting dataSource"); + // logger.debug("Getting dataSource"); return this.dSource; } } diff --git a/src/org/molgenis/framework/db/jpa/AbstractJpaMapper.java b/src/org/molgenis/framework/db/jpa/AbstractJpaMapper.java index 66223d11a..52e4a24c8 100644 --- a/src/org/molgenis/framework/db/jpa/AbstractJpaMapper.java +++ b/src/org/molgenis/framework/db/jpa/AbstractJpaMapper.java @@ -31,7 +31,7 @@ public AbstractJpaMapper(Database database) @Override public abstract E create(); - + @SuppressWarnings("unchecked") public Class getEntityClass() { @@ -45,104 +45,99 @@ public Class getEntityClass() public abstract FieldType getFieldType(String field); @Override - public abstract void resolveForeignKeys(List enteties) - throws ParseException, DatabaseException; + public abstract void resolveForeignKeys(List enteties) throws ParseException, DatabaseException; @Override - public abstract String createFindSqlInclRules(QueryRule[] rules) - throws DatabaseException; - - private final static Logger logger = Logger - .getLogger(AbstractJpaMapper.class); - - public int count(QueryRule ...rules) throws DatabaseException + public abstract String createFindSqlInclRules(QueryRule[] rules) throws DatabaseException; + + private final static Logger logger = Logger.getLogger(AbstractJpaMapper.class); + + public int count(QueryRule... rules) throws DatabaseException { - TypedQuery query = JPAQueryGeneratorUtil.createCount(getDatabase(), - getEntityClass(), this, getDatabase().getEntityManager(), rules); + TypedQuery query = JPAQueryGeneratorUtil.createCount(getDatabase(), getEntityClass(), this, getDatabase() + .getEntityManager(), rules); Long result = query.getSingleResult(); return result.intValue(); } - + @Override public List find(QueryRule... rules) throws DatabaseException { - TypedQuery query = JPAQueryGeneratorUtil.createQuery(this.getDatabase(), - getEntityClass(), this, getDatabase().getEntityManager(), rules); + TypedQuery query = JPAQueryGeneratorUtil.createQuery(this.getDatabase(), getEntityClass(), this, + getDatabase().getEntityManager(), rules); return query.getResultList(); } - + public E findById(Object id) { return getDatabase().getEntityManager().find(getEntityClass(), id); } - + @Override public List findByExample(E example) { return JpaFrameworkFactory.createFramework().findByExample(getEntityManager(), example); } - + public EntityManager getEntityManager() { return getDatabase().getEntityManager(); } - + @Override - public void storeMrefs(List entities) - throws DatabaseException, IOException, ParseException + public void storeMrefs(List entities) throws DatabaseException, IOException, ParseException { - //automatically done by JPA + // automatically done by JPA } @Override - public void removeMrefs(List entities) throws SQLException, - IOException, DatabaseException, ParseException + public void removeMrefs(List entities) throws SQLException, IOException, DatabaseException, ParseException { - //automatically done by JPA + // automatically done by JPA } - + @SuppressWarnings("unused") @Override - public void find(TupleWriter writer, List fieldsToExport, QueryRule[] rules) - throws DatabaseException + public void find(TupleWriter writer, List fieldsToExport, QueryRule[] rules) throws DatabaseException { - //TODO: implement with scrolling results set + // TODO: implement with scrolling results set try { - //streaming result!!!! - ScrollableResults rs = null; //getEntityManager().getNamedQuery("GetCustomers").scroll(ScrollMode.FORWARD_ONLY); - //ResultSetTuple rs = new ResultSetTuple(executeSelect(rules)); - - /*logger.debug("executeSelect(rules)"); - for(QueryRule q : rules){ - logger.debug("rule: " + q.toString()); - }*/ + // streaming result!!!! + ScrollableResults rs = null; // getEntityManager().getNamedQuery("GetCustomers").scroll(ScrollMode.FORWARD_ONLY); + // ResultSetTuple rs = new ResultSetTuple(executeSelect(rules)); + + /* + * logger.debug("executeSelect(rules)"); for(QueryRule q : rules){ + * logger.debug("rule: " + q.toString()); } + */ // transform result set in writer - E entity = create(); - List fields = fieldsToExport; - if(fieldsToExport == null) fields = entity.getFields(); - + E entity = create(); + List fields = fieldsToExport; + if (fieldsToExport == null) fields = entity.getFields(); + writer.setHeaders(fields); writer.writeHeader(); int i = 0; - - if(true) throw new UnsupportedOperationException("needs fixing!"); -// while (rs.next()) -// { -// entity = (E) rs.get(0); -// writer.writeRow(entity); -// i++; -// -// } + + if (true) throw new UnsupportedOperationException("needs fixing!"); + // while (rs.next()) + // { + // entity = (E) rs.get(0); + // writer.writeRow(entity); + // i++; + // + // } // write remaining // load mrefs - logger.debug("*** mapMrefs -> LEFTOVERS"); //program does NOT crash after this + logger.debug("*** mapMrefs -> LEFTOVERS"); // program does NOT crash + // after this rs.close(); writer.close(); - - logger.debug("find(" + create().getClass().getSimpleName() + ", TupleWriter, " + - Arrays.asList(rules) + "): wrote " + i + " lines."); + + logger.debug("find(" + create().getClass().getSimpleName() + ", TupleWriter, " + Arrays.asList(rules) + + "): wrote " + i + " lines."); } catch (Exception e) { diff --git a/src/org/molgenis/framework/db/jpa/HibernateImp.java b/src/org/molgenis/framework/db/jpa/HibernateImp.java index 30d023e2f..cee2b9f19 100644 --- a/src/org/molgenis/framework/db/jpa/HibernateImp.java +++ b/src/org/molgenis/framework/db/jpa/HibernateImp.java @@ -18,52 +18,54 @@ /** * @author joris lops */ -class HibernateImp implements JpaFramework { +class HibernateImp implements JpaFramework +{ - @Override - public List findByExample(EntityManager em, E example) { - Session session = (Session) em.getDelegate(); - Example customerExample = Example.create(example).excludeZeroes(); - Criteria criteria = session.createCriteria(example.getClass()).add( - customerExample); - @SuppressWarnings("unchecked") - List list = criteria.list(); - return list; - } + @Override + public List findByExample(EntityManager em, E example) + { + Session session = (Session) em.getDelegate(); + Example customerExample = Example.create(example).excludeZeroes(); + Criteria criteria = session.createCriteria(example.getClass()).add(customerExample); + @SuppressWarnings("unchecked") + List list = criteria.list(); + return list; + } - @Override - public void createTables(final String persistenceUnitName, final Map configOverwrites) { - final Ejb3Configuration cfg = new Ejb3Configuration(); - cfg.configure(persistenceUnitName, configOverwrites); - final SchemaExport schemaExport = new SchemaExport( - cfg.getHibernateConfiguration()); - schemaExport.setOutputFile("schema.sql"); - schemaExport.create(true, true); - } + @Override + public void createTables(final String persistenceUnitName, final Map configOverwrites) + { + final Ejb3Configuration cfg = new Ejb3Configuration(); + cfg.configure(persistenceUnitName, configOverwrites); + final SchemaExport schemaExport = new SchemaExport(cfg.getHibernateConfiguration()); + schemaExport.setOutputFile("schema.sql"); + schemaExport.create(true, true); + } - @Override - public void updateTables(String persistenceUnitName, final Map configOverwrites) { - final Ejb3Configuration cfg = new Ejb3Configuration(); - cfg.configure(persistenceUnitName, configOverwrites); - final SchemaUpdate schemaUpdate = new SchemaUpdate( - cfg.getHibernateConfiguration()); - schemaUpdate.setOutputFile("schema.sql"); - schemaUpdate.execute(true, true); - } + @Override + public void updateTables(String persistenceUnitName, final Map configOverwrites) + { + final Ejb3Configuration cfg = new Ejb3Configuration(); + cfg.configure(persistenceUnitName, configOverwrites); + final SchemaUpdate schemaUpdate = new SchemaUpdate(cfg.getHibernateConfiguration()); + schemaUpdate.setOutputFile("schema.sql"); + schemaUpdate.execute(true, true); + } - @Override - public void dropTables(String persistenceUnitName, final Map configOverwrites) { - final Ejb3Configuration cfg = new Ejb3Configuration(); - cfg.configure(persistenceUnitName, configOverwrites); - final SchemaExport schemaExport = new SchemaExport( - cfg.getHibernateConfiguration()); - schemaExport.setOutputFile("schema.sql"); - schemaExport.drop(true, true); - } + @Override + public void dropTables(String persistenceUnitName, final Map configOverwrites) + { + final Ejb3Configuration cfg = new Ejb3Configuration(); + cfg.configure(persistenceUnitName, configOverwrites); + final SchemaExport schemaExport = new SchemaExport(cfg.getHibernateConfiguration()); + schemaExport.setOutputFile("schema.sql"); + schemaExport.drop(true, true); + } - @SuppressWarnings("deprecation") + @SuppressWarnings("deprecation") @Override - public Connection getConnection(EntityManager em) { - return ((HibernateEntityManager) em).getSession().connection(); - } + public Connection getConnection(EntityManager em) + { + return ((HibernateEntityManager) em).getSession().connection(); + } } diff --git a/src/org/molgenis/framework/db/jpa/JPAQueryGeneratorUtil.java b/src/org/molgenis/framework/db/jpa/JPAQueryGeneratorUtil.java index 350112026..7eb8269b3 100644 --- a/src/org/molgenis/framework/db/jpa/JPAQueryGeneratorUtil.java +++ b/src/org/molgenis/framework/db/jpa/JPAQueryGeneratorUtil.java @@ -36,18 +36,15 @@ public class JPAQueryGeneratorUtil { - public static TypedQuery createQuery( - Database db, Class inputClass, Mapper mapper, + public static TypedQuery createQuery(Database db, Class inputClass, Mapper mapper, EntityManager em, QueryRule... rules) throws DatabaseException { return createQuery(db, inputClass, inputClass, mapper, em, rules); } @SuppressWarnings("unchecked") - public static TypedQuery createQuery( - Database db, Class inputClass, Class outputClass, - Mapper mapper, EntityManager em, QueryRule... rules) - throws DatabaseException + public static TypedQuery createQuery(Database db, Class inputClass, + Class outputClass, Mapper mapper, EntityManager em, QueryRule... rules) throws DatabaseException { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(outputClass); @@ -64,8 +61,7 @@ public static TypedQuery createQuery( int[] limitOffset = new int[2]; Arrays.fill(limitOffset, -1); - Predicate wherePredicate = createWhere(db, mapper, em, root, cq, cb, - limitOffset, rules); + Predicate wherePredicate = createWhere(db, mapper, em, root, cq, cb, limitOffset, rules); if (wherePredicate != null) { cq.where(wherePredicate); @@ -82,34 +78,33 @@ public static TypedQuery createQuery( return query; } - public static TypedQuery createCount(Database db, - Class entityClass, AbstractJpaMapper abstractJpaMapper, EntityManager em, - QueryRule... rules) throws DatabaseException + public static TypedQuery createCount(Database db, Class entityClass, + AbstractJpaMapper abstractJpaMapper, EntityManager em, QueryRule... rules) throws DatabaseException { - //remove any 'offset' from the query as this screws up count + // remove any 'offset' from the query as this screws up count List limitLess = new ArrayList(); - for(QueryRule r: rules) + for (QueryRule r : rules) { - if(!Operator.OFFSET.equals(r.getOperator())) limitLess.add(r); + if (!Operator.OFFSET.equals(r.getOperator())) limitLess.add(r); } - - return createQuery(db, entityClass, Long.class, abstractJpaMapper, em, limitLess.toArray(new QueryRule[limitLess.size()])); + + return createQuery(db, entityClass, Long.class, abstractJpaMapper, em, + limitLess.toArray(new QueryRule[limitLess.size()])); } - private static Predicate createWhere(Database db, - Mapper mapper, EntityManager em, Root root, CriteriaQuery cq, - CriteriaBuilder cb, int[] limitOffset, QueryRule... rul) + private static Predicate createWhere(Database db, Mapper mapper, EntityManager em, + Root root, CriteriaQuery cq, CriteriaBuilder cb, int[] limitOffset, QueryRule... rul) throws DatabaseException { Map> joinHash = new HashMap>(); return _createWhere(db, mapper, em, root, cq, cb, limitOffset, joinHash, rul); } - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static Predicate _createWhere(Database db, - Mapper mapper, EntityManager em, Root root, CriteriaQuery cq, - CriteriaBuilder cb, int[] limitOffset, Map> joinHash, QueryRule... rul) - throws DatabaseException + @SuppressWarnings( + { "unchecked", "rawtypes" }) + private static Predicate _createWhere(Database db, Mapper mapper, EntityManager em, + Root root, CriteriaQuery cq, CriteriaBuilder cb, int[] limitOffset, + Map> joinHash, QueryRule... rul) throws DatabaseException { List rules = Arrays.asList(rul); @@ -117,8 +112,7 @@ private static Predicate _createWhere(Database db, List orders = new ArrayList(); QueryRule prevRule = null; - - + forLoop: for (int i = 0; i < rules.size(); ++i) { QueryRule rule = rules.get(i); @@ -127,20 +121,17 @@ private static Predicate _createWhere(Database db, rule.setField(mapper.getTableFieldName(rule.getField())); Operator operator = rule.getOperator(); - if (operator == Operator.SORTASC - || operator == Operator.SORTDESC) + if (operator == Operator.SORTASC || operator == Operator.SORTDESC) { - rule.setField(mapper.getTableFieldName(rule.getValue() - .toString())); + rule.setField(mapper.getTableFieldName(rule.getValue().toString())); } String attributeName = rule.getJpaAttribute(); Predicate predicate = null; - Expression expression = _addJoin(rule, root, joinHash); - + Expression lhs = null; if (expression != null) { @@ -151,12 +142,11 @@ else if (attributeName != null) lhs = root.get(attributeName); } Object rhs = rule.getValue(); - + switch (operator) { case LAST: - throw new UnsupportedOperationException( - "Not supported yet."); + throw new UnsupportedOperationException("Not supported yet."); case SORTASC: orders.add(cb.asc(lhs)); break; @@ -177,15 +167,11 @@ else if (attributeName != null) { try { - predicate = cb.equal( - root.get(attributeName), - rule.getValue()); + predicate = cb.equal(root.get(attributeName), rule.getValue()); } catch (Exception ex) { - LogFactory.getLog( - JPAQueryGeneratorUtil.class - .getName()).error(ex); + LogFactory.getLog(JPAQueryGeneratorUtil.class.getName()).error(ex); } } else @@ -194,22 +180,16 @@ else if (attributeName != null) { // it's a xref attribute which is joined // to root - if (attributeName.contains(".") || - root.get(attributeName) - .getJavaType().getName() - .equals("java.util.List") - || root.get(attributeName) - .getJavaType() - .newInstance() instanceof Entity) + if (attributeName.contains(".") + || root.get(attributeName).getJavaType().getName() + .equals("java.util.List") + || root.get(attributeName).getJavaType().newInstance() instanceof Entity) { predicate = cb.equal(lhs, rhs); } else { // normal attribute -// predicate = cb.equal( -// root.get(attributeName), -// rule.getValue()); - predicate = cb.equal(lhs, rhs); + predicate = cb.equal(lhs, rhs); } } catch (InstantiationException ex) @@ -217,80 +197,56 @@ else if (attributeName != null) // this is a hack, newInstance can not // be called on inmutable object // like Integer -// predicate = cb.equal( -// root.get(attributeName), -// rule.getValue()); - predicate = cb.equal(lhs, rhs); + predicate = cb.equal(lhs, rhs); } catch (IllegalAccessException ex) { - LogFactory.getLog( - JPAQueryGeneratorUtil.class - .getName()).error(ex); + LogFactory.getLog(JPAQueryGeneratorUtil.class.getName()).error(ex); throw new DatabaseException(ex); } } break; case NOT: -// predicate = cb.notEqual( -// root.get(attributeName), -// rule.getValue()); - predicate = cb.notEqual(lhs, rhs); + predicate = cb.notEqual(lhs, rhs); break; case LIKE: -// predicate = cb.like( -// root.get(attributeName) -// .as(String.class), -// (String) rule.getValue()); - predicate = cb.like(lhs.as(String.class), (String) rhs); + if (lhs.getJavaType().getSimpleName().equals("String")) + { + predicate = cb.like(lhs.as(String.class), (String) rhs); + } + else + { + // TODO: What to do here? + } break; case LESS: -// predicate = cb.lessThan( -// (Expression) root.get(attributeName), -// (Comparable) rule.getValue()); predicate = cb.lessThan((Expression) lhs, (Comparable) rhs); break; case GREATER: -// predicate = cb.greaterThan( -// (Expression) root.get(attributeName), -// (Comparable) rule.getValue()); predicate = cb.greaterThan((Expression) lhs, (Comparable) rhs); break; case LESS_EQUAL: -// predicate = cb.lessThanOrEqualTo( -// (Expression) root.get(attributeName), -// (Comparable) rule.getValue()); predicate = cb.lessThanOrEqualTo((Expression) lhs, (Comparable) rhs); break; case GREATER_EQUAL: -// predicate = cb.greaterThanOrEqualTo( -// (Expression) root.get(attributeName), -// (Comparable) rule.getValue()); predicate = cb.greaterThanOrEqualTo((Expression) lhs, (Comparable) rhs); break; case NESTED: QueryRule[] nestedrules = rule.getNestedRules(); - _createWhere(db, mapper, em, root, cq, cb, - new int[2], joinHash, nestedrules); + predicate = _createWhere(db, mapper, em, root, cq, cb, new int[2], joinHash, + nestedrules); break; case SUBQUERY: SubQueryRule sqr = (SubQueryRule) rule; - Subquery sq = cq.subquery(sqr - .getSubQueryResultClass()); - Root sqFrom = sq.from(sqr - .getSubQueryFromClass()); + Subquery sq = cq.subquery(sqr.getSubQueryResultClass()); + Root sqFrom = sq.from(sqr.getSubQueryFromClass()); - Mapper sqMapper = db.getMapper(sqr - .getSubQueryFromClass().getName()); + Mapper sqMapper = db.getMapper(sqr.getSubQueryFromClass().getName()); - Predicate where = _createWhere(db, sqMapper, em, - sqFrom, cq, cb, new int[2], joinHash, + Predicate where = _createWhere(db, sqMapper, em, sqFrom, cq, cb, new int[2], joinHash, (QueryRule[]) sqr.getValue()); - sq.select( - sqFrom.get(sqr - .getSubQueryAttributeJpa())) - .where(where); + sq.select(sqFrom.get(sqr.getSubQueryAttributeJpa())).where(where); // the operator of subquery should be handled in // the right way such that no code duplication @@ -299,12 +255,9 @@ else if (attributeName != null) // come) String fieldForSubQuery = sqr.getJpaAttribute(); - if (sqr.getSubQueryOperator().equals( - Operator.IN)) + if (sqr.getSubQueryOperator().equals(Operator.IN)) { - predicate = cb.in( - root.get(fieldForSubQuery)).value( - sq); + predicate = cb.in(root.get(fieldForSubQuery)).value(sq); } else { @@ -317,15 +270,12 @@ else if (attributeName != null) Object[] values = new Object[0]; if (rule.getValue() instanceof List) { - values = ((List) rule.getValue()) - .toArray(); + values = ((List) rule.getValue()).toArray(); } else { values = (Object[]) rule.getValue(); } -// Class attrClass = root.get(attributeName) -// .getJavaType(); Class attrClass = null; if (attributeName.contains(".")) { @@ -339,15 +289,10 @@ else if (attributeName != null) // AbstractEntity) if (AbstractEntity.class.isAssignableFrom(attrClass)) { -// Field idField = getIdField(attrClass); -// predicate = root.get(attributeName) -// .get(idField.getName()).in(values); predicate = root.get(attributeName).in(values); } else { -// predicate = root.get(attributeName).in( -// values); predicate = lhs.in(values); } @@ -358,28 +303,20 @@ else if (attributeName != null) { if (predicate != null) { - if (prevRule != null - && prevRule.getOperator().equals( - Operator.OR)) + if (prevRule != null && prevRule.getOperator().equals(Operator.OR)) { - List restOfQueryRules = rules - .subList(i, rules.size()); - Predicate rightsPred = _createWhere(db, - mapper, em, root, cq, cb, - limitOffset, joinHash, - restOfQueryRules - .toArray(new QueryRule[1])); + List restOfQueryRules = rules.subList(i, rules.size()); + Predicate rightsPred = _createWhere(db, mapper, em, root, cq, cb, limitOffset, + joinHash, restOfQueryRules.toArray(new QueryRule[1])); if (rightsPred != null) { - whereClause = cb.or(whereClause, - rightsPred); + whereClause = cb.or(whereClause, rightsPred); } break forLoop; } else { - whereClause = cb - .and(whereClause, predicate); + whereClause = cb.and(whereClause, predicate); } } } @@ -401,62 +338,48 @@ else if (attributeName != null) // } return whereClause; } - - private static Expression _addJoin(QueryRule rule, Root root, Map> joinHash) throws DatabaseException + + private static Expression _addJoin(QueryRule rule, Root root, + Map> joinHash) throws DatabaseException { try { String attributeName = rule.getJpaAttribute(); - if (attributeName == null) - return null; - - if (rule.getValue() instanceof Entity) - return root.get(attributeName); - - if (attributeName.contains(".") || - root.get(attributeName) - .getJavaType().getName() - .equals("java.util.List") - || root.get(attributeName) - .getJavaType() - .newInstance() instanceof Entity) + if (attributeName == null) return null; + + if (rule.getValue() instanceof Entity) return root.get(attributeName); + + if (attributeName.contains(".") || root.get(attributeName).getJavaType().getName().equals("java.util.List") + || root.get(attributeName).getJavaType().newInstance() instanceof Entity) { - Entity entity = root.getJavaType() - .newInstance(); - String xrefAttribtename = entity - .getXrefIdFieldName(attributeName); - + Entity entity = root.getJavaType().newInstance(); + String xrefAttribtename = entity.getXrefIdFieldName(attributeName); + String[] attributeNameSplit = StringUtils.split(attributeName, "."); - if (attributeNameSplit.length == 0) { + if (attributeNameSplit.length == 0) + { return null; } - else if(attributeNameSplit.length > 1) { - attributeName = attributeNameSplit[0]; + else if (attributeNameSplit.length > 1) + { + attributeName = attributeNameSplit[0]; xrefAttribtename = attributeNameSplit[1]; } - + Join join = null; - // Set> joins = root.getJoins(); - // for (Join tmp : joins.toArray(new Join[0])) - // { - // if (tmp.getAttribute().getName().equals(attributeName)) - // { - // join = tmp; - // } - // } - if(joinHash.containsKey(attributeName)) { + if (joinHash.containsKey(attributeName)) + { join = joinHash.get(attributeName); - } else { - join = root.join( - attributeName, - JoinType.LEFT); + } + else + { + join = root.join(attributeName, JoinType.LEFT); joinHash.put(attributeName, join); } - Expression attribute = join - .get(xrefAttribtename); - + Expression attribute = join.get(xrefAttribtename); + return attribute; } } @@ -468,11 +391,9 @@ else if(attributeNameSplit.length > 1) { } catch (IllegalAccessException ex) { - LogFactory.getLog( - JPAQueryGeneratorUtil.class - .getName()).error(ex); + LogFactory.getLog(JPAQueryGeneratorUtil.class.getName()).error(ex); throw new DatabaseException(ex); } return null; } -} \ No newline at end of file +} diff --git a/src/org/molgenis/framework/db/jpa/JpaDatabase.java b/src/org/molgenis/framework/db/jpa/JpaDatabase.java index 57bcbddae..714940852 100644 --- a/src/org/molgenis/framework/db/jpa/JpaDatabase.java +++ b/src/org/molgenis/framework/db/jpa/JpaDatabase.java @@ -40,17 +40,15 @@ private EMFactory(String persistenceUnit, Map configOverrides) { addEntityManagerFactory(persistenceUnit, configOverrides); } - - private static void addEntityManagerFactory(String persistenceUnitName, - Map configOverwrite) + + private static void addEntityManagerFactory(String persistenceUnitName, Map configOverwrite) { if (!emfs.containsKey(persistenceUnitName)) { EntityManagerFactory emFactory = null; if (configOverwrite != null) { - emFactory = Persistence.createEntityManagerFactory( - persistenceUnitName, configOverwrite); + emFactory = Persistence.createEntityManagerFactory(persistenceUnitName, configOverwrite); } else { @@ -70,8 +68,7 @@ public static EntityManager createEntityManager(String persistenceUnit) { addEntityManagerFactory(persistenceUnit, null); } - EntityManager result = emfs.get(persistenceUnit) - .createEntityManager(); + EntityManager result = emfs.get(persistenceUnit).createEntityManager(); return result; } @@ -85,14 +82,12 @@ public static EntityManager createEntityManager() return result; } - public static EntityManagerFactory getEntityManagerFactoryByName( - String name) + public static EntityManagerFactory getEntityManagerFactoryByName(String name) { return emfs.get(name); } - public static EntityManager createEntityManager( - String persistenceUnitName, Map configOverrides) + public static EntityManager createEntityManager(String persistenceUnitName, Map configOverrides) { if (instance == null) { @@ -102,14 +97,13 @@ public static EntityManager createEntityManager( { addEntityManagerFactory(persistenceUnitName, configOverrides); } - EntityManager result = emfs.get(persistenceUnitName) - .createEntityManager(); + EntityManager result = emfs.get(persistenceUnitName).createEntityManager(); return result; } } private final EntityManager em; - private String persistenceUnitName = "molgenis"; //default + private String persistenceUnitName = "molgenis"; // default protected JpaDatabase(String persistenceUnitName) { @@ -238,13 +232,12 @@ public List executeSQLQuery(String sqlQuery) { return em.createNativeQuery(sqlQuery).getResultList(); } - + @SuppressWarnings("unchecked") public List executeSQLQuery(String sqlQuery, Class resultClass) { return em.createNativeQuery(sqlQuery, resultClass).getResultList(); } - public String getPersistenceUnitName() { @@ -266,12 +259,12 @@ public void index() public List search(Class entityClass, String fieldList, String searchString) { - FullTextEntityManager ftem = Search.getFullTextEntityManager(this.em); - QueryBuilder qb = ftem.getSearchFactory().buildQueryBuilder().forEntity(entityClass).get(); - org.apache.lucene.search.Query query = qb.keyword().onFields(fieldList).matching(searchString).createQuery(); + FullTextEntityManager ftem = Search.getFullTextEntityManager(this.em); + QueryBuilder qb = ftem.getSearchFactory().buildQueryBuilder().forEntity(entityClass).get(); + org.apache.lucene.search.Query query = qb.keyword().onFields(fieldList).matching(searchString).createQuery(); javax.persistence.Query persistenceQuery = ftem.createFullTextQuery(query, entityClass); @SuppressWarnings("unchecked") - List result = persistenceQuery.getResultList(); + List result = persistenceQuery.getResultList(); return result; } } \ No newline at end of file diff --git a/src/org/molgenis/framework/db/jpa/JpaFramework.java b/src/org/molgenis/framework/db/jpa/JpaFramework.java index a733abcac..88f4be19c 100644 --- a/src/org/molgenis/framework/db/jpa/JpaFramework.java +++ b/src/org/molgenis/framework/db/jpa/JpaFramework.java @@ -13,34 +13,35 @@ import org.molgenis.util.Entity; /** - * + * * @author joris lops */ -public interface JpaFramework { - +public interface JpaFramework +{ + public List findByExample(EntityManager em, E example); - + /** * Create tables based on annotations. * * @param persistenceUnitName */ - public void createTables(final String persistenceUnitName, final Map configOverwrites); - + public void createTables(final String persistenceUnitName, final Map configOverwrites); + /** * Update tables based on annotations. * * @param persistenceUnitName */ - public void updateTables(final String persistenceUnitName, final Map configOverwrites); - - /** - * Drop tables based on annotations - * - * @param persistenceUnitName - */ - public void dropTables(final String persistenceUnitName, final Map configOverwrites); - - @Deprecated - public Connection getConnection(EntityManager em); + public void updateTables(final String persistenceUnitName, final Map configOverwrites); + + /** + * Drop tables based on annotations + * + * @param persistenceUnitName + */ + public void dropTables(final String persistenceUnitName, final Map configOverwrites); + + @Deprecated + public Connection getConnection(EntityManager em); } diff --git a/src/org/molgenis/framework/db/jpa/JpaFrameworkFactory.java b/src/org/molgenis/framework/db/jpa/JpaFrameworkFactory.java index d8e439e5b..8d1fe35e1 100644 --- a/src/org/molgenis/framework/db/jpa/JpaFrameworkFactory.java +++ b/src/org/molgenis/framework/db/jpa/JpaFrameworkFactory.java @@ -1,11 +1,13 @@ package org.molgenis.framework.db.jpa; /** - * + * * @author joris lops */ -public class JpaFrameworkFactory { - public static JpaFramework createFramework() { - return new HibernateImp(); - } +public class JpaFrameworkFactory +{ + public static JpaFramework createFramework() + { + return new HibernateImp(); + } } diff --git a/src/org/molgenis/framework/db/jpa/JpaUtil.java b/src/org/molgenis/framework/db/jpa/JpaUtil.java index 547ec200f..2fa4555b9 100644 --- a/src/org/molgenis/framework/db/jpa/JpaUtil.java +++ b/src/org/molgenis/framework/db/jpa/JpaUtil.java @@ -6,8 +6,9 @@ import java.util.Map; import javax.persistence.EntityManager; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.molgenis.framework.db.Database; @@ -28,14 +29,14 @@ public static void createTables(final Database db, final boolean clearEm, final JpaUtil.createTables((JpaDatabase) db, clearEm, configOverwrites); } - public static void createTables(final JpaDatabase db, final boolean clearEm, final Map configOverwrites) + public static void createTables(final JpaDatabase db, final boolean clearEm, + final Map configOverwrites) { if (clearEm) { db.getEntityManager().clear(); } - JpaFrameworkFactory.createFramework().createTables( - db.getPersistenceUnitName(), configOverwrites); + JpaFrameworkFactory.createFramework().createTables(db.getPersistenceUnitName(), configOverwrites); } public static void updateTables(final Database db, final Map configOverwrites) @@ -48,14 +49,14 @@ public static void updateTables(final Database db, final boolean clearEm, final JpaUtil.updateTables((JpaDatabase) db, clearEm, configOverwrites); } - public static void updateTables(final JpaDatabase db, final boolean clearEm, final Map configOverwrites) + public static void updateTables(final JpaDatabase db, final boolean clearEm, + final Map configOverwrites) { if (clearEm) { db.getEntityManager().clear(); } - JpaFrameworkFactory.createFramework().updateTables( - db.getPersistenceUnitName(), configOverwrites); + JpaFrameworkFactory.createFramework().updateTables(db.getPersistenceUnitName(), configOverwrites); } public static void dropAndCreateTables(final Database db, final Map configOverwrites) @@ -63,21 +64,21 @@ public static void dropAndCreateTables(final Database db, final Map configOverwrites) + public static void dropAndCreateTables(final Database db, final boolean clear, + final Map configOverwrites) { JpaUtil.dropAndCreateTables((JpaDatabase) db, clear, configOverwrites); } - public static void dropAndCreateTables(final JpaDatabase db, final boolean clear, final Map configOverwrites) + public static void dropAndCreateTables(final JpaDatabase db, final boolean clear, + final Map configOverwrites) { if (clear) { db.getEntityManager().clear(); } - JpaFrameworkFactory.createFramework().dropTables( - db.getPersistenceUnitName(), configOverwrites); - JpaFrameworkFactory.createFramework().createTables( - db.getPersistenceUnitName(), configOverwrites); + JpaFrameworkFactory.createFramework().dropTables(db.getPersistenceUnitName(), configOverwrites); + JpaFrameworkFactory.createFramework().createTables(db.getPersistenceUnitName(), configOverwrites); } public static void dropTables(Database db, final Map configOverwrites) @@ -112,12 +113,10 @@ public static void executeSQLScript(final File file, final Database db) throw new IllegalArgumentException("!(db instanceof JpaDatabase)"); } - FileReader fr = null; BufferedReader br = null; try { - fr = new FileReader(file); - br = new BufferedReader(fr); + br = new BufferedReader(new FileReader(file)); EntityManager em = db.getEntityManager(); em.getTransaction().begin(); @@ -129,21 +128,26 @@ public static void executeSQLScript(final File file, final Database db) continue; } int result = -1; - try { - result = em.createNativeQuery(sql).executeUpdate(); - } catch (Exception ex) { - logger.error(String.format("Error executing '%s'\n %s", sql, - ex.getMessage())); + try + { + result = em.createNativeQuery(sql).executeUpdate(); + } + catch (Exception ex) + { + logger.error(String.format("Error executing '%s'\n %s", sql, ex.getMessage())); throw ex; } logger.info(String.format("Got result %d from '%s'\n", result, sql)); } em.getTransaction().commit(); - fr.close(); } catch (Exception e) { HandleException.handle(e, logger); } + finally + { + IOUtils.closeQuietly(br); + } } -} +} \ No newline at end of file diff --git a/src/org/molgenis/framework/db/paging/AbstractPager.java b/src/org/molgenis/framework/db/paging/AbstractPager.java index 8b049f8dd..9c93c9220 100644 --- a/src/org/molgenis/framework/db/paging/AbstractPager.java +++ b/src/org/molgenis/framework/db/paging/AbstractPager.java @@ -29,7 +29,8 @@ protected enum State } /** Logger */ - //private Logger logger = Logger.getLogger(this.getClass().getSimpleName()); + // private Logger logger = + // Logger.getLogger(this.getClass().getSimpleName()); /** Class of this pager */ private Class entityClass; @@ -57,14 +58,15 @@ protected enum State /** rules */ private List filters = new ArrayList(); - + /** Logger **/ private final static transient Logger logger = Logger.getLogger(AbstractPager.class.getSimpleName()); /** - * @param entityClass definition of an entity + * @param entityClass + * definition of an entity * @param defaultOrderByField - * name of field that will be used to order database entities by. + * name of field that will be used to order database entities by. * @throws DatabaseException */ public AbstractPager(Class entityClass, String defaultOrderByField) @@ -74,8 +76,8 @@ public AbstractPager(Class entityClass, String defaultOrderByField) this.entityClass = entityClass; this.orderByField = defaultOrderByField; this.defaultOrderByField = defaultOrderByField; - - logger.debug("created for "+entityClass.getCanonicalName() +", ordered by "+defaultOrderByField ); + + logger.debug("created for " + entityClass.getCanonicalName() + ", ordered by " + defaultOrderByField); } /** cache of current page */ @@ -87,46 +89,45 @@ public int getCount(Database db) throws DatabaseException this.refresh(db); return count; } - + @Override public int getCount() { return count; } - - + @Override public List getPage(Database db) throws DatabaseException { this.refresh(db); return page; } - + @Override public List first(Database db) throws DatabaseException { pagingState = State.FIRST; - logger.debug("go to first "+this.getLimit()); + logger.debug("go to first " + this.getLimit()); return this.getPage(db); } @Override public List prev(Database db) throws DatabaseException { - //relative, so need to refresh first + // relative, so need to refresh first this.refresh(db); pagingState = State.PREV; - logger.debug("go to previous "+this.getLimit()); + logger.debug("go to previous " + this.getLimit()); return this.getPage(db); } @Override public List next(Database db) throws DatabaseException { - //relative, so need to refresh first + // relative, so need to refresh first this.refresh(db); pagingState = State.NEXT; - logger.debug("go to next "+this.getLimit()); + logger.debug("go to next " + this.getLimit()); return this.getPage(db); } @@ -134,11 +135,11 @@ public List next(Database db) throws DatabaseException public List last(Database db) throws DatabaseException { pagingState = State.LAST; - logger.debug("go to last "+this.getLimit()); + logger.debug("go to last " + this.getLimit()); return this.getPage(db); } - @Override + @Override public int getLimit() { return limit; @@ -147,13 +148,12 @@ public int getLimit() @Override public void setLimit(int limit) throws DatabaseException { - //FIXME: need safety break! - if (limit <= 0) - throw new IllegalArgumentException("limit must be a positive number"); - if(this.limit != limit) + // FIXME: need safety break! + if (limit <= 0) throw new IllegalArgumentException("limit must be a positive number"); + if (this.limit != limit) { this.limit = limit; - logger.debug("set limit to "+this.getLimit()); + logger.debug("set limit to " + this.getLimit()); this.pagingState = State.REFRESH; } } @@ -165,14 +165,13 @@ public String getOrderByField() } @Override - public void setOrderByField( String orderByField ) throws DatabaseException + public void setOrderByField(String orderByField) throws DatabaseException { - if(orderByField == null || orderByField.equals("")) - throw new DatabaseException("orderByField cannot be null"); - - //pagingState = State.FIRST; + if (orderByField == null || orderByField.equals("")) throw new DatabaseException("orderByField cannot be null"); + + // pagingState = State.FIRST; this.orderByField = orderByField; - logger.debug("set order by field to '"+orderByField +"'"); + logger.debug("set order by field to '" + orderByField + "'"); } @Override @@ -184,20 +183,20 @@ public Operator getOrderByOperator() @Override public void setOrderByOperator(Operator orderByOperator) throws DatabaseException { - if (!orderByOperator.equals(Operator.SORTASC) && !orderByOperator.equals(Operator.SORTDESC)) - throw new IllegalArgumentException("orderByOperator cannot be " + orderByOperator); + if (!orderByOperator.equals(Operator.SORTASC) && !orderByOperator.equals(Operator.SORTDESC)) throw new IllegalArgumentException( + "orderByOperator cannot be " + orderByOperator); this.orderByOperator = orderByOperator; - logger.debug("set order by operator to '"+orderByOperator +"'"); + logger.debug("set order by operator to '" + orderByOperator + "'"); } - + @Override public void resetOrderBy() throws DatabaseException { this.setOrderByField(this.defaultOrderByField); this.setOrderByOperator(Operator.SORTASC); - //pagingState = State.FIRST; - logger.debug("reset order by to default: field '"+orderByField +"', operator '"+orderByOperator +"'"); + // pagingState = State.FIRST; + logger.debug("reset order by to default: field '" + orderByField + "', operator '" + orderByOperator + "'"); } @Override @@ -205,12 +204,11 @@ public int getOffset() { return offset; } - + @Override public void setDirty(boolean dirty) { - if(dirty) - this.pagingState = State.REFRESH; + if (dirty) this.pagingState = State.REFRESH; } @Override @@ -218,20 +216,19 @@ public void setOffset(int offset) { this.offset = offset; this.pagingState = State.REFRESH; - logger.debug("changed offset to: "+offset); + logger.debug("changed offset to: " + offset); // FIXME what are the consequences for keybased??? } @Override public void addFilter(QueryRule filter) throws DatabaseException { - if (filter == null) - throw new DatabaseException("cannot add null filter"); + if (filter == null) throw new DatabaseException("cannot add null filter"); filters.add(filter); - //pagingState = State.FIRST; - //FIXME: would be great if we kept the original object!!! - logger.debug("added filter '"+filter+"'."); + // pagingState = State.FIRST; + // FIXME: would be great if we kept the original object!!! + logger.debug("added filter '" + filter + "'."); } @Override @@ -243,19 +240,19 @@ public QueryRule[] getFilters() @Override public void removeFilter(int index) throws DatabaseException { - logger.debug("removed filter: "+filters.get(index)); + logger.debug("removed filter: " + filters.get(index)); filters.remove(index); - //pagingState = State.FIRST; + // pagingState = State.FIRST; } @Override public void resetFilters() { filters = new ArrayList(); - //pagingState = State.FIRST; + // pagingState = State.FIRST; } -//PROTECTED HELPERS + // PROTECTED HELPERS protected void reloadCount(Database db, QueryRule... rules) throws DatabaseException { count = db.count(entityClass, rules); diff --git a/src/org/molgenis/framework/db/paging/DatabasePager.java b/src/org/molgenis/framework/db/paging/DatabasePager.java index 0e387ea7a..0798d5ac6 100644 --- a/src/org/molgenis/framework/db/paging/DatabasePager.java +++ b/src/org/molgenis/framework/db/paging/DatabasePager.java @@ -14,12 +14,13 @@ *

* Very usefull if one doesn't want to retrieve all data at once into memory. * Instead, one can just iterate through the data while leaving the bulk of data - * savely and efficiently on disk. The DatabasePager takes care - * of (re)querying the Database. + * savely and efficiently on disk. The DatabasePager takes care of (re)querying + * the Database. *

* TODO: add a method to go to a certain page. * - * @param the specific entity type to be paged. + * @param + * the specific entity type to be paged. * */ public interface DatabasePager extends Serializable @@ -29,36 +30,36 @@ public interface DatabasePager extends Serializable * * @return refreshed page * @throws DatabaseException - * @throws ParseException + * @throws ParseException */ - public abstract List first(Database db) throws DatabaseException; + public List first(Database db) throws DatabaseException; /** * Go to previous page and return current page. * * @return refreshed page * @throws DatabaseException - * @throws ParseException + * @throws ParseException */ - public abstract List prev(Database db) throws DatabaseException; + public List prev(Database db) throws DatabaseException; /** * Go to next page and return current page. * * @return refreshed page * @throws DatabaseException - * @throws ParseException + * @throws ParseException */ - public abstract List next(Database db) throws DatabaseException; + public List next(Database db) throws DatabaseException; /** * Go to last page and return current page. * * @return refreshed page * @throws DatabaseException - * @throws ParseException + * @throws ParseException */ - public abstract List last(Database db) throws DatabaseException; + public List last(Database db) throws DatabaseException; /** * Refresh page, reloading dat from database db. @@ -66,15 +67,15 @@ public interface DatabasePager extends Serializable * @param db * @throws DatabaseException */ - public abstract void refresh(Database db) throws DatabaseException; + public void refresh(Database db) throws DatabaseException; /** - * Retrieve current limit, that is, the number of entities to be retrieved in one - * page. + * Retrieve current limit, that is, the number of entities to be retrieved + * in one page. * * @return current limit */ - public abstract int getLimit(); + public int getLimit(); /** * Changes the limit, that is, the number of entities to be retrieved in one @@ -83,7 +84,7 @@ public interface DatabasePager extends Serializable * * @throws DatabaseException */ - public abstract void setLimit( int limit ) throws DatabaseException; + public void setLimit(int limit) throws DatabaseException; /** * Retrieve the current offset, that is, the index of the first entity to be @@ -91,7 +92,7 @@ public interface DatabasePager extends Serializable * * @return current offset. */ - public abstract int getOffset(); + public int getOffset(); /** * Update the offset to match index. @@ -101,37 +102,45 @@ public interface DatabasePager extends Serializable * * @param index */ - public abstract void setOffset( int index ); + public void setOffset(int index); /** - * Retrieve the name of the field that the pages are currently ordered by. + * Retrieve the name of the field that the pages are currently ordered by. + * * @return current order by field name. */ - public abstract String getOrderByField(); + public String getOrderByField(); /** - * Set the field to order the page by. If changed, the offset will be re-set to first(). + * Set the field to order the page by. If changed, the offset will be re-set + * to first(). * - * @param orderByField name - * @throws DatabaseException + * @param orderByField + * name + * @throws DatabaseException */ - public abstract void setOrderByField( String orderByField ) throws DatabaseException; + public void setOrderByField(String orderByField) throws DatabaseException; /** - * Retrieve current order-by operator, either {@link org.molgenis.framework.db.QueryRule.Operator#SORTASC} or {@link org.molgenis.framework.db.QueryRule.Operator#SORTDESC} + * Retrieve current order-by operator, either + * {@link org.molgenis.framework.db.QueryRule.Operator#SORTASC} or + * {@link org.molgenis.framework.db.QueryRule.Operator#SORTDESC} * * @return Operator */ - public abstract Operator getOrderByOperator(); + public Operator getOrderByOperator(); /** - * Set the order-by operator, , either {@link org.molgenis.framework.db.QueryRule.Operator#SORTASC} or {@link org.molgenis.framework.db.QueryRule.Operator#SORTDESC}. If changed, the offset will be re-set to - * first() as all pages are re-ordered. + * Set the order-by operator, , either + * {@link org.molgenis.framework.db.QueryRule.Operator#SORTASC} or + * {@link org.molgenis.framework.db.QueryRule.Operator#SORTDESC}. If + * changed, the offset will be re-set to first() as all pages are + * re-ordered. * * @param orderByOperator * @throws DatabaseException */ - public abstract void setOrderByOperator( Operator orderByOperator ) throws DatabaseException; + public void setOrderByOperator(Operator orderByOperator) throws DatabaseException; /** * Add a filter to the filter list. If not yet in, the offset will be re-st @@ -140,22 +149,24 @@ public interface DatabasePager extends Serializable * @param rule * @throws DatabaseException */ - public abstract void addFilter( QueryRule rule ) throws DatabaseException; + public void addFilter(QueryRule rule) throws DatabaseException; /** - * Retrieve the current list of filters as array. The index of this filters can be used to remove - * specific filters. @see #removeFilter(int) - * @return current filters. + * Retrieve the current list of filters as array. The index of this filters + * can be used to remove specific filters. @see #removeFilter(int) + * + * @return current filters. */ - public abstract QueryRule[] getFilters(); + public QueryRule[] getFilters(); /** * Remove a specific filter by index. * - * @param index of the filter to be removed. + * @param index + * of the filter to be removed. * @throws DatabaseException */ - public abstract void removeFilter( int index ) throws DatabaseException; + public void removeFilter(int index) throws DatabaseException; /** * Reset the orderByField and orderByOperator to default as passed during @@ -163,36 +174,41 @@ public interface DatabasePager extends Serializable * * @throws DatabaseException */ - public abstract void resetOrderBy() throws DatabaseException; + public void resetOrderBy() throws DatabaseException; /** - * Reset the filters to default as passed during - * construction of this DatabasePager (effectively removing all user defined - * filters). + * Reset the filters to default as passed during construction of this + * DatabasePager (effectively removing all user defined filters). */ - public abstract void resetFilters(); + public void resetFilters(); /** * Retrieve the current number of entities in the database, after filtering. + * * @return current count of entities in the Database. - * @throws DatabaseException + * @throws DatabaseException */ - public abstract int getCount(Database db) throws DatabaseException; - + public int getCount(Database db) throws DatabaseException; + /** - * Retrieve the current number of entities in the database, without reloading the database. + * Retrieve the current number of entities in the database, without + * reloading the database. */ - public abstract int getCount(); + public int getCount(); /** - * Retrieve the current page as based on offset and limit, that is, entity[offset | offset >= 0 && offset < limit] until entity[offset+limit || count] + * Retrieve the current page as based on offset and limit, that is, + * entity[offset | offset >= 0 && offset < limit] until entity[offset+limit + * || count] + * * @return current page of entities with length getLimit(). - * @throws DatabaseException + * @throws DatabaseException */ - public abstract List getPage(Database db) throws DatabaseException; + public List getPage(Database db) throws DatabaseException; /** * Force reload. + * * @param dirty */ void setDirty(boolean dirty); diff --git a/src/org/molgenis/framework/db/paging/LimitOffsetPager.java b/src/org/molgenis/framework/db/paging/LimitOffsetPager.java index 65758a8a4..a4066532b 100644 --- a/src/org/molgenis/framework/db/paging/LimitOffsetPager.java +++ b/src/org/molgenis/framework/db/paging/LimitOffsetPager.java @@ -58,10 +58,10 @@ public void refresh(Database db) throws DatabaseException q.addRules(rules); try { - for(String fieldName: this.getEntityClass().newInstance().getFields()) + for (String fieldName : this.getEntityClass().newInstance().getFields()) { - if(fieldName.equals(Field.TYPE_FIELD)) - q.equals(Field.TYPE_FIELD, this.getEntityClass().getSimpleName()); + if (fieldName.equals(Field.TYPE_FIELD)) q.equals(Field.TYPE_FIELD, this.getEntityClass() + .getSimpleName()); } } catch (InstantiationException e) @@ -111,7 +111,7 @@ public void refresh(Database db) throws DatabaseException } case LAST: // set it to be the last valid offset - if (count > limit) offset = (int)Math.round(Math.floor((count - 1) / limit) * limit); + if (count > limit) offset = (int) Math.round(Math.floor((count - 1) / limit) * limit); else offset = 0; logger.debug("handled last, offset: " + offset + ", limit: " + limit + ", count: " + count); diff --git a/src/org/molgenis/framework/db/paging/PrimaryKeyPager.java b/src/org/molgenis/framework/db/paging/PrimaryKeyPager.java index 192f66603..dca8cb47a 100644 --- a/src/org/molgenis/framework/db/paging/PrimaryKeyPager.java +++ b/src/org/molgenis/framework/db/paging/PrimaryKeyPager.java @@ -28,20 +28,22 @@ public class PrimaryKeyPager extends AbstractPager private static final long serialVersionUID = 1707494068232123242L; private static final transient Logger logger = Logger.getLogger(PrimaryKeyPager.class.getSimpleName()); + /** * Constructor. * - * @param entityClass class of the entity to be paged - * @param primaryKeyField the primary key of the entity (must be unique and - * indexed) - * @throws DatabaseException + * @param entityClass + * class of the entity to be paged + * @param primaryKeyField + * the primary key of the entity (must be unique and indexed) + * @throws DatabaseException */ public PrimaryKeyPager(Class entityClass, String primaryKeyField) throws DatabaseException { - super(entityClass,primaryKeyField); + super(entityClass, primaryKeyField); this.primaryKeyField = primaryKeyField; this.setPagingState(State.FIRST); - //this.refresh(); + // this.refresh(); } /** @@ -63,49 +65,51 @@ public PrimaryKeyPager(Class entityClass, String primaryKeyField) throws Data */ public void refresh(Database db) throws DatabaseException { - //don't use getters and setters!!! these will call refresh resulting in endless loops - if (this.pagingState == State.UPTODATE) - return; - + // don't use getters and setters!!! these will call refresh resulting in + // endless loops + if (this.pagingState == State.UPTODATE) return; + // get the rules List rules = new ArrayList(); rules.addAll(Arrays.asList(this.getFilters())); - - logger.debug("refresh started with state '"+pagingState+"'"); + + logger.debug("refresh started with state '" + pagingState + "'"); reloadCount(db, rules.toArray(new QueryRule[rules.size()])); // first: add sorting of order by field - if( getOrderByField() != null || "".equals(getOrderByField()) ) + if (getOrderByField() != null || "".equals(getOrderByField())) { - logger.debug("adding order by on "+getOrderByField()); - if( getOrderByOperator().equals(Operator.SORTASC) ) - rules.add(new QueryRule(Operator.SORTASC, getOrderByField())); + logger.debug("adding order by on " + getOrderByField()); + if (getOrderByOperator().equals(Operator.SORTASC)) rules.add(new QueryRule(Operator.SORTASC, + getOrderByField())); else rules.add(new QueryRule(Operator.SORTDESC, getOrderByField())); } // second: add sorting by primary key (ensuring predictable ordering) - if( !getOrderByField().equals(primaryKeyField) ) + if (!getOrderByField().equals(primaryKeyField)) { - logger.debug("adding order by on "+primaryKeyField); - if( getOrderByOperator().equals(Operator.SORTASC) ) - rules.add(new QueryRule(Operator.SORTASC, primaryKeyField)); + logger.debug("adding order by on " + primaryKeyField); + if (getOrderByOperator().equals(Operator.SORTASC)) rules.add(new QueryRule(Operator.SORTASC, + primaryKeyField)); else rules.add(new QueryRule(Operator.SORTDESC, primaryKeyField)); } - //based on the pagingState we add additional filterings - switch( pagingState ) + // based on the pagingState we add additional filterings + switch (pagingState) { case REFRESH: - if(count > offset) + if (count > offset) { rules.add(new QueryRule(Operator.LIMIT, limit)); rules.add(new QueryRule(getOrderByField(), Operator.GREATER_EQUAL, prevOrderByThreshold)); - if( !getOrderByField().equals(primaryKeyField) )rules.add(new QueryRule(primaryKeyField, Operator.GREATER_EQUAL, prevPKeyThreshold)); - //FIXME how can we distinguish page when sort field is not unique!! - logger.debug("loaded filters for refresh. Added operator: limit="+limit+", offset="+offset); + if (!getOrderByField().equals(primaryKeyField)) rules.add(new QueryRule(primaryKeyField, + Operator.GREATER_EQUAL, prevPKeyThreshold)); + // FIXME how can we distinguish page when sort field is not + // unique!! + logger.debug("loaded filters for refresh. Added operator: limit=" + limit + ", offset=" + offset); break; } else @@ -114,41 +118,43 @@ public void refresh(Database db) throws DatabaseException pagingState = State.LAST; this.refresh(db); return; - } + } case NEXT: if (limit + offset < count) { offset = limit + offset; rules.add(new QueryRule(Operator.LIMIT, Math.min(limit, count - offset))); rules.add(new QueryRule(getOrderByField(), Operator.GREATER, nextOrderByThreshold)); - if( !getOrderByField().equals(primaryKeyField) ) rules.add(new QueryRule(primaryKeyField, Operator.GREATER, nextPKeyThreshold)); - //FIXME how can we distinguish page when sort field is not unique!! - + if (!getOrderByField().equals(primaryKeyField)) rules.add(new QueryRule(primaryKeyField, + Operator.GREATER, nextPKeyThreshold)); + // FIXME how can we distinguish page when sort field is not + // unique!! + // get first from next threshold (exclusive) - logger.debug("loaded filters for next. Added operator: "+getOrderByField()+" > " + nextOrderByThreshold+". Offset is: "+offset+") and "+primaryKeyField+" greater than: " + nextPKeyThreshold); + logger.debug("loaded filters for next. Added operator: " + getOrderByField() + " > " + + nextOrderByThreshold + ". Offset is: " + offset + ") and " + primaryKeyField + + " greater than: " + nextPKeyThreshold); break; } else - //page in 'last' range, go last + // page in 'last' range, go last { pagingState = State.LAST; - logger.debug("next, is already in 'last' range (offset="+offset+"), refresh to last."); + logger.debug("next, is already in 'last' range (offset=" + offset + "), refresh to last."); this.refresh(db); return; } case LAST: // get last, limit to remaining from count - if(count % limit != 0) - rules.add(new QueryRule(Operator.LIMIT, count % limit)); + if (count % limit != 0) rules.add(new QueryRule(Operator.LIMIT, count % limit)); else rules.add(new QueryRule(Operator.LIMIT, limit)); - if (count > limit) - offset = (int) Math.round(Math.floor((count - 1) / limit) * limit); + if (count > limit) offset = (int) Math.round(Math.floor((count - 1) / limit) * limit); else offset = 0; rules.add(new QueryRule(Operator.LAST)); - logger.debug("loaded filters for last. Added operator: 'last'. Offset is: "+offset); - break; + logger.debug("loaded filters for last. Added operator: 'last'. Offset is: " + offset); + break; case PREV: // get last before prev threshold (exclusive) // set it to be the previous valid offset @@ -158,14 +164,17 @@ public void refresh(Database db) throws DatabaseException rules.add(new QueryRule(Operator.LIMIT, limit)); rules.add(new QueryRule(Operator.LAST)); rules.add(new QueryRule(getOrderByField(), Operator.LESS, prevOrderByThreshold)); - if( !getOrderByField().equals(primaryKeyField) ) rules.add(new QueryRule(primaryKeyField, Operator.LESS, prevPKeyThreshold)); - //FIXME how can we distinguish page when sort field is not unique!! - logger.debug("prev, offset: "+offset+", "+getOrderByField()+" < " + prevOrderByThreshold +" and "+primaryKeyField+" greater than: " + prevPKeyThreshold); + if (!getOrderByField().equals(primaryKeyField)) rules.add(new QueryRule(primaryKeyField, + Operator.LESS, prevPKeyThreshold)); + // FIXME how can we distinguish page when sort field is not + // unique!! + logger.debug("prev, offset: " + offset + ", " + getOrderByField() + " < " + prevOrderByThreshold + + " and " + primaryKeyField + " greater than: " + prevPKeyThreshold); break; } else - { //delegate to first - logger.debug("prev, is already in 'first' range (offset="+offset+"), refresh to first"); + { // delegate to first + logger.debug("prev, is already in 'first' range (offset=" + offset + "), refresh to first"); pagingState = State.FIRST; this.refresh(db); return; @@ -175,14 +184,14 @@ public void refresh(Database db) throws DatabaseException offset = 0; rules.add(new QueryRule(Operator.LIMIT, limit)); logger.debug("loaded filters for first: no filters needed"); - break; + break; } + reloadPage(db, rules.toArray(new QueryRule[rules.size()])); - reloadPage(db,rules.toArray(new QueryRule[rules.size()])); - - // remember prevThresholds and nextThresholds for next time (only for prev/next) - if( page.size() > 0 ) + // remember prevThresholds and nextThresholds for next time (only for + // prev/next) + if (page.size() > 0) { prevOrderByThreshold = page.get(0).get(getOrderByField()); prevPKeyThreshold = page.get(0).get(primaryKeyField); @@ -193,8 +202,8 @@ public void refresh(Database db) throws DatabaseException { logger.error("should never happen unless the db was changed between count and find"); } - - //don't forget! + + // don't forget! pagingState = State.UPTODATE; } } diff --git a/src/org/molgenis/framework/security/Login.java b/src/org/molgenis/framework/security/Login.java index 7f61f1b96..49f12ab55 100644 --- a/src/org/molgenis/framework/security/Login.java +++ b/src/org/molgenis/framework/security/Login.java @@ -36,9 +36,10 @@ public interface Login * @param password * of user * @return true if succesfully authenticated - * @throws Exception,RedirectedException + * @throws Exception + * ,RedirectedException */ - public boolean login(Database db, String name, String password) throws Exception,HandleRequestDelegationException; + public boolean login(Database db, String name, String password) throws Exception, HandleRequestDelegationException; /** * Un-authenticate the user. Now the user will be perceived as 'guest'. @@ -50,7 +51,7 @@ public interface Login * * @throws ParseException * @throws DatabaseException - * @throws Exception + * @throws Exception */ public void reload(Database db) throws DatabaseException, ParseException, Exception; @@ -90,24 +91,25 @@ public interface Login * of entities (aka 'entity level security') * * @return readpermission - * @throws DatabaseException - * @throws DatabaseException + * @throws DatabaseException + * @throws DatabaseException */ public boolean canRead(Class entityClass) throws DatabaseException; - + /** * Indicates whether the user has permissions to read data from this class * of entities (aka 'entity level security') * * @return readpermission - * @throws DatabaseException - * @throws DatabaseException + * @throws DatabaseException + * @throws DatabaseException */ public boolean canRead(Entity entity) throws DatabaseException; /** * Indicates whether the user has permissions to read data from this * implementation of ScreenModel + * * @param screen * @return read permission * @throws DatabaseException @@ -117,27 +119,28 @@ public interface Login /** * Indicates whether the user has permissions to read data from this * implementation of ScreenModel + * * @param screen * @return read permission * @throws DatabaseException */ -// public boolean canRead(ScreenModel model) throws DatabaseException; + // public boolean canRead(ScreenModel model) throws DatabaseException; /** * Indicates whether the user has permissions to add, update, delete data * for this entity class (aka 'entity level security') * * @return editpermission - * @throws DatabaseException + * @throws DatabaseException */ public boolean canWrite(Class entityClass) throws DatabaseException; - + /** * Indicates whether the user has permissions to add, update, delete this * particular entity instance* * * @return editpermission - * @throws DatabaseException + * @throws DatabaseException */ public boolean canWrite(Entity entity) throws DatabaseException; @@ -149,11 +152,12 @@ public interface Login /** * Get name of form/plugin to redirect to after login + * * @return name of form/plugin */ public String getRedirect(); - + public void setAdmin(List entities, Database db) throws DatabaseException; - + public void setRedirect(String redirect); } \ No newline at end of file diff --git a/src/org/molgenis/framework/security/SimpleLogin.java b/src/org/molgenis/framework/security/SimpleLogin.java index 14579338e..415130fd0 100644 --- a/src/org/molgenis/framework/security/SimpleLogin.java +++ b/src/org/molgenis/framework/security/SimpleLogin.java @@ -10,21 +10,21 @@ public class SimpleLogin implements Login { - public SimpleLogin() - { + public SimpleLogin() + { + + } - } + public SimpleLogin(Database db, TokenFactory tm) + { - public SimpleLogin(Database db, TokenFactory tm) - { + } - } - - public SimpleLogin(Database db, String redirect, TokenFactory tm) throws Exception + public SimpleLogin(Database db, String redirect, TokenFactory tm) throws Exception { } - + @Override public void reload(Database db) { @@ -77,13 +77,13 @@ public boolean lastSuperuser() return false; } - @Override + @Override public String getUserName() { return ""; } - @Override + @Override public Integer getUserId() { return 0; @@ -123,11 +123,11 @@ public boolean canRead(org.molgenis.framework.ui.ScreenController screen) return true; } -// @Override -// public boolean canRead(org.molgenis.framework.ui.ScreenModel model) -// { -// return true; -// } + // @Override + // public boolean canRead(org.molgenis.framework.ui.ScreenModel model) + // { + // return true; + // } @Override public QueryRule getRowlevelSecurityFilters(Class klazz) diff --git a/src/org/molgenis/framework/server/AbstractMolgenisServlet.java b/src/org/molgenis/framework/server/AbstractMolgenisServlet.java deleted file mode 100644 index cf0ece52b..000000000 --- a/src/org/molgenis/framework/server/AbstractMolgenisServlet.java +++ /dev/null @@ -1,1546 +0,0 @@ -package org.molgenis.framework.server; - -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.net.URL; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Vector; - -import javax.naming.NamingException; -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.lang.StringUtils; -import org.apache.log4j.BasicConfigurator; -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.molgenis.MolgenisOptions; -import org.molgenis.framework.db.Database; -import org.molgenis.framework.db.DatabaseException; -import org.molgenis.framework.db.QueryRule; -import org.molgenis.framework.security.Login; -import org.molgenis.framework.server.services.MolgenisXrefService; -import org.molgenis.framework.ui.ApplicationController; -import org.molgenis.framework.ui.EasyPluginController; -import org.molgenis.framework.ui.FormModel; -import org.molgenis.framework.ui.ScreenController; -import org.molgenis.framework.ui.ScreenModel; -import org.molgenis.framework.ui.ScreenModel.Show; -import org.molgenis.framework.ui.html.FileInput; -import org.molgenis.util.CsvFileReader; -import org.molgenis.util.CsvStringReader; -import org.molgenis.util.CsvWriter; -import org.molgenis.util.Entity; -import org.molgenis.util.HttpServletRequestTuple; -import org.molgenis.util.SimpleTuple; -import org.molgenis.util.Tuple; -import org.molgenis.util.TupleWriter; - -/** - * Abstract MOLGENIS servlet. Implement abstract methods to get it to work. - * TODO: make it use either context.xml or a properties file for configuration. - */ -@Deprecated -public abstract class AbstractMolgenisServlet extends HttpServlet -{ - /** the name of the datatype input */ - public static String INPUT_DATATYPE = "data_type_input"; - /** the name of the data input */ - public static String INPUT_DATA = "data_input"; - /** boolean indicating file upload */ - public static String INPUT_FILE = "data_file"; - /** the action input */ - public static String INPUT_ACTION = "data_action"; - /** the name of the submit button */ - public static String INPUT_SUBMIT = "submit_input"; - /** indicating wether uploads should return added data */ - public static String INPUT_SILENT = "data_silent"; - /** keep track of window ids */ - private static long newWindowId; - - private Database db; - - public Database getDatabase() throws Exception - { - return this.db; - } - - //seems to be the only way to store login info from e.g. R API - //(standalone) database seems to be refreshed for every request - //and even request.getSession().setAttribute("user", user) has no effect - private String __remote__login__request__username = "anonymous"; - private String __remote__login__request__password = "anonymous"; - - // get logger - protected final transient Logger logger = Logger.getLogger(this.getClass() - .getSimpleName()); - - private static final long serialVersionUID = 3141439968743510237L; - // whether cxf is already loaded - private boolean cxfLoaded = false; - - // the used molgenisoptions, set by generated MolgenisServlet - protected MolgenisOptions usedOptions = null; - - /** - * Create a Login specific to the security scheme used in this MOLGENIS. You - * can override this to set a security mechanism. - * - * @throws Exception - */ - public abstract Login createLogin(Database db, HttpServletRequest request) - throws Exception; - - /** - * Instantiate an application with the right root screen and optional file - * path... - */ - public abstract ApplicationController createUserInterface(Login userLogin); - - /** - * @return package name of this molgenisvariant. - */ - // public static abstract String getMolgenisVariantID(); - - /** - * @return the soap implementation - * @throws NamingException - * @throws DatabaseException - */ - public Object getSoapImpl() throws Exception - { - return null; - } - - public static long getNewWindowId() - { - newWindowId++; - return newWindowId; - } - - public void init(ServletConfig config) throws ServletException { - System.out.println("AbstractMolgenisServlet is initializing log4j"); - String log4jLocation = config.getInitParameter("log4j-properties-location"); - - ServletContext sc = config.getServletContext(); - - if (log4jLocation == null) { - if(StringUtils.isNotEmpty(this.usedOptions.log4j_properties_uri)) { - ClassLoader loader = this.getClass().getClassLoader(); - URL urlLog4jProp = loader.getResource(this.usedOptions.log4j_properties_uri); - if(urlLog4jProp == null) { - System.out.println(String.format("*** Incorrect log4j_properties_uri : '%s' in Molgenis properties file, so initializing log4j with BasicConfigurator", urlLog4jProp)); - BasicConfigurator.configure(); - } else { - System.out.println(String.format("*** Log4j initializing with config file %s", urlLog4jProp)); - PropertyConfigurator.configure(urlLog4jProp); - } - } else { - System.err.println("*** No log4j-properties-location init param, so initializing log4j with BasicConfigurator"); - BasicConfigurator.configure(); - } - } else { - String webAppPath = sc.getRealPath("/"); - String log4jProp = webAppPath + File.separator + log4jLocation; - File log4jFile = new File(log4jProp); - if (log4jFile.exists()) { - System.out.println("Initializing log4j with: " + log4jProp); - PropertyConfigurator.configure(log4jProp); - } else { - System.err.println("*** " + log4jProp + " file not found, so initializing log4j with BasicConfigurator"); - BasicConfigurator.configure(); - } - } - super.init(config); - } - - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) - { - try - { - this.service(request, response); - } - catch (IOException e) - { - e.printStackTrace(); - } - catch (ServletException e) - { - e.printStackTrace(); - } - } - - @Override - public void doPut(HttpServletRequest request, HttpServletResponse response) - { - try - { - this.service(request, response); - } - catch (IOException e) - { - e.printStackTrace(); - } - catch (ServletException e) - { - e.printStackTrace(); - } - } - - @Override - public void doDelete(HttpServletRequest request, - HttpServletResponse response) - { - try - { - this.service(request, response); - } - catch (IOException e) - { - e.printStackTrace(); - } - catch (ServletException e) - { - e.printStackTrace(); - } - } - - public void doPost(HttpServletRequest request, HttpServletResponse response) - { - try - { - this.service(request, response); - } - catch (IOException e) - { - e.printStackTrace(); - } - catch (ServletException e) - { - e.printStackTrace(); - } - } - - protected abstract Database createDatabase(); - - /** - * Frontcontroller of the MOLGENIS application. Based on paths, requests are - * delegated to the particular handlers. - * - * @throws ServletException - */ - public void service(HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException - { - // time the service - long startTime = System.currentTimeMillis(); - logger.info("service started"); - - // decide what handler to use based on request - String path = request.getRequestURI(); - logger.debug("url: " + path); - - try - { - this.db = createDatabase(); - createLogin(db, request); //set login to database! - - - if (path != null && path.contains("/api/find")) - { - this.handleDownload(request, response); - } - else if (path != null && path.contains("/api/add")) - { - this.handleUpload(request, response); - } - else if (path != null && path.contains("/api/R")) - { - this.handleRAPIrequest(request, response); - } - else if (path != null && (path.contains("/api/soap"))) - { - this.handleSOAPrequest(request, response); - } - else if (path != null && path.contains("/xref/find")) - { - this.handleXREFrequest(db, request, response); - } - else if (path != null && path.contains("/download/")) - { - this.handleDownloadFile(request, response); - } - // else if (path != null && path.contains("/rest/")) - // { - // // RestInterface.handleRequest(request, response, - // // getDatabase()); - // this.handleSOAPrequest(request, response); - // } - else - { - this.handleGUIrequest(request, response); - } - } - catch (DatabaseException e) - { - e.printStackTrace(); - } - catch (NamingException e) - { - e.printStackTrace(); - } - catch (Exception e) - { - e.printStackTrace(); - } finally { - try - { - this.db.close(); - } - catch (DatabaseException e) - { - // TODO Auto-generated catch block - throw new ServletException(e); - } - } - - // end timing the service - logger.info("service completed in " - + (System.currentTimeMillis() - startTime) + " milliseconds"); - logger.info("------------------------------"); - } - - private void handleDownloadFile(HttpServletRequest request, - HttpServletResponse response) throws IOException - { - // setup the output-stream - response.setBufferSize(10000); - response.setContentType("text/html; charset=UTF-8"); - - // get the relative path - String filename = request.getRequestURI().substring( - request.getServletPath().length() - + request.getContextPath().length()); - logger.debug("THEFILETODOWNLOAD: " + filename); - - String tempDir = System.getProperty("java.io.tmpdir"); - logger.debug("TEMPDIR: " + tempDir); - - File file = new File(tempDir + "/" + filename); - if (file.exists()) - { - response.setContentType("application/x-download"); - response.setContentLength((int) file.length()); - - FileInputStream in = new FileInputStream(file); - OutputStream out = response.getOutputStream(); - // Copy the contents of the file to the output stream - byte[] buf = new byte[1024]; - int count = 0; - while ((count = in.read(buf)) >= 0) - { - out.write(buf, 0, count); - } - in.close(); - out.close(); - } - else - { - response.getWriter().write("file does not exist"); - } - } - - private void handleSOAPrequest(HttpServletRequest request, - HttpServletResponse response) throws Exception - { - // delegate to CXF servlet - // load the bus if needed - if (this.cxfLoaded == false && (this.getSoapImpl() != null))// || - // this.getRestImpl() - // != null)) - { -// super.loadBus(this.getServletConfig()); -// -// Bus bus = this.getBus(); - - // from samples/restfull directory - - // Build up the server factory bean - // JaxRsServerFactoryBean sf = new JaxWsServerFactoryBean(); - // sf.setBus(bus); - // sf.setServiceClass(this.getRestImpl().getClass()); - // // Use the HTTP Binding which understands the Java Rest - // Annotations - // sf.setBindingId(HttpBindingFactory.HTTP_BINDING_ID); - // sf.setAddress("/rest/"); - // sf.getServiceFactory().setInvoker(new - // BeanInvoker(this.getRestImpl())); - // sf.getServiceFactory().setWrapped(false); - - // sf.create(); - -// BusFactory.setDefaultBus(bus); -// Endpoint.publish("/soap/", this.getSoapImpl()); - // Endpoint.publish("/rest/", this.getSoapImpl()); - - // JAX-RS - // JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); - // sf.setBus(bus); - // sf.setResourceClasses(this.getRestImpl().getClass()); - // sf.setResourceProvider(this.getRestImpl().getClass(), new - // SingletonResourceProvider(this.getRestImpl())); - // sf.setAddress("/rest/"); - // sf.create(); - // - // JAX-WS - // Endpoint.publish("/soap/", this.getSoapImpl()); - - // setInterceptors(sf, this.getServletConfig(), - // "jaxrs.inInterceptors"); - // setInterceptors(sf, this.getServletConfig(), - // "jaxrs.outInterceptors"); - - // JAX-WS - // sf.setBindingId(HttpBindingFactory.); - // JAXRSServerFactoryBean sf2 = new JAXRSServerFactoryBean(); - // sf2.setBus(bus); - // sf2.setResourceClasses(this.getSoapImpl().getClass()); - // sf2.setResourceProvider(this.getSoapImpl().getClass(), new - // SingletonResourceProvider(this.getSoapImpl())); - // sf2.setAddress("/soap/"); - // sf2.create(); - - // JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean(); - // //svrFactory.setBus(bus); - // svrFactory.setServiceClass(this.getSoapImpl().getClass()); - // svrFactory.setAddress("/soap/"); - // svrFactory.setServiceBean(this.getSoapImpl()); - // svrFactory.create(); - - // ServiceFactoryBean svrFactory = new CFactoryBean(); - // //svrFactory.setBus(bus); - // svrFactory.setServiceClass(this.getSoapImpl().getClass()); - // svrFactory.setAddress("/soap/"); - // svrFactory.setServiceBean(this.getSoapImpl()); - // svrFactory.create(); - - // - // //Ssf.setProvider(new AegisJSONProvider()); - - this.cxfLoaded = true; - } - - super.doPost(request, response); - - } - - public void handleGUIrequest(HttpServletRequest request, - HttpServletResponse response) throws Exception - { -// // get database session (note: this shouldn't be in the tomcat -// // session!!! -// Database db = null; -// boolean dbAvailable = false; -// String dbErrorMessage = null; -// try -// { -// db = getDatabase(); -// // db.beginTx(); DISCUSSION -// System.err.println("???" + db); -// if (db != null) -// { -// dbAvailable = true; -// logger.info("created database " + db); -// } -// else -// { -// dbErrorMessage = "database is NULL"; -// } -// } -// catch (Exception e) -// { -// logger.error("Database creation failed: " + e.getMessage()); -// e.printStackTrace(); -// // throw new DatabaseException(e); -// dbErrorMessage = e.getMessage(); -// } - - // login/logout - HttpSession session = request.getSession(); - Login userLogin = null; - // Get application from session (or create one) - ApplicationController molgenis = (ApplicationController) session - .getAttribute("application"); - - // on logout throw whole session away. - if (request.getParameter("__action") != null - && request.getParameter("__action").equalsIgnoreCase("Logout")) - { - molgenis = null; - session.setAttribute("application", null); - } - if (molgenis == null) - { - userLogin = createLogin(db, request); - if ((!userLogin.isAuthenticated() && userLogin.isLoginRequired()) - || (request.getParameter("logout") != null && !session - .isNew())) - { - response.setHeader("WWW-Authenticate", - "BASIC realm=\"MOLGENIS\""); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED); - session.invalidate(); - return; - } - molgenis = createUserInterface(userLogin); - } - // this should work unless complicated load balancing without proxy - // rewriting... - molgenis.setBaseUrl(request.getScheme() + "://" - + request.getServerName() + getPort(request) - + request.getContextPath()); - - // ((UserInterface)molgenis).setDatabase(db); - userLogin = ((ApplicationController) molgenis).getLogin(); - -// if (dbAvailable) -// { -// db.setLogin(userLogin); -// } - - // handle request - try - { - // set the base address - - Tuple requestTuple = new HttpServletRequestTuple(request, response); - - // action == download an attached file - // FIXME move to form controllers handlerequest... - if (FileInput.ACTION_DOWNLOAD.equals(requestTuple - .getString(ScreenModel.INPUT_ACTION))) - { - logger.info(requestTuple); - - File file = new File( - db.getFilesource() - + "/" - + requestTuple - .getString(FileInput.INPUT_CURRENT_DOWNLOAD)); - - FileInputStream filestream = new FileInputStream(file); - - response.setContentType("application/x-download"); - response.setContentLength((int) file.length()); - response.setHeader( - "Content-Disposition", - "attachment; filename=" - + requestTuple - .getString(FileInput.INPUT_CURRENT_DOWNLOAD)); - - BufferedOutputStream out = new BufferedOutputStream( - response.getOutputStream()); - byte[] buffer = new byte[1024]; - int bytes_read; - while ((bytes_read = filestream.read(buffer)) != -1) - { - out.write(buffer, 0, bytes_read); - } - filestream.close(); - out.flush(); - out.close(); - } - - // action == download, but now in a standard way, handled by - // controller - else if (ScreenModel.Show.SHOW_DOWNLOAD.equals(requestTuple - .getString(FormModel.INPUT_SHOW))) - { - // get the screen that will hande the download request - ScreenController controller = molgenis - .get(requestTuple.getString(ScreenModel.INPUT_TARGET)); - - // set the headers for the download - response.setContentType("application/x-download"); - - String action = requestTuple - .getString(ScreenModel.INPUT_ACTION); - String extension = null; - if (action.startsWith("download_txt_")) - { - extension = "txt"; - } - else if (action.startsWith("download_xls_")) - { - extension = "xls"; - } - else - { - throw new Exception("Download type '" + action - + "' unsupported!"); - } - - ScreenModel.Show.values(); - response.setHeader("Content-Disposition", - "attachment; filename=" - + controller.getName().toLowerCase() + "." - + extension); - - // let the handleRequest produce the content - controller.handleRequest(db, requestTuple, - response.getOutputStream()); - - // TODO: does this fail when stream is already closed?? - response.getOutputStream().flush(); - response.getOutputStream().close(); - } - - // handle normal event and then write the response - else - { - // capture select - if (requestTuple.getString("select") != null) - { - // get the screen to be selected - ScreenController toBeSelected = molgenis - .get(requestTuple.getString("select")); - // select leaf in its parent - try - { - toBeSelected.getParent().setSelected( - requestTuple.getString("select")); - } - catch (NullPointerException npe) - { - // screen does not exists, ignore request - } - } - - if (Show.SHOW_CLOSE.equals(molgenis.handleRequest(db, - requestTuple, null))) - { - //if close, then write a close script - PrintWriter writer = response.getWriter(); - writer.write(""); - writer.close(); - return; - } - - // workaround - see comment @ - // EasyPluginController.HTML_WAS_ALREADY_SERVED - if (EasyPluginController.HTML_WAS_ALREADY_SERVED != null - && EasyPluginController.HTML_WAS_ALREADY_SERVED) - { - EasyPluginController.HTML_WAS_ALREADY_SERVED = null; - return; - } - - // handle request - molgenis.reload(db); // reload the application - logger.debug("reloaded " + molgenis.getName() - + " screen, rendering..."); - - // ((UserInterface)molgenis).getDatabase().close(); - // ((UserInterface)molgenis).setDatabase(null); - // session are automatically synchronized... - session.setAttribute("application", molgenis); - - // prepare the response - response.setContentType("text/html"); - // response.setBufferSize(10000); - PrintWriter writer = response.getWriter(); - - // TODO set application errors (should not be necessary - // anymore?) - // if (dbAvailable) - // { - // args.put("applicationHtmlError", ""); - // } - // else - // { - // args.put("applicationHtmlError", - // "

Database creation error: " - // + dbErrorMessage + "

"); - // } - - // Render result - String show = requestTuple.getString(FormModel.INPUT_SHOW); - if (ScreenModel.Show.SHOW_DIALOG.equals(show)) - { - molgenis.getModel().setShow(show); - ScreenController target = molgenis.get(requestTuple - .getString("__target")); - molgenis.getModel().setTarget(target); - writer.write(molgenis.render()); - } - else if ("massupdate".equals(show)) - { - molgenis.getModel().setShow("show"); - writer.write(molgenis.render()); - - // List massupdate = requestTuple - // .getList("massUpdate"); - // // if empty list, create empty list - // if (massupdate == null) massupdate = new - // ArrayList(); - // - // Vector massupdate_updateable = new - // Vector(); - // Vector massupdate_readonly = - // getVector(requestTuple - // .getObject("massUpdate_readonly")); - // - // for (Object id : massupdate) - // { - // if (!massupdate_readonly.contains(id)) - // massupdate_updateable - // .add(id.toString()); - // } - // - // args.put("massupdate", massupdate_updateable); - } - else - { - molgenis.getModel().setShow("root"); - writer.write(molgenis.render()); - } - - // if (false) - // { - // logger.info("create template"); - // String templatefile = "Main.ftl"; - // - // // Create a freemarker template - // logger.debug("trying to process template '" + templatefile - // + "'"); - // Configuration freemarkerConf = this - // .getFreemarkerConfiguration(molgenis); - // Template freemarkerTemplate = freemarkerConf - // .getTemplate(templatefile); - // Map args = new TreeMap(); - // args.put("title", molgenis.getLabel()); - // args.put("application", molgenis); - // args.put("widgetfactory", new WidgetFactory()); - // - // if (dbAvailable) - // { - // args.put("applicationHtmlError", ""); - // } - // else - // { - // args.put("applicationHtmlError", - // "

Database creation error: " - // + dbErrorMessage + "

"); - // } - - // args.put("username", userLogin.getUserName()); - - /** - * Work in progress: mechanism to pass REST calls to underlying - * screens (ie. plugins! much needed!) for(int i = 0; i < - * requestTuple.size(); i ++){ - * args.put(requestTuple.getFields().get(i), - * requestTuple.getString(i)); - * //System.out.println("**** putting: " + - * requestTuple.getFields().get(i) + " TO " + - * requestTuple.getString(i)); } - */ - - // FIXME complex screen handling - // String show = requestTuple - // .getString(FormModel.INPUT_SHOW); - // if (show != null) - // { - // args.put("show", requestTuple.getString("__show")); - // - // // if dialog, only show target - // if (ScreenModel.Show.SHOW_DIALOG.equals(show)) - // { - // ScreenModel target = molgenis.get(requestTuple - // .getString("__target")); - // args.put("target", target.getName()); - // args.put("application", target); - // // args.put("show", "dialogue"); - // } - // - // if (requestTuple.getString("__show").equals( - // "massupdate")) - // { - // List massupdate = requestTuple - // .getList("massUpdate"); - // // if empty list, create empty list - // if (massupdate == null) massupdate = new ArrayList(); - // - // Vector massupdate_updateable = new Vector(); - // Vector massupdate_readonly = getVector(requestTuple - // .getObject("massUpdate_readonly")); - // - // for (Object id : massupdate) - // { - // if (!massupdate_readonly.contains(id)) massupdate_updateable - // .add(id.toString()); - // } - // - // args.put("massupdate", massupdate_updateable); - // } - // } - // else - // { - // args.put("show", "root"); - // } - // logger.info("applying layout template"); - - // if (linkoutOverlay()) - // { - // logger.info("applying linkout overlay"); - // Writer result = new StringWriter(); - // PrintWriter tmpWriter = new PrintWriter(result); - // freemarkerTemplate.process(args, tmpWriter); - // String templated = result.toString(); - // LinkOutOverlay linker = new LinkOutOverlay(); - // String afterOverlay = linker.addlinkouts(templated); - // writer.write(afterOverlay); - // } - // else - // { - // freemarkerTemplate.process(args, writer); - // } - // } - writer.close(); - - // done, get rid of screen messages here? - ((ApplicationController) molgenis).clearAllMessages(); - - // TODO THIS USED TO BE HERE.. PLEASE REVIEW!! - // args.put("massupdate", massupdate_updateable); - // } - // } - // else - // { - // args.put("show", "root"); - // } - // logger.info("applying layout template"); - // - // if(usedOptions.linkout_overlay){ - // logger.info("applying linkout overlay"); - // Writer result = new StringWriter(); - // PrintWriter tmpWriter = new PrintWriter(result); - // freemarkerTemplate.process(args, tmpWriter); - // String templated = result.toString(); - // LinkOutOverlay linker = new LinkOutOverlay(); - // String afterOverlay = linker.addlinkouts(templated); - // writer.write(afterOverlay); - // }else{ - // freemarkerTemplate.process(args, writer); - // } - // writer.close(); - // END OF 'USED TO BE HERE' BLOCK - } - // db.commitTx(); DISCUSSION - } - catch (Exception e) - { - // response.getOutputStream().print(e.getMessage()); - logger.error(e.getMessage()); - e.printStackTrace(); - // unrecoverable error? does this take down the whole server? - // throw new RuntimeException(e); - } - - } - - /** - * Delegate to handle request for the R api. - * - * @param request - * @param response - * @throws IOException - */ - public void handleRAPIrequest(HttpServletRequest request, - HttpServletResponse response) throws IOException - { - PrintWriter out = response.getWriter(); - - String filename = request.getRequestURI().substring( - request.getServletPath().length() - + request.getContextPath().length()); - logger.info("getting file: " + filename); - logger.info("url: " + request.getRequestURL()); - logger.info("port: " + request.getLocalPort()); - logger.info("port: " + request.getLocalAddr()); - if (filename.startsWith("/")) filename = filename.substring(1); - - // if R file exists, return that - if (!filename.equals("") && !filename.endsWith(".R")) - { - out.println("you can only load .R files"); - } - else if (filename.equals("")) - { - logger.info("getting default file"); - // String server = - // this.getMolgenisHostName()+request.getContextPath(); - String localName = request.getLocalName(); - if (localName.equals("0.0.0.0")) localName = "localhost"; - String server = "http://" + localName + ":" - + request.getLocalPort() + request.getContextPath(); - String rSource = server + "/api/R/"; - // getRequestURL omits port! - out.println("#step1: (first time only) install RCurl package from omegahat or bioconductor, i.e.
"); - out.println("#source(\"http://bioconductor.org/biocLite.R\")
"); - out.println("#biocLite(\"RCurl\")
"); - out.println(); - out.println("#step2: source this file to use the MOLGENIS R interface, i.e.
"); - out.println("#source(\"" + rSource + "\")
"); - out.println(); - out.println("molgenispath <- paste(\"" + rSource + "\")"); - out.println(); - out.println("serverpath <- paste(\"" + server + "\")"); - out.println(); - out.println("#load autogenerated R interfaces
"); - out.println("source(\"" + rSource + "source.R\")"); - out.println(); - // out.println("#load R/qtl to XGAP functions
"); - // out.println("source(\"" + rSource + "rqtl.R\")"); - out.println(); - // out.println( - // "#load dbGG specific extension to ease use of the Data <- DataElement structure as matrices
" - // ); - // out.println("source(\"" + rSource + this.getMolgenisVariantID() + - // "/R/DataMatrix.R\")"); - out.println(); - out.println("#connect to the server
"); - out.println("MOLGENIS.connect(\"" + server + "\")"); - // chdir=T means temporarily change working directory - } - // otherwise return the default R code to source all - else - { - // the path may contain package name, e.g. - // package.name.path/R/myclass.R - filename = filename.replace(".", "/"); - filename = filename.substring(0, filename.length() - 2) + ".R"; - // map to hard drive, minus path papp/servlet - File root = new File(this.getClass().getResource("source.R") - .getFile()).getParentFile().getParentFile().getParentFile(); - - if (filename.equals("source.R")) - { - root = new File(root.getAbsolutePath() + "/app/servlet"); - } - File source = new File(root.getAbsolutePath() + "/" + filename); - - // up to root of app - logger.info("trying to load R file: " + filename + " from path " - + source); - if (source.exists()) - { - this.writeURLtoOutput(source.toURI().toURL(), out); - } - else - { - out.write("File '" + filename + "' not found"); - } - } - - out.close(); - } - - /** - * Handle use of the download API. - * - * TODO: this method is horrible and should be properly refactored, - * documented and tested! - * - * @param request - * @param response - */ - public void handleDownload(HttpServletRequest request, - HttpServletResponse response) - { - // setup the output-stream - response.setBufferSize(10000); - response.setContentType("text/html; charset=UTF-8"); - logger.info("starting download " + request.getPathInfo()); - long start_time = System.currentTimeMillis(); - - // HttpSession session = request.getSession(); - PrintWriter out = null; - try - { - out = response.getWriter(); - } - catch (IOException e) - { - e.printStackTrace(); - } - Database db = null; - try - { - db = this.getDatabase(); - //db.setLogin(new org.molgenis.framework.security.SimpleLogin(db)); - try - { - - // check whether a class is chosen - if (request.getPathInfo() == null - || request.getPathInfo().equals("/find")) - { - logger.debug("show 'choose entity' dialogue"); - out.println(""); - out.println("You can download data:
"); - - for (String className : db.getEntityNames()) - { - - if (request.getPathInfo() == null) out - .println("" - + className + "
"); - else - out.println("" - + className + "
"); - } - - out.println(""); - - logger.debug("done"); - return; - } - String entityName = request.getPathInfo().substring(1); - - // check whether a querystring has to build - if (request.getQueryString() != null - && request.getQueryString().equals( - "__showQueryDialogue=true")) - { - logger.debug("show 'set filters' dialogue"); - out.println("
"); - out.println("You choose to download '" - + entityName - + "' data. (back)

Here you can have to set at least one filter:
"); - out.println(""); - for (String field : ((Entity) Class.forName(entityName) - .newInstance()).getFields()) - { - out.println(""); - } - out.println("
" + field - + "=
"); - out.println(""); - - // with security break out.println( "
" ); - out.println("
"); - out.println("TIP: notice how the url is bookmarkeable for future downloads!"); - out.println("TIP: click 'save as...' and name it as '.txt' file."); - out.println("
"); - return; - } - - // create query rules - List rulesList = new ArrayList(); - - // use get - if (request.getQueryString() != null) - { - logger.debug("handle find query via http-get: " - + request.getQueryString()); - String[] ruleStrings = request.getQueryString().split("&"); - - for (String rule : ruleStrings) - { - String[] ruleElements = rule.split("="); - - if (ruleElements.length != 2) - { - // throw new Exception( "cannot understand - // querystring " + rule ); - } - else if (ruleElements[1].startsWith("[")) - { - ruleElements[1] = ruleElements[1].replace("%20", - " "); - String[] values = ruleElements[1].substring(1, - ruleElements[1].indexOf("]")).split(","); - rulesList.add(new QueryRule(ruleElements[0], - QueryRule.Operator.IN, values)); - } - else - { - if (ruleElements[1] != "" - && !"__submitbutton" - .equals(ruleElements[0])) rulesList - .add(new QueryRule(ruleElements[0], - QueryRule.Operator.EQUALS, - ruleElements[1])); - } - } - } - // use post - else - { - Tuple requestTuple = new HttpServletRequestTuple(request); - logger.debug("handle find query via http-post with parameters: " - + requestTuple.getFields()); - for (String name : requestTuple.getFields()) - { - if (requestTuple.getString(name).startsWith("[")) - { - String[] values = requestTuple - .getString(name) - .substring( - 1, - requestTuple.getString(name) - .indexOf("]")).split(","); - rulesList.add(new QueryRule(name, - QueryRule.Operator.IN, values)); - } - else - { - rulesList.add(new QueryRule(name, - QueryRule.Operator.EQUALS, requestTuple - .getString(name))); - } - } - } - - // TODO: when is this reached?? - - // execute query - TupleWriter writer = new CsvWriter(out); - // CsvWriter writer = new CsvFileWriter( new - // File("c:/testout.txt") ); - db.find(getClassForName(entityName), writer, - rulesList.toArray(new QueryRule[rulesList.size()])); - } - catch (Exception e) - { - out.println("
" + e.getMessage() - + "
"); - // e.printStackTrace(); - // throw e; - } - finally - { - db.close(); - } - - out.close(); - } - catch (Exception e) - { - out.println("
No database available to query: " - + e.getMessage() + "
"); - logger.error(e); - } - logger.info("servlet took: " - + (System.currentTimeMillis() - start_time)); - logger.info("------------"); - } - - @SuppressWarnings("unchecked") - /* - * No way to do this without warnings. - */ - private Class getClassForName(String entityName) - throws ClassNotFoundException - { - return (Class) Class.forName(entityName); - } - - public void handleUpload(HttpServletRequest request, - HttpServletResponse response) - { - // setup the output-stream - response.setBufferSize(10000); - response.setContentType("text/html; charset=UTF-8"); - - logger.info("upload service started"); - long start_time = System.currentTimeMillis(); - - try - { - Tuple requestTuple = new HttpServletRequestTuple(request); - logger.info("parameters: " + requestTuple.getFields()); - // log paramaters - // for( String s : r.getFields() ) - // { - // logger.info("'" + s + "'=" + r.getObject(s)); - // } - - PrintWriter out = response.getWriter(); - // EntityReaderFactory readerFactory = new CsvReaderFactory(); - - //"hack" to be able to log in via R (default R API has been overridden for xQTL) - if(requestTuple.getString(INPUT_ACTION) != null && requestTuple.getString(INPUT_ACTION).equals("__remote__login__request")) - { - String username = requestTuple.getString(INPUT_DATA); - String password = requestTuple.getString(INPUT_SILENT); - boolean loggedIn = db.getLogin().login(db, username, password); - if(loggedIn) - { - out.println("Welcome, " + username + "!"); - this.__remote__login__request__username = username; - this.__remote__login__request__password = password; - } - else - { - out.println("Login failed: username or password unknown"); - } - out.flush(); - out.close(); - return; - } - - // if no type selected: show data type choice - if (requestTuple.getString(INPUT_DATATYPE) == null) - { - try - { - out.println("
"); - out.println("

Data upload (step 1)

"); - out.println("Choose your data type."); - out.println(""); - out.println(""); - out.println("
"); - } - catch (Exception e) - { - out.println("Upload failed: " + e.getMessage() + ""); - e.printStackTrace(); - throw e; - } - - } - // if no data provided, show csv input form - else if (requestTuple.getObject(INPUT_DATA) == null - && requestTuple.getObject(INPUT_FILE) == null) - { - try - { - // String clazzName = - // requestTuple.getString(INPUT_DATATYPE); - // Class entityClass = - // getClassForName(clazzName); - // Entity template = entityClass.newInstance(); - // - // out - // .println("
"); - // out.println("

Data upload (step 2)

"); - // out.println("Enter your data as CSV."); - // out - // .println(""); - // out - // .println(""); - // out.println("
"); - } - catch (Exception e) - { - out.println("Upload failed: " + e.getMessage() + ""); - e.printStackTrace(); - throw e; - } - } - // process request - else - { - NumberFormat formatter = NumberFormat.getInstance(Locale.US); - logger.info("processing add/update/delete"); - String action = null; // ADD, UPDATE, REMOVE - Class entityClass = null; - - try - { - String clazzName = requestTuple.getString(INPUT_DATATYPE); - entityClass = getClassForName(clazzName); - - // get the constants - Tuple constants = new SimpleTuple(); - for (String column : requestTuple.getFields()) - { - if (!column.equals(INPUT_DATATYPE) - && !column.equals(INPUT_DATA) - && !column.equals(INPUT_ACTION) - && !column.equals(INPUT_SUBMIT) - && !requestTuple.getString(column).equals("")) - { - constants.set(column, - requestTuple.getObject(column)); - } - } - action = requestTuple.getString(INPUT_ACTION); - // //out.println("Defaults: " + constants); - - // create a database - Database db = this.getDatabase(); - - // write to the database - // logger.info("Adding parsed data to database:\n" + - // r.getString(INPUT_DATA)); - - int nRowsChanged = 0; - if (action.equals("ADD")) - { - File temp = File.createTempFile("molgenis", "tab"); - TupleWriter writer = new CsvWriter(new PrintWriter( - new BufferedWriter(new FileWriter(temp)))); - if (requestTuple.getObject(INPUT_SILENT) != null - && requestTuple.getBool(INPUT_SILENT) == true) - { - writer.close(); - writer = null; - } - // List entities = db.toList(entityClass, new - // CsvStringReader(r.getString(INPUT_DATA)); - - if (requestTuple.getObject(INPUT_DATA) != null) - { - logger.info("processing textarea upload..."); - - //allows secure uploading of data from R API - String username = this.__remote__login__request__username; - String password = this.__remote__login__request__password; - db.getLogin().login(db, username, password); - nRowsChanged = db.add(entityClass, new CsvStringReader(requestTuple.getString(INPUT_DATA)), writer); - } - else if (requestTuple.getObject(INPUT_FILE) != null) - { - logger.info("processing file upload..."); - nRowsChanged = db.add( - entityClass, - new CsvFileReader(requestTuple - .getFile(INPUT_FILE)), writer); - } - else - { - logger.error("no input data or input file provided."); - out.print("ERROR: no input data or input file provided."); - } - out.print("Uploaded " + formatter.format(nRowsChanged) - + " rows of " + entityClass.getCanonicalName() - + "\n"); - - if (writer != null) writer.close(); - BufferedReader reader = new BufferedReader( - new FileReader(temp)); - String line = null; - while ((line = reader.readLine()) != null) - { - out.println(line); - } - temp.delete(); - } - else if (action.equals("UPDATE")) - { - if (requestTuple.getObject(INPUT_DATA) != null) - { - nRowsChanged = db.update( - entityClass, - new CsvStringReader(requestTuple - .getString(INPUT_DATA))); - out.print("Updated " - + formatter.format(nRowsChanged) - + " rows of " - + entityClass.getCanonicalName() + "\n"); - } - else if (requestTuple.getObject(INPUT_FILE) != null) - { - nRowsChanged = db.update( - entityClass, - new CsvFileReader(requestTuple - .getFile(INPUT_FILE))); - out.print("Updated " - + formatter.format(nRowsChanged) - + " rows of " - + entityClass.getCanonicalName() + "\n"); - } - } - else if (action.equals("REMOVE")) - { - if (requestTuple.getObject(INPUT_DATA) != null) - { - nRowsChanged = db.remove( - entityClass, - new CsvStringReader(requestTuple - .getString(INPUT_DATA))); - out.print("Removed " - + formatter.format(nRowsChanged) - + " rows of " - + entityClass.getCanonicalName() + "\n"); - } - else if (requestTuple.getObject(INPUT_FILE) != null) - { - nRowsChanged = db.remove( - entityClass, - new CsvFileReader(requestTuple - .getFile(INPUT_FILE))); - out.print("Removed " - + formatter.format(nRowsChanged) - + " rows of " - + entityClass.getCanonicalName() + "\n"); - } - } - else - { - throw new Exception("Unknown action " + action); - } - } - catch (Exception e) - { - out.print("Failed to " + action + " " - + entityClass.getName() + ": " + e.getMessage() - + ""); - e.printStackTrace(); - throw e; - } - - } - - out.close(); - } - catch (Exception e) - { - logger.error(e); - e.printStackTrace(); - } - logger.info("servlet took: " - + (System.currentTimeMillis() - start_time) + " ms"); - logger.info("------------"); - } - - // FIXME move away - @SuppressWarnings("unchecked") - public Vector getVector(Object object) - { - - Vector vector = new Vector(); - if (object != null) - { - if (object.getClass() == Vector.class) - { - vector = (Vector) object; - } - else - // one shift only - { - vector.addElement(object.toString()); - } - } - return vector; - } - - /** - * Helper function to write an URL to an outputstream. E.g. used to pass - * files that are stored elsewhere as proxy. - * - * @param source - * @param out - * @throws IOException - */ - private void writeURLtoOutput(URL source, PrintWriter out) - throws IOException - { - BufferedReader reader = new BufferedReader(new InputStreamReader( - source.openStream())); - String sourceLine; - while ((sourceLine = reader.readLine()) != null) - { - out.println(sourceLine); - } - reader.close(); - } - - public void handleXREFrequest(final Database db, final HttpServletRequest request, - final HttpServletResponse response) throws ServletException - { - try - { - MolgenisXrefService.handleXrefRequest(db, new MolgenisRequest(request), new MolgenisResponse(response)); - } - catch (Exception e) - { - throw new ServletException(e); - } - } - - - - private static String getPort(HttpServletRequest req) - { - if ("http".equalsIgnoreCase(req.getScheme()) - && req.getServerPort() != 80 - || "https".equalsIgnoreCase(req.getScheme()) - && req.getServerPort() != 443) - { - return (":" + req.getServerPort()); - } - else - { - return ""; - } - } - -} diff --git a/src/org/molgenis/framework/server/AuthStatus.java b/src/org/molgenis/framework/server/AuthStatus.java index 0fabe2560..36f3401ff 100644 --- a/src/org/molgenis/framework/server/AuthStatus.java +++ b/src/org/molgenis/framework/server/AuthStatus.java @@ -1,21 +1,23 @@ package org.molgenis.framework.server; -public class AuthStatus{ - +public class AuthStatus +{ + boolean showApi; String printMe; - + public AuthStatus(boolean showApi, String printMe) { super(); this.showApi = showApi; this.printMe = printMe; } - + public boolean isShowApi() { return showApi; } + public String getPrintMe() { return printMe; diff --git a/src/org/molgenis/framework/server/FrontControllerAuthenticator.java b/src/org/molgenis/framework/server/FrontControllerAuthenticator.java index b6b3918d7..b3d37702c 100644 --- a/src/org/molgenis/framework/server/FrontControllerAuthenticator.java +++ b/src/org/molgenis/framework/server/FrontControllerAuthenticator.java @@ -4,39 +4,42 @@ public class FrontControllerAuthenticator { - - public enum LoginStatus { + + public enum LoginStatus + { SUCCESSFULLY_LOGGED_IN, ALREADY_LOGGED_IN, AUTHENTICATION_FAILURE, EXCEPTION_THROWN } - - public enum LogoutStatus { + + public enum LogoutStatus + { SUCCESSFULLY_LOGGED_OUT, ALREADY_LOGGED_OUT, EXCEPTION_THROWN } - - public static LoginStatus login(MolgenisRequest request, String username, - String password) + public static LoginStatus login(MolgenisRequest request, String username, String password) { - //System.out.println("FrontControllerAuthenticator LOGIN called"); + // System.out.println("FrontControllerAuthenticator LOGIN called"); try { - + Database db = request.getDatabase(); - - if(db.getLogin().isAuthenticated()) + + if (db.getLogin().isAuthenticated()) { return LoginStatus.ALREADY_LOGGED_IN; } - + // try to login boolean loggedIn = db.getLogin().login(db, username, password); - - //System.out.println("FrontControllerAuthenticator loggedIn: " + loggedIn); + + // System.out.println("FrontControllerAuthenticator loggedIn: " + + // loggedIn); if (loggedIn) { - //TODO: Missing redirect??? - //Login login = new org.molgenis.auth.DatabaseLogin(request.getDatabase(), "ClusterDemo"); + // TODO: Missing redirect??? + // Login login = new + // org.molgenis.auth.DatabaseLogin(request.getDatabase(), + // "ClusterDemo"); // store login in session request.getRequest().getSession().setAttribute("login", db.getLogin()); @@ -56,31 +59,31 @@ public static LoginStatus login(MolgenisRequest request, String username, public static LogoutStatus logout(MolgenisRequest request) { - //System.out.println("FrontControllerAuthenticator LOGOUT called"); + // System.out.println("FrontControllerAuthenticator LOGOUT called"); try { - + Database db = request.getDatabase(); - - if(!db.getLogin().isAuthenticated()) + + if (!db.getLogin().isAuthenticated()) { return LogoutStatus.ALREADY_LOGGED_OUT; } - - //logout from database - //FIXME: needed?? + + // logout from database + // FIXME: needed?? request.getDatabase().getLogin().logout(request.getDatabase()); - - //set session login to null + + // set session login to null request.getRequest().getSession().setAttribute("login", null); - - //invalidate the session -// response.getResponse().setHeader("WWW-Authenticate", -// "BASIC realm=\"MOLGENIS\""); -// response.getResponse().sendError( -// HttpServletResponse.SC_UNAUTHORIZED); -// request.getRequest().getSession().invalidate(); - + + // invalidate the session + // response.getResponse().setHeader("WWW-Authenticate", + // "BASIC realm=\"MOLGENIS\""); + // response.getResponse().sendError( + // HttpServletResponse.SC_UNAUTHORIZED); + // request.getRequest().getSession().invalidate(); + return LogoutStatus.SUCCESSFULLY_LOGGED_OUT; } catch (Exception e) @@ -88,29 +91,28 @@ public static LogoutStatus logout(MolgenisRequest request) e.printStackTrace(); return LogoutStatus.EXCEPTION_THROWN; } - - -// // remove login fron session -// HttpSession session = request.getRequest().getSession(); -// session.setAttribute("login", null); -// -// // get current db login and invalidate the session -// // if user is not logged in, and login is required -// Login userLogin = null; -// userLogin = request.getDatabase().getLogin(); -// -// if ((!userLogin.isAuthenticated() && userLogin.isLoginRequired())) -// { -// response.getResponse().setHeader("WWW-Authenticate", -// "BASIC realm=\"MOLGENIS\""); -// response.getResponse().sendError( -// HttpServletResponse.SC_UNAUTHORIZED); -// session.invalidate(); -// return; -// } -// -// // logout from db -// userLogin.logout(request.getDatabase()); + + // // remove login fron session + // HttpSession session = request.getRequest().getSession(); + // session.setAttribute("login", null); + // + // // get current db login and invalidate the session + // // if user is not logged in, and login is required + // Login userLogin = null; + // userLogin = request.getDatabase().getLogin(); + // + // if ((!userLogin.isAuthenticated() && userLogin.isLoginRequired())) + // { + // response.getResponse().setHeader("WWW-Authenticate", + // "BASIC realm=\"MOLGENIS\""); + // response.getResponse().sendError( + // HttpServletResponse.SC_UNAUTHORIZED); + // session.invalidate(); + // return; + // } + // + // // logout from db + // userLogin.logout(request.getDatabase()); } } diff --git a/src/org/molgenis/framework/server/JTextAreaAppender.java b/src/org/molgenis/framework/server/JTextAreaAppender.java index ccc7efb05..28b93a8ca 100644 --- a/src/org/molgenis/framework/server/JTextAreaAppender.java +++ b/src/org/molgenis/framework/server/JTextAreaAppender.java @@ -48,8 +48,7 @@ public boolean requiresLayout() public void close() { - if (closed) - return; + if (closed) return; closed = true; if (layout != null) { diff --git a/src/org/molgenis/framework/server/MolgenisCompatibleD2RWebappInitListener.java b/src/org/molgenis/framework/server/MolgenisCompatibleD2RWebappInitListener.java index 5fa887cf2..d246ee647 100644 --- a/src/org/molgenis/framework/server/MolgenisCompatibleD2RWebappInitListener.java +++ b/src/org/molgenis/framework/server/MolgenisCompatibleD2RWebappInitListener.java @@ -56,4 +56,4 @@ //// } // return ConfigLoader.toAbsoluteURI(fileName); // } -//} +// } diff --git a/src/org/molgenis/framework/server/MolgenisContext.java b/src/org/molgenis/framework/server/MolgenisContext.java index 3d8bc0ee5..550fe2fd8 100644 --- a/src/org/molgenis/framework/server/MolgenisContext.java +++ b/src/org/molgenis/framework/server/MolgenisContext.java @@ -17,14 +17,14 @@ public class MolgenisContext private MolgenisOptions usedOptions; private String variant; private TokenFactory tokenFactory; -// private Scheduler scheduler; + // private Scheduler scheduler; private SchedulingService schedulingService; - + // other "static" variables here, eg. // molgenis version // date/time of generation // revision number - + public MolgenisContext(ServletConfig sc, DataSource ds, MolgenisOptions usedOptions, String variant) { this.sc = sc; @@ -32,31 +32,31 @@ public MolgenisContext(ServletConfig sc, DataSource ds, MolgenisOptions usedOpti this.usedOptions = usedOptions; this.variant = variant; this.tokenFactory = new TokenFactory(); - - //start Quartz scheduler -// try -// { -// this.scheduler = StdSchedulerFactory.getDefaultScheduler(); -// this.scheduler.start(); -// System.out.println("Quartz scheduler started"); -// } -// catch (SchedulerException e) -// { -// System.err.println("FATAL EXCEPTION: failure for starting scheduler in MolgenisContext."); -// e.printStackTrace(); -// System.exit(0); -// } + + // start Quartz scheduler + // try + // { + // this.scheduler = StdSchedulerFactory.getDefaultScheduler(); + // this.scheduler.start(); + // System.out.println("Quartz scheduler started"); + // } + // catch (SchedulerException e) + // { + // System.err.println("FATAL EXCEPTION: failure for starting scheduler in MolgenisContext."); + // e.printStackTrace(); + // System.exit(0); + // } this.schedulingService = new SchedulingService(); -// try -// { -// this.schedulingService.start(); -// } -// catch (SchedulerException e) -// { -// System.err.println("FATAL EXCEPTION: failure for starting scheduler in MolgenisContext."); -// e.printStackTrace(); -// } + // try + // { + // this.schedulingService.start(); + // } + // catch (SchedulerException e) + // { + // System.err.println("FATAL EXCEPTION: failure for starting scheduler in MolgenisContext."); + // e.printStackTrace(); + // } } public SchedulingService getSchedulingService() @@ -66,9 +66,9 @@ public SchedulingService getSchedulingService() public Scheduler getScheduler() throws SchedulerException { - StdSchedulerFactory ssf = (StdSchedulerFactory) this.sc.getServletContext().getAttribute("org.quartz.impl.StdSchedulerFactory.KEY"); - if (ssf != null) - return ssf.getScheduler(); + StdSchedulerFactory ssf = (StdSchedulerFactory) this.sc.getServletContext().getAttribute( + "org.quartz.impl.StdSchedulerFactory.KEY"); + if (ssf != null) return ssf.getScheduler(); else throw new SchedulerException("Scheduler not started"); } @@ -87,7 +87,7 @@ public ServletConfig getServletConfig() { return sc; } - + public ServletContext getServletContext() { return sc.getServletContext(); @@ -107,5 +107,5 @@ public void setUsedOptions(MolgenisOptions usedOptions) { this.usedOptions = usedOptions; } - + } diff --git a/src/org/molgenis/framework/server/MolgenisFrontController.java b/src/org/molgenis/framework/server/MolgenisFrontController.java index 4ea55ea1d..d1f6d1445 100644 --- a/src/org/molgenis/framework/server/MolgenisFrontController.java +++ b/src/org/molgenis/framework/server/MolgenisFrontController.java @@ -1,12 +1,18 @@ package org.molgenis.framework.server; +import java.io.File; import java.io.IOException; +import java.net.URL; import java.sql.Connection; import java.sql.SQLException; +import java.text.DateFormat; import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; import java.util.Enumeration; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; @@ -15,24 +21,27 @@ import javax.sql.DataSource; import org.apache.commons.lang.StringUtils; +import org.apache.log4j.BasicConfigurator; +import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Logger; +import org.apache.log4j.PatternLayout; +import org.apache.log4j.PropertyConfigurator; +import org.apache.log4j.RollingFileAppender; import org.molgenis.MolgenisOptions; import org.molgenis.framework.db.DatabaseException; -//import java.util.Date; -//import java.util.Enumeration; -//import javax.servlet.http.HttpSession; public abstract class MolgenisFrontController extends HttpServlet implements MolgenisService { // helper vars private static final long serialVersionUID = -2141508157810793106L; protected Logger logger; + private DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss 'on' dd MMMM yyyy"); // map of all services for this app protected Map services; // list of all connections - protected Map connections; + protected ConcurrentHashMap connections; // the used molgenisoptions, set by generated MolgenisServlet protected MolgenisOptions usedOptions = null; @@ -87,38 +96,65 @@ public void handleRequest(MolgenisRequest request, MolgenisResponse response) th DatabaseException, IOException { HttpServletRequest req = request.getRequest(); - String contextPath = (StringUtils.isNotEmpty(req.getContextPath()) ? req.getContextPath() : context - .getVariant()); - if (StringUtils.startsWith(this.getServletContext().getServerInfo(), "Apache Tomcat")) + + // block spiders + String userAgent = req.getHeader("User-Agent"); + for (String spider : new String[] + { "Googlebot", "Yammybot", "Openbot", "Yahoo", "Slurp", "msnbot", "ia_archiver", "Lycos", "Scooter", + "AltaVista", "Teoma", "Gigabot", "Googlebot-Mobile" }) { - contextPath = req.getContextPath(); + if (userAgent.contains(spider)) + { + response.response.sendError(403, "This page is forbidden for spiders."); + return; + } } - String path = req.getRequestURI().substring(contextPath.length() + 1); - if (path.equals("")) path = "/"; - if (!path.startsWith("/")) + // lots of info about request variables & webservers @ + // http://gbic.target.rug.nl/forum/showthread.php?tid=690 + + // same for every tested webserver: e.g. + // "http://localhost:8080/xqtl/api/R" + String requestURL = req.getRequestURL().toString(); + + // same for every tested webserver: e.g. "/xqtl/api/R" + String requestURI = req.getRequestURI(); + + // empty for Apache Tomcat, but e.g. "/xqtl" for standalone + String appName = req.getServletPath(); + if (appName.equals("")) { - path = "/" + path; + // empty for standalone, but e.g. "/xqtl" for Apache Tomcat + appName = req.getContextPath(); } - for (String p : services.keySet()) + // turns "http://localhost:8080/xqtl/api/R" into + // "http://localhost:8080/xqtl" + String appLocation = requestURL.substring(0, requestURL.length() - (requestURI.length() - appName.length())); + + // turns "http://localhost:8080/xqtl/api/R" into "/api/R" + String requestPath = requestURL.substring(requestURL.length() - (requestURI.length() - appName.length())); + + for (String servicePath : services.keySet()) { - if (path.startsWith(p)) + if (requestPath.startsWith(servicePath)) { long startTime = System.currentTimeMillis(); + Date date = new Date(); // if mapped to "/", we assume we are serving out a file, and do // not manage security/connections - if (p.equals("/")) + if (servicePath.equals("/")) { - System.out.println("> serving file: " + path); - services.get(p).handleRequest(request, response); + System.out.println("> serving file: " + requestPath); + services.get(servicePath).handleRequest(request, response); } else { - System.out.println("> new request to '" + path + "' from " + request.getRequest().getRemoteHost() - + " handled by " + services.get(p).getClass().getSimpleName() + " mapped on path " + p); - System.out.println("request content: " + request.toString()); + System.out.println("> new request \"" + requestPath + "\" from " + + request.getRequest().getRemoteHost() + " at " + dateFormat.format(date) + " handled by " + + services.get(servicePath).getClass().getSimpleName() + " mapped on path " + servicePath); + System.out.println("request fields: " + request.toString()); UUID connId = getSecuredDatabase(request); @@ -126,13 +162,18 @@ public void handleRequest(MolgenisRequest request, MolgenisResponse response) th + (request.getDatabase().getLogin().isAuthenticated() ? "authenticated as " + request.getDatabase().getLogin().getUserName() : "not authenticated")); - request.setRequestPath(path); // the path that was requested - request.setServicePath(p); // the path mapping used to - // handle the request + // e.g. "http://localhost:8080/xqtl" + request.setAppLocation(appLocation); + + // e.g. "/api/R/" + request.setServicePath(servicePath); + + // e.g. "/api/R/source.R" + request.setRequestPath(requestPath); try { - services.get(p).handleRequest(request, response); + services.get(servicePath).handleRequest(request, response); } finally { @@ -197,61 +238,67 @@ protected void manageConnection(UUID connId, long startTime) throws DatabaseExce protected void createLogger(MolgenisOptions mo) throws ServletException { - // try{ - // if(StringUtils.isEmpty(mo.log4j_properties_uri)) { - // //get logger and remove appenders added by classpath JARs. (= evil) - // Logger rootLogger = Logger.getRootLogger(); - // rootLogger.removeAllAppenders(); - // - // //the pattern used to format the logger output - // PatternLayout pattern = new PatternLayout("%-4r %-5p [%c] %m%n"); - // - // //get the level from the molgenis options - // rootLogger.setLevel(mo.log_level); - // - // //console appender - // if(mo.log_target.equals(MolgenisOptions.LogTarget.CONSOLE)) - // { - // rootLogger.addAppender(new ConsoleAppender(pattern)); - // System.out.println("Log4j CONSOLE appender added log level " + - // mo.log_level); - // } - // - // //file appender - // if(mo.log_target.equals(MolgenisOptions.LogTarget.FILE)) - // { - // RollingFileAppender fa = new RollingFileAppender(pattern, - // "logger.out"); - // fa.setMaximumFileSize(100000000); //100MB - // rootLogger.addAppender(fa); - // System.out.println("Log4j FILE appender added with level " + - // mo.log_level + ", writing to: " + new - // File(fa.getFile()).getAbsolutePath()); - // } - // - // //add no appender at all - // if(mo.log_target.equals(MolgenisOptions.LogTarget.OFF)) - // { - // System.out.println("Log4j logger turned off"); - // } - // } else { - // ClassLoader loader = this.getClass().getClassLoader(); - // URL urlLog4jProp = loader.getResource(mo.log4j_properties_uri); - // if(urlLog4jProp == null) { - // System.out.println(String.format("*** Incorrect log4j_properties_uri : '%s' in Molgenis properties file, so initializing log4j with BasicConfigurator", - // urlLog4jProp)); - // BasicConfigurator.configure(); - // } else { - // System.out.println(String.format("*** Log4j initializing with config file %s", - // urlLog4jProp)); - // PropertyConfigurator.configure(urlLog4jProp); - // } - // } - // } - // catch(Exception e) - // { - // throw new ServletException(e); - // } + try + { + if (StringUtils.isEmpty(mo.log4j_properties_uri)) + { + // get logger and remove appenders added by classpath JARs. (= + // evil) + Logger rootLogger = Logger.getRootLogger(); + rootLogger.removeAllAppenders(); + + // the pattern used to format the logger output + PatternLayout pattern = new PatternLayout("%-4r %-5p [%c] %m%n"); + + // get the level from the molgenis options + rootLogger.setLevel(mo.log_level); + + // console appender + if (mo.log_target.equals(MolgenisOptions.LogTarget.CONSOLE)) + { + rootLogger.addAppender(new ConsoleAppender(pattern)); + System.out.println("Log4j CONSOLE appender added log level " + mo.log_level); + } + + // file appender + if (mo.log_target.equals(MolgenisOptions.LogTarget.FILE)) + { + RollingFileAppender fa = new RollingFileAppender(pattern, "logger.out"); + fa.setMaximumFileSize(100000000); // 100MB + rootLogger.addAppender(fa); + System.out.println("Log4j FILE appender added with level " + mo.log_level + ", writing to: " + + new File(fa.getFile()).getAbsolutePath()); + } + + // add no appender at all + if (mo.log_target.equals(MolgenisOptions.LogTarget.OFF)) + { + System.out.println("Log4j logger turned off"); + } + } + else + { + ClassLoader loader = this.getClass().getClassLoader(); + URL urlLog4jProp = loader.getResource(mo.log4j_properties_uri); + if (urlLog4jProp == null) + { + System.out + .println(String + .format("*** Incorrect log4j_properties_uri : '%s' in Molgenis properties file, so initializing log4j with BasicConfigurator", + urlLog4jProp)); + BasicConfigurator.configure(); + } + else + { + System.out.println(String.format("*** Log4j initializing with config file %s", urlLog4jProp)); + PropertyConfigurator.configure(urlLog4jProp); + } + } + } + catch (Exception e) + { + throw new ServletException(e); + } } // private void printSessionInfo(HttpSession session) diff --git a/src/org/molgenis/framework/server/MolgenisRequest.java b/src/org/molgenis/framework/server/MolgenisRequest.java index 71f0d0609..a199c38ea 100644 --- a/src/org/molgenis/framework/server/MolgenisRequest.java +++ b/src/org/molgenis/framework/server/MolgenisRequest.java @@ -10,9 +10,10 @@ public class MolgenisRequest extends HttpServletRequestTuple { Database db; - String servicePath; - String requestPath; - + String servicePath; // e.g. "/api/R/" + String requestPath; // e.g. "/api/R/source.R" + String appLocation; // e.g. "http://localhost:8080/xqtl" + public MolgenisRequest(HttpServletRequest request) throws Exception { super(request); @@ -45,8 +46,6 @@ public void setServicePath(String servicePath) this.servicePath = servicePath; } - - public String getRequestPath() { return requestPath; @@ -57,44 +56,58 @@ public void setRequestPath(String requestPath) this.requestPath = requestPath; } + public String getAppLocation() + { + return appLocation; + } + + public void setAppLocation(String appLocation) + { + this.appLocation = appLocation; + } + /** - * Special toString for MolgenisRequest - * Will break off large values, and hide passwords + * Special toString for MolgenisRequest Will break off large values, and + * hide passwords */ public String toString() { - if (this.getNrColumns() == 0) return "EMPTY REQUEST"; - String result = ""; + if (this.getNrColumns() == 0) return "NONE"; + StringBuilder strBuilder = new StringBuilder(); for (int columnIndex = 0; columnIndex < this.getNrColumns(); columnIndex++) { - - //take care of the value - String value = "NULL"; - if(getObject(columnIndex) != null) - { - value = getObject(columnIndex).toString(); - value = value.length() > 25 ? value.substring(0, 25) + ".." : value; - } - - //take care of the name + + // take care of the value + // String value = "NULL"; + // if (getObject(columnIndex) != null) + // { + // value = getObject(columnIndex).toString(); + // value = value.length() > 25 ? value.substring(0, 25) + ".." : + // value; + // } + + // take care of the name String name = columnIndex + ""; if (getColName(columnIndex) != null) { name = getColName(columnIndex); + strBuilder.append(name).append(' '); } - - //print name + value - if (name.toLowerCase().contains("password") || name.equals(MolgenisServiceAuthenticationHelper.LOGIN_PASSWORD)) - { - result += name + "='*****' "; - } - else - { - result += name + "='" + value + "' "; - } - + + // print name + value + // if (name.toLowerCase().contains("password") + // || + // name.equals(MolgenisServiceAuthenticationHelper.LOGIN_PASSWORD)) + // { + // result += name + "='*****' "; + // } + // else + // { + // result += name + "='" + value + "' "; + // } + } - return result; + return strBuilder.toString(); } } diff --git a/src/org/molgenis/framework/server/MolgenisService.java b/src/org/molgenis/framework/server/MolgenisService.java index 9f420a6fb..9a9a8edf6 100644 --- a/src/org/molgenis/framework/server/MolgenisService.java +++ b/src/org/molgenis/framework/server/MolgenisService.java @@ -13,15 +13,16 @@ * Classes should implement this interface if they are expecting calls that * alter state. * - * BIG DISCUSSION: should this be generalized to JAX-RS and JAX-WS based implementation? + * BIG DISCUSSION: should this be generalized to JAX-RS and JAX-WS based + * implementation? */ public interface MolgenisService { /** * HandleRequest is the standard way how MOLGENIS treats requests that come * in from a user interface (web, script). Typically these requests come - * from the web. - * s + * from the web. s + * * @param db * a MOLGENIS database that can be used by the service * @param request @@ -39,7 +40,6 @@ public interface MolgenisService * because of problems with file uploads in the request or * outputStream */ - public void handleRequest(MolgenisRequest request, - MolgenisResponse response) throws ParseException, DatabaseException, - IOException; + public void handleRequest(MolgenisRequest request, MolgenisResponse response) throws ParseException, + DatabaseException, IOException; } diff --git a/src/org/molgenis/framework/server/MolgenisServiceAuthenticationHelper.java b/src/org/molgenis/framework/server/MolgenisServiceAuthenticationHelper.java index 9db209d52..4b1d00f0f 100644 --- a/src/org/molgenis/framework/server/MolgenisServiceAuthenticationHelper.java +++ b/src/org/molgenis/framework/server/MolgenisServiceAuthenticationHelper.java @@ -7,41 +7,47 @@ import org.molgenis.framework.server.FrontControllerAuthenticator.LogoutStatus; /** - * Simple authentication GUI service for browser-accessed MolgenisServices. - * If you want to add login/logout and all security related checks in your - * MolgenisService, be sure to use the handleAuthentication(MolgenisRequest - * req, MolgenisResponse res) function below. Read its Javadoc for details. - * Remember that login is shared across MolgenisServices when accessed using - * the same session (i.e. don't close your browser), so when logged in via - * one service, you are also logged in for the others. - * + * Simple authentication GUI service for browser-accessed MolgenisServices. If + * you want to add login/logout and all security related checks in your + * MolgenisService, be sure to use the handleAuthentication(MolgenisRequest req, + * MolgenisResponse res) function below. Read its Javadoc for details. Remember + * that login is shared across MolgenisServices when accessed using the same + * session (i.e. don't close your browser), so when logged in via one service, + * you are also logged in for the others. + * */ public class MolgenisServiceAuthenticationHelper { - - public static String LOGIN_USER_NAME = "usr"; - public static String LOGIN_PASSWORD = "pwd"; + + public final static String LOGIN_USER_NAME = "usr"; + public final static String LOGIN_PASSWORD = "pwd"; static String LOGOUT_REQUEST = "logout"; /** - * Handles authentication in combination with a simple menu structure - * which guides and informs the user about his/her authentication status.

+ * Handles authentication in combination with a simple menu structure which + * guides and informs the user about his/her authentication status.
+ *
* * You should reuse this in every MolgenisService that uses authentication - * and is accessed through the browser, except the regular web GUI.

+ * and is accessed through the browser, except the regular web GUI.
+ *
+ * + * At the top of the handleRequest() you are implementing, put:
+ *
* - * At the top of the handleRequest() you are implementing, put:

+ * if(MolgenisServiceAuthenticationHelper.handleAuthentication(req, res) == + * false)
+ * {
+ * return;
+ * }
+ *
* - * if(MolgenisServiceAuthenticationHelper.handleAuthentication(req, res) == false)
- * {
- * return;
- * }

- * - * This will handle login and logout requests, and display a login box if the - * user is not authenticated. The important bit is the return: this prevents - * your service from executing any further when the user is not authenticated. - * HandleAuthentication() expects the string variables LOGIN_USER_NAME and LOGIN_PASSWORD in a login - * request, and the LOGOUT_REQUEST variable plus value for a logout request. + * This will handle login and logout requests, and display a login box if + * the user is not authenticated. The important bit is the return: + * this prevents your service from executing any further when the user is + * not authenticated. HandleAuthentication() expects the string variables + * LOGIN_USER_NAME and LOGIN_PASSWORD in a login request, and the + * LOGOUT_REQUEST variable plus value for a logout request. * * @param req * @param res @@ -51,37 +57,36 @@ public class MolgenisServiceAuthenticationHelper public static AuthStatus handleAuthentication(MolgenisRequest req, PrintWriter out) throws IOException { - - //login request - if(req.getString(LOGIN_USER_NAME) != null && req.getString(LOGIN_PASSWORD) != null ) + // login request + if (req.getString(LOGIN_USER_NAME) != null && req.getString(LOGIN_PASSWORD) != null) { String username = req.getString(LOGIN_USER_NAME); String password = req.getString(LOGIN_PASSWORD); - - LoginStatus login = FrontControllerAuthenticator.login(req, username, password); - - - if(login == LoginStatus.ALREADY_LOGGED_IN) + + LoginStatus login = FrontControllerAuthenticator.login(req, username, password); + + if (login == LoginStatus.ALREADY_LOGGED_IN) { - // reach this by using the 'back' button of the browser and click Login again :) + // reach this by using the 'back' button of the browser and + // click Login again :) String printMe = ""; printMe += ""; printMe += "
You are already logged in.
" + displayLogoutForm() + "
"; return new AuthStatus(false, printMe); } - else if(login == LoginStatus.SUCCESSFULLY_LOGGED_IN) + else if (login == LoginStatus.SUCCESSFULLY_LOGGED_IN) { String printMe = ""; printMe += "
Welcome, " + username + "!
"; return new AuthStatus(false, printMe); } - else if(login == LoginStatus.AUTHENTICATION_FAILURE) + else if (login == LoginStatus.AUTHENTICATION_FAILURE) { String printMe = ""; printMe += "
User or password unknown.
"; return new AuthStatus(false, printMe); } - else if(login == LoginStatus.EXCEPTION_THROWN) + else if (login == LoginStatus.EXCEPTION_THROWN) { String printMe = "An error occurred. Contact your administrator."; return new AuthStatus(false, printMe); @@ -91,29 +96,29 @@ else if(login == LoginStatus.EXCEPTION_THROWN) throw new IOException("Unknown login status: " + login); } } - - + // logout request - if(req.getString(LOGOUT_REQUEST) != null && req.getString(LOGOUT_REQUEST).equals(LOGOUT_REQUEST) ) + if (req.getString(LOGOUT_REQUEST) != null && req.getString(LOGOUT_REQUEST).equals(LOGOUT_REQUEST)) { LogoutStatus logout = FrontControllerAuthenticator.logout(req); - if(logout == LogoutStatus.ALREADY_LOGGED_OUT) + if (logout == LogoutStatus.ALREADY_LOGGED_OUT) { - // reach this by using the 'back' button of the browser and click Logout again :) + // reach this by using the 'back' button of the browser and + // click Logout again :) String printMe = ""; printMe += "
You already logged out.
"; return new AuthStatus(false, printMe); } - else if(logout == LogoutStatus.SUCCESSFULLY_LOGGED_OUT) + else if (logout == LogoutStatus.SUCCESSFULLY_LOGGED_OUT) { String printMe = ""; printMe += "
You are successfully logged out.
"; return new AuthStatus(false, printMe); - + } - else if(logout == LogoutStatus.EXCEPTION_THROWN) + else if (logout == LogoutStatus.EXCEPTION_THROWN) { String printMe = "An error occurred. Contact your administrator."; return new AuthStatus(false, printMe); @@ -123,9 +128,10 @@ else if(logout == LogoutStatus.EXCEPTION_THROWN) throw new IOException("Unknown logout status: " + logout); } } - - // regular request: check if user is authenticated, and if not, display login box - if(!req.getDatabase().getLogin().isAuthenticated()) + + // regular request: check if user is authenticated, and if not, display + // login box + if (!req.getDatabase().getLogin().isAuthenticated()) { String printMe = "
"; printMe += ""; @@ -135,10 +141,10 @@ else if(logout == LogoutStatus.EXCEPTION_THROWN) printMe += ""; return new AuthStatus(true, printMe); } - + return new AuthStatus(true, ""); } - + /** * Display a simple logout button. Reusable in services. */ diff --git a/src/org/molgenis/framework/server/QueryRuleUtil.java b/src/org/molgenis/framework/server/QueryRuleUtil.java index c777a6846..0499b7d61 100644 --- a/src/org/molgenis/framework/server/QueryRuleUtil.java +++ b/src/org/molgenis/framework/server/QueryRuleUtil.java @@ -23,7 +23,7 @@ public static String toRESTstring(List rules) { if (rules.indexOf(r) > 0) { - if (QueryRule.Operator.OR.equals(previousRule)) + if (QueryRule.Operator.OR.equals(previousRule.getOperator())) { filters.append("\\|"); } @@ -39,7 +39,7 @@ public static String toRESTstring(List rules) if (r.getValue() instanceof String) filters.append("'" + r.getValue() + "'"); else filters.append(r.getValue()); - + previousRule = r; } diff --git a/src/org/molgenis/framework/server/ResourceServlet.java b/src/org/molgenis/framework/server/ResourceServlet.java index 59b83ffa9..e198d00c0 100644 --- a/src/org/molgenis/framework/server/ResourceServlet.java +++ b/src/org/molgenis/framework/server/ResourceServlet.java @@ -11,6 +11,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.molgenis.framework.ui.MolgenisOriginalStyle; @@ -30,22 +31,25 @@ public class ResourceServlet extends HttpServlet public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String resourcePath = request.getRequestURI().substring(request.getContextPath().length() + 1); - //logger.debug("retrieving file " + resourcePath); + // logger.debug("retrieving file " + resourcePath); + InputStream in = null; try { - InputStream in = null; if (resourcePath.startsWith("generated-res")) { - //strip the 'generated- - URLConnection conn = MolgenisOriginalStyle.class.getResource(resourcePath.substring(10)).openConnection(); - //File file = conn. - //logger.debug("serving file " + conn); + // strip the 'generated- + URLConnection conn = MolgenisOriginalStyle.class.getResource(resourcePath.substring(10)) + .openConnection(); + // File file = conn. + // logger.debug("serving file " + conn); // URLConnection conn = file.openConnection(); in = new BufferedInputStream(conn.getInputStream()); - //String mimetype = new MimetypesFileTypeMap().getContentType(resourcePath); - //logger.debug("mimetype for " + resourcePath + ": " + mimetype); - //response.setContentType(mimetype); + // String mimetype = new + // MimetypesFileTypeMap().getContentType(resourcePath); + // logger.debug("mimetype for " + resourcePath + ": " + + // mimetype); + // response.setContentType(mimetype); response.setHeader("Cache-Control", "max-age=0"); // allow some // client // side @@ -69,6 +73,10 @@ public void service(HttpServletRequest request, HttpServletResponse response) th e.printStackTrace(); logger.error("loading of failed: " + e); } + finally + { + IOUtils.closeQuietly(in); + } } } diff --git a/src/org/molgenis/framework/server/RestInterface.java b/src/org/molgenis/framework/server/RestInterface.java index ff771f374..3e5a29b5e 100644 --- a/src/org/molgenis/framework/server/RestInterface.java +++ b/src/org/molgenis/framework/server/RestInterface.java @@ -14,10 +14,10 @@ import org.molgenis.framework.ui.html.SelectInput; import org.molgenis.framework.ui.html.StringInput; import org.molgenis.util.CsvWriter; -import org.molgenis.util.TupleWriter; import org.molgenis.util.Entity; import org.molgenis.util.HttpServletRequestTuple; import org.molgenis.util.Tuple; +import org.molgenis.util.TupleWriter; /** * Implementation of the REST interface @@ -55,9 +55,9 @@ public static void handleRequest(HttpServletRequest request, HttpServletResponse logger.info("starting REST request " + request.getPathInfo()); long start_time = System.currentTimeMillis(); - - if(request.getPathInfo().startsWith("/find") || request.getPathInfo().startsWith("/count")) - handleRetrievalRequest(request,response, db); + + if (request.getPathInfo().startsWith("/find") || request.getPathInfo().startsWith("/count")) handleRetrievalRequest( + request, response, db); logger.info("servlet took: " + (System.currentTimeMillis() - start_time)); logger.info("------------"); @@ -99,8 +99,8 @@ private static void handleRetrievalRequest(HttpServletRequest request, HttpServl // execute query if (request.getPathInfo().startsWith("/count/")) { - if (rulesList != null) db.count(getClassForName(entityName), rulesList - .toArray(new QueryRule[rulesList.size()])); + if (rulesList != null) db.count(getClassForName(entityName), + rulesList.toArray(new QueryRule[rulesList.size()])); else { out.println(db.count(getClassForName(entityName))); @@ -112,8 +112,8 @@ private static void handleRetrievalRequest(HttpServletRequest request, HttpServl TupleWriter writer = new CsvWriter(out); // CsvWriter writer = new CsvFileWriter( new // File("c:/testout.txt") ); - if (rulesList != null) db.find(getClassForName(entityName), writer, rulesList - .toArray(new QueryRule[rulesList.size()])); + if (rulesList != null) db.find(getClassForName(entityName), writer, + rulesList.toArray(new QueryRule[rulesList.size()])); else { db.find(getClassForName(entityName), writer); @@ -148,7 +148,6 @@ private static Class getClassForName(String entityName) throws return (Class) Class.forName(entityName); } - private static List createQueryRulesFromRequest(HttpServletRequest request) throws Exception { List rulesList = new ArrayList(); @@ -156,17 +155,19 @@ private static List createQueryRulesFromRequest(HttpServletRequest re if (request.getQueryString() != null) { logger.debug("handle find query via http-get: " + request.getQueryString()); - rulesList = QueryRuleUtil.fromRESTstring(URLDecoder.decode(request.getQueryString(),"UTF-8")); + rulesList = QueryRuleUtil.fromRESTstring(URLDecoder.decode(request.getQueryString(), "UTF-8")); } // use 'post' else { Tuple requestTuple = new HttpServletRequestTuple(request); - String queryString = ""; + StringBuilder queryStringBuilder = new StringBuilder(); for (String name : requestTuple.getFields()) { - queryString += URLDecoder.decode(name,"UTF-8") + "=" + URLDecoder.decode(requestTuple.getString(name),"UTF-8"); + queryStringBuilder.append(URLDecoder.decode(name, "UTF-8")).append('='); + queryStringBuilder.append(URLDecoder.decode(requestTuple.getString(name), "UTF-8")); } + String queryString = queryStringBuilder.toString(); logger.debug("handle find query via http-post with parameters: " + queryString); rulesList = QueryRuleUtil.fromRESTstring(queryString); } @@ -206,8 +207,7 @@ private static void showSelectFilterDialogForEntity(Entity entity, PrintWriter o out.println(fieldInput.getHtml() + operatorInput.getHtml() + valueInput.getHtml()); out.println("
"); - out - .println(""); + out.println(""); out.println("TIP: notice how the url is bookmarkeable for future downloads!"); out.println("TIP: click 'save as...' and name it as '.txt' file."); diff --git a/src/org/molgenis/framework/server/ServeConfig.java b/src/org/molgenis/framework/server/ServeConfig.java index 9bb113cd9..b464b8858 100644 --- a/src/org/molgenis/framework/server/ServeConfig.java +++ b/src/org/molgenis/framework/server/ServeConfig.java @@ -21,8 +21,7 @@ public ServeConfig(ServletContext context) this(context, null, "undefined"); } - public ServeConfig(ServletContext context, - Hashtable initParams, String servletName) + public ServeConfig(ServletContext context, Hashtable initParams, String servletName) { this.context = context; this.init_params = initParams; diff --git a/src/org/molgenis/framework/server/Token.java b/src/org/molgenis/framework/server/Token.java index 6b78ee4cb..6c21a0993 100644 --- a/src/org/molgenis/framework/server/Token.java +++ b/src/org/molgenis/framework/server/Token.java @@ -9,7 +9,7 @@ public class Token implements Serializable private String userName; private Date expiresAt; private Date createdAt; - + public Token(String userName, Date createdAt, Date expiresAt) { super(); @@ -33,6 +33,4 @@ public Date getCreatedAt() return createdAt; } - - } diff --git a/src/org/molgenis/framework/server/TokenFactory.java b/src/org/molgenis/framework/server/TokenFactory.java index c3272a61b..79ebd1070 100644 --- a/src/org/molgenis/framework/server/TokenFactory.java +++ b/src/org/molgenis/framework/server/TokenFactory.java @@ -12,15 +12,16 @@ public class TokenFactory implements Serializable { private static final long serialVersionUID = -1669938881359317765L; private HashMap securityTokens; - + public TokenFactory() { this.securityTokens = new HashMap(); } - + /** - * Create a new token and put it in the map of all tokens. - * Returns the token ID that was given out for convenience. + * Create a new token and put it in the map of all tokens. Returns the token + * ID that was given out for convenience. + * * @param userName * @param validUntil * @return @@ -28,32 +29,33 @@ public TokenFactory() public String makeNewToken(String userName, Date validUntil) { // no tokens for anonymous - if(userName.equals("anonymous")) + if (userName.equals("anonymous")) { return null; } - //create a new token and put it in the map under a uuid + // create a new token and put it in the map under a uuid String uuid = UUID.randomUUID().toString(); - + Date now = new Date(); Token newToken = new Token(userName, now, validUntil); securityTokens.put(uuid, newToken); - - //cleanup invalid tokens + + // cleanup invalid tokens invalidateTokens(); - + return uuid; } - + /** * Delete the token which has this ID. + * * @param uuid * @throws Exception */ public void removeToken(String uuid) throws Exception { - if(securityTokens.containsKey(uuid)) + if (securityTokens.containsKey(uuid)) { securityTokens.remove(uuid); } @@ -62,39 +64,40 @@ public void removeToken(String uuid) throws Exception throw new Exception("The token you requested is not available"); } } - + /** * Get a list of token IDs that belong to this username. + * * @param userName * @return */ public List getTokenIdsForUser(String userName) { List res = new ArrayList(); - - for(String uuid : securityTokens.keySet()) + + for (String uuid : securityTokens.keySet()) { - if(securityTokens.get(uuid).getUserName().equals(userName)) + if (securityTokens.get(uuid).getUserName().equals(userName)) { res.add(uuid); } } - + return res; } - + /** - * Remove tokens that are expired. Called automatically on 1) any 'token login' attempt - * to prevent use of bad tokens 2) creation of new tokens. + * Remove tokens that are expired. Called automatically on 1) any 'token + * login' attempt to prevent use of bad tokens 2) creation of new tokens. */ public void invalidateTokens() { - for(String uuid : securityTokens.keySet()) + for (String uuid : securityTokens.keySet()) { Date expiresAt = securityTokens.get(uuid).getExpiresAt(); Date now = new Date(); - - if(expiresAt.before(now)) + + if (expiresAt.before(now)) { securityTokens.remove(uuid); } @@ -103,12 +106,13 @@ public void invalidateTokens() /** * Find out if there is a token for this ID. + * * @param uuid * @return */ public boolean checkIfTokenExists(String uuid) { - if(securityTokens.containsKey(uuid)) + if (securityTokens.containsKey(uuid)) { return true; } @@ -117,52 +121,56 @@ public boolean checkIfTokenExists(String uuid) /** * Get the token that belongs to this ID. + * * @param uuid * @return * @throws Exception */ public Token getToken(String uuid) throws Exception { - if(!securityTokens.containsKey(uuid)) + if (!securityTokens.containsKey(uuid)) { throw new Exception("The token you requested is not available"); } - + return securityTokens.get(uuid); - + } - + /** * Get all tokens for a username. + * * @param user * @return * @throws Exception */ - public Map getAllTokens(String user) throws Exception{ - + public Map getAllTokens(String user) throws Exception + { + List tokenIds = this.getTokenIdsForUser(user); Map tokenMap = new HashMap(); - - for(String uuid : tokenIds) + + for (String uuid : tokenIds) { Token t = this.getToken(uuid); tokenMap.put(uuid, t); } - + return tokenMap; } - + /** * Helper function: print tokens on sysout. */ public void printTokens() { - for(String uuid : securityTokens.keySet()) + for (String uuid : securityTokens.keySet()) { String user = securityTokens.get(uuid).getUserName(); String created = securityTokens.get(uuid).getCreatedAt().toString(); String expires = securityTokens.get(uuid).getExpiresAt().toString(); - System.out.println("TOKEN: " + uuid + " for user " + user + " created at " + created + " is valid until " + expires); + System.out.println("TOKEN: " + uuid + " for user " + user + " created at " + created + " is valid until " + + expires); } } } diff --git a/src/org/molgenis/framework/server/async/AsyncMolgenisContext.java b/src/org/molgenis/framework/server/async/AsyncMolgenisContext.java index fefc5068e..de20169b3 100644 --- a/src/org/molgenis/framework/server/async/AsyncMolgenisContext.java +++ b/src/org/molgenis/framework/server/async/AsyncMolgenisContext.java @@ -10,20 +10,16 @@ public class AsyncMolgenisContext extends MolgenisContext { private LoadingScreenFactory loadingScreenUUIDFactory; - - + public AsyncMolgenisContext(ServletConfig sc, DataSource ds, MolgenisOptions usedOptions, String variant) { super(sc, ds, usedOptions, variant); this.loadingScreenUUIDFactory = new LoadingScreenFactory(); } - public LoadingScreenFactory getLoadingScreenUUIDFactory() { return loadingScreenUUIDFactory; } - - - + } diff --git a/src/org/molgenis/framework/server/async/AsyncMolgenisFrontController.java b/src/org/molgenis/framework/server/async/AsyncMolgenisFrontController.java index dd99d7c2c..25023f957 100644 --- a/src/org/molgenis/framework/server/async/AsyncMolgenisFrontController.java +++ b/src/org/molgenis/framework/server/async/AsyncMolgenisFrontController.java @@ -12,17 +12,16 @@ import org.molgenis.framework.db.DatabaseException; import org.molgenis.framework.server.MolgenisFrontController; -public abstract class AsyncMolgenisFrontController extends MolgenisFrontController implements -AsyncMolgenisService +public abstract class AsyncMolgenisFrontController extends MolgenisFrontController implements AsyncMolgenisService { // helper vars private static final long serialVersionUID = -2141508157810793106L; Logger logger = Logger.getLogger(AsyncMolgenisFrontController.class); - + // map of all services for this app protected Map services; - - //context + + // context protected AsyncMolgenisContext context; // the one and only service() used in the molgenis app @@ -30,72 +29,77 @@ public void service(HttpServletRequest request, HttpServletResponse response) { try { - //wrap request and response - AsyncMolgenisRequest req = new AsyncMolgenisRequest(request, response); //TODO: Bad, but needed for redirection. DISCUSS. + // wrap request and response + AsyncMolgenisRequest req = new AsyncMolgenisRequest(request, response); // TODO: + // Bad, + // but + // needed + // for + // redirection. + // DISCUSS. AsyncMolgenisResponse res = new AsyncMolgenisResponse(response); - - //handle the request with current database + login + + // handle the request with current database + login this.handleRequest(req, res); } catch (Exception e) { - //TODO: send generic error page with details + // TODO: send generic error page with details logger.error(e.getMessage()); e.printStackTrace(); } } - + @Override - public void handleRequest(AsyncMolgenisRequest request, AsyncMolgenisResponse response) - throws ParseException, DatabaseException, IOException + public void handleRequest(AsyncMolgenisRequest request, AsyncMolgenisResponse response) throws ParseException, + DatabaseException, IOException { long startTime = System.currentTimeMillis(); HttpServletRequest req = request.getRequest(); - String path = req.getRequestURI().substring(context.getVariant().length()+1); - if(path.equals("")) path = "/"; - + String path = req.getRequestURI().substring(context.getVariant().length() + 1); + if (path.equals("")) path = "/"; + UUID id = UUID.randomUUID(); request.setLoadingScreenId(id); this.context.getLoadingScreenUUIDFactory().addLoadingId(id, path); services.get("/loadingscreen").handleRequest(request, response); - + for (String p : services.keySet()) { if (path.startsWith(p)) { - - - //if mapped to "/", we assume we are serving out a file, and do not manage security/connections - if(p.equals("/")) + + // if mapped to "/", we assume we are serving out a file, and do + // not manage security/connections + if (p.equals("/")) { System.out.println("> serving file: " + path); services.get(p).handleRequest(request, response); } else { - System.out.println("> new request to '"+path+"' handled by " + services.get(p).getClass().getSimpleName() + " mapped on path " + p); + System.out.println("> new request to '" + path + "' handled by " + + services.get(p).getClass().getSimpleName() + " mapped on path " + p); System.out.println("request content: " + request.toString()); - + UUID connId = getSecuredDatabase(request); - - System.out.println("database status: " + (request.getDatabase().getLogin().isAuthenticated() ? "authenticated as " - + request.getDatabase().getLogin().getUserName() : "not authenticated")); - + + System.out.println("database status: " + + (request.getDatabase().getLogin().isAuthenticated() ? "authenticated as " + + request.getDatabase().getLogin().getUserName() : "not authenticated")); + request.setServicePath(p); services.get(p).handleAsyncRequest(request, id); - manageConnection(connId,startTime); - - - //printSessionInfo(req.getSession()); - //context.getTokenFactory().printTokens(); + manageConnection(connId, startTime); + + // printSessionInfo(req.getSession()); + // context.getTokenFactory().printTokens(); } - + return; } - + } } - - } diff --git a/src/org/molgenis/framework/server/async/AsyncMolgenisRequest.java b/src/org/molgenis/framework/server/async/AsyncMolgenisRequest.java index c6bb450c9..0642a445a 100644 --- a/src/org/molgenis/framework/server/async/AsyncMolgenisRequest.java +++ b/src/org/molgenis/framework/server/async/AsyncMolgenisRequest.java @@ -10,9 +10,8 @@ public class AsyncMolgenisRequest extends MolgenisRequest { - UUID loadingScreenId; - + public AsyncMolgenisRequest(HttpServletRequest request) throws Exception { super(request); @@ -24,7 +23,7 @@ public AsyncMolgenisRequest(HttpServletRequest request, HttpServletResponse resp super(request, response); } - + public UUID getLoadingScreenId() { return loadingScreenId; @@ -35,6 +34,4 @@ public void setLoadingScreenId(UUID loadingScreenId) this.loadingScreenId = loadingScreenId; } - - } diff --git a/src/org/molgenis/framework/server/async/AsyncMolgenisResponse.java b/src/org/molgenis/framework/server/async/AsyncMolgenisResponse.java index 87fe72d56..ad84bf20f 100644 --- a/src/org/molgenis/framework/server/async/AsyncMolgenisResponse.java +++ b/src/org/molgenis/framework/server/async/AsyncMolgenisResponse.java @@ -9,12 +9,12 @@ public class AsyncMolgenisResponse { HttpServletResponse response; - + public AsyncMolgenisResponse() { } - + public AsyncMolgenisResponse(HttpServletResponse response) { this.response = response; @@ -22,7 +22,7 @@ public AsyncMolgenisResponse(HttpServletResponse response) public AsyncMolgenisResponse(UUID id, MolgenisContext mc) { - //this.response = (HttpServletResponse)new Harry(id,mc); + // this.response = (HttpServletResponse)new Harry(id,mc); } public HttpServletResponse getResponse() diff --git a/src/org/molgenis/framework/server/async/AsyncMolgenisService.java b/src/org/molgenis/framework/server/async/AsyncMolgenisService.java index 7884a3667..67c86a831 100644 --- a/src/org/molgenis/framework/server/async/AsyncMolgenisService.java +++ b/src/org/molgenis/framework/server/async/AsyncMolgenisService.java @@ -9,9 +9,8 @@ public interface AsyncMolgenisService { - public void handleRequest(AsyncMolgenisRequest request, - AsyncMolgenisResponse response) throws ParseException, DatabaseException, - IOException; + public void handleRequest(AsyncMolgenisRequest request, AsyncMolgenisResponse response) throws ParseException, + DatabaseException, IOException; public void handleAsyncRequest(AsyncMolgenisRequest request, UUID id); } diff --git a/src/org/molgenis/framework/server/async/LoadingScreenFactory.java b/src/org/molgenis/framework/server/async/LoadingScreenFactory.java index 8a8bbdd28..80856bf1d 100644 --- a/src/org/molgenis/framework/server/async/LoadingScreenFactory.java +++ b/src/org/molgenis/framework/server/async/LoadingScreenFactory.java @@ -3,23 +3,23 @@ import java.util.HashMap; import java.util.UUID; - - public class LoadingScreenFactory { - public class LoadingScreen{ + public class LoadingScreen + { public LoadingScreen(String a, String b) { - service=a; - output=b; + service = a; + output = b; } + public String service; public String output; - // public Response + // public Response } - - public HashMap ids = new HashMap(); + + public HashMap ids = new HashMap(); public boolean isActiveLoadingScreenId(UUID id) { @@ -32,11 +32,12 @@ public boolean isActiveLoadingScreenId(UUID id) public void addLoadingId(UUID id, String service) { - ids.put(id, new LoadingScreen(service,"")); + ids.put(id, new LoadingScreen(service, "")); } - - public LoadingScreen getLoadinScreen(UUID id){ - return ids.get(id); + + public LoadingScreen getLoadinScreen(UUID id) + { + return ids.get(id); } public LoadingScreen doneLoadingId(UUID id) @@ -45,7 +46,5 @@ public LoadingScreen doneLoadingId(UUID id) ids.remove(id); return s; } - - } diff --git a/src/org/molgenis/framework/server/async/MolgenisLoadingScreenService.java b/src/org/molgenis/framework/server/async/MolgenisLoadingScreenService.java index 126120b4b..69a7f647d 100644 --- a/src/org/molgenis/framework/server/async/MolgenisLoadingScreenService.java +++ b/src/org/molgenis/framework/server/async/MolgenisLoadingScreenService.java @@ -30,31 +30,33 @@ public MolgenisLoadingScreenService(AsyncMolgenisContext mc) * @param response */ @Override - public void handleRequest(AsyncMolgenisRequest req, AsyncMolgenisResponse res) - throws ParseException, DatabaseException, IOException + public void handleRequest(AsyncMolgenisRequest req, AsyncMolgenisResponse res) throws ParseException, + DatabaseException, IOException { - //HttpServletRequest request = req.getRequest(); + // HttpServletRequest request = req.getRequest(); HttpServletResponse response = res.getResponse(); UUID id = req.getLoadingScreenId(); try { PrintWriter out = response.getWriter(); - - if(mc.getLoadingScreenUUIDFactory().isActiveLoadingScreenId(id)) + + if (mc.getLoadingScreenUUIDFactory().isActiveLoadingScreenId(id)) { - out.println(""); + out.println(""); out.println("LOADING"); out.println(""); } - else{ + else + { LoadingScreen lscreen = mc.getLoadingScreenUUIDFactory().doneLoadingId(id); - out.println(""); + out.println(""); out.print(lscreen.output); out.println(""); } - - + } catch (Exception e) { @@ -67,7 +69,7 @@ public void handleRequest(AsyncMolgenisRequest req, AsyncMolgenisResponse res) public void handleAsyncRequest(AsyncMolgenisRequest request, UUID id) { // loading screen itself is not async ofcourse - + } } diff --git a/src/org/molgenis/framework/server/services/FileService.java b/src/org/molgenis/framework/server/services/FileService.java index e3e38671d..44c6b46d5 100644 --- a/src/org/molgenis/framework/server/services/FileService.java +++ b/src/org/molgenis/framework/server/services/FileService.java @@ -14,7 +14,6 @@ import Acme.Serve.FileServlet; - /// Java Servlet implementation of a HTTP file server. //

//Implements the "GET" and "HEAD" methods for files and directories. @@ -23,18 +22,19 @@ //Handles If-Modified-Since. //

-public class FileService extends FileServlet implements MolgenisService{ +public class FileService extends FileServlet implements MolgenisService +{ private MolgenisContext mc; - + public FileService(MolgenisContext mc) throws ServletException { this.mc = mc; - - //needed to pass MIME type mapping from webserver to servlet! - super.init(new ServeConfig( mc.getServletContext(), null, "/")); + + // needed to pass MIME type mapping from webserver to servlet! + super.init(new ServeConfig(mc.getServletContext(), null, "/")); } - + private static final long serialVersionUID = -2932420561105678721L; @Override @@ -49,7 +49,7 @@ public void handleRequest(MolgenisRequest request, MolgenisResponse response) th { throw new IOException(e); } - + } - + } \ No newline at end of file diff --git a/src/org/molgenis/framework/server/services/MolgenisBashService.java b/src/org/molgenis/framework/server/services/MolgenisBashService.java new file mode 100644 index 000000000..f5dd137aa --- /dev/null +++ b/src/org/molgenis/framework/server/services/MolgenisBashService.java @@ -0,0 +1,158 @@ +package org.molgenis.framework.server.services; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; + +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; +import org.molgenis.framework.server.MolgenisContext; +import org.molgenis.framework.server.MolgenisRequest; +import org.molgenis.framework.server.MolgenisResponse; +import org.molgenis.framework.server.MolgenisService; + +public class MolgenisBashService implements MolgenisService +{ + Logger logger = Logger.getLogger(MolgenisBashService.class); + + private MolgenisContext mc; + + public MolgenisBashService(MolgenisContext mc) + { + this.mc = mc; + } + + /** + * Delegate to handle request for the R api. + * + * @param request + * @param response + * @throws IOException + */ + public void handleRequest(MolgenisRequest request, MolgenisResponse response) throws IOException + { + + // Utils.console("starting RApiServlet"); + OutputStream outs = response.getResponse().getOutputStream(); + PrintStream out = new PrintStream(new BufferedOutputStream(outs), false, "UTF8"); // 1.4 + + String s = ""; + + s += "server=" + + (request.getAppLocation().endsWith("/") ? request.getAppLocation() : request.getAppLocation() + "/") + + "\n"; + s += "\n"; + s += "messagebox=$( printf \"%90s\" );\n"; + s += "\n"; + s += "function printError {\n"; + s += " echo ${messagebox// /#}\n"; + s += " echo \"ERROR:\" $1\n"; + s += " echo ${messagebox// /#}\n"; + s += "}\n"; + s += "\n"; + s += "function printWarning {\n"; + s += " echo ${messagebox// /#}\n"; + s += " echo \"WARNING:\" $1\n"; + s += " echo ${messagebox// /#}\n"; + s += "}\n"; + s += "\n"; + s += "function MOLGENIS.login {\n"; + s += " if [ -z \"$1\" ]\n"; + s += " then\n"; + s += " printError \"Missing parameter: username\"\n"; + s += " return\n"; + s += " fi\n"; + s += " if [ -z \"$2\" ]\n"; + s += " then\n"; + s += " printError \"Missing parameter: password\"\n"; + s += " return\n"; + s += " fi\n"; + s += " curl --cookie-jar cookies.txt --user-agent Mozilla/4.0 --data \"__target=UserLogin&__action=Login&username=$1&password=$2\" $server\"molgenis.do\" -v -k -D header\n"; + s += "}\n"; + s += "\n"; + s += "function MOLGENIS.logout {\n"; + s += " curl --cookie-jar cookies.txt --user-agent Mozilla/4.0 --data \"__target=UserLogin&__action=Logout\" $server\"molgenis.do\" -v -k -D header\n"; + s += "}\n"; + s += "\n"; + s += "function getFile {\n"; + s += " if [ -z \"$1\" ]\n"; + s += " then\n"; + s += " printError \"Missing parameter: database file name\"\n"; + s += " return\n"; + s += " fi\n"; + s += " if [ -z \"$2\" ]\n"; + s += " then\n"; + s += " printError \"Missing parameter: local 'save as' file name\"\n"; + s += " return\n"; + s += " fi\n"; + s += " curl -b cookies.txt --user-agent Mozilla/4.0 $server\"downloadfile?name=$1\" -v > $2\n"; + s += "}\n"; + s += "\n"; + s += "function putFile {\n"; + s += " if [ -z \"$1\" ]\n"; + s += " then\n"; + s += " printError \"Missing parameter: local file name\"\n"; + s += " return\n"; + s += " fi\n"; + s += " if [ -z \"$2\" ]\n"; + s += " then\n"; + s += " printWarning \"Missing parameter: database 'save as' file name\"\n"; + s += " return\n"; + s += " fi\n"; + s += " if [ -z \"$3\" ]\n"; + s += " then\n"; + s += " printWarning \"No third parameter: you may need to provide more information to store this file, such as investigation or a type. E.g. add \\\"-F \\\"investigation_id=1\\\"\\\".\"\n"; + s += " fi\n"; + s += " curl -v -b cookies.txt --user-agent Mozilla/4.0 -F \"file=@$1\" -F \"name=$2\" $3 $server\"uploadfile\"\n"; + s += "}\n"; + s += "\n"; + s += "\n"; + s += "## EXAMPLE SCRIPT ##\n"; + s += "\n"; + s += "## essential: connect to the Bash API\n"; + s += "#curl --user-agent Mozilla/4.0 http://localhost:8080/xqtl_lifelines/api/bash -v -k -D header > bashapi.txt\n"; + s += "#source bashapi.txt\n"; + s += "\n"; + s += "## login as 'admin', password 'admin'\n"; + s += "#MOLGENIS.login admin admin\n"; + s += "\n"; + s += "## select some phenotype to analyse\n"; + s += "#pheno=Health19\n"; + s += "\n"; + s += "## download some genotypes\n"; + s += "#getFile llrp_fake_geno llrp_geno.ped\n"; + s += "#getFile llrp_fake_snp llrp_geno.map\n"; + s += "\n"; + s += "## download some phenotypes (custom, but uses server location)\n"; + s += "#curl -b cookies.txt --user-agent Mozilla/4.0 -v -F \'name=$pheno\' -F \'plinkformat=true\' $server\'downloadpheno\' > llrp_pheno_$pheno.txt\n"; + s += "\n"; + s += "## run some analysis\n"; + s += "#../geno/plink-1.07-mac-intel/plink --noweb --file llrp_geno --pheno llrp_pheno_$pheno.txt --assoc --maf 0.05 --hwe -0.001 --1 --allow-no-sex --out results_for_$pheno\n"; + s += "\n"; + s += "## upload some results\n"; + s += "#putFile results_for_$pheno.assoc results_for_$pheno.assoc \'-F \'investigation_name=LifeLines\' -F \'investigation_id=1\' -F \'type=InvestigationFile\' -F \'description=Plink_assoc_results\'\'\n"; + s += "\n"; + s += "## logout\n"; + s += "#MOLGENIS.logout\n"; + s += "\n"; + + writeResponse(response, s, out); + // Utils.console("closed & flushed"); + + } + + private void writeResponse(MolgenisResponse response, String responseLine, PrintStream out) throws IOException + { + response.getResponse().setStatus(HttpServletResponse.SC_OK); + response.getResponse().setContentLength(responseLine.length()); + response.getResponse().setCharacterEncoding("UTF8"); + response.getResponse().setContentType("text/plain"); + out.print(responseLine); + out.flush(); + out.close(); + response.getResponse().flushBuffer(); + } + +} diff --git a/src/org/molgenis/framework/server/services/MolgenisCleanTmpDirService.java b/src/org/molgenis/framework/server/services/MolgenisCleanTmpDirService.java index ec739c306..982ed11e9 100644 --- a/src/org/molgenis/framework/server/services/MolgenisCleanTmpDirService.java +++ b/src/org/molgenis/framework/server/services/MolgenisCleanTmpDirService.java @@ -56,8 +56,8 @@ class CleanTmpDirProcess implements Runnable public void run() { boolean noExceptions = true; - - //10 sec delay after starting the server + + // 10 sec delay after starting the server try { Thread.sleep(10000); @@ -68,8 +68,7 @@ public void run() e.printStackTrace(); noExceptions = false; } - - + while (noExceptions) { try @@ -82,50 +81,54 @@ public void run() long curDate = new Date().getTime(); long maxAge = 1000 * 60 * 60 * mfa; - + for (File f : tmpDir.listFiles()) { // TODO: directory recursion.. -// if (!f.isDirectory()) -// { - long lastMod = f.lastModified(); - long age = curDate - lastMod; - -// System.out.println("lastMod: " + lastMod); -// System.out.println("curDate: " + curDate); -// System.out.println("age: " + age); -// System.out.println("maxAge: " + maxAge); - - if (age > maxAge) - { - System.out.println("MolgenisCleanTmpDirService: tmp file " + f.getName() + " is older than " + mfa + " hours, deleting..."); - FileUtils.deleteQuietly(f); - } - else - { -// System.out.println(f.getAbsolutePath() + " is younger than " + maxAge + " msec"); - } -// } + // if (!f.isDirectory()) + // { + long lastMod = f.lastModified(); + long age = curDate - lastMod; + + // System.out.println("lastMod: " + lastMod); + // System.out.println("curDate: " + curDate); + // System.out.println("age: " + age); + // System.out.println("maxAge: " + maxAge); + + if (age > maxAge) + { + System.out.println("MolgenisCleanTmpDirService: tmp file " + f.getName() + " is older than " + + mfa + " hours, deleting..."); + FileUtils.deleteQuietly(f); + } + else + { + // System.out.println(f.getAbsolutePath() + + // " is younger than " + maxAge + " msec"); + } + // } } } catch (Exception e) { - System.out.println("SEVERE: Breaking execution of CleanTmpDirProcess! InterruptedException on file delete"); + System.out + .println("SEVERE: Breaking execution of CleanTmpDirProcess! InterruptedException on file delete"); e.printStackTrace(); noExceptions = false; } - + long sleepTime = 1000 * hox; System.out.println("MolgenisCleanTmpDirService: going to sleep for " + hox + " seconds.."); - + try { Thread.sleep(sleepTime); } catch (InterruptedException e) { - System.out.println("SEVERE: Breaking execution of CleanTmpDirProcess! InterruptedException on thread sleep"); + System.out + .println("SEVERE: Breaking execution of CleanTmpDirProcess! InterruptedException on thread sleep"); e.printStackTrace(); noExceptions = false; } diff --git a/src/org/molgenis/framework/server/services/MolgenisCleanTmpDirServiceQuartz.java b/src/org/molgenis/framework/server/services/MolgenisCleanTmpDirServiceQuartz.java index 44fd002d4..190cdb40e 100644 --- a/src/org/molgenis/framework/server/services/MolgenisCleanTmpDirServiceQuartz.java +++ b/src/org/molgenis/framework/server/services/MolgenisCleanTmpDirServiceQuartz.java @@ -46,45 +46,45 @@ public MolgenisCleanTmpDirServiceQuartz(MolgenisContext mc) { try { - + CleanTmpDirTask task = new CleanTmpDirTask(); - - //specify your sceduler task details - JobDetail job = new JobDetail(); - job.setName("cleanTmpDirJob"); - job.setJobClass(CleanTmpDirJob.class); - - @SuppressWarnings("unchecked") + + // specify your sceduler task details + JobDetail job = new JobDetail(); + job.setName("cleanTmpDirJob"); + job.setJobClass(CleanTmpDirJob.class); + + @SuppressWarnings("unchecked") Map dataMap = job.getJobDataMap(); - dataMap.put("cleanTmpDirTask", task); - - //configure the scheduler time - SimpleTrigger trigger = new SimpleTrigger(); - trigger.setName("runMeJobTesting"); - trigger.setStartTime(new Date(System.currentTimeMillis() + 1000)); - trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY); - trigger.setRepeatInterval(30000); - + dataMap.put("cleanTmpDirTask", task); + + // configure the scheduler time + SimpleTrigger trigger = new SimpleTrigger(); + trigger.setName("runMeJobTesting"); + trigger.setStartTime(new Date(System.currentTimeMillis() + 1000)); + trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY); + trigger.setRepeatInterval(30000); + Trigger t = TriggerUtils.makeMinutelyTrigger(); t.setStartTime(new Date()); t.setName("MolgenisCleanTmpDirServiceTrigger"); - - //schedule it + + // schedule it SchedulingService schedulingService = mc.getSchedulingService(); -// Scheduler scheduler = mc.getScheduler(); - -// if(!scheduler.isStarted()) -// { -// throw new SchedulerException("Scheduler is not active"); -// } -// -// scheduler.start(); -// scheduler.scheduleJob(job, t); + // Scheduler scheduler = mc.getScheduler(); + + // if(!scheduler.isStarted()) + // { + // throw new SchedulerException("Scheduler is not active"); + // } + // + // scheduler.start(); + // scheduler.scheduleJob(job, t); HashMap dataMap2 = new HashMap(); -// dataMap2.put("cleanTmpDirTask", task); + // dataMap2.put("cleanTmpDirTask", task); schedulingService.scheduleOnce(dataMap2, CleanTmpDirJob.class); -// schedulingService.shutdown(); - + // schedulingService.shutdown(); + System.out.println("MolgenisCleanTmpDirService initialized."); } diff --git a/src/org/molgenis/framework/server/services/MolgenisDataTableService.java b/src/org/molgenis/framework/server/services/MolgenisDataTableService.java index 5f372d4f3..1db47b972 100644 --- a/src/org/molgenis/framework/server/services/MolgenisDataTableService.java +++ b/src/org/molgenis/framework/server/services/MolgenisDataTableService.java @@ -26,11 +26,11 @@ public class MolgenisDataTableService implements MolgenisService { Logger logger = Logger.getLogger(MolgenisDataTableService.class); - //private MolgenisContext mc; + // private MolgenisContext mc; public MolgenisDataTableService(MolgenisContext mc) { -// this.mc = mc; + // this.mc = mc; } /** @@ -41,8 +41,8 @@ public MolgenisDataTableService(MolgenisContext mc) * @param response */ @Override - public void handleRequest(MolgenisRequest req, MolgenisResponse res) - throws ParseException, DatabaseException, IOException + public void handleRequest(MolgenisRequest req, MolgenisResponse res) throws ParseException, DatabaseException, + IOException { HttpServletResponse response = res.getResponse(); @@ -57,8 +57,7 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) } // get parameters - Class entityClass = req.getDatabase().getClassForName(req - .getString("entity")); + Class entityClass = req.getDatabase().getClassForName(req.getString("entity")); // iDisplayLenght = limit int iDisplayLength = 10; @@ -81,26 +80,24 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) // sorting // iSortCol_0 = sort column number // resolve using mDataProp_1='name' - String sortField = req.getString("mDataProp_" - + req.getString("iSortCol_0")); - boolean asc = "asc".equals(req.getString("sSortDir_0")) ? true - : false; + String sortField = req.getString("mDataProp_" + req.getString("iSortCol_0")); + boolean asc = "asc".equals(req.getString("sSortDir_0")) ? true : false; if (asc) q.sortASC(sortField); else q.sortDESC(sortField); // iTotalRecords is unfiltered count! int count = q.count(); - + // sSearch = filtering string - if(!"".equals(req.getString("sSearch"))) + if (!"".equals(req.getString("sSearch"))) { q.search(req.getString("sSearch")); } - - //filtered count + + // filtered count int filteredCount = q.count(); - + // iTotalDisplayRecords is filtered count // todo: implement filters q.offset(iDisplayStart); @@ -118,8 +115,7 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) Map values = new LinkedHashMap(); for (String field : e.getFields()) { - if (e.get(field) != null) values.put(field, e.get(field) - .toString()); + if (e.get(field) != null) values.put(field, e.get(field).toString()); else values.put(field, ""); } diff --git a/src/org/molgenis/framework/server/services/MolgenisDownloadService.java b/src/org/molgenis/framework/server/services/MolgenisDownloadService.java index 679002ca5..a645bffde 100644 --- a/src/org/molgenis/framework/server/services/MolgenisDownloadService.java +++ b/src/org/molgenis/framework/server/services/MolgenisDownloadService.java @@ -20,18 +20,17 @@ import org.molgenis.util.Entity; import org.molgenis.util.TupleWriter; - public class MolgenisDownloadService implements MolgenisService { Logger logger = Logger.getLogger(MolgenisDownloadService.class); - + private MolgenisContext mc; - + public MolgenisDownloadService(MolgenisContext mc) { this.mc = mc; } - + /** * Handle use of the download API. * @@ -42,23 +41,23 @@ public MolgenisDownloadService(MolgenisContext mc) * @param response */ @Override - public void handleRequest(MolgenisRequest req, MolgenisResponse res) - throws ParseException, DatabaseException, IOException + public void handleRequest(MolgenisRequest req, MolgenisResponse res) throws ParseException, DatabaseException, + IOException { logger.info("starting download " + req.getRequest().getPathInfo()); long start_time = System.currentTimeMillis(); - + res.getResponse().setBufferSize(10000); res.getResponse().setContentType("text/html; charset=UTF-8"); - + PrintWriter out = res.getResponse().getWriter(); Database db = req.getDatabase(); - + try { AuthStatus authStatus = MolgenisServiceAuthenticationHelper.handleAuthentication(req, out); - + if (!authStatus.isShowApi()) { out.println(""); @@ -67,19 +66,19 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) } else { - + String entityName = req.getRequest().getPathInfo().substring(req.getServicePath().length()); - + if (entityName.startsWith("/")) { entityName = entityName.substring(1); } - + if (entityName.equals("")) { out.println(""); out.println(authStatus.getPrintMe()); - if(req.getDatabase().getLogin().isAuthenticated()) + if (req.getDatabase().getLogin().isAuthenticated()) { out.println(MolgenisServiceAuthenticationHelper.displayLogoutForm()); } @@ -91,7 +90,7 @@ else if (req.getRequest().getQueryString() != null { out.println(""); out.println(authStatus.getPrintMe()); - if(req.getDatabase().getLogin().isAuthenticated()) + if (req.getDatabase().getLogin().isAuthenticated()) { out.println(MolgenisServiceAuthenticationHelper.displayLogoutForm()); } @@ -116,47 +115,37 @@ else if (req.getRequest().getQueryString() != null out.close(); db.close(); } - - logger.info("servlet took: " - + (System.currentTimeMillis() - start_time)); - logger.info("------------"); + logger.info("servlet took: " + (System.currentTimeMillis() - start_time)); + logger.info("------------"); } - - private void showFilterableDownload(PrintWriter out, String entityName, Database db) throws InstantiationException, IllegalAccessException, ClassNotFoundException + + private void showFilterableDownload(PrintWriter out, String entityName, Database db) throws InstantiationException, + IllegalAccessException, ClassNotFoundException { - //System.out.println("show 'set filters' dialogue"); + // System.out.println("show 'set filters' dialogue"); out.println("
"); - out.println("You choose to download '" - + entityName //FIXME: bad, hardcoded location! + out.println("You choose to download '" + entityName // FIXME: bad, + // hardcoded + // location! + "' data. (back)

Here you can set filters before downloading:
"); out.println("
Please log in:
"); - - String simpleEntityName = entityName.substring(entityName.lastIndexOf('.')+1); + + String simpleEntityName = entityName.substring(entityName.lastIndexOf('.') + 1); Class klazz = db.getClassForName(simpleEntityName); - + for (String field : ((Entity) klazz.newInstance()).getFields()) { - out.println(""); } out.println("
" + field - + "=" + field + "=
"); - out.println(""); + out.println(""); out.println("

"); @@ -164,46 +153,49 @@ private void showFilterableDownload(PrintWriter out, String entityName, Database out.println("TIP: click 'save as...' and name it as '.txt' file."); out.println(""); } - + private void showAvailableDownloads(PrintWriter out, Database db, MolgenisRequest req) throws DatabaseException { - //print message to indicate your are anonymous - if(!db.getLogin().isAuthenticated()) + // print message to indicate your are anonymous + if (!db.getLogin().isAuthenticated()) { out.println("You are currently browsing as anonymous.
"); } - + out.println("You can download these data:
"); out.println(""); - + for (org.molgenis.model.elements.Entity eClass : db.getMetaData().getEntities(false, false)) { String name = eClass.getName(); Class klazz = db.getClassForName(name); - //hide entities without read permission - if(db.getLogin().canRead(klazz)) + // hide entities without read permission + if (db.getLogin().canRead(klazz)) { out.println(""); - out.println(""); - out.println(""); + out.println(""); + out.println(""); out.println(""); } } out.println("
" - + name + "" - + "filter" + "" + name + "" + "filter" + + "
"); } - private List createQueryRules(MolgenisRequest req) throws Exception + private List createQueryRules(MolgenisRequest req, Class klazz) throws Exception { List rulesList = new ArrayList(); - + // use get if (req.getRequest().getQueryString() != null) { - //System.out.println("handle find query via http-get: " + request.getQueryString()); + // System.out.println("handle find query via http-get: " + + // request.getQueryString()); String[] ruleStrings = req.getRequest().getQueryString().split("&"); for (String rule : ruleStrings) @@ -212,71 +204,60 @@ private List createQueryRules(MolgenisRequest req) throws Exception if (ruleElements.length != 2) { - //this is OK: just a not-filled-in queryrule - //throw new Exception("cannot understand querystring " + rule + ", does not have 2 elements"); + // this is OK: just a not-filled-in queryrule + // throw new Exception("cannot understand querystring " + + // rule + ", does not have 2 elements"); } else if (ruleElements[1].startsWith("[")) { - ruleElements[1] = ruleElements[1].replace("%20", - " "); - String[] values = ruleElements[1].substring(1, - ruleElements[1].indexOf("]")).split(","); - rulesList.add(new QueryRule(ruleElements[0], - QueryRule.Operator.IN, values)); + ruleElements[1] = ruleElements[1].replace("%20", " "); + String[] values = ruleElements[1].substring(1, ruleElements[1].indexOf("]")).split(","); + rulesList.add(new QueryRule(ruleElements[0], QueryRule.Operator.IN, values)); } else { - if (ruleElements[1] != "" - && !"__submitbutton" - .equals(ruleElements[0])) rulesList - .add(new QueryRule(ruleElements[0], - QueryRule.Operator.EQUALS, - ruleElements[1])); + if (ruleElements[1] != "" && !"__submitbutton".equals(ruleElements[0])) rulesList + .add(new QueryRule(ruleElements[0], QueryRule.Operator.EQUALS, ruleElements[1])); } } } // use post else { - //System.out.println("handle find query via http-post with parameters: " + req.getFields()); - for (String name : req.getFields()) + // System.out.println("handle find query via http-post with parameters: " + // + req.getFields()); + for (String name : req.getFieldNames()) { - if (req.getString(name).startsWith("[")) - { - String[] values = req - .getString(name) - .substring( - 1, - req.getString(name) - .indexOf("]")).split(","); - rulesList.add(new QueryRule(name, - QueryRule.Operator.IN, values)); - } - else + if (klazz.newInstance().getFields().contains(name)) { - rulesList.add(new QueryRule(name, - QueryRule.Operator.EQUALS, req - .getString(name))); + if (req.getString(name).startsWith("[")) + { + String[] values = req.getString(name).substring(1, req.getString(name).indexOf("]")).split(","); + rulesList.add(new QueryRule(name, QueryRule.Operator.IN, values)); + } + else + { + rulesList.add(new QueryRule(name, QueryRule.Operator.EQUALS, req.getString(name))); + } } } } return rulesList; } - + private void executeQuery(PrintWriter out, MolgenisRequest req, Database db, String entityName) throws Exception { + + String simpleEntityName = entityName.substring(entityName.lastIndexOf('.') + 1); + Class klazz = db.getClassForName(simpleEntityName); + // create query rules - List rulesList = createQueryRules(req); + List rulesList = createQueryRules(req, klazz); // execute query TupleWriter writer = new CsvWriter(out); - - String simpleEntityName = entityName.substring(entityName.lastIndexOf('.')+1); - - Class klazz = db.getClassForName(simpleEntityName); - - db.find(klazz, writer, - rulesList.toArray(new QueryRule[rulesList.size()])); + + db.find(klazz, writer, rulesList.toArray(new QueryRule[rulesList.size()])); } } diff --git a/src/org/molgenis/framework/server/services/MolgenisGuiService.java b/src/org/molgenis/framework/server/services/MolgenisGuiService.java index 26b9f9e90..1a17e161c 100644 --- a/src/org/molgenis/framework/server/services/MolgenisGuiService.java +++ b/src/org/molgenis/framework/server/services/MolgenisGuiService.java @@ -5,12 +5,10 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; -import java.net.URL; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; @@ -25,8 +23,6 @@ import org.molgenis.framework.ui.ScreenModel; import org.molgenis.framework.ui.ScreenModel.Show; import org.molgenis.framework.ui.html.FileInput; -import org.molgenis.util.HtmlTools; -import org.molgenis.util.Tuple; public abstract class MolgenisGuiService { @@ -40,6 +36,16 @@ public MolgenisGuiService(MolgenisContext mc) this.mc = mc; } + /** keep track of window ids */ + // FIXME: still needed? + private static long newWindowId; + + public static long getNewWindowId() + { + newWindowId++; + return newWindowId; + } + public abstract ApplicationController createUserInterface(); /** @@ -87,37 +93,13 @@ public void handleRequest(MolgenisRequest request, MolgenisResponse response) th return; } appController = createUserInterface(); - - // determine the real application base URL (once) - if (StringUtils.startsWith(session.getServletContext().getServerInfo(), "Apache Tomcat")) - { - appController.setBaseUrl(request.getRequest().getRequestURL().toString()); - } - else - { - try - { - new getExposedIP(appController, request); - } - catch (Exception e) - { - throw new IOException(e); - } - } } // Always pass login to GUI appController.setLogin(userLogin); - // this should work unless complicated load balancing without proxy - // rewriting... - // molgenis.setBaseUrl(request.getRequest().getScheme() + "://" - // + request.getRequest().getServerName() + - // getPort(request.getRequest()) - // + request.getRequest().getContextPath()); - // handle request - try + try { if (Show.SHOW_JQGRID.equals(request.getString(FormModel.INPUT_SHOW))) @@ -243,7 +225,7 @@ else if (action.startsWith("download_xls_")) return; } - // handle request by reloading (...) + // handle request by reloading (...) appController.reload(db); // session are automatically synchronized... @@ -313,38 +295,3 @@ else if ("massupdate".equals(show)) } } } - -/** - * Seperate thread to find out what the outside IP address of the application - * is. Can take up to 60 secs if the server cannot be contacted but does not - * block the rest of the application this way. - * - */ -class getExposedIP implements Runnable -{ - private ApplicationController molgenis; - private Tuple request; - - getExposedIP(ApplicationController molgenis, Tuple request) - { - this.molgenis = molgenis; - this.request = request; - Thread t = new Thread(this); - t.start(); - } - - public void run() - { - try - { - String host = HtmlTools.getExposedIPAddress(); - URL reconstructedURL = HtmlTools.getExposedProjectURL(request, host, molgenis.getMolgenisContext() - .getVariant()); - molgenis.setBaseUrl(reconstructedURL.toString()); - } - catch (Exception e) - { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/org/molgenis/framework/server/services/MolgenisJqGridService.java b/src/org/molgenis/framework/server/services/MolgenisJqGridService.java index 6a4e5fe6d..a0d4464d5 100644 --- a/src/org/molgenis/framework/server/services/MolgenisJqGridService.java +++ b/src/org/molgenis/framework/server/services/MolgenisJqGridService.java @@ -49,7 +49,7 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) throws Pars // Get the requested page. By default grid sets this to 1. Integer page = req.getInt("page"); - if(page == null || page < 1) page = 1; + if (page == null || page < 1) page = 1; // get how many rows we want to have into the grid - rowNum // parameter in the grid @@ -60,7 +60,7 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) throws Pars // parameter - // after that the index from colModel String sortIndex = req.getString("sidx"); - + boolean sortAsc = "asc".equals(req.getString("sord")) ? true : false; // sorting order - at first time sortorder @@ -78,9 +78,9 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) throws Pars // create a query on entity Database db = req.getDatabase(); Query q = db.query(entityClass); - - //search? - if(!req.isNull("filter") && !"".equals(req.getString("filter"))) + + // search? + if (!req.isNull("filter") && !"".equals(req.getString("filter"))) { q.search(req.getString("filter").trim()); } @@ -92,21 +92,22 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) throws Pars int total_pages = 1; if (recordCount > 0 && limit > 0) { - total_pages = (int)(recordCount / limit) + 1; + total_pages = (int) (recordCount / limit) + 1; } - - // if for some reasons the requested page is greater than the total - // set the requested page to total page + + // if for some reasons the requested page is greater than the total + // set the requested page to total page if (page > total_pages) page = total_pages; // todo: implement filters q.limit(limit); - q.offset(page*limit - limit); - - //sorting - if(sortAsc) q.sortASC(sortIndex); - else q.sortDESC(sortIndex); - + q.offset(page * limit - limit); + + // sorting + if (sortAsc) q.sortASC(sortIndex); + else + q.sortDESC(sortIndex); + List result = q.find(); // { diff --git a/src/org/molgenis/framework/server/services/MolgenisRapiService.java b/src/org/molgenis/framework/server/services/MolgenisRapiService.java index 2e6815358..089f5f092 100644 --- a/src/org/molgenis/framework/server/services/MolgenisRapiService.java +++ b/src/org/molgenis/framework/server/services/MolgenisRapiService.java @@ -24,14 +24,14 @@ public class MolgenisRapiService implements MolgenisService { Logger logger = Logger.getLogger(MolgenisRapiService.class); - + private MolgenisContext mc; - + public MolgenisRapiService(MolgenisContext mc) { this.mc = mc; } - + /** * Delegate to handle request for the R api. * @@ -39,179 +39,189 @@ public MolgenisRapiService(MolgenisContext mc) * @param response * @throws IOException */ - public void handleRequest(MolgenisRequest request, - MolgenisResponse response) throws IOException + public void handleRequest(MolgenisRequest request, MolgenisResponse response) throws IOException { - //as used in /molgenis/src/org/molgenis/generators/R/RApiGen.R.ftl, must match! - String pwdString = MolgenisServiceAuthenticationHelper.LOGIN_PASSWORD; - String usrString = MolgenisServiceAuthenticationHelper.LOGIN_USER_NAME; - - //Utils.console("starting RApiServlet"); - OutputStream outs = response.getResponse().getOutputStream(); - PrintStream out = new PrintStream(new BufferedOutputStream(outs), false, "UTF8"); // 1.4 - - if(request.getString(usrString) != null && request.getString(pwdString) != null ) + // as used in /molgenis/src/org/molgenis/generators/R/RApiGen.R.ftl, + // must match! + String pwdString = MolgenisServiceAuthenticationHelper.LOGIN_PASSWORD; + String usrString = MolgenisServiceAuthenticationHelper.LOGIN_USER_NAME; + + // Utils.console("starting RApiServlet"); + OutputStream outs = response.getResponse().getOutputStream(); + PrintStream out = new PrintStream(new BufferedOutputStream(outs), false, "UTF8"); // 1.4 + + if (request.getString(usrString) != null && request.getString(pwdString) != null) + { + String usr = request.getString(usrString); + String pwd = request.getString(pwdString); + + LoginStatus login = FrontControllerAuthenticator.login(request, usr, pwd); + + String responseLine; + if (login == LoginStatus.ALREADY_LOGGED_IN) + { + responseLine = "You are already logged in. Log out first."; + } + else if (login == LoginStatus.SUCCESSFULLY_LOGGED_IN) + { + responseLine = "Welcome, " + usr + "!"; + } + else if (login == LoginStatus.AUTHENTICATION_FAILURE) + { + responseLine = "User or password unknown."; + } + else if (login == LoginStatus.EXCEPTION_THROWN) + { + responseLine = "An error occurred. Contact your administrator."; + } + else + { + throw new IOException("Unknown login status: " + login); + } + + writeResponse(response, responseLine, out); + return; + } + + if (request.getString("logout") != null && request.getString("logout").equals("logout")) + { + + LogoutStatus logout = FrontControllerAuthenticator.logout(request); + + String responseLine; + if (logout == LogoutStatus.ALREADY_LOGGED_OUT) + { + responseLine = "You are already logged out. Log in first."; + } + else if (logout == LogoutStatus.SUCCESSFULLY_LOGGED_OUT) + { + responseLine = "You are successfully logged out."; + } + else if (logout == LogoutStatus.EXCEPTION_THROWN) + { + responseLine = "An error occurred. Contact your administrator."; + } + else + { + throw new IOException("Unknown logout status: " + logout); + } + + writeResponse(response, responseLine, out); + return; + } + + String filename = request.getRequestPath().substring(request.getServicePath().length()); + + // Utils.console("filename is now: " + filename); + + String s = ""; + + if (filename.startsWith("/")) + { + filename = filename.substring(1); + } + // if R file exists, return that + if (!filename.equals("") && !filename.endsWith(".R")) + { + // Utils.console("bad request: no R extension"); + s += "you can only load .R files\n"; + } + else if (filename.equals("")) + { + // Utils.console("getting default file"); + String rSource = request.getAppLocation() + request.getRequestPath(); + rSource = rSource.endsWith("/") ? rSource : rSource + "/"; + + // getRequestURL omits port! + s += ("#first time only: install RCurl and bitops\n"); + s += ("#install.packages(\"RCurl\", lib=\"~/libs\")\n"); + s += ("#install.packages(\"bitops\", lib=\"~/libs\")\n"); + s += ("\n"); + s += ("#load RCurl and bitops\n"); + s += ("library(bitops, lib.loc=\"~/libs\")\n"); + s += ("library(RCurl, lib.loc=\"~/libs\")\n"); + s += ("\n"); + s += ("#robust sourcing function for URLs\n"); + s += ("msource <- function(murl = \"http://127.0.0.1:8080/xqtl/api/R/\", verbose = TRUE){\n"); + s += (" if(verbose) cat(\"Creating connection\",murl,\"\\n\")\n"); + s += (" data <- getURLContent(murl)\n"); + s += (" t <- tempfile()\n"); + s += (" writeLines(data, con=t)\n"); + s += (" sys.source(t,globalenv())\n"); + s += (" unlink(t)\n"); + s += ("}\n"); + s += ("\n"); + s += ("#location of this R API and the application itself\n"); + s += ("r_api_location <- paste(\"" + rSource + "\")\n"); + s += ("app_location <- paste(\"" + request.getAppLocation() + "\")\n"); + s += ("\n"); + s += ("#load autogenerated R interfaces\n"); + s += ("source(\"" + rSource + "source.R\")\n"); + s += ("\n"); + s += ("#connect to the server\n"); + s += ("MOLGENIS.connect()\n"); + s += ("\n"); + s += ("#--> login/logout using:\n"); + s += ("# MOLGENIS.login(\"username\",\"password\")\n"); + s += ("# MOLGENIS.logout()\n"); + s += ("\n"); + + } + else + { + // otherwise return the default R code to source all + // Utils.console("getting specific R file"); + filename = filename.replace(".", "/"); + filename = filename.substring(0, filename.length() - 2) + ".R"; + + System.out.println("filename: " + filename); + + // map to hard drive, minus path app/servlet + Class FC = null; + try { - String usr = request.getString(usrString); - String pwd = request.getString(pwdString); - - LoginStatus login = FrontControllerAuthenticator.login(request, usr, pwd); - - String responseLine; - if(login == LoginStatus.ALREADY_LOGGED_IN) - { - responseLine = "You are already logged in. Log out first."; - } - else if(login == LoginStatus.SUCCESSFULLY_LOGGED_IN) - { - responseLine = "Welcome, " + usr + "!"; - } - else if(login == LoginStatus.AUTHENTICATION_FAILURE) - { - responseLine = "User or password unknown."; - } - else if(login == LoginStatus.EXCEPTION_THROWN) - { - responseLine = "An error occurred. Contact your administrator."; - } - else - { - throw new IOException("Unknown login status: " + login); - } - - writeResponse(response, responseLine, out); - return; + FC = Class.forName("app.servlet.FrontController"); } - - if(request.getString("logout") != null && request.getString("logout").equals("logout")) + catch (ClassNotFoundException e) { - - LogoutStatus logout = FrontControllerAuthenticator.logout(request); - - String responseLine; - if(logout == LogoutStatus.ALREADY_LOGGED_OUT) - { - responseLine = "You are already logged out. Log in first."; - } - else if(logout == LogoutStatus.SUCCESSFULLY_LOGGED_OUT) - { - responseLine = "You are successfully logged out."; - } - else if(logout == LogoutStatus.EXCEPTION_THROWN) - { - responseLine = "An error occurred. Contact your administrator."; - } - else - { - throw new IOException("Unknown logout status: " + logout); - } - - writeResponse(response, responseLine, out); - return; + throw new IOException(e); } - - - //Utils.console("URI path: " +request.getRequest().getRequestURI()); - String fullServicePath = request.getRequest().getServletPath() + request.getServicePath(); - //Utils.console("servlet path: " +fullServicePath); - int loc = request.getRequest().getRequestURI().lastIndexOf(fullServicePath); - String filename = request.getRequest().getRequestURI().substring(loc+fullServicePath.length()); - - //Utils.console("filename is now: " + filename); - - String s = ""; - - - if (filename.startsWith("/")){ - filename = filename.substring(1); + + File root = new File(FC.getResource("source.R").getFile()).getParentFile().getParentFile().getParentFile(); + System.out.println("root: " + root.getAbsolutePath()); + + System.out.println("root: " + root.getAbsolutePath()); + + if (filename.equals("source.R")) + { + root = new File(root.getAbsolutePath() + "/app/servlet"); } - // if R file exists, return that - if (!filename.equals("") && !filename.endsWith(".R")){ - //Utils.console("bad request: no R extension"); - s += "you can only load .R files\n"; - } else if (filename.equals("")) + File source = new File(root.getAbsolutePath() + "/" + filename); + + System.out.println("source: " + source.getAbsolutePath()); + + // up to root of app + // Utils.console("trying to load R file: " + filename + + // " from path " + source); + if (source.exists()) { - //Utils.console("getting default file"); - String localName = request.getRequest().getLocalName(); - if (localName.equals("0.0.0.0")) localName = "localhost"; - String server = "http://" + request.getRequest().getLocalName() + ":" + request.getRequest().getLocalPort() + "/"+mc.getVariant(); - String rSource = server + "/api/R/"; - // getRequestURL omits port! - s +=("#first time only: install RCurl and bitops\n"); - s +=("#install.packages(\"RCurl\", lib=\"~/libs\")\n"); - s +=("#install.packages(\"bitops\", lib=\"~/libs\")\n"); - s +=("\n"); - s +=("#load RCurl and bitops\n"); - s +=("library(bitops, lib.loc=\"~/libs\")\n"); - s +=("library(RCurl, lib.loc=\"~/libs\")\n"); - s +=("\n"); - s +=("#get server paths to R API\n"); - s +=("molgenispath <- paste(\"" + rSource + "\")\n"); - s +=("serverpath <- paste(\"" + server + "\")\n"); - s +=("\n"); - s +=("#load autogenerated R interfaces\n"); - s +=("source(\"" + rSource + "source.R\")\n"); - s +=("\n"); - s +=("#connect to the server\n"); - s +=("MOLGENIS.connect(\"" + server + "\")\n"); - s +=("\n"); - s +=("#--> login/logout using:\n"); - s +=("# MOLGENIS.login(\"username\",\"password\")\n"); - s +=("# MOLGENIS.logout()\n"); - s +=("\n"); - + String str = this.printScript(source.toURI().toURL()); + s += (str); } - else{ - // otherwise return the default R code to source all - //Utils.console("getting specific R file"); - filename = filename.replace(".", "/"); - filename = filename.substring(0, filename.length() - 2) + ".R"; - - System.out.println("filename: " + filename); - - //map to hard drive, minus path app/servlet - Class FC = null; - try - { - FC = Class.forName("app.servlet.FrontController"); - } - catch (ClassNotFoundException e) - { - throw new IOException(e); - } - - File root = new File(FC.getResource("source.R") - .getFile()).getParentFile().getParentFile().getParentFile(); - System.out.println("root: " + root.getAbsolutePath()); - - System.out.println("root: " + root.getAbsolutePath()); - - if (filename.equals("source.R")) - { - root = new File(root.getAbsolutePath() + "/app/servlet"); - } - File source = new File(root.getAbsolutePath() + "/" + filename); - - System.out.println("source: " + source.getAbsolutePath()); - - //up to root of app - //Utils.console("trying to load R file: " + filename + " from path " + source); - if(source.exists()){ - String str = this.printScript(source.toURI().toURL(), ""); - s +=(str); - }else{ - s +=("File '" + filename + "' not found\n"); - } - //Utils.console("done getting specific R file"); + else + { + s += ("File '" + filename + "' not found\n"); } - writeResponse(response, s, out); - //Utils.console("closed & flushed"); - - + // Utils.console("done getting specific R file"); + } + writeResponse(response, s, out); + // Utils.console("closed & flushed"); + } - private void writeResponse(MolgenisResponse response, String responseLine, PrintStream out) throws IOException{ - response.getResponse().setStatus(HttpServletResponse.SC_OK); + private void writeResponse(MolgenisResponse response, String responseLine, PrintStream out) throws IOException + { + response.getResponse().setStatus(HttpServletResponse.SC_OK); response.getResponse().setContentLength(responseLine.length()); response.getResponse().setCharacterEncoding("UTF8"); response.getResponse().setContentType("text/plain"); @@ -221,18 +231,23 @@ private void writeResponse(MolgenisResponse response, String responseLine, Print response.getResponse().flushBuffer(); } - private String printScript( URL source, String out ) throws IOException + private String printScript(URL source) throws IOException { - //Utils.console("reading file to be outputted"); + StringBuilder strBuilder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(source.openStream())); - String sourceLine; - while( (sourceLine = reader.readLine()) != null ) + try + { + String sourceLine; + while ((sourceLine = reader.readLine()) != null) + { + strBuilder.append(sourceLine).append('\n'); + } + } + finally { - out += sourceLine + "\n"; + reader.close(); } - reader.close(); - //Utils.console("done reading"); - return out; + return strBuilder.toString(); } - + } diff --git a/src/org/molgenis/framework/server/services/MolgenisRestService.java b/src/org/molgenis/framework/server/services/MolgenisRestService.java index 984a67d28..700dbca47 100644 --- a/src/org/molgenis/framework/server/services/MolgenisRestService.java +++ b/src/org/molgenis/framework/server/services/MolgenisRestService.java @@ -19,33 +19,32 @@ * * See http://cxf.apache.org/docs/jax-rs.html * http://cxf.apache.org/docs/jaxrs-services-configuration.html - * + * */ -public class MolgenisRestService extends CXFNonSpringJaxrsServlet implements MolgenisService +public class MolgenisRestService extends CXFNonSpringJaxrsServlet implements MolgenisService { private static final long serialVersionUID = -6699220792069809444L; Logger logger = Logger.getLogger(MolgenisRapiService.class); - Hashtable restParams; - + Hashtable restParams; + private MolgenisContext mc; - + public MolgenisRestService(MolgenisContext mc) { this.mc = mc; } - + public MolgenisRestService() throws ServletException { - restParams = new Hashtable(); + restParams = new Hashtable(); restParams.put("jaxrs.serviceClasses", "app.servlet.RestApi"); } - - public void handleRequest(MolgenisRequest r, - MolgenisResponse response) throws IOException + + public void handleRequest(MolgenisRequest r, MolgenisResponse response) throws IOException { try { - super.init(new ServeConfig( mc.getServletContext(), restParams, "/")); + super.init(new ServeConfig(mc.getServletContext(), restParams, "/")); super.service(r.getRequest(), response.getResponse()); throw new IOException(); } diff --git a/src/org/molgenis/framework/server/services/MolgenisSoapService.java b/src/org/molgenis/framework/server/services/MolgenisSoapService.java index 82bd004a3..4eb3fe33d 100644 --- a/src/org/molgenis/framework/server/services/MolgenisSoapService.java +++ b/src/org/molgenis/framework/server/services/MolgenisSoapService.java @@ -19,35 +19,34 @@ * * NOT WORKING, seems to get stuck on: * - * Dec 6, 2011 10:59:16 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse - * WARNING: WebApplicationException has been caught : no cause is available + * Dec 6, 2011 10:59:16 PM + * org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse WARNING: + * WebApplicationException has been caught : no cause is available * */ -public class MolgenisSoapService extends CXFNonSpringServlet implements - MolgenisService +public class MolgenisSoapService extends CXFNonSpringServlet implements MolgenisService { Logger logger = Logger.getLogger(MolgenisRapiService.class); private static final long serialVersionUID = 1L; private MolgenisContext mc; private boolean cxfLoaded; - + protected Database freshDatabase = null; public MolgenisSoapService(MolgenisContext mc) throws ServletException { this.mc = mc; - + super.init(mc.getServletConfig()); -// Hashtable params = new Hashtable(); -// params.put("jaxrs.serviceClasses", "app.servlet.SoapApi"); -// -// //ServletConfig sc = config; -// //super.init(sc); + // Hashtable params = new Hashtable(); + // params.put("jaxrs.serviceClasses", "app.servlet.SoapApi"); + // + // //ServletConfig sc = config; + // //super.init(sc); } - public void handleRequest(MolgenisRequest request, MolgenisResponse response) - throws IOException + public void handleRequest(MolgenisRequest request, MolgenisResponse response) throws IOException { freshDatabase = request.getDatabase(); @@ -58,7 +57,7 @@ public void handleRequest(MolgenisRequest request, MolgenisResponse response) super.loadBus(mc.getServletConfig()); Bus bus = this.getBus(); BusFactory.setDefaultBus(bus); - //FIXME: unhardcode path + // FIXME: unhardcode path Endpoint.publish("/api/soap", this.getSoapImpl()); this.cxfLoaded = true; } @@ -82,7 +81,6 @@ public void handleRequest(MolgenisRequest request, MolgenisResponse response) */ public Object getSoapImpl() throws ServletException { - throw new UnsupportedOperationException( - "Don't use this! Try the generated subclass 'SoapService' instead."); + throw new UnsupportedOperationException("Don't use this! Try the generated subclass 'SoapService' instead."); } } diff --git a/src/org/molgenis/framework/server/services/MolgenisTmpFileService.java b/src/org/molgenis/framework/server/services/MolgenisTmpFileService.java index fee44e21a..869c71013 100644 --- a/src/org/molgenis/framework/server/services/MolgenisTmpFileService.java +++ b/src/org/molgenis/framework/server/services/MolgenisTmpFileService.java @@ -10,79 +10,85 @@ import java.util.Hashtable; import org.apache.log4j.Logger; +import org.apache.poi.util.IOUtils; import org.molgenis.framework.server.MolgenisContext; import org.molgenis.framework.server.MolgenisRequest; import org.molgenis.framework.server.MolgenisResponse; import org.molgenis.framework.server.MolgenisService; /** - * Serve files from tmp dir. - * TODO: create best version for this type of service and use it everywhere. - * Though this one works OK. - * How it should really look: + * Serve files from tmp dir. TODO: create best version for this type of service + * and use it everywhere. Though this one works OK. How it should really look: * /molgenis_apps/modules/webserver/core/servlets/Servlet.java - * serveFile(HttpServletRequest req, HttpServletResponse res, boolean headOnly, File file) + * serveFile(HttpServletRequest req, HttpServletResponse res, boolean headOnly, + * File file) */ -public class MolgenisTmpFileService implements MolgenisService +public class MolgenisTmpFileService implements MolgenisService { Logger logger = Logger.getLogger(MolgenisRapiService.class); - Hashtable restParams; - + Hashtable restParams; + private MolgenisContext mc; - + public MolgenisTmpFileService(MolgenisContext mc) { this.mc = mc; } - public void handleRequest(MolgenisRequest request, - MolgenisResponse response) throws IOException + + public void handleRequest(MolgenisRequest request, MolgenisResponse response) throws IOException { String url = request.getRequest().getRequestURI(); - String variant = url.substring(url.indexOf("/")+1,url.indexOf("/tmpfile")); + String variant = url.substring(url.indexOf("/") + 1, url.indexOf("/tmpfile")); + InputStream in = null; OutputStream out = request.getResponse().getOutputStream(); - try{ - InputStream in = null; - - //get filename from used URL, so this is the only 'parameter' + try + { + // get filename from used URL, so this is the only 'parameter' String urlBase = variant + "/tmpfile/"; - String urlFile = url.substring(urlBase.length()+1); - + String urlFile = url.substring(urlBase.length() + 1); + File tmpDir = new File(System.getProperty("java.io.tmpdir")); - File filePath = new File(tmpDir.getAbsolutePath() + File.separatorChar + urlFile); - + File filePath = new File(tmpDir.getAbsolutePath() + File.separatorChar + urlFile); + URL localURL = filePath.toURI().toURL(); URLConnection conn = localURL.openConnection(); in = new BufferedInputStream(conn.getInputStream()); - -// String mimetype = new MimetypesFileTypeMap().getContentType(filePath); -// logger.debug("mimetype for " + localURL + ": " + mimetype); -// request.getResponse().setContentType(mimetype); - + + // String mimetype = new + // MimetypesFileTypeMap().getContentType(filePath); + // logger.debug("mimetype for " + localURL + ": " + mimetype); + // request.getResponse().setContentType(mimetype); + String mimetype = mc.getServletContext().getMimeType(filePath.getName()); if (mimetype != null) request.getResponse().setContentType(mimetype); - - request.getResponse().setContentLength((int)filePath.length()); + + request.getResponse().setContentLength((int) filePath.length()); byte[] buffer = new byte[2048]; - for( ;; ){ + for (;;) + { int nBytes = in.read(buffer); - if( nBytes <= 0 ) - break; + if (nBytes <= 0) break; out.write(buffer, 0, nBytes); } out.flush(); logger.info("serving " + request.getRequest().getRequestURI()); - }catch(Exception e ){ - byte[] header = ("Temporary file "+variant+" location error:\n").getBytes(); - out.write(header,0,header.length); + } + catch (Exception e) + { + byte[] header = ("Temporary file " + variant + " location error:\n").getBytes(); + out.write(header, 0, header.length); byte[] exception = ("loading of failed: " + e).getBytes(); - out.write(exception,0,exception.length); + out.write(exception, 0, exception.length); logger.error("loading of failed: " + e); - }finally{ - out.close(); } - + finally + { + IOUtils.closeQuietly(out); + IOUtils.closeQuietly(in); + } + } -} +} \ No newline at end of file diff --git a/src/org/molgenis/framework/server/services/MolgenisUploadService.java b/src/org/molgenis/framework/server/services/MolgenisUploadService.java index 453c48ba4..a77a82253 100644 --- a/src/org/molgenis/framework/server/services/MolgenisUploadService.java +++ b/src/org/molgenis/framework/server/services/MolgenisUploadService.java @@ -11,6 +11,7 @@ import java.text.ParseException; import java.util.Locale; +import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; @@ -31,44 +32,45 @@ public class MolgenisUploadService implements MolgenisService { Logger logger = Logger.getLogger(MolgenisDownloadService.class); - + /** the name of the datatype input */ - public static String INPUT_DATATYPE = "data_type_input"; + public static final String INPUT_DATATYPE = "data_type_input"; /** the name of the data input */ - public static String INPUT_DATA = "data_input"; + public static final String INPUT_DATA = "data_input"; /** boolean indicating file upload */ - public static String INPUT_FILE = "data_file"; + public static final String INPUT_FILE = "data_file"; /** the name of the submit button */ - public static String INPUT_SUBMIT = "submit_input"; + public static final String INPUT_SUBMIT = "submit_input"; /** the action input */ - public static String INPUT_ACTION = "data_action"; + public static final String INPUT_ACTION = "data_action"; /** indicating wether uploads should return added data */ - public static String INPUT_SILENT = "data_silent"; - -// private MolgenisContext mc; - + public static final String INPUT_SILENT = "data_silent"; + + // private MolgenisContext mc; + public MolgenisUploadService(MolgenisContext mc) { -// this.mc = mc; + // this.mc = mc; } + @Override - public void handleRequest(MolgenisRequest req, MolgenisResponse res) - throws ParseException, DatabaseException, IOException + public void handleRequest(MolgenisRequest req, MolgenisResponse res) throws ParseException, DatabaseException, + IOException { logger.info("starting upload " + req.getRequest().getPathInfo()); long start_time = System.currentTimeMillis(); - + res.getResponse().setBufferSize(10000); res.getResponse().setContentType("text/html; charset=UTF-8"); - + PrintWriter out = res.getResponse().getWriter(); Database db = req.getDatabase(); try { - + AuthStatus authStatus = MolgenisServiceAuthenticationHelper.handleAuthentication(req, out); - + if (!authStatus.isShowApi()) { out.println(""); @@ -82,7 +84,7 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) { out.println(""); authStatus.getPrintMe(); - if(req.getDatabase().getLogin().isAuthenticated()) + if (req.getDatabase().getLogin().isAuthenticated()) { out.println(MolgenisServiceAuthenticationHelper.displayLogoutForm()); } @@ -90,12 +92,11 @@ public void handleRequest(MolgenisRequest req, MolgenisResponse res) out.println(""); } // if no data provided, show csv input form - else if (req.getObject(INPUT_DATA) == null - && req.getObject(INPUT_FILE) == null) + else if (req.getObject(INPUT_DATA) == null && req.getObject(INPUT_FILE) == null) { out.println(""); authStatus.getPrintMe(); - if(req.getDatabase().getLogin().isAuthenticated()) + if (req.getDatabase().getLogin().isAuthenticated()) { out.println(MolgenisServiceAuthenticationHelper.displayLogoutForm()); } @@ -121,92 +122,88 @@ else if (req.getObject(INPUT_DATA) == null out.close(); db.close(); } - - logger.info("servlet took: " - + (System.currentTimeMillis() - start_time) + " ms"); + + logger.info("servlet took: " + (System.currentTimeMillis() - start_time) + " ms"); logger.info("------------"); - + } - + private void showDataTypeChoice(PrintWriter out, MolgenisRequest req) { out.println("
"); out.println("

Data upload (step 1)

"); out.println("Choose your data type."); - out.println("
"); - out.println(""); + out.println(""); out.println("
 
 
"); } - - private void showCsvInputForm(PrintWriter out, MolgenisRequest req) throws InstantiationException, IllegalAccessException + + private void showCsvInputForm(PrintWriter out, MolgenisRequest req) throws InstantiationException, + IllegalAccessException { - //String clazzName = - req.getString(INPUT_DATATYPE); - - //String simpleEntityName = clazzName.substring(clazzName.lastIndexOf('.')+1); - - //Class entityClass = req.getDatabase().getClassForName(simpleEntityName); - //Entity template = entityClass.newInstance(); - - out.println("
"); - out.println("

Data upload (step 2)

"); - out.println("Enter your data as CSV."); - - //FIXME: where is the CSV input form? - -// out -// .println(""); -// out -// .println(""); -// out.println("
"); - + // String clazzName = + req.getString(INPUT_DATATYPE); + + // String simpleEntityName = + // clazzName.substring(clazzName.lastIndexOf('.')+1); + + // Class entityClass = + // req.getDatabase().getClassForName(simpleEntityName); + // Entity template = entityClass.newInstance(); + + out.println("
"); + out.println("

Data upload (step 2)

"); + out.println("Enter your data as CSV."); + + // FIXME: where is the CSV input form? + + // out + // .println(""); + // out + // .println(""); + // out.println("
"); + } - + private void processRequest(MolgenisRequest req, PrintWriter out) throws Exception { NumberFormat formatter = NumberFormat.getInstance(Locale.US); logger.info("processing add/update/delete"); String action = null; // ADD, UPDATE, REMOVE Class entityClass = null; - + String clazzName = req.getString(INPUT_DATATYPE); - String simpleEntityName = clazzName.substring(clazzName.lastIndexOf('.')+1); + String simpleEntityName = clazzName.substring(clazzName.lastIndexOf('.') + 1); entityClass = req.getDatabase().getClassForName(simpleEntityName); // get the constants Tuple constants = new SimpleTuple(); for (String column : req.getFields()) { - if (!column.equals(INPUT_DATATYPE) - && !column.equals(INPUT_DATA) - && !column.equals(INPUT_ACTION) - && !column.equals(INPUT_SUBMIT) - && !req.getString(column).equals("")) + if (!column.equals(INPUT_DATATYPE) && !column.equals(INPUT_DATA) && !column.equals(INPUT_ACTION) + && !column.equals(INPUT_SUBMIT) && !req.getString(column).equals("")) { - constants.set(column, - req.getObject(column)); + constants.set(column, req.getObject(column)); } } action = req.getString(INPUT_ACTION); @@ -223,10 +220,8 @@ private void processRequest(MolgenisRequest req, PrintWriter out) throws Excepti if (action.equals("ADD")) { File temp = File.createTempFile("molgenis", "tab"); - TupleWriter writer = new CsvWriter(new PrintWriter( - new BufferedWriter(new FileWriter(temp)))); - if (req.getObject(INPUT_SILENT) != null - && req.getBool(INPUT_SILENT) == true) + TupleWriter writer = new CsvWriter(new PrintWriter(new BufferedWriter(new FileWriter(temp)))); + if (req.getObject(INPUT_SILENT) != null && req.getBool(INPUT_SILENT) == true) { writer.close(); writer = null; @@ -242,27 +237,29 @@ private void processRequest(MolgenisRequest req, PrintWriter out) throws Excepti else if (req.getObject(INPUT_FILE) != null) { logger.info("processing file upload..."); - nRowsChanged = db.add( - entityClass, - new CsvFileReader(req - .getFile(INPUT_FILE)), writer); + nRowsChanged = db.add(entityClass, new CsvFileReader(req.getFile(INPUT_FILE)), writer); } else { logger.error("no input data or input file provided."); out.print("ERROR: no input data or input file provided."); } - out.print("Uploaded " + formatter.format(nRowsChanged) - + " rows of " + entityClass.getCanonicalName() + out.print("Uploaded " + formatter.format(nRowsChanged) + " rows of " + entityClass.getCanonicalName() + "\n"); if (writer != null) writer.close(); - BufferedReader reader = new BufferedReader( - new FileReader(temp)); - String line = null; - while ((line = reader.readLine()) != null) + BufferedReader reader = new BufferedReader(new FileReader(temp)); + try + { + String line = null; + while ((line = reader.readLine()) != null) + { + out.println(line); + } + } + finally { - out.println(line); + IOUtils.closeQuietly(reader); } temp.delete(); } @@ -270,50 +267,30 @@ else if (action.equals("UPDATE")) { if (req.getObject(INPUT_DATA) != null) { - nRowsChanged = db.update( - entityClass, - new CsvStringReader(req - .getString(INPUT_DATA))); - out.print("Updated " - + formatter.format(nRowsChanged) - + " rows of " - + entityClass.getCanonicalName() + "\n"); + nRowsChanged = db.update(entityClass, new CsvStringReader(req.getString(INPUT_DATA))); + out.print("Updated " + formatter.format(nRowsChanged) + " rows of " + entityClass.getCanonicalName() + + "\n"); } else if (req.getObject(INPUT_FILE) != null) { - nRowsChanged = db.update( - entityClass, - new CsvFileReader(req - .getFile(INPUT_FILE))); - out.print("Updated " - + formatter.format(nRowsChanged) - + " rows of " - + entityClass.getCanonicalName() + "\n"); + nRowsChanged = db.update(entityClass, new CsvFileReader(req.getFile(INPUT_FILE))); + out.print("Updated " + formatter.format(nRowsChanged) + " rows of " + entityClass.getCanonicalName() + + "\n"); } } else if (action.equals("REMOVE")) { if (req.getObject(INPUT_DATA) != null) { - nRowsChanged = db.remove( - entityClass, - new CsvStringReader(req - .getString(INPUT_DATA))); - out.print("Removed " - + formatter.format(nRowsChanged) - + " rows of " - + entityClass.getCanonicalName() + "\n"); + nRowsChanged = db.remove(entityClass, new CsvStringReader(req.getString(INPUT_DATA))); + out.print("Removed " + formatter.format(nRowsChanged) + " rows of " + entityClass.getCanonicalName() + + "\n"); } else if (req.getObject(INPUT_FILE) != null) { - nRowsChanged = db.remove( - entityClass, - new CsvFileReader(req - .getFile(INPUT_FILE))); - out.print("Removed " - + formatter.format(nRowsChanged) - + " rows of " - + entityClass.getCanonicalName() + "\n"); + nRowsChanged = db.remove(entityClass, new CsvFileReader(req.getFile(INPUT_FILE))); + out.print("Removed " + formatter.format(nRowsChanged) + " rows of " + entityClass.getCanonicalName() + + "\n"); } } else diff --git a/src/org/molgenis/framework/server/services/MolgenisXrefService.java b/src/org/molgenis/framework/server/services/MolgenisXrefService.java index b2d8d21f2..c32344e99 100644 --- a/src/org/molgenis/framework/server/services/MolgenisXrefService.java +++ b/src/org/molgenis/framework/server/services/MolgenisXrefService.java @@ -147,21 +147,22 @@ private static String toJSon(final String xrefField, final List xref_lab for (int i = 0; i < records.size(); i++) { final String key = records.get(i).get(xrefField).toString(); - String value = ""; + StringBuilder valueBuilder = new StringBuilder(); for (int j = 0; j < xref_labels.size(); j++) { // hack - if (j > 0) value += "|"; - value += records.get(i).get(xref_labels.get(j)).toString(); + if (j > 0) valueBuilder.append('|'); + valueBuilder.append(records.get(i).get(xref_labels.get(j)).toString()); } - values.put(key, value); + values.put(key, valueBuilder.toString()); } // make JSON object string final List keyValuePairs = new ArrayList(); for (final Entry entry : values.entrySet()) { - keyValuePairs.add(String.format(JSON_KEY_VALUE, StringEscapeUtils.escapeJavaScript(entry.getKey()), StringEscapeUtils.escapeJavaScript(entry.getValue()))); + keyValuePairs.add(String.format(JSON_KEY_VALUE, StringEscapeUtils.escapeJavaScript(entry.getKey()), + StringEscapeUtils.escapeJavaScript(entry.getValue()))); } final String json = String.format("[%s]", StringUtils.join(keyValuePairs, ",")); return json; diff --git a/src/org/molgenis/framework/tupletable/AbstractFilterableTupleTable.java b/src/org/molgenis/framework/tupletable/AbstractFilterableTupleTable.java new file mode 100644 index 000000000..0e97e0fbc --- /dev/null +++ b/src/org/molgenis/framework/tupletable/AbstractFilterableTupleTable.java @@ -0,0 +1,97 @@ +package org.molgenis.framework.tupletable; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.Predicate; +import org.molgenis.framework.db.QueryRule; +import org.molgenis.framework.db.QueryRule.Operator; + +public abstract class AbstractFilterableTupleTable extends AbstractTupleTable implements FilterableTupleTable +{ + private List filters = new ArrayList(); + + protected AbstractFilterableTupleTable() + { + } + + protected AbstractFilterableTupleTable(List rules) + { + if (rules != null) + { + filters = rules; + } + } + + @Override + public void reset() + { + super.reset(); + + filters = new ArrayList(); + } + + @Override + public void setFilters(List rules) throws TableException + { + if (rules == null) + { + throw new NullPointerException("rules cannot be null"); + } + + for (final QueryRule r : rules) + { + verifyRulesRecursive(r); + } + filters = rules; + } + + private void verifyRulesRecursive(QueryRule rule) throws TableException + { + if (Operator.LIMIT.equals(rule.getOperator()) || Operator.LIMIT.equals(rule.getOperator())) + { + throw new TableException( + "TupleTable doesn't support LIMIT or OFFSET QueryRules; use setLimit and setOffset instead"); + } + + if (rule.getNestedRules() != null) for (QueryRule r : rule.getNestedRules()) + { + verifyRulesRecursive(r); + } + } + + @Override + public List getFilters() + { + return filters; + } + + @Override + public QueryRule getSortRule() + { + final QueryRule sortAsc = getRule(Operator.SORTASC); + if (sortAsc != null) + { + return sortAsc; + } + else + { + return getRule(Operator.SORTDESC); + } + } + + private QueryRule getRule(final Operator operator) + { + final QueryRule rule = (QueryRule) CollectionUtils.find(filters, new Predicate() + { + + @Override + public boolean evaluate(Object arg0) + { + return ((QueryRule) arg0).getOperator() == operator; + } + }); + return rule; + } +} diff --git a/src/org/molgenis/framework/tupletable/AbstractTupleTable.java b/src/org/molgenis/framework/tupletable/AbstractTupleTable.java new file mode 100644 index 000000000..75c28e9f5 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/AbstractTupleTable.java @@ -0,0 +1,342 @@ +package org.molgenis.framework.tupletable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.molgenis.model.elements.Field; +import org.molgenis.util.Tuple; + +public abstract class AbstractTupleTable implements TupleTable +{ + private int limit = 0; + private int offset = 0; + private int colOffset = 0; + private int colLimit = 0; + private boolean firstColumnFixed; + private Map columnByIndex; + + @Override + public void reset() + { + limit = 0; + offset = 0; + colOffset = 0; + colLimit = 0; + } + + @Override + public void setFirstColumnFixed(boolean firstColumnFixed) + { + this.firstColumnFixed = firstColumnFixed; + } + + @Override + public boolean isFirstColumnFixed() + { + return firstColumnFixed; + } + + @Override + public void hideColumn(String columnName) + { + try + { + // If the first column is fixed, it can not be hidden + if (isFirstColumnFixed() && getAllColumns().get(0).getName().equals(columnName)) + { + return; + } + + getColumnByName(columnName).setHidden(true); + } + catch (TableException e) + { + throw new RuntimeException(e); + } + } + + @Override + public void showColumn(String columnName) + { + try + { + getColumnByName(columnName).setHidden(false); + } + catch (TableException e) + { + throw new RuntimeException(e); + } + } + + @Override + public List getHiddenColumnNames() + { + List hiddenColumns = new ArrayList(); + try + { + for (Field column : getAllColumns()) + { + if (column.isHidden()) + { + hiddenColumns.add(column.getName()); + } + } + } + catch (TableException e) + { + throw new RuntimeException(e); + } + + return hiddenColumns; + } + + protected List getVisibleColumns() throws TableException + { + List visibleColumns = new ArrayList(); + for (Field column : getAllColumns()) + { + if (!column.isHidden()) + { + visibleColumns.add(column); + } + } + + return visibleColumns; + } + + @Override + public int getLimit() + { + return limit; + } + + @Override + public void setLimit(int limit) + { + if (limit < 0) throw new RuntimeException("limit cannot be < 0"); + this.limit = limit; + } + + @Override + public int getOffset() + { + return offset; + } + + @Override + public void setOffset(int offset) + { + if (offset < 0) throw new RuntimeException("offset cannot be < 0"); + this.offset = offset; + } + + @Override + public abstract List getAllColumns() throws TableException; + + @Override + public List getColumns() throws TableException + { + List result; + List columns = getVisibleColumns(); + + int colCount = columns.size(); + + if (getColOffset() > colCount) + { + setColOffset(colCount); + } + + if (isFirstColumnFixed()) + { + columns.remove(0); + colCount--; + } + + int colLimit = (int) (this.colLimit == 0 ? colCount - getColOffset() : getCurrentColumnPageSize(colCount)); + + if (getColOffset() > 0) + { + if (colLimit > 0) + { + result = columns.subList(getColOffset(), Math.min(getColOffset() + colLimit, colCount)); + } + else + { + result = columns.subList(getColOffset(), colCount); + } + } + else + { + if (colLimit > 0) + { + result = columns.subList(0, colLimit); + } + else + { + result = columns; + } + } + + if (isFirstColumnFixed()) + { + result.add(0, getAllColumns().get(0)); + } + + return result; + } + + @Override + public List getRows() throws TableException + { + List result = new ArrayList(); + for (Tuple t : this) + { + result.add(t); + } + return result; + } + + @Override + public Iterator iterator() + { + try + { + return new TupleTableIterator(this); + } + catch (TableException e) + { + throw new RuntimeException(e); + } + } + + @Override + public void close() throws TableException + { + // close resources if applicable + } + + @Override + public abstract int getCount() throws TableException; + + @Override + public int getColCount() throws TableException + { + return getVisibleColumns().size(); + } + + @Override + public void setColLimit(int limit) + { + if (limit < 0) throw new RuntimeException("colLimit cannot be < 0"); + this.colLimit = limit; + } + + @Override + public int getColLimit() + { + return colLimit; + } + + @Override + public int getColOffset() + { + return colOffset; + } + + @Override + public void setColOffset(int offset) + { + if (offset < 0) throw new RuntimeException("colOffset cannot be < 0"); + this.colOffset = offset; + } + + @Override + public void setLimitOffset(int limit, int offset) + { + this.setLimit(limit); + this.setOffset(offset); + } + + protected int getCurrentColumnPageSize(int colCount) throws TableException + { + int pageSize = getColLimit(); + + if (getColOffset() + pageSize > colCount) + { + pageSize = colCount - getColOffset(); + } + + return pageSize; + } + + /** + * Please override in subclass if you use the TupleTableIterator !!!! + * + * @throws TableException + */ + protected Tuple getValues(int row, List columns) throws TableException + { + return getRows().get(row); + } + + protected int getColumnIndex(String columnName) throws TableException + { + if (columnByIndex == null) + { + columnByIndex = new HashMap(); + + List columns = getAllColumns(); + for (int i = 0; i < columns.size(); i++) + { + columnByIndex.put(columns.get(i).getName(), i); + } + + } + + Integer index = columnByIndex.get(columnName); + + if (index == null) + { + throw new TableException("Unknown columnName [" + columnName + "]"); + } + + return index; + } + + protected Field getColumnByName(String columnName) throws TableException + { + for (Field field : getAllColumns()) + { + if (field.getName().equals(columnName)) + { + return field; + } + } + + throw new TableException("Unknown columnName [" + columnName + "]"); + } + + /** + * Checks if the column is in the current view port (the columns that the + * user sees in the table on the screen) + * + * @param columnName + * @return + * @throws TableException + */ + protected boolean isInViewPort(String columnName) throws TableException + { + for (Field field : getColumns()) + { + if (field.getName().equals(columnName)) + { + return true; + } + } + + return false; + } +} diff --git a/src/org/molgenis/framework/tupletable/DatabaseTupleTable.java b/src/org/molgenis/framework/tupletable/DatabaseTupleTable.java new file mode 100644 index 000000000..b438bdd85 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/DatabaseTupleTable.java @@ -0,0 +1,28 @@ +package org.molgenis.framework.tupletable; + +import org.molgenis.framework.db.Database; + +public interface DatabaseTupleTable +{ +// private Database db; +// +// public DatabaseTupleTable(Database db) { +// if(db == null) throw new IllegalArgumentException(); +// this.db = db; +// } +// +// public Database getDb(); +// { +// return db; +// } +// +// public void setDb(Database db) +// { +// this.db = db; +// } + + public Database getDb(); + + public void setDb(Database db); + +} diff --git a/src/org/molgenis/framework/tupletable/EditableTupleTable.java b/src/org/molgenis/framework/tupletable/EditableTupleTable.java new file mode 100644 index 000000000..6195175e6 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/EditableTupleTable.java @@ -0,0 +1,13 @@ +package org.molgenis.framework.tupletable; + +import org.molgenis.util.Tuple; + +/** Methods for editing a table */ +public interface EditableTupleTable extends TupleTable +{ + public void add(Tuple tuple) throws TableException; + + public void update(Tuple tuple) throws TableException; + + public void remove(Tuple tuple) throws TableException; +} diff --git a/src/org/molgenis/framework/tupletable/FilterableTupleTable.java b/src/org/molgenis/framework/tupletable/FilterableTupleTable.java new file mode 100644 index 000000000..d58619458 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/FilterableTupleTable.java @@ -0,0 +1,32 @@ +package org.molgenis.framework.tupletable; + +import java.util.List; + +import org.molgenis.framework.db.QueryRule; + +/** + * Extension of TupleTable that allows filterings, sortings, etc on the table. + */ +public interface FilterableTupleTable extends TupleTable +{ + /** + * Set the row filters, based on column names. Not allowed are LIMIT, OFFSET + * and SORT filters (@see setLimit, setOffset), which will throw + * TableException. + * + * @throws TableException + */ + public void setFilters(List rules) throws TableException; + + /** + * Get the current set of filters + */ + public List getFilters(); + + /** + * This we can inherit from Query interface? + * + * nb: multiple columns are not allowed for now. + */ + public QueryRule getSortRule(); +} \ No newline at end of file diff --git a/src/org/molgenis/framework/tupletable/TableException.java b/src/org/molgenis/framework/tupletable/TableException.java new file mode 100644 index 000000000..83632e197 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/TableException.java @@ -0,0 +1,21 @@ +package org.molgenis.framework.tupletable; + +public class TableException extends Exception +{ + + public TableException(Throwable e) + { + super(e); + } + + public TableException(String string) + { + super(string); + } + + /** + * + */ + private static final long serialVersionUID = -4121491743394204597L; + +} diff --git a/src/org/molgenis/framework/tupletable/TupleTable.java b/src/org/molgenis/framework/tupletable/TupleTable.java new file mode 100644 index 000000000..016b02376 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/TupleTable.java @@ -0,0 +1,127 @@ +package org.molgenis.framework.tupletable; + +import java.util.Iterator; +import java.util.List; + +import org.molgenis.model.elements.Field; +import org.molgenis.util.Tuple; + +/** + * TupleTable is a simple abstraction for tabular data (columns X rows). + *
    + *
  • Column names are unique + *
  • Column meta data (name,type,label,description,..) for currently visible + * columns are available in getColumns() + *
  • Row data is available as Tuple (hashMap) + *
+ * + * Purpose: this can be used as facade pattern to make views that are reusable + * across heterogeneous backends without extra work, such as database tables, + * Excel files, EAV models, binary formats, etc. + */ +public interface TupleTable extends Iterable +{ + public void hideColumn(String columnName); + + public void showColumn(String columnName); + + public List getHiddenColumnNames(); + + /** Wether the first column is 'fixed', must always be visible **/ + public void setFirstColumnFixed(boolean firstColumnFixed); + + public boolean isFirstColumnFixed(); + + /** + * Get meta data describing the columns in current view (within + * colLimit/colOffset) + */ + public List getColumns() throws TableException; + + /** + * Get all columns, including currently not visible + */ + public List getAllColumns() throws TableException; + + /** Get the data rows in current view (within limit/offset) */ + public List getRows() throws TableException; + + /** + * Get the data rows in current view in a streaming fashion (good for large + * data sets) + */ + @Override + public Iterator iterator(); + + /** Closes the resources from which table reads data (optional) */ + public void close() throws TableException; + + /** + * Get count of all records in the TupleTable + * + * @throws TableException + */ + public int getCount() throws TableException; + + /** + * Get count of all columns in the TupleTable + * + * @throws TableException + */ + public int getColCount() throws TableException; + + /** + * get row limit + */ + public int getLimit(); + + /** + * get column limit + */ + public int getColLimit(); + + /** + * set row limit (i.e. limit the current viewport to the full underlying + * table). Default: 0 (no limit). + */ + public void setLimit(int limit); + + /** + * set column limit (i.e. limit the current viewport to the full underlying + * table). Default: 0 (no limit) + */ + public void setColLimit(int limit); + + /** + * get row offset. Default: 0 + */ + public int getOffset(); + + /** + * get column offset. Default: 0 + */ + public int getColOffset(); + + /** + * set row limit (i.e. limit the current viewport to the full underlying + * table). Default: 0 (no offset) + */ + public void setOffset(int offset); + + /** + * set column limit (i.e. limit the current viewport to the full underlying + * table). Default: 0 (no offset) + */ + public void setColOffset(int offset); + + /** Reset the table, i.e. remove limits and filters */ + public void reset(); + + /** + * shorthand for setLimit(),setOffset() + * + * @param limit + * @param offset + */ + public void setLimitOffset(int limit, int offset); +} diff --git a/src/org/molgenis/framework/tupletable/TupleTableImporter.java b/src/org/molgenis/framework/tupletable/TupleTableImporter.java new file mode 100644 index 000000000..6151696ce --- /dev/null +++ b/src/org/molgenis/framework/tupletable/TupleTableImporter.java @@ -0,0 +1,20 @@ +package org.molgenis.framework.tupletable; + +/** + * + * @author joerivandervelde + * + */ +public class TupleTableImporter +{ + public TupleTableImporter() + { + + } + + public void importTupleTable(TupleTable src, TupleTable dest) + { + + } + +} diff --git a/src/org/molgenis/framework/tupletable/TupleTableIterator.java b/src/org/molgenis/framework/tupletable/TupleTableIterator.java new file mode 100644 index 000000000..b2f4b8646 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/TupleTableIterator.java @@ -0,0 +1,80 @@ +package org.molgenis.framework.tupletable; + +import java.util.Iterator; +import java.util.List; + +import org.molgenis.model.elements.Field; +import org.molgenis.util.Tuple; + +/** + * Iterator to be used with an AbstractTupleTable. Takes into account limit, + * offset, colLimit and colOffset of the TupleTable + * + * If you use this make sure to override getValues(row, colStart, colEnd) in + * AbstractTupleTable + * + * @author erwin + * + */ +public class TupleTableIterator implements Iterator +{ + private AbstractTupleTable tupleTable; + private int row = 0; + + public TupleTableIterator(AbstractTupleTable tupleTable) throws TableException + { + this.tupleTable = tupleTable; + } + + @Override + public boolean hasNext() + { + try + { + if (tupleTable.getOffset() + row >= tupleTable.getCount() + || (tupleTable.getLimit() > 0 && row >= tupleTable.getLimit())) + { + return false; + } + + return true; + } + catch (TableException e) + { + throw new RuntimeException(e); + } + } + + @Override + public Tuple next() + { + + Tuple tuple; + try + { + List columns = tupleTable.getColumns(); + + if (tupleTable.isFirstColumnFixed()) + { + columns.add(tupleTable.getAllColumns().get(0)); + } + + tuple = tupleTable.getValues(tupleTable.getOffset() + row, columns); + } + catch (TableException e) + { + throw new RuntimeException(e); + } + + row++; + + return tuple; + } + + @Override + public void remove() + { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/org/molgenis/framework/tupletable/impl/CsvTable.java b/src/org/molgenis/framework/tupletable/impl/CsvTable.java new file mode 100644 index 000000000..699cf2f82 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/impl/CsvTable.java @@ -0,0 +1,185 @@ +package org.molgenis.framework.tupletable.impl; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.LineNumberReader; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.zip.DataFormatException; + +import org.molgenis.framework.tupletable.AbstractTupleTable; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.model.elements.Field; +import org.molgenis.util.CsvFileReader; +import org.molgenis.util.CsvReader; +import org.molgenis.util.CsvStringReader; +import org.molgenis.util.Tuple; +import org.molgenis.util.TupleIterator; + +/** + * Wrap a CSV file into a TupleTable + */ +public class CsvTable extends AbstractTupleTable +{ + private CsvReader csv; + private InputStream countStream; + private List columns = new ArrayList(); + + File csvFile; + String csvString; + + /** + * Read table from a csv file + * + * @param csvFile + * @throws Exception + */ + public CsvTable(File csvFile) throws Exception + { + if (csvFile == null) throw new NullPointerException("Creation of CsvTable failed: csvFile == null"); + if (!csvFile.exists()) throw new IllegalArgumentException("Creation of CsvTable failed: csvFile does not exist"); + + this.csvFile = csvFile; + this.resetStreams(); + loadColumns(); + } + + /** + * Read table from a csv string + * + * @param csvString + * @throws Exception + */ + public CsvTable(String csvString) throws TableException + { + if (csvString == null) throw new NullPointerException("Creation of CsvTable failed: csvString == null"); + + this.csvString = csvString; + try + { + resetStreams(); + loadColumns(); + } + catch (Exception e) + { + throw new TableException(e); + } + } + + int rowCount = -1; + + /** + * Count rows (not including header of csv file) + */ + @Override + public int getCount() throws TableException + { + if (rowCount == -1) + { + try + { + LineNumberReader lineReader = new LineNumberReader(new InputStreamReader(countStream)); + String line = null; + while ((line = lineReader.readLine()) != null) + { + line = line.trim(); + } + + // substract 1 because of header + rowCount = lineReader.getLineNumber() - 1; + } + catch (Exception e) + { + throw new TableException(e); + } + } + return rowCount; + } + + /** + * Helper method to load the Field metadata + * + * @throws Exception + */ + private void loadColumns() throws Exception + { + for (String name : csv.colnames()) + { + Field f = new Field(name); + columns.add(f); + } + } + + @Override + public List getAllColumns() + { + return columns; + } + + @Override + public List getRows() + { + List result = new ArrayList(); + for (Tuple row : this) + { + result.add(row); + } + + return result; + } + + @Override + public Iterator iterator() + { + try + { + this.resetStreams(); + } + catch (Exception e) + { + // should not happen as this is second load + e.printStackTrace(); + } + + if (getLimit() > 0 || getOffset() > 0 || getColOffset() > 0 || getColLimit() > 0) + { + // offset + 1 to skip the header + return new TupleIterator(csv, getLimit(), getOffset() + 1, getColLimit(), getColOffset()); + } + return csv.iterator(); + } + + @Override + public void close() throws TableException + { + try + { + csv.close(); + countStream.close(); + } + catch (IOException e) + { + throw new TableException(e); + } + } + + private void resetStreams() throws FileNotFoundException, IOException, DataFormatException + { + if (csvFile != null) + { + csv = new CsvFileReader(csvFile); + countStream = new FileInputStream(csvFile); + } + else + { + csv = new CsvStringReader(csvString); + countStream = new ByteArrayInputStream(csvString.getBytes()); + } + } +} diff --git a/src/org/molgenis/framework/tupletable/impl/EditableTableDecorator.java b/src/org/molgenis/framework/tupletable/impl/EditableTableDecorator.java new file mode 100644 index 000000000..c5f55cf94 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/impl/EditableTableDecorator.java @@ -0,0 +1,208 @@ +package org.molgenis.framework.tupletable.impl; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.molgenis.framework.db.Database; +import org.molgenis.framework.db.QueryRule; +import org.molgenis.framework.tupletable.FilterableTupleTable; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.model.elements.Field; +import org.molgenis.util.SimpleTuple; +import org.molgenis.util.Tuple; + +/** Will change all row values to become edit boxes */ +public class EditableTableDecorator implements FilterableTupleTable +{ + FilterableTupleTable decoratedTable; + + public EditableTableDecorator(FilterableTupleTable decoratedTable) + { + this.decoratedTable = decoratedTable; + } + + @Override + public List getColumns() throws TableException + { + return decoratedTable.getColumns(); + } + + @Override + public List getAllColumns() throws TableException + { + return decoratedTable.getAllColumns(); + } + + @Override + public List getRows() throws TableException + { + try + { + List editableRows = new ArrayList(); + + for (Tuple t : this.decoratedTable.getRows()) + { + Tuple editable = new SimpleTuple(); + + for (String field : t.getFieldNames()) + { + editable.set(field, + ""); + + } + + // for (Field field : t.getFieldTypes()) { + // HtmlInput i = (HtmlInput) field.getType() + // .createInput(field.getName()); + // i.setValue(t.getObject(field.getName())); + // + // editable.set(field.getName(), i); + // } + editableRows.add(editable); + } + + return editableRows; + } + catch (Exception e) + { + e.printStackTrace(); + throw new TableException(e); + } + } + + @Override + public Iterator iterator() + { + return decoratedTable.iterator(); + } + + @Override + public void close() throws TableException + { + decoratedTable.close(); + } + + @Override + public int getCount() throws TableException + { + return decoratedTable.getCount(); + } + + @Override + public int getColCount() throws TableException + { + return decoratedTable.getColCount(); + } + + @Override + public int getLimit() + { + return decoratedTable.getLimit(); + } + + @Override + public int getColLimit() + { + return decoratedTable.getColLimit(); + } + + @Override + public void setLimit(int limit) + { + decoratedTable.setLimit(limit); + } + + @Override + public void setColLimit(int limit) + { + decoratedTable.setColLimit(limit); + } + + @Override + public int getOffset() + { + return decoratedTable.getOffset(); + } + + @Override + public int getColOffset() + { + return decoratedTable.getColOffset(); + } + + @Override + public void setOffset(int offset) + { + decoratedTable.setOffset(offset); + } + + @Override + public void setColOffset(int offset) + { + decoratedTable.setColOffset(offset); + } + + @Override + public void reset() + { + decoratedTable.reset(); + } + + @Override + public void setLimitOffset(int limit, int offset) + { + decoratedTable.setLimitOffset(limit, offset); + + } + + @Override + public void setFilters(List rules) throws TableException + { + decoratedTable.setFilters(rules); + } + + @Override + public List getFilters() + { + return decoratedTable.getFilters(); + } + + @Override + public QueryRule getSortRule() + { + return decoratedTable.getSortRule(); + } + + @Override + public void hideColumn(String columnName) + { + decoratedTable.hideColumn(columnName); + } + + @Override + public void showColumn(String columnName) + { + decoratedTable.showColumn(columnName); + } + + @Override + public List getHiddenColumnNames() + { + return decoratedTable.getHiddenColumnNames(); + } + + @Override + public void setFirstColumnFixed(boolean firstColumnFixed) + { + decoratedTable.setFirstColumnFixed(firstColumnFixed); + } + + @Override + public boolean isFirstColumnFixed() + { + return decoratedTable.isFirstColumnFixed(); + } + +} diff --git a/src/org/molgenis/framework/tupletable/impl/EntityTable.java b/src/org/molgenis/framework/tupletable/impl/EntityTable.java new file mode 100644 index 000000000..d31a0ba22 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/impl/EntityTable.java @@ -0,0 +1,158 @@ +package org.molgenis.framework.tupletable.impl; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.molgenis.framework.db.Database; +import org.molgenis.framework.db.DatabaseException; +import org.molgenis.framework.db.Query; +import org.molgenis.framework.db.QueryRule; +import org.molgenis.framework.tupletable.AbstractFilterableTupleTable; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.model.elements.Field; +import org.molgenis.util.Entity; +import org.molgenis.util.SimpleTuple; +import org.molgenis.util.Tuple; + +/** + * Wrap an Entity (that is stored in a database) into a TupleTable + */ +public class EntityTable extends AbstractFilterableTupleTable +{ + // class to query + private Class entityClass; + + // copy of the fields from meta database + private List columns; + + /** + * Constructor + * + * @param database + * containing the entity + * @param entityClass + * class of entities to query + */ + public EntityTable(final Database database, final Class entityClass) + { + super(); + + this.setDb(database); + + if (entityClass == null) + { + throw new NullPointerException("entityClass can't be null"); + } + + this.entityClass = entityClass; + } + + @Override + public List getAllColumns() throws TableException + { + if (columns != null) return columns; + + try + { + columns = getDb().getMetaData().getEntity(entityClass.getSimpleName()).getAllFields(); + return columns; + } + catch (Exception e) + { + throw new TableException(e); + } + } + + @Override + public List getRows() + { + try + { + Query q = getDb().query(entityClass); + if (this.getLimit() > 0) + { + q.limit(this.getLimit()); + } + if (this.getOffset() > 0) + { + q.offset(this.getOffset()); + } + if (getFilters().size() > 0) + { + q.addRules(getFilters().toArray(new QueryRule[getFilters().size()])); + } + List entities = q.find(); + + List result = new ArrayList(); + for (Entity e : entities) + { + final Tuple t = new SimpleTuple(); + + for (Field f : getColumns()) + { + t.set(f.getName(), e.get(f.getName())); + } + + result.add(t); + } + return result; + } + catch (Exception e) + { + throw new RuntimeException(e); + } + } + + @Override + public Iterator iterator() + { + // should be optimized + return this.getRows().iterator(); + } + + @Override + public void close() throws TableException + { + } + + @Override + public int getCount() throws TableException + { + try + { + if (getFilters().size() > 0) return getDb().count(entityClass, + getFilters().toArray(new QueryRule[getFilters().size()])); + else + return getDb().count(entityClass); + } + catch (DatabaseException e) + { + throw new TableException(e); + } + } + + /** + * very bad: bypasses all security and connection management + */ + private Database db; + + public void setDb(Database db) + { + if (db == null) throw new NullPointerException("database cannot be null in setDb(db)"); + this.db = db; + } + + public Database getDb() + { + // try + // { + // db = DatabaseFactory.create(); + // } + // catch (DatabaseException e) + // { + // throw new RuntimeException(e); + // } + return this.db; + } +} diff --git a/src/org/molgenis/framework/tupletable/impl/JdbcTable.java b/src/org/molgenis/framework/tupletable/impl/JdbcTable.java new file mode 100644 index 000000000..7edf35c22 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/impl/JdbcTable.java @@ -0,0 +1,126 @@ +package org.molgenis.framework.tupletable.impl; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.molgenis.framework.db.Database; +import org.molgenis.framework.db.QueryRule; +import org.molgenis.framework.tupletable.AbstractFilterableTupleTable; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.model.elements.Field; +import org.molgenis.util.Tuple; + +public class JdbcTable extends AbstractFilterableTupleTable +{ + private Database db; + private List rs; + private List columns; + private final String query; + private final String countQuery; + private boolean loaded = false; + + public JdbcTable(Database db, String query, List rules) throws TableException + { + super(); + this.db = db; + this.query = query; + this.setFilters(rules); + + final String fromExpression = StringUtils.substringBetween(query, "SELECT", "FROM"); + this.countQuery = StringUtils.replace(query, fromExpression, " COUNT(*) "); + } + + public JdbcTable(Database db, String query) throws TableException + { + this(db, query, new ArrayList()); + } + + private void load() throws TableException + { + if (!loaded) + { + loaded = true; + try + { + rs = db.sql(query, getFilters().toArray(new QueryRule[0])); + columns = loadColumns(); + } + catch (Exception e) + { + throw new TableException(e); + } + } + } + + @Override + public List getAllColumns() throws TableException + { + load(); + return columns; + } + + private List loadColumns() throws TableException + { + load(); + if (rs.size() > 0) + { + return rs.get(0).getFieldTypes(); + } + return new ArrayList(); + } + + /** + * Don't forget to call close after done with Iterator + */ + @Override + public Iterator iterator() + { + try + { + load(); + return rs.iterator(); + } + catch (Exception e) + { + throw new RuntimeException(e); + } + } + + @Override + public void close() throws TableException + { + } + + @Override + public int getCount() throws TableException + { + try + { + final List countSet = db.sql(countQuery, getFilters().toArray(new QueryRule[0])); + int rowCount = 0; + if (countSet.size() > 0) + { + final Number count = (Number) countSet.get(0).getInt(1); + rowCount = count.intValue(); + } + return rowCount; + } + catch (Exception ex) + { + throw new TableException(ex); + } + } + + public void setDb(Database db) + { + if (db == null) throw new NullPointerException("database cannot be null in setDb(db)"); + this.db = db; + } + + public Database getDb() + { + return this.db; + } +} diff --git a/src/org/molgenis/framework/tupletable/impl/MemoryTable.java b/src/org/molgenis/framework/tupletable/impl/MemoryTable.java new file mode 100644 index 000000000..9a9956ce5 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/impl/MemoryTable.java @@ -0,0 +1,112 @@ +package org.molgenis.framework.tupletable.impl; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.molgenis.fieldtypes.StringField; +import org.molgenis.framework.tupletable.AbstractTupleTable; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.model.elements.Field; +import org.molgenis.util.SimpleTuple; +import org.molgenis.util.Tuple; + +/** + * Wrap a List into a TupleTable + */ +public class MemoryTable extends AbstractTupleTable +{ + private List columns = new ArrayList(); + private List rows = new ArrayList(); + + /** + * Construct from list of tuples. Field will be derived based on column + * names and value type of first tuple. Otherwise field type will be String. + */ + public MemoryTable(List rows) + { + if (rows == null) throw new NullPointerException("Creation of MemoryTable failed: rows == null"); + + this.rows = rows; + + // use first row + if (rows.size() > 0) + { + for (String field : rows.get(0).getFieldNames()) + { + Field f = new Field(field); + f.setType(new StringField()); + columns.add(f); + } + } + } + + @Override + public List getAllColumns() + { + return this.columns; + } + + @Override + public List getRows() throws TableException + { + List columns = new ArrayList(); + for (Field f : getColumns()) + columns.add(f.getName()); + + List result = new ArrayList(); + if (getLimit() > 0 || getOffset() > 0) + { + int count = 0; + int index = 1; + for (Tuple row : this.rows) + { + if (index > getOffset()) + { + SimpleTuple copy = new SimpleTuple(columns); + for (String col : columns) + { + copy.set(col, row.getObject(col)); + } + result.add(new SimpleTuple(copy)); + + count++; + if (count >= getLimit()) break; + } + index++; + } + } + else + { + for (Tuple row : this.rows) + { + SimpleTuple copy = new SimpleTuple(columns); + for (String col : columns) + { + copy.set(col, row.getObject(col)); + } + result.add(new SimpleTuple(copy)); + } + } + return result; + } + + @Override + public Iterator iterator() + { + try + { + return this.getRows().iterator(); + } + catch (TableException e) + { + throw new RuntimeException(e); + } + } + + @Override + public int getCount() throws TableException + { + return rows.size(); + } +} diff --git a/src/org/molgenis/framework/tupletable/impl/MemoryTableFactory.java b/src/org/molgenis/framework/tupletable/impl/MemoryTableFactory.java new file mode 100644 index 000000000..c9c8d4014 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/impl/MemoryTableFactory.java @@ -0,0 +1,33 @@ +package org.molgenis.framework.tupletable.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.molgenis.framework.tupletable.TupleTable; +import org.molgenis.util.SimpleTuple; +import org.molgenis.util.Tuple; + +public class MemoryTableFactory +{ + public static TupleTable create() + { + return create(5,5); + } + + public static TupleTable create(int nrows, int ncols) + { + List rows = new ArrayList(); + + for (int i = 1; i <= nrows; i++) + { + Tuple t = new SimpleTuple(); + for (int j = 1; j <= ncols; j++) + { + t.set("col" + j, "val" + j + "," + i); + } + rows.add(t); + } + + return new MemoryTable(rows); + } +} diff --git a/src/org/molgenis/framework/tupletable/impl/RSIterator.java b/src/org/molgenis/framework/tupletable/impl/RSIterator.java new file mode 100644 index 000000000..134e87db2 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/impl/RSIterator.java @@ -0,0 +1,61 @@ +package org.molgenis.framework.tupletable.impl; + +import java.sql.SQLException; +import java.util.Iterator; + +import org.molgenis.util.ResultSetTuple; +import org.molgenis.util.SimpleTuple; +import org.molgenis.util.Tuple; + +public class RSIterator implements Iterator +{ + private ResultSetTuple entities; + private boolean didNext = false; + private boolean hasNext = false; + + public RSIterator(ResultSetTuple rs) + { + this.entities = rs; + } + + public Tuple next() + { + try + { + if (!didNext) + { + entities.next(); + } + didNext = false; + return new SimpleTuple(entities); + } + catch (SQLException e) + { + throw new RuntimeException(e); + } + } + + public boolean hasNext() + { + try + { + if (!didNext) + { + hasNext = entities.next(); + didNext = true; + } + return hasNext; + } + catch (SQLException e) + { + throw new RuntimeException(e); + } + } + + @Override + public void remove() + { + // TODO Auto-generated method stub + + } +} \ No newline at end of file diff --git a/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridColModel.java b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridColModel.java new file mode 100644 index 000000000..ded8b5361 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridColModel.java @@ -0,0 +1,211 @@ +package org.molgenis.framework.tupletable.view.JQGridJSObjects; + +import org.molgenis.MolgenisFieldTypes.FieldTypeEnum; +import org.molgenis.model.elements.Field; + +@SuppressWarnings("unused") +@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = +{ "URF_UNREAD_FIELD", "UUF_UNUSED_FIELD" }, justification = "Gson reads private fields") +public class JQGridColModel +{ + private String name; + private String index; + private int width = 100; + private String stype; + private boolean sortable = false; + private boolean search = true; + private boolean fixed = false; + private SearchOptions searchoptions; + private SearchRule searchrules; + private EditOptions editoptions; + private boolean editable; + // for tree view + private String title; + private boolean isFolder = false; + private String path; + private String edittype; + private String add; + private String datetype; + + public JQGridColModel(String f) + { + this.name = f; + this.index = f; + this.title = f; + this.path = f; + this.editable = false; + this.sortable = false; + } + + // FIXME call JQGridColModel(String) + // TODO discuss: why JQGridColModel(Field)/JQGridColModel(String) sets + // editable to true/false + public JQGridColModel(Field f) + { + this.name = f.getSqlName(); + this.index = f.getSqlName(); + this.title = name; + this.path = title; + this.editable = true; + this.sortable = false; + + this.searchoptions = SearchOptions.create(f.getType().getEnumType()); + this.searchrules = SearchRule.createSearchRule(f.getType().getEnumType()); + + // TODO discuss: why try-catch for all code? + try + { + // TODO discuss: possible code smell, hard coded reference + if (!name.equals("Pa_Id")) + { + + StringBuilder strBuilder = new StringBuilder(); + + if ("enum".equals(f.getType().toString())) + { + + for (String category : f.getEnumOptions()) + { + String code = category.split("\\.")[0]; + strBuilder.append(code).append(':').append(category).append(';'); + } + strBuilder.deleteCharAt(strBuilder.length() - 1); + + edittype = "select"; + + String editOptionsStr = strBuilder.toString(); + editoptions = EditOptions.createEditOptions(":;" + editOptionsStr); + searchoptions.sopt = new String[] + { "eq", "ne" }; + this.stype = "select"; + searchoptions.value = editOptionsStr; + + } + else if ("bool".equals(f.getType().toString())) + { + edittype = "select"; + + } + else if ("datetime".equals(f.getType().toString())) + { + datetype = "datetype"; + } + + } + else + { + + editoptions = EditOptions.createEditOptions(); + editoptions.disabled = "disabled"; + editoptions.style = "width:100px;background:lightgrey"; + fixed = true; + } + + } + catch (Exception e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + private static class SearchOptions + { + private boolean required = true; + private boolean searchhidden = true; + private String value; + private String[] sopt = new String[] + { "eq", "ne", "bw", "bn", "ew", "en", "cn", "nc" }; + + private String dataInit = "function(elem){ $(elem).datepicker({dateFormat:\"mm/dd/yyyy\"});}}"; + + public SearchOptions() + { + } + + public SearchOptions(String[] sopt) + { + this.sopt = sopt; + } + + public static SearchOptions create(FieldTypeEnum fte) + { + switch (fte) + { + case INT: + case LONG: + case DECIMAL: + case DATE: + case DATE_TIME: + return new SearchOptions(new String[] + { "eq", "ne", "lt", "le", "gt", "ge" }); + + default: + return new SearchOptions(); + } + } + } + + private static class SearchRule + { + private boolean number = false; + private boolean integer = false; + private boolean email = false; + private boolean date = false; + private boolean time = false; + + public static SearchRule createSearchRule(FieldTypeEnum fte) + { + switch (fte) + { + case INT: + case LONG: + { + final SearchRule rule = new SearchRule(); + rule.integer = true; + return rule; + } + case DECIMAL: + { + final SearchRule rule = new SearchRule(); + rule.number = true; + return rule; + } + case DATE: + { + final SearchRule rule = new SearchRule(); + rule.date = true; + return rule; + } + + default: + return new SearchRule(); + } + } + } + + private static class EditOptions + { + private String value; + private String disabled; + private String style; + private String name; + + public static EditOptions createEditOptions(String actualValue) + { + final EditOptions editOptions = new EditOptions(); + editOptions.value = actualValue; + + return editOptions; + } + + // make Pa_Id field disabled and lightgrey + public static EditOptions createEditOptions() + { + final EditOptions editOptions = new EditOptions(); + + return editOptions; + } + } +} \ No newline at end of file diff --git a/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridConfiguration.java b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridConfiguration.java new file mode 100644 index 000000000..717aed962 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridConfiguration.java @@ -0,0 +1,162 @@ +package org.molgenis.framework.tupletable.view.JQGridJSObjects; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import org.molgenis.framework.db.Database; +import org.molgenis.framework.tupletable.DatabaseTupleTable; +import org.molgenis.framework.tupletable.EditableTupleTable; +import org.molgenis.framework.tupletable.FilterableTupleTable; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.framework.tupletable.TupleTable; +import org.molgenis.model.elements.Field; + +@SuppressWarnings("unused") +@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = +{ "URF_UNREAD_FIELD", "SS_SHOULD_BE_STATIC" }, justification = "Gson reads private fields") +public class JQGridConfiguration +{ + private String id; + + /** ajax url */ + private final String url; + + private final String editurl; + + /** formatting of the ajax service data */ + private final String datatype = "json"; + + /** id of pager diff (== toolbar at bottom) */ + private final String pager; + + /** labels of the columns */ + private List colNames = new ArrayList(); + + /** definitions of the columns */ + private List colModel = new ArrayList(); + + /** current limit = number of rows to show */ + private int rowNum = 10; + + /** choices of alternative rowNum values */ + private Integer[] rowList = new Integer[] + { 10, 20, 30 }; + + /** indicates whether we want to show total records from query in page bar */ + private boolean viewrecords = true; + + /** the caption of this table */ + private String caption = "jqGrid View"; + + private boolean autowidth = true; + + /** whether this grid is sortable */ + private String sortname = ""; + + /** default sorting order */ + private String sortorder = "desc"; + + /** default height */ + private String height = "232px"; + + /** the total column count **/ + private int totalColumnCount; + + /** the current column offset **/ + private int colOffset; + + /** the current coliumn limit, so the nr of visible columns **/ + private int colLimit; + + /** list of hidden column names **/ + private List hiddenColumns; + + /** Wether the first column is 'fixed', must always be visible **/ + private boolean firstColumnFixed; + + /** virtual scrolling */ + // private int scroll = 1; + + /** preload filter settings */ + // note: this is a string value + // private String postData = + // "{filters : '{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"Country.Code\",\"op\":\"eq\",\"data\":\"AGO\"}]}'}"; + private JQGridPostData postData = new JQGridPostData(); + + /** ???? */ + private HashMap jsonReader = new HashMap(); + + // private String postData = "viewType : JQ_GRID"; + + private JQGridSettings settings = new JQGridSettings(); + + private JQGridSearchOptions searchOptions = new JQGridSearchOptions(); + + @SuppressWarnings("unchecked") + private Object[] toolbar = Arrays.asList(true, "top").toArray(); + + public JQGridConfiguration(Database db, String id, String idField, String url, String caption, TupleTable tupleTable) + throws TableException + { + if (tupleTable instanceof DatabaseTupleTable) + { + ((DatabaseTupleTable) tupleTable).setDb(db); + } + + this.id = id; + this.pager = "#" + id + "_pager"; + this.url = url; + this.editurl = url; + this.caption = caption; + this.totalColumnCount = tupleTable.getColCount(); + this.colOffset = tupleTable.getColOffset(); + this.colLimit = tupleTable.getColLimit(); + this.firstColumnFixed = tupleTable.isFirstColumnFixed(); + + // "{repeatitems: false, id: \"Code\"}" + jsonReader.put("repeatitems", false); + jsonReader.put("id", idField); + + this.hiddenColumns = tupleTable.getHiddenColumnNames(); + + if (tupleTable instanceof FilterableTupleTable) + { + // sortable = true; + settings.setSearch(true); + } + + if (tupleTable instanceof EditableTupleTable) + { + settings.setAdd(true); + settings.setEdit(true); + settings.setDel(true); + } + + // set col names + for (final Field f : tupleTable.getColumns()) + { + colModel.add(new JQGridColModel(f)); + } + } + + public JQGridConfiguration(String id, String url, String caption) + { + this.id = id; + this.pager = "#" + id + "Pager"; + this.url = url; + this.editurl = url; + this.caption = caption; + } + + public JQGridSearchOptions getSearchOptions() + { + return searchOptions; + } + + public void setSearchOptions(JQGridSearchOptions searchOptions) + { + this.searchOptions = searchOptions; + } +} diff --git a/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridFilter.java b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridFilter.java new file mode 100644 index 000000000..3d4bfe96e --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridFilter.java @@ -0,0 +1,38 @@ +package org.molgenis.framework.tupletable.view.JQGridJSObjects; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +//{"groupOp":"AND","rules":[{"field":"Country.Code","op":"eq","data":"AGO"}]} +public class JQGridFilter +{ + private String groupOp; + private List rules; + + public JQGridFilter() + { + this.groupOp = "AND"; + this.rules = new ArrayList(); + } + + public String getGroupOp() + { + return groupOp; + } + + public void setGroupOp(String groupOp) + { + this.groupOp = groupOp; + } + + public List getRules() + { + return Collections.unmodifiableList(rules); + } + + public void addRule(JQGridRule rule) + { + this.rules.add(rule); + } +} diff --git a/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridPostData.java b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridPostData.java new file mode 100644 index 000000000..790669fbe --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridPostData.java @@ -0,0 +1,120 @@ +package org.molgenis.framework.tupletable.view.JQGridJSObjects; + +import org.molgenis.util.Tuple; + +import com.google.gson.Gson; + +/** + * This is the request that we receive from JQGrid via JSON. Also, this can be + * used to preload a 'saved' filters/sort/paging setting. + */ +public class JQGridPostData +{ + private JQGridFilter filters; + /** sort order */ + private String sord; + /** sort index field name */ + private String sidx; + /** number of rows to show */ + private int rows; + /** page offset, each page being rows long */ + private int page; + private int colPage; + + public JQGridPostData() + { + this.sord = null; + this.sidx = null; + this.rows = 0; + this.page = 0; + this.colPage = 1; + this.filters = new JQGridFilter(); + } + + public JQGridPostData(Tuple request) + { + this.rows = request.getInt("rows"); + this.page = request.getInt("page"); + this.sidx = request.getString("sidx"); + this.sord = request.getString("sord"); + this.colPage = request.getInt("colPage"); + + JQGridFilter gridFilter = new Gson().fromJson(request.getString("filters"), JQGridFilter.class); + + if (gridFilter == null) + { + // Check simple, single search + String searchString = request.getString("searchString"); + String searchField = request.getString("searchField"); + String searchOper = request.getString("searchOper"); + + if ((searchString != null) && (searchField != null) && (searchOper != null)) + { + JQGridRule.JQGridOp op = JQGridRule.JQGridOp.valueOf(searchOper); + gridFilter = new JQGridFilter(); + gridFilter.addRule(new JQGridRule(searchField, op, searchString)); + } + } + this.filters = gridFilter; + } + + public JQGridFilter getFilters() + { + return filters; + } + + public void setFilters(JQGridFilter filters) + { + this.filters = filters; + } + + public String getSord() + { + return sord; + } + + public void setSord(String sord) + { + this.sord = sord; + } + + public String getSidx() + { + return sidx; + } + + public void setSidx(String sidx) + { + this.sidx = sidx; + } + + public int getRows() + { + return rows; + } + + public void setRows(int rows) + { + this.rows = rows; + } + + public int getPage() + { + return page; + } + + public void setPage(int page) + { + this.page = page; + } + + public int getColPage() + { + return colPage; + } + + public void setColPage(int colPage) + { + this.colPage = colPage; + } +} diff --git a/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridResult.java b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridResult.java new file mode 100644 index 000000000..a98092fce --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridResult.java @@ -0,0 +1,51 @@ +package org.molgenis.framework.tupletable.view.JQGridJSObjects; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; + +/** + * Class wrapping the results of a jqGrid query. To be serialized by Gson, hence + * no accessors necessary for private datamembers. + */ +public class JQGridResult +{ + private final int page; + private final int total; + private final int records; + private final List> rows; + + public JQGridResult(int page, int total, int records) + { + this.page = page; + this.total = total; + this.records = records; + this.rows = new ArrayList>(); + } + + public int getPage() + { + return page; + } + + public int getTotal() + { + return total; + } + + public int getRecords() + { + return records; + } + + public List> getRows() + { + return Collections.unmodifiableList(rows); + } + + public boolean addRow(LinkedHashMap row) + { + return rows.add(row); + } +} \ No newline at end of file diff --git a/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridRule.java b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridRule.java new file mode 100644 index 000000000..133d4b39e --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridRule.java @@ -0,0 +1,36 @@ +package org.molgenis.framework.tupletable.view.JQGridJSObjects; + +//{"field":"Country.Code","op":"eq","data":"AGO"} +public class JQGridRule +{ + private final String field; + private final JQGridOp op; + private final String data; + + public enum JQGridOp + { + eq, ne, lt, le, gt, ge, bw, bn, in, ni, ew, en, cn, nc + } + + public JQGridRule(String field, JQGridOp op, String data) + { + this.field = field; + this.op = op; + this.data = data; + } + + public String getField() + { + return field; + } + + public JQGridOp getOp() + { + return op; + } + + public String getData() + { + return data; + } +} diff --git a/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridSearchOptions.java b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridSearchOptions.java new file mode 100644 index 000000000..722f44b49 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridSearchOptions.java @@ -0,0 +1,67 @@ +package org.molgenis.framework.tupletable.view.JQGridJSObjects; + +import java.util.Arrays; +import java.util.List; + +public class JQGridSearchOptions +{ + private boolean multipleSearch; + private boolean multipleGroup; + private boolean showQuery; + private List sopt; + + public JQGridSearchOptions() + { + this(true, true, true, Arrays.asList(JQGridRule.JQGridOp.values())); + } + + public JQGridSearchOptions(boolean multipleSearch, boolean multipleGroup, boolean showQuery, + List sopt) + { + this.multipleSearch = multipleSearch; + this.multipleGroup = multipleGroup; + this.showQuery = showQuery; + this.sopt = sopt; + } + + public boolean isMultipleSearch() + { + return multipleSearch; + } + + public void setMultipleSearch(boolean multipleSearch) + { + this.multipleSearch = multipleSearch; + } + + public boolean isMultipleGroup() + { + return multipleGroup; + } + + public void setMultipleGroup(boolean multipleGroup) + { + this.multipleGroup = multipleGroup; + } + + public boolean isShowQuery() + { + return showQuery; + } + + public void setShowQuery(boolean showQuery) + { + this.showQuery = showQuery; + } + + public List getSopt() + { + return sopt; + } + + public void setSopt(List sopt) + { + this.sopt = sopt; + } + +} diff --git a/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridSettings.java b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridSettings.java new file mode 100644 index 000000000..f1bf42665 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridJSObjects/JQGridSettings.java @@ -0,0 +1,62 @@ +package org.molgenis.framework.tupletable.view.JQGridJSObjects; + +public class JQGridSettings +{ + private boolean del; + private boolean add; + private boolean edit; + private boolean search; + + public JQGridSettings() + { + this(false, false, false, false); + } + + public JQGridSettings(boolean del, boolean add, boolean edit, boolean search) + { + this.del = del; + this.add = add; + this.edit = edit; + this.search = search; + } + + public boolean isDel() + { + return del; + } + + public void setDel(boolean del) + { + this.del = del; + } + + public boolean isAdd() + { + return add; + } + + public void setAdd(boolean add) + { + this.add = add; + } + + public boolean isEdit() + { + return edit; + } + + public void setEdit(boolean edit) + { + this.edit = edit; + } + + public boolean isSearch() + { + return search; + } + + public void setSearch(boolean search) + { + this.search = search; + } +} \ No newline at end of file diff --git a/src/org/molgenis/framework/tupletable/view/JQGridView.ftl b/src/org/molgenis/framework/tupletable/view/JQGridView.ftl new file mode 100644 index 000000000..f0488b064 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridView.ftl @@ -0,0 +1,322 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ + +
+
+ + + + + + + + + + +
+ + + + + Columns of + + + + +
+
+
+
+
+ + +
+ +
+
\ No newline at end of file diff --git a/src/org/molgenis/framework/tupletable/view/JQGridView.java b/src/org/molgenis/framework/tupletable/view/JQGridView.java new file mode 100644 index 000000000..025d805aa --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridView.java @@ -0,0 +1,613 @@ +package org.molgenis.framework.tupletable.view; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.json.JSONObject; +import org.molgenis.framework.db.Database; +import org.molgenis.framework.db.QueryRule; +import org.molgenis.framework.db.QueryRule.Operator; +import org.molgenis.framework.server.MolgenisRequest; +import org.molgenis.framework.tupletable.DatabaseTupleTable; +import org.molgenis.framework.tupletable.EditableTupleTable; +import org.molgenis.framework.tupletable.FilterableTupleTable; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.framework.tupletable.TupleTable; +import org.molgenis.framework.tupletable.view.JQGridJSObjects.JQGridConfiguration; +import org.molgenis.framework.tupletable.view.JQGridJSObjects.JQGridFilter; +import org.molgenis.framework.tupletable.view.JQGridJSObjects.JQGridPostData; +import org.molgenis.framework.tupletable.view.JQGridJSObjects.JQGridResult; +import org.molgenis.framework.tupletable.view.JQGridJSObjects.JQGridRule; +import org.molgenis.framework.tupletable.view.JQGridJSObjects.JQGridSearchOptions; +import org.molgenis.framework.tupletable.view.renderers.Renderers; +import org.molgenis.framework.tupletable.view.renderers.Renderers.JQGridRenderer; +import org.molgenis.framework.tupletable.view.renderers.Renderers.Renderer; +import org.molgenis.framework.ui.FreemarkerView; +import org.molgenis.framework.ui.ScreenController; +import org.molgenis.framework.ui.html.HtmlWidget; +import org.molgenis.util.HandleRequestDelegationException; +import org.molgenis.util.Tuple; + +import com.google.gson.Gson; + +/** + * View class which provides a JQGrid view on a {@link TupleTable} + */ +public class JQGridView extends HtmlWidget +{ + public static final String OPERATION = "Operation"; + private static final int DEFAULT_MAX_VISIBLE_COLUMN_COUNT = 5; + private JQGridSearchOptions searchOptions; + private int maxVisibleColumnCount = DEFAULT_MAX_VISIBLE_COLUMN_COUNT; + private JQGridViewCallback callback; + + /** + * Operations that the GridView can handle. LOAD_CONFIG, RENDER_DATA, + * LOAD_TREE + */ + private enum Operation + { + LOAD_CONFIG, RENDER_DATA, EDIT_RECORD, ADD_RECORD, DELETE_RECORD, NEXT_COLUMNS, PREVIOUS_COLUMNS, SET_COLUMN_PAGE, HIDE_COLUMN, SHOW_COLUMN + } + + /** + * Interface for builder classes that allow easy reconstruction of the + * view's inner {@link TupleTable} in the {@link JQGridView#handleRequest} + * function + */ + public interface TupleTableBuilder + { + public TupleTable create(Tuple request) throws TableException; + + public String getUrl(); + } + + private final TupleTableBuilder tupleTableBuilder; + + private JQGridView(String name, TupleTableBuilder tupleTableBuilder) + { + super(name); + this.tupleTableBuilder = tupleTableBuilder; + } + + /** + * Default construction with an anonymous inner + * {@link JQGridView.TupleTableBuilder} + */ + public JQGridView(final String name, final ScreenController hostController, final TupleTable table) + { + + this(name, new TupleTableBuilder() + { + @Override + public String getUrl() + { + return "molgenis.do?__target=" + hostController.getName() + "&__action=download_json_" + name; + } + + @Override + public TupleTable create(Tuple request) throws TableException + { + return table; + } + }); + + if (hostController instanceof JQGridViewCallback) + { + callback = (JQGridViewCallback) hostController; + } + } + + public JQGridView(final String name, final ScreenController hostController, final TupleTable table, + JQGridSearchOptions searchOptions) + { + this(name, hostController, table); + this.searchOptions = searchOptions; + } + + /** + * Handle a particular {@link MolgenisRequest}, and render into an + * {@link OutputStream}. Particulars handled: + *
    + *
  • Wrap the desired data source in the appropriate instantiation of + * {@link TupleTable}.
  • + *
  • Determine which {@link Operation} the request is asking to handle. + *
  • Apply proper sorting and filter rules.
  • + *
  • Select the appropriate view towards which to export/render.
  • + *
  • Select and render the data.
  • + *
+ * + * @param db + * The database to connect to + * @param request + * The {@link MolgenisRequest} tuple that encodes the request to + * handle + * @param out + * The {@link OutputStream} to render to. + */ + public void handleRequest(Database db, Tuple request, OutputStream out) throws HandleRequestDelegationException + { + try + { + if (db.getConnection().isClosed()) + { + throw new HandleRequestDelegationException(new Exception("handleRequest: Connection is closed!")); + } + + final TupleTable tupleTable = tupleTableBuilder.create(request); + tupleTable.setColLimit(maxVisibleColumnCount); + + if (tupleTable instanceof DatabaseTupleTable) + { + ((DatabaseTupleTable) tupleTable).setDb(db); + } + + final Operation operation = StringUtils.isNotEmpty(request.getString(OPERATION)) ? Operation + .valueOf(request.getString(OPERATION)) : Operation.RENDER_DATA; + + switch (operation) + { + case LOAD_CONFIG: + if (callback != null) + { + callback.beforeLoadConfig((MolgenisRequest) request, tupleTable); + } + loadTupleTableConfig(db, (MolgenisRequest) request, tupleTable); + break; + case HIDE_COLUMN: + String columnToRemove = request.getString("column"); + tupleTable.hideColumn(columnToRemove); + loadTupleTableConfig(db, (MolgenisRequest) request, tupleTable); + break; + case SHOW_COLUMN: + String columnToShow = request.getString("column"); + tupleTable.showColumn(columnToShow); + loadTupleTableConfig(db, (MolgenisRequest) request, tupleTable); + break; + case SET_COLUMN_PAGE: + + // TODO put this in a util class (default value for + // requestparams) + int colPage; + try + { + colPage = request.getInt("colPage"); + } + catch (Exception e) + { + colPage = 1; + } + + // TODO put maxColPage function in util class + int maxColPage = (int) Math.floor(tupleTable.getColCount() / (double) tupleTable.getColLimit()); + if ((tupleTable.getColCount() % tupleTable.getColLimit()) > 0) + { + maxColPage++; + } + colPage = Math.min(colPage, maxColPage); + + int colOffset = (colPage - 1) * tupleTable.getColLimit(); + colOffset = Math.max(colOffset, 0); + + tupleTable.setColOffset(colOffset); + loadTupleTableConfig(db, (MolgenisRequest) request, tupleTable); + break; + case NEXT_COLUMNS: + tupleTable.setColOffset(tupleTable.getColOffset() + maxVisibleColumnCount); + loadTupleTableConfig(db, (MolgenisRequest) request, tupleTable); + break; + case PREVIOUS_COLUMNS: + tupleTable.setColOffset(tupleTable.getColOffset() - maxVisibleColumnCount); + loadTupleTableConfig(db, (MolgenisRequest) request, tupleTable); + break; + case RENDER_DATA: + final List rules = new ArrayList(); + + // parse the request into post data + final JQGridPostData postData = new JQGridPostData(request); + + // convert any filters to query rules + final List filterRules = createQueryRulesFromJQGridRequest(postData.getFilters()); + + if (CollectionUtils.isNotEmpty(filterRules)) + { + if (tupleTable instanceof FilterableTupleTable) + { + rules.addAll(filterRules); + ((FilterableTupleTable) tupleTable).setFilters(rules); + } + } + int residue = 0; + final int rowCount = tupleTable.getCount(); + if (rowCount % postData.getRows() != 0) + { + residue = 1; + } + final int totalPages = (int) Math.ceil(rowCount / (double) postData.getRows()) + residue; + + // update page + postData.setPage(Math.min(postData.getPage(), totalPages)); + final int offset = Math.max((postData.getPage() - 1) * postData.getRows(), 0); + + final String exportSelection = request.getString("exportSelection"); + if (!StringUtils.equalsIgnoreCase(exportSelection, "ALL")) + { + // data.rows == limit + tupleTable.setLimit(postData.getRows()); + // data.rows * data.page + tupleTable.setOffset(offset); + } + + if (StringUtils.isNotEmpty(postData.getSidx()) && tupleTable instanceof FilterableTupleTable) + { + final Operator sortOperator = StringUtils.equals(postData.getSord(), "asc") ? QueryRule.Operator.SORTASC + : QueryRule.Operator.SORTDESC; + rules.add(new QueryRule(sortOperator, postData.getSidx())); + } + + if (tupleTable instanceof FilterableTupleTable) + { + ((FilterableTupleTable) tupleTable).setFilters(rules); + } + + renderData(((MolgenisRequest) request), postData, totalPages, tupleTable); + break; + + case EDIT_RECORD: + + if (!(tupleTable instanceof EditableTupleTable)) + { + throw new UnsupportedOperationException("TupleTable is not editable"); + } + + // create a json object to take the message and success + // variables. + JSONObject result = new JSONObject(); + + try + { + ((EditableTupleTable) tupleTable).update(request); + + result.put("message", "Record updated"); + result.put("success", true); + } + catch (Exception e) + { + e.printStackTrace(); + + result.put("message", e.getMessage()); + result.put("success", false); + } + + // Send this json string back the html. + ((MolgenisRequest) request).getResponse().getOutputStream().println(result.toString()); + break; + + case ADD_RECORD: + + if (!(tupleTable instanceof EditableTupleTable)) + + { + throw new UnsupportedOperationException("TupleTable is not editable"); + } + + // create a json object to take the message and success + // variables. + result = new JSONObject(); + + try + { + ((EditableTupleTable) tupleTable).add(request); + + result.put("message", "Record added"); + result.put("success", true); + } + catch (Exception e) + { + e.printStackTrace(); + + result.put("message", e.getMessage()); + result.put("success", false); + } + + // Send this json string back the html. + ((MolgenisRequest) request).getResponse().getOutputStream().println(result.toString()); + break; + + case DELETE_RECORD: + if (!(tupleTable instanceof EditableTupleTable)) + { + throw new UnsupportedOperationException("TupleTable is not editable"); + } + + // create a json object to take the message and success + // variables. + result = new JSONObject(); + + try + { + ((EditableTupleTable) tupleTable).remove(request); + + result.put("message", "Record deleted"); + result.put("success", true); + } + catch (Exception e) + { + e.printStackTrace(); + + result.put("message", e.getMessage()); + result.put("success", false); + } + + // Send this json string back the html. + ((MolgenisRequest) request).getResponse().getOutputStream().println(result.toString()); + break; + default: + break; + } + + } + catch (final Exception e) + { + e.printStackTrace(); + throw new HandleRequestDelegationException(e); + } + + } + + /** + * Render a particular subset of data from a {@link TupleTable} to a + * particular {@link Renderer}. + * + * @param request + * The request encoding the particulars of the rendering to be + * done. + * @param postData + * The selected page (only relevant for {@link JQGridRenderer} + * rendering) + * @param totalPages + * The total number of pages (only relevant for + * {@link JQGridRenderer} rendering) + * @param tupleTable + * The table from which to render the data. + */ + private void renderData(MolgenisRequest request, JQGridPostData postData, int totalPages, + final TupleTable tupleTable) throws TableException + { + + String strViewType = request.getString("viewType"); + if (StringUtils.isEmpty(strViewType)) + { + strViewType = "JQ_GRID"; + } + + try + { + final ViewFactory viewFactory = new ViewFactoryImpl(); + final Renderers.Renderer view = viewFactory.createView(strViewType); + view.export(request, request.getString("caption"), tupleTable, totalPages, postData.getPage()); + } + catch (final Exception e) + { + throw new TableException(e); + } + } + + /** + * Extract the filter rules from the sent jquery request, and convert them + * into Molgenis Query rules. + * + * @param filters + * A request containing filter rules + * @return A list of QueryRules that represent the filter rules from the + * request. + */ + private static List createQueryRulesFromJQGridRequest(JQGridFilter filters) + { + final List rules = new ArrayList(); + if (filters != null) + { + final String groupOp = filters.getGroupOp(); + + int ruleIdx = 0; + for (final JQGridRule rule : filters.getRules()) + { + final QueryRule queryRule = convertOperator(rule); + rules.add(queryRule); + + final boolean notLast = filters.getRules().size() - 1 != ruleIdx++; + if (groupOp.equals("OR") && notLast) + { + rules.add(new QueryRule(QueryRule.Operator.OR)); + } + } + } + return rules; + } + + /** + * Create a {@link QueryRule} based on a jquery operator string, from the + * filter popup/dropdown in the {@link JQGridRenderer} UI. Example: + * Supplying the arguments 'name', 'ne', 'Asia' creates a QueryRule that + * filters for rows where the 'name' column does not equal 'Asia'. + * + * @param field + * The field to which to apply the operator + * @param op + * The operator string (jquery syntax) + * @param value + * The value (if any) for the right-hand side of the operator + * expression. + * @return A new QueryRule that represents the supplied jquery expression. + */ + + private static QueryRule convertOperator(JQGridRule jqGridRule) + { + // ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'] + QueryRule rule = new QueryRule(jqGridRule.getField(), QueryRule.Operator.EQUALS, jqGridRule.getData()); + switch (jqGridRule.getOp()) + { + case eq: + rule.setOperator(QueryRule.Operator.EQUALS); + return rule; + case ne: + rule.setOperator(QueryRule.Operator.EQUALS); + return toNotRule(rule); + case lt: + rule.setOperator(QueryRule.Operator.LESS); + return rule; + case le: + rule.setOperator(QueryRule.Operator.LESS_EQUAL); + return rule; + case gt: + rule.setOperator(QueryRule.Operator.GREATER); + return rule; + case ge: + rule.setOperator(QueryRule.Operator.GREATER_EQUAL); + return rule; + case bw: + rule.setValue(jqGridRule.getData() + "%"); + rule.setOperator(QueryRule.Operator.LIKE); + return rule; + case bn: + // NOT + rule.setValue(jqGridRule.getData() + "%"); + rule.setOperator(QueryRule.Operator.LIKE); + rule = toNotRule(rule); + return rule; + case in: + rule.setOperator(QueryRule.Operator.IN); + return rule; + case ni: + // NOT + rule.setOperator(QueryRule.Operator.IN); + rule = toNotRule(rule); + return rule; + case ew: + rule.setValue("%" + jqGridRule.getData()); + rule.setOperator(QueryRule.Operator.LIKE); + return rule; + case en: + // NOT + rule.setValue("%" + jqGridRule.getData()); + rule.setOperator(QueryRule.Operator.LIKE); + return toNotRule(rule); + case cn: + rule.setValue("%" + jqGridRule.getData() + "%"); + rule.setOperator(QueryRule.Operator.LIKE); + return rule; + case nc: + // NOT + rule.setValue("%" + jqGridRule.getData() + "%"); + rule.setOperator(QueryRule.Operator.LIKE); + return toNotRule(rule); + default: + throw new IllegalArgumentException(String.format("Unkown Operator: %s", jqGridRule.getOp())); + } + } + + /** + * Add a 'NOT' operator to a particular rule. + * + * @param rule + * The rule to negate. + * @return A new {@link QueryRule} which is the negation of the supplied + * rule. + */ + private static QueryRule toNotRule(QueryRule rule) + { + return new QueryRule(QueryRule.Operator.NOT, rule); + } + + /** + * Create the HTML that is sent to the browser. Based on a Freemarker + * template file. + */ + @Override + public String toHtml() + { + final Map args = new HashMap(); + + args.put("tableId", super.getId()); + args.put("url", tupleTableBuilder.getUrl()); + + return new FreemarkerView(JQGridView.class, args).render(); + } + + /** + * Create a properly-configured grid with default settings, on first load. + */ + public void loadTupleTableConfig(Database db, MolgenisRequest request, TupleTable tupleTable) + throws TableException, IOException + { + + final JQGridConfiguration config = new JQGridConfiguration(db, getId(), "Name", tupleTableBuilder.getUrl(), + getLabel(), tupleTable); + + if (searchOptions != null) + { + config.setSearchOptions(searchOptions); + } + + Writer writer = new OutputStreamWriter(request.getResponse().getOutputStream(), Charset.forName("UTF-8")); + try + { + new Gson().toJson(config, writer); + } + finally + { + writer.close(); + } + } + + /** + * Function to build a datastructure filled with rows from a + * {@link TupleTable}, to be serialised by Gson and displayed from there by + * a jqGrid. + * + * @param rowCount + * The number of rows to select. + * @param totalPages + * The total number of pages of data (ie. dependent on size of + * dataset and nr. of rows per page) + * @param page + * The selected page. + * @param table + * The Tupletable from which to read the data. + * @return + */ + + public static JQGridResult buildJQGridResults(final int rowCount, final int totalPages, final int page, + final TupleTable table) throws TableException + { + final JQGridResult result = new JQGridResult(page, totalPages, rowCount); + + Iterator it = table.iterator(); + while (it.hasNext()) + { + Tuple row = it.next(); + final LinkedHashMap rowMap = new LinkedHashMap(); + + final List fieldNames = row.getFieldNames(); + for (final String fieldName : fieldNames) + { + final String rowValue = !row.isNull(fieldName) ? row.getString(fieldName) : "null"; + rowMap.put(fieldName, rowValue); // TODO encode to HTML + } + result.addRow(rowMap); + } + + return result; + } +} diff --git a/src/org/molgenis/framework/tupletable/view/JQGridViewCallback.java b/src/org/molgenis/framework/tupletable/view/JQGridViewCallback.java new file mode 100644 index 000000000..f0bb93ca7 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/JQGridViewCallback.java @@ -0,0 +1,9 @@ +package org.molgenis.framework.tupletable.view; + +import org.molgenis.framework.server.MolgenisRequest; +import org.molgenis.framework.tupletable.TupleTable; + +public interface JQGridViewCallback +{ + void beforeLoadConfig(MolgenisRequest request, TupleTable tupleTable); +} diff --git a/src/org/molgenis/framework/tupletable/view/ViewFactory.java b/src/org/molgenis/framework/tupletable/view/ViewFactory.java new file mode 100644 index 000000000..c080a97ae --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/ViewFactory.java @@ -0,0 +1,8 @@ +package org.molgenis.framework.tupletable.view; + +import org.molgenis.framework.tupletable.view.renderers.Renderers.Renderer; + +public interface ViewFactory +{ + public Renderer createView(String viewName); +} diff --git a/src/org/molgenis/framework/tupletable/view/ViewFactoryImpl.java b/src/org/molgenis/framework/tupletable/view/ViewFactoryImpl.java new file mode 100644 index 000000000..262f723c1 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/ViewFactoryImpl.java @@ -0,0 +1,31 @@ +package org.molgenis.framework.tupletable.view; + +import org.molgenis.framework.tupletable.view.renderers.Renderers.CSVRenderer; +import org.molgenis.framework.tupletable.view.renderers.Renderers.ExcelRenderer; +import org.molgenis.framework.tupletable.view.renderers.Renderers.JQGridRenderer; +import org.molgenis.framework.tupletable.view.renderers.Renderers.Renderer; +import org.molgenis.framework.tupletable.view.renderers.Renderers.SPSSRenderer; + +public class ViewFactoryImpl implements ViewFactory +{ + public Renderer createView(String viewName) + { + if (viewName.equals("JQ_GRID")) + { + return new JQGridRenderer(); + } + else if (viewName.equals("EXCEL")) + { + return new ExcelRenderer(); + } + else if (viewName.equals("CSV")) + { + return new CSVRenderer(); + } + else if (viewName.equals("SPSS")) + { + return new SPSSRenderer(); + } + throw new IllegalArgumentException(String.format("view: %s not found", viewName)); + } +} diff --git a/src/org/molgenis/framework/tupletable/view/renderers/AbstractExporter.java b/src/org/molgenis/framework/tupletable/view/renderers/AbstractExporter.java new file mode 100644 index 000000000..9d228d28d --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/renderers/AbstractExporter.java @@ -0,0 +1,19 @@ +package org.molgenis.framework.tupletable.view.renderers; + +import java.io.OutputStream; + +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.framework.tupletable.TupleTable; + +public abstract class AbstractExporter +{ + protected final TupleTable tupleTable; + + public AbstractExporter(TupleTable tupleTable) + { + if (tupleTable == null) throw new IllegalArgumentException(); + this.tupleTable = tupleTable; + } + + public abstract void export(OutputStream os) throws TableException; +} diff --git a/src/org/molgenis/framework/tupletable/view/renderers/CsvExporter.java b/src/org/molgenis/framework/tupletable/view/renderers/CsvExporter.java new file mode 100644 index 000000000..4736c80ca --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/renderers/CsvExporter.java @@ -0,0 +1,53 @@ +package org.molgenis.framework.tupletable.view.renderers; + +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.framework.tupletable.TupleTable; +import org.molgenis.model.elements.Field; +import org.molgenis.util.CsvWriter; +import org.molgenis.util.Tuple; + +/** + * Export TupleTable to CSV file. + * + * This should replace CsvWriter class. TODO: + */ +public class CsvExporter extends AbstractExporter +{ + public CsvExporter(TupleTable table) + { + super(table); + } + + @Override + public void export(OutputStream os) throws TableException + { + CsvWriter csv = new CsvWriter(os); + + // write headers + List headers = new ArrayList(); + for (Field column : tupleTable.getColumns()) + { + headers.add(column.getSqlName()); + } + csv.setHeaders(headers); + csv.writeHeader(); + + // write rows + for (Tuple row : tupleTable) + { + csv.writeRow(row); + } + + csv.close(); + } + + public void initHeaders(OutputStream os) + { + // TODO Auto-generated method stub + + } +} diff --git a/src/org/molgenis/framework/tupletable/view/renderers/ExcelExporter.java b/src/org/molgenis/framework/tupletable/view/renderers/ExcelExporter.java new file mode 100644 index 000000000..1e3737d60 --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/renderers/ExcelExporter.java @@ -0,0 +1,145 @@ +package org.molgenis.framework.tupletable.view.renderers; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; + +import org.apache.poi.hssf.usermodel.HSSFHeader; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.CreationHelper; +import org.apache.poi.ss.usermodel.Header; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.framework.tupletable.TupleTable; +import org.molgenis.model.elements.Field; +import org.molgenis.util.Tuple; + +public class ExcelExporter extends AbstractExporter +{ + + private final Workbook wb; + private final Sheet sh; + private final CreationHelper creationHelper; + private final CellStyle dateCellStyle; + private final CellStyle dateTimeCellStyle; + + public ExcelExporter(TupleTable tableModel) + { + super(tableModel); + wb = new SXSSFWorkbook(100); // param indicates streaming buffer size + sh = wb.createSheet(); + + // create cell styles, required for proper date output + creationHelper = wb.getCreationHelper(); + + dateCellStyle = wb.createCellStyle(); + dateCellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy/mm/dd")); + + dateTimeCellStyle = wb.createCellStyle(); + dateTimeCellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy/m/d h:mm")); + } + + @Override + public void export(OutputStream os) throws TableException + { + createHeaders(); + + int rowIdx = 1; // headers are row 0 + for (Tuple row : tupleTable) + { + writeRow(row, rowIdx++); + } + try + { + wb.write(os); + } + catch (IOException e) + { + throw new TableException(e); + } + } + + private void createHeaders() throws TableException + { + final Header header = sh.getHeader(); + header.setCenter("Center Header"); + header.setLeft("Left Header"); + header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") + HSSFHeader.fontSize((short) 16) + + "Right w/ Stencil-Normal Italic font and size 16"); + + final Row headerRow = sh.createRow(0); + int colIdx = 0; + for (Field column : tupleTable.getColumns()) + { + final Cell headerCell = headerRow.createCell(colIdx++); + headerCell.setCellValue(column.getName()); + } + } + + private void writeRow(Tuple row, int rowIdx) throws TableException + { + final Row excelRow = sh.createRow(rowIdx); + int colIdx = 0; + final List columns = tupleTable.getColumns(); + for (final Field column : columns) + { + final Cell c = excelRow.createCell(colIdx++); + writeTypedCell(c, column, row); + } + } + + private void writeTypedCell(Cell c, Field column, Tuple row) throws TableException + { + try + { + String columnName = column.getSqlName(); + switch (column.getType().getEnumType()) + { + case RICHTEXT: + case CHAR: + case TEXT: + case STRING: + c.setCellValue(row.getString(columnName)); + break; + case INT: + case CATEGORICAL: // TODO : check the crap out of this + case LONG: + if (row.getInt(columnName) != null) + { + c.setCellValue(row.getInt(columnName)); + } + break; + case DATE: + if (row.getDate(columnName) != null) + { + c.setCellStyle(dateCellStyle); + c.setCellValue(row.getDate(columnName)); + } + break; + case DATE_TIME: + if (row.getDate(columnName) != null) + { + c.setCellStyle(dateTimeCellStyle); + c.setCellValue(row.getDate(columnName)); + } + break; + case DECIMAL: + if (row.getDouble(columnName) != null) + { + c.setCellValue(row.getDouble(columnName)); + } + break; + default: + throw new IllegalArgumentException(String.format("Type %s not available", column.getType())); + } + } + catch (Exception e) + { + throw new TableException(e); + } + } +} diff --git a/src/org/molgenis/framework/tupletable/view/renderers/Renderers.java b/src/org/molgenis/framework/tupletable/view/renderers/Renderers.java new file mode 100644 index 000000000..6c7ee63bd --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/renderers/Renderers.java @@ -0,0 +1,159 @@ +package org.molgenis.framework.tupletable.view.renderers; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.Charset; +import java.util.Arrays; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; + +import org.molgenis.framework.server.MolgenisRequest; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.framework.tupletable.TupleTable; +import org.molgenis.framework.tupletable.view.JQGridView; +import org.molgenis.framework.tupletable.view.JQGridJSObjects.JQGridResult; +import org.molgenis.framework.ui.html.HtmlWidget; +import org.molgenis.util.ZipUtils; +import org.molgenis.util.ZipUtils.DirectoryStructure; + +import com.google.gson.Gson; + +/** + * Class containing a series of simple renderers to do the administrative + * busywork required to render from a particular {@link TupleTable} to a + * particular view (current options are an {@link AbstractExporter} or a + * {@link HtmlWidget}. See the org.molgenis.modules.datatable.view package. + */ +public class Renderers +{ + + public static class HeaderHelper + { + public static void setHeader(HttpServletResponse response, String contentType, String fileName) + { + response.setContentType(contentType); + response.addHeader("Content-Disposition", "attachment; filename=" + fileName); + } + } + + /** + * Interface to render from a Table/request combination to a particular + * view. Current implementations are trivial except {@link SPSSRenderer}. + */ + public interface Renderer + { + public void export(MolgenisRequest request, String datasetName, TupleTable tupleTable, int totalPages, int page) + throws TableException, IOException; + } + + public static class JQGridRenderer implements Renderer + { + @Override + public void export(MolgenisRequest request, String fileName, TupleTable tupleTable, int totalPages, + int currentPage) throws TableException, IOException + { + final JQGridResult result = JQGridView.buildJQGridResults(tupleTable.getCount(), totalPages, currentPage, + tupleTable); + + Writer writer = new OutputStreamWriter(request.getResponse().getOutputStream(), Charset.forName("UTF-8")); + try + { + new Gson().toJson(result, writer); + } + finally + { + writer.close(); + } + } + } + + public static class ExcelRenderer implements Renderer + { + @Override + public void export(MolgenisRequest request, String fileName, TupleTable tupleTable, int totalPages, + int currentPage) throws TableException, IOException + { + HeaderHelper.setHeader(request.getResponse(), "application/ms-excel", fileName + ".xlsx"); + final ExcelExporter excelExport = new ExcelExporter(tupleTable); + excelExport.export(request.getResponse().getOutputStream()); + } + } + + public static class CSVRenderer implements Renderer + { + @Override + public void export(MolgenisRequest request, String fileName, TupleTable tupleTable, int totalPages, + int currentPage) throws TableException, IOException + { + HeaderHelper.setHeader(request.getResponse(), "application/ms-excel", fileName + ".csv"); + final CsvExporter csvExporter = new CsvExporter(tupleTable); + csvExporter.export(request.getResponse().getOutputStream()); + } + } + + /** + * Several things need to happen to export to SPSS: + *
    + *
  • Several files need to be created in the temp dir: + *
  • One textfile encoding the actual data, for example as tab-separated + * values.
  • + *
  • One .sps syntax script that will set the variables and labels in SPSS + * and load the data.
  • + *
  • One textfile with instructions on how to use the script in SPSS.
  • + *
  • These files should be compressed together into a .zip file for + * download.
  • + *
+ */ + public static class SPSSRenderer implements Renderer + { + @Override + public void export(MolgenisRequest request, String fileName, TupleTable tupleTable, int totalPages, + int currentPage) throws TableException, IOException + { + try + { + final File tempDir = new File(System.getProperty("java.io.tmpdir")); + final File spssFile = File.createTempFile("spssExport", ".sps", tempDir); + final File spssCsvFile = File.createTempFile("csvSpssExport", ".csv", tempDir); + // TODO: instruction .txt file. + final File zipExport = File.createTempFile("spssExport", ".zip", tempDir); + + final FileOutputStream spssFileStream = new FileOutputStream(spssFile); + final FileOutputStream spssCsvFileStream = new FileOutputStream(spssCsvFile); + final SPSSExporter spssExporter = new SPSSExporter(tupleTable); + spssExporter.export(spssCsvFileStream, spssFileStream, spssCsvFile.getName()); + + spssCsvFileStream.close(); + spssFileStream.close(); + ZipUtils.compress(Arrays.asList(spssFile, spssCsvFile), zipExport, DirectoryStructure.EXCLUDE_DIR); + HeaderHelper.setHeader(request.getResponse(), "application/octet-stream", fileName + ".zip"); + exportFile(zipExport, request.getResponse()); + } + catch (Exception e) + { + throw new TableException(e); + } + } + + private void exportFile(File file, HttpServletResponse response) throws IOException + { + FileInputStream fileIn = new FileInputStream(file); + ServletOutputStream out = response.getOutputStream(); + + byte[] outputByte = new byte[4096]; + // copy binary content to output stream + while (fileIn.read(outputByte, 0, 4096) != -1) + { + out.write(outputByte, 0, 4096); + } + fileIn.close(); + out.flush(); + out.close(); + } + } +} \ No newline at end of file diff --git a/src/org/molgenis/framework/tupletable/view/renderers/SPSSExporter.java b/src/org/molgenis/framework/tupletable/view/renderers/SPSSExporter.java new file mode 100644 index 000000000..494698d2a --- /dev/null +++ b/src/org/molgenis/framework/tupletable/view/renderers/SPSSExporter.java @@ -0,0 +1,109 @@ +package org.molgenis.framework.tupletable.view.renderers; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.molgenis.MolgenisFieldTypes.FieldTypeEnum; +import org.molgenis.fieldtypes.CategoricalType; +import org.molgenis.fieldtypes.FieldType; +import org.molgenis.framework.tupletable.TableException; +import org.molgenis.framework.tupletable.TupleTable; +import org.molgenis.model.elements.Field; + +/** + * + * @author Daan Reid + * + * Exporter that writes to two streams; one of comma-separated values, + * and one SPSS script file to read them. + */ +public class SPSSExporter extends CsvExporter +{ + public SPSSExporter(TupleTable matrix) + { + super(matrix); + // SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); + } + + public void export(OutputStream csvOs, OutputStream spssOs, String csvFileName) throws TableException + { + super.export(csvOs); + writeSPSFile(spssOs, csvFileName); + } + + private void writeSPSFile(OutputStream spssOs, String csvFileName) throws TableException + { + BufferedWriter spsWriter = new BufferedWriter(new OutputStreamWriter(spssOs)); + + List columns = tupleTable.getColumns(); + StringWriter valLabels = new StringWriter(); + StringWriter colNames = new StringWriter(); + List categoricalFields = new ArrayList(); + + // write variable definitions + for (Field field : columns) + { + FieldType fieldType = field.getType(); + if (fieldType.getEnumType() == FieldTypeEnum.CATEGORICAL) + { + categoricalFields.add(field); + } + colNames.write(String.format("%s %s ", field.getName(), colTypeToSPSSType(fieldType.getEnumType()))); + } + + // add category labels to variables if appropriate + for (Field field : categoricalFields) + { + Map categoryMapping = ((CategoricalType) field.getType()).getCategoryMapping(); + valLabels.write(String.format("ADD VALUE LABELS %s ", field.getName())); + for (Entry entry : categoryMapping.entrySet()) + { + valLabels.write(String.format(" %s \'%s\' ", entry.getKey(), entry.getValue())); + } + valLabels.write("\n"); + } + + try + { + String spsFormatStr = String.format("GET DATA\n" + "/type = txt\n" + "/file = \'%s\'\n " + + "/qualifier = \'\"\'\n" + "/delimiters = \'\\t\'\n" + "/firstcase = 2\n" + "/variables = %s.\n" + + "/execute.", csvFileName, colNames.toString() + valLabels.toString()); + + spsWriter.write(spsFormatStr); + spsWriter.flush(); + spsWriter.close(); + } + catch (IOException e) + { + throw new TableException(e); + } + } + + private static String colTypeToSPSSType(FieldTypeEnum columnType) + { + switch (columnType) + { + case CATEGORICAL: + return "F"; + case DATE: + return "ADATE"; + case DATE_TIME: + return "ADATE"; + case DECIMAL: + return "F"; + case INT: + return "F"; + case STRING: + return "A"; + default: + throw new IllegalArgumentException("Unknown field type: " + columnType); + } + } +} diff --git a/src/org/molgenis/framework/ui/ApplicationController.java b/src/org/molgenis/framework/ui/ApplicationController.java index 1ab08a966..88007aec1 100644 --- a/src/org/molgenis/framework/ui/ApplicationController.java +++ b/src/org/molgenis/framework/ui/ApplicationController.java @@ -6,14 +6,12 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.log4j.Logger; import org.molgenis.MolgenisOptions; import org.molgenis.framework.db.Database; import org.molgenis.framework.security.Login; import org.molgenis.framework.server.MolgenisContext; +import org.molgenis.framework.server.MolgenisRequest; import org.molgenis.framework.ui.ScreenModel.Show; import org.molgenis.framework.ui.html.FreemarkerInput; import org.molgenis.framework.ui.html.HtmlSettings; @@ -33,7 +31,7 @@ */ public class ApplicationController extends SimpleScreenController { - public static String MOLGENIS_TEMP_PATH = "molgenis_temp"; + public static final String MOLGENIS_TEMP_PATH = "molgenis_temp"; /** autogenerated */ private static final long serialVersionUID = 3108474555679524568L; /** */ @@ -42,8 +40,6 @@ public class ApplicationController extends SimpleScreenController sessionVariables = new HashMap(); - - } diff --git a/src/org/molgenis/framework/ui/ApplicationModel.java b/src/org/molgenis/framework/ui/ApplicationModel.java index a8a930a96..6dc20c28d 100644 --- a/src/org/molgenis/framework/ui/ApplicationModel.java +++ b/src/org/molgenis/framework/ui/ApplicationModel.java @@ -49,18 +49,23 @@ public String getCustomHtmlBodyOnLoad() public void setTarget(ScreenController target) { - /*BUG: - This can be resolved to a NULL pointer - (When the underlying caller doesn't have required fields filled in ?) - To replicate: press the add new btn next to an entity which - has required fields not filled out - - * NullPointerException - at org.molgenis.framework.ui.ApplicationModel.setTarget(ApplicationModel.java:64) - at org.molgenis.framework.server.AbstractMolgenisServlet.handleGUIrequest(AbstractMolgenisServlet.java:607) - at org.molgenis.framework.server.AbstractMolgenisServlet.service(AbstractMolgenisServlet.java:242) - at org.molgenis.framework.server.AbstractMolgenisServlet.doPost(AbstractMolgenisServlet.java:178) - */ + /* + * BUG: This can be resolved to a NULL pointer (When the underlying + * caller doesn't have required fields filled in ?) To replicate: press + * the add new btn next to an entity which has required fields not + * filled out + * + * NullPointerException at + * org.molgenis.framework.ui.ApplicationModel.setTarget + * (ApplicationModel.java:64) at + * org.molgenis.framework.server.AbstractMolgenisServlet + * .handleGUIrequest(AbstractMolgenisServlet.java:607) at + * org.molgenis.framework + * .server.AbstractMolgenisServlet.service(AbstractMolgenisServlet + * .java:242) at + * org.molgenis.framework.server.AbstractMolgenisServlet.doPost + * (AbstractMolgenisServlet.java:178) + */ this.target = target.getModel(); } diff --git a/src/org/molgenis/framework/ui/ApplicationView.ftl b/src/org/molgenis/framework/ui/ApplicationView.ftl index 368b5ac83..e019ded9d 100644 --- a/src/org/molgenis/framework/ui/ApplicationView.ftl +++ b/src/org/molgenis/framework/ui/ApplicationView.ftl @@ -21,6 +21,6 @@ <@molgenis_footer /> \ No newline at end of file diff --git a/src/org/molgenis/framework/ui/EasyPluginController.java b/src/org/molgenis/framework/ui/EasyPluginController.java index 9cabe2fb8..2f297448c 100644 --- a/src/org/molgenis/framework/ui/EasyPluginController.java +++ b/src/org/molgenis/framework/ui/EasyPluginController.java @@ -38,7 +38,7 @@ public abstract class EasyPluginController extends Simple public EasyPluginController(String name, ScreenController parent) { super(name, null, parent); - this.setModel((M)this); + this.setModel((M) this); } /** @@ -54,8 +54,8 @@ public void handleRequest(Database db, Tuple request) throws HandleRequestDelega } public Show handleRequest(Database db, Tuple request, OutputStream out) throws HandleRequestDelegationException - { - final HttpServletRequest realRequest = ((MolgenisRequest)request).getRequest(); + { + final HttpServletRequest realRequest = ((MolgenisRequest) request).getRequest(); // automatically calls functions with same name as action delegate(request.getAction(), db, request, out); @@ -88,10 +88,12 @@ public void delegate(String action, Database db, Tuple request, OutputStream out } catch (NoSuchMethodException e1) { -// this.getModel().setMessages(new ScreenMessage("Unknown action: " + action, false)); -// logger.error("call of " + this.getClass().getName() + "(name=" + this.getName() + ")." + action -// + "(db,tuple) failed: " + e1.getMessage()); -// db.rollbackTx(); + // this.getModel().setMessages(new + // ScreenMessage("Unknown action: " + action, false)); + // logger.error("call of " + this.getClass().getName() + + // "(name=" + this.getName() + ")." + action + // + "(db,tuple) failed: " + e1.getMessage()); + // db.rollbackTx(); // useless - can't do this on every error! we cannot distinguish // exceptions because they are all InvocationTargetException // anyway @@ -100,7 +102,7 @@ public void delegate(String action, Database db, Tuple request, OutputStream out if (out != null) try { - //db.beginTx(); + // db.beginTx(); logger.debug("trying to use reflection to call " + this.getClass().getName() + "." + action); Method m = this.getClass().getMethod(action, Database.class, Tuple.class, OutputStream.class); m.invoke(this, db, request, out); @@ -212,24 +214,29 @@ public void setController(ScreenController controller) @Override public boolean isVisible() { - if (this.getApplicationController().getLogin().isAuthenticated()){ - try { - if (this.getApplicationController().getLogin().canRead(this)) { - return true; + if (this.getApplicationController().getLogin().isAuthenticated()) + { + try + { + if (this.getApplicationController().getLogin().canRead(this)) + { + return true; + } + } + catch (DatabaseException e) + { + e.printStackTrace(); } - } catch (DatabaseException e) { - e.printStackTrace(); } + return false; } - return false; - } - + @Override public String getLabel() { return this.label; } - + @Override public abstract ScreenView getView(); } diff --git a/src/org/molgenis/framework/ui/EasyPluginModel.java b/src/org/molgenis/framework/ui/EasyPluginModel.java index 62a8784f0..30618606e 100644 --- a/src/org/molgenis/framework/ui/EasyPluginModel.java +++ b/src/org/molgenis/framework/ui/EasyPluginModel.java @@ -102,11 +102,11 @@ public void setError(String message) { controller.setError(message); } - + @Override public String toString() { - return getClass().getSimpleName()+"(name="+getName()+")"; + return getClass().getSimpleName() + "(name=" + getName() + ")"; } @Override diff --git a/src/org/molgenis/framework/ui/EasyPluginView.java b/src/org/molgenis/framework/ui/EasyPluginView.java index b9f982ff8..59fd12648 100644 --- a/src/org/molgenis/framework/ui/EasyPluginView.java +++ b/src/org/molgenis/framework/ui/EasyPluginView.java @@ -8,7 +8,7 @@ public EasyPluginView(M model) { super(model); } - + public abstract HtmlElement getInputs(M model); @Override diff --git a/src/org/molgenis/framework/ui/FormController.java b/src/org/molgenis/framework/ui/FormController.java index 487e36e5d..14ada6d14 100644 --- a/src/org/molgenis/framework/ui/FormController.java +++ b/src/org/molgenis/framework/ui/FormController.java @@ -21,6 +21,8 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; +import org.molgenis.fieldtypes.MrefField; +import org.molgenis.fieldtypes.XrefField; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; import org.molgenis.framework.db.QueryRule; @@ -42,13 +44,11 @@ /** * @param */ -public abstract class FormController extends - SimpleScreenController> +public abstract class FormController extends SimpleScreenController> { // member variables /** */ - private static final transient Logger logger = Logger - .getLogger(FormController.class.getSimpleName()); + private static final transient Logger logger = Logger.getLogger(FormController.class.getSimpleName()); /** Helper object that takes care of database paging */ protected DatabasePager pager; @@ -74,8 +74,7 @@ public FormController(String name, ScreenController parent) // FIXME: this assumes first column is sortable... try { - this.pager = new LimitOffsetPager(getEntityClass(), model - .create().getFields().firstElement()); + this.pager = new LimitOffsetPager(getEntityClass(), model.create().getFields().firstElement()); // this.pager = new PrimaryKeyPager(view.getEntityClass(), // view.getDatabase(), view.create().getIdField()); @@ -113,8 +112,7 @@ public Show handleRequest(Database db, Tuple request, OutputStream out) model.setSelectedIds(request.getList(FormModel.INPUT_SELECTED)); // if none selected, make empty list - if (model.getSelectedIds() == null) model - .setSelectedIds(new ArrayList()); + if (model.getSelectedIds() == null) model.setSelectedIds(new ArrayList()); // get the current command if any ScreenCommand command = model.getCommand(action); @@ -144,8 +142,7 @@ else if (action.equals("filter_remove")) // reset the filters... pager.resetFilters(); - for (QueryRule rewrittenRule : this.rewriteAllRules(db, - model.getUserRules())) + for (QueryRule rewrittenRule : this.rewriteAllRules(db, model.getUserRules())) { pager.addFilter(rewrittenRule); } @@ -162,12 +159,14 @@ else if (action.equals("filter_set")) this.addFilter(pager, db, request); // go to this screen if it is not selected - // DISABLED/DEPRECATED: use &select=${screenName} to go to the desired screen instead - // this is the default application behaviour and should be respected -// if (getParent() != null) -// { -// getParent().setSelected(model.getName()); -// } + // DISABLED/DEPRECATED: use &select=${screenName} to go to the + // desired screen instead + // this is the default application behaviour and should be + // respected + // if (getParent() != null) + // { + // getParent().setSelected(model.getName()); + // } } else if (action.equals("update")) @@ -200,8 +199,7 @@ else if (action.equals("last")) } else if (action.equals("sort")) { - String attribute = getSearchField(request - .getString("__sortattribute")); + String attribute = getSearchField(request.getString("__sortattribute")); if (pager.getOrderByField().equals(attribute)) { @@ -231,8 +229,7 @@ else if (action.equals("hideColumn")) List UserHiddencols = model.getUserHiddenColumns(); String attribute = request.getString("attribute"); - if (!UserHiddencols.contains(attribute)) UserHiddencols - .add(attribute); + if (!UserHiddencols.contains(attribute)) UserHiddencols.add(attribute); model.setUserHiddenColumns(UserHiddencols); } @@ -241,8 +238,7 @@ else if (action.equals("showColumn")) List UserHiddencols = model.getUserHiddenColumns(); String attribute = request.getString("attribute"); - if (UserHiddencols.contains(attribute)) UserHiddencols - .remove(attribute); + if (UserHiddencols.contains(attribute)) UserHiddencols.remove(attribute); model.setUserHiddenColumns(UserHiddencols); } // ACTIONS BELOW HAVE BEEN MOVED TO 'form.command' package @@ -307,65 +303,67 @@ else if (action.equals("showColumn")) return Show.SHOW_MAIN; } - private Show addFilter(DatabasePager pager, Database db, Tuple request) - throws DatabaseException, MolgenisModelException + private Show addFilter(DatabasePager pager, Database db, Tuple request) throws DatabaseException, + MolgenisModelException { FormModel model = getModel(); - + List rules = new ArrayList(); - //support for multiple filters in a request URL - //example and syntax: get all markers between basepair position 150 and 300: - //?__target=Markers&__action=filter_set&__filter_attribute=Marker_bpstart&__filter_operator=GREATER&__filter_value=150&__filter_attribute1=Marker_bpstart&__filter_operator1=LESS&__filter_value1=300 - //keep adding numbers for multiple filters, e.g. __filter_attribute2, __filter_attribute3 and so on - for(int filterIndex = 0; filterIndex < 100; filterIndex ++) + // support for multiple filters in a request URL + // example and syntax: get all markers between basepair position 150 and + // 300: + // ?__target=Markers&__action=filter_set&__filter_attribute=Marker_bpstart&__filter_operator=GREATER&__filter_value=150&__filter_attribute1=Marker_bpstart&__filter_operator1=LESS&__filter_value1=300 + // keep adding numbers for multiple filters, e.g. __filter_attribute2, + // __filter_attribute3 and so on + for (int filterIndex = 0; filterIndex < 100; filterIndex++) { - //for the first filter, usually the only one, keep the normal 'getters': - //e.g. "__filter_attribute" and not "__filter_attribute1" - //for subsequent ones, add a number to get multiple filters from the request + // for the first filter, usually the only one, keep the normal + // 'getters': + // e.g. "__filter_attribute" and not "__filter_attribute1" + // for subsequent ones, add a number to get multiple filters from + // the request String getThisFilter = ""; - if(filterIndex != 0) + if (filterIndex != 0) { getThisFilter = filterIndex + ""; } - - try{ - //get the operator - Operator operator = QueryRule.Operator.valueOf(request - .getString("__filter_operator" + getThisFilter)); - - //get the value + + try + { + // get the operator + Operator operator = QueryRule.Operator.valueOf(request.getString("__filter_operator" + getThisFilter)); + + // get the value String value = request.getString("__filter_value" + getThisFilter); - + if (StringUtils.isEmpty(value)) { // to prevent null-pointer exception value = ""; } - + // automatically add LIKE delimiters % if (operator.equals(Operator.LIKE) && !value.contains("%")) { value = "%" + value + "%"; } - - //create the rule - QueryRule rule = new QueryRule(request.getString("__filter_attribute" + getThisFilter), - operator, value); - + + // create the rule + QueryRule rule = new QueryRule(request.getString("__filter_attribute" + getThisFilter), operator, value); + rules.add(rule); } - catch(Exception e) + catch (Exception e) { break; } } - + model.getUserRules().addAll(rules); // reload the filters... pager.resetFilters(); - for (QueryRule rewrittenRule : this.rewriteAllRules(db, - model.getUserRules())) + for (QueryRule rewrittenRule : this.rewriteAllRules(db, model.getUserRules())) { pager.addFilter(rewrittenRule); } @@ -375,7 +373,7 @@ private Show addFilter(DatabasePager pager, Database db, Tuple request) pager.addFilter(r); } pager.first(db); - + return Show.SHOW_MAIN; } @@ -385,8 +383,7 @@ private Show addFilter(DatabasePager pager, Database db, Tuple request) * @throws DatabaseException * @throws MolgenisModelException */ - public QueryRule[] rewriteAllRules(Database db, - List rulesToRewrite) throws DatabaseException, + public QueryRule[] rewriteAllRules(Database db, List rulesToRewrite) throws DatabaseException, MolgenisModelException { List result = new ArrayList(); @@ -398,8 +395,7 @@ public QueryRule[] rewriteAllRules(Database db, Class entityClass = this.getEntityClass(); - org.molgenis.model.elements.Entity eType = db.getMetaData() - .getEntity(entityClass.getSimpleName()); // TODO + org.molgenis.model.elements.Entity eType = db.getMetaData().getEntity(entityClass.getSimpleName()); // TODO QueryRule orRule = new QueryRule(Operator.OR); boolean first = true; @@ -408,15 +404,22 @@ public QueryRule[] rewriteAllRules(Database db, // "__Type" for (Field field : eType.getFields()) { - //System.out.println("*** FIELD NAME : " + field.getName().toLowerCase()); + // System.out.println("*** FIELD NAME : " + + // field.getName().toLowerCase()); if (!field.getName().equals(Field.TYPE_FIELD)) { // getsSearchField will map the field to field_name in // case of xref/mref - QueryRule fieldRule = new QueryRule( - this.getSearchField(field.getName()), - r.getOperator(), r.getValue()); + QueryRule fieldRule = new QueryRule(this.getSearchField(field.getName()), r.getOperator(), + r.getValue()); + + if (field.getType() instanceof XrefField || field.getType() instanceof MrefField) + { + List labels = field.getXrefLabels(); + if (labels.size() > 0) fieldRule.setField(field.getXrefLabels().get(0).getName()); + } + // if(field.getType().getClass().getSimpleName().equals("XrefField") // || // field.getType().getClass().getSimpleName().equals("MrefField") @@ -425,7 +428,8 @@ public QueryRule[] rewriteAllRules(Database db, // fieldRule = new QueryRule(field.getName(), // r.getOperator(), r.getValue()); // } - //System.out.println("*** QUERYRULE : " + fieldRule.toString()); + // System.out.println("*** QUERYRULE : " + + // fieldRule.toString()); // add 'or' except for first filter rule if (first) first = false; else @@ -464,24 +468,23 @@ public void reload(Database db) // check whether the parent has changed and then reset List newSystemRules = model.getSystemRules(); - if (!newSystemRules.equals(model.getSystemRules())) + // if (!newSystemRules.equals(model.getSystemRules())) + // { + // remember old user filters + // List oldRules = Arrays.asList(pager.getFilters()); + pager.resetFilters(); + for (QueryRule rule : newSystemRules) { - // remember old user filters - // List oldRules = Arrays.asList(pager.getFilters()); - pager.resetFilters(); - for (QueryRule rule : newSystemRules) - { - pager.addFilter(rule); - } + pager.addFilter(rule); + } - model.setSystemRules(newSystemRules); + model.setSystemRules(newSystemRules); - for (QueryRule rule : this.rewriteAllRules(db, - model.getUserRules())) - { - pager.addFilter(rule); - } + for (QueryRule rule : this.rewriteAllRules(db, model.getUserRules())) + { + pager.addFilter(rule); } + // } // check view and set limit accordingly // if (view.getMode().equals(Mode.EDIT_VIEW) && !view.isReadonly()) @@ -550,8 +553,7 @@ public List getData(Database db) throws DatabaseException FormModel model = getModel(); // set form level rights - boolean formReadonly = model.isReadonly() - || !model.getLogin().canWrite(model.create().getClass()); + boolean formReadonly = model.isReadonly() || !model.getLogin().canWrite(model.create().getClass()); model.setReadonly(formReadonly); // load the rows @@ -564,8 +566,7 @@ public List getData(Database db) throws DatabaseException for (E record : allRecords) { - boolean rowReadonly = formReadonly - || !model.getLogin().canWrite(record.getClass()); + boolean rowReadonly = formReadonly || !model.getLogin().canWrite(record.getClass()); if (rowReadonly) record.setReadonly(true); // else @@ -586,8 +587,7 @@ public List getData(Database db) throws DatabaseException * @throws DatabaseException * @throws IOException */ - public boolean doAdd(Database db, Tuple request) throws ParseException, - DatabaseException, IOException + public boolean doAdd(Database db, Tuple request) throws ParseException, DatabaseException, IOException { ScreenMessage msg = null; Entity entity = getModel().create(); @@ -598,8 +598,7 @@ public boolean doAdd(Database db, Tuple request) throws ParseException, db.beginTx(); entity.set(request, false); int updatedRows = 0; - if (request.getObject(FormModel.INPUT_BATCHADD) != null - && request.getInt(FormModel.INPUT_BATCHADD) > 1) + if (request.getObject(FormModel.INPUT_BATCHADD) != null && request.getInt(FormModel.INPUT_BATCHADD) > 1) { // batch int i; @@ -614,8 +613,7 @@ public boolean doAdd(Database db, Tuple request) throws ParseException, } db.commitTx(); - msg = new ScreenMessage("ADD SUCCESS: affected " + updatedRows, - null, true); + msg = new ScreenMessage("ADD SUCCESS: affected " + updatedRows, null, true); result = true; // navigate to newly added record pager.last(db); @@ -624,8 +622,7 @@ public boolean doAdd(Database db, Tuple request) throws ParseException, catch (Exception e) { db.rollbackTx(); - msg = new ScreenMessage("ADD FAILED: " + e.getMessage(), null, - false); + msg = new ScreenMessage("ADD FAILED: " + e.getMessage(), null, false); result = false; } getModel().getMessages().add(msg); @@ -641,8 +638,7 @@ public boolean doAdd(Database db, Tuple request) throws ParseException, } // helper method - protected void doUpdate(Database db, Tuple request) - throws DatabaseException, IOException, ParseException + protected void doUpdate(Database db, Tuple request) throws DatabaseException, IOException, ParseException { Entity entity = getModel().create(); ScreenMessage msg = null; @@ -650,15 +646,13 @@ protected void doUpdate(Database db, Tuple request) { entity.set(request, false); int updatedRows = db.update(entity); - msg = new ScreenMessage("UPDATE SUCCESS: affected " + updatedRows, - null, true); + msg = new ScreenMessage("UPDATE SUCCESS: affected " + updatedRows, null, true); } catch (Exception e) { logger.error("doUpdate(): " + e); e.printStackTrace(); - msg = new ScreenMessage("UPDATE FAILED: " + e.getMessage(), null, - false); + msg = new ScreenMessage("UPDATE FAILED: " + e.getMessage(), null, false); } getModel().getMessages().add(msg); if (msg.isSuccess()) @@ -669,8 +663,7 @@ protected void doUpdate(Database db, Tuple request) } // helper method - protected void doRemove(Database db, Tuple request) - throws DatabaseException, ParseException, IOException + protected void doRemove(Database db, Tuple request) throws DatabaseException, ParseException, IOException { Entity entity = getModel().create(); ScreenMessage msg = null; @@ -678,16 +671,13 @@ protected void doRemove(Database db, Tuple request) { entity.set(request); int updatedRows = db.remove(entity); - if (updatedRows > 0) msg = new ScreenMessage( - "REMOVE SUCCESS: affected " + updatedRows, null, true); + if (updatedRows > 0) msg = new ScreenMessage("REMOVE SUCCESS: affected " + updatedRows, null, true); else - msg = new ScreenMessage( - "REMOVE FAILED: call system administrator", null, false); + msg = new ScreenMessage("REMOVE FAILED: call system administrator", null, false); } catch (Exception e) { - msg = new ScreenMessage("REMOVE FAILED: " + e.getMessage(), null, - false); + msg = new ScreenMessage("REMOVE FAILED: " + e.getMessage(), null, false); } getModel().getMessages().add(msg); @@ -713,9 +703,8 @@ public void doXrefselect(Tuple request) throws DatabaseException // set the filter to select the xref-ed entity pager.resetFilters(); getModel().setUserRules(new ArrayList()); - QueryRule rule = new QueryRule(request.getString("attribute"), - QueryRule.Operator.valueOf(request.getString("operator")), - request.getString("value")); + QueryRule rule = new QueryRule(request.getString("attribute"), QueryRule.Operator.valueOf(request + .getString("operator")), request.getString("value")); pager.addFilter(rule); // tell "my" menu to select me @@ -727,7 +716,7 @@ public void doXrefselect(Tuple request) throws DatabaseException if (aParent instanceof MenuModel) { parentRequest.set("select", aChildName); - MenuController c = (MenuController) (Object) aParent; + MenuController c = (MenuController) aParent; c.doSelect(parentRequest); } aChildName = aParent.getName(); @@ -929,8 +918,7 @@ public List getVisibleColumnNames() { // strip prefix = this.getEntityClass() + "_" String name = i.getName(); - name = name.substring(this.getEntityClass().getSimpleName() - .length() + 1); + name = name.substring(this.getEntityClass().getSimpleName().length() + 1); // then add _label using getSearchField() where needed showColumns.add(getSearchField(name)); @@ -948,7 +936,7 @@ public ScreenView getView() { return new FreemarkerView("FormView.ftl", getModel()); } - + /** * Provides the class of the entitites managed by this form. Note: Java * erases the specific type of E, therefore we cannot say E.newInstance(); diff --git a/src/org/molgenis/framework/ui/FormModel.java b/src/org/molgenis/framework/ui/FormModel.java index cad2b70b2..b010d4c0b 100644 --- a/src/org/molgenis/framework/ui/FormModel.java +++ b/src/org/molgenis/framework/ui/FormModel.java @@ -21,6 +21,7 @@ import java.util.TreeMap; import java.util.Vector; +import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.molgenis.framework.db.CsvToDatabase; import org.molgenis.framework.db.Database; @@ -74,8 +75,7 @@ public static class ParentFilter private List parentLabels; private String xrefToParent; - public ParentFilter(String parentForm, String parentId, - List parentLabel, String xrefToParent) + public ParentFilter(String parentForm, String parentId, List parentLabel, String xrefToParent) { this.parentForm = parentForm; this.parentId = parentId; @@ -164,15 +164,17 @@ public String toString() public static final String ACTION_DOWNLOAD = "download"; // PROPERTIES (default initialization is done in reset!) - private static final transient Logger logger = Logger - .getLogger(FormModel.class); + private static final transient Logger logger = Logger.getLogger(FormModel.class); /** List of actions of this screen */ private Map commands = new LinkedHashMap(); /** Optional custom header for the selected form screen */ private String header; - + + /** Optional description for the selected form screen */ + private String description; + /** entity csv reader */ private CsvToDatabase csvReader; @@ -270,10 +272,10 @@ public FormModel(FormController controller) // TXT file: Download all super.addCommand(new DownloadAllCommand("download_txt_all", this.getController())); - + // XLS file: Download visible super.addCommand(new DownloadVisibleXlsCommand("download_xls_visible", this.getController())); - + // XLS file: Download Selected super.addCommand(new DownloadSelectedXlsCommand("download_xls_selected", this.getController())); @@ -282,32 +284,31 @@ public FormModel(FormController controller) // File: Add batch super.addCommand(new AddBatchCommand("upload_csv", this.getController())); - + // File: Add batch super.addCommand(new AddCsvFileCommand("upload_csvfile", this.getController())); - + // Sending data to a Galaxy server. // Note: We do not send the actual data. - // Instead we send a link that Galaxy can GET or POST to fetch the data. - + // Instead we send a link that Galaxy can GET or POST to fetch the data. + // Todo: add option to send only selected records/fields to Galaxy. // File: Send Selected to Galaxy - //super.addCommand(new GalaxyCommand("send_selected_to_galaxy", this.getController())); - + // super.addCommand(new GalaxyCommand("send_selected_to_galaxy", + // this.getController())); + // File: Send All to Galaxy super.addCommand(new GalaxyCommand("send_all_to_galaxy", this.getController())); - + // EDIT MENU // EDIT: Add new record super.addCommand(new AddCommand("edit_new", this.getController())); // EDIT: Update selected - super.addCommand(new EditSelectedCommand("edit_update_selected", this - .getController())); + super.addCommand(new EditSelectedCommand("edit_update_selected", this.getController())); // EDIT: Remove selected - super.addCommand(new RemoveSelectedCommand("edit_remove_selected", this - .getController())); + super.addCommand(new RemoveSelectedCommand("edit_remove_selected", this.getController())); // menu VIEW // ScreenCommand v2 = new ViewRecordViewCommand("recordview", @@ -316,38 +317,30 @@ public FormModel(FormController controller) // super.addCommand("View", v2); // v3.setToolbar(true); - super.addCommand(new ViewEditViewCommand("editview", this - .getController())); - super.addCommand(new ViewListViewCommand("listview", this - .getController())); + super.addCommand(new ViewEditViewCommand("editview", this.getController())); + super.addCommand(new ViewListViewCommand("listview", this.getController())); - ChangeListLimitCommand view_5 = new ChangeListLimitCommand( - "view_5show5", this.getController()); + ChangeListLimitCommand view_5 = new ChangeListLimitCommand("view_5show5", this.getController()); view_5.setLimit(5); super.addCommand(view_5); - ChangeListLimitCommand view_10 = new ChangeListLimitCommand( - "view_6show10", this.getController()); + ChangeListLimitCommand view_10 = new ChangeListLimitCommand("view_6show10", this.getController()); view_5.setLimit(10); super.addCommand(view_10); - ChangeListLimitCommand view_20 = new ChangeListLimitCommand( - "view_7show20", this.getController()); + ChangeListLimitCommand view_20 = new ChangeListLimitCommand("view_7show20", this.getController()); view_20.setLimit(20); super.addCommand(view_20); - ChangeListLimitCommand view_50 = new ChangeListLimitCommand( - "view_8show50", this.getController()); + ChangeListLimitCommand view_50 = new ChangeListLimitCommand("view_8show50", this.getController()); view_50.setLimit(50); super.addCommand(view_50); - ChangeListLimitCommand view_100 = new ChangeListLimitCommand( - "view_9show100", this.getController()); + ChangeListLimitCommand view_100 = new ChangeListLimitCommand("view_9show100", this.getController()); view_100.setLimit(100); super.addCommand(view_100); - ChangeListLimitCommand view_500 = new ChangeListLimitCommand( - "view_10show500", this.getController()); + ChangeListLimitCommand view_500 = new ChangeListLimitCommand("view_10show500", this.getController()); view_500.setLimit(500); super.addCommand(view_500); @@ -429,15 +422,11 @@ public QueryRule[] getRules(boolean includingLimitOffset) rules.addAll(this.getUserRules()); if (includingLimitOffset) { - if (this.limit > 0) rules.add(new QueryRule( - QueryRule.Operator.LIMIT, this.limit)); - if (this.offset > 0) rules.add(new QueryRule( - QueryRule.Operator.OFFSET, this.offset)); + if (this.limit > 0) rules.add(new QueryRule(QueryRule.Operator.LIMIT, this.limit)); + if (this.offset > 0) rules.add(new QueryRule(QueryRule.Operator.OFFSET, this.offset)); } - if (this.sortby != "") rules.add(new QueryRule(this.sortMode, - this.sortby)); - logger.debug("rules.size: " + rules.size() + "=" - + this.getSystemRules().size() + "+" + if (!StringUtils.equals(this.sortby, "")) rules.add(new QueryRule(this.sortMode, this.sortby)); + logger.debug("rules.size: " + rules.size() + "=" + this.getSystemRules().size() + "+" + this.getUserRules().size()); return rules.toArray(new QueryRule[rules.size()]); } @@ -454,14 +443,12 @@ public E create() // set defaults for xrefs for (ParentFilter pf : this.getParentFilters()) { - FormModel parent = (FormModel) this.getController() - .get(pf.getParentForm()).getModel(); + FormModel parent = (FormModel) this.getController().get(pf.getParentForm()).getModel(); List records = parent.getRecords(); if (records.size() > 0) { // xref only - Object value = ((Entity) records.get(0)).get(pf - .getParentId()); + Object value = ((Entity) records.get(0)).get(pf.getParentId()); if (!(value instanceof List) && value != null) { entity.set(pf.getXrefToParent(), value); @@ -470,8 +457,7 @@ public E create() for (String labelName : pf.getParentLabels()) { Object label = ((Entity) records.get(0)).get(labelName); - entity.set(pf.getXrefToParent() + "_" + labelName, - label); + entity.set(pf.getXrefToParent() + "_" + labelName, label); } } } @@ -481,8 +467,7 @@ public E create() catch (Exception e) { // should never happen - logger.error("failed to create class " - + getController().getEntityClass() + ": " + e); + logger.error("failed to create class " + getController().getEntityClass() + ": " + e); e.printStackTrace(); } return null; @@ -496,8 +481,7 @@ public E create() public Vector getHeaders() { Vector headers = new Vector(); - for (HtmlInput input : getController().getInputs(this.create(), true) - .getInputs()) + for (HtmlInput input : getController().getInputs(this.create(), true).getInputs()) { headers.add(input.getLabel()); } @@ -579,8 +563,7 @@ public Vector getFilters() throws DatabaseException } } - filters.add(label + " " + rule.getOperator().toString() + " " - + rule.getValue()); + filters.add(label + " " + rule.getOperator().toString() + " " + rule.getValue()); } @@ -716,18 +699,29 @@ public List getRecords() { return records; } - + /** Getter/setter for optional custom header for the selected form screen */ public String getHeader() { return this.header; } - + public void setHeader(String header) { this.header = header; } + /** Getter/setter for optional description for the selected form screen */ + public String getDescription() + { + return this.description; + } + + public void setDescription(String description) + { + this.description = description; + } + /** * User defined filtering rules. For example, filtering by a field such as * date. @@ -757,15 +751,13 @@ public List getSystemRules() List rules = new ArrayList(); // parent filters - if (this.getParentFilters() != null - && this.getParentFilters().size() > 0) + if (this.getParentFilters() != null && this.getParentFilters().size() > 0) { List xref_filters = new ArrayList(); for (ParentFilter pf : this.getParentFilters()) { - FormModel parent = (FormModel) this.getController() - .get(pf.getParentForm()).getModel(); + FormModel parent = (FormModel) this.getController().get(pf.getParentForm()).getModel(); List records = parent.getRecords(); // add filters for xref or mref relationships (if any) @@ -774,8 +766,7 @@ public List getSystemRules() if (records.size() > 0) { - Object parentValue = ((Entity) records.get(0)).get(pf - .getParentId()); + Object parentValue = ((Entity) records.get(0)).get(pf.getParentId()); // mref? if (parentValue instanceof List) { @@ -784,12 +775,9 @@ public List getSystemRules() { for (int i = 0; i < values.size(); i++) { - QueryRule rule = new QueryRule( - pf.getXrefToParent(), - QueryRule.Operator.EQUALS, + QueryRule rule = new QueryRule(pf.getXrefToParent(), QueryRule.Operator.EQUALS, values.get(i)); - if (xref_filters.size() > 0) xref_filters - .add(new QueryRule(Operator.OR)); + if (xref_filters.size() > 0) xref_filters.add(new QueryRule(Operator.OR)); xref_filters.add(rule); } } @@ -797,12 +785,9 @@ public List getSystemRules() // impossible condition else { - QueryRule rule = new QueryRule( - pf.getXrefToParent(), - QueryRule.Operator.EQUALS, + QueryRule rule = new QueryRule(pf.getXrefToParent(), QueryRule.Operator.EQUALS, Integer.MIN_VALUE); - if (xref_filters.size() > 0) xref_filters - .add(new QueryRule(Operator.OR)); + if (xref_filters.size() > 0) xref_filters.add(new QueryRule(Operator.OR)); xref_filters.add(rule); } @@ -810,10 +795,8 @@ public List getSystemRules() // xref else if (parentValue != null) { - QueryRule rule = new QueryRule(pf.getXrefToParent(), - QueryRule.Operator.EQUALS, parentValue); - if (xref_filters.size() > 0) xref_filters - .add(new QueryRule(Operator.OR)); + QueryRule rule = new QueryRule(pf.getXrefToParent(), QueryRule.Operator.EQUALS, parentValue); + if (xref_filters.size() > 0) xref_filters.add(new QueryRule(Operator.OR)); xref_filters.add(rule); } @@ -903,14 +886,14 @@ public File getDownloadFile(Database db, Tuple requestTuple) String file = null; try { - file = db.getFilesource() - + requestTuple.getString(FileInput.INPUT_CURRENT_DOWNLOAD); + file = db.getFilesource() + requestTuple.getString(FileInput.INPUT_CURRENT_DOWNLOAD); logger.error("file to download: " + file); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); + return null; } return new File(file); } @@ -1000,8 +983,7 @@ public List getParentFilters() public E getCurrent() { - if (this.getRecords() != null && this.getRecords().size() > 0) return this - .getRecords().get(0); + if (this.getRecords() != null && this.getRecords().size() > 0) return this.getRecords().get(0); return null; } diff --git a/src/org/molgenis/framework/ui/FormView.ftl b/src/org/molgenis/framework/ui/FormView.ftl index dfdc4f063..8a167b48d 100644 --- a/src/org/molgenis/framework/ui/FormView.ftl +++ b/src/org/molgenis/framework/ui/FormView.ftl @@ -320,6 +320,7 @@ var molgenis_required = new Array(${required}); <#macro listview screen> +<#if screen.description??>${screen.description}

<#assign offset = screen.offset /> <#assign count = 0 /> @@ -395,7 +396,7 @@ var molgenis_required = new Array(${required}); <#elseif input.getClass().getSimpleName() == "HyperlinkInput" || input.getClass().getSimpleName() == "EmbeddedInput" || input.getHtmlValue()?length < 100> <#else> - + diff --git a/src/org/molgenis/framework/ui/FreemarkerView.java b/src/org/molgenis/framework/ui/FreemarkerView.java index 2a4aba7c0..1809f24f5 100644 --- a/src/org/molgenis/framework/ui/FreemarkerView.java +++ b/src/org/molgenis/framework/ui/FreemarkerView.java @@ -7,6 +7,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import org.apache.log4j.Logger; import org.molgenis.framework.ui.html.WidgetFactory; @@ -97,14 +98,15 @@ public String render(String templatePath, Map templateArgs)// , // (nb this method is deprecated but I can't see why) loaders.add(new ClassTemplateLoader()); - for (Object key : templateArgs.keySet()) + for (Entry entry : templateArgs.entrySet()) { - if ("model".equals(key) && templateArgs.get(key) != null) + Object value = entry.getValue(); + if (entry.getKey() != null && entry.getKey().equals("model") && value != null) { - loaders.add(new ClassTemplateLoader(templateArgs.get(key).getClass())); + loaders.add(new ClassTemplateLoader(value.getClass())); // also add superclass because of generated code - loaders.add(new ClassTemplateLoader(templateArgs.get(key).getClass().getSuperclass())); + loaders.add(new ClassTemplateLoader(value.getClass().getSuperclass())); } } loaders.add(new FileTemplateLoader()); @@ -114,8 +116,8 @@ public String render(String templatePath, Map templateArgs)// , // Object.class, ""); // ClassTemplateLoader loader2 = new ClassTemplateLoader( // getClass().getSuperclass(), ""); - MultiTemplateLoader mLoader = new MultiTemplateLoader(loaders.toArray(new TemplateLoader[loaders - .size()])); + MultiTemplateLoader mLoader = new MultiTemplateLoader( + loaders.toArray(new TemplateLoader[loaders.size()])); conf.setTemplateLoader(mLoader); logger.debug("created freemarker config"); } diff --git a/src/org/molgenis/framework/ui/GenericPlugin.java b/src/org/molgenis/framework/ui/GenericPlugin.java index 22b341291..7fd34fbbb 100644 --- a/src/org/molgenis/framework/ui/GenericPlugin.java +++ b/src/org/molgenis/framework/ui/GenericPlugin.java @@ -26,7 +26,7 @@ @Deprecated public class GenericPlugin extends PluginModel { - //serialization id + // serialization id private static final long serialVersionUID = 1L; // wrapper of this template private freemarker.template.Configuration cfg = null; @@ -56,19 +56,16 @@ public void handleRequest(Database db, Tuple request) String action = request.getAction(); try { - logger.debug("trying to use reflection to call " - + this.getClass().getName() + "." + action); - Method m = this.getClass().getMethod(action, Database.class, - Tuple.class); + logger.debug("trying to use reflection to call " + this.getClass().getName() + "." + action); + Method m = this.getClass().getMethod(action, Database.class, Tuple.class); m.invoke(this, db, request); - logger.debug("call of " + this.getClass().getName() + "(name=" - + this.getName() + ")." + action + " completed"); + logger.debug("call of " + this.getClass().getName() + "(name=" + this.getName() + ")." + action + + " completed"); } catch (Exception e) { - logger.error("call of " + this.getClass().getName() + "(name=" - + this.getName() + ")." + action + " failed: " - + e.getMessage()); + logger.error("call of " + this.getClass().getName() + "(name=" + this.getName() + ")." + action + + " failed: " + e.getMessage()); e.printStackTrace(); } } @@ -76,12 +73,17 @@ public void handleRequest(Database db, Tuple request) @Override public boolean isVisible() { - if (this.getLogin().isAuthenticated()){ - try { - if (this.getLogin().canRead(this)) { + if (this.getLogin().isAuthenticated()) + { + try + { + if (this.getLogin().canRead(this)) + { return true; } - } catch (DatabaseException e) { + } + catch (DatabaseException e) + { e.printStackTrace(); } } @@ -93,7 +95,7 @@ public String render(String templatePath) logger.debug("trying to render " + templatePath); try { - //keep configuration in session so we can reuse it + // keep configuration in session so we can reuse it if (cfg == null) { logger.debug("create freemarker config"); @@ -104,17 +106,15 @@ public String render(String templatePath) cfg.setObjectWrapper(wrapper); // create template loader - ClassTemplateLoader loader1 = new ClassTemplateLoader( - getClass(), ""); - ClassTemplateLoader loader2 = new ClassTemplateLoader( - getClass().getSuperclass(), ""); + ClassTemplateLoader loader1 = new ClassTemplateLoader(getClass(), ""); + ClassTemplateLoader loader2 = new ClassTemplateLoader(getClass().getSuperclass(), ""); TemplateLoader[] loaders = new TemplateLoader[] { loader1, loader2 }; MultiTemplateLoader mLoader = new MultiTemplateLoader(loaders); cfg.setTemplateLoader(mLoader); logger.debug("created freemarker config"); } - + // create template parameters Map templateArgs = new TreeMap(); templateArgs.put("screen", this); @@ -129,8 +129,7 @@ public String render(String templatePath) } catch (Exception e) { - logger.error("rendering of template " + templatePath + " failed:" - + e.getMessage()); + logger.error("rendering of template " + templatePath + " failed:" + e.getMessage()); e.printStackTrace(); } @@ -143,22 +142,22 @@ public String render() // this. Ouch! return render(this.getViewTemplate()); } - + public boolean renderAsForm() { return this.isForm; } - + public void clearMessage() - { + { this.setMessages(); - } + } @Override public void reset() { // TODO Auto-generated method stub - + } @Override @@ -171,6 +170,6 @@ public ScreenView getView() public void reload(Database db) { // TODO Auto-generated method stub - + } } diff --git a/src/org/molgenis/framework/ui/IntegratedPluginController.java b/src/org/molgenis/framework/ui/IntegratedPluginController.java index 273182861..48c652b0c 100644 --- a/src/org/molgenis/framework/ui/IntegratedPluginController.java +++ b/src/org/molgenis/framework/ui/IntegratedPluginController.java @@ -20,20 +20,19 @@ public IntegratedPluginController(String name, M model, ScreenController pare super(name, parent); this.setModel(model); } - + public String include(Tuple request, String path) { - HttpServletRequestTuple rt = (HttpServletRequestTuple) request; - HttpServletRequest httpRequest = rt.getRequest(); + HttpServletRequestTuple rt = (HttpServletRequestTuple) request; + HttpServletRequest httpRequest = rt.getRequest(); HttpServletResponse httpResponse = rt.getResponse(); - RedirectTextWrapper respWrapper = new RedirectTextWrapper(httpResponse); - + RedirectTextWrapper respWrapper = new RedirectTextWrapper(httpResponse); + // Call/include page try { RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(path); - if (dispatcher != null) - dispatcher.include(httpRequest, respWrapper); + if (dispatcher != null) dispatcher.include(httpRequest, respWrapper); } catch (Exception e) { @@ -42,7 +41,7 @@ public String include(Tuple request, String path) return respWrapper.getOutput(); } - + private class RedirectTextWrapper extends HttpServletResponseWrapper { private PrintWriter printWriter; @@ -52,7 +51,7 @@ public RedirectTextWrapper(HttpServletResponse response) { super(response); this.stringWriter = new StringWriter(); - this.printWriter = new PrintWriter(stringWriter); + this.printWriter = new PrintWriter(stringWriter); } @Override diff --git a/src/org/molgenis/framework/ui/MenuController.java b/src/org/molgenis/framework/ui/MenuController.java index de154f5c3..04dcf405a 100644 --- a/src/org/molgenis/framework/ui/MenuController.java +++ b/src/org/molgenis/framework/ui/MenuController.java @@ -13,7 +13,6 @@ package org.molgenis.framework.ui; - import java.io.OutputStream; import org.apache.log4j.Logger; @@ -23,7 +22,7 @@ public class MenuController extends SimpleScreenController { - private static final transient Logger logger = Logger.getLogger(MenuController.class.getSimpleName()); + private static final transient Logger logger = Logger.getLogger(MenuController.class.getSimpleName()); private static final long serialVersionUID = -7579424157884595183L; public MenuController(String name, ScreenController parent) @@ -32,24 +31,24 @@ public MenuController(String name, ScreenController parent) this.setModel(new MenuModel(this)); this.getModel().setLabel(name); } - + public ScreenView getView() { return new FreemarkerView("MenuView.ftl", this.getModel()); } @Override - public Show handleRequest(Database db, Tuple request, OutputStream out) + public Show handleRequest(Database db, Tuple request, OutputStream out) { this.doSelect(request); - + return Show.SHOW_MAIN; } @Override public void reload(Database db) { - logger.debug("reloading Menu("+getModel().getName()+")"); + logger.debug("reloading Menu(" + getModel().getName() + ")"); ScreenModel selected = getModel().getSelected(); if (selected == null) { @@ -71,7 +70,8 @@ public void reload(Database db) /** * Request to choose which subscreen is whosed. * - * @param request containing all the data from the http-request. + * @param request + * containing all the data from the http-request. */ public boolean doSelect(Tuple request) { @@ -85,12 +85,12 @@ public boolean doSelect(Tuple request) return false; } } - + public MenuModel getModel() { return super.getModel(); } - + @Override public ScreenModel getSelected() { @@ -100,29 +100,27 @@ public ScreenModel getSelected() } if (getChildren().size() > 0) { - if (getChildren().firstElement() instanceof ScreenModel) return getChildren() - .firstElement().getModel(); + if (getChildren().firstElement() instanceof ScreenModel) return getChildren().firstElement().getModel(); } return null; } - + public String getCustomHtmlHeaders() { - String result = ""; + StringBuilder strBuilder = new StringBuilder(""); if (this.getModel() != null && this.getModel().getSelected() != null) { - result += this.getModel().getSelected().getController() - .getCustomHtmlHeaders(); + strBuilder.append(this.getModel().getSelected().getController().getCustomHtmlHeaders()); } else { for (ScreenController c : this.getChildren()) { - result += c.getCustomHtmlHeaders(); + strBuilder.append(c.getCustomHtmlHeaders()); } } - return result; + return strBuilder.toString(); } } diff --git a/src/org/molgenis/framework/ui/MenuModel.java b/src/org/molgenis/framework/ui/MenuModel.java index a65ae4faa..9e61132e0 100644 --- a/src/org/molgenis/framework/ui/MenuModel.java +++ b/src/org/molgenis/framework/ui/MenuModel.java @@ -67,8 +67,7 @@ public MenuModel(ScreenController controller) */ public void hide(String name) { - if (this.getController().get(name) != null) - hiddenScreenNames.add(name); + if (this.getController().get(name) != null) hiddenScreenNames.add(name); } @@ -94,7 +93,8 @@ public List getVisibleChildren() // remove hidden children from the list, and also commands for (ScreenController s : subscreens) { - if (this.hiddenScreenNames.indexOf(s.getName()) < 0 && s instanceof ScreenController && s.getModel().isVisible()) + if (this.hiddenScreenNames.indexOf(s.getName()) < 0 && s instanceof ScreenController + && s.getModel().isVisible()) { result.add(s.getModel()); } @@ -103,14 +103,14 @@ public List getVisibleChildren() return result; } -// public Login getLogin() -// { -// return getController().getRootController().getLogin(); -// } + // public Login getLogin() + // { + // return getController().getRootController().getLogin(); + // } public ScreenModel getSelected() { - + List subscreens = getVisibleChildren(); if (subscreens.contains(super.getSelected())) { @@ -122,7 +122,7 @@ else if (subscreens.size() > 0) } else { - logger.error("Menu "+this.getName()+" doesn't have any subforms attached!"); + logger.error("Menu " + this.getName() + " doesn't have any subforms attached!"); return null; } } @@ -131,8 +131,7 @@ else if (subscreens.size() > 0) public boolean isVisible() { // the menu is visible if one its children is visible. - if (this.getVisibleChildren().size() > 0) - return true; + if (this.getVisibleChildren().size() > 0) return true; return false; } @@ -145,18 +144,17 @@ public void setPosition(Position position) { this.position = position; } - + @Override public void reset() { // TODO Auto-generated method stub - + } - + public String toString() { - return "MenuModel(name="+getName()+")"; + return "MenuModel(name=" + getName() + ")"; } - } diff --git a/src/org/molgenis/framework/ui/PluginModel.java b/src/org/molgenis/framework/ui/PluginModel.java index a040aec16..daf7578bc 100644 --- a/src/org/molgenis/framework/ui/PluginModel.java +++ b/src/org/molgenis/framework/ui/PluginModel.java @@ -11,8 +11,7 @@ import org.molgenis.util.HandleRequestDelegationException; import org.molgenis.util.Tuple; -public abstract class PluginModel extends - SimpleScreenController implements ScreenModel +public abstract class PluginModel extends SimpleScreenController implements ScreenModel { private static final long serialVersionUID = -6748634936592503575L; private String label; @@ -24,37 +23,36 @@ public PluginModel(String name, ScreenController parent) super(name, null, parent); // label is the last part of the name this.setModel(this); - this.setLabel(this.getName().substring( - this.getName().lastIndexOf("_") + 1)); + this.setLabel(this.getName().substring(this.getName().lastIndexOf("_") + 1)); } public ScreenView getView() { throw new UnsupportedOperationException(); } - + public Login getLogin() { return this.getApplicationController().getLogin(); } - + public TokenFactory getTokenFactory() { return this.getController().getApplicationController().getMolgenisContext().getTokenFactory(); } - + public void handleRequest(Database db, Tuple request) throws HandleRequestDelegationException, Exception { - + } - - public Show handleRequest(Database db, Tuple request, OutputStream out) throws HandleRequestDelegationException, Exception + + public Show handleRequest(Database db, Tuple request, OutputStream out) throws HandleRequestDelegationException, + Exception { this.handleRequest(db, request); return Show.SHOW_MAIN; } - /** * A plugin is actually a model-view-controller structure. The extension of * plugin is the controller. The freemarker template is the view, see @@ -63,8 +61,9 @@ public Show handleRequest(Database db, Tuple request, OutputStream out) throws H */ /** - * Show plugin or not, depending on whether the user is authenticated. - * Note: at the moment you can still override this method in your plugin to bypass security (evil). + * Show plugin or not, depending on whether the user is authenticated. Note: + * at the moment you can still override this method in your plugin to bypass + * security (evil). */ @Override public boolean isVisible() @@ -165,7 +164,7 @@ public ScreenModel getSelected() * For example: <#macro MyPlugin screen> Hello World */ public abstract String getViewName(); - + @Override public abstract void reload(Database db); @@ -188,16 +187,16 @@ public ApplicationController getRootScreen() { return this.getApplicationController(); } - + /** Shorthand for setMessages(new ScreenMessage("success message",true)); */ public void setSuccess(String message) { - this.setMessages(new ScreenMessage(message,true)); + this.setMessages(new ScreenMessage(message, true)); } - + /** Shorthand for setMessages(new ScreenMessage("succes message",false)); */ public void setError(String message) { - this.setMessages(new ScreenMessage(message,false)); + this.setMessages(new ScreenMessage(message, false)); } } diff --git a/src/org/molgenis/framework/ui/ScreenController.java b/src/org/molgenis/framework/ui/ScreenController.java index 4fdd02151..8cd605517 100644 --- a/src/org/molgenis/framework/ui/ScreenController.java +++ b/src/org/molgenis/framework/ui/ScreenController.java @@ -16,9 +16,6 @@ import java.io.OutputStream; import java.io.Serializable; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.molgenis.framework.db.Database; import org.molgenis.framework.ui.ScreenModel.Show; import org.molgenis.framework.ui.html.HtmlInputException; @@ -38,8 +35,7 @@ * (see templates). It also eases understanding as Screen is reduced to a simple * Bean (that can be hold in a Session) and the Controllers that manipulate it. */ -public interface ScreenController extends - Serializable, Tree> +public interface ScreenController extends Serializable, Tree> { /** * Refresh/reload the model. @@ -78,10 +74,11 @@ public interface ScreenController extends * * @param request * a request - * @throws HandleRequestDelegationException - * @throws Exception + * @throws HandleRequestDelegationException + * @throws Exception */ - //public void handleRequest(Database db, Tuple request) throws Exception, HandleRequestDelegationException; + // public void handleRequest(Database db, Tuple request) throws Exception, + // HandleRequestDelegationException; /** * Handle a user request (typically implemented in the subclass). @@ -91,11 +88,12 @@ public interface ScreenController extends * @param out * additional parameter that allows you to write downloadable * output - * @return - * @throws Exception - * @throws HandleRequestDelegationException + * @return + * @throws Exception + * @throws HandleRequestDelegationException */ - public Show handleRequest(Database db, Tuple request, OutputStream out) throws HandleRequestDelegationException, Exception; + public Show handleRequest(Database db, Tuple request, OutputStream out) throws HandleRequestDelegationException, + Exception; /** * Get the view @@ -157,9 +155,4 @@ public interface ScreenController extends ScreenModel getSelected(); - /** - * Retrieve the base url for this MOLGENIS. You can use this to build new - * urls to your app. - */ - String getApplicationUrl(); } diff --git a/src/org/molgenis/framework/ui/ScreenMessage.java b/src/org/molgenis/framework/ui/ScreenMessage.java index e264a1369..1d4cc9146 100644 --- a/src/org/molgenis/framework/ui/ScreenMessage.java +++ b/src/org/molgenis/framework/ui/ScreenMessage.java @@ -28,9 +28,12 @@ public class ScreenMessage * Standard constructor, where all the information about the message can be * set. * - * @param message The string representation of the message. - * @param entity Pointer to the entity used in the database transaction. - * @param success Indicates whether the transaction was succesfull. + * @param message + * The string representation of the message. + * @param entity + * Pointer to the entity used in the database transaction. + * @param success + * Indicates whether the transaction was succesfull. */ public ScreenMessage(String message, Entity entity, boolean success) { @@ -38,12 +41,12 @@ public ScreenMessage(String message, Entity entity, boolean success) this.message = message; this.success = success; } - + public ScreenMessage(String message, boolean success) { this.message = message; this.success = success; - } + } // access /** @@ -53,10 +56,10 @@ public ScreenMessage(String message, boolean success) */ public String getText() { - if(message == null) return "Unknown error"; + if (message == null) return "Unknown error"; return message; } - + public String test() { return "test"; @@ -81,7 +84,7 @@ public boolean isSuccess() { return success ? true : false; } - + /** * Returns a string-representation of this message. * @@ -89,18 +92,22 @@ public boolean isSuccess() */ public String toString() { - return getText() + ":"+( isSuccess() ? "success" : "failed"); + return getText() + ":" + (isSuccess() ? "success" : "failed"); } public String getHtml() { - /*<#if screen.message.isSuccess()>${screen.message.message}

- <#else>${screen.message.message}

*/ - if(getText().length() > 0) - return ""+getText()+""; + /* + * <#if screen.message.isSuccess()>${screen.message.message}

+ * <#else>${screen.message.message}

+ */ + if (getText().length() > 0) return "" + + getText() + ""; else return ""; - + } // member variables diff --git a/src/org/molgenis/framework/ui/ScreenModel.java b/src/org/molgenis/framework/ui/ScreenModel.java index e6c3a3c68..5129a9b24 100644 --- a/src/org/molgenis/framework/ui/ScreenModel.java +++ b/src/org/molgenis/framework/ui/ScreenModel.java @@ -45,7 +45,7 @@ public interface ScreenModel extends Serializable /** Bind parameter name for screen action (to be used by layout renderer) */ public static final String INPUT_ACTION = "__action"; - + /** * Parameter to indicate how the results should be shown (as download, as * popup, inline with the rest of the GUI (Default) @@ -56,43 +56,47 @@ public enum Show * Show the current screen as JSON */ SHOW_JSON("json"), - + /** * Show the jqGrid */ SHOW_JQGRID("jqGrid"), /** - * Show the current screen as part of its parent. This means the layout template is called on the root of the user interface. + * Show the current screen as part of its parent. This means the layout + * template is called on the root of the user interface. */ - SHOW_MAIN("inline"), + SHOW_MAIN("inline"), /** - * Show the current screen or command as popup. This means the layout template is applied on this element only. + * Show the current screen or command as popup. This means the layout + * template is applied on this element only. */ - SHOW_DIALOG("popup"), + SHOW_DIALOG("popup"), /** - * Don't layout the screen. Instead pass use the outputstream in handleRequest so it can be - * downloaded. This result in a download file. + * Don't layout the screen. Instead pass use the outputstream in + * handleRequest so it can be downloaded. This result in a download + * file. */ SHOW_DOWNLOAD("download"), /** * Don't show anything */ - SHOW_CLOSE("close"); - + SHOW_CLOSE("close"); + private String TAG; + Show(String name) { this.TAG = name; } - + public String toString() { return this.TAG; } - + public boolean equals(String str) { - if(str != null && str.equals(this.TAG)) return true; + if (str != null && str.equals(this.TAG)) return true; return false; } } @@ -101,7 +105,7 @@ public boolean equals(String str) * Reset the view to construction defaults, resetting all user set changes. */ public void reset(); - + public String getName(); /** @@ -157,30 +161,33 @@ public boolean equals(String str) /** * Get the screen messages + * * @return */ public Vector getMessages(); /** - * Get selected other models to be shown. - * This is a shorthand for getController().getSelected().getModel(); + * Get selected other models to be shown. This is a shorthand for + * getController().getSelected().getModel(); + * * @return */ public ScreenModel getSelected(); /** * Set the screen messages + * * @param messages */ public void setMessages(Vector messages); - - public void setMessages(ScreenMessage ... messages); - + + public void setMessages(ScreenMessage... messages); + /** Shorthand for setMessages(new ScreenMessage("success message",true)); */ public void setSuccess(String message); - + /** Shorthand for setMessages(new ScreenMessage("succes message",false)); */ public void setError(String message); - + public String render() throws HtmlInputException; } diff --git a/src/org/molgenis/framework/ui/ScreenView.java b/src/org/molgenis/framework/ui/ScreenView.java index 3c8153281..ab3425ec5 100644 --- a/src/org/molgenis/framework/ui/ScreenView.java +++ b/src/org/molgenis/framework/ui/ScreenView.java @@ -6,9 +6,12 @@ * A ScreenView contains the layout of a part of the user-interface. */ public interface ScreenView -{ - /** This methods produces an html representation of the view - * @throws HtmlInputException */ +{ + /** + * This methods produces an html representation of the view + * + * @throws HtmlInputException + */ public String render() throws HtmlInputException; /** Produces any custom html headers needed, e.g. to load css or javascript */ diff --git a/src/org/molgenis/framework/ui/SimpleScreenController.java b/src/org/molgenis/framework/ui/SimpleScreenController.java index 53b1d56e8..f492f8dc6 100644 --- a/src/org/molgenis/framework/ui/SimpleScreenController.java +++ b/src/org/molgenis/framework/ui/SimpleScreenController.java @@ -15,9 +15,6 @@ import java.io.IOException; import java.io.Serializable; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.log4j.Logger; import org.molgenis.framework.db.Database; import org.molgenis.framework.ui.html.HtmlInputException; @@ -29,9 +26,8 @@ * Base-class for a screen displaying information from the invengine system to * the user. */ -public abstract class SimpleScreenController extends - SimpleTree> implements ScreenController, - Serializable +public abstract class SimpleScreenController extends SimpleTree> + implements ScreenController, Serializable { // member variables /** */ @@ -48,8 +44,7 @@ public abstract class SimpleScreenController extends // private String viewName; // constructor - public SimpleScreenController(String name, MODEL model, - ScreenController parent) + public SimpleScreenController(String name, MODEL model, ScreenController parent) { super(name, parent); this.model = model; @@ -67,8 +62,6 @@ public SimpleScreenController(String name, MODEL model, */ public abstract void reload(Database db) throws Exception; - - /** * This is the actual control-method, which changes the view. The view * itself may delegate requests to other objects (e.g. delegate insert to @@ -77,10 +70,11 @@ public SimpleScreenController(String name, MODEL model, * * @param request * The http-request in a convenient map. - * @throws HandleRequestDelegationException - * @throws Exception + * @throws HandleRequestDelegationException + * @throws Exception */ - //public abstract void handleRequest(Database db, Tuple request) throws Exception, HandleRequestDelegationException; + // public abstract void handleRequest(Database db, Tuple request) throws + // Exception, HandleRequestDelegationException; // public String getFromRequest(Tuple request, String name) // { @@ -164,14 +158,13 @@ public String getViewTemplate() @Override public String getCustomHtmlHeaders() { - String result = ""; + StringBuilder resultBuilder = new StringBuilder(); for (ScreenController c : this.getChildren()) { - result += ""; - result += c.getCustomHtmlHeaders(); + resultBuilder.append(""); + resultBuilder.append(c.getCustomHtmlHeaders()); } - - return result; + return resultBuilder.toString(); } @Override @@ -183,14 +176,12 @@ public String getLabel() @Override public String getCustomHtmlBodyOnLoad() { - String result = ""; + StringBuilder resultBuilder = new StringBuilder(); for (ScreenController c : this.getChildren()) { - //result += ""; - result += c.getCustomHtmlBodyOnLoad(); + resultBuilder.append(c.getCustomHtmlBodyOnLoad()); } - - return result; + return resultBuilder.toString(); } /** @@ -231,9 +222,9 @@ public ScreenModel getSelected() public String render() throws HtmlInputException { String result = this.getView().render(); - if(result == null || "".equals(result)) + if (result == null || "".equals(result)) { - throw new HtmlInputException("render showed nothing for "+this); + throw new HtmlInputException("render showed nothing for " + this); } return result; } @@ -242,19 +233,13 @@ public String render() throws HtmlInputException // public void setParent(Object parent) // { // // TODO Auto-generated method stub - // + // // } - + @Override public Database getDatabase() { return this.getApplicationController().getDatabase(); } - - @Override - public String getApplicationUrl() - { - return this.getApplicationController().getApplicationUrl(); - } } diff --git a/src/org/molgenis/framework/ui/SimpleScreenModel.java b/src/org/molgenis/framework/ui/SimpleScreenModel.java index 21f67e443..93960092a 100644 --- a/src/org/molgenis/framework/ui/SimpleScreenModel.java +++ b/src/org/molgenis/framework/ui/SimpleScreenModel.java @@ -31,14 +31,12 @@ * Base-class for a screen displaying information from the invengine system to * the user. */ -public abstract class SimpleScreenModel implements - ScreenModel, Serializable +public abstract class SimpleScreenModel implements ScreenModel, Serializable { // member variables private static final long serialVersionUID = 3764151203967037515L; /** Logger */ - protected final transient Logger logger = Logger.getLogger(this.getClass() - .getSimpleName()); + protected final transient Logger logger = Logger.getLogger(this.getClass().getSimpleName()); /** * constant parameter name for screen target controller (to be used when * rendering actions) @@ -71,8 +69,7 @@ public abstract class SimpleScreenModel implements * @param parent * The parent of this screen. */ - public SimpleScreenModel( - ScreenController controller) + public SimpleScreenModel(ScreenController controller) { // super(name, parent); this.controller = controller; @@ -86,12 +83,11 @@ public void reset() { } - + public String render() throws HtmlInputException { String result = this.getController().render(); - if(result == null) - System.out.println("error with render of "+this); + if (result == null) System.out.println("error with render of " + this); return this.getController().render(); } @@ -218,15 +214,14 @@ public void addCommand(ScreenCommand command) // commands must have a unique id if (getCommand(command.getName()) != null) { - logger.warn("command with name '" + command.getName() - + "' already exists; replaced"); + logger.warn("command with name '" + command.getName() + "' already exists; replaced"); } // create new menu if not exists if (menubar.containsKey(command.getMenu()) == false) { - menubar.put(command.getMenu(), new CommandMenu( - command.getMenu(), this.getController(), command.getMenu(), "", "")); + menubar.put(command.getMenu(), new CommandMenu(command.getMenu(), this.getController(), command.getMenu(), + "", "")); } // put the command in the menu @@ -238,8 +233,7 @@ public ScreenCommand getCommand(String commandID) { for (CommandMenu menu : menubar.values()) { - if (menu.getCommand(commandID) != null) return menu - .getCommand(commandID); + if (menu.getCommand(commandID) != null) return menu.getCommand(commandID); } return null; } @@ -283,29 +277,30 @@ public ScreenModel getSelected() { return this.getController().getSelected(); } -// -// @Override -// public void setSelected(String viewid) -// { -// // check if the path to this is also selected -// if (this.getController().getParent() != null) -// { -// logger.debug("call setselected on parent"); -// this.getController().getParent().setSelected(this.getName()); -// } -// -// logger.debug("Screen " + this.getName() + " selected " + viewid); -// this.selectedId = viewid; -// } - + + // + // @Override + // public void setSelected(String viewid) + // { + // // check if the path to this is also selected + // if (this.getController().getParent() != null) + // { + // logger.debug("call setselected on parent"); + // this.getController().getParent().setSelected(this.getName()); + // } + // + // logger.debug("Screen " + this.getName() + " selected " + viewid); + // this.selectedId = viewid; + // } + public List getChildren() { List result = new ArrayList(); - for(ScreenController childController: getController().getChildren()) + for (ScreenController childController : getController().getChildren()) { result.add(childController.getModel()); } - + return result; } @@ -318,17 +313,17 @@ public void setVisible(boolean visible) { this.visible = visible; } - + /** Shorthand for setMessages(new ScreenMessage("success message",true)); */ public void setSuccess(String message) { - this.setMessages(new ScreenMessage(message,true)); + this.setMessages(new ScreenMessage(message, true)); } - + /** Shorthand for setMessages(new ScreenMessage("succes message",false)); */ public void setError(String message) { - this.setMessages(new ScreenMessage(message,false)); + this.setMessages(new ScreenMessage(message, false)); } public String getCustomHtmlHeaders() diff --git a/src/org/molgenis/framework/ui/SimpleScreenView.java b/src/org/molgenis/framework/ui/SimpleScreenView.java index 2d91fc45d..c959f54df 100644 --- a/src/org/molgenis/framework/ui/SimpleScreenView.java +++ b/src/org/molgenis/framework/ui/SimpleScreenView.java @@ -22,7 +22,7 @@ public abstract class SimpleScreenView implements ScreenV { String customHtmlHeaders = ""; M model = null; - + public SimpleScreenView(M model) { this.model = model; diff --git a/src/org/molgenis/framework/ui/commands/AddBatchCommand.java b/src/org/molgenis/framework/ui/commands/AddBatchCommand.java index 7bed6b946..4fd0d39d4 100644 --- a/src/org/molgenis/framework/ui/commands/AddBatchCommand.java +++ b/src/org/molgenis/framework/ui/commands/AddBatchCommand.java @@ -26,8 +26,7 @@ public class AddBatchCommand extends SimpleCommand { private static final long serialVersionUID = -4067952586340535730L; - public static final transient Logger logger = Logger - .getLogger(AddBatchCommand.class); + public static final transient Logger logger = Logger.getLogger(AddBatchCommand.class); public AddBatchCommand(String name, ScreenController owner) { @@ -61,16 +60,14 @@ public List getActions() public List> getInputs() throws DatabaseException { // delegate to the formscreen - List> inputs = this.getFormScreen().getNewRecordForm() - .getInputs(); + List> inputs = this.getFormScreen().getNewRecordForm().getInputs(); // remove not-null constraints for (HtmlInput i : inputs) i.setNillable(true); // add the textarea for csv - TextInput csvInput = new TextInput("__csvdata", - "put here your data in comma-separated format."); + TextInput csvInput = new TextInput("__csvdata", "put here your data in comma-separated format."); csvInput.setLabel("CSV data"); csvInput.setTooltip("put here your data in comma-separated format."); csvInput.setDescription("Put your CSV data here."); @@ -80,8 +77,7 @@ public List> getInputs() throws DatabaseException } @Override - public ScreenModel.Show handleRequest(Database db, Tuple request, - OutputStream downloadStream) throws Exception + public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream downloadStream) throws Exception { logger.debug(this.getName()); @@ -91,27 +87,22 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, ScreenMessage msg = null; try { - CsvToDatabase csvReader = this - .getFormScreen().getCsvReader(); + CsvToDatabase csvReader = this.getFormScreen().getCsvReader(); - int updatedRows = csvReader.importCsv(db, new CsvStringReader( - request.getString("__csvdata")), request, + int updatedRows = csvReader.importCsv(db, new CsvStringReader(request.getString("__csvdata")), request, DatabaseAction.ADD); // for (E entity : entities) // logger.debug("parsed: " + entity); // view.getDatabase().add(entities); - msg = new ScreenMessage("CSV UPLOAD SUCCESS: added " - + updatedRows + " rows", null, true); - logger.debug("CSV UPLOAD SUCCESS: added " + updatedRows - + " rows"); + msg = new ScreenMessage("CSV UPLOAD SUCCESS: added " + updatedRows + " rows", null, true); + logger.debug("CSV UPLOAD SUCCESS: added " + updatedRows + " rows"); getFormScreen().getPager().resetFilters(); getFormScreen().getPager().last(db); } catch (Exception e) { e.printStackTrace(); - msg = new ScreenMessage("CSV UPLOAD FAILED: " + e.getMessage(), - null, false); + msg = new ScreenMessage("CSV UPLOAD FAILED: " + e.getMessage(), null, false); logger.error("CSV UPLOAD FAILED: " + e.getMessage()); } getFormScreen().getMessages().add(msg); diff --git a/src/org/molgenis/framework/ui/commands/AddCommand.java b/src/org/molgenis/framework/ui/commands/AddCommand.java index eb0c7cfa3..da744679b 100644 --- a/src/org/molgenis/framework/ui/commands/AddCommand.java +++ b/src/org/molgenis/framework/ui/commands/AddCommand.java @@ -22,7 +22,7 @@ public class AddCommand extends SimpleCommand { private static final long serialVersionUID = 1512493344265778285L; - public AddCommand(String name, ScreenController parent) + public AddCommand(String name, ScreenController parent) { super(name, parent); this.setLabel("Add new record"); @@ -44,9 +44,9 @@ public List getActions() { List inputs = new ArrayList(); -// HiddenInput inDialog = new HiddenInput("__indialog","add"); -// inputs.add(inDialog); - + // HiddenInput inDialog = new HiddenInput("__indialog","add"); + // inputs.add(inDialog); + ActionInput submit = new ActionInput("Add", ActionInput.Type.SAVE); submit.setValue("edit_new"); submit.setIcon("generated-res/img/save.png"); @@ -58,17 +58,17 @@ public List getActions() return inputs; } - + @Override public boolean isVisible() { - //hide add button if the screen is readonly - return !this.getFormScreen().isReadonly(); + // hide add button if the screen is readonly + return !this.getFormScreen().isReadonly(); } @Override public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream downloadStream) throws Exception - { + { if (request.getString(FormModel.INPUT_SHOW) == null) { // delegate to the form controller diff --git a/src/org/molgenis/framework/ui/commands/AddCommand2.java b/src/org/molgenis/framework/ui/commands/AddCommand2.java index 429e6433b..109212457 100644 --- a/src/org/molgenis/framework/ui/commands/AddCommand2.java +++ b/src/org/molgenis/framework/ui/commands/AddCommand2.java @@ -28,7 +28,7 @@ public class AddCommand2 extends SimpleCommand Vector messages = new Vector(); boolean success = false; - public AddCommand2(String name, ScreenController parent) + public AddCommand2(String name, ScreenController parent) { super(name, parent); this.setLabel("Add new record"); @@ -40,7 +40,7 @@ public AddCommand2(String name, ScreenController parent) public List> getInputs() throws DatabaseException { CommandTemplate f = new CommandTemplate(); - f.addAll(this.getFormScreen().getNewRecordForm().getInputs()); + f.addAll(this.getFormScreen().getNewRecordForm().getInputs()); f.setAll(previousRequest); return f.getInputs(); } @@ -77,12 +77,13 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream d if (this.getName().equals(request.getAction())) { // delegate to the form controller - //boolean success = ((FormController) this.getScreen().getController()).doAdd(db, request); - this.messages = this.getFormScreen().getMessages(); + // boolean success = ((FormController) + // this.getScreen().getController()).doAdd(db, request); + this.messages = this.getFormScreen().getMessages(); } return ScreenModel.Show.SHOW_MAIN; } - + public Vector getMessages() { return messages; diff --git a/src/org/molgenis/framework/ui/commands/AddCsvFileCommand.java b/src/org/molgenis/framework/ui/commands/AddCsvFileCommand.java index 5d2ed552a..351751a8e 100644 --- a/src/org/molgenis/framework/ui/commands/AddCsvFileCommand.java +++ b/src/org/molgenis/framework/ui/commands/AddCsvFileCommand.java @@ -26,8 +26,7 @@ public class AddCsvFileCommand extends SimpleCommand { private static final long serialVersionUID = -4067952586340535730L; - public static final transient Logger logger = Logger - .getLogger(AddCsvFileCommand.class); + public static final transient Logger logger = Logger.getLogger(AddCsvFileCommand.class); public AddCsvFileCommand(String name, ScreenController owner) { @@ -61,8 +60,7 @@ public List getActions() public List> getInputs() throws DatabaseException { // delegate to the formscreen - List> inputs = this.getFormScreen().getNewRecordForm() - .getInputs(); + List> inputs = this.getFormScreen().getNewRecordForm().getInputs(); // remove not-null constraints for (HtmlInput i : inputs) @@ -79,8 +77,7 @@ public List> getInputs() throws DatabaseException } @Override - public ScreenModel.Show handleRequest(Database db, Tuple request, - OutputStream downloadStream) throws Exception + public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream downloadStream) throws Exception { logger.debug(this.getName()); @@ -90,27 +87,22 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, ScreenMessage msg = null; try { - CsvToDatabase csvReader = this - .getFormScreen().getCsvReader(); + CsvToDatabase csvReader = this.getFormScreen().getCsvReader(); - int updatedRows = csvReader.importCsv(db, new CsvFileReader( - request.getFile("filefor___csvdata")), request, - DatabaseAction.ADD); + int updatedRows = csvReader.importCsv(db, new CsvFileReader(request.getFile("filefor___csvdata")), + request, DatabaseAction.ADD); // for (E entity : entities) // logger.debug("parsed: " + entity); // view.getDatabase().add(entities); - msg = new ScreenMessage("CSV UPLOAD SUCCESS: added " - + updatedRows + " rows", null, true); - logger.debug("CSV UPLOAD SUCCESS: added " + updatedRows - + " rows"); + msg = new ScreenMessage("CSV UPLOAD SUCCESS: added " + updatedRows + " rows", null, true); + logger.debug("CSV UPLOAD SUCCESS: added " + updatedRows + " rows"); getFormScreen().getPager().resetFilters(); getFormScreen().getPager().last(db); } catch (Exception e) { e.printStackTrace(); - msg = new ScreenMessage("CSV UPLOAD FAILED: " + e.getMessage(), - null, false); + msg = new ScreenMessage("CSV UPLOAD FAILED: " + e.getMessage(), null, false); logger.error("CSV UPLOAD FAILED: " + e.getMessage()); } getFormScreen().getMessages().add(msg); diff --git a/src/org/molgenis/framework/ui/commands/AddXrefCommand.java b/src/org/molgenis/framework/ui/commands/AddXrefCommand.java index 5699b15fe..30913046f 100644 --- a/src/org/molgenis/framework/ui/commands/AddXrefCommand.java +++ b/src/org/molgenis/framework/ui/commands/AddXrefCommand.java @@ -29,31 +29,36 @@ public class AddXrefCommand extends AddCommand private static final long serialVersionUID = 1512493344265778285L; private E xrefEntity; private EntityForm xrefForm; - //private UiToolkit library = HtmlSettings.uiToolkit; - public AddXrefCommand(ScreenController parent) + // private UiToolkit library = HtmlSettings.uiToolkit; + + public AddXrefCommand(ScreenController parent) { this("", parent, null, null); } public AddXrefCommand(String name, ScreenController parent, E xrefEntity, EntityForm xrefForm) { - //if the parent is a command then we need to getParent() until we find a form... + // if the parent is a command then we need to getParent() until we find + // a form... super(name, getParentController(parent)); this.xrefEntity = xrefEntity; - this.xrefForm = xrefForm; - this.setLabel("Add " + xrefEntity.getClass().getSimpleName()); + this.xrefForm = xrefForm; + if (xrefEntity != null) + { + this.setLabel("Add " + xrefEntity.getClass().getSimpleName()); + } this.setIcon("generated-res/img/new.png"); this.setDialog(true); this.setMenu("Edit"); this.setToolbar(false); } - - //get the formController that this command is part of. + + // get the formController that this command is part of. private static FormController getParentController(ScreenController parent) { ScreenController formController = parent; - while(formController.hasParent() && !(formController instanceof FormController)) + while (formController.hasParent() && !(formController instanceof FormController)) formController = formController.getParent(); return (FormController) formController; } @@ -62,7 +67,7 @@ private static FormController getParentController(ScreenController parent) public List getActions() { List actions = super.getActions(); - + // Override functionality of standard save button: // postData(): post data via rest api, retrieve object including id back // setXrefOption(): set newly inserted object as current option @@ -70,10 +75,14 @@ public List getActions() { if (actions.get(i).getType() == Type.SAVE) { - if(actions.get(i).getUiToolkit() == UiToolkit.ORIGINAL) - actions.get(i).setJavaScriptAction("if( validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis'+new Date().getTime();} var entity = postData(document.forms[0].entity_name.value); window.opener.setXrefOption(document.forms[0].__action.value, document.forms[0].id_field.value, document.forms[0].label_field.value, entity); window.close();} else return false;"); + if (actions.get(i).getUiToolkit() == UiToolkit.ORIGINAL) actions + .get(i) + .setJavaScriptAction( + "if( validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis'+new Date().getTime();} var entity = postData(document.forms[0].entity_name.value); window.opener.setXrefOption(document.forms[0].__action.value, document.forms[0].id_field.value, document.forms[0].label_field.value, entity); window.close();} else return false;"); else - actions.get(i).setJavaScriptAction("if( $(this.form).valid() && validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis'+new Date().getTime();} var entity = postData(document.forms[0].entity_name.value); window.opener.setXrefOption(document.forms[0].__action.value, document.forms[0].id_field.value, document.forms[0].label_field.value, entity); ;window.close();} return false;"); + actions.get(i) + .setJavaScriptAction( + "if( $(this.form).valid() && validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis'+new Date().getTime();} var entity = postData(document.forms[0].entity_name.value); window.opener.setXrefOption(document.forms[0].__action.value, document.forms[0].id_field.value, document.forms[0].label_field.value, entity); ;window.close();} return false;"); } } return actions; @@ -91,7 +100,8 @@ public List> getInputs() throws DatabaseException ((AbstractRefInput) inputs.get(i)).setIncludeAddButton(false); } } - // add three hidden fields for javascript to know entity name, id field and label field + // add three hidden fields for javascript to know entity name, id field + // and label field inputs.add(new HiddenInput("entity_name", xrefEntity.getClass().getSimpleName().toLowerCase())); inputs.add(new HiddenInput("id_field", this.xrefEntity.getIdField())); inputs.add(new HiddenInput("label_field", this.xrefEntity.getLabelFields().get(0))); @@ -101,7 +111,7 @@ public List> getInputs() throws DatabaseException @Override public boolean isVisible() { - return false; + return false; } @Override @@ -116,14 +126,13 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream d xrefEntity.set(request); int updatedRows = db.add(xrefEntity); db.commitTx(); - msg = new ScreenMessage("ADD SUCCESS: affected " + updatedRows, null, true); + msg = new ScreenMessage("ADD SUCCESS: affected " + updatedRows, null, true); } catch (Exception e) { msg = new ScreenMessage("ADD FAILED: " + e.getMessage(), null, false); e.printStackTrace(); - if (db.inTx()) - db.rollbackTx(); + if (db.inTx()) db.rollbackTx(); } ((FormController) this.getController()).getModel().getMessages().add(msg); } diff --git a/src/org/molgenis/framework/ui/commands/ChangeListLimitCommand.java b/src/org/molgenis/framework/ui/commands/ChangeListLimitCommand.java index ed21ede94..6c1daec2b 100644 --- a/src/org/molgenis/framework/ui/commands/ChangeListLimitCommand.java +++ b/src/org/molgenis/framework/ui/commands/ChangeListLimitCommand.java @@ -17,17 +17,17 @@ import org.molgenis.util.Tuple; /** - * This command changes the limit of the number of items shown in listview - * + * This command changes the limit of the number of items shown in listview + * * @param */ public class ChangeListLimitCommand extends SimpleCommand { private static final long serialVersionUID = -8328256342346578115L; - //the limit it should change too + // the limit it should change too private int limit = 5; - public ChangeListLimitCommand(String name, ScreenController parentScreen) + public ChangeListLimitCommand(String name, ScreenController parentScreen) { super(name, parentScreen); this.setLabel("Show %s items"); @@ -41,11 +41,11 @@ public boolean isVisible() // only show in list view return getFormScreen().getMode().equals(Mode.LIST_VIEW); } - + @Override public String getLabel() { - return String.format(super.getLabel(),getLimit()); + return String.format(super.getLabel(), getLimit()); } @Override diff --git a/src/org/molgenis/framework/ui/commands/CommandMenu.java b/src/org/molgenis/framework/ui/commands/CommandMenu.java index 17b636086..366071fad 100644 --- a/src/org/molgenis/framework/ui/commands/CommandMenu.java +++ b/src/org/molgenis/framework/ui/commands/CommandMenu.java @@ -15,19 +15,18 @@ import org.molgenis.framework.ui.html.HtmlInput; import org.molgenis.util.Tuple; - public class CommandMenu extends SimpleCommand { private static final long serialVersionUID = 7869046696648113688L; public static final transient Logger logger = Logger.getLogger(CommandMenu.class); - /** menu items with order as entered*/ - private Map menu_items = new LinkedHashMap(); + /** menu items with order as entered */ + private Map menu_items = new LinkedHashMap(); - public CommandMenu(String id, ScreenController screen, String label, String icon, String action) + public CommandMenu(String id, ScreenController screen, String label, String icon, String action) { - super( id, screen ); + super(id, screen); this.setLabel(label); this.setIcon(icon); this.setJavaScriptAction(action); @@ -35,32 +34,34 @@ public CommandMenu(String id, ScreenController screen, String label, String /** * Add a menu item. + * * @param command */ - public void addCommand( ScreenCommand command ) + public void addCommand(ScreenCommand command) { - if(menu_items.containsKey(command.getName())) + if (menu_items.containsKey(command.getName())) { - logger.warn("addCommand: command with id '"+command.getName()+"' already exists; replaced"); + logger.warn("addCommand: command with id '" + command.getName() + "' already exists; replaced"); } - menu_items.put(command.getName(),command); + menu_items.put(command.getName(), command); } - + /** * Return the values as list. - * + * */ public Collection getCommands() { - //Logger.getLogger("test").debug("returning commands "+menu_items.values().size()); + // Logger.getLogger("test").debug("returning commands "+menu_items.values().size()); return menu_items.values(); } /** * Find a specific command. + * * @param name */ - public ScreenCommand getCommand( String name ) + public ScreenCommand getCommand(String name) { return menu_items.get(name); } @@ -80,8 +81,7 @@ public List> getInputs() throws DatabaseException } @Override - public Show handleRequest(Database db, Tuple request, - OutputStream downloadStream) throws Exception + public Show handleRequest(Database db, Tuple request, OutputStream downloadStream) throws Exception { return ScreenModel.Show.SHOW_DIALOG; } diff --git a/src/org/molgenis/framework/ui/commands/DownloadAllCommand.java b/src/org/molgenis/framework/ui/commands/DownloadAllCommand.java index 9a338972a..e3e28f969 100644 --- a/src/org/molgenis/framework/ui/commands/DownloadAllCommand.java +++ b/src/org/molgenis/framework/ui/commands/DownloadAllCommand.java @@ -24,7 +24,7 @@ /** * This command returns all records currently selected as CSV download. - * + * * @param */ public class DownloadAllCommand extends SimpleCommand @@ -32,7 +32,7 @@ public class DownloadAllCommand extends SimpleCommand private static final long serialVersionUID = -2682113764135477871L; public static final transient Logger logger = Logger.getLogger(DownloadAllCommand.class); - public DownloadAllCommand(String name, ScreenController parentScreen) + public DownloadAllCommand(String name, ScreenController parentScreen) { super(name, parentScreen); this.setLabel("Download all (.txt)"); @@ -47,12 +47,13 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream c logger.debug(this.getName()); FormModel model = this.getFormScreen(); - FormController controller = ((FormController)this.getController()); - + FormController controller = ((FormController) this.getController()); + List fieldsToExport = controller.getVisibleColumnNames(); - - //TODO : remove entity name, capitals to small , and remove all _name fields - //we need to rewrite rules to accomodate the 'all' + + // TODO : remove entity name, capitals to small , and remove all _name + // fields + // we need to rewrite rules to accomodate the 'all' QueryRule[] rules; try { @@ -64,7 +65,7 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream c e.printStackTrace(); throw new DatabaseException(e); } - + db.find(model.getController().getEntityClass(), new CsvWriter(csvDownload), fieldsToExport, rules); return ScreenModel.Show.SHOW_MAIN; diff --git a/src/org/molgenis/framework/ui/commands/DownloadAllXlsCommand.java b/src/org/molgenis/framework/ui/commands/DownloadAllXlsCommand.java index ac2eb61fc..1f66073a0 100644 --- a/src/org/molgenis/framework/ui/commands/DownloadAllXlsCommand.java +++ b/src/org/molgenis/framework/ui/commands/DownloadAllXlsCommand.java @@ -18,7 +18,7 @@ import org.molgenis.util.Tuple; import org.molgenis.util.XlsWriter; -public class DownloadAllXlsCommand extends SimpleCommand +public class DownloadAllXlsCommand extends SimpleCommand { private static final long serialVersionUID = -2682113764135477871L; public static final transient Logger logger = Logger.getLogger(DownloadAllCommand.class); @@ -38,12 +38,13 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream x logger.debug(this.getName()); FormModel model = this.getFormScreen(); - FormController controller = ((FormController)this.getController()); - + FormController controller = ((FormController) this.getController()); + List fieldsToExport = controller.getVisibleColumnNames(); - - //TODO : remove entity name, capitals to small , and remove all _name fields - //we need to rewrite rules to accomodate the 'all' + + // TODO : remove entity name, capitals to small , and remove all _name + // fields + // we need to rewrite rules to accomodate the 'all' QueryRule[] rules; try { @@ -55,12 +56,14 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream x e.printStackTrace(); throw new DatabaseException(e); } - + // Comments from Despoina: - //TODO : the actual xls headers/formatting - //TODO : this needs different call or TODO just an extra if in abstractMolgenisServlet for the different suffix (.xls) ? - - // This db.find() is rerouted by your Database implementation's find() to the one in the appropriate mapper + // TODO : the actual xls headers/formatting + // TODO : this needs different call or TODO just an extra if in + // abstractMolgenisServlet for the different suffix (.xls) ? + + // This db.find() is rerouted by your Database implementation's find() + // to the one in the appropriate mapper db.find(model.getController().getEntityClass(), new XlsWriter(xlsDownload), fieldsToExport, rules); return ScreenModel.Show.SHOW_MAIN; @@ -79,5 +82,4 @@ public List> getInputs() throws DatabaseException return null; } - } diff --git a/src/org/molgenis/framework/ui/commands/DownloadSelectedCommand.java b/src/org/molgenis/framework/ui/commands/DownloadSelectedCommand.java index 873afea9e..b1349ef92 100644 --- a/src/org/molgenis/framework/ui/commands/DownloadSelectedCommand.java +++ b/src/org/molgenis/framework/ui/commands/DownloadSelectedCommand.java @@ -31,10 +31,9 @@ public class DownloadSelectedCommand extends SimpleCommand { private static final long serialVersionUID = 3619865367653131342L; - public static final transient Logger logger = Logger - .getLogger(DownloadSelectedCommand.class); + public static final transient Logger logger = Logger.getLogger(DownloadSelectedCommand.class); - public DownloadSelectedCommand(String name, ScreenController parentScreen) + public DownloadSelectedCommand(String name, ScreenController parentScreen) { super(name, parentScreen); this.setLabel("Download selected (.txt)"); @@ -73,15 +72,15 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream c if (records.size() == 0) { - //csvDownload.println("No records selected."); + // csvDownload.println("No records selected."); return ScreenModel.Show.SHOW_MAIN; } - - List fieldsToExport = ((FormController)this.getController()).getVisibleColumnNames(); + + List fieldsToExport = ((FormController) this.getController()).getVisibleColumnNames(); // watch out, the "IN" operator expects an Object[] - db.find(view.getController().getEntityClass(), new CsvWriter(csvDownload), fieldsToExport, - new QueryRule("id", Operator.IN, records)); + db.find(view.getController().getEntityClass(), new CsvWriter(csvDownload), fieldsToExport, new QueryRule("id", + Operator.IN, records)); return ScreenModel.Show.SHOW_MAIN; } diff --git a/src/org/molgenis/framework/ui/commands/DownloadSelectedXlsCommand.java b/src/org/molgenis/framework/ui/commands/DownloadSelectedXlsCommand.java index 990410416..66ad17586 100644 --- a/src/org/molgenis/framework/ui/commands/DownloadSelectedXlsCommand.java +++ b/src/org/molgenis/framework/ui/commands/DownloadSelectedXlsCommand.java @@ -31,10 +31,9 @@ public class DownloadSelectedXlsCommand extends SimpleCommand { private static final long serialVersionUID = 3619865367653131342L; - public static final transient Logger logger = Logger - .getLogger(DownloadSelectedXlsCommand.class); + public static final transient Logger logger = Logger.getLogger(DownloadSelectedXlsCommand.class); - public DownloadSelectedXlsCommand(String name, ScreenController parentScreen) + public DownloadSelectedXlsCommand(String name, ScreenController parentScreen) { super(name, parentScreen); this.setLabel("Download selected (.xls)"); @@ -52,8 +51,7 @@ public boolean isVisible() @SuppressWarnings("unchecked") @Override - public ScreenModel.Show handleRequest(Database db, Tuple request, - OutputStream xlsDownload) throws Exception + public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream xlsDownload) throws Exception { logger.debug(this.getName()); @@ -74,15 +72,15 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, if (records.size() == 0) { - //xlsDownload.println("No records selected."); + // xlsDownload.println("No records selected."); return ScreenModel.Show.SHOW_MAIN; } - - List fieldsToExport = ((FormController)this.getController()).getVisibleColumnNames(); + + List fieldsToExport = ((FormController) this.getController()).getVisibleColumnNames(); // watch out, the "IN" operator expects an Object[] - db.find(view.getController().getEntityClass(), new XlsWriter(xlsDownload), fieldsToExport, - new QueryRule("id", Operator.IN, records)); + db.find(view.getController().getEntityClass(), new XlsWriter(xlsDownload), fieldsToExport, new QueryRule("id", + Operator.IN, records)); return ScreenModel.Show.SHOW_MAIN; } diff --git a/src/org/molgenis/framework/ui/commands/DownloadVisibleCommand.java b/src/org/molgenis/framework/ui/commands/DownloadVisibleCommand.java index e2d4e9704..177aeaa61 100644 --- a/src/org/molgenis/framework/ui/commands/DownloadVisibleCommand.java +++ b/src/org/molgenis/framework/ui/commands/DownloadVisibleCommand.java @@ -21,8 +21,9 @@ /** * This command downloads the records currently shown as csv. + * * @author Morris Swertz - * + * * @param */ public class DownloadVisibleCommand extends SimpleCommand @@ -30,7 +31,7 @@ public class DownloadVisibleCommand extends SimpleCommand private static final long serialVersionUID = -6279819301321361448L; public static final transient Logger logger = Logger.getLogger(DownloadVisibleCommand.class); - public DownloadVisibleCommand(String name, ScreenController parentScreen) + public DownloadVisibleCommand(String name, ScreenController parentScreen) { super(name, parentScreen); this.setDownload(true); @@ -43,10 +44,11 @@ public DownloadVisibleCommand(String name, ScreenController parentScreen) public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream csvDownload) throws Exception { FormModel view = this.getFormScreen(); - List fieldsToExport = ((FormController)this.getController()).getVisibleColumnNames(); + List fieldsToExport = ((FormController) this.getController()).getVisibleColumnNames(); CsvWriter writer = new CsvWriter(csvDownload, fieldsToExport); writer.writeHeader(); - for(Entity e: view.getRecords()) writer.writeRow(e); + for (Entity e : view.getRecords()) + writer.writeRow(e); writer.close(); return ScreenModel.Show.SHOW_MAIN; } diff --git a/src/org/molgenis/framework/ui/commands/DownloadVisibleXlsCommand.java b/src/org/molgenis/framework/ui/commands/DownloadVisibleXlsCommand.java index bb4b279ec..b4fc4bc18 100644 --- a/src/org/molgenis/framework/ui/commands/DownloadVisibleXlsCommand.java +++ b/src/org/molgenis/framework/ui/commands/DownloadVisibleXlsCommand.java @@ -22,8 +22,9 @@ /** * This command downloads the records currently shown as csv. + * * @author Morris Swertz - * + * * @param */ public class DownloadVisibleXlsCommand extends SimpleCommand @@ -31,7 +32,7 @@ public class DownloadVisibleXlsCommand extends SimpleCommand private static final long serialVersionUID = -6279819301321361448L; public static final transient Logger logger = Logger.getLogger(DownloadVisibleXlsCommand.class); - public DownloadVisibleXlsCommand(String name, ScreenController parentScreen) + public DownloadVisibleXlsCommand(String name, ScreenController parentScreen) { super(name, parentScreen); this.setDownload(true); @@ -41,14 +42,15 @@ public DownloadVisibleXlsCommand(String name, ScreenController parentScreen) } @Override - public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream xlsDownload) throws ParseException, DatabaseException, - Exception + public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream xlsDownload) throws ParseException, + DatabaseException, Exception { FormModel view = this.getFormScreen(); - List fieldsToExport = ((FormController)this.getController()).getVisibleColumnNames(); + List fieldsToExport = ((FormController) this.getController()).getVisibleColumnNames(); XlsWriter writer = new XlsWriter(xlsDownload, fieldsToExport); writer.writeHeader(); - for(Entity e: view.getRecords()) writer.writeRow(e); + for (Entity e : view.getRecords()) + writer.writeRow(e); writer.close(); return ScreenModel.Show.SHOW_MAIN; } diff --git a/src/org/molgenis/framework/ui/commands/EditSelectedCommand.java b/src/org/molgenis/framework/ui/commands/EditSelectedCommand.java index 3c0c11521..7e94e95c6 100644 --- a/src/org/molgenis/framework/ui/commands/EditSelectedCommand.java +++ b/src/org/molgenis/framework/ui/commands/EditSelectedCommand.java @@ -28,8 +28,7 @@ public class EditSelectedCommand extends SimpleCommand { private static final long serialVersionUID = -2996595009523144519L; - public static final transient Logger logger = Logger - .getLogger(EditSelectedCommand.class); + public static final transient Logger logger = Logger.getLogger(EditSelectedCommand.class); private List selectedIds = new ArrayList(); public EditSelectedCommand(String name, ScreenController parentScreen) @@ -50,8 +49,7 @@ public boolean isVisible() } @Override - public ScreenModel.Show handleRequest(Database db, Tuple request, - OutputStream out) throws Exception + public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream out) throws Exception { logger.debug(this.getName()); @@ -66,13 +64,12 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, } ScreenMessage msg = null; - - //cleanup the request, only use ticked (marked with 'use_' + + // cleanup the request, only use ticked (marked with 'use_' Tuple updateTuple = new SimpleTuple(); - for(HtmlInput input : this.getFormScreen().getNewRecordForm() - .getInputs()) + for (HtmlInput input : this.getFormScreen().getNewRecordForm().getInputs()) { - if(!request.isNull("use_"+input.getName())) + if (!request.isNull("use_" + input.getName())) { updateTuple.set(input.getName(), request.getObject(input.getName())); } @@ -81,8 +78,7 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, int row = 0; try { - Query q = db.query( - view.getController().getEntityClass()).in( + Query q = db.query(view.getController().getEntityClass()).in( view.create().getIdField(), idList); List entities = q.find(); @@ -90,13 +86,12 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, for (Entity e : entities) { row++; - //set only not null values + // set only not null values e.set(updateTuple, false); db.update(e); } db.commitTx(); - msg = new ScreenMessage("MASS UPDATE SUCCESS: updated " - + entities.size() + " rows", null, true); + msg = new ScreenMessage("MASS UPDATE SUCCESS: updated " + entities.size() + " rows", null, true); } catch (Exception e) @@ -110,13 +105,12 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, logger.error("doMassUpdate() Should never happen: " + e1); e1.printStackTrace(); } - msg = new ScreenMessage("MASS UPDATE FAILED on item '" + row - + "': " + e, null, false); + msg = new ScreenMessage("MASS UPDATE FAILED on item '" + row + "': " + e, null, false); } view.getMessages().add(msg); } - //record the selected ids + // record the selected ids else { this.selectedIds = request.getList(FormModel.INPUT_SELECTED); @@ -149,15 +143,16 @@ public List getActions() public List> getInputs() throws DatabaseException { List> inputs = new ArrayList>(); - - if(this.selectedIds == null || this.selectedIds.size() == 0){ + + if (this.selectedIds == null || this.selectedIds.size() == 0) + { Paragraph t = new Paragraph("No records were selected for updating."); t.setDescription("Error."); inputs.add(t); return inputs; } - - Paragraph t = new Paragraph("Selected ids:"+ this.selectedIds.toString()); + + Paragraph t = new Paragraph("Selected ids:" + this.selectedIds.toString()); t.setDescription("The IDs you have selected for updating."); inputs.add(t); @@ -170,8 +165,7 @@ public List> getInputs() throws DatabaseException } // get inputs from formscreen - for (HtmlInput input : this.getFormScreen().getNewRecordForm() - .getInputs()) + for (HtmlInput input : this.getFormScreen().getNewRecordForm().getInputs()) { if (!input.isHidden() && !input.isReadonly()) { @@ -181,7 +175,7 @@ public List> getInputs() throws DatabaseException } } - + return inputs; } } diff --git a/src/org/molgenis/framework/ui/commands/EditSelectedInput.java b/src/org/molgenis/framework/ui/commands/EditSelectedInput.java index 0f4e05262..2935b5469 100644 --- a/src/org/molgenis/framework/ui/commands/EditSelectedInput.java +++ b/src/org/molgenis/framework/ui/commands/EditSelectedInput.java @@ -4,27 +4,28 @@ /** * Decorates an input with a checkbox to disable/enable the input + * * @param */ public class EditSelectedInput extends HtmlInput { private HtmlInput input; - + public EditSelectedInput(HtmlInput input) { this.input = input; } - + public String getLabel() { return input.getLabel(); } - + @Override public String toHtml() { input.setNillable(true); - return "" + input.toHtml(); + return "" + input.toHtml(); } } diff --git a/src/org/molgenis/framework/ui/commands/GalaxyCommand.java b/src/org/molgenis/framework/ui/commands/GalaxyCommand.java index 3cdd5dcf9..0645838de 100644 --- a/src/org/molgenis/framework/ui/commands/GalaxyCommand.java +++ b/src/org/molgenis/framework/ui/commands/GalaxyCommand.java @@ -8,6 +8,7 @@ import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; +import org.molgenis.framework.server.MolgenisRequest; import org.molgenis.framework.ui.ScreenController; import org.molgenis.framework.ui.ScreenModel; import org.molgenis.framework.ui.html.ActionInput; @@ -16,43 +17,52 @@ /** * This command returns JavaScript code to download all records in CSV format. - * + * * @param */ +public class GalaxyCommand extends SimpleCommand +{ -public class GalaxyCommand extends SimpleCommand { - - public GalaxyCommand(String name, ScreenController parentController) { + public GalaxyCommand(String name, ScreenController parentController) + { super(name, parentController); - if (this.getName() == "send_all_to_galaxy") { + if (this.getName() == "send_all_to_galaxy") + { this.setLabel("Send All to Galaxy"); - } else { + } + else + { this.setLabel("Send Selected to Galaxy"); } - //this.setLabel("Send to Galaxy"); + // this.setLabel("Send to Galaxy"); this.setIcon("generated-res/img/upload2galaxy.png"); this.setMenu("File"); - //this.setDialog(false); - + // this.setDialog(false); + } // TODO: Get proper UID. private static final long serialVersionUID = 1L; + private String appLoc; @Override - public String getJavaScriptAction() { + public String getJavaScriptAction() + { StringBuffer jScript = new StringBuffer(); jScript.append(""); - - if(this.getController().getApplicationController().getGalaxyUrl() != null) { - + + if (this.getController().getApplicationController().getGalaxyUrl() != null) + { + String galaxy_url = this.getController().getApplicationController().getGalaxyUrl(); - String molgenis_site = this.getController().getApplicationController().getApplicationUrl(); - String molgenis_download_all = molgenis_site+"/molgenis.do?__target="+this.getController().getName()+"&__action=download_txt_all&__show=download"; - String molgenis_download_selected = molgenis_site+"/molgenis.do?__target="+this.getController().getName()+"&__action=download_txt_selected&__show=download"; - + String molgenis_site = appLoc; + String molgenis_download_all = molgenis_site + "/molgenis.do?__target=" + this.getController().getName() + + "&__action=download_txt_all&__show=download"; + String molgenis_download_selected = molgenis_site + "/molgenis.do?__target=" + + this.getController().getName() + "&__action=download_txt_selected&__show=download"; + jScript.append("var form = document.createElement('form');"); jScript.append("form.setAttribute('method', 'post');"); jScript.append("form.setAttribute('action', '" + galaxy_url + "');"); @@ -60,9 +70,12 @@ public String getJavaScriptAction() { jScript.append("var hiddenField = document.createElement('input');"); jScript.append("hiddenField.setAttribute('type', 'hidden');"); jScript.append("hiddenField.setAttribute('name', 'URL');"); - if (this.getName() == "send_all_to_galaxy") { + if (this.getName() == "send_all_to_galaxy") + { jScript.append("hiddenField.setAttribute('value', '" + molgenis_download_all + "');"); - } else { + } + else + { jScript.append("hiddenField.setAttribute('value', '" + molgenis_download_selected + "');"); } jScript.append("hiddenField.setAttribute('value', '" + molgenis_download_all + "');"); @@ -70,74 +83,86 @@ public String getJavaScriptAction() { jScript.append("document.body.appendChild(form);"); jScript.append("form.submit();"); - + } return jScript.toString(); - + } - + @Override - public List> getInputs() throws DatabaseException { + public List> getInputs() throws DatabaseException + { return null; } - + @Override - public List getActions() { + public List getActions() + { return new ArrayList(); } - + @Override - //public ScreenModel.Show handleRequest(Database db, Tuple request, PrintWriter downloadStream) { - public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream downloadStream) { - logger.debug("galaxy button clicked: "+this.getController().getApplicationController().getGalaxyUrl()); + // public ScreenModel.Show handleRequest(Database db, Tuple request, + // PrintWriter downloadStream) { + public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream downloadStream) + { + logger.debug("galaxy button clicked: " + this.getController().getApplicationController().getGalaxyUrl()); + appLoc = ((MolgenisRequest) request).getAppLocation(); return ScreenModel.Show.SHOW_MAIN; } - //@SuppressWarnings("unchecked") - //@Override + // @SuppressWarnings("unchecked") + // @Override // - //public ScreenModel.Show handleRequest(Database db, Tuple request, PrintWriter csvDownload) - // throws ParseException, DatabaseException, IOException { + // public ScreenModel.Show handleRequest(Database db, Tuple request, + // PrintWriter csvDownload) + // throws ParseException, DatabaseException, IOException { // - // public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream downloadStream) - // { - // logger.debug("galaxy button clicked: "+this.getController().getApplicationController().getGalaxyUrl()); - // logger.error(this.getName()); + // public ScreenModel.Show handleRequest(Database db, Tuple request, + // OutputStream downloadStream) + // { + // logger.debug("galaxy button clicked: "+this.getController().getApplicationController().getGalaxyUrl()); + // logger.error(this.getName()); // - // FormModel view = this.getFormScreen(); + // FormModel view = this.getFormScreen(); // - // Object ids = request.getList(FormModel.INPUT_SELECTED); - // List records = new ArrayList(); + // Object ids = request.getList(FormModel.INPUT_SELECTED); + // List records = new ArrayList(); // - // if (ids != null) - // { - // if (ids instanceof List) - // { - // records = (List) ids; - // } - // else - // records.add(ids); - // } + // if (ids != null) + // { + // if (ids instanceof List) + // { + // records = (List) ids; + // } + // else + // records.add(ids); + // } // - // if (records.size() == 0) - // { - // csvDownload.println("No records selected."); - // return ScreenModel.Show.SHOW_MAIN; - // } + // if (records.size() == 0) + // { + // csvDownload.println("No records selected."); + // return ScreenModel.Show.SHOW_MAIN; + // } // - // List fieldsToExport = ((FormController)this.getController()).getVisibleColumnNames(); + // List fieldsToExport = + // ((FormController)this.getController()).getVisibleColumnNames(); // - // // watch out, the "IN" operator expects an Object[] - // db.find(view.getController().getEntityClass(), new CsvWriter(csvDownload), fieldsToExport, - // new QueryRule("id", Operator.IN, records)); - // return ScreenModel.Show.SHOW_MAIN; - // } - + // // watch out, the "IN" operator expects an Object[] + // db.find(view.getController().getEntityClass(), new + // CsvWriter(csvDownload), fieldsToExport, + // new QueryRule("id", Operator.IN, records)); + // return ScreenModel.Show.SHOW_MAIN; + // } + @Override - public boolean isVisible() { - // Show this menu item only if the user navigated to Molgenis from a Galaxy server. - if(this.getController().getApplicationController().getGalaxyUrl() != null) { + public boolean isVisible() + { + // Show this menu item only if the user navigated to Molgenis from a + // Galaxy server. + if (this.getController().getApplicationController().getGalaxyUrl() != null) + { return true; } return false; diff --git a/src/org/molgenis/framework/ui/commands/PluginCommand.java b/src/org/molgenis/framework/ui/commands/PluginCommand.java index 04ea9905f..2b121ed31 100644 --- a/src/org/molgenis/framework/ui/commands/PluginCommand.java +++ b/src/org/molgenis/framework/ui/commands/PluginCommand.java @@ -11,7 +11,7 @@ public abstract class PluginCommand extends SimpleCommand private static final long serialVersionUID = 1236057686333854770L; /** Constructor */ - public PluginCommand(String name, ScreenController parentScreen) + public PluginCommand(String name, ScreenController parentScreen) { super(name, parentScreen); this.setMenu("Plugin"); diff --git a/src/org/molgenis/framework/ui/commands/RemoveSelectedCommand.java b/src/org/molgenis/framework/ui/commands/RemoveSelectedCommand.java index 29b0bbb7d..be5a45953 100644 --- a/src/org/molgenis/framework/ui/commands/RemoveSelectedCommand.java +++ b/src/org/molgenis/framework/ui/commands/RemoveSelectedCommand.java @@ -25,7 +25,7 @@ public class RemoveSelectedCommand extends SimpleCommand private static final long serialVersionUID = 4730493886936446817L; public static final transient Logger logger = Logger.getLogger(RemoveSelectedCommand.class); - public RemoveSelectedCommand(String name, ScreenController parentScreen) + public RemoveSelectedCommand(String name, ScreenController parentScreen) { super(name, parentScreen); this.setLabel("Remove selected"); @@ -36,15 +36,15 @@ public RemoveSelectedCommand(String name, ScreenController parentScreen) @Override public boolean isVisible() { - //only in listview - return getFormScreen().getMode().equals(Mode.LIST_VIEW) && !this.getFormScreen().isReadonly(); + // only in listview + return getFormScreen().getMode().equals(Mode.LIST_VIEW) && !this.getFormScreen().isReadonly(); } @Override public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream downloadStream) throws Exception { logger.debug(this.getName()); - + FormModel view = getFormScreen(); ScreenMessage msg = null; @@ -59,7 +59,8 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream d } // find selected entities - Query q = db.query(view.getController().getEntityClass()).in(view.create().getIdField(), idList); + Query q = db.query(view.getController().getEntityClass()).in(view.create().getIdField(), + idList); List selection = q.find(); // delete selected entities @@ -71,14 +72,14 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream d msg = new ScreenMessage("REMOVE SELECTION FAILED: " + e.getMessage(), null, false); } view.getMessages().add(msg); - + // **make sure the user sees a record**/ if (msg.isSuccess()) { view.getPager().prev(db); // resetChildren(); } - + return ScreenModel.Show.SHOW_MAIN; } diff --git a/src/org/molgenis/framework/ui/commands/ScreenCommand.java b/src/org/molgenis/framework/ui/commands/ScreenCommand.java index d92bc894c..c4483b18a 100644 --- a/src/org/molgenis/framework/ui/commands/ScreenCommand.java +++ b/src/org/molgenis/framework/ui/commands/ScreenCommand.java @@ -195,8 +195,7 @@ public interface ScreenCommand extends Serializable, ScreenModel * @throws DatabaseException * @throws ParseException */ - public ScreenModel.Show handleRequest(Database db, Tuple request, - OutputStream downloadStream) throws Exception; + public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream downloadStream) throws Exception; /** * @return boolean whether this action should be treated as a download diff --git a/src/org/molgenis/framework/ui/commands/SimpleCommand.java b/src/org/molgenis/framework/ui/commands/SimpleCommand.java index 023f93537..66a2ea03b 100644 --- a/src/org/molgenis/framework/ui/commands/SimpleCommand.java +++ b/src/org/molgenis/framework/ui/commands/SimpleCommand.java @@ -5,7 +5,7 @@ import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; -import org.molgenis.framework.server.AbstractMolgenisServlet; +import org.molgenis.framework.server.services.MolgenisGuiService; import org.molgenis.framework.ui.FormModel; import org.molgenis.framework.ui.FreemarkerView; import org.molgenis.framework.ui.ScreenController; @@ -19,11 +19,12 @@ * Implementation of screen command. */ public abstract class SimpleCommand extends SimpleScreenModel implements ScreenCommand -{ +{ private static final long serialVersionUID = -3289941539731301135L; /** Logger */ - //private static final transient Logger logger = Logger.getLogger(SimpleCommand.class.getSimpleName()); + // private static final transient Logger logger = + // Logger.getLogger(SimpleCommand.class.getSimpleName()); /** Internal name of this command (unique within the screen) */ private String name; @@ -34,11 +35,14 @@ public abstract class SimpleCommand extends SimpleScreenModel implements ScreenC /** Path to an icon image to show on this command */ private String icon; - /** Piece of javascript; if none is provide it is autogenerated depend on all settings */ + /** + * Piece of javascript; if none is provide it is autogenerated depend on all + * settings + */ private String onClickJavascript; - + /** The Screen this command is linked to */ - private ScreenController screenController; + private ScreenController screenController; /** The name of the screen to be target (default: this.screen) */ private String targetScreen; @@ -79,7 +83,8 @@ public String getJavaScriptAction() // make sure the current window has a name (so popup can call back // if necessary) - jScript.append("if( window.name == '' ){ window.name = 'molgenis_"+AbstractMolgenisServlet.getNewWindowId()+"';}"); + jScript.append("if( window.name == '' ){ window.name = 'molgenis_" + MolgenisGuiService.getNewWindowId() + + "';}"); // default target screen is 'self' jScript.append("document.forms." + this.getController().getName() + "_form." + FormModel.INPUT_TARGET @@ -93,11 +98,10 @@ public String getJavaScriptAction() if (this.isDialog()) { // open a new screen named 'popup' - jScript - .append("molgenis_window = window.open('','" - + "molgenis_" - + this.getName() - + "','height=800,width=800,location=no,status=no,menubar=no,directories=no,toolbar=no,resizable=yes,scrollbars=yes');"); + jScript.append("molgenis_window = window.open('','" + + "molgenis_" + + this.getName() + + "','height=800,width=800,location=no,status=no,menubar=no,directories=no,toolbar=no,resizable=yes,scrollbars=yes');"); // make this new screen the target of this form jScript.append("document.forms." + this.getController().getName() + "_form.target='" + "molgenis_" @@ -307,12 +311,11 @@ public String getCustomHtmlBodyOnLoad() { return ""; } - + @Override public String render() { return new FreemarkerView("ScreenCommand.ftl", this).render(); } - - + } diff --git a/src/org/molgenis/framework/ui/commands/ViewEditViewCommand.java b/src/org/molgenis/framework/ui/commands/ViewEditViewCommand.java index ef30e0df4..091fd8c55 100644 --- a/src/org/molgenis/framework/ui/commands/ViewEditViewCommand.java +++ b/src/org/molgenis/framework/ui/commands/ViewEditViewCommand.java @@ -20,7 +20,7 @@ public class ViewEditViewCommand extends SimpleCommand { private static final long serialVersionUID = -4074166087593025109L; - public ViewEditViewCommand(String name, ScreenController parentScreen) + public ViewEditViewCommand(String name, ScreenController parentScreen) { super(name, parentScreen); this.setLabel("View/Edit Record"); @@ -40,13 +40,12 @@ public ScreenModel.Show handleRequest(Database db, Tuple request, OutputStream o @Override public boolean isVisible() - { - //show add button when not in recordview - //show add button if the screen is not readonly - return !this.getFormScreen().getMode().equals(Mode.EDIT_VIEW) - && !this.getFormScreen().isReadonly() - && this.getFormScreen().getRecordInputs().size() != 0 - && !this.getFormScreen().getRecords().get(0).isReadonly(); + { + // show add button when not in recordview + // show add button if the screen is not readonly + return !this.getFormScreen().getMode().equals(Mode.EDIT_VIEW) && !this.getFormScreen().isReadonly() + && this.getFormScreen().getRecordInputs().size() != 0 + && !this.getFormScreen().getRecords().get(0).isReadonly(); } @Override diff --git a/src/org/molgenis/framework/ui/html/AbstractHtmlElement.java b/src/org/molgenis/framework/ui/html/AbstractHtmlElement.java index d13598ee9..36f736deb 100644 --- a/src/org/molgenis/framework/ui/html/AbstractHtmlElement.java +++ b/src/org/molgenis/framework/ui/html/AbstractHtmlElement.java @@ -8,8 +8,9 @@ /** * Base class for all html elements. For scripting pu + * * @author mswertz - * + * */ public abstract class AbstractHtmlElement implements HtmlElement, ScreenView { @@ -30,20 +31,19 @@ public AbstractHtmlElement() { this.id = UUID.randomUUID().toString().replace("-", ""); } - + @Override public void set(Tuple params) throws HtmlInputException { this.setId(params.getString(ID)); this.setClazz(params.getString(CLASS)); } - + @Override public abstract String render(); @Override - public abstract String render(Tuple params) throws ParseException, - HtmlInputException; + public abstract String render(Tuple params) throws ParseException, HtmlInputException; @Override public String getCustomHtmlHeaders() @@ -51,7 +51,7 @@ public String getCustomHtmlHeaders() return null; } - //PROPERTIES + // PROPERTIES @Override public String getId() { diff --git a/src/org/molgenis/framework/ui/html/AbstractRefInput.java b/src/org/molgenis/framework/ui/html/AbstractRefInput.java index 2ce77db3a..ce8815b97 100644 --- a/src/org/molgenis/framework/ui/html/AbstractRefInput.java +++ b/src/org/molgenis/framework/ui/html/AbstractRefInput.java @@ -2,14 +2,11 @@ import java.util.ArrayList; import java.util.List; -import java.util.ResourceBundle; import org.apache.commons.lang.StringUtils; -import org.json.JSONException; -import org.json.JSONObject; import org.molgenis.framework.db.QueryRule; -import org.molgenis.framework.server.AbstractMolgenisServlet; import org.molgenis.framework.server.QueryRuleUtil; +import org.molgenis.framework.server.services.MolgenisGuiService; import org.molgenis.util.Entity; import org.molgenis.util.Tuple; @@ -18,6 +15,7 @@ public abstract class AbstractRefInput extends HtmlInput { private static String DEFAULT_URL = "xref/find"; + protected abstract String renderOptions(); // determines how ajax-chosen renders the select (multiple, search) @@ -73,7 +71,7 @@ public AbstractRefInput(Tuple t) throws HtmlInputException } catch (Exception e) { - new HtmlInputException(e); + throw new HtmlInputException(e); } xrefEntity = klass; @@ -133,7 +131,7 @@ public void setXrefEntity(String xrefClassname) throws HtmlInputException } catch (ClassNotFoundException e) { - new HtmlInputException(xrefClassname); + throw new HtmlInputException(xrefClassname); } } @@ -224,7 +222,7 @@ public ActionInput createAddButton() addButton .setJavaScriptAction("if( window.name == '' ){ window.name = 'molgenis_" - + AbstractMolgenisServlet.getNewWindowId() + + MolgenisGuiService.getNewWindowId() + "';}document.getElementById('" + this.getId() + "').form.__action.value='" @@ -245,7 +243,7 @@ public final String toJquery(String htmlOptions, String xrefLabelString) { if (this.isHidden()) { - return ""; + return this.renderHidden(); } final String cssClasses = String.format("%s %s", this.isReadonly() ? "readonly " : "", this.isNillable() ? "" @@ -263,12 +261,16 @@ public final String toJquery(String htmlOptions, String xrefLabelString) { data.filters = new Gson().toJson(getXrefFilters()); } - -// String preloadScript = "$("+getId()+").click(function() {if($(this).find('a.chzn-single-with-drop,.chzn-drop').length > 1 ) " + -// "{$(this).find('input[type=text]:first').keyup();}});"; - - //simulate keyup to load data; then blur by removing class=chzn-single-with-drop - String preloadScript = "$('#"+getId()+"_chzn').find('input[type=text]:first').focus(function(){$(this).keyup()});"; + + // String preloadScript = + // "$("+getId()+").click(function() {if($(this).find('a.chzn-single-with-drop,.chzn-drop').length > 1 ) " + // + + // "{$(this).find('input[type=text]:first').keyup();}});"; + + // simulate keyup to load data; then blur by removing + // class=chzn-single-with-drop + String preloadScript = "$('#" + getId() + + "_chzn').find('input[type=text]:first').focus(function(){$(this).keyup()});"; // #arg1 = id // #arg2 = title @@ -293,21 +295,23 @@ public final String toJquery(String htmlOptions, String xrefLabelString) config.data = data; config.jsonTermKey = SEARCH_TERM; Gson gson = new Gson(); - + String handleScript = "function (data) {var terms = {}; $.each(data, function (i, val) {terms[i] = val;});return terms;}"; - final String ajaxChosenScript = ""; + final String ajaxChosenScript = ""; final String includeButton = includeAddButton && !this.isReadonly() ? this.createAddButton().toString() : ""; return select + ajaxChosenScript + includeButton; } + public abstract String renderHidden(); + @Override public String toHtml() { if (this.error != null) return "ERROR: " + error; - if ("".equals(getXrefEntity()) || "".equals(getXrefField()) || getXrefLabels() == null + if (getXrefEntity() == null || "".equals(getXrefField()) || getXrefLabels() == null || getXrefLabels().size() == 0) { throw new RuntimeException("XrefInput(" + this.getName() diff --git a/src/org/molgenis/framework/ui/html/AccordeonLayout.java b/src/org/molgenis/framework/ui/html/AccordeonLayout.java index 161a9f6bd..171a34f51 100644 --- a/src/org/molgenis/framework/ui/html/AccordeonLayout.java +++ b/src/org/molgenis/framework/ui/html/AccordeonLayout.java @@ -1,6 +1,5 @@ package org.molgenis.framework.ui.html; - /** * Accordeon layout is a MultiPanel layout that shows multiple panels underneath * each other. A button can be used to show one of the panels. @@ -23,17 +22,16 @@ public String render() { if (this.style == UiToolkit.JQUERY) { - String returnString = "
"; + StringBuilder strBuilder = new StringBuilder("
"); for (String title : elements.keySet()) { - returnString += "

" + title + "

"; - returnString += elements.get(title).render(); - returnString += "
"; + strBuilder.append("

").append(title).append("

"); + strBuilder.append(elements.get(title).render()); + strBuilder.append("
"); } - - returnString += "
"; - return returnString; + strBuilder.append("
"); + return strBuilder.toString(); } else { diff --git a/src/org/molgenis/framework/ui/html/ActionInput.java b/src/org/molgenis/framework/ui/html/ActionInput.java index b5a861970..7c9cdc3d2 100644 --- a/src/org/molgenis/framework/ui/html/ActionInput.java +++ b/src/org/molgenis/framework/ui/html/ActionInput.java @@ -2,7 +2,7 @@ import java.text.ParseException; -import org.molgenis.framework.server.AbstractMolgenisServlet; +import org.molgenis.framework.server.services.MolgenisGuiService; import org.molgenis.util.Tuple; /** @@ -42,7 +42,7 @@ public String toString() return tag; } } - + private int width = 0; /** Path to an icon image */ @@ -55,7 +55,7 @@ public String toString() /** JavaScript action */ private String JavaScriptAction; - + /** Text to display on button (normally "value") */ private String buttonValue; @@ -81,7 +81,8 @@ public ActionInput(String name, String label) { this(name, Type.CUSTOM); this.setLabel(label); - this.setButtonValue(label); // override default button value (name) with label + this.setButtonValue(label); // override default button value (name) with + // label } /** @@ -95,7 +96,8 @@ public ActionInput(String name, String label, String buttonValue) { this(name, label); this.setTooltip(buttonValue); - this.setButtonValue(buttonValue); // override label as button value with explicit button value + this.setButtonValue(buttonValue); // override label as button value with + // explicit button value } /** @@ -135,8 +137,10 @@ public ActionInput() @Override public String toHtml() { - // Use plain HTML rendering if chosen by user OR if there is only an icon and no text to be shown - // on the button. Reason for this is that jQuery does not render image-only buttons well, messing up + // Use plain HTML rendering if chosen by user OR if there is only an + // icon and no text to be shown + // on the button. Reason for this is that jQuery does not render + // image-only buttons well, messing up // the alignment. if (this.uiToolkit == UiToolkit.ORIGINAL || (this.getIcon() != null && this.buttonValue.equals(""))) { @@ -154,19 +158,15 @@ public String renderDefault() StringBuffer input = new StringBuffer(""); if (getIcon() != null) { - input.append("\"""); + + "\" id=\"" + this.getId() + "\" style=\"" + this.getStyle() + "\" " + tabIndex + " />"); } else { - input.append(""); + input.append(""); } return input.toString(); @@ -204,18 +204,22 @@ public String getJavaScriptAction() if (this.type == Type.SAVE) { StringBuffer jScript = new StringBuffer(); - if(this.uiToolkit == UiToolkit.ORIGINAL) - jScript.append("if( validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis'+new Date().getTime();} document.forms[0].target = window.opener.name; document.forms[0].submit(); window.close();} else return false;"); + if (this.uiToolkit == UiToolkit.ORIGINAL) jScript + .append("if( validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis'+new Date().getTime();} document.forms[0].target = window.opener.name; document.forms[0].submit(); window.close();} else return false;"); else - jScript.append("if( $(this.form).valid() && validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis'+new Date().getTime();} document.forms[0].__show.value = ''; document.forms[0].__action.value ='"+this.getValue()+"'; document.forms[0].target = window.opener.name; document.forms[0].submit(); window.close();} return false;"); - //jScript.append("alert('click');"); - + jScript.append("if( $(this.form).valid() && validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis'+new Date().getTime();} document.forms[0].__show.value = ''; document.forms[0].__action.value ='" + + this.getValue() + + "'; document.forms[0].target = window.opener.name; document.forms[0].submit(); window.close();} return false;"); + // jScript.append("alert('click');"); + return jScript.toString(); } else if (this.type == Type.NEXT) { StringBuffer jScript = new StringBuffer(); - jScript.append("if( validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis_"+AbstractMolgenisServlet.getNewWindowId()+"';} document.forms[0].__show.value='popup'; document.forms[0].submit();} else return false;"); + jScript.append("if( validateForm(document.forms[0],molgenis_required) ) { if( window.opener.name == '' ){ window.opener.name = 'molgenis_" + + MolgenisGuiService.getNewWindowId() + + "';} document.forms[0].__show.value='popup'; document.forms[0].submit();} else return false;"); return jScript.toString(); } else if (this.type == Type.CLOSE) @@ -262,19 +266,19 @@ public String getLabel() { return " "; } - + public String getButtonValue() { - if(buttonValue == null) return this.getLabel(); + if (buttonValue == null) return this.getLabel(); return buttonValue; } - + public void setButtonValue(String buttonValue) { this.buttonValue = buttonValue; } - - /** Helper method to produce the html for the icon (<img>)*/ + + /** Helper method to produce the html for the icon (<img>) */ public String getIconHtml() { // TODO Auto-generated method stub @@ -284,9 +288,8 @@ public String getIconHtml() /** Helper method to produce html for the clickable image */ public String toIconHtml() { - return ""; + return ""; // edit${offset}${readonly} @@ -295,13 +298,12 @@ public String toIconHtml() /** Helper method to render this button as clickable link */ public String toLinkHtml() { - return "" + getLabel() + ""; + return "" + + getLabel() + ""; } @Override - public String toHtml(Tuple params) throws ParseException, - HtmlInputException + public String toHtml(Tuple params) throws ParseException, HtmlInputException { return new ActionInput(params).render(); } @@ -323,17 +325,19 @@ private String renderJquery() // Make the actual CSS for the icon button iconClassCss = ""; - // Make the jQuery code to be appended to make the button an image button + // Make the jQuery code to be appended to make the button an image + // button icons += "{ icons: {primary:'" + iconClass + "', secondary: null}" + (isShowLabel() ? "}" : ", text: false }"); } String result = iconClassCss + "" - + "\n"; return result; @@ -353,20 +357,24 @@ public void setShowLabel(boolean showLabel) { this.showLabel = showLabel; } - - public void setIconHeight(int iconHeight) { + + public void setIconHeight(int iconHeight) + { this.iconHeight = iconHeight; } - - public int getIconHeight() { + + public int getIconHeight() + { return iconHeight; } - - public void setIconWidth(int iconWidth) { + + public void setIconWidth(int iconWidth) + { this.iconWidth = iconWidth; } - - public int getIconWidth() { + + public int getIconWidth() + { return iconWidth; } diff --git a/src/org/molgenis/framework/ui/html/AutocompleteInput.java b/src/org/molgenis/framework/ui/html/AutocompleteInput.java index b8e62dccf..c0a130700 100644 --- a/src/org/molgenis/framework/ui/html/AutocompleteInput.java +++ b/src/org/molgenis/framework/ui/html/AutocompleteInput.java @@ -1,6 +1,6 @@ package org.molgenis.framework.ui.html; -public class AutocompleteInput extends HtmlInput +public class AutocompleteInput extends HtmlInput { private String entityClass; private String entityField; @@ -11,39 +11,53 @@ public AutocompleteInput(String name, String label, String entityClass, String e this.entityClass = entityClass; this.entityField = entityField; } - + @Override public String toHtml() { - return - "" + - "\n"; + return "" + + "\n"; } } diff --git a/src/org/molgenis/framework/ui/html/BoolInput.java b/src/org/molgenis/framework/ui/html/BoolInput.java index 321d07231..8620f2606 100644 --- a/src/org/molgenis/framework/ui/html/BoolInput.java +++ b/src/org/molgenis/framework/ui/html/BoolInput.java @@ -41,8 +41,7 @@ public BoolInput(String name, String label, Boolean value) * @param nillable * @param readonly */ - public BoolInput(String name, String label, Boolean value, - boolean nillable, boolean readonly) + public BoolInput(String name, String label, Boolean value, boolean nillable, boolean readonly) { this(name, label, value); this.setValue(value); @@ -97,29 +96,26 @@ public String toHtml() private String toDefault() { - if (isReadonly()) return "\n"; + if (isReadonly()) return "\n"; else - return "\n"; + return "\n"; } private String toJquery() { - String description = " title=\"" + this.getDescription() + "\""; + String description = " title=\"" + this.getDescription() + "\""; if (isReadonly()) return "\n\n"; diff --git a/src/org/molgenis/framework/ui/html/CheckboxInput.java b/src/org/molgenis/framework/ui/html/CheckboxInput.java index 08fba9643..ee1de2621 100644 --- a/src/org/molgenis/framework/ui/html/CheckboxInput.java +++ b/src/org/molgenis/framework/ui/html/CheckboxInput.java @@ -14,7 +14,7 @@ public class CheckboxInput extends OptionInput> { public static final String VALUES = "values"; private String onchange = null; - + /** * Construct a checkbox input with a name, a label and a description, as * well as one or more options and zero or more selected values. @@ -25,8 +25,7 @@ public class CheckboxInput extends OptionInput> * @param options * @param value */ - public CheckboxInput(String name, String label, String description, - Vector options, List value) + public CheckboxInput(String name, String label, String description, Vector options, List value) { super(name, value); super.setLabel(label); @@ -46,13 +45,11 @@ public CheckboxInput(String name, String label, String description, * @param nillable * @param readonly */ - public CheckboxInput(String name, List options, - List optionLabels, String label, List value, - boolean nillable, boolean readonly) + public CheckboxInput(String name, List options, List optionLabels, String label, + List value, boolean nillable, boolean readonly) { super(name, value); - if (optionLabels != null && optionLabels.size() > 0 - && optionLabels.size() != options.size()) throw new IllegalArgumentException( + if (optionLabels != null && optionLabels.size() > 0 && optionLabels.size() != options.size()) throw new IllegalArgumentException( "optionLabels, if set, must be of same size as options"); List result = new ArrayList(); @@ -74,8 +71,9 @@ public CheckboxInput(String name, List options, this.setNillable(nillable); this.setReadonly(readonly); } - - /** Construct a new checkbox based on a Tuple with properties. + + /** + * Construct a new checkbox based on a Tuple with properties. * * @param properties * @throws HtmlInputException @@ -84,8 +82,8 @@ public CheckboxInput(String name, List options, public CheckboxInput(Tuple properties) throws HtmlInputException { super(properties); - if(!properties.isNull(VALUE)) this.setValue((List) properties.getList(VALUE)); - if(!properties.isNull(VALUES)) this.setValue((List) properties.getList(VALUES)); + if (!properties.isNull(VALUE)) this.setValue((List) properties.getList(VALUE)); + if (!properties.isNull(VALUES)) this.setValue((List) properties.getList(VALUES)); } /** @@ -119,8 +117,7 @@ public String toHtml() StringBuffer optionString = new StringBuffer(""); String readonly = (isReadonly() ? " class=\"readonly\" readonly " : ""); String checked = ""; - String onchange = (this.onchange != null) ? " onchange=\"" - + this.onchange + "\"" : ""; + String onchange = (this.onchange != null) ? " onchange=\"" + this.onchange + "\"" : ""; if (!(getOptions().isEmpty())) { @@ -128,26 +125,21 @@ public String toHtml() { if (getObject() != null) { - checked = (((List) getObject()).contains(option - .getValue().toString()) ? " checked " : ""); + checked = (((List) getObject()).contains(option.getValue().toString()) ? " checked " : ""); } - optionString.append("" + option.getLabel() - + "
\n"); + optionString.append("" + + option.getLabel() + "
\n"); } } else { if (getObject() != null) { - checked = (((Vector) getObject()).contains(this - .getName()) ? " checked " : ""); + checked = (((Vector) getObject()).contains(this.getName()) ? " checked " : ""); } - optionString.append("" + this.getLabel()); + optionString.append("" + this.getLabel()); } return optionString.toString(); @@ -156,22 +148,22 @@ public String toHtml() @Override public String getValue() { - String value = ""; + StringBuilder valueBuilder = new StringBuilder(); for (ValueLabel i : getOptions()) { if (((Vector) getObject()).contains(i.getValue())) { - value += i.getLabel() + ", "; + valueBuilder.append(i.getLabel()).append(", "); } } // remove trailing comma - if (value.length() > 2) + if (valueBuilder.length() > 2) { - return value.substring(0, value.length() - 2); + return valueBuilder.substring(0, valueBuilder.length() - 2); } - return value; + return valueBuilder.toString(); } - + @Override public String toHtml(Tuple p) throws HtmlInputException { diff --git a/src/org/molgenis/framework/ui/html/CodeInput.java b/src/org/molgenis/framework/ui/html/CodeInput.java index 28d96f1f7..e1ad16f5a 100644 --- a/src/org/molgenis/framework/ui/html/CodeInput.java +++ b/src/org/molgenis/framework/ui/html/CodeInput.java @@ -23,34 +23,36 @@ */ public class CodeInput extends StringInput { - public enum Parser { - - FREEMARKER("\"../contrib/freemarker/js/parsefreemarker.js\"", "css/freemarkercolors.css"), - JAVA("[\"../contrib/java/js/tokenizejava.js\",\"../contrib/java/js/parsejava.js\"]", "generated-res/lib/codemirror-1.0/contrib/java/css/javacolors.css"); - + public enum Parser + { + + FREEMARKER("\"../contrib/freemarker/js/parsefreemarker.js\"", "css/freemarkercolors.css"), JAVA( + "[\"../contrib/java/js/tokenizejava.js\",\"../contrib/java/js/parsejava.js\"]", + "generated-res/lib/codemirror-1.0/contrib/java/css/javacolors.css"); + private final String path; private final String css; - + Parser(String path, String css) { this.path = path; this.css = css; } - + public String getPath() { return path; } - + public String getCssPath() { return css; } } - + private Parser parser = Parser.FREEMARKER; - + public CodeInput(String name) { this(name, null, Parser.FREEMARKER); @@ -100,21 +102,17 @@ public String getCustomHtmlHeaders() + "\n}" + "\n .editbox {" + "\n background: white;" - + "\n}" + + "\n}" + "\n.CodeMirror-scroll {" + "\n height: auto;" - + "\n overflow-y: hidden;" - + "\n overflow-x: auto;" - + "\n width: 100%" - + "\n}" - + "\n"; + + "\n overflow-y: hidden;" + "\n overflow-x: auto;" + "\n width: 100%" + "\n}" + "\n"; } - + public String getParser() { return this.parser.getPath(); } - + public String getParserStyle() { return this.parser.getCssPath(); @@ -126,8 +124,6 @@ public String toHtml() parameters.put("input", this); // delegate to freemarker (sad Java doesn't allow multiline strings). - return new FreemarkerView( - "org/molgenis/framework/ui/html/CodeInput.ftl", - parameters).render(); + return new FreemarkerView("org/molgenis/framework/ui/html/CodeInput.ftl", parameters).render(); } } diff --git a/src/org/molgenis/framework/ui/html/CommandTemplate.java b/src/org/molgenis/framework/ui/html/CommandTemplate.java index 352d25896..4a46681cd 100644 --- a/src/org/molgenis/framework/ui/html/CommandTemplate.java +++ b/src/org/molgenis/framework/ui/html/CommandTemplate.java @@ -36,8 +36,7 @@ public void addAll(Vector> inputs) @Override public HtmlInput get(Object key) { - if (key instanceof String) return super.get(((String) key) - .toLowerCase()); + if (key instanceof String) return super.get(((String) key).toLowerCase()); return super.get(key); } diff --git a/src/org/molgenis/framework/ui/html/Container.java b/src/org/molgenis/framework/ui/html/Container.java index 65674584f..01997fb19 100644 --- a/src/org/molgenis/framework/ui/html/Container.java +++ b/src/org/molgenis/framework/ui/html/Container.java @@ -14,8 +14,7 @@ * elements within one plugin. All "pieces" of your UI puzzle should be located * within a Container. */ -public class Container extends LinkedHashMap> implements - HtmlElement,ScreenView +public class Container extends LinkedHashMap> implements HtmlElement, ScreenView { private static final long serialVersionUID = -8565170009471766957L; @@ -40,8 +39,7 @@ public void addAll(Vector> inputs) @Override public HtmlInput get(Object key) { - if (key instanceof String) return super.get(((String) key) - .toLowerCase()); + if (key instanceof String) return super.get(((String) key).toLowerCase()); return super.get(key); } @@ -77,12 +75,12 @@ public List> getInputs() public String toHtml() { - String returnString = ""; + StringBuilder strBuilder = new StringBuilder(); for (HtmlInput i : this.getInputs()) { - returnString += i.toHtml(); + strBuilder.append(i.toHtml()); } - return returnString; + return strBuilder.toString(); } @Override @@ -115,7 +113,7 @@ public String getId() public void setId(String id) { // TODO Auto-generated method stub - + } @Override @@ -129,13 +127,13 @@ public String getClazz() public void setClazz(String clazz) { // TODO Auto-generated method stub - + } @Override public void set(Tuple properties) throws HtmlInputException { // TODO Auto-generated method stub - + } } diff --git a/src/org/molgenis/framework/ui/html/CustomHtml.java b/src/org/molgenis/framework/ui/html/CustomHtml.java index 6d5850cd2..31526cfd9 100644 --- a/src/org/molgenis/framework/ui/html/CustomHtml.java +++ b/src/org/molgenis/framework/ui/html/CustomHtml.java @@ -3,7 +3,7 @@ public class CustomHtml extends HtmlWidget { private String html; - + public CustomHtml(String html) { super(null); diff --git a/src/org/molgenis/framework/ui/html/DateInput.java b/src/org/molgenis/framework/ui/html/DateInput.java index da47299f1..32f1a63fc 100644 --- a/src/org/molgenis/framework/ui/html/DateInput.java +++ b/src/org/molgenis/framework/ui/html/DateInput.java @@ -24,14 +24,13 @@ * Input for date. */ - public class DateInput extends HtmlInput { /** String constants for property name 'hidden' */ public static final String DATEFORMAT = "dateformat"; /** Description. Defaults to 'name'. */ - private String dateformat= "dd-MM-yyyy"; - + private String dateformat = "dd-MM-yyyy"; + /** * Construct date input with name and using default value of today as value * @@ -88,8 +87,7 @@ public DateInput(String name, String label, Date value) * @param nillable * @param readonly */ - public DateInput(String name, String label, Date value, boolean nillable, - boolean readonly) + public DateInput(String name, String label, Date value, boolean nillable, boolean readonly) { super(name, value); if (label != null && !label.equals("null")) this.setLabel(label); @@ -107,7 +105,7 @@ public DateInput(Tuple properties) throws HtmlInputException { set(properties); } - + /** * Construct date input with name, label, value, tuple for script properties * @@ -119,8 +117,8 @@ public DateInput(Tuple properties) throws HtmlInputException * @param dateformat * @param Jqueryproperties */ - public DateInput(String name, String label, Date value, boolean nillable, - boolean readonly, String dateformat, String jqueryproperties) throws HtmlInputException + public DateInput(String name, String label, Date value, boolean nillable, boolean readonly, String dateformat, + String jqueryproperties) throws HtmlInputException { super(name, value); if (label != null && !label.equals("null")) this.setLabel(label); @@ -128,7 +126,7 @@ public DateInput(String name, String label, Date value, boolean nillable, this.setNillable(nillable); this.setDateFormat(dateformat); this.setJqueryproperties(jqueryproperties); - + } /** Null constructor. Use with caution. */ @@ -152,8 +150,7 @@ public String toHtml() private String toDefault() { - String readonly = (isReadonly() ? " class=\"readonly\" readonly " - : "onclick=\"showDateInput(this) " + ""); + String readonly = (isReadonly() ? " class=\"readonly\" readonly " : "onclick=\"showDateInput(this) " + ""); if (this.isHidden()) { @@ -162,9 +159,8 @@ private String toDefault() return input.toHtml(); } - return ""; + return ""; } @@ -209,11 +205,11 @@ public String getValue() public String toJquery() { - String description = getName().equals(getDescription()) ? "" : " title=\""+getDescription()+"\""; - //set defaults: + String description = getName().equals(getDescription()) ? "" : " title=\"" + getDescription() + "\""; + // set defaults: String options = "dateFormat: 'dd-mm-yy', changeMonth: true, changeYear: true, showButtonPanel: true"; String datevalue = this.getValue(this.getDateFormat()); - //change defaults to Jquery scriptvalues if set + // change defaults to Jquery scriptvalues if set if (this.getJqueryproperties() != null) { options = this.getJqueryproperties(); @@ -228,25 +224,17 @@ public String toJquery() String validate = ""; if (!this.isNillable()) validate = " required"; - String result = ""; + String result = ""; // add the dialog unless readonly (input is always readonly, i.e., // cannot be typed in). - if (!this.isReadonly()) result += ""; + if (!this.isReadonly()) result += ""; return result; } + @Override public String toHtml(Tuple p) throws ParseException, HtmlInputException { diff --git a/src/org/molgenis/framework/ui/html/DatetimeInput.java b/src/org/molgenis/framework/ui/html/DatetimeInput.java index 2e2b66446..6bff1fecc 100644 --- a/src/org/molgenis/framework/ui/html/DatetimeInput.java +++ b/src/org/molgenis/framework/ui/html/DatetimeInput.java @@ -34,16 +34,15 @@ public DatetimeInput(String name, Date value) { super(name, value); } - + /** Construct DatetimeInput with name, label, value */ public DatetimeInput(String name, String label, Date value) { super(name, label, value); } - /** Constructe Datetimeinput with name, label, value, nillable, and readonly*/ - public DatetimeInput(String name, String label, Date value, - boolean nillable, boolean readonly) + /** Constructe Datetimeinput with name, label, value, nillable, and readonly */ + public DatetimeInput(String name, String label, Date value, boolean nillable, boolean readonly) { super(name, value); if (label != null && !label.equals("null")) this.setLabel(label); @@ -62,12 +61,11 @@ public String toHtml() { if (this.isHidden()) { - StringInput input = new StringInput(this.getName(), this - .getValue()); + StringInput input = new StringInput(this.getName(), this.getValue()); input.setHidden(true); return input.toHtml(); } - + if (uiToolkit == UiToolkit.ORIGINAL) { return this.toDefault(); @@ -79,44 +77,42 @@ public String toHtml() return "NOT IMPLEMENTED FOR LIBRARY " + uiToolkit; } - + private String toDefault() { String readonly = isReadonly() ? " class=\"readonly\" readonly=\"readonly\" " : "onclick=\"showDateInput(this,true) " + ""; - - return ""; + return ""; } public String toJquery() - { - String description = getName().equals(getDescription()) ? "" : " title=\""+getDescription()+"\""; + { + String description = getName().equals(getDescription()) ? "" : " title=\"" + getDescription() + "\""; String options = "dateFormat: 'dd-mm-yy', changeMonth: true, changeYear: true, showButtonPanel: true"; - //add clear button if nillable - String createScript = "function( input ) {setTimeout(function() {var buttonPane = $( input ).datepicker( \"widget\" ).find( \".ui-datepicker-buttonpane\" );" + - "$( \"

"; - if(headerColumn){ + if (headerColumn) + { result += (""); } - - for (int colCount = 0; colCount < cols.size(); colCount++) { - result += (""); + + for (int colCount = 0; colCount < cols.size(); colCount++) + { + result += (""); } result += ""; return result; diff --git a/src/org/molgenis/framework/ui/html/EmailInput.java b/src/org/molgenis/framework/ui/html/EmailInput.java index cc913f7f2..c6fdaf0d7 100644 --- a/src/org/molgenis/framework/ui/html/EmailInput.java +++ b/src/org/molgenis/framework/ui/html/EmailInput.java @@ -9,14 +9,14 @@ */ public class EmailInput extends ValidatingInput { - + public EmailInput(String name) { super(name, null); this.validationString = "email"; this.setMaxWidth(10); } - + public EmailInput(String name, String label) { this(name); @@ -27,15 +27,14 @@ public EmailInput(String name, String label) public EmailInput(String name, Integer value) { - super( name, value ); + super(name, value); this.validationString = "email"; this.setMaxWidth(10); } - public EmailInput(String name, String label, Integer value, - boolean nillable, boolean readonly, String description) + public EmailInput(String name, String label, Integer value, boolean nillable, boolean readonly, String description) { - super(name,label, value, nillable,readonly, description); + super(name, label, value, nillable, readonly, description); this.validationString = "email"; this.setMaxWidth(10); } @@ -46,7 +45,7 @@ protected EmailInput() this.validationString = "email"; this.setMaxWidth(10); } - + public EmailInput(Tuple params) throws HtmlInputException { super(params); @@ -54,8 +53,7 @@ public EmailInput(Tuple params) throws HtmlInputException } @Override - public String toHtml(Tuple params) throws ParseException, - HtmlInputException + public String toHtml(Tuple params) throws ParseException, HtmlInputException { return new EmailInput(params).render(); } diff --git a/src/org/molgenis/framework/ui/html/EntityDataTable.java b/src/org/molgenis/framework/ui/html/EntityDataTable.java index 51e2134a4..c42793b49 100644 --- a/src/org/molgenis/framework/ui/html/EntityDataTable.java +++ b/src/org/molgenis/framework/ui/html/EntityDataTable.java @@ -11,9 +11,10 @@ import org.molgenis.util.Entity; /** - * DataTable for listing entity via an AJAX list view, incl search. - * - * To get this to work you also need to install the related molgenisservice. In your properties say:
+ * DataTable for listing entity via an AJAX list view, incl search. + * + * To get this to work you also need to install the related molgenisservice. In + * your properties say:
* org.molgenis.framework.server.services.MolgenisDataTableService@/datatable */ public class EntityDataTable extends HtmlWidget @@ -64,35 +65,34 @@ public String toHtml() } - String result = "
${input.getHtmlValue()}${input.getHtmlValue(100)}...${input.getHtmlValue(100)}...
" + row + "" + - ( - getCellString(colCount, rowCount).contains("<") - ? - getCellString(colCount, rowCount) - : - "" - ) - + "" + + (getCellString(colCount, rowCount).contains("<") ? getCellString(colCount, rowCount) + : "") + "
"; + StringBuilder strBuilder = new StringBuilder(); + strBuilder.append("
"); for (String label : labels) - result += ""; - result += "
" + label + "
"; - result += "\n"; - return result; + strBuilder.append("{ 'mDataProp' : '").append(label).append("'}").append(','); + if (!labels.isEmpty()) strBuilder.deleteCharAt(strBuilder.length() - 1); + strBuilder.append(" ],"); + strBuilder.append(" 'fnServerParams' : function(aoData) {"); + strBuilder.append("\n aoData.push({"); + strBuilder.append("\n 'name' : 'entity',"); + strBuilder.append("\n 'value' : '").append(klazzName).append('\''); + strBuilder.append("\n });"); + strBuilder.append("\n}"); + strBuilder.append("});"); + strBuilder.append("\nnew FixedColumns(oTable, {'iLeftWidth' : 200});"); + strBuilder.append(""); + return strBuilder.toString(); } } diff --git a/src/org/molgenis/framework/ui/html/EntityForm.java b/src/org/molgenis/framework/ui/html/EntityForm.java index abfb0de25..f8944986f 100644 --- a/src/org/molgenis/framework/ui/html/EntityForm.java +++ b/src/org/molgenis/framework/ui/html/EntityForm.java @@ -61,8 +61,7 @@ public void setEntity(E entity) public void setInputs(List> inputs) { - throw new UnsupportedOperationException( - "In EntityForm the inputs cannot be changed"); + throw new UnsupportedOperationException("In EntityForm the inputs cannot be changed"); } /** @@ -92,23 +91,23 @@ public void set(String name, Object value) throws Exception */ public abstract Vector getHeaders(); - public List> getInputs(String ... fieldNames) + public List> getInputs(String... fieldNames) { Entity entity = this.getEntity(); List> inputs = this.getInputs(); - List> result = new ArrayList>(); - - for(String fieldName: fieldNames) + List> result = new ArrayList>(); + + for (String fieldName : fieldNames) { - if(!entity.getFields().contains(fieldName)) + if (!entity.getFields().contains(fieldName)) { - throw new RuntimeException(fieldName +" not known in "+this.getClass().getSimpleName()); + throw new RuntimeException(fieldName + " not known in " + this.getClass().getSimpleName()); } - - for(HtmlInput input: inputs) + + for (HtmlInput input : inputs) { - //will this work always?? - if(input.getName().equalsIgnoreCase(entity.getClass().getSimpleName()+"_"+fieldName)) + // will this work always?? + if (input.getName().equalsIgnoreCase(entity.getClass().getSimpleName() + "_" + fieldName)) { result.add(input); } @@ -116,6 +115,6 @@ public List> getInputs(String ... fieldNames) } return result; - + } } diff --git a/src/org/molgenis/framework/ui/html/EntityJqGrid.java b/src/org/molgenis/framework/ui/html/EntityJqGrid.java index c80c6ad83..37641b1bd 100644 --- a/src/org/molgenis/framework/ui/html/EntityJqGrid.java +++ b/src/org/molgenis/framework/ui/html/EntityJqGrid.java @@ -64,8 +64,8 @@ public String toHtml() colDefs += String.format("{name: '%s', index: '%s', width: 55},", field.getName(), field.getName()); } } - colDefs.substring(0, colDefs.length() - 2); - colNames.substring(0, colNames.length() - 2); + colDefs = colDefs.substring(0, colDefs.length() - 2); + colNames = colNames.substring(0, colNames.length() - 2); // configure the jqGrid String result = ""; @@ -93,8 +93,11 @@ public String toHtml() // create search box. OnChange, update postData with filter and // reload - result += "\n$('#" + getName() - + "_pager_left').append('');"; + result += "\n$('#" + + getName() + + "_pager_left').append('');"; result += "\n"; diff --git a/src/org/molgenis/framework/ui/html/EntityTable.java b/src/org/molgenis/framework/ui/html/EntityTable.java index b260fd295..fe6059e35 100644 --- a/src/org/molgenis/framework/ui/html/EntityTable.java +++ b/src/org/molgenis/framework/ui/html/EntityTable.java @@ -20,9 +20,9 @@ public EntityTable(Collection entities, boolean editButton, St public EntityTable(String name, Collection entities) { - this(name,entities,false); + this(name, entities, false); } - + public EntityTable(String name, Collection entities, boolean editButton, String... columns) { super(name); @@ -66,39 +66,43 @@ public EntityTable(String name, Collection entities, boolean e @Override public String toHtml() { - String htmlTable = ""; + StringBuilder htmlBuilder = new StringBuilder("
"); // create header - htmlTable += ""; + htmlBuilder.append(""); for (String column : this.columns) { - htmlTable += ""; + htmlBuilder.append(""); } - htmlTable += ""; + htmlBuilder.append(""); // render records int color = 0; for (Entity e : entities) { - htmlTable += ""; + htmlBuilder.append(""); if (color == 0) color = 1; else color = 0; for (String column : this.columns) { - htmlTable += ""; + htmlBuilder.append(""); } if (editButton == true) { - htmlTable += ""; + htmlBuilder + .append(""); } - htmlTable += ""; + htmlBuilder.append(""); } - htmlTable += "
" + column + "").append(column).append("
" +( e.get(column) == null ? "" : e.get(column).toString().replace(">", ">").replace("<", "<").replace("\n","
")) + "
"); + if (e.get(column) != null) htmlBuilder.append(e.get(column).toString().replace(">", ">") + .replace("<", "<").replace("\n", "
")); + htmlBuilder.append("
"; + htmlBuilder.append("
"); - return htmlTable; + return htmlBuilder.toString(); } - } diff --git a/src/org/molgenis/framework/ui/html/EnumInput.java b/src/org/molgenis/framework/ui/html/EnumInput.java index 324dbe7c6..fef96b206 100644 --- a/src/org/molgenis/framework/ui/html/EnumInput.java +++ b/src/org/molgenis/framework/ui/html/EnumInput.java @@ -11,7 +11,6 @@ package org.molgenis.framework.ui.html; - /** * Input for enumerated data. */ @@ -21,7 +20,7 @@ public EnumInput(String name, String value) { super(name, value); } - + public EnumInput(String name) { this(name, null); diff --git a/src/org/molgenis/framework/ui/html/FileInput.java b/src/org/molgenis/framework/ui/html/FileInput.java index fd13c3c9b..3d0d64198 100644 --- a/src/org/molgenis/framework/ui/html/FileInput.java +++ b/src/org/molgenis/framework/ui/html/FileInput.java @@ -32,8 +32,7 @@ public FileInput(String name) this(name, null); } - public FileInput(String name, String label, String value, boolean nillable, - boolean readonly) + public FileInput(String name, String label, String value, boolean nillable, boolean readonly) { this(name, value); this.setLabel(label); @@ -55,8 +54,7 @@ public String toHtml() { // FIXME how to check not null file uploads this.setNillable(true); - String readonly = (isReadonly() ? "readonly class=\"readonly\" readonly " - : ""); + String readonly = (isReadonly() ? "readonly class=\"readonly\" readonly " : ""); StringInput hidden = new StringInput(this.getName(), super.getValue()); hidden.setLabel(this.getLabel()); @@ -68,19 +66,17 @@ public String toHtml() return hidden.toHtml(); } - if(uiToolkit == UiToolkit.ORIGINAL) + if (uiToolkit == UiToolkit.ORIGINAL) { return hidden.toHtml() - + (!isReadonly() ? "" - : "") + getValue(); + + (!isReadonly() ? "" : "") + getValue(); } else if (uiToolkit == UiToolkit.JQUERY) { return hidden.toHtml() + (!isReadonly() ? "" - : "") + getValue(); + + "name=\"filefor_" + getName() + "\" size=\"20\">" : "") + getValue(); } else { @@ -93,10 +89,9 @@ else if (uiToolkit == UiToolkit.JQUERY) */ public String getValue() { - if (super.getValue() != "") return super.getValue() + if (!super.getValue().isEmpty()) return super.getValue() + ""; + + super.getValue() + "';this.form.__action.value='" + ACTION_DOWNLOAD + "'; return true;\"/>"; return super.getValue(); } diff --git a/src/org/molgenis/framework/ui/html/FlowLayout.java b/src/org/molgenis/framework/ui/html/FlowLayout.java index 7620d350a..1debe11e6 100644 --- a/src/org/molgenis/framework/ui/html/FlowLayout.java +++ b/src/org/molgenis/framework/ui/html/FlowLayout.java @@ -41,8 +41,7 @@ public void setElements(List elements) @Override public void add(HtmlElement input) { - if (input == null) throw new UnsupportedOperationException( - "intput cannot be null"); + if (input == null) throw new UnsupportedOperationException("intput cannot be null"); this.elements.add(input); } @@ -50,19 +49,12 @@ public void add(HtmlElement input) @Override public String render() { - String returnString = ""; + StringBuilder strBuilder = new StringBuilder(); for (HtmlElement i : this.getElements()) { - // If the element is an HtmlInput, also include the label (render() does not do this for you) - if (i instanceof HtmlInput && !(i instanceof ActionInput)) { -// if (!input.isHidden() && input.getLabel() != null && !input.getLabel().equals("")) { -// returnString += ""; -// } - } - returnString += i.render(); + strBuilder.append(i.render()); } - return returnString; + return strBuilder.toString(); } @Override @@ -72,8 +64,7 @@ public String getCustomHtmlHeaders() } @Override - public String render(Tuple params) throws ParseException, - HtmlInputException + public String render(Tuple params) throws ParseException, HtmlInputException { throw new UnsupportedOperationException("not implemented"); } diff --git a/src/org/molgenis/framework/ui/html/FreemarkerInput.java b/src/org/molgenis/framework/ui/html/FreemarkerInput.java index 7a4ffbdb8..d66effc66 100644 --- a/src/org/molgenis/framework/ui/html/FreemarkerInput.java +++ b/src/org/molgenis/framework/ui/html/FreemarkerInput.java @@ -11,7 +11,6 @@ package org.molgenis.framework.ui.html; - /** * Renders an editor for freemarker including code higlighting and line numbers. * diff --git a/src/org/molgenis/framework/ui/html/GridPanel.java b/src/org/molgenis/framework/ui/html/GridPanel.java index 343193a77..c49ef50a9 100644 --- a/src/org/molgenis/framework/ui/html/GridPanel.java +++ b/src/org/molgenis/framework/ui/html/GridPanel.java @@ -8,10 +8,10 @@ public GridPanel() { super(); } - + public GridPanel(int columns) { - this.columns = columns; + this.columns = columns; } public void setColumns(int columns) @@ -22,31 +22,28 @@ public void setColumns(int columns) @Override public String toHtml() { - String result = "\n"; - int cell = 0; + StringBuilder strBuilder = new StringBuilder("
\n"); + int cell = 0; for (HtmlInput i : this.inputs.values()) { - if (i.isHidden()) - continue; + if (i.isHidden()) continue; if (cell % columns == 0) { - if (cell != 0) - result += "\n"; - result += ""; + if (cell != 0) strBuilder.append("\n"); + strBuilder.append(""); } - result += (""); - + strBuilder.append(""); + cell++; } - - if (this.inputs.size() > 0) - result += "\n"; - result += "
" + i.getLabel() + "" + i.toHtml() + "").append(i.getLabel()).append("").append(i.toHtml()).append("
\n"; + if (this.inputs.size() > 0) strBuilder.append("\n"); + + strBuilder.append("\n"); - return result; + return strBuilder.toString(); } } diff --git a/src/org/molgenis/framework/ui/html/HexaInput.java b/src/org/molgenis/framework/ui/html/HexaInput.java index e6e811abe..dcbebe2b1 100644 --- a/src/org/molgenis/framework/ui/html/HexaInput.java +++ b/src/org/molgenis/framework/ui/html/HexaInput.java @@ -9,8 +9,8 @@ public class HexaInput extends StringInput public HexaInput(String name) { this(name, null); - } - + } + public HexaInput(String name, String value) { super(name, value); diff --git a/src/org/molgenis/framework/ui/html/HiddenInput.java b/src/org/molgenis/framework/ui/html/HiddenInput.java index 1a0842c6b..1faaf8cd5 100644 --- a/src/org/molgenis/framework/ui/html/HiddenInput.java +++ b/src/org/molgenis/framework/ui/html/HiddenInput.java @@ -3,7 +3,8 @@ import org.molgenis.util.Tuple; /** - * Input that should be hidden from view. Used for hidden parameters that users don't want/need to see. + * Input that should be hidden from view. Used for hidden parameters that users + * don't want/need to see. */ public class HiddenInput extends StringInput { @@ -18,11 +19,11 @@ public HiddenInput() { // TODO Auto-generated constructor stub } - + @Override public String toHtml(Tuple params) throws HtmlInputException { - params.set(HIDDEN,true); + params.set(HIDDEN, true); return super.toHtml(params); } diff --git a/src/org/molgenis/framework/ui/html/HorizontalRuler.java b/src/org/molgenis/framework/ui/html/HorizontalRuler.java index e932b738e..76dbcf812 100644 --- a/src/org/molgenis/framework/ui/html/HorizontalRuler.java +++ b/src/org/molgenis/framework/ui/html/HorizontalRuler.java @@ -2,8 +2,9 @@ public class HorizontalRuler extends HtmlInput { - - public HorizontalRuler() { + + public HorizontalRuler() + { this.setLabel(""); } diff --git a/src/org/molgenis/framework/ui/html/HtmlElement.java b/src/org/molgenis/framework/ui/html/HtmlElement.java index 6093bc04f..11415e880 100644 --- a/src/org/molgenis/framework/ui/html/HtmlElement.java +++ b/src/org/molgenis/framework/ui/html/HtmlElement.java @@ -28,9 +28,9 @@ public interface HtmlElement public enum UiToolkit { /** jquery-ui */ - JQUERY, + JQUERY, /** old layout */ - ORIGINAL, + ORIGINAL, /** twitter bootstrap */ BOOTSTRAP }; diff --git a/src/org/molgenis/framework/ui/html/HtmlForm.java b/src/org/molgenis/framework/ui/html/HtmlForm.java index c1dd0d0de..26d02bb93 100644 --- a/src/org/molgenis/framework/ui/html/HtmlForm.java +++ b/src/org/molgenis/framework/ui/html/HtmlForm.java @@ -75,7 +75,7 @@ public HtmlInput setReadonly(boolean readonly) return this; } - public void addInput(HtmlInput ... inputs) + public void addInput(HtmlInput... inputs) { for (HtmlInput input : inputs) { @@ -111,28 +111,28 @@ public List getCompactView() * All fields that are not in this list will be marked as 'collapsed' so * they are not visible unless the button 'details' is pushed * - * @param compactView list of field names + * @param compactView + * list of field names */ public void setCompactView(List compactView) { this.compactView = compactView; } - + /** - * A simple method to create a edited view for one entity. + * A simple method to create a edited view for one entity. */ @Override public String toHtml() { - String htmlTable = ""; - for(HtmlInput i: this.getInputs()) + StringBuilder htmlBuilder = new StringBuilder("
"); + for (HtmlInput i : this.getInputs()) { - htmlTable += ""; + htmlBuilder.append(""); } - htmlTable += "
" + - i.getLabel() + ""+ i.getHtml() +"
"); + htmlBuilder.append(i.getLabel()).append("").append(i.getHtml()).append("
"; - return htmlTable; - + htmlBuilder.append(""); + return htmlBuilder.toString(); } } diff --git a/src/org/molgenis/framework/ui/html/HtmlInput.java b/src/org/molgenis/framework/ui/html/HtmlInput.java index 1d006f1ef..1bf169672 100644 --- a/src/org/molgenis/framework/ui/html/HtmlInput.java +++ b/src/org/molgenis/framework/ui/html/HtmlInput.java @@ -36,7 +36,7 @@ public abstract class HtmlInput extends AbstractHtmlElement implements Input< /** String constants for property name 'hidden' */ public static final String HIDDEN = "hidden"; - + public static final String JQUERYPROPERTIES = "Jqueryproperties"; // PROPERTIES @@ -81,13 +81,13 @@ public abstract class HtmlInput extends AbstractHtmlElement implements Input< /** to pass jquery script properties. */ private String Jqueryproperties; - + /** Tab index of this input (optionl) */ protected String tabIndex = ""; /** Style to render in */ protected UiToolkit uiToolkit = HtmlSettings.uiToolkit; - + protected RenderDecorator renderDecorator = HtmlSettings.defaultRenderDecorator; /** @@ -100,15 +100,15 @@ public abstract class HtmlInput extends AbstractHtmlElement implements Input< */ public HtmlInput(String name, E value) { - if(name == null) name = UUID.randomUUID().toString().replace("-",""); + if (name == null) name = UUID.randomUUID().toString().replace("-", ""); this.setId(name.replace(" ", "")); this.setName(name.replace(" ", "")); this.setLabel(name); - //this.setDescription(name); + // this.setDescription(name); this.setId(name); this.setValue(value); } - + public HtmlInput(String name, String label, E value) { assert (name != null); @@ -116,14 +116,14 @@ public HtmlInput(String name, String label, E value) this.setId(name.replace(" ", "")); this.setName(name.replace(" ", "")); this.setLabel(label); - //this.setDescription(name); + // this.setDescription(name); this.setId(name); - this.setValue(value); + this.setValue(value); } /** - * Complete constructor - * + * Complete constructor + * * @param name * @param label * @param value @@ -131,8 +131,7 @@ public HtmlInput(String name, String label, E value) * @param readonly * @param description */ - public HtmlInput(String name, String label, E value, boolean nillable, - boolean readonly, String description) + public HtmlInput(String name, String label, E value, boolean nillable, boolean readonly, String description) { this(name, value); this.setLabel(label); @@ -142,7 +141,8 @@ public HtmlInput(String name, String label, E value, boolean nillable, } /** - * Constructor using a tuple. Valid keys for the tuple are listed as constant, e.g. HtmlInput.NAME + * Constructor using a tuple. Valid keys for the tuple are listed as + * constant, e.g. HtmlInput.NAME * * @param properties * @throws HtmlInputException @@ -191,14 +191,15 @@ public String getLabel() public HtmlInput setLabel(String label) { - //assert (label != null); fails web tests due to label -> null constructors, so allow it + // assert (label != null); fails web tests due to label -> null + // constructors, so allow it this.label = label; return this; } public String getName() { - if(name == null) return this.getId(); + if (name == null) return this.getId(); return name; } @@ -213,11 +214,12 @@ public E getObject() { return value; } - + public String getObjectString() { - if(this.value == null) return ""; - else return value.toString(); + if (this.value == null) return ""; + else + return value.toString(); } // TODO: This *needs* to be renamed to getValueToString() or removed!!! @@ -241,63 +243,64 @@ public String getValue(boolean replaceSpecialChars) } // todo: why different from getHtmlValue()?? -// if (replaceSpechialChars) -// { -// return this.renderDecorator.render(getObject().toString().replace("\n", "
") -// .replace("\r", "").replace(">", ">") -// .replace("<", "<")); -// } -// else -// { + // if (replaceSpechialChars) + // { + // return + // this.renderDecorator.render(getObject().toString().replace("\n", + // "
") + // .replace("\r", "").replace(">", ">") + // .replace("<", "<")); + // } + // else + // { return getObject().toString(); -// } + // } } - + public String getHtmlValue(int maxLength) { - //we render all tags, but we stop rendering text outside tags after maxLength - String result = ""; + // we render all tags, but we stop rendering text outside tags after + // maxLength + StringBuilder strBuilder = new StringBuilder(); boolean inTag = false; int count = 0; - for(char c: this.getHtmlValue().toCharArray()) + for (char c : this.getHtmlValue().toCharArray()) { - //check if we go into tag - if('<' == c) + // check if we go into tag + if ('<' == c) { - inTag = true; + inTag = true; } - - if(inTag || count < maxLength) + + if (inTag || count < maxLength) { - result += c; + strBuilder.append(c); } - - if('>' == c) + + if ('>' == c) { inTag = false; } - - if(!inTag) count++; + + if (!inTag) count++; } - - return result; + return strBuilder.toString(); } public String getHtmlValue() { String value = null; value = this.getValue(); - //.replace("\n", "
").replace("\r", "") - //.replace(">", ">").replace("<", "<"); + // .replace("\n", "
").replace("\r", "") + // .replace(">", ">").replace("<", "<"); return this.renderDecorator.render(value); } public String getJavaScriptValue() { - String value = StringEscapeUtils.escapeXml(StringEscapeUtils - .escapeJavaScript(this.getValue())); + String value = StringEscapeUtils.escapeXml(StringEscapeUtils.escapeJavaScript(this.getValue())); return value; } @@ -310,20 +313,18 @@ public String getJavaScriptValue() * @throws HtmlInputException */ @Deprecated - public String toHtml(Tuple params) throws ParseException, - HtmlInputException + public String toHtml(Tuple params) throws ParseException, HtmlInputException { throw new UnsupportedOperationException(); } /** Synonym to toHtml */ @SuppressWarnings("deprecation") - public String render(Tuple params) throws ParseException, - HtmlInputException + public String render(Tuple params) throws ParseException, HtmlInputException { return this.toHtml(params); } - + @Override public String render() { @@ -336,8 +337,8 @@ public String getCustomHtmlHeaders() // TODO Auto-generated method stub return null; } - - //BORING PROPERTIES + + // BORING PROPERTIES public HtmlInput setValue(E value) { this.value = value; @@ -479,12 +480,10 @@ public HtmlInput setTabIndex(int tabidx) tabIndex = " tabindex=" + Integer.toString(tabidx); return this; } - + public UiToolkit getUiToolkit() { return this.uiToolkit; } - - } diff --git a/src/org/molgenis/framework/ui/html/HtmlSettings.java b/src/org/molgenis/framework/ui/html/HtmlSettings.java index ce79bd05a..09064a8aa 100644 --- a/src/org/molgenis/framework/ui/html/HtmlSettings.java +++ b/src/org/molgenis/framework/ui/html/HtmlSettings.java @@ -5,11 +5,11 @@ import org.molgenis.framework.ui.html.render.RenderDecorator; public class HtmlSettings -{ - public static UiToolkit uiToolkit = UiToolkit.JQUERY; - //public static UiToolkit uiToolkit = UiToolkit.ORIGINAL; +{ + public final static UiToolkit uiToolkit = UiToolkit.JQUERY; + // public static UiToolkit uiToolkit = UiToolkit.ORIGINAL; public static RenderDecorator defaultRenderDecorator = new LinkoutRenderDecorator(); - - //FIXME: define new MolgenisOption with default 'true' + + // FIXME: define new MolgenisOption with default 'true' public static boolean showDescription = true; } diff --git a/src/org/molgenis/framework/ui/html/HtmlWidget.java b/src/org/molgenis/framework/ui/html/HtmlWidget.java index ff33a2474..f99bebe62 100644 --- a/src/org/molgenis/framework/ui/html/HtmlWidget.java +++ b/src/org/molgenis/framework/ui/html/HtmlWidget.java @@ -8,12 +8,12 @@ public abstract class HtmlWidget extends HtmlInput public HtmlWidget(String name, String label) { - super(name,label); + super(name, label); } public HtmlWidget(String name) { - super(name,name); + super(name, name); } } diff --git a/src/org/molgenis/framework/ui/html/HyperlinkInput.java b/src/org/molgenis/framework/ui/html/HyperlinkInput.java index e595bfabb..063f4e665 100644 --- a/src/org/molgenis/framework/ui/html/HyperlinkInput.java +++ b/src/org/molgenis/framework/ui/html/HyperlinkInput.java @@ -30,7 +30,7 @@ public HyperlinkInput(String name) { this(name, null); } - + /** * Construct HyperlinkInput with name and value * @@ -51,8 +51,7 @@ public HyperlinkInput(String name, String value) * @param nillable * @param readonly */ - public HyperlinkInput(String name, String label, String value, - boolean nillable, boolean readonly) + public HyperlinkInput(String name, String label, String value, boolean nillable, boolean readonly) { super(name, value); this.setLabel(label); @@ -74,8 +73,7 @@ public HyperlinkInput(Tuple properties) @Override public String getValue() { - return "" + super.getValue() - + ""; + return "" + super.getValue() + ""; } /** @@ -89,21 +87,21 @@ public String getHtmlValue() @Override public String toHtml() { -// String readonly = (isReadonly() ? "readonly class=\"readonly\" " : ""); + // String readonly = (isReadonly() ? "readonly class=\"readonly\" " : + // ""); -// if (this.isHidden()) -// { - StringInput input = new StringInput(this.getName(), super - .getValue()); - input.setLabel(this.getLabel()); - input.setDescription(this.getDescription()); - input.setHidden(this.isHidden()); - input.setReadonly(this.isReadonly()); - return input.toHtml() + this.getValue(); -// } + // if (this.isHidden()) + // { + StringInput input = new StringInput(this.getName(), super.getValue()); + input.setLabel(this.getLabel()); + input.setDescription(this.getDescription()); + input.setHidden(this.isHidden()); + input.setReadonly(this.isReadonly()); + return input.toHtml() + this.getValue(); + // } -// return ""; + // return ""; } @Override diff --git a/src/org/molgenis/framework/ui/html/ImageInput.java b/src/org/molgenis/framework/ui/html/ImageInput.java index e0f3fccc9..7b9e61336 100644 --- a/src/org/molgenis/framework/ui/html/ImageInput.java +++ b/src/org/molgenis/framework/ui/html/ImageInput.java @@ -20,10 +20,8 @@ public ImageInput(String name, Object value) @Override public String getValue() { - if (super.getValue() != "") return getObject() + ""; return super.getValue(); } diff --git a/src/org/molgenis/framework/ui/html/Input.java b/src/org/molgenis/framework/ui/html/Input.java index 5c6079034..1a05868ff 100644 --- a/src/org/molgenis/framework/ui/html/Input.java +++ b/src/org/molgenis/framework/ui/html/Input.java @@ -1,9 +1,8 @@ package org.molgenis.framework.ui.html; /** - * Input is the base-class for all the input classes. It provides the - * common interface as well as some convenience methods for processing the - * inputs. + * Input is the base-class for all the input classes. It provides the common + * interface as well as some convenience methods for processing the inputs. * * An Input has: *
    @@ -23,5 +22,4 @@ public interface Input { - } \ No newline at end of file diff --git a/src/org/molgenis/framework/ui/html/IntInput.java b/src/org/molgenis/framework/ui/html/IntInput.java index fee9f429d..3b95e385c 100644 --- a/src/org/molgenis/framework/ui/html/IntInput.java +++ b/src/org/molgenis/framework/ui/html/IntInput.java @@ -9,14 +9,14 @@ */ public class IntInput extends ValidatingInput { - + public IntInput(String name) { super(name, null); this.validationString = "digits"; this.setMaxWidth(10); } - + public IntInput(String name, String label) { this(name); @@ -27,15 +27,14 @@ public IntInput(String name, String label) public IntInput(String name, Integer value) { - super( name, value ); + super(name, value); this.validationString = "digits"; this.setMaxWidth(10); } - public IntInput(String name, String label, Integer value, - boolean nillable, boolean readonly, String description) + public IntInput(String name, String label, Integer value, boolean nillable, boolean readonly, String description) { - super(name,label, value, nillable,readonly, description); + super(name, label, value, nillable, readonly, description); this.validationString = "digits"; this.setMaxWidth(10); } @@ -46,7 +45,7 @@ protected IntInput() this.validationString = "digits"; this.setMaxWidth(10); } - + public IntInput(Tuple params) throws HtmlInputException { super(params); @@ -54,8 +53,7 @@ public IntInput(Tuple params) throws HtmlInputException } @Override - public String toHtml(Tuple params) throws ParseException, - HtmlInputException + public String toHtml(Tuple params) throws ParseException, HtmlInputException { return new IntInput(params).render(); } diff --git a/src/org/molgenis/framework/ui/html/JQueryDataTable.java b/src/org/molgenis/framework/ui/html/JQueryDataTable.java index 0b3e8b5ab..91051e232 100644 --- a/src/org/molgenis/framework/ui/html/JQueryDataTable.java +++ b/src/org/molgenis/framework/ui/html/JQueryDataTable.java @@ -1,20 +1,24 @@ package org.molgenis.framework.ui.html; /** - * An extension of Table that renders as a jQuery DataTable instead of - * a plain HTML table. + * An extension of Table that renders as a jQuery DataTable instead of a plain + * HTML table. * * @author erikroos - * + * */ public class JQueryDataTable extends Table { + private boolean bSort = false; + private boolean bFilter = false; + private boolean bPaginate = false; + public JQueryDataTable(String name) { this(name, null); } - + public JQueryDataTable(String name, String label) { super(name, label); @@ -22,29 +26,82 @@ public JQueryDataTable(String name, String label) super.setDefaultCellStyle(""); super.setHeaderCellStyle(""); } - + @Override - public String toHtml() { - String result = super.toHtml(); - result += ""; - return result; + else + { + strBuilder.append("\n\"bFilter\": false,"); + } + if (bPaginate) + { + strBuilder.append("\n\"bPaginate\": true,"); + } + else + { + strBuilder.append("\n\"bPaginate\": false,"); + } + + strBuilder.append("\n\"aoColumns\": ["); + // Prevent fancy auto-detected sorting types by hard-setting to 'string' + // for every column + for (int i = 0; i < super.cols.size() + 1; i++) + { + strBuilder.append("\n{ \"sType\": \"string\" },"); + } + strBuilder.setLength(strBuilder.length() - 1); // chop off last , + strBuilder.append("\n]"); + strBuilder.append("\n})"); + return strBuilder.toString(); + } + + public boolean isbSort() + { + return bSort; + } + + public void setbSort(boolean bSort) + { + this.bSort = bSort; + } + + public boolean isbFilter() + { + return bFilter; + } + + public void setbFilter(boolean bFilter) + { + this.bFilter = bFilter; + } + + public boolean isbPaginate() + { + return bPaginate; + } + + public void setbPaginate(boolean bPaginate) + { + this.bPaginate = bPaginate; } } diff --git a/src/org/molgenis/framework/ui/html/JQueryDataTableBeta.java b/src/org/molgenis/framework/ui/html/JQueryDataTableBeta.java index e3a608a71..aa79c14e8 100644 --- a/src/org/molgenis/framework/ui/html/JQueryDataTableBeta.java +++ b/src/org/molgenis/framework/ui/html/JQueryDataTableBeta.java @@ -15,12 +15,9 @@ public JQueryDataTableBeta(String name) public String toHtml() { String result = super.toHtml(); - result += ""; + result += ""; return result; } diff --git a/src/org/molgenis/framework/ui/html/JQueryEditable.java b/src/org/molgenis/framework/ui/html/JQueryEditable.java new file mode 100644 index 000000000..fa08f1f48 --- /dev/null +++ b/src/org/molgenis/framework/ui/html/JQueryEditable.java @@ -0,0 +1,95 @@ +package org.molgenis.framework.ui.html; + +public class JQueryEditable extends HtmlWidget +{ + private String contents; + + /* Todo : data can be html >> */ + public JQueryEditable(String name, String contents) + { + super(name); + this.setContents(contents); + } + + /** + * + * + */ + // private String renderEditable(String contents) + // { + // String returnString = null; + // + // if (!contents.isEmpty()) + // { + // returnString = "
    Dolor
    "; + // returnString = "
    Lorem ipsum " + // + "dolor sit amet, consectetuer .
    "; + // + // // returnString = "
  • " + // // + node.getLabel() + "\n" + "
      \n"; + // } + // else + // { + // returnString = "No text available!"; + // // returnString = "
    • " + + // // node.getLabel() + "\n" + // // + "
        \n"; + // } + // + // return returnString; + // } + + public String toHtml() + { + String html = "" + + "\n" + + ""; + + return html; + } + + public String getContents() + { + return contents; + } + + public void setContents(String contents) + { + this.contents = contents; + } +} diff --git a/src/org/molgenis/framework/ui/html/JQuerySplitter.java b/src/org/molgenis/framework/ui/html/JQuerySplitter.java index 6fe5d9bdf..13b799869 100644 --- a/src/org/molgenis/framework/ui/html/JQuerySplitter.java +++ b/src/org/molgenis/framework/ui/html/JQuerySplitter.java @@ -1,6 +1,5 @@ package org.molgenis.framework.ui.html; - public class JQuerySplitter extends HtmlWidget { private String splitterName; @@ -9,98 +8,99 @@ public class JQuerySplitter extends HtmlWidget public JQuerySplitter(String name, JQuerySplitterContents contents) { super(name); - + this.setSplitterContents(new JQuerySplitterContents()); this.setSplitterContents(contents); this.setSplitterName(name); } @Override - public String toHtml(){ - -//<<<<<<< .mine -// String html = "\n"; -// html += ""; -// //html += "