Search in sources :

Example 1 with ImageJConnection

use of org.vcell.imagej.ImageJHelper.ImageJConnection 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);
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) ZipEntry(java.util.zip.ZipEntry) BufferedInputStream(java.io.BufferedInputStream) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) VCFileChooser(org.vcell.util.gui.VCFileChooser) TimeSpecs(cbit.vcell.export.server.TimeSpecs) ImageJConnection(org.vcell.imagej.ImageJHelper.ImageJConnection) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Hashtable(java.util.Hashtable) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) DataInputStream(java.io.DataInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) DataFormatException(java.util.zip.DataFormatException) UserCancelException(org.vcell.util.UserCancelException) ZipInputStream(java.util.zip.ZipInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) CSGObject(cbit.vcell.geometry.CSGObject) ChooseFile(cbit.vcell.client.task.ChooseFile) File(java.io.File)

Aggregations

ImageException (cbit.image.ImageException)1 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)1 ChooseFile (cbit.vcell.client.task.ChooseFile)1 TimeSpecs (cbit.vcell.export.server.TimeSpecs)1 CSGObject (cbit.vcell.geometry.CSGObject)1 GeometryException (cbit.vcell.geometry.GeometryException)1 PropertyVetoException (java.beans.PropertyVetoException)1 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 DataInputStream (java.io.DataInputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Hashtable (java.util.Hashtable)1 DataFormatException (java.util.zip.DataFormatException)1 GZIPInputStream (java.util.zip.GZIPInputStream)1 ZipEntry (java.util.zip.ZipEntry)1