use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.
the class ClientRequestManager method openAfterChecking.
private void openAfterChecking(VCDocumentInfo documentInfo, final TopLevelWindowManager requester, final boolean inNewWindow) {
final String DOCUMENT_INFO = "documentInfo";
final String SEDML_TASK = "SedMLTask";
final String SEDML_MODEL = "SedMLModel";
final String BNG_UNIT_SYSTEM = "bngUnitSystem";
/* asynchronous and not blocking any window */
bOpening = true;
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
// may want to insert corrected VCDocumentInfo later if our import debugger corrects it (BNGL Debugger).
hashTable.put(DOCUMENT_INFO, documentInfo);
// start a thread that gets it and updates the GUI by creating a new document desktop
String taskName = null;
if (documentInfo instanceof ExternalDocInfo) {
taskName = "Importing document";
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
File file = externalDocInfo.getFile();
if (file != null && !file.getName().isEmpty() && file.getName().endsWith("bngl")) {
BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
String fileText;
String originalFileText;
try {
fileText = BeanUtils.readBytesFromFile(file, null);
originalFileText = new String(fileText);
} catch (IOException e1) {
e1.printStackTrace();
DialogUtils.showErrorDialog(requester.getComponent(), "<html>Error reading file " + file.getPath() + "</html>");
return;
}
Reader reader = externalDocInfo.getReader();
boolean bException = true;
while (bException) {
try {
BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
boolean bStochastic = true;
boolean bRuleBased = true;
SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("temp NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(ruleBasedSimContext);
RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
RbmUtils.reactionRuleLabelIndex = 0;
RbmUtils.reactionRuleNames.clear();
ASTModel astModel = RbmUtils.importBnglFile(reader);
// for now, hasUnitSystem() always returns false
if (astModel.hasUnitSystem()) {
bngUnitSystem = astModel.getUnitSystem();
}
if (astModel.hasCompartments()) {
Structure struct = bioModel.getModel().getStructure(0);
if (struct != null) {
bioModel.getModel().removeStructure(struct);
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
if (!astModel.hasMolecularDefinitions()) {
System.out.println("Molecular Definition Block missing.");
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
} else {
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
}
astModel.jjtAccept(constructionVisitor, rbmModelContainer);
bException = false;
} catch (final Exception e) {
e.printStackTrace(System.out);
BNGLDebuggerPanel panel = new BNGLDebuggerPanel(fileText, e);
int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, "Bngl Debugger: " + file.getName());
if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
throw new UserCancelException("Canceling Import");
}
// inserting <potentially> corrected DocumentInfo
fileText = panel.getText();
externalDocInfo = new ExternalDocInfo(panel.getText());
reader = externalDocInfo.getReader();
hashTable.put(DOCUMENT_INFO, externalDocInfo);
}
}
if (!originalFileText.equals(fileText)) {
// file has been modified
String message = "Importing <b>" + file.getName() + "</b> into vCell. <br>Overwrite the file on the disk?<br>";
message = "<html>" + message + "</html>";
Object[] options = { "Overwrite and Import", "Import Only", "Cancel" };
int returnCode = JOptionPane.showOptionDialog(requester.getComponent(), message, "Bngl Debugger", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
if (returnCode == JOptionPane.YES_OPTION) {
try {
FileWriter fw = new FileWriter(file);
fw.write(fileText);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} else if (returnCode == JOptionPane.CANCEL_OPTION || returnCode == JOptionPane.CLOSED_OPTION) {
return;
}
}
if (!(bngUnitSystem.getOrigin() == BngUnitOrigin.PARSER)) {
BNGLUnitsPanel panel = new BNGLUnitsPanel(bngUnitSystem);
int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, " Bngl Units Selector", null, false);
if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
// TODO: or do nothing and continue with default values?
return;
} else {
bngUnitSystem = panel.getUnits();
}
}
hashTable.put(BNG_UNIT_SYSTEM, bngUnitSystem);
} else if (file != null && !file.getName().isEmpty() && file.getName().toLowerCase().endsWith(".sedml")) {
try {
XMLSource xmlSource = externalDocInfo.createXMLSource();
File sedmlFile = xmlSource.getXmlFile();
SedML sedml = Libsedml.readDocument(sedmlFile).getSedMLModel();
if (sedml == null || sedml.getModels().isEmpty()) {
return;
}
AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(), file.getName());
hashTable.put(SEDML_MODEL, sedml);
hashTable.put(SEDML_TASK, chosenTask);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("failed to read document: " + e.getMessage(), e);
}
} else if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
try {
ArchiveComponents ac = null;
ac = Libsedml.readSEDMLArchive(new FileInputStream(file));
SEDMLDocument doc = ac.getSedmlDocument();
SedML sedml = doc.getSedMLModel();
if (sedml == null) {
throw new RuntimeException("Failed importing " + file.getName());
}
if (sedml.getModels().isEmpty()) {
throw new RuntimeException("Unable to find any model in " + file.getName());
}
AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(), file.getName());
hashTable.put(SEDML_MODEL, sedml);
hashTable.put(SEDML_TASK, chosenTask);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("failed to read archive: " + e.getMessage(), e);
}
}
} else {
taskName = "Loading document '" + documentInfo.getVersion().getName() + "' from database";
}
AsynchClientTask task0 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
public void run(Hashtable<String, Object> hashTable) throws Exception {
if (!inNewWindow) {
// request was to replace the document in an existing window
getMdiManager().blockWindow(requester.getManagerID());
}
}
};
AsynchClientTask task1 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
VCDocument doc = null;
VCDocumentInfo documentInfo = (VCDocumentInfo) hashTable.get(DOCUMENT_INFO);
if (documentInfo instanceof BioModelInfo) {
BioModelInfo bmi = (BioModelInfo) documentInfo;
doc = getDocumentManager().getBioModel(bmi);
} else if (documentInfo instanceof MathModelInfo) {
MathModelInfo mmi = (MathModelInfo) documentInfo;
doc = getDocumentManager().getMathModel(mmi);
} else if (documentInfo instanceof GeometryInfo) {
GeometryInfo gmi = (GeometryInfo) documentInfo;
doc = getDocumentManager().getGeometry(gmi);
} else if (documentInfo instanceof ExternalDocInfo) {
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
File file = externalDocInfo.getFile();
if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
TranslationLogger transLogger = new TranslationLogger(requester);
doc = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, (SedML) hashTable.get(SEDML_MODEL), (AbstractTask) hashTable.get(SEDML_TASK));
} else if (!externalDocInfo.isXML()) {
if (hashTable.containsKey(BNG_UNIT_SYSTEM)) {
// not XML, look for BNGL etc.
// we use the BngUnitSystem already created during the 1st pass
BngUnitSystem bngUnitSystem = (BngUnitSystem) hashTable.get(BNG_UNIT_SYSTEM);
BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
SimulationContext odeSimContext = bioModel.addNewSimulationContext("BioNetGen app", SimulationContext.Application.NETWORK_DETERMINISTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(ruleBasedSimContext);
appList.add(odeSimContext);
// set convention for initial conditions in generated application for seed species (concentration or count)
ruleBasedSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
odeSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
RbmUtils.reactionRuleLabelIndex = 0;
RbmUtils.reactionRuleNames.clear();
Reader reader = externalDocInfo.getReader();
ASTModel astModel = RbmUtils.importBnglFile(reader);
if (bioModel.getModel() != null && bioModel.getModel().getVcMetaData() != null) {
VCMetaData vcMetaData = bioModel.getModel().getVcMetaData();
vcMetaData.setFreeTextAnnotation(bioModel, astModel.getProlog());
}
if (astModel.hasCompartments()) {
Structure struct = bioModel.getModel().getStructure(0);
if (struct != null) {
bioModel.getModel().removeStructure(struct);
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
if (!astModel.hasMolecularDefinitions()) {
System.out.println("Molecular Definition Block missing. Extracting it from Species, Reactions, Obserbables.");
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
} else {
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
}
// we'll convert the kinetic parameters to BngUnitSystem inside the visit(ASTKineticsParameter...)
astModel.jjtAccept(constructionVisitor, rbmModelContainer);
// set the volume in the newly created application to BngUnitSystem.bnglModelVolume
// TODO: set the right values if we import compartments from the bngl file!
// if(!bngUnitSystem.isConcentration()) {
Expression sizeExpression = new Expression(bngUnitSystem.getVolume());
ruleBasedSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
odeSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
// }
// we remove the NFSim application if any seed species is clamped because NFSim doesn't know what to do with it
boolean bClamped = false;
for (SpeciesContextSpec scs : ruleBasedSimContext.getReactionContext().getSpeciesContextSpecs()) {
if (scs.isConstant()) {
bClamped = true;
break;
}
}
if (bClamped) {
bioModel.removeSimulationContext(ruleBasedSimContext);
}
// // TODO: DON'T delete this code
// // the code below is needed if we also want to create simulations, example for 1 rule based simulation
// // it is rule-based so it wont have to flatten, should be fast.
// MathMappingCallback callback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
// NetworkGenerationRequirements networkGenerationRequirements = null; // network generation should not be executed.
// ruleBasedSimContext.refreshMathDescription(callback,networkGenerationRequirements);
// Simulation sim = ruleBasedSimContext.addNewSimulation(SimulationOwner.DEFAULT_SIM_NAME_PREFIX,callback,networkGenerationRequirements);
doc = bioModel;
}
} else {
// is XML
try (TranslationLogger transLogger = new TranslationLogger(requester)) {
XMLSource xmlSource = externalDocInfo.createXMLSource();
org.jdom.Element rootElement = xmlSource.getXmlDoc().getRootElement();
String xmlType = rootElement.getName();
String modelXmlType = null;
if (xmlType.equals(XMLTags.VcmlRootNodeTag)) {
// For now, assuming that <vcml> element has only one child (biomodel, mathmodel or geometry).
// Will deal with multiple children of <vcml> Element when we get to model composition.
@SuppressWarnings("unchecked") List<Element> childElementList = rootElement.getChildren();
// assuming first child is the biomodel, mathmodel or geometry.
Element modelElement = childElementList.get(0);
modelXmlType = modelElement.getName();
}
if (xmlType.equals(XMLTags.BioModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.BioModelTag))) {
doc = XmlHelper.XMLToBioModel(xmlSource);
} else if (xmlType.equals(XMLTags.MathModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.MathModelTag))) {
doc = XmlHelper.XMLToMathModel(xmlSource);
} else if (xmlType.equals(XMLTags.GeometryTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.GeometryTag))) {
doc = XmlHelper.XMLToGeometry(xmlSource);
} else if (xmlType.equals(XMLTags.SbmlRootNodeTag)) {
Namespace namespace = rootElement.getNamespace(XMLTags.SBML_SPATIAL_NS_PREFIX);
boolean bIsSpatial = (namespace == null) ? false : true;
doc = XmlHelper.importSBML(transLogger, xmlSource, bIsSpatial);
} else if (xmlType.equals(XMLTags.CellmlRootNodeTag)) {
if (requester instanceof BioModelWindowManager) {
doc = XmlHelper.importBioCellML(transLogger, xmlSource);
} else {
doc = XmlHelper.importMathCellML(transLogger, xmlSource);
}
} else if (xmlType.equals(MicroscopyXMLTags.FRAPStudyTag)) {
doc = VFrapXmlHelper.VFRAPToBioModel(hashTable, xmlSource, getDocumentManager(), requester);
} else if (xmlType.equals(XMLTags.SedMLTypeTag)) {
doc = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, (SedML) hashTable.get(SEDML_MODEL), (AbstractTask) hashTable.get(SEDML_TASK));
} else {
// unknown XML format
throw new RuntimeException("unsupported XML format, first element tag is <" + rootElement.getName() + ">");
}
if (externalDocInfo.getDefaultName() != null) {
doc.setName(externalDocInfo.getDefaultName());
}
}
}
if (doc == null) {
File f = externalDocInfo.getFile();
if (f != null) {
throw new RuntimeException("Unable to determine type of file " + f.getCanonicalPath());
}
throw new ProgrammingException();
}
}
// create biopax objects using annotation
if (doc instanceof BioModel) {
BioModel bioModel = (BioModel) doc;
try {
bioModel.getVCMetaData().createBioPaxObjects(bioModel);
} catch (Exception e) {
e.printStackTrace();
}
}
requester.prepareDocumentToLoad(doc, inNewWindow);
hashTable.put("doc", doc);
}
};
AsynchClientTask task2 = new AsynchClientTask("Showing document", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
try {
Throwable exc = (Throwable) hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR);
if (exc == null) {
VCDocument doc = (VCDocument) hashTable.get("doc");
DocumentWindowManager windowManager = null;
if (inNewWindow) {
windowManager = createDocumentWindowManager(doc);
// request was to create a new top-level window with this doc
getMdiManager().createNewDocumentWindow(windowManager);
// if (windowManager instanceof BioModelWindowManager) {
// ((BioModelWindowManager)windowManager).preloadApps();
// }
} else {
// request was to replace the document in an existing window
windowManager = (DocumentWindowManager) requester;
getMdiManager().setCanonicalTitle(requester.getManagerID());
windowManager.resetDocument(doc);
}
hashTable.put(WIN_MGR_KEY, windowManager);
}
} finally {
if (!inNewWindow) {
getMdiManager().unBlockWindow(requester.getManagerID());
}
bOpening = false;
}
}
};
AsynchClientTask task3 = new AsynchClientTask("Special Layout", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
// TODO Auto-generated method stub
if (documentInfo instanceof ExternalDocInfo) {
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
if (externalDocInfo.isBioModelsNet()) {
DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
if (windowManager instanceof BioModelWindowManager) {
((BioModelWindowManager) windowManager).specialLayout();
}
}
}
}
};
AsynchClientTask task4 = new AsynchClientTaskFunction(ClientRequestManager::setWindowFocus, "Set window focus", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false);
ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] { task0, task1, task2, task3, task4 }, false);
}
use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.
the class ClientRequestManager method changeGeometry0.
private void changeGeometry0(final TopLevelWindowManager requester, final SimulationContext simContext) {
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);
}
}
}
};
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] { selectDocumentTypeTask, selectLoadGeomTask, processGeometryTask, setNewGeometryTask }, false);
}
use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.
the class ClientRequestManager method startExport.
/**
* Insert the method's description here.
* Creation date: (6/15/2004 2:37:01 AM)
*/
public void startExport(final OutputContext outputContext, Component requester, final ExportSpecs exportSpecs) {
// start a thread to get it; not blocking any window/frame
AsynchClientTask task1 = new AsynchClientTask("starting exporting", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
getClientServerManager().getJobManager().startExport(outputContext, exportSpecs);
}
};
ClientTaskDispatcher.dispatch(requester, new Hashtable<String, Object>(), new AsynchClientTask[] { task1 });
}
use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.
the class ClientRequestManager method getSaveImageAndGeometryTask.
private AsynchClientTask getSaveImageAndGeometryTask() {
final AsynchClientTask saveImageAndGeometryTask = new AsynchClientTask("creating geometry", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
getClientTaskStatusSupport().setMessage("Getting new Geometry name...");
String newGeometryName = null;
while (true) {
newGeometryName = ClientRequestManager.this.getMdiManager().getDatabaseWindowManager().showSaveDialog(((Geometry) hashTable.get("doc")).getDocumentType(), (Component) hashTable.get(ClientRequestManager.GUI_PARENT), (newGeometryName == null ? "NewGeometry" : newGeometryName));
if (newGeometryName == null || newGeometryName.trim().length() == 0) {
newGeometryName = null;
DialogUtils.showWarningDialog((Component) hashTable.get(ClientRequestManager.GUI_PARENT), "New Geometry name cannot be empty.");
continue;
}
// Check name conflict
GeometryInfo[] geometryInfos = ClientRequestManager.this.getDocumentManager().getGeometryInfos();
boolean bNameConflict = false;
for (int i = 0; i < geometryInfos.length; i++) {
if (geometryInfos[i].getVersion().getOwner().equals(ClientRequestManager.this.getDocumentManager().getUser())) {
if (geometryInfos[i].getVersion().getName().equals(newGeometryName)) {
bNameConflict = true;
break;
}
}
}
if (bNameConflict) {
DialogUtils.showWarningDialog((Component) hashTable.get(ClientRequestManager.GUI_PARENT), "A Geometry with name " + newGeometryName + " already exists. Choose a different name.");
continue;
} else {
break;
}
}
getClientTaskStatusSupport().setMessage("Saving image portion of Geometry...");
saveImageAutoName(ClientRequestManager.this, ((Geometry) hashTable.get("doc")).getGeometrySpec().getImage());
getClientTaskStatusSupport().setMessage("Saving final Geometry...");
ClientRequestManager.this.getDocumentManager().saveAsNew((Geometry) hashTable.get("doc"), newGeometryName);
}
};
return saveImageAndGeometryTask;
}
use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.
the class ClientRequestManager method downloadExportedData.
/**
* Comment
*/
public static void downloadExportedData(final Component requester, final UserPreferences userPrefs, final ExportEvent evt) {
AsynchClientTask task1 = new AsynchClientTask("Retrieving data from '" + evt.getLocation() + "'", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
final Exception[] excArr = new Exception[] { null };
final boolean[] bFlagArr = new boolean[] { false };
final ByteArrayOutputStream[] baosArr = new ByteArrayOutputStream[1];
final HttpGet[] httpGetArr = new HttpGet[1];
final ImageJConnection[] imagejConnetArr = new ImageJConnection[1];
// Start download of exported file in separate thread that is interruptible (apache HTTPClient)
Thread interruptible = new Thread(new Runnable() {
@Override
public void run() {
if (getClientTaskStatusSupport() != null) {
getClientTaskStatusSupport().setMessage("downloading data...");
}
CloseableHttpClient httpclient = HttpClients.createDefault();
httpGetArr[0] = new HttpGet(evt.getLocation());
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpGetArr[0]);
HttpEntity entity = response.getEntity();
if (entity != null) {
long size = entity.getContentLength();
InputStream instream = entity.getContent();
try {
// Thread.sleep(60000);
if (size > 0) {
baosArr[0] = new ByteArrayOutputStream((int) size);
} else {
baosArr[0] = new ByteArrayOutputStream();
}
IOUtils.copy(instream, baosArr[0]);
} finally {
instream.close();
}
}
} catch (Exception e) {
excArr[0] = e;
} finally {
if (imagejConnetArr[0] != null) {
imagejConnetArr[0].closeConnection();
}
if (response != null) {
try {
response.close();
} catch (Exception e) {
}
}
if (httpclient != null) {
try {
httpclient.close();
} catch (Exception e) {
}
}
bFlagArr[0] = true;
}
}
});
interruptible.start();
// Wait for download to 1-finish, 2-fail or 3-be cancelled by user
while (!bFlagArr[0]) {
if (getClientTaskStatusSupport() != null && getClientTaskStatusSupport().isInterrupted()) {
// user cancelled
if (httpGetArr[0] != null) {
httpGetArr[0].abort();
}
if (imagejConnetArr[0] != null) {
imagejConnetArr[0].closeConnection();
}
throw UserCancelException.CANCEL_GENERIC;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// caused by pressing 'cancel' button on progresspopup
if (httpGetArr[0] != null) {
httpGetArr[0].abort();
}
if (imagejConnetArr[0] != null) {
imagejConnetArr[0].closeConnection();
}
if (getClientTaskStatusSupport() != null && getClientTaskStatusSupport().isInterrupted()) {
throw UserCancelException.CANCEL_GENERIC;
}
}
}
if (excArr[0] != null) {
// download failed
throw excArr[0];
}
//
if (evt.getFormat() == null || !evt.getFormat().equals("IMAGEJ")) {
// save for file save operations
hashTable.put(BYTES_KEY, baosArr[0].toByteArray());
} else {
// NRRD format send to ImageJ
if (getClientTaskStatusSupport() != null) {
getClientTaskStatusSupport().setMessage("unpacking data...");
}
ByteArrayInputStream bais = new ByteArrayInputStream(baosArr[0].toByteArray());
ZipInputStream zis = null;
BufferedInputStream bis = null;
try {
zis = new ZipInputStream(bais);
ZipEntry entry = zis.getNextEntry();
// System.out.println("zipfile entry name="+entry.getName()+"zipfile entry size="+entry.getSize());
// File tempf = new File("C:\\temp\\tempf.nrrd");
// FileOutputStream fos = new FileOutputStream(tempf);
// byte[] mybuf = new byte[1000];
// int numread = 0;
// while((numread = zis.read(mybuf)) != -1){
// fos.write(mybuf, 0, numread);
// }
// fos.close();
TimeSpecs timeSpecs = evt.getTimeSpecs();
double[] timePoints = new double[timeSpecs.getEndTimeIndex() - timeSpecs.getBeginTimeIndex() + 1];
for (int tp = timeSpecs.getBeginTimeIndex(); tp <= timeSpecs.getEndTimeIndex(); tp++) {
timePoints[tp - timeSpecs.getBeginTimeIndex()] = timeSpecs.getAllTimes()[tp];
}
// doesn't open connection until later
imagejConnetArr[0] = new ImageJConnection(ImageJHelper.ExternalCommunicator.IMAGEJ);
bis = new BufferedInputStream(zis);
ImageJHelper.vcellSendNRRD(requester, bis, getClientTaskStatusSupport(), imagejConnetArr[0], "VCell exported data '" + entry.getName() + "'", timePoints, evt.getVariableSpecs().getVariableNames());
} finally {
if (zis != null) {
try {
zis.closeEntry();
zis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// finished, exit all further tasks
throw UserCancelException.CANCEL_GENERIC;
}
}
};
AsynchClientTask task2 = new AsynchClientTask("selecting file to save", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
// user pref could be null if trying local export
String defaultPath = getPreferredPath(userPrefs);
final VCFileChooser fileChooser = new VCFileChooser(defaultPath);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setMultiSelectionEnabled(false);
String name = evt.getDataIdString();
String suffix = null;
if (evt.getLocation().toLowerCase().endsWith(".mov")) {
fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_MOV);
fileChooser.setFileFilter(FileFilters.FILE_FILTER_MOV);
suffix = "_exported.mov";
} else if (evt.getLocation().toLowerCase().endsWith(".gif")) {
fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_GIF);
fileChooser.setFileFilter(FileFilters.FILE_FILTER_GIF);
suffix = "_exported.gif";
} else if (evt.getLocation().toLowerCase().endsWith(".jpeg")) {
fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_JPEG);
fileChooser.setFileFilter(FileFilters.FILE_FILTER_JPEG);
suffix = "_exported.jpeg";
} else {
fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_ZIP);
fileChooser.setFileFilter(FileFilters.FILE_FILTER_ZIP);
suffix = "_exported.zip";
}
File file = new File(name + suffix);
if (file.exists()) {
int count = 0;
do {
file = new File(name + "_" + count + suffix);
count++;
} while (file.exists());
}
fileChooser.setSelectedFile(file);
fileChooser.setDialogTitle("Save exported dataset...");
int approve = fileChooser.showSaveDialog(requester);
if (approve == JFileChooser.APPROVE_OPTION) {
hashTable.put("selectedFile", fileChooser.getSelectedFile());
} else {
fileChooser.setSelectedFile(null);
}
}
};
AsynchClientTask task3 = new AsynchClientTask("saving to file", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
File selectedFile = (File) hashTable.get("selectedFile");
if (selectedFile == null) {
return;
}
setPreferredPath(userPrefs, selectedFile);
// System.out.println("New preferred file path: " + newPath + ", Old preferred file path: " + defaultPath);
if (selectedFile.exists()) {
String question = null;
if (userPrefs != null) {
question = PopupGenerator.showWarningDialog(requester, userPrefs, UserMessage.warn_OverwriteFile, selectedFile.getAbsolutePath());
} else {
question = DialogUtils.showWarningDialog(requester, "Overwrite File?", "Overwrite file '" + selectedFile.getAbsolutePath() + "'?", new String[] { UserMessage.OPTION_OVERWRITE_FILE, UserMessage.OPTION_CANCEL }, UserMessage.OPTION_OVERWRITE_FILE);
}
if (question != null && question.equals(UserMessage.OPTION_CANCEL)) {
return;
}
}
byte[] bytes = (byte[]) hashTable.get(BYTES_KEY);
FileOutputStream fo = new FileOutputStream(selectedFile);
fo.write(bytes);
fo.close();
}
};
ClientTaskDispatcher.dispatch(requester, new Hashtable<String, Object>(), new AsynchClientTask[] { task1, task2, task3 }, false, true, null);
}
Aggregations