@Test
  public void testMerlinDataLoaderU32() throws Exception {
    final String path = testFileFolder + "I13-20150210-101459-1.mib";
    IDataHolder dataHolder = LoaderFactory.getData(path, null);

    IDataset data = dataHolder.getDataset(0);
    int[] shape = data.getShape();
    assertEquals(515, shape[0], 0.0);
    assertEquals(515, shape[1], 0.0);
  }
  @Test
  public void testMerlinDataLoader() throws Exception {
    final String path = testFileFolder + "default1.mib";
    IDataHolder dataHolder = LoaderFactory.getData(path, null);

    IDataset data = dataHolder.getDataset(0);
    int[] shape = data.getShape();
    assertEquals(512, shape[0], 0.0);
    assertEquals(512, shape[1], 0.0);
    assertEquals(4095, data.max().intValue(), 0.0);
  }
  @Test
  public void loadLoaderFactory() throws Exception {

    IDataHolder dataHolder = LoaderFactory.getData(testFileFolder + file, null);

    IDataset data = dataHolder.getDataset("Portable Grey Map");
    // Check the first data point
    assertEquals(data.getDouble(0, 0), 0.0, 0.0);
    // Check the middle data point
    assertEquals(data.getDouble(512, 511), 15104.0, 0.0);
    // Check the last data point
    assertEquals(data.getDouble(1023, 1023), 0.0, 0.0);
  }
  private void processClientLocalUpdate() {
    DataBean bean = new DataBean();
    int gridDim = (int) Math.ceil(Math.sqrt(filesToLoad.size()));
    if (imageGrid != null) imageGrid.dispose();

    imageGrid = new PlotServerSWTImageGrid(gridDim, gridDim, canvas, plotViewName);
    imageGrid.setThumbnailSize(getPreferenceImageSize());
    Iterator<String> iter = filesToLoad.iterator();
    while (iter.hasNext()) {
      String filename = iter.next();
      try {
        IDataHolder holder = LoaderFactory.getData(filename);
        IDataset data = holder.getDataset(0);
        List<DatasetWithAxisInformation> datalist = new ArrayList<DatasetWithAxisInformation>();
        DatasetWithAxisInformation d = new DatasetWithAxisInformation();
        if (data != null) {
          d.setData(data);
          datalist.add(d);
          bean.setData(datalist);
        }
      } catch (Exception e) {
        logger.error("Error loading data with filename " + filename, e);
      }
      bean.putGuiParameter(GuiParameters.FILENAME, filename);
      processNewFile(bean);
    }
    if (liveActive) {
      sldProgress
          .getDisplay()
          .asyncExec(
              new Runnable() {
                @Override
                public void run() {
                  playback.moveToLast();
                }
              });
    }
  }
  @SuppressWarnings("unchecked")
  @Override
  public void update(Object source, Object changeCode) {
    if (stopLoading) return;

    if (source == ImageExplorerView.FOLDER_UPDATE_MARKER) { // Folder Update
      if (changeCode instanceof List<?>) {
        playback.clearPlayback();
        btnPlay
            .getDisplay()
            .asyncExec(
                new Runnable() {
                  @Override
                  public void run() {
                    resetPlaying(false);
                    if (isLive) {
                      playback.setDelay(50);
                      playback.setStepping(1);
                      playback.start();
                      btnPlay.setSelection(true);
                      btnPlay.setImage(imgStill);
                      execSvc.execute(playback);
                      if (!monActive)
                        CommandExecutor.executeCommand(
                            getViewSite(),
                            "uk.ac.diamond.scisoft.analysis.rcp.MontorDirectoryAction");
                      cmbDirectoryLocation.setText(currentDir);
                      isLive = false;
                    }
                  }
                });
        filesToLoad = (List<String>) changeCode;
        processClientLocalUpdate();
      }
    } else {
      if (source instanceof RMIPlotServer && changeCode instanceof String) {
        String viewName = (String) changeCode;
        if (!viewName.startsWith("Image Explorer")) return;
        RMIPlotServer server = (RMIPlotServer) source;
        try {
          String[] names = server.getGuiNames();
          final DataBean bean = server.getData(names[0]);
          // when imagegrid size is set it means we need to reset the grid
          if (bean != null && bean.getGuiParameters().get(GuiParameters.IMAGEGRIDSIZE) != null) {
            Display.getDefault()
                .syncExec(
                    new Runnable() {
                      @Override
                      public void run() {
                        Integer[] gridDim =
                            (Integer[]) bean.getGuiParameters().get(GuiParameters.IMAGEGRIDSIZE);
                        if (imageGrid != null) imageGrid.dispose();
                        imageGrid =
                            new PlotServerSWTImageGrid(
                                gridDim[0], gridDim[1], canvas, plotViewName);
                        imageGrid.setThumbnailSize(getPreferenceImageSize());
                      }
                    });
          }
          if (bean != null) {
            if (bean.getData().isEmpty()) {
              // We try to load the data from the filename if data not in the databean
              String filename = (String) bean.getGuiParameters().get(GuiParameters.FILENAME);
              if (filename == null) return;
              List<DatasetWithAxisInformation> data = new ArrayList<>();
              DatasetWithAxisInformation dwai = new DatasetWithAxisInformation();
              IDataHolder holder = LoaderFactory.getData(filename);
              IDataset loadedData = holder.getDataset(0);
              dwai.setData(loadedData);
              data.add(dwai);
              bean.setData(data);
            }
            processUpdate(bean);
          } else {
            throw new Exception("Databean is null. This image grid use is not supported.");
          }
        } catch (Exception e) {
          logger.error("Error updating data from server: ", e);
        }
      }
    }
  }
 public static void handleException(
     final ScanFileHolderException e,
     final IDataHolder dh,
     final String fileName,
     final double maxVal,
     final boolean unsigned,
     final int numBits)
     throws ScanFileHolderException, UnsupportedOperationException, IllegalArgumentException {
   /*
    * Need massive error handling here, since we get same type of
    * exception with different messages.
    * The exception throwing might change as time passes, the
    * current handling is determined on 2014-03-04.
    * "Unable" means we can not recover, the image could not be
    * created. Currently this can not happen, instead we get an
    * exception with "Error" in its message. See below.
    * "ScaledSaver" means not allowed parameters, that is use either 32 bits or float,
    * or <=16 bits with big enough max and not unsigned if there is any negative value.
    * "No writer" means the writer could not write the image (for
    * example bmp writer can save only RGBDataset), in this case
    * converting the dataset might help.
    * "Error" means other kind of problem, probably not recoverable.
    */
   do {
     if (StringUtils.matchStringWithPattern(e.getMessage(), ".*Unable.*", true)) break;
     final StringBuffer sb = new StringBuffer();
     if (StringUtils.matchStringWithPattern(e.getMessage(), ".*No writer.*", true)) {
       sb.append(e.getLocalizedMessage());
       sb.append("\n\nSuggestion: ");
       sb.append(
           "To save the image as "
               + FileUtils.getFileExtension(fileName)
               + " type, you can try to ");
       if (dh.getDataset(0) instanceof RGBDataset)
         sb.append("convert the RGB dataset to integer dataset.");
       else sb.append("convert the dataset to RGB dataset.");
       throw new IllegalArgumentException(sb.toString(), e.getCause());
     }
     if (StringUtils.matchStringWithPattern(e.getMessage(), ".*ScaledSaver.*", true)) {
       if (numBits > 16) // Currently impossible case
       break;
       sb.append(e.getLocalizedMessage());
       sb.append("\n\nSuggestion: ");
       sb.append(
           "To save the image as "
               + FileUtils.getFileExtension(fileName)
               + " type, you can try to any of these possibilites:\n");
       sb.append("- Choose 32 bits or float type.\n");
       double maxTotalValue = maxVal;
       boolean addedSignedHint = !unsigned;
       for (int i = 0; i < dh.size() && !addedSignedHint && maxVal > 0; i++) {
         final IDataset data = dh.getDataset(i);
         if (maxVal > 0) maxTotalValue = Math.max(data.max().doubleValue(), maxTotalValue);
         if (!addedSignedHint && (unsigned && data.min().doubleValue() < 0)) {
           sb.append("- Choose signed values.\n");
           addedSignedHint = true;
         }
       }
       if (maxTotalValue > maxVal)
         sb.append("- Choose max value >= max value of image (" + maxTotalValue + ").\n");
       sb.append("- Choose autoscale option.");
       throw new IllegalArgumentException(sb.toString(), e.getCause());
     }
     if (StringUtils.matchStringWithPattern(e.getMessage(), ".*Error.*", true)) break;
     throw new UnsupportedOperationException(
         "Unexpected error: " + e.getLocalizedMessage(), e.getCause());
   } while (false);
   throw e;
 }