diff --git a/Dockerfile b/Dockerfile index 0e7ea0eeff..eb2640f162 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,7 +2,7 @@ FROM eclipse-temurin:17 as jre-build # Create a custom Java runtime RUN $JAVA_HOME/bin/jlink \ - --add-modules java.base \ + --add-modules ALL-MODULE-PATH \ --strip-debug \ --no-man-pages \ --no-header-files \ @@ -60,17 +60,7 @@ RUN python3 -m pip install poetry && poetry config cache-dir "/poetry/.cache" ENV PATH="/root/.poetry/bin:/root/.local/bin:$PATH" # Copy JAR files -COPY ./vcell-client/target/vcell-client-0.0.1-SNAPSHOT.jar \ - ./vcell-client/target/maven-jars/*.jar \ - ./vcell-core/target/vcell-core-0.0.1-SNAPSHOT.jar \ - ./vcell-core/target/maven-jars/*.jar \ - ./vcell-server/target/vcell-server-0.0.1-SNAPSHOT.jar \ - ./vcell-server/target/maven-jars/*.jar \ - ./vcell-vmicro/target/vcell-vmicro-0.0.1-SNAPSHOT.jar \ - ./vcell-vmicro/target/maven-jars/*.jar \ - ./vcell-admin/target/vcell-admin-0.0.1-SNAPSHOT.jar \ - ./vcell-admin/target/maven-jars/*.jar \ - ./vcell-cli/target/vcell-cli-0.0.1-SNAPSHOT.jar \ +COPY ./vcell-cli/target/vcell-cli-0.0.1-SNAPSHOT.jar \ ./vcell-cli/target/maven-jars/*.jar \ ./non-maven-java-libs/org/sbml/libcombine/libCombineLinux64/0.2.7/libCombineLinux64-0.2.7.jar \ /usr/local/app/vcell/lib/ diff --git a/README.md b/README.md index acff63b0f2..93e61ab8c2 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Requirements: Eclipse IDE for Java Developers and Java JDK 1.8 or later * Name: VCellClient * Main: * Project: `vcell-client` - * Main Class: `cbit.vcell.client.test.VCellClientTest` + * Main Class: `cbit.vcell.client.test.VCellClientMain` * Arguments: * Program arguments: `vcellapi-beta.cam.uchc.edu:8080` * VM arguments are: @@ -111,7 +111,7 @@ VCell Server Installation General Requirements ### Other Details -1. Creating certs [details](README_certs.md) +1. Creating certs [details](docs-misc/README_certs.md) 1.1. (TLS/SSL website for (vcellapi.cam.uchc.edu,vcell-api.cam.uchc.edu) 1.2. Microsoft authenticode codesigning (to prevent install4j from being rejected on windows clients) 1.3. Apple codesigning for macos (prevents from mac refusing install4j install)) @@ -122,9 +122,9 @@ VCell Server Installation General Requirements 4. Building VCell Client/Server [Software detailed instructions](docker/build/README.md) 4.1. Github/Travis/Appveyor/Dockerhub [Instructions](README_git_trav_appv_dhub.md) 5. Deploying VCell Client/Server software [detailed instructions](docker/swarm/README.md) - 5.1. VCell System [Flow-Control](README_flow_control.md) + 5.1. VCell System [Flow-Control](docs-misc/README_flow_control.md) 6. Server Administration [detailed instructions](docker/swarm/README_admin.md) (.e.g restarting VCell services) -7. [Debugging detailed instructions](README_Debugging.md) (.e.g debug vcell client/server) +7. [Debugging detailed instructions](docs-misc/README_Debugging.md) (.e.g debug vcell client/server) 8. serverconfig.sh file must be customized for your configuration (see vcell/docker/swarm/serverconfig-uch.sh). diff --git a/docker/build/Dockerfile-api-dev b/docker/build/Dockerfile-api-dev index 01fa09b248..ab7dce26ad 100644 --- a/docker/build/Dockerfile-api-dev +++ b/docker/build/Dockerfile-api-dev @@ -1,10 +1,8 @@ FROM eclipse-temurin:17 as jre-build # Create a custom Java runtime -# java.beans.PropertyChangeEvent requires java.desktop -# org.apache.logging.log4j.core.util.DefaultShutdownCallbackRegistry requires java.management (MBeanRegistrationException) RUN $JAVA_HOME/bin/jlink \ - --add-modules java.base,java.instrument,java.logging,java.management,java.desktop,java.naming,java.sql,java.xml,jdk.jdwp.agent,jdk.httpserver \ + --add-modules ALL-MODULE-PATH \ --strip-debug \ --no-man-pages \ --no-header-files \ @@ -12,23 +10,35 @@ RUN $JAVA_HOME/bin/jlink \ --output /javaruntime # Define base image and copy in jlink created minimal Java 17 environment -FROM debian:buster-slim +FROM python:3.9.7-slim ENV JAVA_HOME=/opt/java/openjdk ENV PATH "${JAVA_HOME}/bin:${PATH}" COPY --from=jre-build /javaruntime $JAVA_HOME +# now we have Java 17 and Python 3.9 + RUN apt-get -y update && \ - apt-get install -y curl dnsutils && \ + apt-get install -y --no-install-recommends curl dnsutils && \ mkdir -p /usr/local/app/lib - + +RUN python3 -m pip install poetry && poetry config cache-dir "/poetry/.cache" +ENV PATH="/root/.poetry/bin:/root/.local/bin:$PATH" + WORKDIR /usr/local/app -COPY ./vcell-server/target/vcell-server-0.0.1-SNAPSHOT.jar \ - ./vcell-server/target/maven-jars/*.jar \ - ./vcell-api/target/vcell-api-0.0.1-SNAPSHOT.jar \ +# Copy JAR files +COPY ./vcell-api/target/vcell-api-0.0.1-SNAPSHOT.jar \ ./vcell-api/target/maven-jars/*.jar \ ./lib/ +# Copy and install vcell-cli-utils +COPY ./vcell-cli-utils/ /usr/local/app/python/vcell_cli_utils/ +RUN cd /usr/local/app/python/vcell_cli_utils/ && \ + poetry config cache-dir "/poetry/.cache" --local && \ + chmod 755 poetry.toml && \ + poetry install + +# copy API resources COPY ./vcell-api/docroot ./docroot COPY ./vcell-api/webapp ./webapp COPY ./vcell-api/keystore_macbook.jks . @@ -53,6 +63,7 @@ ENV softwareVersion=SOFTWARE-VERSION-NOT-SET \ ssl_ignoreHostMismatch=true \ ssl_ignoreCertProblems=false \ submit_service_host="submit" \ + workingDir="/usr/local/app" \ userTimezone="-05:00" ENV dbpswdfile=/run/secrets/dbpswd \ @@ -71,6 +82,7 @@ ENTRYPOINT java \ -Dlog4j.configurationFile=/usr/local/app/vcell-api.log4j.xml \ -Dvcell.server.id="${serverid}" \ -Dvcell.installDir=/usr/local/app \ + -Dcli.workingDir="${workingDir}" \ -Dvcell.server.dbConnectURL="${dburl}" \ -Dvcell.server.dbDriverName="${dbdriver}" \ -Dvcell.server.dbUserid="${dbuser}" \ diff --git a/docker/build/Dockerfile-clientgen-dev b/docker/build/Dockerfile-clientgen-dev index 7cd31b7219..d1a0b235dc 100644 --- a/docker/build/Dockerfile-clientgen-dev +++ b/docker/build/Dockerfile-clientgen-dev @@ -1,4 +1,23 @@ -FROM openjdk:17-jdk-slim +FROM eclipse-temurin:17 as jre-build + +# Create a custom Java runtime +RUN $JAVA_HOME/bin/jlink \ + --add-modules java.base,java.instrument,java.logging,java.management,java.desktop,java.naming,java.transaction.xa,java.xml,jdk.jdwp.agent \ + --strip-debug \ + --no-man-pages \ + --no-header-files \ + --compress=2 \ + --output /javaruntime + +# Define base image and copy in jlink created minimal Java 17 environment +FROM debian:buster-slim +ENV JAVA_HOME=/opt/java/openjdk +ENV PATH "${JAVA_HOME}/bin:${PATH}" +COPY --from=jre-build /javaruntime $JAVA_HOME + +RUN mkdir -p /usr/local/app && \ + apt-get -y update && \ + apt-get -y install wget RUN mkdir /installer && cd /installer && \ wget --quiet -O install4j_unix_10_0_4.tar.gz \ diff --git a/docker/build/Dockerfile-data-dev b/docker/build/Dockerfile-data-dev index 294ac9d698..bcb1c0784b 100644 --- a/docker/build/Dockerfile-data-dev +++ b/docker/build/Dockerfile-data-dev @@ -1,62 +1,8 @@ -# VTK and OpenJDK n Alpine Linux -#FROM alpine:3.7 -# Install some Alpine packages -#RUN apk add --no-cache \ -# bash \ -# build-base \ -# cmake \ -# wget \ -# mesa-dev \ -# mesa-osmesa \ -# python2-dev -# Download and extract VTK source, then configure and build VTK -#RUN wget -nv -O- http://www.vtk.org/files/release/7.1/VTK-7.1.0.tar.gz | \ -# tar xz && \ -# cd VTK-7.1.0 && \ -# cmake \ -# -D CMAKE_BUILD_TYPE:STRING=Release \ -# -D CMAKE_INSTALL_PREFIX:STRING=/usr \ -# -D BUILD_DOCUMENTATION:BOOL=OFF \ -# -D BUILD_EXAMPLES:BOOL=OFF \ -# -D BUILD_TESTING:BOOL=OFF \ -# -D BUILD_SHARED_LIBS:BOOL=ON \ -# -D VTK_USE_X:BOOL=OFF \ -# -D VTK_OPENGL_HAS_OSMESA:BOOL=ON \ -# -D OSMESA_LIBRARY=/usr/lib/libOSMesa.so.8 \ -# -D OSMESA_INCLUDE_DIR=/usr/include/GL/ \ -# -D VTK_RENDERING_BACKEND:STRING=OpenGL \ -# -D VTK_Group_MPI:BOOL=OFF \ -# -D VTK_Group_StandAlone:BOOL=OFF \ -# -D VTK_Group_Rendering:BOOL=ON \ -# -D VTK_WRAP_PYTHON=ON \ -# -D VTK_PYTHON_VERSION:STRING=2 \ -# . && \ -# make -j 2 && \ -# make install && \ -# cd .. && rm -rf VTK-7.1.0 -# install thrift python package -#RUN wget https://bootstrap.pypa.io/get-pip.py \ -# && python get-pip.py \ -# && pip install thrift -#RUN apk update && apk upgrade && \ -# apk add openjdk8 && \ -# mkdir /tmp/tmprt && \ -# cd /tmp/tmprt && \ -# apk add zip && \ -# unzip -q /usr/lib/jvm/default-jvm/jre/lib/rt.jar && \ -# apk add zip && \ -# zip -q -r /tmp/rt.zip . && \ -# apk del zip && \ -# cd /tmp && \ -# mv rt.zip /usr/lib/jvm/default-jvm/jre/lib/rt.jar && \ -# rm -rf /tmp/tmprt /var/cache/apk/* bin/jjs bin/keytool bin/orbd bin/pack200 bin/policytool \ -# bin/rmid bin/rmiregistry bin/servertool bin/tnameserv bin/unpack200 - FROM eclipse-temurin:17 as jre-build # Create a custom Java runtime RUN $JAVA_HOME/bin/jlink \ - --add-modules java.base,java.instrument,java.logging,java.management,java.desktop,java.naming,java.sql,java.xml,jdk.jdwp.agent \ + --add-modules ALL-MODULE-PATH \ --strip-debug \ --no-man-pages \ --no-header-files \ @@ -71,9 +17,9 @@ COPY --from=jre-build /javaruntime $JAVA_HOME # now we have Java 17 and Python 3.9 -RUN mkdir -p /usr/local/app && \ - apt-get -y update && \ - apt-get -y install openssh-client screen +RUN apt-get -y update && \ + apt-get -y install openssh-client screen && \ + mkdir -p /usr/local/app RUN python3 -m pip install poetry && poetry config cache-dir "/poetry/.cache" ENV PATH="/root/.poetry/bin:/root/.local/bin:$PATH" @@ -157,5 +103,5 @@ ENTRYPOINT java \ -Dvcell.mongodb.port.internal=${mongodb_port_internal} \ -Dvcell.mongodb.database=${mongodb_database} \ -Dvcelldata.web.server.port=${webDataPort} \ - -cp "./lib/*" cbit.vcell.message.server.data.SimDataServer \ + -cp "./lib/*" cbit.vcell.message.server.data.SimDataServerMain \ "${servertype}" diff --git a/docker/build/Dockerfile-sched-dev b/docker/build/Dockerfile-sched-dev index 454d7efaf3..958f8453b4 100644 --- a/docker/build/Dockerfile-sched-dev +++ b/docker/build/Dockerfile-sched-dev @@ -2,7 +2,7 @@ FROM eclipse-temurin:17 as jre-build # Create a custom Java runtime RUN $JAVA_HOME/bin/jlink \ - --add-modules java.base,java.instrument,java.logging,java.management,java.desktop,java.naming,java.sql,java.transaction.xa,java.xml,jdk.jdwp.agent \ + --add-modules ALL-MODULE-PATH \ --strip-debug \ --no-man-pages \ --no-header-files \ diff --git a/docker/build/Dockerfile-web-dev b/docker/build/Dockerfile-web-dev index 615e9728e0..88c6976f33 100644 --- a/docker/build/Dockerfile-web-dev +++ b/docker/build/Dockerfile-web-dev @@ -2,7 +2,7 @@ FROM eclipse-temurin:17 as jre-build # Create a custom Java runtime RUN $JAVA_HOME/bin/jlink \ - --add-modules java.base,java.instrument,java.logging,java.management,java.desktop,java.naming,java.sql,java.xml,jdk.jdwp.agent,jdk.httpserver \ + --add-modules ALL-MODULE-PATH \ --strip-debug \ --no-man-pages \ --no-header-files \ diff --git a/docker/build/installers/VCell.install4j b/docker/build/installers/VCell.install4j index 326db8204a..4b78fc7135 100644 --- a/docker/build/installers/VCell.install4j +++ b/docker/build/installers/VCell.install4j @@ -120,7 +120,7 @@ - + @@ -156,7 +156,7 @@ - + @@ -186,7 +186,7 @@ - + @@ -217,7 +217,7 @@ - + @@ -244,7 +244,7 @@ - + diff --git a/docker/swarm/README_admin.md b/docker/swarm/README_admin.md index c182c546c8..2baa706de5 100644 --- a/docker/swarm/README_admin.md +++ b/docker/swarm/README_admin.md @@ -8,6 +8,7 @@ sudo docker service update --force --detach=false vcellrel_data sudo docker service update --force --detach=false vcellrel_sched sudo docker service update --force --detach=false vcellrel_submit sudo docker service update --force --detach=false vcellrel_api +sudo docker service update --force --detach=false vcellrel_web (not used) sudo docker service update --force --detach=false vcellrel_opt ### Restart Alpha Site (from development swarm cluster, e.g. vcellapi-beta.cam.uchc.edu or vcell-node3 or vcell-node4) @@ -20,4 +21,5 @@ sudo docker service update --force --detach=false vcellalpha_data sudo docker service update --force --detach=false vcellalpha_sched sudo docker service update --force --detach=false vcellalpha_submit sudo docker service update --force --detach=false vcellalpha_api +sudo docker service update --force --detach=false vcellalpha_web (not used) sudo docker service update --force --detach=false vcellalpha_opt diff --git a/docker/swarm/localconfig_realslurm_oracle.sh b/docker/swarm/localconfig_realslurm_oracle.sh index 1949c0631f..39bc730aff 100755 --- a/docker/swarm/localconfig_realslurm_oracle.sh +++ b/docker/swarm/localconfig_realslurm_oracle.sh @@ -182,13 +182,10 @@ VCELL_SECRETS_DIR=${HOME}/vcellkeys_oracle VCELL_SIMDATADIR_ARCHIVE_EXTERNAL=/share/apps/vcell12/users VCELL_SIMDATADIR_ARCHIVE_INTERNAL=/share/apps/vcell12/users VCELL_SIMDATADIR_ARCHIVE_HOST=/Volumes/vcell-1/users -VCELL_SIMDATADIR_ARCHIVE_HOST_ORIG=/Volumes/vcell-2/users VCELL_SIMDATADIR_EXTERNAL=/share/apps/vcell3/users VCELL_SIMDATADIR_HOST=/Volumes/vcell/users VCELL_SIMDATADIR_SECONDARY_EXTERNAL=/share/apps/vcell3/users VCELL_SIMDATADIR_SECONDARY_HOST=/Volumes/vcell/users -VCELL_SIMDATADIR_SECONDARY_EXTERNAL_ORIG=/share/apps/vcell7/users -VCELL_SIMDATADIR_SECONDARY_HOST_ORIG=/Volumes/vcell-1/users VCELL_SIMDATADIR_PARALLEL_EXTERNAL=/share/apps/vcell3parallel VCELL_SITE_CAMEL=${_site_camel} VCELL_SITE=$VCELL_SITE diff --git a/docker/swarm/localconfig_realslurm_postgres.sh b/docker/swarm/localconfig_realslurm_postgres.sh index 11d1455aaf..3acb164ecb 100755 --- a/docker/swarm/localconfig_realslurm_postgres.sh +++ b/docker/swarm/localconfig_realslurm_postgres.sh @@ -181,11 +181,11 @@ VCELL_REPO_NAMESPACE=$VCELL_REPO_NAMESPACE VCELL_SECRETS_DIR=${HOME}/vcellkeys_postgres VCELL_SIMDATADIR_ARCHIVE_EXTERNAL=/share/apps/vcell12/users VCELL_SIMDATADIR_ARCHIVE_INTERNAL=/share/apps/vcell12/users -VCELL_SIMDATADIR_ARCHIVE_HOST=/Volumes/vcell-2/users +VCELL_SIMDATADIR_ARCHIVE_HOST=/Volumes/vcell-1/users VCELL_SIMDATADIR_EXTERNAL=/share/apps/vcell3/users VCELL_SIMDATADIR_HOST=/Volumes/vcell/users -VCELL_SIMDATADIR_SECONDARY_EXTERNAL=/share/apps/vcell10/users -VCELL_SIMDATADIR_SECONDARY_HOST=/Volumes/vcell-1/users +VCELL_SIMDATADIR_SECONDARY_EXTERNAL=/share/apps/vcell3/users +VCELL_SIMDATADIR_SECONDARY_HOST=/Volumes/vcell/users VCELL_SIMDATADIR_PARALLEL_EXTERNAL=/share/apps/vcell3parallel VCELL_SITE_CAMEL=${_site_camel} VCELL_SITE=$VCELL_SITE diff --git a/pom.xml b/pom.xml index b55a0d5917..b98ebee2e9 100644 --- a/pom.xml +++ b/pom.xml @@ -124,6 +124,7 @@ ${imagej2.version} 1.5.0 + 4.6.3 diff --git a/vcell-admin/pom.xml b/vcell-admin/pom.xml index 564f058d08..bd6e91a4e3 100644 --- a/vcell-admin/pom.xml +++ b/vcell-admin/pom.xml @@ -125,7 +125,7 @@ info.picocli picocli - 4.6.3 + ${picocli.version} diff --git a/vcell-admin/src/main/java/cbit/vcell/math/validation/gui/MathGenerationDebugger.java b/vcell-admin/src/main/java/cbit/vcell/math/validation/gui/MathGenerationDebugger.java index 19d3a69238..f033ed21ed 100644 --- a/vcell-admin/src/main/java/cbit/vcell/math/validation/gui/MathGenerationDebugger.java +++ b/vcell-admin/src/main/java/cbit/vcell/math/validation/gui/MathGenerationDebugger.java @@ -10,32 +10,20 @@ package cbit.vcell.math.validation.gui; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JTextPane; - -import org.vcell.util.document.KeyValue; -import org.vcell.util.document.UserLoginInfo; -import org.vcell.util.gui.DialogUtils; - import cbit.vcell.client.VCellClient; import cbit.vcell.client.server.ClientServerInfo; import cbit.vcell.math.gui.MathDebuggerPanel; import cbit.vcell.mathmodel.MathModel; import cbit.vcell.modeldb.MathVerifier; import cbit.vcell.modeldb.MathVerifier.MathGenerationResults; +import org.vcell.util.document.KeyValue; +import org.vcell.util.document.UserLoginInfo; +import org.vcell.util.gui.DialogUtils; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; public class MathGenerationDebugger extends JPanel { private JTextField simContextTextField; @@ -162,13 +150,14 @@ private void compareMath_4_8(){ DialogUtils.showErrorDialog(this, e.getMessage(), e); } } - + private void showBioModel(){ try { new Thread() { public void run(){ + VCellClient vcellClient = new VCellClient(null, null); ClientServerInfo clientServerInfo = ClientServerInfo.createLocalServerInfo(vcellUserID,new UserLoginInfo.DigestedPassword(vcellUserPassword)); - VCellClient.startClient(mathGenerationResults.bioModelFromDB, clientServerInfo); + vcellClient.startClient(mathGenerationResults.bioModelFromDB, clientServerInfo); } }.start(); diff --git a/vcell-admin/src/main/java/org/vcell/standalone/VCellClientDevMain.java b/vcell-admin/src/main/java/org/vcell/standalone/VCellClientDevMain.java new file mode 100644 index 0000000000..7b18605f80 --- /dev/null +++ b/vcell-admin/src/main/java/org/vcell/standalone/VCellClientDevMain.java @@ -0,0 +1,94 @@ +/* + * Copyright (C) 1999-2011 University of Connecticut Health Center + * + * Licensed under the MIT License (the "License"). + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.opensource.org/licenses/mit-license.php + */ + +package org.vcell.standalone; + +import cbit.vcell.client.VCellClient; +import cbit.vcell.client.VCellLookAndFeel; +import cbit.vcell.client.server.ClientServerInfo; +import cbit.vcell.resource.ErrorUtils; +import cbit.vcell.resource.LibraryLoaderThread; +import cbit.vcell.resource.PropertyLoader; +import com.google.inject.Guice; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.google.inject.Singleton; +import org.apache.commons.lang3.ArrayUtils; +import org.vcell.dependency.server.VCellServerModule; +import org.vcell.util.document.UserLoginInfo; +import org.vcell.util.document.VCDocument; + +import java.io.IOException; + +@Singleton +public class VCellClientDevMain { + + private final VCellClient vCellClient; + + @Inject + public VCellClientDevMain(VCellClient vcellClient) throws IOException { + this.vCellClient = vcellClient; + String user = null; + String password = null; + VCDocument initialDocument = null; + UserLoginInfo.DigestedPassword digestedPassword = null; + if (password != null && password.length() != 0) { + digestedPassword = new UserLoginInfo.DigestedPassword(password); + } + ClientServerInfo csInfo = ClientServerInfo.createLocalServerInfo(user, digestedPassword); + //call in main thread, since it's quick and not necessarily thread safe + VCellLookAndFeel.setVCellLookAndFeel(); + + vcellClient.startClient(initialDocument, csInfo); + } + + public static void main(String[] args) { + try { + ErrorUtils.setDebug(true); + PropertyLoader.loadProperties(ArrayUtils.addAll(REQUIRED_CLIENT_PROPERTIES, REQUIRED_LOCAL_PROPERTIES)); + Injector injector = Guice.createInjector(new VCellServerModule()); + + VCellClientDevMain vcellClientStandalone = injector.getInstance(VCellClientDevMain.class); + + //starting loading libraries + new LibraryLoaderThread(true).start(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + +/** + * array of properties required for correct operation + */ +private static final String REQUIRED_CLIENT_PROPERTIES[] = { + PropertyLoader.installationRoot, + PropertyLoader.vcellSoftwareVersion, +}; + +/** + * array of properties required for correct local operation + */ +private static final String REQUIRED_LOCAL_PROPERTIES[] = { + PropertyLoader.primarySimDataDirInternalProperty, + PropertyLoader.secondarySimDataDirInternalProperty, + PropertyLoader.dbPasswordValue, + PropertyLoader.dbUserid, + PropertyLoader.dbDriverName, + PropertyLoader.dbConnectURL, + PropertyLoader.userTimezone, + PropertyLoader.vcellServerIDProperty, + PropertyLoader.mongodbDatabase, + PropertyLoader.mongodbHostInternal, +// PropertyLoader.mongodbLoggingCollection, + PropertyLoader.mongodbPortInternal + +}; +} diff --git a/vcell-api/src/main/java/org/vcell/rest/VCellApiMain.java b/vcell-api/src/main/java/org/vcell/rest/VCellApiMain.java index 77c4bf7626..316a465bda 100644 --- a/vcell-api/src/main/java/org/vcell/rest/VCellApiMain.java +++ b/vcell-api/src/main/java/org/vcell/rest/VCellApiMain.java @@ -8,6 +8,8 @@ import cbit.vcell.mongodb.VCMongoMessage; import cbit.vcell.mongodb.VCMongoMessage.ServiceName; import cbit.vcell.resource.PropertyLoader; +import com.google.inject.Guice; +import com.google.inject.Injector; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import org.apache.logging.log4j.LogManager; @@ -25,6 +27,7 @@ import org.vcell.db.ConnectionFactory; import org.vcell.db.DatabaseService; import org.vcell.db.KeyFactory; +import org.vcell.dependency.server.VCellServerModule; import org.vcell.rest.admin.AdminService; import org.vcell.rest.events.RestEventService; import org.vcell.rest.health.HealthService; @@ -47,206 +50,207 @@ public class VCellApiMain { private final static Logger lg = LogManager.getLogger(VCellApiMain.class); private final static String TEST_USER = PropertyLoader.TESTACCOUNT_USERID; - /** - * @param args - */ - public static void main(String[] args) { + + private void init(String[] args) throws Exception { + if (args.length != 2) { + lg.info("usage: VCellApiMain javascriptDir port"); + System.exit(1); + } + File javascriptDir = new File(args[0]); + if (!javascriptDir.isDirectory()) { + throw new RuntimeException("javascriptDir '" + args[0] + "' is not a directory"); + } + + String portString = args[1]; + Integer port=null; // was hard-coded at 8080 try { - if (args.length!=2){ - lg.info("usage: VCellApiMain javascriptDir port"); - System.exit(1); + port = Integer.parseInt(portString); + }catch (NumberFormatException e){ + lg.error(e); + throw new RuntimeException("failed to parse port argument '"+portString+"'",e); + } + + lg.trace("connecting to database"); + + lg.trace("oracle factory (next)"); + ConnectionFactory conFactory = DatabaseService.getInstance().createConnectionFactory(); + KeyFactory keyFactory = conFactory.getKeyFactory(); + lg.trace("database impl (next)"); + DatabaseServerImpl databaseServerImpl = new DatabaseServerImpl(conFactory, keyFactory); + lg.trace("local db server (next)"); + LocalAdminDbServer localAdminDbServer = new LocalAdminDbServer(conFactory, keyFactory); + lg.trace("admin db server (next)"); + AdminDBTopLevel adminDbTopLevel = new AdminDBTopLevel(conFactory); + + lg.trace("messaging service (next)"); + VCMessagingService vcMessagingService_int = new VCMessagingServiceActiveMQ(); + VCMessagingDelegate delegate = new VCMessagingDelegate() { + + @Override + public void onTraceEvent(String string) { + if (lg.isTraceEnabled()) lg.trace("onTraceEvent(): "+string); } - File javascriptDir = new File(args[0]); - if (!javascriptDir.isDirectory()){ - throw new RuntimeException("javascriptDir '"+args[0]+"' is not a directory"); + + @Override + public void onRpcRequestSent(VCRpcRequest vcRpcRequest, UserLoginInfo userLoginInfo, VCMessage vcRpcRequestMessage) { + if (lg.isTraceEnabled()) lg.trace("onRpcRequestSent(): "+vcRpcRequest.getMethodName()); } - PropertyLoader.loadProperties(REQUIRED_SERVICE_PROPERTIES); + @Override + public void onRpcRequestProcessed(VCRpcRequest vcRpcRequest, VCMessage rpcVCMessage) { + if (lg.isTraceEnabled()) lg.trace("onRpcRequestProcessed(): "+vcRpcRequest.getMethodName()); + } - lg.debug("properties loaded"); - - String portString = args[1]; - Integer port=null; // was hard-coded at 8080 - try { - port = Integer.parseInt(portString); - }catch (NumberFormatException e){ - lg.error(e); - throw new RuntimeException("failed to parse port argument '"+portString+"'",e); + @Override + public void onMessageSent(VCMessage message, VCDestination desintation) { + if (lg.isTraceEnabled()) lg.trace("onMessageSent(): "+message); + } + + @Override + public void onMessageReceived(VCMessage vcMessage, VCDestination vcDestination) { + if (lg.isTraceEnabled()) lg.trace("onMessageReceived(): "+vcMessage); + } + + @Override + public void onException(Exception e) { + lg.error(e.getMessage(), e); } - - lg.trace("connecting to database"); - - lg.trace("oracle factory (next)"); - ConnectionFactory conFactory = DatabaseService.getInstance().createConnectionFactory(); - KeyFactory keyFactory = conFactory.getKeyFactory(); - lg.trace("database impl (next)"); - DatabaseServerImpl databaseServerImpl = new DatabaseServerImpl(conFactory, keyFactory); - lg.trace("local db server (next)"); - LocalAdminDbServer localAdminDbServer = new LocalAdminDbServer(conFactory, keyFactory); - lg.trace("admin db server (next)"); - AdminDBTopLevel adminDbTopLevel = new AdminDBTopLevel(conFactory); - - lg.trace("messaging service (next)"); - VCMessagingService vcMessagingService_int = new VCMessagingServiceActiveMQ(); - VCMessagingDelegate delegate = new VCMessagingDelegate() { - - @Override - public void onTraceEvent(String string) { - if (lg.isTraceEnabled()) lg.trace("onTraceEvent(): "+string); - } - - @Override - public void onRpcRequestSent(VCRpcRequest vcRpcRequest, UserLoginInfo userLoginInfo, VCMessage vcRpcRequestMessage) { - if (lg.isTraceEnabled()) lg.trace("onRpcRequestSent(): "+vcRpcRequest.getMethodName()); - } - - @Override - public void onRpcRequestProcessed(VCRpcRequest vcRpcRequest, VCMessage rpcVCMessage) { - if (lg.isTraceEnabled()) lg.trace("onRpcRequestProcessed(): "+vcRpcRequest.getMethodName()); - } - - @Override - public void onMessageSent(VCMessage message, VCDestination desintation) { - if (lg.isTraceEnabled()) lg.trace("onMessageSent(): "+message); - } - - @Override - public void onMessageReceived(VCMessage vcMessage, VCDestination vcDestination) { - if (lg.isTraceEnabled()) lg.trace("onMessageReceived(): "+vcMessage); - } - - @Override - public void onException(Exception e) { - lg.error(e.getMessage(), e); - } - }; - String jmshost_int = PropertyLoader.getRequiredProperty(PropertyLoader.jmsIntHostInternal); - int jmsport_int = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.jmsIntPortInternal)); - vcMessagingService_int.setConfiguration(delegate, jmshost_int, jmsport_int); - - lg.trace("rest database service (next)"); - RestDatabaseService restDatabaseService = new RestDatabaseService(databaseServerImpl, localAdminDbServer, vcMessagingService_int); - - lg.trace("rest event service (next)"); - RestEventService restEventService = new RestEventService(vcMessagingService_int); - - lg.trace("use verifier (next)"); - UserService userService = new UserService(adminDbTopLevel); - - lg.trace("mongo (next)"); - VCMongoMessage.enabled=true; - VCMongoMessage.serviceStartup(ServiceName.unknown, port, args); - - lg.info("setting up server configuration"); - - lg.trace("register engine (next)"); - Engine.register(true); - - WadlComponent component = new WadlComponent(); - //Server httpServer = component.getServers().add(Protocol.HTTP, 80); - //Server httpsServer = component.getServers().add(Protocol.HTTPS, 443); - + }; + String jmshost_int = PropertyLoader.getRequiredProperty(PropertyLoader.jmsIntHostInternal); + int jmsport_int = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.jmsIntPortInternal)); + vcMessagingService_int.setConfiguration(delegate, jmshost_int, jmsport_int); + + lg.trace("rest database service (next)"); + RestDatabaseService restDatabaseService = new RestDatabaseService(databaseServerImpl, localAdminDbServer, vcMessagingService_int); + + lg.trace("rest event service (next)"); + RestEventService restEventService = new RestEventService(vcMessagingService_int); + + lg.trace("use verifier (next)"); + UserService userService = new UserService(adminDbTopLevel); + + lg.trace("mongo (next)"); + VCMongoMessage.enabled=true; + VCMongoMessage.serviceStartup(ServiceName.unknown, port, args); + + lg.info("setting up server configuration"); + + lg.trace("register engine (next)"); + Engine.register(true); + + WadlComponent component = new WadlComponent(); + //Server httpServer = component.getServers().add(Protocol.HTTP, 80); + //Server httpsServer = component.getServers().add(Protocol.HTTPS, 443); + // Client httpsClient = component.getClients().add(Protocol.HTTPS); // Client httpClient = component.getClients().add(Protocol.HTTP); - lg.trace("adding FILE protcol"); - @SuppressWarnings("unused") - Client httpClient = component.getClients().add(Protocol.FILE); - lg.trace("adding CLAP protcol"); - @SuppressWarnings("unused") - Client clapClient = component.getClients().add(Protocol.CLAP); - - lg.trace("adding CLAP https"); - File keystorePath = new File(PropertyLoader.getRequiredProperty(PropertyLoader.vcellapiKeystoreFile)); - String keystorePassword = PropertyLoader.getSecretValue(PropertyLoader.vcellapiKeystorePswd, PropertyLoader.vcellapiKeystorePswdFile); - try { - // - // keystorePassword may be encrypted with dbPassword, if it is decypt it. - // - String dbPassword = PropertyLoader.getSecretValue(PropertyLoader.dbPasswordValue, PropertyLoader.dbPasswordFile); - SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); - SecretKey key = kf.generateSecret(new PBEKeySpec(dbPassword.toCharArray())); - Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); - pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(new byte[] {32,11,55,121,01,42,89,11}, 20)); - keystorePassword = new String(pbeCipher.doFinal(DatatypeConverter.parseBase64Binary(keystorePassword))); - }catch (IllegalBlockSizeException e){ - lg.warn("password unhashing didn't work - trying clear text password: "+e.getMessage()); - } - Server httpsServer = component.getServers().add(Protocol.HTTPS,port); - Series parameters = httpsServer.getContext().getParameters(); - parameters.add("keystorePath", keystorePath.toString()); - parameters.add("keystorePassword", keystorePassword); - parameters.add("keystoreType", "JKS"); - parameters.add("keyPassword", keystorePassword); - /** - * last nmap scan to determine supported cipher suites: - * - * $ nmap -sV --script ssl-enum-ciphers -p 8082 155.37.249.214 - * Starting Nmap 7.93 ( https://nmap.org ) at 2023-01-11 22:44 EST - * | ssl-enum-ciphers: - * | TLSv1.2: - * | ciphers: - * | TLS_DHE_RSA_WITH_AES_128_CBC_SHA (dh 2048) - A - * | TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 (dh 2048) - A - * | TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (dh 2048) - A - * | TLS_DHE_RSA_WITH_AES_256_CBC_SHA (dh 2048) - A - * | TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 (dh 2048) - A - * | TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (dh 2048) - A - * | TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A - * | TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (secp256r1) - A - * | TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A - * | TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A - * | TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (secp256r1) - A - * | TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A - * | TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A - * | TLS_RSA_WITH_AES_128_CBC_SHA256 (rsa 2048) - A - * | TLS_RSA_WITH_AES_128_GCM_SHA256 (rsa 2048) - A - * | TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A - * | TLS_RSA_WITH_AES_256_CBC_SHA256 (rsa 2048) - A - * | TLS_RSA_WITH_AES_256_GCM_SHA384 (rsa 2048) - A - * | compressors: - * | NULL - * | cipher preference: client - * |_ least strength: A - * |_http-server-header: Restlet-Framework/2.4.3 - */ - - lg.trace("create config"); - Configuration templateConfiguration = new Configuration(); - templateConfiguration.setObjectWrapper(new DefaultObjectWrapper()); - -// lg.trace("verify python installation"); -// PythonSupport.verifyInstallation(new PythonPackage[] { PythonPackage.COPASI, PythonPackage.LIBSBML, PythonPackage.THRIFT }); -// -// lg.trace("start Optimization Service"); - - RsaJsonWebKey jsonWebKey = JWTUtils.createNewJsonWebKey("k1"); - JWTUtils.setRsaJsonWebKey(jsonWebKey); - - lg.trace("create app"); - boolean bIgnoreHostMismatchForHealthService = true; // HealthService connects via localhost, this will never match host in production cert - boolean bIgnoreCertProblemsForHealthService = PropertyLoader.getBooleanProperty(PropertyLoader.sslIgnoreCertProblems, false); - User testUser = localAdminDbServer.getUser(TEST_USER); - UserInfo testUserInfo = localAdminDbServer.getUserInfo(testUser.getID()); // lookup hashed auth credentials in database. - HealthService healthService = new HealthService(restEventService, "localhost", port, - bIgnoreCertProblemsForHealthService, bIgnoreHostMismatchForHealthService, - testUserInfo.userid, testUserInfo.digestedPassword0); - AdminService adminService = new AdminService(adminDbTopLevel, databaseServerImpl); - RpcService rpcService = new RpcService(vcMessagingService_int); - WadlApplication app = new VCellApiApplication(restDatabaseService, userService, rpcService, restEventService, adminService, templateConfiguration, healthService, javascriptDir); - lg.trace("attach app"); - component.getDefaultHost().attach(app); - - lg.info("component start()"); - lg.trace("start component"); - component.start(); - lg.info("component ended."); - lg.trace("component started"); - - lg.trace("start VCell Health Monitoring service"); - healthService.start(); - - } catch (Exception e) { - lg.error(e.getMessage(), e); + lg.trace("adding FILE protcol"); + @SuppressWarnings("unused") + Client httpClient = component.getClients().add(Protocol.FILE); + lg.trace("adding CLAP protcol"); + @SuppressWarnings("unused") + Client clapClient = component.getClients().add(Protocol.CLAP); + + lg.trace("adding CLAP https"); + File keystorePath = new File(PropertyLoader.getRequiredProperty(PropertyLoader.vcellapiKeystoreFile)); + String keystorePassword = PropertyLoader.getSecretValue(PropertyLoader.vcellapiKeystorePswd, PropertyLoader.vcellapiKeystorePswdFile); + try { + // + // keystorePassword may be encrypted with dbPassword, if it is decypt it. + // + String dbPassword = PropertyLoader.getSecretValue(PropertyLoader.dbPasswordValue, PropertyLoader.dbPasswordFile); + SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); + SecretKey key = kf.generateSecret(new PBEKeySpec(dbPassword.toCharArray())); + Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); + pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(new byte[] {32,11,55,121,01,42,89,11}, 20)); + keystorePassword = new String(pbeCipher.doFinal(DatatypeConverter.parseBase64Binary(keystorePassword))); + }catch (IllegalBlockSizeException e){ + lg.warn("password unhashing didn't work - trying clear text password: "+e.getMessage()); + } + Server httpsServer = component.getServers().add(Protocol.HTTPS,port); + Series parameters = httpsServer.getContext().getParameters(); + parameters.add("keystorePath", keystorePath.toString()); + parameters.add("keystorePassword", keystorePassword); + parameters.add("keystoreType", "JKS"); + parameters.add("keyPassword", keystorePassword); + /** + * last nmap scan to determine supported cipher suites: + * + * $ nmap -sV --script ssl-enum-ciphers -p 8082 155.37.249.214 + * Starting Nmap 7.93 ( https://nmap.org ) at 2023-01-11 22:44 EST + * | ssl-enum-ciphers: + * | TLSv1.2: + * | ciphers: + * | TLS_DHE_RSA_WITH_AES_128_CBC_SHA (dh 2048) - A + * | TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 (dh 2048) - A + * | TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (dh 2048) - A + * | TLS_DHE_RSA_WITH_AES_256_CBC_SHA (dh 2048) - A + * | TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 (dh 2048) - A + * | TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (dh 2048) - A + * | TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A + * | TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (secp256r1) - A + * | TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A + * | TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A + * | TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (secp256r1) - A + * | TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A + * | TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A + * | TLS_RSA_WITH_AES_128_CBC_SHA256 (rsa 2048) - A + * | TLS_RSA_WITH_AES_128_GCM_SHA256 (rsa 2048) - A + * | TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A + * | TLS_RSA_WITH_AES_256_CBC_SHA256 (rsa 2048) - A + * | TLS_RSA_WITH_AES_256_GCM_SHA384 (rsa 2048) - A + * | compressors: + * | NULL + * | cipher preference: client + * |_ least strength: A + * |_http-server-header: Restlet-Framework/2.4.3 + */ + + lg.trace("create config"); + Configuration templateConfiguration = new Configuration(); + templateConfiguration.setObjectWrapper(new DefaultObjectWrapper()); + + RsaJsonWebKey jsonWebKey = JWTUtils.createNewJsonWebKey("k1"); + JWTUtils.setRsaJsonWebKey(jsonWebKey); + + lg.trace("create app"); + boolean bIgnoreHostMismatchForHealthService = true; // HealthService connects via localhost, this will never match host in production cert + boolean bIgnoreCertProblemsForHealthService = PropertyLoader.getBooleanProperty(PropertyLoader.sslIgnoreCertProblems, false); + User testUser = localAdminDbServer.getUser(TEST_USER); + UserInfo testUserInfo = localAdminDbServer.getUserInfo(testUser.getID()); // lookup hashed auth credentials in database. + HealthService healthService = new HealthService(restEventService, "localhost", port, + bIgnoreCertProblemsForHealthService, bIgnoreHostMismatchForHealthService, + testUserInfo.userid, testUserInfo.digestedPassword0); + AdminService adminService = new AdminService(adminDbTopLevel, databaseServerImpl); + RpcService rpcService = new RpcService(vcMessagingService_int); + WadlApplication app = new VCellApiApplication(restDatabaseService, userService, rpcService, restEventService, adminService, templateConfiguration, healthService, javascriptDir); + lg.trace("attach app"); + component.getDefaultHost().attach(app); + + lg.info("component start()"); + lg.trace("start component"); + component.start(); + lg.info("component ended."); + lg.trace("component started"); + + lg.trace("start VCell Health Monitoring service"); + healthService.start(); + } + + public static void main(String[] args) { + try { + + PropertyLoader.loadProperties(REQUIRED_SERVICE_PROPERTIES); + lg.debug("properties loaded"); + + Injector injector = Guice.createInjector(new VCellServerModule()); + + VCellApiMain vCellApiMain = injector.getInstance(VCellApiMain.class); + vCellApiMain.init(args); + + } catch (Throwable e) { + lg.error("VCellApiMain failed", e); + System.exit(1); } } @@ -257,6 +261,7 @@ public void onException(Exception e) { PropertyLoader.dbDriverName, PropertyLoader.dbUserid, PropertyLoader.dbPasswordFile, + PropertyLoader.userTimezone, PropertyLoader.mongodbHostInternal, PropertyLoader.mongodbPortInternal, PropertyLoader.mongodbDatabase, diff --git a/vcell-api/src/main/java/org/vcell/rest/health/HealthService.java b/vcell-api/src/main/java/org/vcell/rest/health/HealthService.java index fe0b114649..406c5619e3 100644 --- a/vcell-api/src/main/java/org/vcell/rest/health/HealthService.java +++ b/vcell-api/src/main/java/org/vcell/rest/health/HealthService.java @@ -207,8 +207,8 @@ private void loginLoop() { long id = loginStartEvent(); try { UserLoginInfo userLoginInfo = new UserLoginInfo(testUserid, testPassword); - RemoteProxyVCellConnectionFactory vcellConnectionFactory = new RemoteProxyVCellConnectionFactory(host, port, userLoginInfo); - VCellConnection vcellConnection = vcellConnectionFactory.createVCellConnection(); + RemoteProxyVCellConnectionFactory vcellConnectionFactory = new RemoteProxyVCellConnectionFactory(host, port); + VCellConnection vcellConnection = vcellConnectionFactory.createVCellConnection(userLoginInfo); VCInfoContainer vcInfoContainer = vcellConnection.getUserMetaDbServer().getVCInfoContainer(); loginSuccess(id); }catch (Throwable e) { @@ -233,8 +233,8 @@ private void runsimLoop() { KeyValue savedBioModelKey = null; VCSimulationIdentifier runningSimId = null; try { - RemoteProxyVCellConnectionFactory vcellConnectionFactory = new RemoteProxyVCellConnectionFactory(host, port, userLoginInfo); - VCellConnection vcellConnection = vcellConnectionFactory.createVCellConnection(); + RemoteProxyVCellConnectionFactory vcellConnectionFactory = new RemoteProxyVCellConnectionFactory(host, port); + VCellConnection vcellConnection = vcellConnectionFactory.createVCellConnection(userLoginInfo); String vcmlString = IOUtils.toString(getClass().getResourceAsStream("/TestTemplate.vcml")); @@ -308,8 +308,8 @@ public void setMessage(String message) { } }finally { // cleanup try { - RemoteProxyVCellConnectionFactory vcellConnectionFactory = new RemoteProxyVCellConnectionFactory(host, port, userLoginInfo); - VCellConnection vcellConnection = vcellConnectionFactory.createVCellConnection(); + RemoteProxyVCellConnectionFactory vcellConnectionFactory = new RemoteProxyVCellConnectionFactory(host, port); + VCellConnection vcellConnection = vcellConnectionFactory.createVCellConnection(userLoginInfo); if (runningSimId!=null) { try { vcellConnection.getSimulationController().stopSimulation(runningSimId); diff --git a/vcell-cli-utils/.gitignore b/vcell-cli-utils/.gitignore index 2831c34aa4..6a950873e8 100644 --- a/vcell-cli-utils/.gitignore +++ b/vcell-cli-utils/.gitignore @@ -112,8 +112,6 @@ venv.bak/ # Mac related ignores .DS_Store -/sample_model/out/ - # Temp directory temp/ tests/results/ diff --git a/vcell-client/pom.xml b/vcell-client/pom.xml index 7236798875..f992a66d28 100644 --- a/vcell-client/pom.xml +++ b/vcell-client/pom.xml @@ -130,6 +130,12 @@ javahelp 2.0.05 + + + info.picocli + picocli + ${picocli.version} + org.eclipse.jetty diff --git a/vcell-client/src/main/java/cbit/vcell/client/ClientRequestManager.java b/vcell-client/src/main/java/cbit/vcell/client/ClientRequestManager.java index cf585802d0..44e29beb6a 100644 --- a/vcell-client/src/main/java/cbit/vcell/client/ClientRequestManager.java +++ b/vcell-client/src/main/java/cbit/vcell/client/ClientRequestManager.java @@ -234,10 +234,13 @@ public class ClientRequestManager implements RequestManager, PropertyChangeListener, ExportListener, VCellMessageEventListener { private VCellClient vcellClient = null; + private final UserRegistrationManager userRegistrationManager; + private boolean bOpening = false; private boolean bExiting = false; - public ClientRequestManager(VCellClient vcellClient) { + public ClientRequestManager(VCellClient vcellClient, UserRegistrationManager userRegistrationManager) { + this.userRegistrationManager = userRegistrationManager; setVcellClient(vcellClient); // listen to connectionStatus events getClientServerManager().addPropertyChangeListener(this); @@ -372,7 +375,7 @@ public void changeGeometry(DocumentWindowManager requester, SimulationContext si } public static void continueAfterMathModelGeomChangeWarning(MathModelWindowManager mathModelWindowManager, - Geometry newGeometry) throws UserCancelException { + Geometry newGeometry) throws UserCancelException { MathModel mathModel = mathModelWindowManager.getMathModel(); if (mathModel != null && mathModel.getMathDescription() != null) { @@ -407,11 +410,11 @@ public static void continueAfterMathModelGeomChangeWarning(MathModelWindowManage "After changing MathModel geometry please note:\n" + " 1. Check Geometry subvolume names match MathModel compartment names." + (bHasSims && bMeshResolutionChange ? "\n" - + " 2. All existing simulations mesh sizes will be reset" - + " because the new Geometry spatial dimension(" + newGeometry.getDimension() + "D)" - + " does not equal the current Geometry spatial dimension(" - + oldGeometry.getDimension() + "D)" + "\n" + meshResolutionChangeSB.toString() - : ""), + + " 2. All existing simulations mesh sizes will be reset" + + " because the new Geometry spatial dimension(" + newGeometry.getDimension() + "D)" + + " does not equal the current Geometry spatial dimension(" + + oldGeometry.getDimension() + "D)" + "\n" + meshResolutionChangeSB.toString() + : ""), new String[] { "Continue", "Cancel" }, "Continue"); if (result != null && result.equals("Continue")) { return; @@ -426,7 +429,7 @@ public static void continueAfterMathModelGeomChangeWarning(MathModelWindowManage enum CloseOption { SAVE_AND_CLOSE, CLOSE_IN_ANY_CASE, CANCEL_CLOSE, } - + public enum CallAction { EXPORT, RUN, SAVE, SAVEASNEW, } @@ -633,7 +636,7 @@ public boolean skipIfCancel(UserCancelException exc) { } private XmlTreeDiff compareDocuments(final VCDocument doc1, final VCDocument doc2, - DiffConfiguration comparisonSetting) throws Exception { + DiffConfiguration comparisonSetting) throws Exception { VCellThreadChecker.checkCpuIntensiveInvocation(); @@ -647,21 +650,21 @@ private XmlTreeDiff compareDocuments(final VCDocument doc1, final VCDocument doc String doc1XML = null; String doc2XML = null; switch (doc1.getDocumentType()) { - case BIOMODEL_DOC: { - doc1XML = XmlHelper.bioModelToXML((BioModel) doc1); - doc2XML = XmlHelper.bioModelToXML((BioModel) doc2); - break; - } - case MATHMODEL_DOC: { - doc1XML = XmlHelper.mathModelToXML((MathModel) doc1); - doc2XML = XmlHelper.mathModelToXML((MathModel) doc2); - break; - } - case GEOMETRY_DOC: { - doc1XML = XmlHelper.geometryToXML((Geometry) doc1); - doc2XML = XmlHelper.geometryToXML((Geometry) doc2); - break; - } + case BIOMODEL_DOC: { + doc1XML = XmlHelper.bioModelToXML((BioModel) doc1); + doc2XML = XmlHelper.bioModelToXML((BioModel) doc2); + break; + } + case MATHMODEL_DOC: { + doc1XML = XmlHelper.mathModelToXML((MathModel) doc1); + doc2XML = XmlHelper.mathModelToXML((MathModel) doc2); + break; + } + case GEOMETRY_DOC: { + doc1XML = XmlHelper.geometryToXML((Geometry) doc1); + doc2XML = XmlHelper.geometryToXML((Geometry) doc2); + break; + } } final XmlTreeDiff diffTree = XmlHelper.compareMerge(doc1XML, doc2XML, comparisonSetting, true); return diffTree; @@ -701,21 +704,21 @@ public XmlTreeDiff compareWithSaved(VCDocument document) { } // make the info and get saved version switch (document.getDocumentType()) { - case BIOMODEL_DOC: { - BioModel bioModel = (BioModel) document; - savedVersion = getDocumentManager().getBioModel(bioModel.getVersion().getVersionKey()); - break; - } - case MATHMODEL_DOC: { - MathModel mathModel = (MathModel) document; - savedVersion = getDocumentManager().getMathModel(mathModel.getVersion().getVersionKey()); - break; - } - case GEOMETRY_DOC: { - Geometry geometry = (Geometry) document; - savedVersion = getDocumentManager().getGeometry(geometry.getKey()); - break; - } + case BIOMODEL_DOC: { + BioModel bioModel = (BioModel) document; + savedVersion = getDocumentManager().getBioModel(bioModel.getVersion().getVersionKey()); + break; + } + case MATHMODEL_DOC: { + MathModel mathModel = (MathModel) document; + savedVersion = getDocumentManager().getMathModel(mathModel.getVersion().getVersionKey()); + break; + } + case GEOMETRY_DOC: { + Geometry geometry = (Geometry) document; + savedVersion = getDocumentManager().getGeometry(geometry.getKey()); + break; + } } return compareDocuments(savedVersion, document, DiffConfiguration.COMPARE_DOCS_SAVED); } catch (Exception e) { @@ -750,7 +753,7 @@ public XmlTreeDiff compareApplications(BioModel bioModel, String appName1, Strin } public void connectAs(final String user, final DigestedPassword digestedPassword, - final TopLevelWindowManager requester) { + final TopLevelWindowManager requester) { JDialog dialog = new JDialog(); dialog.setAlwaysOnTop(true); int confirm = JOptionPane.showOptionDialog(dialog, UserMessage.warn_changeUser.getMessage(null), @@ -848,16 +851,16 @@ VCDocument createDefaultDocument(VCDocumentType docType) { VCDocument defaultDocument = null; try { switch (docType) { - case BIOMODEL_DOC: { - // blank - return createDefaultBioModelDocument(null); - } - case MATHMODEL_DOC: { - return createDefaultMathModelDocument(); - } - default: { - throw new RuntimeException("default document can only be BioModel or MathModel"); - } + case BIOMODEL_DOC: { + // blank + return createDefaultBioModelDocument(null); + } + case MATHMODEL_DOC: { + return createDefaultMathModelDocument(); + } + default: { + throw new RuntimeException("default document can only be BioModel or MathModel"); + } } } catch (Exception e) { e.printStackTrace(System.out); @@ -925,7 +928,7 @@ private MathModel createMathModel(String name, Geometry geometry) { } public void createMathModelFromApplication(final BioModelWindowManager requester, final String name, - final SimulationContext simContext) { + final SimulationContext simContext) { if (simContext == null) { PopupGenerator.showErrorDialog(requester, "Selected Application is null, cannot generate corresponding math model"); @@ -933,10 +936,10 @@ public void createMathModelFromApplication(final BioModelWindowManager requester } switch (simContext.getApplicationType()) { - case NETWORK_STOCHASTIC: - break; - case RULE_BASED_STOCHASTIC: - case NETWORK_DETERMINISTIC: + case NETWORK_STOCHASTIC: + break; + case RULE_BASED_STOCHASTIC: + case NETWORK_DETERMINISTIC: } AsynchClientTask task1 = new AsynchClientTask("Creating MathModel from BioModel Application", @@ -991,7 +994,7 @@ public void run(Hashtable hashTable) throws Exception { } public void createBioModelFromApplication(final BioModelWindowManager requester, final String name, - final SimulationContext simContext) { + final SimulationContext simContext) { if (simContext == null) { PopupGenerator.showErrorDialog(requester, "Selected Application is null, cannot generate corresponding bio model"); @@ -1050,7 +1053,7 @@ public void run(Hashtable hashTable) throws Exception { } public void createRuleBasedBioModelFromApplication(final BioModelWindowManager requester, final String name, - final SimulationContext simContext) { + final SimulationContext simContext) { if (simContext == null) { PopupGenerator.showErrorDialog(requester, "Selected Application is null, cannot generate corresponding bio model"); @@ -1121,21 +1124,21 @@ public void run(Hashtable hashTable) throws Exception { // }; // ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(), new AsynchClientTask[]{task1, task2}, false); //} - private BioModel createDefaultBioModelDocument(BngUnitSystem bngUnitSystem) throws Exception { - BioModel bioModel = new BioModel(null); - bioModel.setName("BioModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1)); - - Model model; - if (bngUnitSystem == null) { - model = new Model("model"); - } else { - model = new Model("model", bngUnitSystem.createModelUnitSystem()); - } - bioModel.setModel(model); - - model.createFeature(); - return bioModel; +private BioModel createDefaultBioModelDocument(BngUnitSystem bngUnitSystem) throws Exception { + BioModel bioModel = new BioModel(null); + bioModel.setName("BioModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1)); + + Model model; + if (bngUnitSystem == null) { + model = new Model("model"); + } else { + model = new Model("model", bngUnitSystem.createModelUnitSystem()); } + bioModel.setModel(model); + + model.createFeature(); + return bioModel; +} private MathModel createDefaultMathModelDocument() throws Exception { Geometry geometry = new Geometry("Untitled", 0); @@ -1150,7 +1153,7 @@ public VCDocumentInfo selectDocumentFromType(VCDocumentType documentType, TopLev } public Geometry getGeometryFromDocumentSelection(Component parentComponent, VCDocumentInfo vcDocumentInfo, - boolean bClearVersion) throws Exception, UserCancelException { + boolean bClearVersion) throws Exception, UserCancelException { Geometry geom = null; if (vcDocumentInfo.getVersionType() .equals(VersionableType.BioModelMetaData)/* documentType == VCDocument.BIOMODEL_DOC */) { @@ -1243,7 +1246,7 @@ public static boolean isImportGeometryType(DocumentCreationInfo documentCreation || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE // || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ || // documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER - ; + ; } private static void throwImportWholeDirectoryException(File invalidFile, String extraInfo) throws Exception { @@ -1396,29 +1399,29 @@ private enum NRRDENCODING { public static AsynchClientTask getParseImageTask(final Component requesterComp,final VCDocument.DocumentCreationInfo documentCreationInfo,final MDIManager mdiManager) { AsynchClientTask parseImageTask = new AsynchClientTask("read and parse image file",AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { - @Override - public void run(final Hashtable hashTable) throws Exception { - + @Override + public void run(final Hashtable hashTable) throws Exception { + final Component guiParent = (Component) hashTable.get(ClientRequestManager.GUI_PARENT); try { FieldDataFileOperationSpec fdfos = null; - // if(documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ){ - // hashTable.put("imageFile",ImageJHelper.vcellWantImage(getClientTaskStatusSupport(),"Image for new VCell geometry")); - // } - // if(documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER){ - // hashTable.put("imageFile",ImageJHelper.vcellWantSurface(getClientTaskStatusSupport(),"Image for new VCell geometry")); - // } + // if(documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ){ + // hashTable.put("imageFile",ImageJHelper.vcellWantImage(getClientTaskStatusSupport(),"Image for new VCell geometry")); + // } + // if(documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER){ + // hashTable.put("imageFile",ImageJHelper.vcellWantSurface(getClientTaskStatusSupport(),"Image for new VCell geometry")); + // } if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE - // || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ || - // documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER + // || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ || + // documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER ) { - + File imageFile = (File) hashTable.get(IMAGE_FILE); if (imageFile == null) { throw new Exception("No file selected"); } if (ExtensionFilter.isMatchingExtension(imageFile, ".nrrd")) { - + DataInputStream dis = null; try { dis = new DataInputStream(new BufferedInputStream(new FileInputStream(imageFile))); @@ -1440,7 +1443,7 @@ public void run(final Hashtable hashTable) throws Exception { } StringTokenizer stringTokenizer = new StringTokenizer(line, ": "); String headerParam = stringTokenizer.nextToken(); - // System.out.println(headerParam); + // System.out.println(headerParam); if (headerParam.equals("sizes")) { if (dimension != -1) { xsize = Integer.parseInt(stringTokenizer.nextToken()); @@ -1535,7 +1538,7 @@ public void run(final Hashtable hashTable) throws Exception { } else { throw new Exception("Unexpected data type=" + type.toString()); } - + minValue = Math.min(minValue, data[i]); maxValue = Math.max(maxValue, data[i]); } @@ -1544,7 +1547,7 @@ public void run(final Hashtable hashTable) throws Exception { getClientTaskStatusSupport() .setMessage("Scaling " + encoding + " " + type + " NRRD data."); } - + short[] dataToSegment = new short[data.length]; double scaleShort = Math.pow(2, Short.SIZE) - 1; for (int i = 0; i < data.length; i++) { @@ -1603,7 +1606,7 @@ public boolean accept(File pathname) { } break; } - + } hashTable.put(IMPORT_SOURCE_NAME, "Directory: " + imageFile.getAbsolutePath()); origImageSizeInfo = imageDatasetReader @@ -1656,7 +1659,7 @@ public boolean accept(File pathname) { fdfos.extent = mesh.getExtent(); fdfos.isize = meshISize; fdfos.shortSpecData = new short[][][] { { dataToSegment } }; - + } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH) { ISize isize = getISizeFromUser(guiParent, new ISize(256, 256, 8), "Enter # of pixels for x,y,z (e.g. 3D{256,256,8}, 2D{256,256,1}, 1D{256,1,1})"); @@ -1665,10 +1668,10 @@ public boolean accept(File pathname) { fdfos.extent = new Extent(1, 1, 1); fdfos.isize = isize; hashTable.put(IMPORT_SOURCE_NAME, "Scratch: New Geometry"); - // final int SCRATCH_SIZE_LIMIT = 512*512*20; - // if(isize.getXYZ() > (SCRATCH_SIZE_LIMIT)){ - // throw new Exception("Total pixels (x*y*z) cannot be >"+SCRATCH_SIZE_LIMIT+"."); - // } + // final int SCRATCH_SIZE_LIMIT = 512*512*20; + // if(isize.getXYZ() > (SCRATCH_SIZE_LIMIT)){ + // throw new Exception("Total pixels (x*y*z) cannot be >"+SCRATCH_SIZE_LIMIT+"."); + // } } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC) { if (hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE) != null) { Geometry workspaceGeom = (Geometry) hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE); @@ -1749,7 +1752,7 @@ public void run(Hashtable hashTable) throws Exception { }; return selectImageFileTask; } - + public static AsynchClientTask getImportFileImageTask(final VCDocument.DocumentCreationInfo documentCreationInfo) { AsynchClientTask importFileImageTask = new AsynchClientTask("Importing Image from File...",AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { @Override @@ -1839,7 +1842,7 @@ public int compare(File o1, File o2) { }; return importFileImageTask; } - + public static AsynchClientTask getResizeImageTask(final VCDocument.DocumentCreationInfo documentCreationInfo) { AsynchClientTask resizeImageTask = new AsynchClientTask("Resizing Image...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { @@ -1857,7 +1860,7 @@ public void run(Hashtable hashTable) throws Exception { }; return resizeImageTask; } - + private static void resize0(Hashtable hashTable/*ImageSizeInfo sourceSize,ImageSizeInfo newSize*/) { // OrigOrigin = new Origin // CartesianMesh origMesh = CartesianMesh.createSimpleCartesianMesh(orig, extent, size, regionImage); @@ -1889,11 +1892,11 @@ private static void resize0(Hashtable hashTable/*ImageSizeInfo sourceSize,ImageS } double[] newData = null; if(origMesh.getSizeY() == 1 && origMesh.getSizeZ() == 1){ - newData = MathTestingUtilities.resample1DSpatialSimple(origData, origMesh, resampleMesh); + newData = MathTestingUtilities.resample1DSpatialSimple(origData, origMesh, resampleMesh); }else if(origMesh.getSizeZ() == 1){ - newData = MathTestingUtilities.resample2DSpatialSimple(origData, origMesh, resampleMesh); + newData = MathTestingUtilities.resample2DSpatialSimple(origData, origMesh, resampleMesh); }else{ - newData = MathTestingUtilities.resample3DSpatialSimple(origData, origMesh, resampleMesh); + newData = MathTestingUtilities.resample3DSpatialSimple(origData, origMesh, resampleMesh); } short[][][] newShort = new short[1][1][resampleMesh.getISize().getXYZ()]; for(int i=0;i hashTable) throws Exception { } } }; - + AsynchClientTask importFileImageTask = getImportFileImageTask(documentCreationInfo); - + AsynchClientTask resizeImageTask = getResizeImageTask(documentCreationInfo); - + AsynchClientTask finishTask = new AsynchClientTask("Finishing...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { @Override @@ -2087,7 +2090,7 @@ public static ISize getISizeFromUser(Component guiParent, ISize initISize, Strin } public static ImageSizeInfo queryImageResize(final Component requester, final ImageSizeInfo origImageSizeInfo, - boolean bFullMode) { + boolean bFullMode) { ImageResizePanel imageResizePanel = new ImageResizePanel(); imageResizePanel.init(origImageSizeInfo, bFullMode); imageResizePanel.setPreferredSize(new Dimension(400, 200)); @@ -2116,7 +2119,7 @@ private static void resizeImage(FieldDataFileOperationSpec fdfos, ISize newImage double scaleFactor = (double) newImagesISize.getX() / (double) fdfos.isize.getX(); if (xsize != fdfos.isize.getX() || ysize != fdfos.isize.getY()) { int numChannels = fdfos.shortSpecData[0].length;// this normally contains different variables but is - // used for channels here + // used for channels here // resize each z section to xsize,ysize AffineTransform scaleAffineTransform = AffineTransform.getScaleInstance(scaleFactor, scaleFactor); AffineTransformOp scaleAffineTransformOp = new AffineTransformOp(scaleAffineTransform, @@ -2146,199 +2149,199 @@ private static void resizeImage(FieldDataFileOperationSpec fdfos, ISize newImage } public AsynchClientTask[] createNewDocument(final TopLevelWindowManager requester, - final VCDocument.DocumentCreationInfo documentCreationInfo) {// throws UserCancelException, Exception { + final VCDocument.DocumentCreationInfo documentCreationInfo) {// throws UserCancelException, Exception { /* asynchronous and not blocking any window */ AsynchClientTask[] taskArray = null; final int createOption = documentCreationInfo.getOption(); switch (documentCreationInfo.getDocumentType()) { - case BIOMODEL_DOC: { - AsynchClientTask task1 = new AsynchClientTask("creating biomodel", - AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { - @Override - public void run(Hashtable hashTable) throws Exception { - BioModel bioModel = createDefaultBioModelDocument(null); - hashTable.put("doc", bioModel); - } - }; - taskArray = new AsynchClientTask[] { task1 }; - break; - } - case MATHMODEL_DOC: { - if ((createOption == VCDocument.MATH_OPTION_NONSPATIAL) - || (createOption == VCDocument.MATH_OPTION_SPATIAL_EXISTS)) { - AsynchClientTask task2 = new AsynchClientTask("creating mathmodel", + case BIOMODEL_DOC: { + AsynchClientTask task1 = new AsynchClientTask("creating biomodel", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { @Override public void run(Hashtable hashTable) throws Exception { - Geometry geometry = null; - if (createOption == VCDocument.MATH_OPTION_NONSPATIAL) { - geometry = new Geometry("Untitled", 0); - } else { - geometry = (Geometry) hashTable.get(GEOMETRY_KEY); - } - MathModel mathModel = createMathModel("Untitled", geometry); - mathModel.setName("MathModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1)); - hashTable.put("doc", mathModel); + BioModel bioModel = createDefaultBioModelDocument(null); + hashTable.put("doc", bioModel); } }; - if (createOption == VCDocument.MATH_OPTION_SPATIAL_EXISTS) { - AsynchClientTask task1 = createSelectDocTask(requester); - AsynchClientTask task1b = createSelectLoadGeomTask(requester); - taskArray = new AsynchClientTask[] { task1, task1b, task2 }; - } else { - taskArray = new AsynchClientTask[] { task2 }; - } + taskArray = new AsynchClientTask[] { task1 }; break; - } else if (createOption == VCDocument.MATH_OPTION_FROMBIOMODELAPP) { - - AsynchClientTask task1 = new AsynchClientTask("select biomodel application", - AsynchClientTask.TASKTYPE_SWING_BLOCKING) { - @Override - public void run(Hashtable hashTable) throws Exception { - // spatial or non-spatial - BioModelInfo bioModelInfo = (BioModelInfo) DialogUtils.getDBTreePanelSelection( - requester.getComponent(), - getMdiManager().getDatabaseWindowManager().getBioModelDbTreePanel(), "Open", - "Select BioModel"); - if (bioModelInfo != null) { // may throw UserCancelException - hashTable.put("bioModelInfo", bioModelInfo); - } - } - }; - AsynchClientTask task2 = new AsynchClientTask("find sim contexts in biomodel application", - AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { - @Override - public void run(Hashtable hashTable) throws Exception { - // spatial or non-spatial - // Get the simContexts in the corresponding BioModel - BioModelInfo bioModelInfo = (BioModelInfo) hashTable.get("bioModelInfo"); - SimulationContext[] simContexts = getDocumentManager().getBioModel(bioModelInfo) - .getSimulationContexts(); - if (simContexts != null) { // may throw UserCancelException - hashTable.put("simContexts", simContexts); + } + case MATHMODEL_DOC: { + if ((createOption == VCDocument.MATH_OPTION_NONSPATIAL) + || (createOption == VCDocument.MATH_OPTION_SPATIAL_EXISTS)) { + AsynchClientTask task2 = new AsynchClientTask("creating mathmodel", + AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { + @Override + public void run(Hashtable hashTable) throws Exception { + Geometry geometry = null; + if (createOption == VCDocument.MATH_OPTION_NONSPATIAL) { + geometry = new Geometry("Untitled", 0); + } else { + geometry = (Geometry) hashTable.get(GEOMETRY_KEY); + } + MathModel mathModel = createMathModel("Untitled", geometry); + mathModel.setName("MathModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1)); + hashTable.put("doc", mathModel); } + }; + if (createOption == VCDocument.MATH_OPTION_SPATIAL_EXISTS) { + AsynchClientTask task1 = createSelectDocTask(requester); + AsynchClientTask task1b = createSelectLoadGeomTask(requester); + taskArray = new AsynchClientTask[] { task1, task1b, task2 }; + } else { + taskArray = new AsynchClientTask[] { task2 }; } - }; - AsynchClientTask task3 = new AsynchClientTask("create math model from biomodel application", - AsynchClientTask.TASKTYPE_SWING_BLOCKING) { - @Override - public void run(Hashtable hashTable) throws Exception { - SimulationContext[] simContexts = (SimulationContext[]) hashTable.get("simContexts"); - String[] simContextNames = new String[simContexts.length]; + break; + } else if (createOption == VCDocument.MATH_OPTION_FROMBIOMODELAPP) { - if (simContextNames.length == 0) { - throw new RuntimeException("no application is available"); - } else { - for (int i = 0; i < simContexts.length; i++) { - simContextNames[i] = simContexts[i].getName(); + AsynchClientTask task1 = new AsynchClientTask("select biomodel application", + AsynchClientTask.TASKTYPE_SWING_BLOCKING) { + @Override + public void run(Hashtable hashTable) throws Exception { + // spatial or non-spatial + BioModelInfo bioModelInfo = (BioModelInfo) DialogUtils.getDBTreePanelSelection( + requester.getComponent(), + getMdiManager().getDatabaseWindowManager().getBioModelDbTreePanel(), "Open", + "Select BioModel"); + if (bioModelInfo != null) { // may throw UserCancelException + hashTable.put("bioModelInfo", bioModelInfo); } - Component component = requester.getComponent(); - // Get the simContext names, so that user can choose which simContext math to - // import - String simContextChoice = (String) PopupGenerator.showListDialog(component, simContextNames, - "Please select Application"); - if (simContextChoice == null) { - throw UserCancelException.CANCEL_DB_SELECTION; + } + }; + AsynchClientTask task2 = new AsynchClientTask("find sim contexts in biomodel application", + AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { + @Override + public void run(Hashtable hashTable) throws Exception { + // spatial or non-spatial + // Get the simContexts in the corresponding BioModel + BioModelInfo bioModelInfo = (BioModelInfo) hashTable.get("bioModelInfo"); + SimulationContext[] simContexts = getDocumentManager().getBioModel(bioModelInfo) + .getSimulationContexts(); + if (simContexts != null) { // may throw UserCancelException + hashTable.put("simContexts", simContexts); } - SimulationContext chosenSimContext = null; - for (int i = 0; i < simContexts.length; i++) { - if (simContexts[i].getName().equals(simContextChoice)) { - chosenSimContext = simContexts[i]; - break; + } + }; + AsynchClientTask task3 = new AsynchClientTask("create math model from biomodel application", + AsynchClientTask.TASKTYPE_SWING_BLOCKING) { + @Override + public void run(Hashtable hashTable) throws Exception { + SimulationContext[] simContexts = (SimulationContext[]) hashTable.get("simContexts"); + String[] simContextNames = new String[simContexts.length]; + + if (simContextNames.length == 0) { + throw new RuntimeException("no application is available"); + } else { + for (int i = 0; i < simContexts.length; i++) { + simContextNames[i] = simContexts[i].getName(); + } + Component component = requester.getComponent(); + // Get the simContext names, so that user can choose which simContext math to + // import + String simContextChoice = (String) PopupGenerator.showListDialog(component, simContextNames, + "Please select Application"); + if (simContextChoice == null) { + throw UserCancelException.CANCEL_DB_SELECTION; } + SimulationContext chosenSimContext = null; + for (int i = 0; i < simContexts.length; i++) { + if (simContexts[i].getName().equals(simContextChoice)) { + chosenSimContext = simContexts[i]; + break; + } + } + Objects.requireNonNull(chosenSimContext); + + BioModelInfo bioModelInfo = (BioModelInfo) hashTable.get("bioModelInfo"); + // Get corresponding mathDesc to create new mathModel and return. + String newName = bioModelInfo.getVersion().getName() + "_" + chosenSimContext.getName(); + MathDescription bioMathDesc = chosenSimContext.getMathDescription(); + MathDescription newMathDesc = null; + newMathDesc = new MathDescription(newName + "_" + (new Random()).nextInt()); + + newMathDesc.setGeometry(bioMathDesc.getGeometry()); + newMathDesc.read_database(new CommentStringTokenizer(bioMathDesc.getVCML_database())); + newMathDesc.isValid(); + + MathModel newMathModel = new MathModel(null); + newMathModel.setName(newName); + newMathModel.setMathDescription(newMathDesc); + hashTable.put("doc", newMathModel); } - Objects.requireNonNull(chosenSimContext); - - BioModelInfo bioModelInfo = (BioModelInfo) hashTable.get("bioModelInfo"); - // Get corresponding mathDesc to create new mathModel and return. - String newName = bioModelInfo.getVersion().getName() + "_" + chosenSimContext.getName(); - MathDescription bioMathDesc = chosenSimContext.getMathDescription(); - MathDescription newMathDesc = null; - newMathDesc = new MathDescription(newName + "_" + (new Random()).nextInt()); - - newMathDesc.setGeometry(bioMathDesc.getGeometry()); - newMathDesc.read_database(new CommentStringTokenizer(bioMathDesc.getVCML_database())); - newMathDesc.isValid(); - - MathModel newMathModel = new MathModel(null); - newMathModel.setName(newName); - newMathModel.setMathDescription(newMathDesc); - hashTable.put("doc", newMathModel); } - } - }; - taskArray = new AsynchClientTask[] { task1, task2, task3 }; - break; - } else { - throw new RuntimeException( - "Unknown MathModel Document creation option value=" + documentCreationInfo.getOption()); - } - } - case GEOMETRY_DOC: { - if (createOption == VCDocument.GEOM_OPTION_1D || createOption == VCDocument.GEOM_OPTION_2D - || createOption == VCDocument.GEOM_OPTION_3D) { - // analytic - AsynchClientTask task1 = new AsynchClientTask("creating analytic geometry", - AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { - @Override - public void run(Hashtable hashTable) throws Exception { - Geometry geometry = new Geometry( - "Geometry" + (getMdiManager().getNumCreatedDocumentWindows() + 1), - documentCreationInfo.getOption()); - geometry.getGeometrySpec() - .addSubVolume(new AnalyticSubVolume("subdomain0", new Expression(1.0))); - geometry.precomputeAll(new GeometryThumbnailImageFactoryAWT()); - hashTable.put("doc", geometry); - } - }; - taskArray = new AsynchClientTask[] { task1 }; - break; + }; + taskArray = new AsynchClientTask[] { task1, task2, task3 }; + break; + } else { + throw new RuntimeException( + "Unknown MathModel Document creation option value=" + documentCreationInfo.getOption()); + } } - if (createOption == VCDocument.GEOM_OPTION_CSGEOMETRY_3D) { - // constructed solid geometry - AsynchClientTask task1 = new AsynchClientTask("creating constructed solid geometry", - AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { - @Override - public void run(Hashtable hashTable) throws Exception { - Geometry geometry = new Geometry( - "Geometry" + (getMdiManager().getNumCreatedDocumentWindows() + 1), 3); - Extent extent = geometry.getExtent(); - if (extent != null) { - // create a CSGPrimitive of type cube and scale it to the 'extent' components. - // Use this as the default or background CSGObject (subdomain). - // This can be considered as the equivalent of subdomain (with expression) 1.0 - // for analyticSubvolume. - // basic cube - CSGPrimitive cube = new CSGPrimitive("cube", CSGPrimitive.PrimitiveType.CUBE); - // scaled cube - double x = extent.getX(); - double y = extent.getY(); - double z = extent.getZ(); - CSGScale scaledCube = new CSGScale("scale", new Vect3d(x / 2.0, y / 2.0, z / 2.0)); - scaledCube.setChild(cube); - // translated scaled cube - CSGTranslation translatedScaledCube = new CSGTranslation("translation", - new Vect3d(x / 2, y / 2, z / 2)); - translatedScaledCube.setChild(scaledCube); - CSGObject csgObject = new CSGObject(null, "subdomain0", 0); - csgObject.setRoot(translatedScaledCube); - geometry.getGeometrySpec().addSubVolume(csgObject, false); + case GEOMETRY_DOC: { + if (createOption == VCDocument.GEOM_OPTION_1D || createOption == VCDocument.GEOM_OPTION_2D + || createOption == VCDocument.GEOM_OPTION_3D) { + // analytic + AsynchClientTask task1 = new AsynchClientTask("creating analytic geometry", + AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { + @Override + public void run(Hashtable hashTable) throws Exception { + Geometry geometry = new Geometry( + "Geometry" + (getMdiManager().getNumCreatedDocumentWindows() + 1), + documentCreationInfo.getOption()); + geometry.getGeometrySpec() + .addSubVolume(new AnalyticSubVolume("subdomain0", new Expression(1.0))); geometry.precomputeAll(new GeometryThumbnailImageFactoryAWT()); hashTable.put("doc", geometry); } - } - }; - taskArray = new AsynchClientTask[] { task1 }; - break; - } else { - throw new RuntimeException( - "Unknown Geometry Document creation option value=" + documentCreationInfo.getOption()); + }; + taskArray = new AsynchClientTask[] { task1 }; + break; + } + if (createOption == VCDocument.GEOM_OPTION_CSGEOMETRY_3D) { + // constructed solid geometry + AsynchClientTask task1 = new AsynchClientTask("creating constructed solid geometry", + AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { + @Override + public void run(Hashtable hashTable) throws Exception { + Geometry geometry = new Geometry( + "Geometry" + (getMdiManager().getNumCreatedDocumentWindows() + 1), 3); + Extent extent = geometry.getExtent(); + if (extent != null) { + // create a CSGPrimitive of type cube and scale it to the 'extent' components. + // Use this as the default or background CSGObject (subdomain). + // This can be considered as the equivalent of subdomain (with expression) 1.0 + // for analyticSubvolume. + // basic cube + CSGPrimitive cube = new CSGPrimitive("cube", CSGPrimitive.PrimitiveType.CUBE); + // scaled cube + double x = extent.getX(); + double y = extent.getY(); + double z = extent.getZ(); + CSGScale scaledCube = new CSGScale("scale", new Vect3d(x / 2.0, y / 2.0, z / 2.0)); + scaledCube.setChild(cube); + // translated scaled cube + CSGTranslation translatedScaledCube = new CSGTranslation("translation", + new Vect3d(x / 2, y / 2, z / 2)); + translatedScaledCube.setChild(scaledCube); + CSGObject csgObject = new CSGObject(null, "subdomain0", 0); + csgObject.setRoot(translatedScaledCube); + geometry.getGeometrySpec().addSubVolume(csgObject, false); + geometry.precomputeAll(new GeometryThumbnailImageFactoryAWT()); + hashTable.put("doc", geometry); + } + } + }; + taskArray = new AsynchClientTask[] { task1 }; + break; + } else { + throw new RuntimeException( + "Unknown Geometry Document creation option value=" + documentCreationInfo.getOption()); + } + } + default: { + throw new RuntimeException("Unknown default document type: " + documentCreationInfo.getDocumentType()); } - } - default: { - throw new RuntimeException("Unknown default document type: " + documentCreationInfo.getDocumentType()); - } } return taskArray; } @@ -2346,7 +2349,7 @@ public void run(Hashtable hashTable) throws Exception { private static final int MAX_NUMBER_OF_COLORS_IMPORTED_FILE = 256; public static VCImage createVCImageFromUnsignedShorts(short[] dataToSegment, Extent extent, ISize isize, - BitSet uniquePixelBS) throws Exception { + BitSet uniquePixelBS) throws Exception { // auto segment int minVal = dataToSegment[0] & 0x0000FFFF; @@ -2390,7 +2393,7 @@ public static VCImage createVCImageFromUnsignedShorts(short[] dataToSegment, Ext } public void curateDocument(final VCDocumentInfo documentInfo, final int curateType, - final TopLevelWindowManager requester) { + final TopLevelWindowManager requester) { if (documentInfo != null) { // see if we have this open @@ -2408,8 +2411,8 @@ public void curateDocument(final VCDocumentInfo documentInfo, final int curateTy + CurateSpec.CURATE_TYPE_STATES[curateType] + " versions of documents cannot be deleted without VCELL administrative assistance.\n" + (curateType == CurateSpec.PUBLISH ? CurateSpec.CURATE_TYPE_STATES[curateType] - + " versions of documents MUST remain publically accessible to other VCELL users.\n" - : "") + + " versions of documents MUST remain publically accessible to other VCELL users.\n" + : "") + "Do you want to " + CurateSpec.CURATE_TYPE_NAMES[curateType] + " document '" + documentInfo.getVersion().getName() + "'" + "\nwith version date '" + documentInfo.getVersion().getDate().toString() + "'?"), @@ -2447,7 +2450,8 @@ public void run(Hashtable hashTable) throws Exception { public void updateUserRegistration(final DocumentWindowManager currWindowManager, final boolean bNewUser) { try { - UserRegistrationManager.registrationOperationGUI(this, currWindowManager, + + userRegistrationManager.registrationOperationGUI(this, currWindowManager, getClientServerManager().getClientServerInfo(), (bNewUser ? LoginManager.USERACTION_REGISTER : LoginManager.USERACTION_EDITINFO), (bNewUser ? null : getClientServerManager())); @@ -2463,8 +2467,8 @@ public void updateUserRegistration(final DocumentWindowManager currWindowManager public void sendLostPassword(final DocumentWindowManager currWindowManager, final String userid) { try { - UserRegistrationManager.registrationOperationGUI(this, currWindowManager, - VCellClient.createClientServerInfo(getClientServerManager().getClientServerInfo(), userid, null), + userRegistrationManager.registrationOperationGUI(this, currWindowManager, + VCellClient.getInstance().createClientServerInfo(getClientServerManager().getClientServerInfo(), userid, null), LoginManager.USERACTION_LOSTPASSWORD, null); } catch (UserCancelException e) { return; @@ -2479,7 +2483,7 @@ public void deleteDocument(final VCDocumentInfo documentInfo, final TopLevelWind } public void deleteDocument(final VCDocumentInfo documentInfo, final TopLevelWindowManager requester, - boolean bDontAsk) { + boolean bDontAsk) { if (documentInfo != null) { // see if we have this open String documentID = documentInfo.getVersion().getVersionKey().toString(); @@ -2538,7 +2542,7 @@ public void run(Hashtable hashTable) throws Exception { * Comment */ public static void downloadExportedData(final Component requester, final UserPreferences userPrefs, - final ExportEvent evt) { + final ExportEvent evt) { TreeSet exportsRecord = getExportsRecord(); if (exportsRecord.contains(evt.getJobID() + "")) { return; @@ -2613,7 +2617,7 @@ public void run() { // Wait for download to 1-finish, 2-fail or 3-be cancelled by user while (!bFlagArr[0]) { if (getClientTaskStatusSupport() != null && getClientTaskStatusSupport().isInterrupted()) {// user - // cancelled + // cancelled if (httpGetArr[0] != null) { httpGetArr[0].abort(); } @@ -2861,7 +2865,7 @@ public void exportDocument(TopLevelWindowManager manager, FileFilter forceFilefi if (forceFilefilter != null) { hash.put(ChooseFile.FORCE_FILE_FILTER, forceFilefilter); } - + hash.put("CallAction", CallAction.EXPORT); hash.put(CommonTask.DOCUMENT_WINDOW_MANAGER.name, manager); hash.put("currentDocumentWindow", currentWindow); @@ -2936,7 +2940,7 @@ public DocumentManager getDocumentManager() { } public MergedDatasetViewerController getMergedDatasetViewerController(OutputContext outputContext, - VCDataIdentifier vcdId, boolean expectODEData) throws DataAccessException { + VCDataIdentifier vcdId, boolean expectODEData) throws DataAccessException { if (vcdId instanceof MergedDataInfo) { DataManager dataManager = getDataManager(outputContext, vcdId, !expectODEData); return new MergedDatasetViewerController(dataManager); @@ -2946,7 +2950,7 @@ public MergedDatasetViewerController getMergedDatasetViewerController(OutputCont } public DataViewerController getDataViewerController(OutputContext outputContext, Simulation simulation, - int jobIndex) throws DataAccessException { + int jobIndex) throws DataAccessException { VCSimulationIdentifier vcSimulationIdentifier = simulation.getSimulationInfo() .getAuthoritativeVCSimulationIdentifier(); final VCDataIdentifier vcdataIdentifier = new VCSimulationDataIdentifier(vcSimulationIdentifier, jobIndex); @@ -2960,24 +2964,24 @@ private VCDocumentInfo getMatchingDocumentInfo(VCDocument vcDoc) throws DataAcce VCDocumentInfo vcDocInfo = null; switch (vcDoc.getDocumentType()) { - case BIOMODEL_DOC: { - BioModel bm = ((BioModel) vcDoc); - vcDocInfo = getDocumentManager().getBioModelInfo(bm.getVersion().getVersionKey()); - break; - } - case MATHMODEL_DOC: { - MathModel mm = ((MathModel) vcDoc); - vcDocInfo = getDocumentManager().getMathModelInfo(mm.getVersion().getVersionKey()); - break; - } - case GEOMETRY_DOC: { - Geometry geom = ((Geometry) vcDoc); - vcDocInfo = getDocumentManager().getGeometryInfo(geom.getKey()); - break; - } - default: { - throw new IllegalArgumentException("Invalid VC document: " + vcDoc.getDocumentType()); - } + case BIOMODEL_DOC: { + BioModel bm = ((BioModel) vcDoc); + vcDocInfo = getDocumentManager().getBioModelInfo(bm.getVersion().getVersionKey()); + break; + } + case MATHMODEL_DOC: { + MathModel mm = ((MathModel) vcDoc); + vcDocInfo = getDocumentManager().getMathModelInfo(mm.getVersion().getVersionKey()); + break; + } + case GEOMETRY_DOC: { + Geometry geom = ((Geometry) vcDoc); + vcDocInfo = getDocumentManager().getGeometryInfo(geom.getKey()); + break; + } + default: { + throw new IllegalArgumentException("Invalid VC document: " + vcDoc.getDocumentType()); + } } return vcDocInfo; @@ -3028,7 +3032,7 @@ public void managerIDchanged(java.lang.String oldID, java.lang.String newID) { } public AsynchClientTask[] newDocument(TopLevelWindowManager requester, - final VCDocument.DocumentCreationInfo documentCreationInfo) { + final VCDocument.DocumentCreationInfo documentCreationInfo) { // gcwtodo AsynchClientTask createNewDocumentTask = new AsynchClientTask("Creating New Document", @@ -3208,7 +3212,7 @@ public void onVCellMessageEvent(final VCellMessageEvent event) { private final static String WIN_MGR_KEY = "WIN_MGR_KY"; private void openAfterChecking(VCDocumentInfo documentInfo, final TopLevelWindowManager requester, - final boolean inNewWindow) { + final boolean inNewWindow) { final String DOCUMENT_INFO = "documentInfo"; final String SEDML_TASK = "SedMLTask"; @@ -3346,7 +3350,7 @@ private void openAfterChecking(VCDocumentInfo documentInfo, final TopLevelWindow } List sedmls = new ArrayList<>(); for (SEDMLDocument doc : docs) { - SedML sedml =doc.getSedMLModel(); + SedML sedml =doc.getSedMLModel(); if (sedml == null) { throw new RuntimeException("Failed importing " + file.getName()); } @@ -3504,7 +3508,7 @@ public void run(Hashtable hashTable) throws Exception { @SuppressWarnings("unchecked") List childElementList = rootElement.getChildren(); Element modelElement = childElementList.get(0); // assuming first child is the biomodel, - // mathmodel or geometry. + // mathmodel or geometry. modelXmlType = modelElement.getName(); } if (xmlType.equals(XMLTags.BioModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) @@ -3542,13 +3546,13 @@ public void run(Hashtable hashTable) throws Exception { List sedmls = new ArrayList<>(); sedmls.add(sedml); hashTable.put(SEDML_MODELS, sedmls); - + // default to import all tasks List vcdocs = XmlHelper.importSEDML(transLogger, externalDocInfo, sedml, false); for (VCDocument vcdoc : vcdocs) { docs.add(vcdoc); } - + isSEDML = true; } else { // unknown XML format throw new RuntimeException( @@ -3604,7 +3608,7 @@ public void run(Hashtable hashTable) throws Exception { windowManagers.add(windowManager); } hashTable.put("managers", windowManagers); - hashTable.put("docs", docs); + hashTable.put("docs", docs); } else { VCDocument doc = (VCDocument) hashTable.get("doc"); DocumentWindowManager windowManager = null; @@ -3780,36 +3784,36 @@ public static void idToNameConversion(VCDocument vcDoc) { } entitiesToRename.put(id, name); } - for(Structure struct : vcBioModel.getModel().getStructures()) { - String id = struct.getName(); - String name = struct.getSbmlName(); - if(name == null || name.isEmpty()) { - continue; - } - if(id.equals(name)) { - continue; - } - if(isRestrictedXYZT(name, vcBioModel)) { - continue; - } - name = TokenMangler.fixTokenStrict(name, 60); - while (true) { - if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) { - break; - } - name = TokenMangler.getNextEnumeratedToken(name); - } - if(id.equals(name)) { - continue; - } - try { - System.out.println(name + " <-- " + id); - struct.setName(name, true); - } catch(PropertyVetoException e) { - e.printStackTrace(); + for(Structure struct : vcBioModel.getModel().getStructures()) { + String id = struct.getName(); + String name = struct.getSbmlName(); + if(name == null || name.isEmpty()) { + continue; + } + if(id.equals(name)) { + continue; + } + if(isRestrictedXYZT(name, vcBioModel)) { + continue; + } + name = TokenMangler.fixTokenStrict(name, 60); + while (true) { + if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) { + break; + } + name = TokenMangler.getNextEnumeratedToken(name); + } + if(id.equals(name)) { + continue; + } + try { + System.out.println(name + " <-- " + id); + struct.setName(name, true); + } catch(PropertyVetoException e) { + e.printStackTrace(); + } + entitiesToRename.put(id, name); } - entitiesToRename.put(id, name); - } vcBioModel.getSimulationContext(0).substituteChangedNamesInExpressions(entitiesToRename); for (ReactionStep rs : vcBioModel.getModel().getReactionSteps()) { @@ -3846,7 +3850,7 @@ public static void idToNameConversion(VCDocument vcDoc) { /** * raise issue tab if error is present - * + * * @param hashTable * @throws Exception */ @@ -3900,8 +3904,8 @@ public void openDocument(VCDocumentInfo documentInfo, TopLevelWindowManager requ } String documentID = null; if (documentInfo.getVersion() != null && documentInfo.getVersion().getVersionKey() != null) { // CLEAN UP BOGUS - // VERSION in - // XmlInfo !!! + // VERSION in + // XmlInfo !!! documentID = documentInfo.getVersion().getVersionKey().toString(); } @@ -4014,7 +4018,7 @@ public void run() { /** * This method gets called when a bound property is changed. - * + * * @param evt A PropertyChangeEvent object describing the event source and the * property that has changed. */ @@ -4066,18 +4070,18 @@ public void revertToSaved(DocumentWindowManager documentWindowManager) { try { KeyValue versionKey = document.getVersion().getVersionKey(); switch (document.getDocumentType()) { - case BIOMODEL_DOC: { - info = getDocumentManager().getBioModelInfo(versionKey); - break; - } - case MATHMODEL_DOC: { - info = getDocumentManager().getMathModelInfo(versionKey); - break; - } - case GEOMETRY_DOC: { - info = getDocumentManager().getGeometryInfo(versionKey); - break; - } + case BIOMODEL_DOC: { + info = getDocumentManager().getBioModelInfo(versionKey); + break; + } + case MATHMODEL_DOC: { + info = getDocumentManager().getMathModelInfo(versionKey); + break; + } + case GEOMETRY_DOC: { + info = getDocumentManager().getGeometryInfo(versionKey); + break; + } } } catch (DataAccessException e) { e.printStackTrace(System.out); @@ -4098,6 +4102,7 @@ public SimulationStatus runSimulation(final SimulationInfo simInfo, int numSimul public void runSimulations(final ClientSimManager clientSimManager, final Simulation[] simulations) { runSimulations(clientSimManager, simulations, null); } + public void runSimulations(final ClientSimManager clientSimManager, final Simulation[] simulations,AsynchClientTask[] endTasks) { DocumentWindowManager documentWindowManager = clientSimManager.getDocumentWindowManager(); if (documentWindowManager.getUser() == null || User.isGuest(documentWindowManager.getUser().getName())) { @@ -4240,7 +4245,7 @@ public void saveDocument(DocumentWindowManager documentWindowManager, boolean re } public void saveDocument(final DocumentWindowManager documentWindowManager, boolean replace, - AsynchClientTask closeWindowTask) { + AsynchClientTask closeWindowTask) { if (documentWindowManager.getUser() == null || User.isGuest(documentWindowManager.getUser().getName())) { DialogUtils.showErrorDialog(documentWindowManager.getComponent(), User.createGuestErrorMessage("saveDocument")); @@ -4591,7 +4596,7 @@ public OpenModelInfoHolder[] getOpenDesktopDocumentInfos(boolean bIncludeSimulat } public void showComparisonResults(TopLevelWindowManager requester, XmlTreeDiff diffTree, String baselineDesc, - String modifiedDesc) { + String modifiedDesc) { TMLPanel comparePanel = new TMLPanel(); comparePanel.setXmlTreeDiff(diffTree); comparePanel.setBaselineVersionDescription(baselineDesc); @@ -4652,7 +4657,7 @@ public void showComparisonResults(TopLevelWindowManager requester, XmlTreeDiff d //} public static FieldDataFileOperationSpec createFDOSFromImageFile(File imageFile, boolean bCropOutBlack, - Integer saveOnlyThisTimePointIndex) throws DataFormatException, ImageException { + Integer saveOnlyThisTimePointIndex) throws DataFormatException, ImageException { try { ImageDatasetReader imageDatasetReader = ImageDatasetReaderService.getInstance().getImageDatasetReader(); ImageDataset[] imagedataSets = imageDatasetReader.readImageDatasetChannels(imageFile.getAbsolutePath(), @@ -4673,7 +4678,7 @@ public static FieldDataFileOperationSpec createFDOSFromImageFile(File imageFile, } public static FieldDataFileOperationSpec createFDOSWithChannels(ImageDataset[] imagedataSets, - Integer saveOnlyThisTimePointIndex) { + Integer saveOnlyThisTimePointIndex) { final FieldDataFileOperationSpec fdos = new FieldDataFileOperationSpec(); // [time][var][data] @@ -4722,75 +4727,76 @@ public static FieldDataFileOperationSpec createFDOSWithChannels(ImageDataset[] i public void accessPermissions(Component requester, VCDocument vcDoc) { VersionInfo selectedVersionInfo = null; switch (vcDoc.getDocumentType()) { - case BIOMODEL_DOC: - BioModelInfo[] bioModelInfos = getDocumentManager().getBioModelInfos(); - for (BioModelInfo bioModelInfo : bioModelInfos) { - if (bioModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { - selectedVersionInfo = bioModelInfo; - break; + case BIOMODEL_DOC: + BioModelInfo[] bioModelInfos = getDocumentManager().getBioModelInfos(); + for (BioModelInfo bioModelInfo : bioModelInfos) { + if (bioModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { + selectedVersionInfo = bioModelInfo; + break; + } } - } - break; - case MATHMODEL_DOC: - MathModelInfo[] mathModelInfos = getDocumentManager().getMathModelInfos(); - for (MathModelInfo mathModelInfo : mathModelInfos) { - if (mathModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { - selectedVersionInfo = mathModelInfo; - break; + break; + case MATHMODEL_DOC: + MathModelInfo[] mathModelInfos = getDocumentManager().getMathModelInfos(); + for (MathModelInfo mathModelInfo : mathModelInfos) { + if (mathModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { + selectedVersionInfo = mathModelInfo; + break; + } } - } - break; - case GEOMETRY_DOC: - GeometryInfo[] geoInfos = getDocumentManager().getGeometryInfos(); - for (GeometryInfo geoInfo : geoInfos) { - if (geoInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { - selectedVersionInfo = geoInfo; - break; + break; + case GEOMETRY_DOC: + GeometryInfo[] geoInfos = getDocumentManager().getGeometryInfos(); + for (GeometryInfo geoInfo : geoInfos) { + if (geoInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { + selectedVersionInfo = geoInfo; + break; + } } - } - break; + break; } getMdiManager().getDatabaseWindowManager().accessPermissions(requester, selectedVersionInfo, false); } + public void accessPermissionsEx(Component requester, VCDocument vcDoc, boolean bGrantSupportPermissions) { VersionInfo selectedVersionInfo = null; switch (vcDoc.getDocumentType()) { - case BIOMODEL_DOC: - BioModelInfo[] bioModelInfos = getDocumentManager().getBioModelInfos(); - for (BioModelInfo bioModelInfo : bioModelInfos) { - if (bioModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { - selectedVersionInfo = bioModelInfo; - break; + case BIOMODEL_DOC: + BioModelInfo[] bioModelInfos = getDocumentManager().getBioModelInfos(); + for (BioModelInfo bioModelInfo : bioModelInfos) { + if (bioModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { + selectedVersionInfo = bioModelInfo; + break; + } } - } - break; - case MATHMODEL_DOC: - MathModelInfo[] mathModelInfos = getDocumentManager().getMathModelInfos(); - for (MathModelInfo mathModelInfo : mathModelInfos) { - if (mathModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { - selectedVersionInfo = mathModelInfo; - break; + break; + case MATHMODEL_DOC: + MathModelInfo[] mathModelInfos = getDocumentManager().getMathModelInfos(); + for (MathModelInfo mathModelInfo : mathModelInfos) { + if (mathModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { + selectedVersionInfo = mathModelInfo; + break; + } } - } - break; - case GEOMETRY_DOC: - GeometryInfo[] geoInfos = getDocumentManager().getGeometryInfos(); - for (GeometryInfo geoInfo : geoInfos) { - if (geoInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { - selectedVersionInfo = geoInfo; - break; + break; + case GEOMETRY_DOC: + GeometryInfo[] geoInfos = getDocumentManager().getGeometryInfos(); + for (GeometryInfo geoInfo : geoInfos) { + if (geoInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) { + selectedVersionInfo = geoInfo; + break; + } } - } - break; + break; } getMdiManager().getDatabaseWindowManager().accessPermissions(requester, selectedVersionInfo, true); } public static Collection updateMath(final Component requester, - final SimulationContext simulationContext, final boolean bShowWarning, - final NetworkGenerationRequirements networkGenerationRequirements) { + final SimulationContext simulationContext, final boolean bShowWarning, + final NetworkGenerationRequirements networkGenerationRequirements) { ArrayList rval = new ArrayList<>(); AsynchClientTask task1 = new AsynchClientTask("generating math", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { diff --git a/vcell-client/src/main/java/cbit/vcell/client/UserRegistrationManager.java b/vcell-client/src/main/java/cbit/vcell/client/UserRegistrationManager.java index d8e479156e..b00312ddd8 100644 --- a/vcell-client/src/main/java/cbit/vcell/client/UserRegistrationManager.java +++ b/vcell-client/src/main/java/cbit/vcell/client/UserRegistrationManager.java @@ -24,197 +24,201 @@ public class UserRegistrationManager { - @Inject - private static RegistrationService injectedRegistrationService; + private final RegistrationService injectedRegistrationService; private static RegistrationPanel registrationPanel = null; - public static void registrationOperationGUI(final RequestManager requestManager, final DocumentWindowManager currWindowManager, - final ClientServerInfo currentClientServerInfo, final String userAction, final ClientServerManager clientServerManager) throws Exception{ - if(!(userAction.equals(LoginManager.USERACTION_REGISTER) || - userAction.equals(LoginManager.USERACTION_EDITINFO) || - userAction.equals(LoginManager.USERACTION_LOSTPASSWORD))){ - throw new IllegalArgumentException(UserRegistrationOP.class.getName()+".registrationOperationGUI: Only New registration, Edit UserInfo or Lost Password allowed."); - } - if((userAction.equals(LoginManager.USERACTION_REGISTER) || userAction.equals(LoginManager.USERACTION_LOSTPASSWORD)) && clientServerManager != null){ - throw new IllegalArgumentException(UserRegistrationOP.class.getName()+".registrationOperationGUI: Register New User Info requires clientServerManager null."); - } - if(userAction.equals(LoginManager.USERACTION_EDITINFO) && clientServerManager == null){ - throw new IllegalArgumentException(UserRegistrationOP.class.getName()+".registrationOperationGUI: Edit User Info requires clientServerManager not null."); - } + @Inject + UserRegistrationManager(RegistrationService registrationService) { + this.injectedRegistrationService = registrationService; + } - RegistrationService registrationService = injectedRegistrationService; - if(clientServerManager != null){ - registrationService = clientServerManager.getRegistrationProvider(); + public void registrationOperationGUI(final RequestManager requestManager, final DocumentWindowManager currWindowManager, + final ClientServerInfo currentClientServerInfo, final String userAction, final ClientServerManager clientServerManager) throws Exception{ + if(!(userAction.equals(LoginManager.USERACTION_REGISTER) || + userAction.equals(LoginManager.USERACTION_EDITINFO) || + userAction.equals(LoginManager.USERACTION_LOSTPASSWORD))){ + throw new IllegalArgumentException(UserRegistrationOP.class.getName()+".registrationOperationGUI: Only New registration, Edit UserInfo or Lost Password allowed."); + } + if((userAction.equals(LoginManager.USERACTION_REGISTER) || userAction.equals(LoginManager.USERACTION_LOSTPASSWORD)) && clientServerManager != null){ + throw new IllegalArgumentException(UserRegistrationOP.class.getName()+".registrationOperationGUI: Register New User Info requires clientServerManager null."); + } + if(userAction.equals(LoginManager.USERACTION_EDITINFO) && clientServerManager == null){ + throw new IllegalArgumentException(UserRegistrationOP.class.getName()+".registrationOperationGUI: Edit User Info requires clientServerManager not null."); + } + + RegistrationService registrationService = injectedRegistrationService; + if(clientServerManager != null){ + registrationService = clientServerManager.getRegistrationProvider(); + } + if(userAction.equals(LoginManager.USERACTION_LOSTPASSWORD)){ + if(currentClientServerInfo.getUsername() == null || currentClientServerInfo.getUsername().length() == 0){ + throw new IllegalArgumentException("Lost Password requires a VCell User Name."); } - if(userAction.equals(LoginManager.USERACTION_LOSTPASSWORD)){ - if(currentClientServerInfo.getUsername() == null || currentClientServerInfo.getUsername().length() == 0){ - throw new IllegalArgumentException("Lost Password requires a VCell User Name."); - } - String result = PopupGenerator.showWarningDialog(currWindowManager, null, - new UserMessage( + String result = PopupGenerator.showWarningDialog(currWindowManager, null, + new UserMessage( "Sending Password via email for user '"+currentClientServerInfo.getUsername()+ - "'\nusing currently registered email address.", + "'\nusing currently registered email address.", new String[] {"OK","Cancel"},"OK"), - null); - if(!result.equals("OK")){ - throw UserCancelException.CANCEL_GENERIC; + null); + if(!result.equals("OK")){ + throw UserCancelException.CANCEL_GENERIC; + } + registrationService.sendLostPassword(currentClientServerInfo.getUsername()); + return; + } + + final RegistrationService finalRegistrationProvider = registrationService; + final String ORIGINAL_USER_INFO_HOLDER = "originalUserInfoHolder"; + //final String DIGESTED_USERIDS_KEY = "DIGESTED_USERIDS_KEY"; + AsynchClientTask gatherInfoTask = new AsynchClientTask("gathering user info for updating", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { + + @Override + public void run(Hashtable hashTable) throws Exception { + if(userAction.equals(LoginManager.USERACTION_EDITINFO)){ + UserInfo originalUserInfoHolder = finalRegistrationProvider.getUserInfo(clientServerManager.getUser().getID()); + hashTable.put(ORIGINAL_USER_INFO_HOLDER, originalUserInfoHolder); } - registrationService.sendLostPassword(currentClientServerInfo.getUsername()); - return; } - - final RegistrationService finalRegistrationProvider = registrationService; - final String ORIGINAL_USER_INFO_HOLDER = "originalUserInfoHolder"; - //final String DIGESTED_USERIDS_KEY = "DIGESTED_USERIDS_KEY"; - AsynchClientTask gatherInfoTask = new AsynchClientTask("gathering user info for updating", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { - - @Override - public void run(Hashtable hashTable) throws Exception { - if(userAction.equals(LoginManager.USERACTION_EDITINFO)){ - UserInfo originalUserInfoHolder = finalRegistrationProvider.getUserInfo(clientServerManager.getUser().getID()); - hashTable.put(ORIGINAL_USER_INFO_HOLDER, originalUserInfoHolder); - } - } - }; - - final String NEW_USER_INFO_KEY = "NEW_USER_INFO_KEY"; - AsynchClientTask showPanelTask = new AsynchClientTask("please fill the user registration form", AsynchClientTask.TASKTYPE_SWING_BLOCKING) { - - @Override - public void run(Hashtable hashTable) throws Exception { - if (registrationPanel == null) { - registrationPanel = new RegistrationPanel(); - } else { - if (currentClientServerInfo.getUsername() != null) { // another user already connected - registrationPanel.reset(); - } + }; + + final String NEW_USER_INFO_KEY = "NEW_USER_INFO_KEY"; + AsynchClientTask showPanelTask = new AsynchClientTask("please fill the user registration form", AsynchClientTask.TASKTYPE_SWING_BLOCKING) { + + @Override + public void run(Hashtable hashTable) throws Exception { + if (registrationPanel == null) { + registrationPanel = new RegistrationPanel(); + } else { + if (currentClientServerInfo.getUsername() != null) { // another user already connected + registrationPanel.reset(); } - UserInfo originalUserInfoHolder = (UserInfo)hashTable.get(ORIGINAL_USER_INFO_HOLDER);; - if(userAction.equals(LoginManager.USERACTION_EDITINFO) && originalUserInfoHolder != null) { - registrationPanel.setUserInfo(originalUserInfoHolder,true); + } + UserInfo originalUserInfoHolder = (UserInfo)hashTable.get(ORIGINAL_USER_INFO_HOLDER);; + if(userAction.equals(LoginManager.USERACTION_EDITINFO) && originalUserInfoHolder != null) { + registrationPanel.setUserInfo(originalUserInfoHolder,true); + } + do { + int result = DialogUtils.showComponentOKCancelDialog(currWindowManager.getComponent(), registrationPanel, + (userAction.equals(LoginManager.USERACTION_REGISTER)?"Create New User Registration":"Update Registration Information ("+clientServerManager.getUser().getName()+")")); + if (result != JOptionPane.OK_OPTION) { + throw UserCancelException.CANCEL_GENERIC; } - do { - int result = DialogUtils.showComponentOKCancelDialog(currWindowManager.getComponent(), registrationPanel, - (userAction.equals(LoginManager.USERACTION_REGISTER)?"Create New User Registration":"Update Registration Information ("+clientServerManager.getUser().getName()+")")); - if (result != JOptionPane.OK_OPTION) { - throw UserCancelException.CANCEL_GENERIC; + UserRegistrationOP.NewPasswordUserInfo newUserInfo = registrationPanel.getUserInfo(); + + if(userAction.equals(LoginManager.USERACTION_EDITINFO)){ + //User editing registration info but did not enter new clear text password in gui, + //set existing digestPassword + if(newUserInfo.digestedPassword0 == null && originalUserInfoHolder.digestedPassword0 != null){ + newUserInfo.digestedPassword0 = originalUserInfoHolder.digestedPassword0; } - UserRegistrationOP.NewPasswordUserInfo newUserInfo = registrationPanel.getUserInfo(); - - if(userAction.equals(LoginManager.USERACTION_EDITINFO)){ - //User editing registration info but did not enter new clear text password in gui, - //set existing digestPassword - if(newUserInfo.digestedPassword0 == null && originalUserInfoHolder.digestedPassword0 != null){ - newUserInfo.digestedPassword0 = originalUserInfoHolder.digestedPassword0; - } - if(newUserInfo.otherDigestedPassword == null && originalUserInfoHolder.digestedPassword0 != null){ - newUserInfo.otherDigestedPassword = originalUserInfoHolder.digestedPassword0; - } + if(newUserInfo.otherDigestedPassword == null && originalUserInfoHolder.digestedPassword0 != null){ + newUserInfo.otherDigestedPassword = originalUserInfoHolder.digestedPassword0; } - - try { - if(!checkUserInfo(currWindowManager, originalUserInfoHolder,newUserInfo,userAction)){ - PopupGenerator.showInfoDialog(currWindowManager, "No registration information has changed."); - continue; - } - } catch (UserCancelException ex) { - continue; - } catch (Exception ex) { - PopupGenerator.showErrorDialog(currWindowManager, ex.getMessage()); + } + + try { + if(!checkUserInfo(currWindowManager, originalUserInfoHolder,newUserInfo,userAction)){ + PopupGenerator.showInfoDialog(currWindowManager, "No registration information has changed."); continue; } - hashTable.put(NEW_USER_INFO_KEY, newUserInfo); - break; - } while (true); - } - }; - - // final String USERID_NOT_UNIQUE = "USERID_NOT_UNIQUE"; - AsynchClientTask updateDbTask = new AsynchClientTask(userAction.equals(LoginManager.USERACTION_REGISTER)?"registering new user":"updating user info", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { - - @Override - public void run(Hashtable hashTable) throws Exception { - UserInfo newUserInfo = (UserInfo)hashTable.get(NEW_USER_INFO_KEY); - // if(userAction.equals(LoginManager.USERACTION_REGISTER)){ - // //Check userid already exists - // if(!finalRegistrationProvider.isUserIdUnique(newUserInfo.userid)){ - // throw UserCancelException.createCustomUserCancelException(USERID_NOT_UNIQUE); - // } - // } - try { - UserInfo registeredUserInfo = finalRegistrationProvider.insertUserInfo(newUserInfo,(userAction.equals(LoginManager.USERACTION_EDITINFO)?true:false)); - hashTable.put("registeredUserInfo", registeredUserInfo); - }catch (IllegalArgumentException e) { - throw e; - }catch (Exception e) { - e.printStackTrace(); - throw new Exception("Error " - + (userAction.equals(LoginManager.USERACTION_REGISTER)?"registering new user" :"updating user info ") + " ("+newUserInfo.userid+"), " - + e.getMessage()); + } catch (UserCancelException ex) { + continue; + } catch (Exception ex) { + PopupGenerator.showErrorDialog(currWindowManager, ex.getMessage()); + continue; } - } - }; - - AsynchClientTask connectTask = new AsynchClientTask("user logging in", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { - - @Override - public void run(Hashtable hashTable) throws Exception { - UserInfo registeredUserInfo = (UserInfo)hashTable.get("registeredUserInfo"); - try { - if (userAction.equals(LoginManager.USERACTION_REGISTER)) { - try{ - ClientServerInfo newClientServerInfo = VCellClient.createClientServerInfo(currentClientServerInfo, registeredUserInfo.userid, registeredUserInfo.digestedPassword0); - requestManager.connectToServer(currWindowManager, newClientServerInfo); - }finally{ - ConnectionStatus connectionStatus = requestManager.getConnectionStatus(); - if(connectionStatus.getStatus() != ConnectionStatus.CONNECTED){ - PopupGenerator.showErrorDialog(currWindowManager, "Automatic login of New user '"+registeredUserInfo.userid+"' failed.\n"+ + hashTable.put(NEW_USER_INFO_KEY, newUserInfo); + break; + } while (true); + } + }; + + // final String USERID_NOT_UNIQUE = "USERID_NOT_UNIQUE"; + AsynchClientTask updateDbTask = new AsynchClientTask(userAction.equals(LoginManager.USERACTION_REGISTER)?"registering new user":"updating user info", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { + + @Override + public void run(Hashtable hashTable) throws Exception { + UserInfo newUserInfo = (UserInfo)hashTable.get(NEW_USER_INFO_KEY); + // if(userAction.equals(LoginManager.USERACTION_REGISTER)){ + // //Check userid already exists + // if(!finalRegistrationProvider.isUserIdUnique(newUserInfo.userid)){ + // throw UserCancelException.createCustomUserCancelException(USERID_NOT_UNIQUE); + // } + // } + try { + UserInfo registeredUserInfo = finalRegistrationProvider.insertUserInfo(newUserInfo,(userAction.equals(LoginManager.USERACTION_EDITINFO)?true:false)); + hashTable.put("registeredUserInfo", registeredUserInfo); + }catch (IllegalArgumentException e) { + throw e; + }catch (Exception e) { + e.printStackTrace(); + throw new Exception("Error " + + (userAction.equals(LoginManager.USERACTION_REGISTER)?"registering new user" :"updating user info ") + " ("+newUserInfo.userid+"), " + + e.getMessage()); + } + } + }; + + AsynchClientTask connectTask = new AsynchClientTask("user logging in", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { + + @Override + public void run(Hashtable hashTable) throws Exception { + UserInfo registeredUserInfo = (UserInfo)hashTable.get("registeredUserInfo"); + try { + if (userAction.equals(LoginManager.USERACTION_REGISTER)) { + try{ + ClientServerInfo newClientServerInfo = VCellClient.getInstance().createClientServerInfo(currentClientServerInfo, registeredUserInfo.userid, registeredUserInfo.digestedPassword0); + requestManager.connectToServer(currWindowManager, newClientServerInfo); + }finally{ + ConnectionStatus connectionStatus = requestManager.getConnectionStatus(); + if(connectionStatus.getStatus() != ConnectionStatus.CONNECTED){ + PopupGenerator.showErrorDialog(currWindowManager, "Automatic login of New user '"+registeredUserInfo.userid+"' failed.\n"+ "Restart VCell and login as '"+registeredUserInfo.userid+"' to use new VCell account." - ); + ); } } - } - }catch (Exception e) { - e.printStackTrace(); - throw new Exception("Error logging in user " + " ("+registeredUserInfo.userid+"), " + e.getMessage()); } - } - }; - - AsynchClientTask useridErrorTask = new AsynchClientTask("re-enter userid...",AsynchClientTask.TASKTYPE_NONSWING_BLOCKING,false,false) { - @Override - public void run(final Hashtable hashTable) throws Exception { - if(hashTable.containsKey(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR)){ - //retry if requested - if(hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR) instanceof IllegalArgumentException){ - //Exception handled here, suppress ClientTaskDispatcher error dialog. - hashTable.remove(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR); - UserInfo newUserInfo = (UserInfo)hashTable.get(NEW_USER_INFO_KEY); - PopupGenerator.showErrorDialog(currWindowManager, "Login ID '"+newUserInfo.userid+"' cannot be used, enter a different one."); - //Use thread to restart registration process again - new Thread(new Runnable() { - @Override - public void run() { - try { - registrationOperationGUI(requestManager, currWindowManager, currentClientServerInfo, userAction, clientServerManager); - } catch (Exception e) { - e.printStackTrace(); - DialogUtils.showErrorDialog(currWindowManager.getComponent(), e.getMessage()); - } + }catch (Exception e) { + e.printStackTrace(); + throw new Exception("Error logging in user " + " ("+registeredUserInfo.userid+"), " + e.getMessage()); + } + } + }; + + AsynchClientTask useridErrorTask = new AsynchClientTask("re-enter userid...",AsynchClientTask.TASKTYPE_NONSWING_BLOCKING,false,false) { + @Override + public void run(final Hashtable hashTable) throws Exception { + if(hashTable.containsKey(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR)){ + //retry if requested + if(hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR) instanceof IllegalArgumentException){ + //Exception handled here, suppress ClientTaskDispatcher error dialog. + hashTable.remove(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR); + UserInfo newUserInfo = (UserInfo)hashTable.get(NEW_USER_INFO_KEY); + PopupGenerator.showErrorDialog(currWindowManager, "Login ID '"+newUserInfo.userid+"' cannot be used, enter a different one."); + //Use thread to restart registration process again + new Thread(new Runnable() { + @Override + public void run() { + try { + registrationOperationGUI(requestManager, currWindowManager, currentClientServerInfo, userAction, clientServerManager); + } catch (Exception e) { + e.printStackTrace(); + DialogUtils.showErrorDialog(currWindowManager.getComponent(), e.getMessage()); } - }).start(); - } + } + }).start(); } } - }; - ClientTaskDispatcher.dispatch(currWindowManager.getComponent(), new Hashtable(), new AsynchClientTask[] {gatherInfoTask, showPanelTask, updateDbTask, connectTask,useridErrorTask}, false); - } + } + }; + ClientTaskDispatcher.dispatch(currWindowManager.getComponent(), new Hashtable(), new AsynchClientTask[] {gatherInfoTask, showPanelTask, updateDbTask, connectTask,useridErrorTask}, false); + } - private static boolean checkUserInfo(DocumentWindowManager currWindowManager, UserInfo origUserInfo,UserRegistrationOP.NewPasswordUserInfo newUserInfo,String userAction) throws Exception{ + private boolean checkUserInfo(DocumentWindowManager currWindowManager, UserInfo origUserInfo,UserRegistrationOP.NewPasswordUserInfo newUserInfo,String userAction) throws Exception{ TokenMangler.checkLoginID(newUserInfo.userid); boolean bEditing = userAction.equals(LoginManager.USERACTION_EDITINFO); - String emptyMessge = " can not be empty"; + String emptyMessge = " can not be empty"; if(newUserInfo.userid == null || newUserInfo.userid.length() == 0){throw new Exception("Registration Info: userid" + emptyMessge);} if(newUserInfo.digestedPassword0 == null || !newUserInfo.digestedPassword0.equals(newUserInfo.otherDigestedPassword)){ if(bEditing){ @@ -225,7 +229,7 @@ private static boolean checkUserInfo(DocumentWindowManager currWindowManager, Us } if(newUserInfo.email == null || newUserInfo.email.length() == 0 || newUserInfo.email.indexOf("@") < 0){throw new Exception("please type in a valid email address.");} if(newUserInfo.wholeName == null || newUserInfo.wholeName.length() == 0){throw new Exception("Registration Info: Name" + emptyMessge);} - + if(newUserInfo.title != null && newUserInfo.title.length() == 0){ newUserInfo.title = null; } @@ -237,11 +241,11 @@ private static boolean checkUserInfo(DocumentWindowManager currWindowManager, Us if(UserRegistrationOP.hasIllegalCharacters(newUserInfo.userid)){throw new Exception("Registration Info: userid" + hasIllegalMessage);} if(UserRegistrationOP.hasIllegalCharacters(newUserInfo.email)){throw new Exception("Registration Info: email" + hasIllegalMessage);} if(UserRegistrationOP.hasIllegalCharacters(newUserInfo.wholeName)){throw new Exception("Registration Info: firstName" + hasIllegalMessage);} - + if(newUserInfo.title!=null && UserRegistrationOP.hasIllegalCharacters(newUserInfo.title)){throw new Exception("Registration Info: title" + hasIllegalMessage);} if(newUserInfo.company!=null && UserRegistrationOP.hasIllegalCharacters(newUserInfo.company)){throw new Exception("Registration Info: organization" + hasIllegalMessage);} if(newUserInfo.country!=null && UserRegistrationOP.hasIllegalCharacters(newUserInfo.country)){throw new Exception("Registration Info: country" + hasIllegalMessage);} - + if(origUserInfo != null){ String[] columnNames = new String[] {"Field","Original","New Value"}; Vector tableRow = new Vector(); @@ -249,18 +253,18 @@ private static boolean checkUserInfo(DocumentWindowManager currWindowManager, Us if(!newUserInfo.digestedPassword0.equals(origUserInfo.digestedPassword0)){tableRow.add(new String[] {"password","---","changed"});} if(!newUserInfo.email.equals(origUserInfo.email)){tableRow.add(new String[] {"email",origUserInfo.email,newUserInfo.email});} if(!newUserInfo.wholeName.equals(origUserInfo.wholeName)){tableRow.add(new String[] {"firstName",origUserInfo.wholeName,newUserInfo.wholeName});} - + if(!Compare.isEqualOrNull(newUserInfo.title, origUserInfo.title)){tableRow.add(new String[] {"title",origUserInfo.title,newUserInfo.title});} if(!Compare.isEqualOrNull(newUserInfo.company, origUserInfo.company)){tableRow.add(new String[] {"organization",origUserInfo.company,newUserInfo.company});} if(!Compare.isEqualOrNull(newUserInfo.country, origUserInfo.country)){tableRow.add(new String[] {"country",origUserInfo.country,newUserInfo.country});} if(!(newUserInfo.notify == origUserInfo.notify)){tableRow.add(new String[] {"notify",origUserInfo.notify+"",newUserInfo.notify+""});} - + if(tableRow.size() > 0){ String[][] tableData = new String[tableRow.size()][]; tableRow.copyInto(tableData); DialogUtils.showComponentOKCancelTableList( - currWindowManager.getComponent(), "Confirm Registration Info Changes", - columnNames, tableData,null); + currWindowManager.getComponent(), "Confirm Registration Info Changes", + columnNames, tableData,null); return true; } return false; diff --git a/vcell-client/src/main/java/cbit/vcell/client/VCellClient.java b/vcell-client/src/main/java/cbit/vcell/client/VCellClient.java index e2083c7ba7..4c90fd77e4 100644 --- a/vcell-client/src/main/java/cbit/vcell/client/VCellClient.java +++ b/vcell-client/src/main/java/cbit/vcell/client/VCellClient.java @@ -19,6 +19,8 @@ import javax.swing.RepaintManager; import javax.swing.SwingUtilities; +import cbit.vcell.server.VCellConnectionFactory; +import com.google.inject.Inject; import org.vcell.util.UserCancelException; import org.vcell.util.document.UserLoginInfo; import org.vcell.util.document.UserLoginInfo.DigestedPassword; @@ -49,6 +51,9 @@ * @author: Ion Moraru */ public class VCellClient { + private final UserRegistrationManager userRegistrationManager; // injected in constructor + private final VCellConnectionFactory vcellConnectionFactory; // injected in constructor + private ClientServerManager clientServerManager = null; private StatusUpdater statusUpdater = null; private RequestManager requestManager = null; @@ -64,16 +69,8 @@ public static VCellClient getInstance() { } public static class CheckThreadViolationRepaintManager extends RepaintManager { - // it is recommended to pass the complete check - private boolean completeCheck = true; - - public boolean isCompleteCheck() { - return completeCheck; - } - - public void setCompleteCheck(boolean completeCheck) { - this.completeCheck = completeCheck; - } + // it is recommended to pass the complete check + private final boolean completeCheck = true; public synchronized void addInvalidComponent(JComponent component) { checkThreadViolations(component); @@ -114,8 +111,10 @@ private void checkThreadViolations(JComponent c) { * Insert the method's description here. * Creation date: (5/5/2004 3:56:09 PM) */ -private VCellClient() { - // just so we don't create this elsewhere +@Inject +public VCellClient(UserRegistrationManager userRegistrationManager, VCellConnectionFactory vcellConnectionFactory) { + this.userRegistrationManager = userRegistrationManager; + this.vcellConnectionFactory = vcellConnectionFactory; } @@ -147,106 +146,59 @@ private DocumentWindowManager createAndShowGUI(VCDocument startupDoc) { return windowManager; } -/** - * Insert the method's description here. - * Creation date: (5/12/2004 4:36:34 PM) - * @return cbit.vcell.client.server.ClientServerManager - */ public ClientServerManager getClientServerManager() { return clientServerManager; } -/** - * Insert the method's description here. - * Creation date: (5/24/2004 12:26:43 PM) - * @return cbit.vcell.client.MDIManager - */ public MDIManager getMdiManager() { return mdiManager; } -/** - * Insert the method's description here. - * Creation date: (5/24/2004 12:26:43 PM) - * @return cbit.vcell.client.RequestManager - */ public RequestManager getRequestManager() { return requestManager; } -/** - * Insert the method's description here. - * Creation date: (5/14/2004 2:59:53 PM) - * @return cbit.vcell.client.StatusUpdater - */ StatusUpdater getStatusUpdater() { return statusUpdater; } -/** - * Insert the method's description here. - * Creation date: (5/12/2004 4:36:34 PM) - * @param newClientServerManager cbit.vcell.client.server.ClientServerManager - */ private void setClientServerManager(ClientServerManager newClientServerManager) { clientServerManager = newClientServerManager; } - -/** - * Insert the method's description here. - * Creation date: (5/24/2004 12:26:43 PM) - * @param newMdiManager cbit.vcell.client.MDIManager - */ private void setMdiManager(MDIManager newMdiManager) { mdiManager = newMdiManager; } - -/** - * Insert the method's description here. - * Creation date: (5/24/2004 12:26:43 PM) - * @param newRequestManager cbit.vcell.client.RequestManager - */ private void setRequestManager(RequestManager newRequestManager) { requestManager = newRequestManager; } - -/** - * Insert the method's description here. - * Creation date: (5/14/2004 2:59:53 PM) - * @param newStatusUpdater cbit.vcell.client.StatusUpdater - */ private void setStatusUpdater(StatusUpdater newStatusUpdater) { statusUpdater = newStatusUpdater; } -public static VCellClient startClient(final VCDocument startupDoc, final ClientServerInfo clientServerInfo) { - /* Set Look and Feel */ +public void startClient(final VCDocument startupDoc, final ClientServerInfo clientServerInfo) { VCellLookAndFeel.setVCellLookAndFeel(); - // instantiate app - final VCellClient vcellClient = new VCellClient(); - Hashtable hash = new Hashtable(); AsynchClientTask task1 = new AsynchClientTask("Starting Virtual Cell", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) { public void run(Hashtable hashTable) throws Exception { // start management layer InteractiveContextDefaultProvider defaultRequester = new VCellGuiInteractiveContextDefaultProvider(); - vcellClient.setClientServerManager(new ClientServerManager(clientServerInfo, defaultRequester)); - vcellClient.setRequestManager(new ClientRequestManager(vcellClient)); - vcellClient.setMdiManager(new ClientMDIManager(vcellClient.getRequestManager())); + VCellClient.this.setClientServerManager(new ClientServerManager(vcellConnectionFactory, clientServerInfo, defaultRequester)); + VCellClient.this.setRequestManager(new ClientRequestManager(VCellClient.this, VCellClient.this.userRegistrationManager)); + VCellClient.this.setMdiManager(new ClientMDIManager(VCellClient.this.getRequestManager())); // start auxilliary stuff - vcellClient.startStatusThreads(); + VCellClient.this.startStatusThreads(); // make sure we have at least a blank document to start with if (startupDoc != null) { hashTable.put("startupDoc",startupDoc); } else { - VCDocument newStartupDoc = ((ClientRequestManager)vcellClient.getRequestManager()).createDefaultDocument(VCDocumentType.BIOMODEL_DOC); + VCDocument newStartupDoc = ((ClientRequestManager)VCellClient.this.getRequestManager()).createDefaultDocument(VCDocumentType.BIOMODEL_DOC); hashTable.put("startupDoc",newStartupDoc); } DocumentWindowAboutBox.parseVCellVersion(); @@ -260,7 +212,7 @@ public void run(Hashtable hashTable) throws Exception { // needs to be set first, else throw away dirty/needs paint information stored in previous instance. RepaintManager.setCurrentManager(new VCellClient.CheckThreadViolationRepaintManager()); - DocumentWindowManager currWindowManager = vcellClient.createAndShowGUI(startupDoc); + DocumentWindowManager currWindowManager = VCellClient.this.createAndShowGUI(startupDoc); if (currWindowManager != null) { hashTable.put("currWindowManager", currWindowManager); } @@ -281,16 +233,19 @@ public void run(Hashtable hashTable) throws Exception { //-----use following in BreakPoint conditional before ApplicationLauncher.launchApplication in eclipse // System.setProperty("install4j.runtimeDir","/home/vcell/VCell_Test/.install4j"); // return false; - ApplicationLauncher.launchApplication("127", null, false, null/*new ApplicationLauncher.Callback() { - public void exited(int exitValue) { - DialogUtils.showInfoDialog(windowForComponent, "ApplicationLauncher.launchApplication.exited(), exitValue="+exitValue); - } - - public void prepareShutdown() { - DialogUtils.showInfoDialog(windowForComponent, "ApplicationLauncher.launchApplication.prepareShutdown()"); - } - }*/ - ); + +// ApplicationLauncher.Callback callback1 = new ApplicationLauncher.Callback() { +// public void exited(int exitValue) { +// DialogUtils.showInfoDialog(windowForComponent, "ApplicationLauncher.launchApplication.exited(), exitValue="+exitValue); +// } +// public void prepareShutdown() { +// DialogUtils.showInfoDialog(windowForComponent, "ApplicationLauncher.launchApplication.prepareShutdown()"); +// } +// } + String[] install4jArgs = null; + boolean blocking = false; + ApplicationLauncher.Callback callback = null; + ApplicationLauncher.launchApplication("127", install4jArgs, blocking, callback); } catch (Exception e) { e.printStackTrace(); @@ -306,7 +261,7 @@ public void prepareShutdown() { public void run(Hashtable hashTable) throws Exception { if (clientServerInfo.getUsername() == null) { // we were not supplied login credentials; pop-up dialog - VCellClient.login(vcellClient.getRequestManager(), clientServerInfo, ((DocumentWindowManager)hashTable.get("currWindowManager"))); + VCellClient.this.login(VCellClient.this.getRequestManager(), clientServerInfo, ((DocumentWindowManager)hashTable.get("currWindowManager"))); } } }; @@ -317,17 +272,16 @@ public void run(Hashtable hashTable) throws Exception { if (clientServerInfo.getUsername() != null) { DocumentWindowManager currWindowManager = (DocumentWindowManager)hashTable.get("currWindowManager"); // we were not supplied login credentials; pop-up dialog - vcellClient.getRequestManager().connectToServer(currWindowManager, clientServerInfo); + VCellClient.this.getRequestManager().connectToServer(currWindowManager, clientServerInfo); } } }; AsynchClientTask[] taskArray = new AsynchClientTask[] { task1, task2, task2a, task2b, task3}; ClientTaskDispatcher.dispatch(null, hash, taskArray); - return vcellClient; } -public static void login(final RequestManager requestManager, final ClientServerInfo clientServerInfo, final DocumentWindowManager currWindowManager){ +public void login(final RequestManager requestManager, final ClientServerInfo clientServerInfo, final DocumentWindowManager currWindowManager){ final LoginManager loginManager = new LoginManager(); LoginDelegate loginDelegate = new LoginDelegate() { @@ -350,7 +304,7 @@ public void run(Hashtable hashTable) throws Exception { ConnectionStatus connectionStatus = requestManager.getConnectionStatus(); loginManager.close(); if(connectionStatus.getStatus() != ConnectionStatus.CONNECTED){ - VCellClient.login(requestManager,clientServerInfo, currWindowManager); + VCellClient.this.login(requestManager,clientServerInfo, currWindowManager); } else { ErrorUtils.setLoginInfo(clientServerInfo.getUserLoginInfo()); @@ -363,7 +317,7 @@ public void run(Hashtable hashTable) throws Exception { public void registerRequest() { loginManager.close(); try { - UserRegistrationManager.registrationOperationGUI(requestManager, currWindowManager, clientServerInfo, LoginManager.USERACTION_REGISTER,null); + VCellClient.this.userRegistrationManager.registrationOperationGUI(requestManager, currWindowManager, clientServerInfo, LoginManager.USERACTION_REGISTER,null); } catch (UserCancelException e) { //do nothing } catch (Exception e) { @@ -375,7 +329,7 @@ public void registerRequest() { public void lostPasswordRequest(String userid) { try { ClientServerInfo newClientServerInfo = createClientServerInfo(clientServerInfo,userid,null); - UserRegistrationManager.registrationOperationGUI(requestManager, currWindowManager, newClientServerInfo, LoginManager.USERACTION_LOSTPASSWORD,null); + VCellClient.this.userRegistrationManager.registrationOperationGUI(requestManager, currWindowManager, newClientServerInfo, LoginManager.USERACTION_LOSTPASSWORD,null); } catch (UserCancelException e) { //do nothing } catch (Exception e) { @@ -395,8 +349,7 @@ public void userCancel(){ } - -public static ClientServerInfo createClientServerInfo(ClientServerInfo clientServerInfo,String userid,DigestedPassword digestedPassword){ +public ClientServerInfo createClientServerInfo(ClientServerInfo clientServerInfo,String userid,DigestedPassword digestedPassword){ switch (clientServerInfo.getServerType()) { case SERVER_LOCAL: { return ClientServerInfo.createLocalServerInfo(userid,digestedPassword); diff --git a/vcell-client/src/main/java/cbit/vcell/client/VCellClientMain.java b/vcell-client/src/main/java/cbit/vcell/client/VCellClientMain.java new file mode 100644 index 0000000000..391ba246cf --- /dev/null +++ b/vcell-client/src/main/java/cbit/vcell/client/VCellClientMain.java @@ -0,0 +1,174 @@ +/* + * Copyright (C) 1999-2011 University of Connecticut Health Center + * + * Licensed under the MIT License (the "License"). + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.opensource.org/licenses/mit-license.php + */ + +package cbit.vcell.client; + +import cbit.util.xml.VCLogger; +import cbit.util.xml.XmlUtil; +import cbit.vcell.client.desktop.NetworkProxyPreferences; +import cbit.vcell.client.server.ClientServerInfo; +import cbit.vcell.message.server.bootstrap.client.RemoteProxyVCellConnectionFactory; +import cbit.vcell.mongodb.VCMongoMessage; +import cbit.vcell.resource.*; +import cbit.vcell.xml.XmlHelper; +import com.google.inject.Guice; +import com.google.inject.Injector; +import org.jdom.Document; +import org.vcell.dependency.client.VCellClientModule; +import org.vcell.util.BeanUtils; +import org.vcell.util.document.UserLoginInfo; +import org.vcell.util.document.VCDocument; +import org.vcell.util.document.VCellSoftwareVersion; +import org.vcell.util.logging.ConsoleCapture; +import picocli.CommandLine; +import picocli.CommandLine.Command; +import picocli.CommandLine.Option; +import picocli.CommandLine.Parameters; + +import javax.swing.*; +import java.io.File; +import java.lang.management.ManagementFactory; +import java.util.Arrays; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.Callable; +import java.util.prefs.Preferences; + + +@Command(name = "vcell", version = "vcellclient 1.0", description = "VCell Client") +public class VCellClientMain implements Callable { + + /** + * array of properties required for correct operation + */ + private static final String[] REQUIRED_CLIENT_PROPERTIES = { + PropertyLoader.installationRoot, + PropertyLoader.vcellSoftwareVersion, + }; + public static ArrayBlockingQueue recordedUserEvents = new ArrayBlockingQueue<>(50, true); + @Parameters(description = "optional vcell model file, accepts drag and drop install4j VCell launcher", arity = "0..1") + private final File vcellModelFile = null; + @Option(names = {"--api-host"}, required = true, description = "VCell api server host[:port]") + private String host = System.getProperty(PropertyLoader.vcellServerHost, "vcellapi.cam.uchc.edu"); + @Option(names = {"--userid"}, hidden = true, description = "vcell userid") + private String userid = null; + @Option(names = {"--password"}, hidden = true, description = "vcell password") + private String password = null; + @Option(names = {"-console"}, type = Boolean.class, description = "Install4J parameter, ignored") + private boolean _console = false; + private VCellClient vcellClient; + + + private VCellClientMain() { + } + + /** + * Starts the application. + * + * @param args an array of command-line arguments + */ + public static void main(java.lang.String[] args) { + System.out.println("starting with arguments " + Arrays.asList(args)); + int exitCode = 1; + try { + CommandLine commandLine = new CommandLine(new VCellClientMain()); + exitCode = commandLine.execute(args); + } catch (Throwable t) { + t.printStackTrace(); + } + } + + private static void setProxyConfiguration() { + String proxy_http_host = System.getProperty(NetworkProxyUtils.PROXY_HTTP_HOST); + String proxy_http_port = System.getProperty(NetworkProxyUtils.PROXY_HTTP_PORT); + String proxy_socks_host = System.getProperty(NetworkProxyUtils.PROXY_SOCKS_HOST); + String proxy_socks_port = System.getProperty(NetworkProxyUtils.PROXY_SOCKS_PORT); + String currentProxyHost = (proxy_http_host != null) ? proxy_http_host : proxy_socks_host; + String currentProxyPort = (proxy_http_host != null) ? proxy_http_port : proxy_socks_port; + Preferences prefs = Preferences.userNodeForPackage(RemoteProxyVCellConnectionFactory.class); + NetworkProxyUtils.setProxyProperties(false, null, + prefs.get(NetworkProxyPreferences.prefProxyType, NetworkProxyPreferences.prefProxyType), + currentProxyHost, + currentProxyPort, + prefs.get(NetworkProxyPreferences.prefProxyType, NetworkProxyPreferences.prefProxyType), + prefs.get(NetworkProxyPreferences.prefProxyHost, NetworkProxyPreferences.prefProxyHost), + prefs.get(NetworkProxyPreferences.prefProxyPort, NetworkProxyPreferences.prefProxyPort)); + } + + @Override + public Integer call() throws Exception { + String[] hostParts = this.host.split(":"); + String apihost = hostParts[0]; + int apiport = 443; + if (hostParts.length == 2) { + apiport = Integer.parseInt(hostParts[1]); + } + + PropertyLoader.loadProperties(REQUIRED_CLIENT_PROPERTIES); + Injector injector = Guice.createInjector(new VCellClientModule(apihost, apiport)); + this.vcellClient = injector.getInstance(VCellClient.class); + + Thread dynamicClientPropertiesThread = new Thread(() -> BeanUtils.updateDynamicClientProperties()); + dynamicClientPropertiesThread.setDaemon(false); // non-daemon thread to keep JVM running + dynamicClientPropertiesThread.start(); + + setProxyConfiguration(); + + final boolean IS_DEBUG = ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0; + if (!IS_DEBUG) { + String siteName = VCellSoftwareVersion.fromSystemProperty().getSite().name().toLowerCase(); + ConsoleCapture.getInstance().captureStandardOutAndError(new File(ResourceUtil.getLogDir(), "vcellrun_" + siteName + ".log")); + } + ErrorUtils.setDebug(IS_DEBUG); + + VCDocument initialDocument = null; + if (vcellModelFile != null && vcellModelFile.exists() && vcellModelFile.isFile()) { + initialDocument = startupWithOpen(vcellModelFile); + } + + UserLoginInfo.DigestedPassword digestedPassword = null; + if (password != null && password.length() > 0) { + digestedPassword = new UserLoginInfo.DigestedPassword(password); + } + ClientServerInfo csInfo = ClientServerInfo.createRemoteServerInfo(apihost, apiport, userid, digestedPassword); + + try { + VCMongoMessage.enabled = false; + + vcellClient.startClient(initialDocument, csInfo); + ErrorUtils.setClientServerInfo(csInfo); + + //starting loading libraries + new LibraryLoaderThread(true).start(); + + } catch (Exception exception) { + ErrorUtils.sendRemoteLogMessage(csInfo.getUserLoginInfo(), csInfo + "\nvcell startup failed\n\n" + exception.getMessage()); + JOptionPane.showMessageDialog(null, exception.getMessage(), "Fatal Error", JOptionPane.OK_OPTION); + System.err.println("Exception occurred in main() of VCellApplication"); + exception.printStackTrace(System.out); + throw exception; + } + return 0; + } + + private VCDocument startupWithOpen(File documentFile) { + VCDocument initialDocument = null; + try { + Document xmlDoc = XmlUtil.readXML(documentFile); + String vcmlString = XmlUtil.xmlToString(xmlDoc, false); + java.awt.Component parent = null; + VCLogger vcLogger = new TranslationLogger(parent); + initialDocument = XmlHelper.XMLToDocument(vcLogger, vcmlString); + } catch (Exception e) { + e.printStackTrace(System.out); + JOptionPane.showMessageDialog(null, e.getMessage(), "vcell startup error", JOptionPane.ERROR_MESSAGE); + } + return initialDocument; + } +} diff --git a/vcell-client/src/main/java/cbit/vcell/client/test/VCellClientTest.java b/vcell-client/src/main/java/cbit/vcell/client/test/VCellClientTest.java deleted file mode 100644 index fdba5f2e57..0000000000 --- a/vcell-client/src/main/java/cbit/vcell/client/test/VCellClientTest.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (C) 1999-2011 University of Connecticut Health Center - * - * Licensed under the MIT License (the "License"). - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.opensource.org/licenses/mit-license.php - */ - -package cbit.vcell.client.test; -import java.io.File; -import java.lang.management.ManagementFactory; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.StringTokenizer; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.prefs.Preferences; - -import javax.swing.JOptionPane; - -import org.apache.commons.lang3.ArrayUtils; -import org.jdom.Document; -import org.vcell.util.BeanUtils; -import org.vcell.util.document.UserLoginInfo; -import org.vcell.util.document.VCDocument; -import org.vcell.util.document.VCellSoftwareVersion; -import org.vcell.util.logging.ConsoleCapture; - -import cbit.util.xml.VCLogger; -import cbit.util.xml.XmlUtil; -import cbit.vcell.client.TranslationLogger; -import cbit.vcell.client.VCellClient; -import cbit.vcell.client.desktop.NetworkProxyPreferences; -import cbit.vcell.client.server.ClientServerInfo; -import cbit.vcell.message.server.bootstrap.client.RemoteProxyVCellConnectionFactory; -import cbit.vcell.mongodb.VCMongoMessage; -import cbit.vcell.mongodb.VCMongoMessage.ServiceName; -import cbit.vcell.resource.ErrorUtils; -import cbit.vcell.resource.LibraryLoaderThread; -import cbit.vcell.resource.NetworkProxyUtils; -import cbit.vcell.resource.PropertyLoader; -import cbit.vcell.resource.PythonSupport; -import cbit.vcell.resource.PythonSupport.PythonPackage; -import cbit.vcell.resource.ResourceUtil; -import cbit.vcell.xml.XmlHelper; -/** - * Insert the type's description here. - * Creation date: (5/3/2004 12:02:01 PM) - * @author: Ion Moraru - */ -public class VCellClientTest { - - - private static VCellClient vcellClient = null; - - public static VCellClient getVCellClient() { - return vcellClient; - } - - public static ArrayBlockingQueue recordedUserEvents = new ArrayBlockingQueue<>(50, true); -/** - * Starts the application. - * @param args an array of command-line arguments - */ -public static void main(java.lang.String[] args) { - - System.out.println("raw CLI arguments = "+Arrays.asList(args)); - - new Thread(new Runnable() { - @Override - public void run() { - BeanUtils.updateDynamicClientProperties(); - } - }).start(); - - //check synchronize Proxy prefs, Proxy Properties - Preferences prefs = Preferences.userNodeForPackage(RemoteProxyVCellConnectionFactory.class); - Boolean bHttp = - (System.getProperty(NetworkProxyUtils.PROXY_HTTP_HOST)==null && System.getProperty(NetworkProxyUtils.PROXY_SOCKS_HOST)==null?null:System.getProperty(NetworkProxyUtils.PROXY_HTTP_HOST) != null); - String currentProxyHost = - (bHttp==null?null:(bHttp?System.getProperty(NetworkProxyUtils.PROXY_HTTP_HOST):System.getProperty(NetworkProxyUtils.PROXY_SOCKS_HOST))); - String currentProxyPort= - (bHttp==null?null:(bHttp?System.getProperty(NetworkProxyUtils.PROXY_HTTP_PORT):System.getProperty(NetworkProxyUtils.PROXY_SOCKS_PORT))); - NetworkProxyUtils.setProxyProperties(false,null, - prefs.get(NetworkProxyPreferences.prefProxyType,NetworkProxyPreferences.prefProxyType), - currentProxyHost,currentProxyPort, - prefs.get(NetworkProxyPreferences.prefProxyType,NetworkProxyPreferences.prefProxyType), - prefs.get(NetworkProxyPreferences.prefProxyHost,NetworkProxyPreferences.prefProxyHost),prefs.get(NetworkProxyPreferences.prefProxyPort,NetworkProxyPreferences.prefProxyPort)); - - final boolean IS_DEBUG = ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0; - if (!IS_DEBUG) { - String siteName = VCellSoftwareVersion.fromSystemProperty().getSite().name().toLowerCase(); - ConsoleCapture.getInstance().captureStandardOutAndError(new File(ResourceUtil.getLogDir(),"vcellrun_"+siteName+".log")); - } -// Logging.init(); - ErrorUtils.setDebug(IS_DEBUG); - if(args != null && args.length >= 1 && args[0].equals("-console")){//remove install4j parameter - List newArgs = new ArrayList(); - newArgs.addAll(Arrays.asList(args)); - newArgs.remove(0); - args = newArgs.toArray(new String[0]); - } - StringBuffer stringBuffer = new StringBuffer(); - for (int i = 0; i < args.length; i++){ - stringBuffer.append("arg"+i+"=\""+args[i]+"\" "); - } - System.out.println("starting with arguments ["+stringBuffer+"]"); - System.out.println("Running under Java major version: ONE point "+ ResourceUtil.getJavaVersion().toString()+". Specifically: Java "+(System.getProperty("java.version"))+ - ", published by "+(System.getProperty("java.vendor"))+", on the "+ (System.getProperty("os.arch"))+" architecture running version "+(System.getProperty("os.version"))+ - " of the "+(System.getProperty("os.name"))+" operating system"); - - ClientServerInfo csInfo = null; - String hoststr = System.getProperty(PropertyLoader.vcellServerHost); - String[] hosts = null; - if (hoststr != null) { - StringTokenizer st = new StringTokenizer(hoststr," ,;"); - if (st.countTokens() >= 1) { - hosts = new String[st.countTokens()]; - int count = 0; - while (st.hasMoreTokens()) { - hosts[count ++] = st.nextToken(); - } - } - } - if (hosts == null) { - hosts = new String[1]; - } - String user = null; - String password = null; - VCDocument initialDocument = null; - if (args.length == 3) { - hosts[0] = args[0]; - user = args[1]; - password = args[2]; - }else if (args.length==0){ - // this is ok - }else if (args.length==1){ - //Check if arg is drag-n-drop file or a 'hostname' - try{ - //drag and drop file on install4j VCell launcher will pass filepath as single arg to VCell - File openThisVCellFile = new File(args[0]); - if(openThisVCellFile.exists() && openThisVCellFile.isFile()){ - initialDocument = startupWithOpen(args[0]); - } - }catch(Exception e){ - e.printStackTrace(); - //continue to hostname check - } - //If startup file not exist assume arg is a hostname - if(initialDocument == null){ - hosts[0] = args[0]; - } - //If install4j drag-n-drop, hosts[0] stays null and host is assumed to be loaded from a client property - - }else if (args.length==2 && args[0].equals("-open")){ -// hosts[0] = "-local"; - initialDocument = startupWithOpen(args[1]); - }else{ - System.out.println("usage: VCellClientTest ( ((-local|host[:port]) [userid password]) | ([-open] filename) )"); - System.exit(1); - } - boolean bLocal = false; - if (hosts[0]!=null && hosts[0].equalsIgnoreCase("-local")){ - bLocal = true; - } - if (bLocal) { - csInfo = ClientServerInfo.createLocalServerInfo(user, (password==null || password.length()==0?null:new UserLoginInfo.DigestedPassword(password))); - } else { - String[] hostParts = hosts[0].split(":"); - String apihost = hostParts[0]; - int apiport = Integer.parseInt(hostParts[1]); - csInfo = ClientServerInfo.createRemoteServerInfo(apihost, apiport, user,(password==null || password.length()==0?null:new UserLoginInfo.DigestedPassword(password))); - } - try { - if (bLocal){ - PropertyLoader.loadProperties(ArrayUtils.addAll(REQUIRED_CLIENT_PROPERTIES,REQUIRED_LOCAL_PROPERTIES) ); - try { - VCMongoMessage.enabled = true; - VCMongoMessage.serviceStartup(ServiceName.client,null,null); - PropertyLoader.sendErrorsToMongo(); - }catch (Exception e){ - System.out.println("failed to start Mongo logging"); - } - }else{ - PropertyLoader.loadProperties(REQUIRED_CLIENT_PROPERTIES); - VCMongoMessage.enabled = false; - } - - //call in main thread, since it's quick and not necessarily thread safe - vcellClient = VCellClient.startClient(initialDocument, csInfo); - ErrorUtils.setClientServerInfo(csInfo); - -// VCellClientDataService vcellClientDataService = new VCellClientDataServiceImpl(vcellClient); -// VCellProxyServer.startVCellVisitDataServerThread(vcellClientDataService); - - - //starting loading libraries - new LibraryLoaderThread(true).start( ); - - try { - PythonSupport.verifyInstallation(PythonPackage.values()); - }catch (Exception e){ - e.printStackTrace(System.out); - } - -// SimulationService.Iface simService = new SimulationServiceImpl(); -// VCellIJServer.startVCellVisitDataServerThread(simService, false); - - } catch (Throwable exception) { - ErrorUtils.sendRemoteLogMessage(csInfo.getUserLoginInfo(),csInfo.toString()+"\nvcell startup failed\n\n" + exception.getMessage()); - JOptionPane.showMessageDialog(null, exception.getMessage(), "Fatal Error",JOptionPane.OK_OPTION); - System.err.println("Exception occurred in main() of VCellApplication"); - exception.printStackTrace(System.out); - } -} - - -private static VCDocument startupWithOpen(String fileName) { - VCDocument initialDocument = null; - try { - Document xmlDoc = XmlUtil.readXML(new File(fileName)); - String vcmlString = XmlUtil.xmlToString(xmlDoc, false); - java.awt.Component parent = null; - VCLogger vcLogger = new TranslationLogger(parent); - initialDocument = XmlHelper.XMLToDocument(vcLogger,vcmlString); - }catch (Exception e){ - e.printStackTrace(System.out); - JOptionPane.showMessageDialog(null,e.getMessage(),"vcell startup error",JOptionPane.ERROR_MESSAGE); - } - return initialDocument; -} - -/** - * array of properties required for correct operation - */ -private static final String REQUIRED_CLIENT_PROPERTIES[] = { - PropertyLoader.installationRoot, - PropertyLoader.vcellSoftwareVersion, -}; - -/** - * array of properties required for correct local operation - */ -private static final String REQUIRED_LOCAL_PROPERTIES[] = { - PropertyLoader.primarySimDataDirInternalProperty, - PropertyLoader.secondarySimDataDirInternalProperty, - PropertyLoader.dbPasswordValue, - PropertyLoader.dbUserid, - PropertyLoader.dbDriverName, - PropertyLoader.dbConnectURL, - PropertyLoader.vcellServerIDProperty, - PropertyLoader.mongodbDatabase, - PropertyLoader.mongodbHostInternal, -// PropertyLoader.mongodbLoggingCollection, - PropertyLoader.mongodbPortInternal - -}; -} diff --git a/vcell-client/src/main/java/org/vcell/dependency/client/VCellClientModule.java b/vcell-client/src/main/java/org/vcell/dependency/client/VCellClientModule.java new file mode 100644 index 0000000000..8892df8cba --- /dev/null +++ b/vcell-client/src/main/java/org/vcell/dependency/client/VCellClientModule.java @@ -0,0 +1,51 @@ +package org.vcell.dependency.client; + +import cbit.vcell.message.server.bootstrap.client.RemoteProxyVCellConnectionFactory; +import cbit.vcell.server.VCellConnectionFactory; +import cbit.vcell.simdata.ExternalDataIdentifierService; +import com.google.inject.AbstractModule; +import com.google.inject.name.Names; +import org.vcell.DependencyConstants; +import org.vcell.service.registration.RegistrationService; +import org.vcell.service.registration.remote.RemoteRegistrationService; +import org.vcell.util.document.ExternalDataIdentifier; +import org.vcell.util.document.User; + +import java.util.HashMap; +import java.util.Vector; + +public class VCellClientModule extends AbstractModule { + + private final String apiHost; + private final int apiPort; + + public VCellClientModule(String apiHost, int apiPort) { + this.apiHost = apiHost; + this.apiPort = apiPort; + } + + public interface UnimplementedService { + } + + public static class UnimplementedExternalDataIdentifierService implements ExternalDataIdentifierService, UnimplementedService { + @Override + public HashMap> getAllExternalDataIdentifiers() { + throw new UnsupportedOperationException("Field datda operations Not implemented for client-side simulations"); + } + } + + + @Override + protected void configure() { + // only one implementation, to break compile-time cyclic dependency (vcell-core -> vcell-service) + bind(ExternalDataIdentifierService.class).toInstance(new UnimplementedExternalDataIdentifierService()); + + bind(VCellConnectionFactory.class).to(RemoteProxyVCellConnectionFactory.class).asEagerSingleton(); + + // RegistrationService interface is not clean - mixes new registration with updates - is there another way? + bind(RegistrationService.class).toInstance(new RemoteRegistrationService()); // used on remote client. + + bind(String.class).annotatedWith(Names.named(DependencyConstants.VCELL_API_HOST)).toInstance(apiHost); + bind(Integer.class).annotatedWith(Names.named(DependencyConstants.VCELL_API_PORT)).toInstance(apiPort); + } +} diff --git a/vcell-client/src/main/java/org/vcell/util/gui/DialogUtils.java b/vcell-client/src/main/java/org/vcell/util/gui/DialogUtils.java index 39bb4db7eb..c07564822d 100644 --- a/vcell-client/src/main/java/org/vcell/util/gui/DialogUtils.java +++ b/vcell-client/src/main/java/org/vcell/util/gui/DialogUtils.java @@ -56,6 +56,7 @@ import javax.swing.event.ListSelectionListener; import cbit.vcell.client.VCellClient; +import cbit.vcell.client.VCellClientMain; import org.vcell.client.logicalwindow.LWContainerHandle; import org.vcell.client.logicalwindow.LWDialog; import org.vcell.client.logicalwindow.LWNamespace; @@ -792,9 +793,9 @@ private static class ContextCarrierException extends RuntimeException { public static String collectRecordedUserEvents(){ String content = ""; - if(VCellClientTest.recordedUserEvents != null && VCellClientTest.recordedUserEvents.size() > 0){ + if(VCellClientMain.recordedUserEvents != null && VCellClientMain.recordedUserEvents.size() > 0){ content+= "-----Recorded User Events-----"+BeanUtils.PLAINTEXT_EMAIL_NEWLINE; - Iterator iter = VCellClientTest.recordedUserEvents.iterator(); + Iterator iter = VCellClientMain.recordedUserEvents.iterator(); while(iter.hasNext()){ content+= iter.next()+BeanUtils.PLAINTEXT_EMAIL_NEWLINE; } diff --git a/vcell-core/pom.xml b/vcell-core/pom.xml index b04e388bbc..73fc7f4782 100644 --- a/vcell-core/pom.xml +++ b/vcell-core/pom.xml @@ -111,6 +111,11 @@ vcell-apiclient ${project.version} + + com.google.inject + guice + 7.0.0 + javax.media.jai diff --git a/vcell-core/src/main/java/cbit/vcell/client/server/ClientServerManager.java b/vcell-core/src/main/java/cbit/vcell/client/server/ClientServerManager.java index e1f8fd593f..a4ad853e5f 100644 --- a/vcell-core/src/main/java/cbit/vcell/client/server/ClientServerManager.java +++ b/vcell-core/src/main/java/cbit/vcell/client/server/ClientServerManager.java @@ -23,7 +23,6 @@ import cbit.vcell.resource.PropertyLoader; import cbit.vcell.server.*; import cbit.vcell.simdata.VCDataManager; -import com.google.inject.Inject; import org.apache.http.HttpStatus; import org.apache.http.client.HttpResponseException; import org.apache.logging.log4j.LogManager; @@ -43,11 +42,8 @@ */ public class ClientServerManager implements SessionManager,DataSetControllerProvider { private final static Logger lg = LogManager.getLogger(ClientServerManager.class); + private final VCellConnectionFactory vcellConnectionFactory; - @Inject - private LocalVCellConnectionService localVCellConnectionService; - - public interface InteractiveContext { void showErrorDialog(String errorMessage); @@ -221,7 +217,8 @@ public synchronized void addPropertyChangeListener(java.beans.PropertyChangeList getPropertyChange().addPropertyChangeListener(listener); } -public ClientServerManager(ClientServerInfo clientServerInfo, InteractiveContextDefaultProvider defaultInteractiveContextProvider) { +public ClientServerManager(VCellConnectionFactory vcellConnectionFactory, ClientServerInfo clientServerInfo, InteractiveContextDefaultProvider defaultInteractiveContextProvider) { + this.vcellConnectionFactory = vcellConnectionFactory; this.clientServerInfo = clientServerInfo; this.defaultInteractiveContextProvider = defaultInteractiveContextProvider; } @@ -377,32 +374,13 @@ private VCellConnection connectToServer(InteractiveContext requester,boolean bSh VCellThreadChecker.checkRemoteInvocation(); VCellConnection newVCellConnection = null; - VCellConnectionFactory vcConnFactory = null; String badConnStr = ""; try { try { - switch (getClientServerInfo().getServerType()) { - case SERVER_REMOTE: { - String apihost = getClientServerInfo().getApihost(); - Integer apiport = getClientServerInfo().getApiport(); - try { - badConnStr += apihost+":"+apiport; - vcConnFactory = new RemoteProxyVCellConnectionFactory(apihost, apiport, getClientServerInfo().getUserLoginInfo()); - setConnectionStatus(new ClientConnectionStatus(getClientServerInfo().getUsername(), apihost, apiport, ConnectionStatus.INITIALIZING)); - newVCellConnection = vcConnFactory.createVCellConnection(); - } catch (AuthenticationException ex) { - throw ex; - } - break; - } - case SERVER_LOCAL: { - new PropertyLoader(); - vcConnFactory = localVCellConnectionService.getLocalVCellConnectionFactory(getClientServerInfo().getUserLoginInfo()); - setConnectionStatus(new ClientConnectionStatus(getClientServerInfo().getUsername(), null, null, ConnectionStatus.INITIALIZING)); - newVCellConnection = vcConnFactory.createVCellConnection(); - break; - } - } + String apihost = getClientServerInfo().getApihost(); + Integer apiport = getClientServerInfo().getApiport(); + setConnectionStatus(new ClientConnectionStatus(getClientServerInfo().getUsername(), apihost, apiport, ConnectionStatus.INITIALIZING)); + newVCellConnection = vcellConnectionFactory.createVCellConnection(getClientServerInfo().getUserLoginInfo()); requester.clearConnectWarning(); reconnectStat = ReconnectStatus.NOT; }catch(Exception e) { diff --git a/vcell-core/src/main/java/cbit/vcell/message/server/bootstrap/client/RemoteProxyVCellConnectionFactory.java b/vcell-core/src/main/java/cbit/vcell/message/server/bootstrap/client/RemoteProxyVCellConnectionFactory.java index 13aa083650..7feb0c5f74 100644 --- a/vcell-core/src/main/java/cbit/vcell/message/server/bootstrap/client/RemoteProxyVCellConnectionFactory.java +++ b/vcell-core/src/main/java/cbit/vcell/message/server/bootstrap/client/RemoteProxyVCellConnectionFactory.java @@ -10,47 +10,37 @@ package cbit.vcell.message.server.bootstrap.client; -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.atomic.AtomicLong; - +import cbit.rmi.event.*; +import cbit.vcell.message.VCRpcRequest; +import cbit.vcell.message.VCellQueue; import cbit.vcell.resource.PropertyLoader; -import org.apache.http.client.ClientProtocolException; +import cbit.vcell.server.ConnectionException; +import cbit.vcell.server.VCellConnection; +import cbit.vcell.server.VCellConnectionFactory; +import com.google.gson.Gson; +import com.google.inject.Inject; +import com.google.inject.name.Named; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.vcell.DependencyConstants; import org.vcell.api.client.VCellApiClient; import org.vcell.api.client.VCellApiClient.RpcDestination; import org.vcell.api.client.VCellApiRpcRequest; import org.vcell.api.common.AccessTokenRepresentation; -import org.vcell.api.common.events.BroadcastEventRepresentation; -import org.vcell.api.common.events.DataJobEventRepresentation; -import org.vcell.api.common.events.EventWrapper; -import org.vcell.api.common.events.ExportEventRepresentation; -import org.vcell.api.common.events.SimulationJobStatusEventRepresentation; -import org.vcell.util.AuthenticationException; +import org.vcell.api.common.events.*; import org.vcell.util.document.KeyValue; import org.vcell.util.document.User; import org.vcell.util.document.UserLoginInfo; -import com.google.gson.Gson; - -import cbit.rmi.event.DataJobEvent; -import cbit.rmi.event.ExportEvent; -import cbit.rmi.event.MessageData; -import cbit.rmi.event.MessageEvent; -import cbit.rmi.event.SimulationJobStatusEvent; -import cbit.rmi.event.VCellMessageEvent; -import cbit.vcell.message.VCRpcRequest; -import cbit.vcell.message.VCellQueue; -import cbit.vcell.server.ConnectionException; -import cbit.vcell.server.VCellConnection; -import cbit.vcell.server.VCellConnectionFactory; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; public class RemoteProxyVCellConnectionFactory implements VCellConnectionFactory { @@ -75,7 +65,7 @@ public class RemoteProxyVCellConnectionFactory implements VCellConnectionFactory Arrays.sort(temp); vcellguestAllowed = Collections.unmodifiableList(Arrays.asList(temp)); } - private UserLoginInfo userLoginInfo; + private final String apihost; private final Integer apiport; private final VCellApiClient vcellApiClient; @@ -171,28 +161,29 @@ public RemoteProxyException(String message, Exception e) { } -public RemoteProxyVCellConnectionFactory(String apihost, Integer apiport, UserLoginInfo userLoginInfo) throws ClientProtocolException, IOException { - this.apihost = apihost; - this.apiport = apiport; - this.userLoginInfo = userLoginInfo; - boolean bIgnoreCertProblems = PropertyLoader.getBooleanProperty(PropertyLoader.sslIgnoreCertProblems,false); - boolean bIgnoreHostMismatch = PropertyLoader.getBooleanProperty(PropertyLoader.sslIgnoreHostMismatch,false);; - try { - this.vcellApiClient = new VCellApiClient(this.apihost, this.apiport, bIgnoreCertProblems, bIgnoreHostMismatch); - } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { - throw new RuntimeException("VCellApiClient configuration exception: "+e.getMessage(),e); + @Inject + public RemoteProxyVCellConnectionFactory( + @Named(DependencyConstants.VCELL_API_HOST) String apihost, + @Named(DependencyConstants.VCELL_API_PORT) Integer apiport) { + this.apihost = apihost; + this.apiport = apiport; + boolean bIgnoreCertProblems = PropertyLoader.getBooleanProperty(PropertyLoader.sslIgnoreCertProblems,false); + boolean bIgnoreHostMismatch = PropertyLoader.getBooleanProperty(PropertyLoader.sslIgnoreHostMismatch,false);; + try { + this.vcellApiClient = new VCellApiClient(this.apihost, this.apiport, bIgnoreCertProblems, bIgnoreHostMismatch); + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { + throw new RuntimeException("VCellApiClient configuration exception: "+e.getMessage(),e); + } } - - AccessTokenRepresentation accessTokenRep = this.vcellApiClient.authenticate(userLoginInfo.getUserName(), userLoginInfo.getDigestedPassword().getString(),true); - userLoginInfo.setUser(new User(accessTokenRep.userId, new KeyValue(accessTokenRep.getUserKey()))); -} -public void changeUser(UserLoginInfo userLoginInfo) { - this.userLoginInfo = userLoginInfo; -} - -public VCellConnection createVCellConnection() throws AuthenticationException, ConnectionException { - return new LocalVCellConnectionMessaging(userLoginInfo,rpcSender); +public VCellConnection createVCellConnection(UserLoginInfo userLoginInfo) throws ConnectionException { + try { + AccessTokenRepresentation accessTokenRep = this.vcellApiClient.authenticate(userLoginInfo.getUserName(), userLoginInfo.getDigestedPassword().getString(),true); + userLoginInfo.setUser(new User(accessTokenRep.userId, new KeyValue(accessTokenRep.getUserKey()))); + return new LocalVCellConnectionMessaging(userLoginInfo,rpcSender); + } catch (IOException e) { + throw new ConnectionException("failed to connect: "+e.getMessage(), e); + } } public static String getVCellSoftwareVersion(String apihost, Integer apiport) { diff --git a/vcell-core/src/main/java/cbit/vcell/server/LocalVCellConnectionService.java b/vcell-core/src/main/java/cbit/vcell/server/LocalVCellConnectionService.java index 7837b0b3d4..7741730c93 100644 --- a/vcell-core/src/main/java/cbit/vcell/server/LocalVCellConnectionService.java +++ b/vcell-core/src/main/java/cbit/vcell/server/LocalVCellConnectionService.java @@ -3,5 +3,5 @@ import org.vcell.util.document.UserLoginInfo; public interface LocalVCellConnectionService { - VCellConnectionFactory getLocalVCellConnectionFactory(UserLoginInfo userLoginInfo); + VCellConnectionFactory getLocalVCellConnectionFactory(); } diff --git a/vcell-core/src/main/java/cbit/vcell/server/VCellConnectionFactory.java b/vcell-core/src/main/java/cbit/vcell/server/VCellConnectionFactory.java index dafbc35ba8..7203d766f9 100644 --- a/vcell-core/src/main/java/cbit/vcell/server/VCellConnectionFactory.java +++ b/vcell-core/src/main/java/cbit/vcell/server/VCellConnectionFactory.java @@ -13,20 +13,8 @@ import org.vcell.util.AuthenticationException; import org.vcell.util.document.UserLoginInfo; -/** - * This type was created in VisualAge. - */ +import java.io.IOException; + public interface VCellConnectionFactory { -/** - * Insert the method's description here. - * Creation date: (8/9/2001 12:02:55 PM) - * @param userID java.lang.String - * @param password java.lang.String - */ -void changeUser(UserLoginInfo userLoginInfo); -/** - * This method was created in VisualAge. - * @return cbit.vcell.server.VCellConnection - */ -VCellConnection createVCellConnection() throws ConnectionException, AuthenticationException; + VCellConnection createVCellConnection(UserLoginInfo userLoginInfo) throws ConnectionException, AuthenticationException, IOException; } diff --git a/vcell-core/src/main/java/org/vcell/DependencyConstants.java b/vcell-core/src/main/java/org/vcell/DependencyConstants.java new file mode 100644 index 0000000000..81ea518d6b --- /dev/null +++ b/vcell-core/src/main/java/org/vcell/DependencyConstants.java @@ -0,0 +1,6 @@ +package org.vcell; + +public class DependencyConstants { + public static final String VCELL_API_PORT = "VCELL_API_PORT"; + public static final String VCELL_API_HOST = "VCELL_API_HOST"; +} diff --git a/vcell-core/src/test/java/cbit/vcell/message/server/bootstrap/client/RemoteProxyVCellConnectionFactoryTest.java b/vcell-core/src/test/java/cbit/vcell/message/server/bootstrap/client/RemoteProxyVCellConnectionFactoryTest.java index a38916bfae..d73bfd9be3 100644 --- a/vcell-core/src/test/java/cbit/vcell/message/server/bootstrap/client/RemoteProxyVCellConnectionFactoryTest.java +++ b/vcell-core/src/test/java/cbit/vcell/message/server/bootstrap/client/RemoteProxyVCellConnectionFactoryTest.java @@ -33,9 +33,9 @@ public class RemoteProxyVCellConnectionFactoryTest { @Before public void setUp() throws Exception { UserLoginInfo userLoginInfo = new UserLoginInfo("schaff",new DigestedPassword("xxxxxxx")); - factory = new RemoteProxyVCellConnectionFactory("localhost", 8099, userLoginInfo); + factory = new RemoteProxyVCellConnectionFactory("localhost", 8099); apiClient = factory.getVCellApiClient(); - vcConn = factory.createVCellConnection(); + vcConn = factory.createVCellConnection(userLoginInfo); } @After diff --git a/vcell-core/src/test/java/org/vcell/core/DependencyInjectionTest.java b/vcell-core/src/test/java/org/vcell/core/DependencyInjectionTest.java new file mode 100644 index 0000000000..a7809dcfa1 --- /dev/null +++ b/vcell-core/src/test/java/org/vcell/core/DependencyInjectionTest.java @@ -0,0 +1,171 @@ +package org.vcell.core; + + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Inject; +import com.google.inject.Injector; +import org.junit.Assert; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.vcell.test.Fast; + +@Category(Fast.class) +public class DependencyInjectionTest { + interface TestService { + int add(int a, int b); + } + + public static class TestServiceImpl implements TestService { + @Override + public int add(int a, int b) { + return a + b; + } + } + + static class TestApplicationDelayedRunner { + + private final TestService testService; + + @Inject + public TestApplicationDelayedRunner(TestService testService) { + this.testService = testService; + } + + public int add(int a, int b) { + return new TestApplication(testService).add(a, b); + } + } + + static class TestApplicationTransitiveRunner { + @Inject + TestService testService; + + public void setTestService(TestService testService) { + this.testService = testService; + } + + public int add(int a, int b) { + return testService.add(a, b); + } + } + + static class TestApplicationTransitiveImplicitRunner { + + @Inject + TestApplication testApplication; + + public void setTestApplication(TestApplication testApplication) { + this.testApplication = testApplication; + } + + public int add(int a, int b) { + return testApplication.add(a, b); + } + } + + static class TestApplication { + @Inject + TestService testService; + + @Inject + public TestApplication(TestService testService) { + this.testService = testService; + } + + public int add(int a, int b) { + return testService.add(a, b); + } + } + + static class TestModule extends AbstractModule { + @Override + public void configure() { + bind(TestService.class).to(TestServiceImpl.class); + requestStaticInjection(TestApplicationDelayedRunner.class); + } + + } + + @Test + public void testSimple() { + Injector injector = Guice.createInjector(new TestModule()); + TestService testService = injector.getInstance(TestService.class); + Assert.assertTrue("expecting to return 3", testService.add(1,2) == 3); + Assert.assertNotNull(injector); + } + + @Test + public void testFieldInjectionFromInjector() { + Injector injector = Guice.createInjector(new TestModule()); + TestService testService = injector.getInstance(TestService.class); + TestApplication testApplication = injector.getInstance(TestApplication.class); + Assert.assertTrue("expecting to return 3", testApplication.add(1,2) == 3); + Assert.assertNotNull(injector); + } + + @Test + public void testFieldInjectionFromConstructor() { + Injector injector = Guice.createInjector(new TestModule()); + TestService testService = injector.getInstance(TestService.class); + TestApplication testApplication = new TestApplication(new TestServiceImpl()); + Assert.assertTrue("expecting to return 3", testApplication.add(1,2) == 3); + Assert.assertNotNull(injector); + } + + @Test + public void testDelayedFieldInjectionFromInjector() { + Injector injector = Guice.createInjector(new TestModule()); + TestService testService = injector.getInstance(TestService.class); + TestApplicationDelayedRunner testApplication = injector.getInstance(TestApplicationDelayedRunner.class); + Assert.assertTrue("expecting to return 3", testApplication.add(1,2) == 3); + Assert.assertNotNull(injector); + } + + @Test(expected = NullPointerException.class) + public void testDelayedFieldInjectionFromConstructor_shouldFail() { + Injector injector = Guice.createInjector(new TestModule()); + TestApplicationDelayedRunner testApplication = new TestApplicationDelayedRunner(null); + Assert.assertTrue("expecting to return 3", testApplication.add(1,2) == 3); + Assert.assertNotNull(injector); + } + + @Test + public void testTransitiveFieldInjectionFromInjector() { + Injector injector = Guice.createInjector(new TestModule()); + TestService testService = injector.getInstance(TestService.class); + TestApplicationTransitiveRunner testApplication = injector.getInstance(TestApplicationTransitiveRunner.class); + Assert.assertTrue("expecting to return 3", testApplication.add(1,2) == 3); + Assert.assertNotNull(injector); + } + + @Test(expected = NullPointerException.class) + public void testTransitiveFieldInjectionFromConstructor_shouldFail() { + Injector injector = Guice.createInjector(new TestModule()); + TestService testService = injector.getInstance(TestService.class); + TestApplicationTransitiveRunner testApplication = new TestApplicationTransitiveRunner(); + Assert.assertTrue("expecting to return 3", testApplication.add(1,2) == 3); + Assert.assertNotNull(injector); + } + + @Test + public void testTransitiveImplicitFieldInjectionFromInjector() { + Injector injector = Guice.createInjector(new TestModule()); + TestService testService = injector.getInstance(TestService.class); + TestApplicationTransitiveImplicitRunner testApplication = injector.getInstance(TestApplicationTransitiveImplicitRunner.class); + Assert.assertTrue("expecting to return 3", testApplication.add(1,2) == 3); + Assert.assertNotNull(injector); + } + + @Test(expected = NullPointerException.class) + public void testTransitiveImplicitFieldInjectionFromConstructor_shouldFail() { + Injector injector = Guice.createInjector(new TestModule()); + TestService testService = injector.getInstance(TestService.class); + TestApplicationTransitiveImplicitRunner testApplication = new TestApplicationTransitiveImplicitRunner(); + Assert.assertTrue("expecting to return 3", testApplication.add(1,2) == 3); + Assert.assertNotNull(injector); + } + + + +} diff --git a/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/HtcSimulationWorker.java b/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/HtcSimulationWorker.java index 6dc7c6f37f..b25df8f1c3 100644 --- a/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/HtcSimulationWorker.java +++ b/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/HtcSimulationWorker.java @@ -19,16 +19,11 @@ import cbit.vcell.message.messages.WorkerEventMessage; import cbit.vcell.message.server.ManageUtils; import cbit.vcell.message.server.ServerMessagingDelegate; -import cbit.vcell.message.server.ServiceInstanceStatus; -import cbit.vcell.message.server.ServiceProvider; import cbit.vcell.message.server.batch.opt.OptimizationBatchServer; -import cbit.vcell.message.server.bootstrap.ServiceType; import cbit.vcell.message.server.cmd.CommandService.CommandOutput; import cbit.vcell.message.server.htc.HtcProxy; import cbit.vcell.message.server.htc.slurm.SlurmProxy; import cbit.vcell.messaging.server.SimulationTask; -import cbit.vcell.mongodb.VCMongoMessage; -import cbit.vcell.mongodb.VCMongoMessage.ServiceName; import cbit.vcell.resource.OperatingSystemInfo; import cbit.vcell.resource.PropertyLoader; import cbit.vcell.resource.ResourceUtil; @@ -48,19 +43,18 @@ import cbit.vcell.solvers.ExecutableCommand; import cbit.vcell.xml.XmlHelper; import cbit.vcell.xml.XmlParseException; +import com.google.inject.Guice; +import com.google.inject.Injector; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.vcell.util.DataAccessException; +import org.vcell.dependency.server.VCellServerModule; import org.vcell.util.document.KeyValue; import org.vcell.util.document.User; -import org.vcell.util.document.VCellServerID; import org.vcell.util.exe.ExecutableException; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; -import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.*; @@ -69,7 +63,12 @@ * Creation date: (10/25/2001 4:14:09 PM) * @author: Jim Schaff */ -public class HtcSimulationWorker extends ServiceProvider implements HtcProxy.HtcProxyFactory { +public class HtcSimulationWorker implements HtcProxy.HtcProxyFactory { + + public static final Logger lg = LogManager.getLogger(HtcSimulationWorker.class); + + private VCMessagingService vcMessagingService_int = null; + private VCMessagingService vcMessagingService_sim = null; private HtcProxy htcProxy = null; @@ -79,12 +78,21 @@ public class HtcSimulationWorker extends ServiceProvider implements HtcProxy.Htc private VCMessageSession messageProducer_sim = null; private VCMessageSession messageProducer_int = null; private VCPooledQueueConsumer pooledQueueConsumer_int = null; - public static Logger lg = LogManager.getLogger(HtcSimulationWorker.class); -public HtcSimulationWorker(HtcProxy htcProxy, VCMessagingService vcMessagingService_int, VCMessagingService vcMessagingService_sim, ServiceInstanceStatus serviceInstanceStatus, boolean bSlaveMode) throws DataAccessException, FileNotFoundException, UnknownHostException { - super(vcMessagingService_int, vcMessagingService_sim, serviceInstanceStatus, bSlaveMode); - this.htcProxy = htcProxy; +public HtcSimulationWorker() { + this.htcProxy = SlurmProxy.createRemoteProxy(); + + VCMessagingService vcMessagingService_int = new VCMessagingServiceActiveMQ(); + String jmshost_int = PropertyLoader.getRequiredProperty(PropertyLoader.jmsIntHostInternal); + int jmsport_int = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.jmsIntPortInternal)); + this.vcMessagingService_int.setConfiguration(new ServerMessagingDelegate(), jmshost_int, jmsport_int); + + VCMessagingService vcMessagingService_sim = new VCMessagingServiceActiveMQ(); + String jmshost_sim = PropertyLoader.getRequiredProperty(PropertyLoader.jmsSimHostInternal); + int jmsport_sim = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.jmsSimPortInternal)); + this.vcMessagingService_sim.setConfiguration(new ServerMessagingDelegate(), jmshost_sim, jmsport_sim); + this.optimizationBatchServer = new OptimizationBatchServer(this); } @@ -602,46 +610,22 @@ private HtcJobID submit2PBS(SimulationTask simTask, HtcProxy clonedHtcProxy, Pos return jobid; } -@Override -public void stopService(){ - this.pooledQueueConsumer_int.shutdownAndAwaitTermination(); - super.stopService(); -} - /** * Starts the application. * @param args an array of command-line arguments */ -public static void main(java.lang.String[] args) { - OperatingSystemInfo.getInstance(); - - if (args.length != 0) { - System.out.println("No arguments expected: " + HtcSimulationWorker.class.getName()); - System.exit(1); - } - +public static void main(String[] args) throws IOException { try { - PropertyLoader.loadProperties(REQUIRED_SERVICE_PROPERTIES); - - HtcProxy htcProxy = SlurmProxy.createRemoteProxy(); - - int serviceOrdinal = 0; - VCMongoMessage.serviceStartup(ServiceName.pbsWorker, new Integer(serviceOrdinal), args); - - ServiceInstanceStatus serviceInstanceStatus = new ServiceInstanceStatus(VCellServerID.getSystemServerID(), - ServiceType.PBSCOMPUTE, serviceOrdinal, ManageUtils.getHostName(), new Date(), true); + if (args.length != 0) { + System.out.println("No arguments expected: " + HtcSimulationWorker.class.getName()); + System.exit(1); + } - VCMessagingService vcMessagingService_int = new VCMessagingServiceActiveMQ(); - String jmshost_int = PropertyLoader.getRequiredProperty(PropertyLoader.jmsIntHostInternal); - int jmsport_int = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.jmsIntPortInternal)); - vcMessagingService_int.setConfiguration(new ServerMessagingDelegate(), jmshost_int, jmsport_int); - - VCMessagingService vcMessagingService_sim = new VCMessagingServiceActiveMQ(); - String jmshost_sim = PropertyLoader.getRequiredProperty(PropertyLoader.jmsSimHostInternal); - int jmsport_sim = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.jmsSimPortInternal)); - vcMessagingService_sim.setConfiguration(new ServerMessagingDelegate(), jmshost_sim, jmsport_sim); + OperatingSystemInfo.getInstance(); + PropertyLoader.loadProperties(REQUIRED_SERVICE_PROPERTIES); - HtcSimulationWorker htcSimulationWorker = new HtcSimulationWorker(htcProxy, vcMessagingService_int, vcMessagingService_sim, serviceInstanceStatus, false); + Injector injector = Guice.createInjector(new VCellServerModule()); + HtcSimulationWorker htcSimulationWorker = injector.getInstance(HtcSimulationWorker.class); htcSimulationWorker.init(); } catch (Throwable e) { @@ -649,47 +633,6 @@ public static void main(java.lang.String[] args) { } } -//private static HtcProxy creatCommandServiceSSH(java.lang.String[] args) throws IOException { -// PropertyLoader.loadProperties(REQUIRED_SERVICE_PROPERTIES); -// -// CommandService commandService = null; -// if (args.length==3){ -// String sshHost = args[0]; -// String sshUser = args[1]; -// File sshKeyFile = new File(args[2]); -// try { -// commandService = new CommandServiceSshNative(sshHost,sshUser,sshKeyFile); -// commandService.command(new String[] { "/usr/bin/env bash -c ls | head -5" }); -// lg.trace("SSH Connection test passed with installed keyfile, running ls as user "+sshUser+" on "+sshHost); -// } catch (Exception e) { -// lg.error(e); -// try { -// commandService = new CommandServiceSshNative(sshHost,sshUser,sshKeyFile,new File("/root")); -// commandService.command(new String[] { "/usr/bin/env bash -c ls | head -5" }); -// lg.trace("SSH Connection test passed after installing keyfile, running ls as user "+sshUser+" on "+sshHost); -// } catch (Exception e2) { -// lg.error(e2); -// throw new RuntimeException("failed to establish an ssh command connection to "+sshHost+" as user '"+sshUser+"' using key '"+sshKeyFile+"'",e); -// } -// } -// AbstractSolver.bMakeUserDirs = false; // can't make user directories, they are remote. -// }else{ -// commandService = new CommandServiceLocal(); -// } -// BatchSystemType batchSystemType = BatchSystemType.SLURM; -// HtcProxy htcProxy = null; -// switch(batchSystemType){ -// case SLURM:{ -// htcProxy = new SlurmProxy(commandService, PropertyLoader.getRequiredProperty(PropertyLoader.htcUser)); -// break; -// } -// default: { -// throw new RuntimeException("unrecognized batch scheduling option :"+batchSystemType); -// } -// } -// return htcProxy; -//} - private static final String REQUIRED_SERVICE_PROPERTIES[] = { PropertyLoader.vcellSoftwareVersion, PropertyLoader.primarySimDataDirInternalProperty, diff --git a/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/SolverPostprocessor.java b/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/SolverPostprocessor.java index b1083c3405..8cd7c2667e 100644 --- a/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/SolverPostprocessor.java +++ b/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/SolverPostprocessor.java @@ -29,8 +29,6 @@ import cbit.vcell.message.messages.WorkerEventMessage; import cbit.vcell.message.server.ManageUtils; import cbit.vcell.message.server.ServerMessagingDelegate; -import cbit.vcell.message.server.jmx.VCellServiceMXBean; -import cbit.vcell.message.server.jmx.VCellServiceMXBeanImpl; import cbit.vcell.mongodb.VCMongoMessage; import cbit.vcell.mongodb.VCMongoMessage.ServiceName; import cbit.vcell.resource.PropertyLoader; @@ -72,12 +70,6 @@ public static void main(java.lang.String[] args) { VCMongoMessage.serviceStartup(ServiceName.solverPostprocessor, Integer.valueOf(simKey.toString()), args); - // - // JMX registration - // - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - mbs.registerMBean(new VCellServiceMXBeanImpl(), new ObjectName(VCellServiceMXBean.jmxObjectName)); - vcMessagingService = new VCMessagingServiceActiveMQ(); String jmshost = PropertyLoader.getRequiredProperty(PropertyLoader.jmsSimHostInternal); int jmsport = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.jmsSimPortInternal)); diff --git a/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/SolverPreprocessor.java b/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/SolverPreprocessor.java index 384fce40fd..e1be35eed4 100644 --- a/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/SolverPreprocessor.java +++ b/vcell-server/src/main/java/cbit/vcell/message/server/batch/sim/SolverPreprocessor.java @@ -32,8 +32,6 @@ import cbit.vcell.message.jms.activeMQ.VCMessagingServiceActiveMQ; import cbit.vcell.message.messages.WorkerEventMessage; import cbit.vcell.message.server.ServerMessagingDelegate; -import cbit.vcell.message.server.jmx.VCellServiceMXBean; -import cbit.vcell.message.server.jmx.VCellServiceMXBeanImpl; import cbit.vcell.messaging.server.SimulationTask; import cbit.vcell.mongodb.VCMongoMessage; import cbit.vcell.mongodb.VCMongoMessage.ServiceName; @@ -117,12 +115,6 @@ public static void main(java.lang.String[] args) { VCMongoMessage.serviceStartup(ServiceName.solverPreprocessor, Integer.valueOf(simTask.getSimKey().toString()), args); - // - // JMX registration - // - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - mbs.registerMBean(new VCellServiceMXBeanImpl(), new ObjectName(VCellServiceMXBean.jmxObjectName)); - final HTCSolver htcSolver = new HTCSolver(simTask, userDirectory,parallelDirectory) { public void startSolver() { try { diff --git a/vcell-server/src/main/java/cbit/vcell/message/server/bootstrap/LocalVCellConnectionFactory.java b/vcell-server/src/main/java/cbit/vcell/message/server/bootstrap/LocalVCellConnectionFactory.java index cad414ca02..9c334b3d61 100644 --- a/vcell-server/src/main/java/cbit/vcell/message/server/bootstrap/LocalVCellConnectionFactory.java +++ b/vcell-server/src/main/java/cbit/vcell/message/server/bootstrap/LocalVCellConnectionFactory.java @@ -38,29 +38,10 @@ public class LocalVCellConnectionFactory implements VCellConnectionFactory { public static final Logger lg = LogManager.getLogger(LocalVCellConnectionFactory.class); - private UserLoginInfo userLoginInfo; private ConnectionFactory connectionFactory = null; -/** - * LocalVCellConnectionFactory constructor comment. - */ -public LocalVCellConnectionFactory(UserLoginInfo userLoginInfo) { - this.userLoginInfo = userLoginInfo; -} -/** - * Insert the method's description here. - * Creation date: (8/9/2001 12:08:06 PM) - * @param userID java.lang.String - * @param password java.lang.String - */ -public void changeUser(UserLoginInfo userLoginInfo) { - this.userLoginInfo = userLoginInfo; -} -/** - * This method was created in VisualAge. - * @return cbit.vcell.server.VCellConnection - */ -public VCellConnection createVCellConnection() throws AuthenticationException, ConnectionException { +@Override +public VCellConnection createVCellConnection(UserLoginInfo userLoginInfo) throws AuthenticationException, ConnectionException { try { if (connectionFactory == null) { connectionFactory = DatabaseService.getInstance().createConnectionFactory(); @@ -93,15 +74,6 @@ public VCellConnection createVCellConnection() throws AuthenticationException, C } } -/** - * Insert the method's description here. - * Creation date: (8/9/2001 12:34:14 PM) - * @param newConFactory cbit.sql.ConnectionFactory - */ -public void setConnectionFactory(ConnectionFactory newConnectionFactory) { - connectionFactory = newConnectionFactory; -} - /** * trigger loading of HDF library when running local */ diff --git a/vcell-server/src/main/java/cbit/vcell/message/server/bootstrap/LocalVCellConnectionServiceImpl.java b/vcell-server/src/main/java/cbit/vcell/message/server/bootstrap/LocalVCellConnectionServiceImpl.java index 430b1f5642..714f95a46c 100644 --- a/vcell-server/src/main/java/cbit/vcell/message/server/bootstrap/LocalVCellConnectionServiceImpl.java +++ b/vcell-server/src/main/java/cbit/vcell/message/server/bootstrap/LocalVCellConnectionServiceImpl.java @@ -1,15 +1,22 @@ package cbit.vcell.message.server.bootstrap; +import com.google.inject.Inject; +import com.google.inject.Singleton; import org.vcell.util.document.UserLoginInfo; import cbit.vcell.server.LocalVCellConnectionService; import cbit.vcell.server.VCellConnectionFactory; +@Singleton public class LocalVCellConnectionServiceImpl implements LocalVCellConnectionService { + public LocalVCellConnectionServiceImpl() { + } + + @Override - public VCellConnectionFactory getLocalVCellConnectionFactory(UserLoginInfo userLoginInfo) { - return new LocalVCellConnectionFactory(userLoginInfo); + public VCellConnectionFactory getLocalVCellConnectionFactory() { + return new LocalVCellConnectionFactory(); } } diff --git a/vcell-server/src/main/java/cbit/vcell/message/server/data/SimDataServer.java b/vcell-server/src/main/java/cbit/vcell/message/server/data/SimDataServer.java index 83ffc935a4..eae689f455 100644 --- a/vcell-server/src/main/java/cbit/vcell/message/server/data/SimDataServer.java +++ b/vcell-server/src/main/java/cbit/vcell/message/server/data/SimDataServer.java @@ -9,96 +9,31 @@ */ package cbit.vcell.message.server.data; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLDecoder; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TreeSet; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; - -import cbit.vcell.message.jms.activeMQ.VCMessagingServiceActiveMQ; -import org.apache.commons.httpclient.URI; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.NameValuePair; -import org.apache.http.client.utils.URLEncodedUtils; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.bootstrap.HttpServer; -import org.apache.http.impl.bootstrap.ServerBootstrap; -import org.apache.http.protocol.HttpContext; -import org.apache.http.protocol.HttpRequestHandler; -import org.apache.http.ssl.SSLContexts; -import org.vcell.util.document.KeyValue; -import org.vcell.util.document.User; -import org.vcell.util.document.VCDataIdentifier; -import org.vcell.util.document.VCellServerID; import cbit.rmi.event.DataJobListener; import cbit.rmi.event.ExportListener; import cbit.vcell.export.server.ExportServiceImpl; -import cbit.vcell.message.VCMessage; -import cbit.vcell.message.VCMessageSelector; -import cbit.vcell.message.VCMessageSession; -import cbit.vcell.message.VCMessagingConstants; -import cbit.vcell.message.VCMessagingException; -import cbit.vcell.message.VCMessagingService; -import cbit.vcell.message.VCPooledQueueConsumer; -import cbit.vcell.message.VCQueueConsumer; -import cbit.vcell.message.VCRpcMessageHandler; -import cbit.vcell.message.VCellQueue; -import cbit.vcell.message.VCellTopic; +import cbit.vcell.message.*; +import cbit.vcell.message.jms.activeMQ.VCMessagingServiceActiveMQ; import cbit.vcell.message.messages.MessageConstants; -import cbit.vcell.message.server.ManageUtils; import cbit.vcell.message.server.ServerMessagingDelegate; -import cbit.vcell.message.server.ServiceInstanceStatus; -import cbit.vcell.message.server.ServiceProvider; import cbit.vcell.message.server.bootstrap.ServiceType; -import cbit.vcell.mongodb.VCMongoMessage; -import cbit.vcell.mongodb.VCMongoMessage.ServiceName; -import cbit.vcell.resource.LibraryLoaderThread; -import cbit.vcell.resource.OperatingSystemInfo; import cbit.vcell.resource.PropertyLoader; -import cbit.vcell.resource.PythonSupport; -import cbit.vcell.resource.PythonSupport.PythonPackage; import cbit.vcell.simdata.Cachetable; import cbit.vcell.simdata.DataServerImpl; import cbit.vcell.simdata.DataSetControllerImpl; -import cbit.vcell.simdata.Hdf5Utils; -import cbit.vcell.solver.VCSimulationDataIdentifier; -import cbit.vcell.solver.VCSimulationIdentifier; -import cbit.vcell.solver.ode.ODESimData; -import cbit.vcell.util.ColumnDescription; -import ncsa.hdf.hdf5lib.H5; -import ncsa.hdf.hdf5lib.HDF5Constants; +import org.apache.http.impl.bootstrap.HttpServer; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; /** * Insert the type's description here. * Creation date: (10/18/2001 4:31:11 PM) * @author: Jim Schaff */ -public class SimDataServer extends ServiceProvider implements ExportListener, DataJobListener { +public class SimDataServer implements ExportListener, DataJobListener { public enum SimDataServiceType { @@ -106,199 +41,45 @@ public enum SimDataServiceType { SimDataOnly, CombinedData } - - private DataServerImpl dataServerImpl = null; + + public static final Logger lg = LogManager.getLogger(SimDataServer.class); + + private final VCMessagingService vcMessagingService_int; + private final DataServerImpl dataServerImpl; private VCQueueConsumer rpcConsumer = null; private VCRpcMessageHandler rpcMessageHandler = null; private VCPooledQueueConsumer pooledQueueConsumer = null; private VCMessageSession sharedProducerSession = null; - private final SimDataServiceType simDataServiceType; private HttpServer server; -/** - * @param serviceInstanceStatus - * @param dataServerImpl - * @param vcMessagingService - * @param log - * @throws Exception - */ -public SimDataServer(ServiceInstanceStatus serviceInstanceStatus, DataServerImpl dataServerImpl, VCMessagingService vcMessagingService, SimDataServiceType simDataServiceType, boolean bSlaveMode) throws Exception { - super(vcMessagingService,null,serviceInstanceStatus,bSlaveMode); - this.dataServerImpl = dataServerImpl; - this.simDataServiceType = simDataServiceType; - - try (InputStream inputStream = new FileInputStream(new File(PropertyLoader.getRequiredProperty(PropertyLoader.vcellapiKeystoreFile)))) { - final KeyStore serverKeyStore = KeyStore.getInstance("jks"); - String pwd = Files.readAllLines(new File(PropertyLoader.getRequiredProperty(PropertyLoader.vcellapiKeystorePswdFile)).toPath()).get(0); - serverKeyStore.load(inputStream, pwd.toCharArray()); - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - keyManagerFactory.init(serverKeyStore, pwd.toCharArray()); - KeyManager[] serverKeyManagers = keyManagerFactory.getKeyManagers(); - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(serverKeyStore); - TrustManager[] serverTrustManagers = trustManagerFactory.getTrustManagers(); - final SSLContext sslContext = SSLContexts.createDefault(); - sslContext.init(serverKeyManagers, serverTrustManagers, new SecureRandom()); - int listenPort = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.webDataServerPort)); - server = ServerBootstrap.bootstrap().registerHandler("/simhdf5/*", new HttpRequestHandler() { - @Override - public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { - try { - URI uri = new URI(request.getRequestLine().getUri(),true); - final List parse = URLEncodedUtils.parse(uri.getQuery(),Charset.forName("utf-8")); - lg.info(uri.getQuery()); - lg.info(uri.getPath()); - final Path path = Paths.get(uri.getPath()); - final Iterator iterator = path.iterator(); - final String SIMDATADDF5 = "simhdf5"; - final String ODE = "ode"; - String simdataRoute = iterator.next().toString(); - String dataType = iterator.next().toString(); - if(simdataRoute.toLowerCase().equals(SIMDATADDF5) && dataType.toLowerCase().equals(ODE)) { - String simID = null; - TreeSet jobIDs = new TreeSet(); - String userKey = null; - String userid = null; - double blank = -1.0; - for(NameValuePair nvp:parse) { - if(nvp.getName().toLowerCase().equals("simid")) { - simID = nvp.getValue(); - }else if(nvp.getName().toLowerCase().equals("jobid")) { - String jobStr = URLDecoder.decode(nvp.getValue(), "UTF-8");// integer Separated by commas - StringTokenizer st = new StringTokenizer(jobStr,","); - while(st.hasMoreElements()) { - jobIDs.add(Integer.parseInt(st.nextToken())); - } - }else if(nvp.getName().toLowerCase().equals("userkey")) { - userKey = nvp.getValue(); - }else if(nvp.getName().toLowerCase().equals("userid")) { - userid = URLDecoder.decode(nvp.getValue(), "UTF-8"); - }else if(nvp.getName().toLowerCase().equals("blank")) { - blank = Double.parseDouble(nvp.getValue()); - } - } - User user = new User(userid,new KeyValue(userKey)); - VCSimulationIdentifier vcsid = new VCSimulationIdentifier(new KeyValue(simID), user); - File hdf5File = createHdf5(vcsid, jobIDs.toArray(new Integer[0]), blank); - - String exportBaseURL = PropertyLoader.getRequiredProperty(PropertyLoader.exportBaseURLProperty); - URL url = new URL(exportBaseURL + hdf5File.getName()); - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); - response.addHeader("Location",url.toString()); - response.setEntity(null); - return; - } - response.setStatusCode(HttpStatus.SC_NOT_FOUND); - response.setEntity(new StringEntity("Not Found")); - } catch (Exception e) { - lg.error(e.getMessage(), e); - response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); - response.setEntity(new StringEntity(e.getMessage())); +public SimDataServer() throws Exception { + String cacheSize = PropertyLoader.getRequiredProperty(PropertyLoader.simdataCacheSizeProperty); + long maxMemSize = Long.parseLong(cacheSize); - } - } - }).setListenerPort(listenPort).setSslContext(sslContext).create(); - server.start(); - - }catch(Exception e) { - lg.error(e.getMessage(), e); - } - - -} + Cachetable cacheTable = new Cachetable(MessageConstants.MINUTE_IN_MS * 20,maxMemSize); + DataSetControllerImpl dataSetControllerImpl = new DataSetControllerImpl(cacheTable, + new File(PropertyLoader.getRequiredProperty(PropertyLoader.primarySimDataDirInternalProperty)), + new File(PropertyLoader.getProperty(PropertyLoader.secondarySimDataDirInternalProperty, PropertyLoader.getRequiredProperty(PropertyLoader.primarySimDataDirInternalProperty)))); -private File createHdf5(VCSimulationIdentifier vcsid,Integer[] scanJobs,double blankCellValue/*for Histogram*/) throws Exception{ - File hdf5TempFile = null; - int hdf5FileID = -1; - int jobGroupID = -1; - try { - String exportBaseDir = PropertyLoader.getRequiredProperty(PropertyLoader.exportBaseDirInternalProperty); - hdf5TempFile = File.createTempFile("webexport_"+vcsid.getSimulationKey()+"_", ".hdf", new File(exportBaseDir)); - hdf5FileID = H5.H5Fcreate(hdf5TempFile.getAbsolutePath(), HDF5Constants.H5F_ACC_TRUNC,HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT); - Hdf5Utils.insertAttribute(hdf5FileID, "simID",vcsid.getSimulationKey().toString());//Hdf5Utils.writeHDF5Dataset(hdf5FileID, "simID", null,vcsid.getSimulationKey().toString() , true); - Hdf5Utils.insertAttribute(hdf5FileID,"exportUser",vcsid.getOwner().getName()) ;//Hdf5Utils.writeHDF5Dataset(hdf5FileID, "exportUser", null,vcsid.getOwner().getName() , true); - - for(int scan=0;scan orderedColumnNames = new TreeSet(new Comparator() { - @Override - public int compare(ColumnDescription o1, ColumnDescription o2) { - if(o1.getName().equals("t") && o2.getName().equals("t")) {//'t' as first in the list - return 0; - }else if(o1.getName().equals("t")) { - return -1; - }else if(o2.getName().equals("t")) { - return 1; - } - return o1.getName().compareToIgnoreCase(o2.getName()); - }}); - orderedColumnNames.addAll(Arrays.asList(odeSimData.getColumnDescriptions())); - jobGroupID = (int) Hdf5Utils.createGroup(hdf5FileID, "Set "+scan); - //writeHDF5Dataset(hdf5FileID, "Set "+scan, null, null, false); - Hdf5Utils.HDF5WriteHelper help0 = Hdf5Utils.createDataset(jobGroupID, "data", new long[] {allColumnsCount,allRowsCount}); - //(HDF5WriteHelper) Hdf5Utils.writeHDF5Dataset(jobGroupID, "data", new long[] {allColumnsCount,allRowsCount}, new Object[] {}, false); - double[] fromData = new double[allColumnsCount*allRowsCount]; - int index = 0; - ArrayList dataTypes = new ArrayList(); - ArrayList dataIDs = new ArrayList(); - ArrayList dataShapes = new ArrayList(); - ArrayList dataLabels = new ArrayList(); - ArrayList dataNames = new ArrayList(); - Iterator columnNamesIterator = orderedColumnNames.iterator(); - while(columnNamesIterator.hasNext()) { - - ColumnDescription colDescr = columnNamesIterator.next(); - final String columnName = colDescr.getName(); - final int columnIndex = odeSimData.findColumn(columnName); - dataTypes.add("float64"); - dataIDs.add("data_set_"+columnName); - dataShapes.add(allRowsCount+""); - dataLabels.add(columnName); - dataNames.add(columnName/*name*/); - double[] columnData = odeSimData.extractColumn(columnIndex); - for(int myrows=0;myrows parse = URLEncodedUtils.parse(uri.getQuery(), Charset.forName("utf-8")); + lg.info(uri.getQuery()); + lg.info(uri.getPath()); + final Path path = Paths.get(uri.getPath()); + final Iterator iterator = path.iterator(); + final String SIMDATADDF5 = "simhdf5"; + final String ODE = "ode"; + String simdataRoute = iterator.next().toString(); + String dataType = iterator.next().toString(); + if(simdataRoute.toLowerCase().equals(SIMDATADDF5) && dataType.toLowerCase().equals(ODE)) { + String simID = null; + TreeSet jobIDs = new TreeSet(); + String userKey = null; + String userid = null; + double blank = -1.0; + for(NameValuePair nvp:parse) { + if(nvp.getName().toLowerCase().equals("simid")) { + simID = nvp.getValue(); + }else if(nvp.getName().toLowerCase().equals("jobid")) { + String jobStr = URLDecoder.decode(nvp.getValue(), "UTF-8");// integer Separated by commas + StringTokenizer st = new StringTokenizer(jobStr,","); + while(st.hasMoreElements()) { + jobIDs.add(Integer.parseInt(st.nextToken())); + } + }else if(nvp.getName().toLowerCase().equals("userkey")) { + userKey = nvp.getValue(); + }else if(nvp.getName().toLowerCase().equals("userid")) { + userid = URLDecoder.decode(nvp.getValue(), "UTF-8"); + }else if(nvp.getName().toLowerCase().equals("blank")) { + blank = Double.parseDouble(nvp.getValue()); + } + } + User user = new User(userid,new KeyValue(userKey)); + VCSimulationIdentifier vcsid = new VCSimulationIdentifier(new KeyValue(simID), user); + File hdf5File = createHdf5(vcsid, jobIDs.toArray(new Integer[0]), blank); + + String exportBaseURL = PropertyLoader.getRequiredProperty(PropertyLoader.exportBaseURLProperty); + URL url = new URL(exportBaseURL + hdf5File.getName()); + response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.addHeader("Location",url.toString()); + response.setEntity(null); + return; + } + response.setStatusCode(HttpStatus.SC_NOT_FOUND); + response.setEntity(new StringEntity("Not Found")); + } catch (Exception e) { + lg.error(e.getMessage(), e); + response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); + response.setEntity(new StringEntity(e.getMessage())); + + } + } + }).setListenerPort(listenPort).setSslContext(sslContext).create(); + server.start(); + + }catch(Exception e) { + lg.error(e.getMessage(), e); + } + } + + private File createHdf5(VCSimulationIdentifier vcsid,Integer[] scanJobs,double blankCellValue/*for Histogram*/) throws Exception{ + File hdf5TempFile = null; + int hdf5FileID = -1; + int jobGroupID = -1; + try { + String exportBaseDir = PropertyLoader.getRequiredProperty(PropertyLoader.exportBaseDirInternalProperty); + hdf5TempFile = File.createTempFile("webexport_"+vcsid.getSimulationKey()+"_", ".hdf", new File(exportBaseDir)); + hdf5FileID = H5.H5Fcreate(hdf5TempFile.getAbsolutePath(), HDF5Constants.H5F_ACC_TRUNC,HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT); + Hdf5Utils.insertAttribute(hdf5FileID, "simID",vcsid.getSimulationKey().toString());//Hdf5Utils.writeHDF5Dataset(hdf5FileID, "simID", null,vcsid.getSimulationKey().toString() , true); + Hdf5Utils.insertAttribute(hdf5FileID,"exportUser",vcsid.getOwner().getName()) ;//Hdf5Utils.writeHDF5Dataset(hdf5FileID, "exportUser", null,vcsid.getOwner().getName() , true); + + for(int scan=0;scan orderedColumnNames = new TreeSet(new Comparator() { + @Override + public int compare(ColumnDescription o1, ColumnDescription o2) { + if(o1.getName().equals("t") && o2.getName().equals("t")) {//'t' as first in the list + return 0; + }else if(o1.getName().equals("t")) { + return -1; + }else if(o2.getName().equals("t")) { + return 1; + } + return o1.getName().compareToIgnoreCase(o2.getName()); + }}); + orderedColumnNames.addAll(Arrays.asList(odeSimData.getColumnDescriptions())); + jobGroupID = (int) Hdf5Utils.createGroup(hdf5FileID, "Set "+scan); + //writeHDF5Dataset(hdf5FileID, "Set "+scan, null, null, false); + Hdf5Utils.HDF5WriteHelper help0 = Hdf5Utils.createDataset(jobGroupID, "data", new long[] {allColumnsCount,allRowsCount}); + //(HDF5WriteHelper) Hdf5Utils.writeHDF5Dataset(jobGroupID, "data", new long[] {allColumnsCount,allRowsCount}, new Object[] {}, false); + double[] fromData = new double[allColumnsCount*allRowsCount]; + int index = 0; + ArrayList dataTypes = new ArrayList(); + ArrayList dataIDs = new ArrayList(); + ArrayList dataShapes = new ArrayList(); + ArrayList dataLabels = new ArrayList(); + ArrayList dataNames = new ArrayList(); + Iterator columnNamesIterator = orderedColumnNames.iterator(); + while(columnNamesIterator.hasNext()) { + + ColumnDescription colDescr = columnNamesIterator.next(); + final String columnName = colDescr.getName(); + final int columnIndex = odeSimData.findColumn(columnName); + dataTypes.add("float64"); + dataIDs.add("data_set_"+columnName); + dataShapes.add(allRowsCount+""); + dataLabels.add(columnName); + dataNames.add(columnName/*name*/); + double[] columnData = odeSimData.extractColumn(columnIndex); + for(int myrows=0;myrows vcell-service) @@ -18,6 +20,7 @@ protected void configure() { // only one implementation, to break compile-time cyclic dependency (vcell-core -> vcell-service) bind(LocalVCellConnectionService.class).toInstance(new LocalVCellConnectionServiceImpl()); + bind(VCellConnectionFactory.class).to(LocalVCellConnectionFactory.class).asEagerSingleton(); // server-side implementation (talk directly to database) // RegistrationService interface is not clean - mixes new registration with updates - is there another way? diff --git a/vcell-util/pom.xml b/vcell-util/pom.xml index a530f136b2..13f5c1faa6 100644 --- a/vcell-util/pom.xml +++ b/vcell-util/pom.xml @@ -107,11 +107,6 @@ gson 2.9.1 - - com.google.inject - guice - 5.1.0 - commons-io diff --git a/vcell-vmicro/src/main/java/org/vcell/vmicro/op/display/DisplayBioModelOp.java b/vcell-vmicro/src/main/java/org/vcell/vmicro/op/display/DisplayBioModelOp.java index c83b618104..1021780d78 100644 --- a/vcell-vmicro/src/main/java/org/vcell/vmicro/op/display/DisplayBioModelOp.java +++ b/vcell-vmicro/src/main/java/org/vcell/vmicro/op/display/DisplayBioModelOp.java @@ -12,7 +12,8 @@ public static void displayBioModel(final BioModel bioModel){ new Thread() { public void run(){ ClientServerInfo clientServerInfo = ClientServerInfo.createLocalServerInfo("schaff", new DigestedPassword("abc")); - VCellClient vcellClient = VCellClient.startClient(bioModel, clientServerInfo); + VCellClient vCellClient = new VCellClient(null, null); + vCellClient.startClient(bioModel, clientServerInfo); } }.start(); } diff --git a/vcell-web/src/main/java/org/vcell/web/MainService.java b/vcell-web/src/main/java/org/vcell/web/MainService.java index 1b5839b6f4..02b3b28e93 100644 --- a/vcell-web/src/main/java/org/vcell/web/MainService.java +++ b/vcell-web/src/main/java/org/vcell/web/MainService.java @@ -32,6 +32,8 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; +import com.google.inject.Guice; +import com.google.inject.Injector; import org.apache.commons.httpclient.URI; import org.apache.http.Header; import org.apache.http.HttpException; @@ -51,6 +53,7 @@ import org.vcell.db.DatabaseService; import org.vcell.db.DatabaseSyntax; import org.vcell.db.KeyFactory; +import org.vcell.dependency.server.VCellServerModule; import org.vcell.util.ConfigurationException; import org.vcell.util.DataAccessException; import org.vcell.util.ObjectNotFoundException; @@ -100,7 +103,9 @@ private static class AuthenticationInfo { public static void main(String[] args) { try { - new MainService(); + Injector injector = Guice.createInjector(new VCellServerModule()); + MainService mainService = injector.getInstance(MainService.class); + mainService.start(); } catch (Exception e) { e.printStackTrace(); } @@ -283,12 +288,14 @@ else if(nvp.getName().toLowerCase().equals("blank")) { } } }).setListenerPort(listenPort).setSslContext(sslContext).create(); - server.start(); }catch(Exception e) { e.printStackTrace(); } + } + public void start() throws IOException { + this.server.start(); } private static File createInfosHdf5(User authuser,DatabaseServerImpl databaseServerImpl) throws IOException, HDF5LibraryException, HDF5Exception, DataAccessException { diff --git a/vcell.bat b/vcell.bat index 81433d5de4..7342523590 100644 --- a/vcell.bat +++ b/vcell.bat @@ -1,13 +1,13 @@ echo off set CLASSPATH=.\vcell-client\target\maven-jars\*;.\vcell-client\target\* -set MAIN_CLASS=cbit.vcell.client.test.VCellClientTest +set MAIN_CLASS=cbit.vcell.client.test.VCellClientMain set props=-Dvcell.installDir=%~dp0 set props=%props% -Dvcell.softwareVersion=standalone_VCell_7.0 set props=%props% -Dvcell.bioformatsJarFileName=vcell-bioformats-0.0.9-jar-with-dependencies.jar set props=%props% -Dvcell.bioformatsJarDownloadURL=http://vcell.org/webstart/vcell-bioformats-0.0.9-jar-with-dependencies.jar -echo java %props% -cp %CLASSPATH% %MAIN_CLASS% vcellapi.cam.uchc.edu:443 +echo java %props% -cp %CLASSPATH% %MAIN_CLASS% --api-host=vcellapi.cam.uchc.edu:443 -java %props% -cp %CLASSPATH% %MAIN_CLASS% vcellapi.cam.uchc.edu:443 \ No newline at end of file +java %props% -cp %CLASSPATH% %MAIN_CLASS% --api-host=vcellapi.cam.uchc.edu:443 \ No newline at end of file diff --git a/vcell.sh b/vcell.sh index 569c382c49..542ca9496e 100755 --- a/vcell.sh +++ b/vcell.sh @@ -1,12 +1,12 @@ #!/usr/bin/env bash CLASSPATH=./vcell-client/target/maven-jars/*:./vcell-client/target/* -MAIN_CLASS=cbit.vcell.client.test.VCellClientTest +MAIN_CLASS=cbit.vcell.client.VCellClientMain props="-Dvcell.installDir=$PWD" props="${props} -Dvcell.softwareVersion=standalone_VCell_7.0" props="${props} -Dvcell.bioformatsJarFileName=vcell-bioformats-0.0.9-jar-with-dependencies.jar" props="${props} -Dvcell.bioformatsJarDownloadURL=http://vcell.org/webstart/vcell-bioformats-0.0.9-jar-with-dependencies.jar" -echo java ${props} -cp $CLASSPATH $MAIN_CLASS vcellapi.cam.uchc.edu:443 -java ${props} -cp $CLASSPATH $MAIN_CLASS vcellapi.cam.uchc.edu:443 +echo java ${props} -cp $CLASSPATH $MAIN_CLASS --api-host=vcellapi.cam.uchc.edu:443 +java ${props} -cp $CLASSPATH $MAIN_CLASS --api-host=vcellapi.cam.uchc.edu:443