-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathClientRequestManager.java
More file actions
4764 lines (4434 loc) · 198 KB
/
ClientRequestManager.java
File metadata and controls
4764 lines (4434 loc) · 198 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.gui.ImageResizePanel;
import cbit.image.*;
import cbit.rmi.event.ExportEvent;
import cbit.rmi.event.ExportListener;
import cbit.rmi.event.VCellMessageEvent;
import cbit.rmi.event.VCellMessageEventListener;
import cbit.vcell.VirtualMicroscopy.ImageDataset;
import cbit.vcell.VirtualMicroscopy.importer.MicroscopyXMLTags;
import cbit.vcell.VirtualMicroscopy.importer.VFrapXmlHelper;
import cbit.vcell.biomodel.BioModel;
import cbit.vcell.biomodel.meta.VCMetaData;
import cbit.vcell.client.TopLevelWindowManager.OpenModelInfoHolder;
import cbit.vcell.client.data.DataViewerController;
import cbit.vcell.client.data.ExportDataRepresentation;
import cbit.vcell.client.data.MergedDatasetViewerController;
import cbit.vcell.client.desktop.DocumentWindow;
import cbit.vcell.client.desktop.biomodel.DocumentEditor;
import cbit.vcell.client.server.ClientServerInfo;
import cbit.vcell.client.server.UserPreferences;
import cbit.vcell.client.task.*;
import cbit.vcell.clientdb.DocumentManager;
import cbit.vcell.desktop.ClientLogin;
import cbit.vcell.desktop.ImageDbTreePanel;
import cbit.vcell.export.server.ExportFormat;
import cbit.vcell.export.server.ExportSpecs;
import cbit.vcell.export.server.HumanReadableExportData;
import cbit.vcell.export.server.N5Specs;
import cbit.vcell.field.FieldDataFileConversion;
import cbit.vcell.field.io.FieldData;
import cbit.vcell.geometry.*;
import cbit.vcell.geometry.gui.ROIMultiPaintManager;
import cbit.vcell.geometry.surface.*;
import cbit.vcell.mapping.*;
import cbit.vcell.mapping.SimulationContext.MathMappingCallback;
import cbit.vcell.mapping.SimulationContext.NetworkGenerationRequirements;
import cbit.vcell.math.CompartmentSubDomain;
import cbit.vcell.math.MathDescription;
import cbit.vcell.math.MembraneSubDomain;
import cbit.vcell.mathmodel.MathModel;
import cbit.vcell.model.*;
import cbit.vcell.model.Model.ModelParameter;
import cbit.vcell.model.Model.RbmModelContainer;
import cbit.vcell.model.Model.ReservedSymbol;
import cbit.vcell.numericstest.ModelGeometryOP;
import cbit.vcell.numericstest.ModelGeometryOPResults;
import cbit.vcell.parser.Expression;
import cbit.vcell.render.Vect3d;
import cbit.vcell.resource.ResourceUtil;
import cbit.vcell.server.SimulationStatus;
import cbit.vcell.simdata.*;
import cbit.vcell.solver.*;
import cbit.vcell.solver.test.MathTestingUtilities;
import cbit.vcell.solvers.CartesianMesh;
import cbit.vcell.xml.ExternalDocInfo;
import cbit.vcell.xml.XMLSource;
import cbit.vcell.xml.XMLTags;
import cbit.vcell.xml.XmlHelper;
import cbit.xml.merge.XmlTreeDiff;
import cbit.xml.merge.XmlTreeDiff.DiffConfiguration;
import cbit.xml.merge.gui.TMLPanel;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jlibsedml.ArchiveComponents;
import org.jlibsedml.Libsedml;
import org.jlibsedml.SEDMLDocument;
import org.jlibsedml.SedML;
import org.vcell.api.server.AsynchMessageManager;
import org.vcell.api.server.ClientServerManager;
import org.vcell.api.server.ConnectionStatus;
import org.vcell.api.utils.Auth0ConnectionUtils;
import org.vcell.model.bngl.ASTModel;
import org.vcell.model.bngl.BngUnitSystem;
import org.vcell.model.bngl.BngUnitSystem.BngUnitOrigin;
import org.vcell.model.bngl.gui.BNGLDebuggerPanel;
import org.vcell.model.bngl.gui.BNGLUnitsPanel;
import org.vcell.model.rbm.RbmUtils;
import org.vcell.model.rbm.RbmUtils.BnglObjectConstructionVisitor;
import org.vcell.model.ssld.SsldModel;
import org.vcell.model.ssld.SsldUtils;
import org.vcell.util.*;
import org.vcell.util.document.*;
import org.vcell.util.document.VCDocument.DocumentCreationInfo;
import org.vcell.util.document.VCDocument.VCDocumentType;
import org.vcell.util.gui.*;
import org.vcell.util.gui.exporter.ExtensionFilter;
import org.vcell.util.gui.exporter.FileFilters;
import org.vcell.util.importer.PathwayImportPanel.PathwayImportOption;
import org.vcell.vcellij.ImageDatasetReader;
import org.vcell.vcellij.ImageDatasetReaderService;
import javax.swing.Timer;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferUShort;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.zip.DataFormatException;
import java.util.zip.GZIPInputStream;
public class ClientRequestManager
implements RequestManager, PropertyChangeListener, ExportListener, VCellMessageEventListener {
private VCellClient vcellClient = null;
private boolean bOpening = false;
private boolean bExiting = false;
private static final Logger lg = LogManager.getLogger(ClientRequestManager.class);
public ClientRequestManager(VCellClient vcellClient) {
setVcellClient(vcellClient);
// listen to connectionStatus events
getClientServerManager().addPropertyChangeListener(this);
getClientServerManager().getAsynchMessageManager().addExportListener(this);
getClientServerManager().getAsynchMessageManager().addVCellMessageEventListener(this);
}
private static final String GEOMETRY_KEY = "geometry";
private static final String VERSIONINFO_KEY = "VERSIONINFO_KEY";
private AsynchClientTask createSelectDocTask(final TopLevelWindowManager requester) {
AsynchClientTask selectDocumentTypeTask = new AsynchClientTask("Select/Load geometry",
AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
String[][] docTypeoptions = new String[][] { { "BioModel names" }, { "MathModel names" } };
VCDocumentType[] sourceDocumentTypes = new VCDocumentType[] { VCDocumentType.BIOMODEL_DOC,
VCDocumentType.MATHMODEL_DOC };
VCAssert.assertTrue(docTypeoptions.length == sourceDocumentTypes.length, "Label and types mismatch");
int[] geomType = DialogUtils.showComponentOKCancelTableList(
JOptionPane.getFrameForComponent(requester.getComponent()), "Select different Geometry",
new String[] { "Search by" }, docTypeoptions, ListSelectionModel.SINGLE_SELECTION);
final int selectedType = geomType[0];
VCDocumentType sourceDocumentType = sourceDocumentTypes[selectedType];
VersionInfo vcVersionInfo = null;
if (geomType[0] == 3) {
ImageDbTreePanel imageDbTreePanel = new ImageDbTreePanel();
imageDbTreePanel.setDocumentManager(getDocumentManager());
imageDbTreePanel.setPreferredSize(new java.awt.Dimension(200, 400));
vcVersionInfo = DialogUtils.getDBTreePanelSelection(requester.getComponent(), imageDbTreePanel,
"OK", "Select Image:");
} else {
if(hashTable.get(BioModelWindowManager.SELECT_GEOM_POPUP) != null && ((Boolean)hashTable.get(BioModelWindowManager.SELECT_GEOM_POPUP)).booleanValue()) {
if(getClientTaskStatusSupport() instanceof AsynchProgressPopup) {
((AsynchProgressPopup)getClientTaskStatusSupport()).setVisible(false);
}
try {
Object obj = getMdiManager().getDatabaseWindowManager().selectDocument2(sourceDocumentType,
requester);
if (obj instanceof Geometry) {//user selected geometry directly using popup
hashTable.put(GEOMETRY_KEY, ((Geometry) obj));
return;
}
vcVersionInfo = (VersionInfo) obj;//user selected VCDocument, list will be shown to select from
} finally {
if(getClientTaskStatusSupport() instanceof AsynchProgressPopup) {
((AsynchProgressPopup)getClientTaskStatusSupport()).setVisible(true);
}
}
}else {
vcVersionInfo = selectDocumentFromType(sourceDocumentType, requester);
}
}
hashTable.put(VERSIONINFO_KEY, vcVersionInfo);
}
};
return selectDocumentTypeTask;
}
private AsynchClientTask createSelectLoadGeomTask(final TopLevelWindowManager requester) {
AsynchClientTask selectLoadGeomTask = new AsynchClientTask("Select/Load geometry...",
AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
if(hashTable.get(GEOMETRY_KEY) != null) {//Already loaded from selection of BioModelDBTree from previous task
((Geometry)hashTable.get(GEOMETRY_KEY)).precomputeAll(new GeometryThumbnailImageFactoryAWT());
return;
}
VersionInfo vcVersionInfo = (VersionInfo) hashTable.get(VERSIONINFO_KEY);
Geometry geom = null;
if (vcVersionInfo instanceof VCDocumentInfo) {
geom = getGeometryFromDocumentSelection(requester.getComponent(), (VCDocumentInfo) vcVersionInfo,
false);
} else if (vcVersionInfo instanceof VCImageInfo) {
VCImage img = getDocumentManager().getImage((VCImageInfo) vcVersionInfo);
geom = new Geometry("createSelectLoadGeomTask", img);
} else {
throw new Exception("Unexpected versioninfo type.");
}
geom.precomputeAll(new GeometryThumbnailImageFactoryAWT());// pregenerate sampled image, cpu intensive
hashTable.put(GEOMETRY_KEY, geom);
}
};
return selectLoadGeomTask;
}
private void changeGeometry0(final TopLevelWindowManager requester, final SimulationContext simContext,Hashtable<String, Object> hashTable) {
AsynchClientTask selectDocumentTypeTask = createSelectDocTask(requester);
AsynchClientTask selectLoadGeomTask = createSelectLoadGeomTask(requester);
AsynchClientTask processGeometryTask = new AsynchClientTask("Processing geometry...",
AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
Geometry newGeometry = (Geometry) hashTable.get(GEOMETRY_KEY);
if (requester instanceof MathModelWindowManager) {
// User can cancel here
continueAfterMathModelGeomChangeWarning((MathModelWindowManager) requester, newGeometry);
}
if (newGeometry.getDimension() > 0
&& newGeometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
newGeometry.getGeometrySurfaceDescription().updateAll();
}
}
};
AsynchClientTask setNewGeometryTask = new AsynchClientTask("Setting new Geometry...",
AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
Geometry newGeometry = (Geometry) hashTable.get(GEOMETRY_KEY);
if (newGeometry != null) {
if (requester instanceof BioModelWindowManager) {
simContext.setGeometry(newGeometry);
} else if (requester instanceof MathModelWindowManager) {
MathModel mathModel = (MathModel) ((MathModelWindowManager) requester).getVCDocument();
mathModel.getMathDescription().setGeometry(newGeometry);
}
}
}
};
ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] {
selectDocumentTypeTask, selectLoadGeomTask, processGeometryTask, setNewGeometryTask }, false);
}
public void changeGeometry(DocumentWindowManager requester, SimulationContext simContext,Hashtable<String, Object> hashTable) {
changeGeometry0(requester, simContext,hashTable);
}
public static void continueAfterMathModelGeomChangeWarning(MathModelWindowManager mathModelWindowManager,
Geometry newGeometry) throws UserCancelException {
MathModel mathModel = mathModelWindowManager.getMathModel();
if (mathModel != null && mathModel.getMathDescription() != null) {
Geometry oldGeometry = mathModel.getMathDescription().getGeometry();
if (oldGeometry != null && oldGeometry.getDimension() == 0) {
return;
}
boolean bMeshResolutionChange = true;
if (oldGeometry == null) {
bMeshResolutionChange = false;
}
if (newGeometry != null && oldGeometry != null
&& oldGeometry.getDimension() == newGeometry.getDimension()) {
bMeshResolutionChange = false;
}
boolean bHasSims = (mathModel.getSimulations() != null) && (mathModel.getSimulations().length > 0);
StringBuffer meshResolutionChangeSB = new StringBuffer();
if (bHasSims && bMeshResolutionChange) {
ISize newGeomISize = MeshSpecification.calulateResetSamplingSize(newGeometry);
for (int i = 0; i < mathModel.getSimulations().length; i++) {
if (mathModel.getSimulations()[i].getMeshSpecification() != null) {
String simName = mathModel.getSimulations()[i].getName();
ISize simMeshSize = mathModel.getSimulations()[i].getMeshSpecification().getSamplingSize();
meshResolutionChangeSB.append((i != 0 ? "\n" : "") + "'" + simName + "' Mesh" + simMeshSize
+ " will be reset to " + newGeomISize + "");
}
}
}
String result = DialogUtils.showWarningDialog(
JOptionPane.getFrameForComponent(mathModelWindowManager.getComponent()),
"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()
: ""),
new String[] { "Continue", "Cancel" }, "Continue");
if (result != null && result.equals("Continue")) {
return;
}
} else {
return;
}
throw UserCancelException.CANCEL_GENERIC;
}
enum CloseOption {
SAVE_AND_CLOSE, CLOSE_IN_ANY_CASE, CANCEL_CLOSE,
}
public enum CallAction {
EXPORT, RUN, SAVE, SAVEASNEW,
}
private CloseOption checkBeforeClosing(DocumentWindowManager windowManager) {
getMdiManager().showWindow(windowManager.getManagerID());
// we need to check for changes and get user confirmation...
VCDocument vcDocument = windowManager.getVCDocument();
if (vcDocument.getVersion() == null && !isDifferentFromBlank(vcDocument.getDocumentType(), vcDocument)) {
return CloseOption.CLOSE_IN_ANY_CASE;
}
boolean isChanged = true;
try {
isChanged = getDocumentManager().isChanged(vcDocument);
} catch (Exception exc) {
exc.printStackTrace();
String choice = PopupGenerator.showWarningDialog(windowManager, getUserPreferences(),
UserMessage.warn_UnableToCheckForChanges, null);
if (choice.equals(UserMessage.OPTION_CANCEL)) {
// user canceled
return CloseOption.CANCEL_CLOSE;
}
}
// warn if necessary
if (isChanged) {
JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
final String[] warnCloseArr = new String[] { UserMessage.OPTION_YES, "No", UserMessage.OPTION_CANCEL };
int confirm = JOptionPane.showOptionDialog(dialog, UserMessage.warn_close.getMessage(null),
"Save warning...", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, warnCloseArr,
warnCloseArr[0]);
// String choice = PopupGenerator.showWarningDialog(windowManager, getUserPreferences(), UserMessage.warn_close,null);
if (confirm != 0 && confirm != 1/* choice.equals(UserMessage.OPTION_CANCEL) */) {
// user canceled
return CloseOption.CANCEL_CLOSE;
}
if (confirm == 0/* choice.equals(UserMessage.OPTION_YES) */) {
return CloseOption.SAVE_AND_CLOSE;
}
}
// nothing changed, or user confirmed, close it
return CloseOption.CLOSE_IN_ANY_CASE;
}
public boolean isDifferentFromBlank(VCDocumentType documentType, VCDocument vcDocument) {
// Handle Bio/Math models different from Geometry since createDefaultDoc for
// Geometry
// will bring up the NewGeometryEditor which is unnecessary.
// figure out if we come from a blank new document; if so, replace it inside
// same window
if (documentType != vcDocument.getDocumentType()) {
// If the docType we are trying to open is not the same as the requesting
// windowmanager's docType
// we have to open the doc in a new window, hence return true;
return true;
}
VCDocument blank = null;
if (vcDocument.getDocumentType() != VCDocumentType.GEOMETRY_DOC) {
// BioModel/MathModel
blank = createDefaultDocument(vcDocument.getDocumentType());
try {
blank.setName(vcDocument.getName());
} catch (PropertyVetoException e) {
} // ignore. doesn't happen
return !blank.compareEqual(vcDocument);
} else {
// Geometry
blank = new Geometry(vcDocument.getName(), 1);
if (blank.compareEqual(vcDocument)) {
return false;
}
blank = new Geometry(vcDocument.getName(), 2);
if (blank.compareEqual(vcDocument)) {
return false;
}
blank = new Geometry(vcDocument.getName(), 3);
if (blank.compareEqual(vcDocument)) {
return false;
}
return true;
}
}
@Override
public ClientServerInfo getClientServerInfo() {
return getVcellClient().getClientServerManager().getClientServerInfo();
}
private boolean closeAllWindows(boolean duringExit) {
// create copy to avoid ConcurrentModification exception caused by closing
// window
ArrayList<TopLevelWindowManager> modificationSafeCopy = new ArrayList<>(getMdiManager().getWindowManagers());
for (TopLevelWindowManager windowManager : modificationSafeCopy) {
boolean closed = closeWindow(windowManager.getManagerID(), duringExit);
if (!closed) {
// user canceled, don't keep going...
return false;
}
}
return true;
}
public boolean closeWindow(final java.lang.String windowID, final boolean exitIfLast) {
// called from DocumentWindow or from DatabaseWindow
final TopLevelWindowManager windowManager = getMdiManager().getWindowManager(windowID);
if (windowManager instanceof DocumentWindowManager) {
// we'll need to run some checks first
getMdiManager().showWindow(windowID);
getMdiManager().blockWindow(windowID);
CloseOption closeOption = checkBeforeClosing((DocumentWindowManager) windowManager);
if (closeOption.equals(CloseOption.CANCEL_CLOSE)) {
// user canceled
getMdiManager().unBlockWindow(windowID);
return false;
} else if (closeOption.equals(CloseOption.SAVE_AND_CLOSE)) {
AsynchClientTask closeTask = new AsynchClientTask("closing document",
AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
// if there is error saving the document, try to unblock the window
if (hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR) != null) {
getMdiManager().unBlockWindow(windowID);
getMdiManager().showWindow(windowID);
} else {
long openWindows = getMdiManager().closeWindow(windowManager.getManagerID());
if (exitIfLast && (openWindows == 0)) {
setBExiting(true);
exitApplication();
}
}
}
@Override
public boolean skipIfCancel(UserCancelException exc) {
// if save as new edition, don't skip
if (exc == UserCancelException.CANCEL_DELETE_OLD
|| exc == UserCancelException.CANCEL_NEW_NAME) {
return false;
} else {
return true;
}
}
};
if (((DocumentWindowManager) windowManager).getUser() == null
|| User.isGuest(((DocumentWindowManager) windowManager).getUser().getName())) {
JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(dialog, User.createGuestErrorMessage("saveDocument"), "Error...",
JOptionPane.ERROR_MESSAGE, null);
return false;
}
saveDocument((DocumentWindowManager) windowManager, true, closeTask);
return true;
} else {
long openWindows = getMdiManager().closeWindow(windowID);
if (exitIfLast && (openWindows == 0)) {
setBExiting(true);
exitApplication();
}
return true;
}
} else if (windowManager instanceof DatabaseWindowManager) {
// nothing to check here, just close it
long openWindows = getMdiManager().closeWindow(windowID);
if (exitIfLast && (openWindows == 0)) {
setBExiting(true);
exitApplication();
}
return true;
} else if (windowManager instanceof TestingFrameworkWindowManager) {
// nothing to check here, just close it
long openWindows = getMdiManager().closeWindow(windowID);
if (exitIfLast && (openWindows == 0)) {
setBExiting(true);
exitApplication();
}
return true;
} else if (windowManager instanceof BNGWindowManager) {
// nothing to check here, just close it
long openWindows = getMdiManager().closeWindow(windowID);
if (exitIfLast && (openWindows == 0)) {
setBExiting(true);
exitApplication();
}
return true;
} else if (windowManager instanceof FieldDataWindowManager) {
// nothing to check here, just close it
long openWindows = getMdiManager().closeWindow(windowID);
if (exitIfLast && (openWindows == 0)) {
setBExiting(true);
exitApplication();
}
return true;
} else {
return false;
}
}
private XmlTreeDiff compareDocuments(final VCDocument doc1, final VCDocument doc2,
DiffConfiguration comparisonSetting) throws Exception {
VCellThreadChecker.checkCpuIntensiveInvocation();
if ((DiffConfiguration.COMPARE_DOCS_SAVED != comparisonSetting)
&& (DiffConfiguration.COMPARE_DOCS_OTHER != comparisonSetting)) {
throw new RuntimeException("Unsupported comparison setting: " + comparisonSetting);
}
if (doc1.getDocumentType() != doc2.getDocumentType()) {
throw new RuntimeException("Only comparison of documents of the same type is currently supported");
}
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;
}
}
final XmlTreeDiff diffTree = XmlHelper.compareMerge(doc1XML, doc2XML, comparisonSetting, true);
return diffTree;
}
public XmlTreeDiff compareWithOther(final VCDocumentInfo docInfo1, final VCDocumentInfo docInfo2) {
VCDocument document1, document2;
try {
// get the VCDocument versions from documentManager
if (docInfo1 instanceof BioModelInfo && docInfo2 instanceof BioModelInfo) {
document1 = getDocumentManager().getBioModel((BioModelInfo) docInfo1);
document2 = getDocumentManager().getBioModel((BioModelInfo) docInfo2);
} else if (docInfo1 instanceof MathModelInfo && docInfo2 instanceof MathModelInfo) {
document1 = getDocumentManager().getMathModel((MathModelInfo) docInfo1);
document2 = getDocumentManager().getMathModel((MathModelInfo) docInfo2);
} else if (docInfo1 instanceof GeometryInfo && docInfo2 instanceof GeometryInfo) {
document1 = getDocumentManager().getGeometry((GeometryInfo) docInfo1);
document2 = getDocumentManager().getGeometry((GeometryInfo) docInfo2);
} else {
throw new IllegalArgumentException("The two documents are invalid or of different types.");
}
return compareDocuments(document1, document2, DiffConfiguration.COMPARE_DOCS_OTHER);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
public XmlTreeDiff compareWithSaved(VCDocument document) {
VCDocument savedVersion = null;
try {
if (document == null) {
throw new IllegalArgumentException("Invalid VC document: " + 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;
}
}
return compareDocuments(savedVersion, document, DiffConfiguration.COMPARE_DOCS_SAVED);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
public XmlTreeDiff compareApplications(BioModel bioModel, String appName1, String appName2) throws Exception {
// clone BioModel as bioModel1 and remove all but appName1
BioModel bioModel1 = (BioModel) BeanUtils.cloneSerializable(bioModel);
bioModel1.refreshDependencies();
SimulationContext[] allSimContexts1 = bioModel1.getSimulationContexts();
for (SimulationContext sc : allSimContexts1) {
if (!sc.getName().equals(appName1)) {
bioModel1.removeSimulationContext(sc);
}
}
// clone BioModel as bioModel2 and remove all but appName2
BioModel bioModel2 = (BioModel) BeanUtils.cloneSerializable(bioModel);
bioModel2.refreshDependencies();
SimulationContext[] allSimContexts2 = bioModel2.getSimulationContexts();
for (SimulationContext sc : allSimContexts2) {
if (!sc.getName().equals(appName2)) {
bioModel2.removeSimulationContext(sc);
}
}
return compareDocuments(bioModel1, bioModel2, DiffConfiguration.COMPARE_DOCS_SAVED);
}
public void connectToServer(TopLevelWindowManager requester, ClientServerInfo clientServerInfo) throws Exception {
getClientServerManager().connectNewServer(new VCellGuiInteractiveContext(requester), clientServerInfo);
}
public void logOut(final TopLevelWindowManager requester){
JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
StringBuilder dialogMessage = new StringBuilder();
dialogMessage.append("You are about to log out of the VCell client.\n\n");
if (requester instanceof DocumentWindowManager documentWindowManager){
if(!User.isGuest(documentWindowManager.getUser().getName())){
dialogMessage.append("""
Because VCell uses a browser-based login,
you'll be redirected to a logout page to
complete the logout process there.
""");
}
}
dialogMessage.append("Do you wish to continue?");
int confirm = JOptionPane.showOptionDialog(dialog, dialogMessage.toString(),
"Logout", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
new String[] { "Continue", "Cancel" }, "Continue");
if (confirm == JOptionPane.OK_OPTION) {
closeAllWindows(false);
getClientServerManager().cleanup(); //set VCell connection to null
getClientServerManager().getAsynchMessageManager().stopPolling();
Hashtable<String, Object> hash = new Hashtable<String, Object>();
Auth0ConnectionUtils auth0ConnectionUtils = getClientServerManager().auth0ConnectionUtils;
if (!getClientServerInfo().getUsername().equals(User.VCELL_GUEST_NAME)){
auth0ConnectionUtils.logOut();
}
Auth0ConnectionUtils.setShowLoginPopUp(true);
AsynchClientTask waitTask = new AsynchClientTask("wait for window closing",
AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
// wait until all windows are closed.
long startTime = System.currentTimeMillis();
while (true) {
long numOpenWindows = getMdiManager().closeWindow(ClientMDIManager.DATABASE_WINDOW_ID);
if (numOpenWindows == 0) {
break;
}
// if can't save all the documents, don't connect as thus throw exception.
if (System.currentTimeMillis() - startTime > 60000) {
throw UserCancelException.CANCEL_GENERIC;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
AsynchClientTask[] newTasks = newDocument(requester,
new VCDocument.DocumentCreationInfo(VCDocumentType.BIOMODEL_DOC, 0));
AsynchClientTask task0 = new AsynchClientTask("preparing", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get("windowManager");
if (windowManager != null) {
Frame frameParent = JOptionPane.getFrameForComponent(windowManager.getComponent());
ClientMDIManager.blockWindow(frameParent);
frameParent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
}
};
AsynchClientTask task1 = ClientLogin.popupLogin();
AsynchClientTask task2 = ClientLogin.loginWithAuth0(auth0ConnectionUtils);
AsynchClientTask task3 = ClientLogin.connectToServer(auth0ConnectionUtils, getClientServerInfo());
AsynchClientTask refresh = new AsynchClientTask("Refresh", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false,
false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
getMdiManager().refreshRecyclableWindows();
DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get("windowManager");
if (windowManager != null) {
Frame frameParent = JOptionPane.getFrameForComponent(windowManager.getComponent());
ClientMDIManager.unBlockWindow(frameParent);
frameParent.setCursor(Cursor.getDefaultCursor());
}
}
};
ArrayList<AsynchClientTask> tasks = new ArrayList<>(Arrays.stream(newTasks).toList());
tasks.add(0, waitTask);
tasks.add(task0);
tasks.add(task1);
tasks.add(task2);
tasks.add(task3);
tasks.add(refresh);
ClientTaskDispatcher.dispatch(null, hash, tasks.toArray(new AsynchClientTask[0]));
}
}
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");
}
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
return defaultDocument;
}
private MathModel createMathModel(String name, Geometry geometry) {
MathModel mathModel = new MathModel(null);
MathDescription mathDesc = mathModel.getMathDescription();
try {
mathDesc.setGeometry(geometry);
if (geometry.getDimension() == 0) {
mathDesc.addSubDomain(
new CompartmentSubDomain("Compartment", CompartmentSubDomain.NON_SPATIAL_PRIORITY));
} else {
try {
if (geometry.getDimension() > 0
&& geometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
geometry.getGeometrySurfaceDescription().updateAll();
}
} catch (ImageException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Geometric surface generation error: \n" + e.getMessage());
} catch (GeometryException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Geometric surface generation error: \n" + e.getMessage());
}
SubVolume subVolumes[] = geometry.getGeometrySpec().getSubVolumes();
for (int i = 0; i < subVolumes.length; i++) {
mathDesc.addSubDomain(new CompartmentSubDomain(subVolumes[i].getName(), subVolumes[i].getHandle()));
}
//
// add only those MembraneSubDomains corresponding to surfaces that acutally
// exist in geometry.
//
GeometricRegion regions[] = geometry.getGeometrySurfaceDescription().getGeometricRegions();
for (int i = 0; i < regions.length; i++) {
if (regions[i] instanceof SurfaceGeometricRegion) {
SurfaceGeometricRegion surfaceRegion = (SurfaceGeometricRegion) regions[i];
SubVolume subVolume1 = ((VolumeGeometricRegion) surfaceRegion.getAdjacentGeometricRegions()[0])
.getSubVolume();
SubVolume subVolume2 = ((VolumeGeometricRegion) surfaceRegion.getAdjacentGeometricRegions()[1])
.getSubVolume();
CompartmentSubDomain compartment1 = mathDesc.getCompartmentSubDomain(subVolume1.getName());
CompartmentSubDomain compartment2 = mathDesc.getCompartmentSubDomain(subVolume2.getName());
MembraneSubDomain membraneSubDomain = mathDesc.getMembraneSubDomain(compartment1, compartment2);
if (membraneSubDomain == null) {
SurfaceClass surfaceClass = geometry.getGeometrySurfaceDescription()
.getSurfaceClass(subVolume1, subVolume2);
membraneSubDomain = new MembraneSubDomain(compartment1, compartment2,
surfaceClass.getName());
mathDesc.addSubDomain(membraneSubDomain);
}
}
}
}
mathDesc.isValid();
mathModel.setName(name);
} catch (Exception e) {
e.printStackTrace(System.out);
}
return mathModel;
}
public void createMathModelFromApplication(final BioModelWindowManager requester, final String name,
final SimulationContext simContext) {
if (simContext == null) {
PopupGenerator.showErrorDialog(requester,
"Selected Application is null, cannot generate corresponding math model");
return;
}
switch (simContext.getApplicationType()) {
case NETWORK_STOCHASTIC:
break;
case RULE_BASED_STOCHASTIC:
case NETWORK_DETERMINISTIC:
}
AsynchClientTask task1 = new AsynchClientTask("Creating MathModel from BioModel Application",
AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
MathModel newMathModel = new MathModel(null);
// Get corresponding mathDesc to create new mathModel.
MathDescription mathDesc = simContext.getMathDescription();
MathDescription newMathDesc = null;
newMathDesc = new MathDescription(name + "_" + (new java.util.Random()).nextInt());
try {
if (mathDesc.getGeometry().getDimension() > 0
&& mathDesc.getGeometry().getGeometrySurfaceDescription().getGeometricRegions() == null) {
mathDesc.getGeometry().getGeometrySurfaceDescription().updateAll();
}
} catch (ImageException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Geometric surface generation error:\n" + e.getMessage());
} catch (GeometryException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Geometric surface generation error:\n" + e.getMessage());
}
newMathDesc.setGeometry(mathDesc.getGeometry());
newMathDesc.read_database(new CommentStringTokenizer(mathDesc.getVCML_database()));
newMathDesc.isValid();
newMathModel.setName(name);
newMathModel.setMathDescription(newMathDesc);
hashTable.put("newMathModel", newMathModel);
}
};
AsynchClientTask task2 = new AsynchClientTask("Creating MathModel from BioModel Application",
AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
MathModel newMathModel = (MathModel) hashTable.get("newMathModel");
DocumentWindowManager windowManager = createDocumentWindowManager(newMathModel);
if (simContext.getBioModel().getVersion() != null) {
((MathModelWindowManager) windowManager).setCopyFromBioModelAppVersionableTypeVersion(
new VersionableTypeVersion(VersionableType.BioModelMetaData,
simContext.getBioModel().getVersion()));
}
DocumentWindow dw = getMdiManager().createNewDocumentWindow(windowManager);
setFinalWindow(hashTable, dw);
}
};
ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable<String, Object>(),
new AsynchClientTask[] { task1, task2 }, false);
}
public void createBioModelFromApplication(final BioModelWindowManager requester, final String name,
final SimulationContext simContext) {
if (simContext == null) {
PopupGenerator.showErrorDialog(requester,
"Selected Application is null, cannot generate corresponding bio model");
return;
}
if (simContext.isRuleBased()) {
createRuleBasedBioModelFromApplication(requester, name, simContext);
return;
}
AsynchClientTask task1 = new AsynchClientTask("Creating BioModel from BioModel Application",
AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
MathMapping transformedMathMapping = simContext.createNewMathMapping();
BioModel newBioModel = new BioModel(null);
SimulationContext transformedSimContext = transformedMathMapping
.getTransformation().transformedSimContext;
Model newModel = transformedSimContext.getModel();
newBioModel.setModel(newModel);
RbmModelContainer rbmmc = newModel.getRbmModelContainer();
for (RbmObservable o : rbmmc.getObservableList()) {
rbmmc.removeObservable(o);
}
for (ReactionRule r : rbmmc.getReactionRuleList()) {
rbmmc.removeReactionRule(r);
}
for (ReactionStep rs : newModel.getReactionSteps()) {
String oldName = rs.getName();
if (oldName.startsWith("_reverse_")) {
String newName = newModel.getReactionName("rev", oldName.substring("_reverse_".length()));
rs.setName(newName);
}
}
hashTable.put("newBioModel", newBioModel);
}
};
AsynchClientTask task2 = new AsynchClientTask("Creating BioModel from BioModel Application",
AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
BioModel newBioModel = (BioModel) hashTable.get("newBioModel");
DocumentWindowManager windowManager = createDocumentWindowManager(newBioModel);
// if(simContext.getBioModel().getVersion() != null){
// ((BioModelWindowManager)windowManager). setCopyFromBioModelAppVersionableTypeVersion(
// new VersionableTypeVersion(VersionableType.BioModelMetaData, simContext.getBioModel().getVersion()));
// }
getMdiManager().createNewDocumentWindow(windowManager);
}
};
ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable<String, Object>(),
new AsynchClientTask[] { task1, task2 }, false);
}
public void createRuleBasedBioModelFromApplication(final BioModelWindowManager requester, final String name,
final SimulationContext simContext) {
if (simContext == null) {
PopupGenerator.showErrorDialog(requester,
"Selected Application is null, cannot generate corresponding bio model");
return;
}
AsynchClientTask task1 = new AsynchClientTask("Creating BioModel from BioModel Application",
AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
MathMapping transformedMathMapping = simContext.createNewMathMapping();
BioModel newBioModel = new BioModel(null);
SimulationContext transformedSimContext = transformedMathMapping
.getTransformation().transformedSimContext;
Model model = transformedSimContext.getModel();
newBioModel.setModel(model);
hashTable.put("newBioModel", newBioModel);
}
};
AsynchClientTask task2 = new AsynchClientTask("Creating BioModel from BioModel Application",
AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
BioModel newBioModel = (BioModel) hashTable.get("newBioModel");
DocumentWindowManager windowManager = createDocumentWindowManager(newBioModel);