public JSONObject changePlateLocation(HttpSession session, JSONObject json) {
    Long plateId = json.getLong("plateId");
    String locationBarcode = json.getString("locationBarcode");

    try {
      String newLocation = LimsUtils.lookupLocation(locationBarcode);
      if (newLocation != null) {
        User user =
            securityManager.getUserByLoginName(
                SecurityContextHolder.getContext().getAuthentication().getName());
        // Plate<LinkedList<Plateable>, Plateable> plate = requestManager.<LinkedList<Plateable>,
        // Plateable> getPlateById(plateId);
        Plate<? extends List<? extends Plateable>, ? extends Plateable> plate =
            requestManager.getPlateById(plateId);
        plate.setLocationBarcode(locationBarcode);
        /*
        Note note = new Note();
        note.setInternalOnly(true);
        note.setText("Location changed to " + newLocation + " by " + user.getLoginName() + " on " + new Date());
        note.setOwner(user);
        note.setCreationDate(new Date());
        plate.getNotes().add(note);
        requestManager.saveSampleNote(sample, note);
        */
        requestManager.savePlate(plate);
      } else {
        return JSONUtils.SimpleJSONError("New location barcode not recognised");
      }
    } catch (IOException e) {
      e.printStackTrace();
      return JSONUtils.SimpleJSONError(e.getMessage());
    }

    return JSONUtils.SimpleJSONResponse("Plate saved successfully");
  }
  public JSONObject printPlateBarcodes(HttpSession session, JSONObject json) {
    try {
      User user =
          securityManager.getUserByLoginName(
              SecurityContextHolder.getContext().getAuthentication().getName());

      String serviceName = null;
      if (json.has("serviceName")) {
        serviceName = json.getString("serviceName");
      }

      MisoPrintService<File, PrintContext<File>> mps = null;
      if (serviceName == null) {
        Collection<MisoPrintService> services =
            printManager.listPrintServicesByBarcodeableClass(Plate.class);
        if (services.size() == 1) {
          mps = services.iterator().next();
        } else {
          return JSONUtils.SimpleJSONError(
              "No serviceName specified, but more than one available service able to print this barcode type.");
        }
      } else {
        mps = printManager.getPrintService(serviceName);
      }

      Queue<File> thingsToPrint = new LinkedList<File>();
      JSONArray ss = JSONArray.fromObject(json.getString("plates"));
      for (JSONObject s : (Iterable<JSONObject>) ss) {
        try {
          Long plateId = s.getLong("plateId");
          // Plate<LinkedList<Plateable>, Plateable>  plate = requestManager.<LinkedList<Plateable>,
          // Plateable> getPlateById(plateId);
          Plate<? extends List<? extends Plateable>, ? extends Plateable> plate =
              requestManager.getPlateById(plateId);
          // autosave the barcode if none has been previously generated
          if (plate.getIdentificationBarcode() == null
              || "".equals(plate.getIdentificationBarcode())) {
            requestManager.savePlate(plate);
          }
          File f = mps.getLabelFor(plate);
          if (f != null) thingsToPrint.add(f);
        } catch (IOException e) {
          e.printStackTrace();
          return JSONUtils.SimpleJSONError("Error printing barcodes: " + e.getMessage());
        }
      }
      PrintJob pj = printManager.print(thingsToPrint, mps.getName(), user);
      return JSONUtils.SimpleJSONResponse("Job " + pj.getJobId() + " : Barcodes printed.");
    } catch (MisoPrintException e) {
      e.printStackTrace();
      return JSONUtils.SimpleJSONError("Failed to print barcodes: " + e.getMessage());
    } catch (IOException e) {
      e.printStackTrace();
      return JSONUtils.SimpleJSONError("Failed to print barcodes: " + e.getMessage());
    }
  }
  @Override
  public Map<Integer, Set<TagBarcode>> getApplicableBarcodes() {
    if (tagBarcodeMap.isEmpty()) {
      if (requestManager != null) {
        tagBarcodeMap.put(1, new TreeSet<TagBarcode>());

        try {
          List<TagBarcode> barcodes =
              new ArrayList<TagBarcode>(
                  requestManager.listAllTagBarcodesByPlatform(PlatformType.ILLUMINA.getKey()));
          for (TagBarcode t : barcodes) {
            if (getName().equals(t.getStrategyName())
                && t.getName() != null
                && t.getName().startsWith("Index ")) {
              log.debug("Registering tag barcode: " + t.getName());
              tagBarcodeMap.get(1).add(t);
            }
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return tagBarcodeMap;
  }
  public JSONObject plateElementsDataTable(HttpSession session, JSONObject json) {
    if (json.has("plateId")) {
      try {
        JSONObject j = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        long plateId = json.getLong("plateId");

        Plate<? extends List<? extends Plateable>, ? extends Plateable> plate =
            requestManager.getPlateById(plateId);
        if (plate != null) {
          for (Plateable p : plate.getElements()) {
            if (p instanceof Library) {
              Library l = (Library) p;
              String strategyName = "No barcode";

              StringBuilder seqbuilder = new StringBuilder();
              if (!l.getTagBarcodes().isEmpty()) {
                int count = 1;
                Collection<TagBarcode> barcodes = l.getTagBarcodes().values();
                for (TagBarcode tb : barcodes) {
                  strategyName = tb.getStrategyName();
                  seqbuilder.append(tb.getSequence());
                  if (l.getTagBarcodes().values().size() > 1
                      && count < l.getTagBarcodes().values().size()) {
                    seqbuilder.append("-");
                  }
                  count++;
                }
              } else {
                log.info("No tag barcodes!");
              }

              jsonArray.add(
                  "['"
                      + l.getName()
                      + "','"
                      + l.getAlias()
                      + "','"
                      + strategyName
                      + "','"
                      + seqbuilder.toString()
                      + "','"
                      + "<a href=\"/miso/library/"
                      + l.getId()
                      + "\"><span class=\"ui-icon ui-icon-pencil\"></span></a>"
                      + "']");
            }
          }
        }
        j.put("elementsArray", jsonArray);
        return j;
      } catch (IOException e) {
        log.debug("Failed", e);
        return JSONUtils.SimpleJSONError("Failed: " + e.getMessage());
      }
    } else {
      return JSONUtils.SimpleJSONError("No plates to show");
    }
  }
 public JSONObject deletePlate(HttpSession session, JSONObject json) {
   try {
     User user =
         securityManager.getUserByLoginName(
             SecurityContextHolder.getContext().getAuthentication().getName());
     if (user.isAdmin()) {
       if (json.has("plateId")) {
         Long plateId = json.getLong("plateId");
         requestManager.deletePlate(requestManager.getPlateById(plateId));
         return JSONUtils.SimpleJSONResponse("Plate deleted");
       } else {
         return JSONUtils.SimpleJSONError("No plate specified to delete.");
       }
     } else {
       return JSONUtils.SimpleJSONError("Only admins can delete objects.");
     }
   } catch (IOException e) {
     e.printStackTrace();
     return JSONUtils.SimpleJSONError("Error getting currently logged in user.");
   }
 }
  public String jsonRestProjectList(Long projectId) throws IOException {
    StringBuilder sb = new StringBuilder();

    Project p = requestManager.getProjectById(projectId);
    sb.append("'id':'" + projectId + "'");
    sb.append(",");
    sb.append("'name':'" + p.getName() + "'");
    sb.append(",");
    sb.append("'alias':'" + p.getAlias() + "'");

    return "{" + sb.toString() + "}";
  }
 @RequestMapping(value = "projects", method = RequestMethod.GET)
 public @ResponseBody String jsonRest() throws IOException {
   StringBuilder sb = new StringBuilder();
   Collection<Project> lp = requestManager.listAllProjects();
   int pi = 0;
   for (Project p : lp) {
     pi++;
     sb.append(jsonRestProjectList(p.getProjectId()));
     if (pi < lp.size()) {
       sb.append(",");
     }
   }
   return "[" + sb.toString() + "]";
 }
  public JSONObject getPlateBarcode(HttpSession session, JSONObject json) {
    Long plateId = json.getLong("plateId");
    File temploc = new File(session.getServletContext().getRealPath("/") + "temp/");
    try {
      // Plate<LinkedList<Plateable>, Plateable> plate = requestManager.<LinkedList<Plateable>,
      // Plateable> getPlateById(plateId);
      Plate<? extends List<? extends Plateable>, ? extends Plateable> plate =
          requestManager.getPlateById(plateId);
      barcodeFactory.setPointPixels(1.5f);
      barcodeFactory.setBitmapResolution(600);
      RenderedImage bi = null;

      if (json.has("barcodeGenerator")) {
        BarcodeDimension dim = new BarcodeDimension(100, 100);
        if (json.has("dimensionWidth") && json.has("dimensionHeight")) {
          dim =
              new BarcodeDimension(
                  json.getDouble("dimensionWidth"), json.getDouble("dimensionHeight"));
        }
        BarcodeGenerator bg = BarcodeFactory.lookupGenerator(json.getString("barcodeGenerator"));
        if (bg != null) {
          bi = barcodeFactory.generateBarcode(plate, bg, dim);
        } else {
          return JSONUtils.SimpleJSONError(
              "'" + json.getString("barcodeGenerator") + "' is not a valid barcode generator type");
        }
      } else {
        bi = barcodeFactory.generateSquareDataMatrix(plate, 400);
      }

      if (bi != null) {
        File tempimage = misoFileManager.generateTemporaryFile("barcode-", ".png", temploc);
        if (ImageIO.write(bi, "png", tempimage)) {
          return JSONUtils.JSONObjectResponse("img", tempimage.getName());
        }
        return JSONUtils.SimpleJSONError("Writing temp image file failed.");
      } else {
        return JSONUtils.SimpleJSONError("Plate has no parseable barcode");
      }
    } catch (IOException e) {
      e.printStackTrace();
      return JSONUtils.SimpleJSONError(
          e.getMessage() + ": Cannot seem to access " + temploc.getAbsolutePath());
    }
  }
 @RequestMapping(value = "/libraries/rest/", method = RequestMethod.GET)
 public @ResponseBody Collection<Library> jsonRest() throws IOException {
   return requestManager.listAllLibraries();
 }
  public JSONObject saveImportedElements(HttpSession session, JSONObject json) {
    if (json.has("elements")) {
      Plate currentPlate = null;
      Pool currentPool = null;

      try {
        String description = json.getString("description");
        String creationDate = json.getString("creationDate");
        String plateMaterialType = null;
        if (json.has("plateMaterialType") && !json.getString("plateMaterialType").equals("")) {
          plateMaterialType = json.getString("plateMaterialType");
        }

        JSONObject elements = json.getJSONObject("elements");
        JSONArray pools = JSONArray.fromObject(elements.get("pools"));
        JSONArray savedPlates = new JSONArray();
        ObjectMapper mapper = new ObjectMapper();

        for (JSONArray innerPoolList : (Iterable<JSONArray>) pools) {
          for (JSONObject pool : (Iterable<JSONObject>) innerPoolList) {
            log.info(pool.toString());

            PlatePool platePool =
                mapper.readValue(pool.toString(), new TypeReference<PlatePool>() {});
            currentPool = platePool;

            for (Plate<LinkedList<Library>, Library> plate : platePool.getPoolableElements()) {
              JSONObject j = new JSONObject();

              //              if (json.has("tagBarcode")) {
              //                String tagBarcode = json.getString("tagBarcode");
              //
              // plate.setTagBarcode(requestManager.listAllTagBarcodesByStrategyName());
              //              }

              if (plate.getDescription() == null) {
                plate.setDescription(description);
              }

              if (plate.getCreationDate() == null) {
                // plate.setCreationDate(DateFormat.getInstance().parse(creationDate));
              }

              if (plate.getPlateMaterialType() == null && plateMaterialType != null) {
                plate.setPlateMaterialType(PlateMaterialType.valueOf(plateMaterialType));
              }
              log.info("Saving plate: " + plate.toString());
              currentPlate = plate;
              long plateId = requestManager.savePlate(plate);
              j.put("plateId", plateId);
              savedPlates.add(j);
              currentPlate = null;
            }

            log.info("Saving pool: " + pool.toString());
            requestManager.savePool(platePool);
            currentPool = null;
          }
        }
        JSONObject resp = new JSONObject();
        resp.put("plates", savedPlates);
        return resp;
      } catch (IOException e) {
        if (currentPool != null) {
          log.error(
              "Error saving pool elements on new plate save. Deleting pool "
                  + currentPool.toString());
          // clear out child elements to make sure plate meets delete requirements
          currentPool.getPoolableElements().clear();
          try {
            requestManager.deletePool(currentPool);
          } catch (IOException e1) {
            log.error("Cannot delete pool. Nothing left to do.");
            e1.printStackTrace();
          }
        }

        if (currentPlate != null) {
          log.error(
              "Error saving plate elements on new plate save. Deleting plate "
                  + currentPlate.toString());
          // clear out child elements to make sure plate meets delete requirements
          currentPlate.getElements().clear();
          try {
            requestManager.deletePlate(currentPlate);
          } catch (IOException e1) {
            log.error("Cannot delete plate. Nothing left to do.");
            e1.printStackTrace();
          }
        }

        log.error("Caused by...");
        e.printStackTrace();
        return JSONUtils.SimpleJSONError("Cannot save imported plate: " + e.getMessage());
      }
    } else {
      return JSONUtils.SimpleJSONError("No valid plates available to save");
    }
  }
Example #11
0
  @Deprecated
  public JSONObject previewExperiment(HttpSession session, JSONObject json) {
    String experimentId = (String) json.get("experimentId");

    try {
      Experiment e = requestManager.getExperimentById(Long.parseLong(experimentId));
      Collection<Run> runs = requestManager.listRunsByExperimentId(e.getExperimentId());

      session.setAttribute("experiment", e);

      StringBuilder rb = new StringBuilder();
      for (Run r : runs) {
        rb.append("<li><a href='/miso/run/")
            .append(r.getRunId())
            .append("'>")
            .append(r.getName())
            .append("</a></li>");
      }

      StringBuilder sb = new StringBuilder();
      if (e.getPool() != null) {
        if (e.getPlatform().getPlatformType().equals(PlatformType.ILLUMINA)) {
          for (Object dil : e.getPool().getDilutions()) {
            Sample s = ((LibraryDilution) dil).getLibrary().getSample();
            sb.append("<li><a href='/miso/sample/")
                .append(s.getSampleId())
                .append("'>")
                .append(s.getName())
                .append("</a></li>");
          }
        } else {
          for (Object dil : e.getPool().getDilutions()) {
            Sample s =
                ((emPCRDilution) dil).getEmPCR().getLibraryDilution().getLibrary().getSample();
            sb.append("<li><a href='/miso/sample/")
                .append(s.getSampleId())
                .append("'>")
                .append(s.getName())
                .append("</a></li>");
          }
        }
      }

      StringBuilder b = new StringBuilder();
      b.append(
          "<div onclick=\"Effect.toggle('preview"
              + experimentId
              + "','blind'); return false;\">"
              + "<img src=\"/styles/images/moreinfo.png\" class=\"previewimage\"/></div>");
      b.append("<br/><div id=\"preview" + experimentId + "\" class='exppreview'>");
      b.append("Title: <b>").append(e.getTitle()).append("</b><br/>");
      b.append("Description: <b>").append(e.getDescription()).append("</b><br/>");
      b.append("Samples: <ul class=\"bullets\">").append(sb.toString()).append("</ul>");
      b.append("Runs: <ul class=\"bullets\">").append(rb.toString()).append("</ul>");
      b.append("</div>");
      return JSONUtils.SimpleJSONResponse(b.toString());

    } catch (IOException e) {
      log.debug("Failed", e);
      return JSONUtils.SimpleJSONError("Failed");
    }
  }
Example #12
0
 public void update(Long runId) throws IOException {
   update(misoRequestManager.getRunById(runId));
 }
  @RequestMapping(value = "project/{projectId}", method = RequestMethod.GET)
  public @ResponseBody String jsonRestProject(@PathVariable Long projectId, ModelMap model)
      throws IOException {
    StringBuilder sb = new StringBuilder();

    Project p = requestManager.getProjectById(projectId);
    sb.append("'id':'" + projectId + "'");
    sb.append(",");
    sb.append("'name':'" + p.getName() + "'");
    sb.append(",");
    sb.append("'alias':'" + p.getAlias() + "'");
    sb.append(",");
    sb.append("'progress':'" + p.getProgress().name() + "'");
    sb.append(",");
    sb.append("'description':'" + p.getDescription() + "'");
    sb.append(",");

    sb.append("'overviews':[");
    if (p.getOverviews().size() > 0) {
      int oi = 0;
      for (ProjectOverview overview : p.getOverviews()) {
        oi++;
        sb.append("{");
        sb.append("'allSampleQcPassed':" + overview.getAllSampleQcPassed());
        sb.append(",");
        sb.append("'libraryPreparationComplete':" + overview.getLibraryPreparationComplete());
        sb.append(",");
        sb.append("'allLibrariesQcPassed':" + overview.getAllLibrariesQcPassed());
        sb.append(",");
        sb.append("'allPoolsConstructed':" + overview.getAllPoolsConstructed());
        sb.append(",");
        sb.append("'allRunsCompleted':" + overview.getAllRunsCompleted());
        sb.append(",");
        sb.append("'primaryAnalysisCompleted':" + overview.getPrimaryAnalysisCompleted());
        sb.append("}");
        if (oi < p.getOverviews().size()) {
          sb.append(",");
        }
      }
    }
    sb.append("]");
    sb.append(",");

    sb.append("'samples':[");
    Collection<Sample> samples = requestManager.listAllSamplesByProjectId(projectId);
    if (samples.size() > 0) {
      int si = 0;
      for (Sample sample : samples) {
        si++;
        String sampleQubit = "not available";
        if (requestManager.listAllSampleQCsBySampleId(sample.getId()).size() > 0) {
          ArrayList<SampleQC> sampleQcList =
              new ArrayList(requestManager.listAllSampleQCsBySampleId(sample.getId()));
          SampleQC lastQc = sampleQcList.get(sampleQcList.size() - 1);
          sampleQubit = (lastQc.getResults() != null ? lastQc.getResults().toString() : "");
        }
        sb.append("{");
        sb.append("'alias':'" + sample.getAlias() + "'");
        sb.append(",");
        sb.append(
            "'qcPassed':'"
                + (sample.getQcPassed() != null ? sample.getQcPassed().toString() : "")
                + "'");
        sb.append(",");

        sb.append(
            "'receivedDate':'"
                + (sample.getReceivedDate() != null
                    ? LimsUtils.getDateAsString(sample.getReceivedDate())
                    : "not available")
                + "'");
        sb.append(",");
        sb.append(
            "'sampleType':'"
                + (sample.getSampleType() != null ? sample.getSampleType() : "")
                + "'");
        sb.append(",");
        sb.append("'sampleQubit':'" + sampleQubit + "'");
        sb.append("}");

        if (si < samples.size()) {
          sb.append(",");
        }
      }
    }
    sb.append("]");
    sb.append(",");

    sb.append("'runs':[");
    Collection<Run> runs = requestManager.listAllRunsByProjectId(projectId);
    if (runs.size() > 0) {
      int ri = 0;
      for (Run run : runs) {
        ri++;
        if (!run.getStatus().getHealth().getKey().equals("Failed")) {
          ArrayList<String> runSamples = new ArrayList();
          Collection<SequencerPartitionContainer<SequencerPoolPartition>> spcs =
              requestManager.listSequencerPartitionContainersByRunId(run.getId());
          if (spcs.size() > 0) {
            for (SequencerPartitionContainer<SequencerPoolPartition> spc : spcs) {

              if (spc.getPartitions().size() > 0) {
                for (SequencerPoolPartition spp : spc.getPartitions()) {
                  if (spp.getPool() != null) {
                    if (spp.getPool().getDilutions().size() > 0) {
                      for (Dilution dilution : spp.getPool().getDilutions()) {
                        Sample sample = dilution.getLibrary().getSample();
                        if (sample.getProject().equals(p)) {
                          runSamples.add(sample.getAlias());
                        }
                      }
                    }
                  }
                }
              }
            }
          }

          sb.append("{");
          sb.append("'name':'" + run.getName() + "'");
          sb.append(",");
          sb.append(
              "'status':'"
                  + (run.getStatus() != null && run.getStatus().getHealth() != null
                      ? run.getStatus().getHealth().getKey()
                      : "")
                  + "'");
          sb.append(",");
          sb.append(
              "'startDate':'"
                  + (run.getStatus() != null && run.getStatus().getStartDate() != null
                      ? run.getStatus().getStartDate().toString()
                      : "")
                  + "'");
          sb.append(",");
          sb.append(
              "'completionDate':'"
                  + (run.getStatus() != null && run.getStatus().getCompletionDate() != null
                      ? run.getStatus().getCompletionDate().toString()
                      : "")
                  + "'");
          sb.append(",");
          sb.append(
              "'platformType':'"
                  + (run.getPlatformType() != null ? run.getPlatformType().getKey() : "")
                  + "'");
          sb.append(",");
          sb.append("'samples':[");
          if (runSamples.size() > 0) {
            int rsi = 0;
            for (String alias : runSamples) {
              rsi++;
              sb.append("{'sampleAlias':'" + alias + "'}");
              if (rsi < runSamples.size()) {
                sb.append(",");
              }
            }
          }
          sb.append("]");
          sb.append("}");
          if (ri < runs.size()) {
            sb.append(",");
          }
        }
      }
    }
    sb.append("]");

    return "{" + sb.toString() + "}";
  }
  private Map<String, Run> processRunJSON(
      HealthType ht, JSONArray runs, RequestManager requestManager) {
    Map<String, Run> updatedRuns = new HashMap<String, Run>();
    List<Run> runsToSave = new ArrayList<Run>();
    // 2011-01-25 15:37:27.093
    DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    DateFormat simpleLogDateFormat = new SimpleDateFormat("yyyyMMdd");
    Pattern simpleDateRegex = Pattern.compile("[0-9]{8}");

    StringBuilder sb = new StringBuilder();

    for (JSONObject run : (Iterable<JSONObject>) runs) {
      String runName = run.getString("runName");
      sb.append("Processing " + runName + "\n");
      log.debug("Processing " + runName);

      if (run.has("status")) {
        String xml = run.getString("status");
        Status is = new SolidStatus(xml);
        is.setHealth(ht);
        is.setRunName(runName);

        Run r = null;
        Matcher m = p.matcher(runName);
        if (m.matches()) {
          try {
            r = requestManager.getRunByAlias(runName);
          } catch (IOException ioe) {
            log.warn(
                "Cannot find run by this alias. This usually means the run hasn't been previously imported. If attemptRunPopulation is false, processing will not take place for this run!");
          }
        }

        try {
          if (attemptRunPopulation) {
            if (r == null) {
              log.debug("Saving new run and status: " + is.getRunName());
              r = new SolidRun(xml);
              r.getStatus().setHealth(ht);
              if (run.has("fullPath")) {
                r.setFilePath(run.getString("fullPath"));
              }

              SequencerReference sr = null;
              if (run.has("sequencerName")) {
                sr = requestManager.getSequencerReferenceByName(run.getString("sequencerName"));
                r.getStatus().setInstrumentName(run.getString("sequencerName"));
                r.setSequencerReference(sr);
              }
              if (r.getSequencerReference() == null) {
                sr = requestManager.getSequencerReferenceByName(m.group(1));
                r.getStatus().setInstrumentName(m.group(1));
                r.setSequencerReference(sr);
              }
              if (r.getSequencerReference() == null) {
                sr = requestManager.getSequencerReferenceByName(r.getStatus().getInstrumentName());
                r.setSequencerReference(sr);
              }

              if (r.getSequencerReference() != null) {
                if (run.has("startDate")) {
                  try {
                    log.debug("Updating start date:" + run.getString("startDate"));

                    Matcher m2 = simpleDateRegex.matcher(run.getString("startDate"));
                    if (m2.matches()) {
                      r.getStatus()
                          .setStartDate(simpleLogDateFormat.parse(run.getString("startDate")));
                    } else {
                      r.getStatus().setStartDate(logDateFormat.parse(run.getString("startDate")));
                    }
                  } catch (ParseException e) {
                    log.error(e.getMessage());
                    e.printStackTrace();
                  }
                }

                if (run.has("completionDate")) {
                  try {
                    if (run.get("completionDate") != null
                        && !run.getString("completionDate").equals("null")) {
                      log.debug("Updating completion date:" + run.getString("completionDate"));
                      r.getStatus()
                          .setCompletionDate(logDateFormat.parse(run.getString("completionDate")));
                    } else {
                      r.getStatus().setCompletionDate(null);
                    }
                  } catch (ParseException e) {
                    log.error(e.getMessage());
                    e.printStackTrace();
                  }
                }
              }
            } else {
              log.debug("Updating existing run and status: " + is.getRunName());

              r.setAlias(runName);
              r.setPlatformType(PlatformType.SOLID);

              if (r.getSequencerReference() == null) {
                SequencerReference sr = null;
                if (run.has("sequencerName")) {
                  sr = requestManager.getSequencerReferenceByName(run.getString("sequencerName"));
                  r.getStatus().setInstrumentName(run.getString("sequencerName"));
                  r.setSequencerReference(sr);
                }
                if (r.getSequencerReference() == null) {
                  sr = requestManager.getSequencerReferenceByName(m.group(1));
                  r.getStatus().setInstrumentName(m.group(1));
                  r.setSequencerReference(sr);
                }
                if (r.getSequencerReference() == null) {
                  sr =
                      requestManager.getSequencerReferenceByName(r.getStatus().getInstrumentName());
                  r.setSequencerReference(sr);
                }
              }
              if (r.getSequencerReference() != null) {
                if (run.has("startDate")) {
                  try {
                    log.debug("Updating start date:" + run.getString("startDate"));

                    Matcher m2 = simpleDateRegex.matcher(run.getString("startDate"));
                    if (m2.matches()) {
                      r.getStatus()
                          .setStartDate(simpleLogDateFormat.parse(run.getString("startDate")));
                    } else {
                      r.getStatus().setStartDate(logDateFormat.parse(run.getString("startDate")));
                    }
                  } catch (ParseException e) {
                    log.error(e.getMessage());
                    e.printStackTrace();
                  }
                }

                if (run.has("completionDate")) {
                  try {
                    if (run.get("completionDate") != null
                        && !run.getString("completionDate").equals("null")) {
                      log.debug("Updating completion date:" + run.getString("completionDate"));
                      r.getStatus()
                          .setCompletionDate(logDateFormat.parse(run.getString("completionDate")));
                    } else {
                      r.getStatus().setCompletionDate(null);
                    }
                  } catch (ParseException e) {
                    log.error(e.getMessage());
                    e.printStackTrace();
                  }
                }

                // update path if changed
                if (run.has("fullPath")
                    && !"".equals(run.getString("fullPath"))
                    && r.getFilePath() != null
                    && !"".equals(r.getFilePath())) {
                  if (!run.getString("fullPath").equals(r.getFilePath())) {
                    log.debug(
                        "Updating run file path:"
                            + r.getFilePath()
                            + " -> "
                            + run.getString("fullPath"));
                    r.setFilePath(run.getString("fullPath"));
                  }
                }

                // update status if run isn't completed or failed
                if (!r.getStatus().getHealth().equals(HealthType.Completed)
                    && !r.getStatus().getHealth().equals(HealthType.Failed)) {
                  log.debug(
                      "Saving previously saved status: "
                          + is.getRunName()
                          + " ("
                          + r.getStatus().getHealth().getKey()
                          + " -> "
                          + is.getHealth().getKey()
                          + ")");
                  r.setStatus(is);
                }
              }
            }

            if (r.getSequencerReference() != null) {
              List<SequencerPartitionContainer<SequencerPoolPartition>> fs =
                  ((SolidRun) r).getSequencerPartitionContainers();
              if (fs.isEmpty()) {
                if (run.has("containerId") && !"".equals(run.getString("containerId"))) {
                  Collection<SequencerPartitionContainer<SequencerPoolPartition>> pfs =
                      requestManager.listSequencerPartitionContainersByBarcode(
                          run.getString("containerId"));
                  if (!pfs.isEmpty()) {
                    if (pfs.size() == 1) {
                      SequencerPartitionContainer lf =
                          new ArrayList<SequencerPartitionContainer<SequencerPoolPartition>>(pfs)
                              .get(0);
                      if (lf.getSecurityProfile() != null && r.getSecurityProfile() == null) {
                        r.setSecurityProfile(lf.getSecurityProfile());
                      }
                      if (lf.getPlatform() == null
                          && r.getSequencerReference().getPlatform() != null) {
                        lf.setPlatform(r.getSequencerReference().getPlatform());
                      }
                      //                      else {
                      //                        lf.setPlatformType(PlatformType.SOLID);
                      //                      }
                      ((RunImpl) r).addSequencerPartitionContainer(lf);
                    }
                  } else {
                    log.debug("No containers linked to run " + r.getId() + ": creating...");
                    SequencerPartitionContainer f = new SequencerPartitionContainerImpl();
                    f.setSecurityProfile(r.getSecurityProfile());
                    f.initEmptyPartitions();
                    f.setIdentificationBarcode(run.getString("containerNum"));
                    if (f.getPlatform() == null
                        && r.getSequencerReference().getPlatform() != null) {
                      f.setPlatform(r.getSequencerReference().getPlatform());
                    }
                    //                    else {
                    //                      f.setPlatformType(PlatformType.SOLID);
                    //                    }
                    // f.setPaired(r.getPairedEnd());
                    ((RunImpl) r).addSequencerPartitionContainer(f);
                  }
                }
              } else {
                SequencerPartitionContainer f = fs.iterator().next();
                log.debug("Got container " + f.getId());

                if (f.getSecurityProfile() == null) {
                  f.setSecurityProfile(r.getSecurityProfile());
                }

                if (f.getPlatform() == null && r.getSequencerReference().getPlatform() != null) {
                  f.setPlatform(r.getSequencerReference().getPlatform());
                }
                //                else {
                //                  f.setPlatformType(PlatformType.SOLID);
                //                }

                if (run.has("containerId") && !"".equals(run.getString("containerId"))) {
                  f.setIdentificationBarcode(run.getString("containerId"));
                }

                long flowId = requestManager.saveSequencerPartitionContainer(f);
                f.setId(flowId);
              }

              updatedRuns.put(r.getAlias(), r);
              runsToSave.add(r);
            }
          }
        } catch (IOException e) {
          log.error(e.getMessage());
          e.printStackTrace();
        }
      }
    }

    try {
      if (runsToSave.size() > 0) {
        int[] saved = requestManager.saveRuns(runsToSave);
        log.info("Batch saved " + saved.length + " / " + runs.size() + " runs");
      }
    } catch (IOException e) {
      log.error("Couldn't save run batch: " + e.getMessage());
      e.printStackTrace();
    }

    return updatedRuns;
  }