public void parseStatsMessage(Message<Map<String, Map<String, byte[]>>> message)
     throws IOException {
   Map<String, Map<String, byte[]>> a = message.getPayload();
   for (String type : a.keySet()) {
     Map<String, byte[]> b = a.get(type);
     for (String filename : b.keySet()) {
       log.info("Processing stats for: " + filename);
       BufferedInputStream bis =
           new BufferedInputStream(new ByteArrayInputStream(b.get(filename)));
       File outFile = null;
       OutputStream out = null;
       try {
         outFile = new File(new File("/tmp/"), filename);
         try {
           out = new FileOutputStream(outFile);
           byte[] buf = new byte[16884];
           int len;
           while ((len = bis.read(buf)) > 0) {
             out.write(buf, 0, len);
           }
         } catch (IOException e) {
           log.error("Could not write temporary file: " + outFile.getAbsolutePath());
           e.printStackTrace();
         } finally {
           try {
             bis.close();
           } catch (IOException e) {
             // ignore
           }
         }
       } finally {
         if (out != null) {
           out.close();
         }
         if (outFile != null) {
           File newFile = misoFileManager.storeFile(Run.class, "stats", outFile);
           if (newFile != null && outFile.delete()) {
             File destination = new File(newFile.getParentFile(), newFile.getName().split("-")[0]);
             if (LimsUtils.checkDirectory(destination, true)) {
               if (LimsUtils.unzipFile(newFile, destination)) {
                 newFile.delete();
               }
             }
           }
         }
       }
     }
   }
 }
  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");
  }
Ejemplo n.º 3
0
 @Test
 public void testImportBulkInputXLS() {
   try {
     InputStream in =
         FormUtilsTests.class.getClassLoader().getResourceAsStream("test-bulk_input.xlsx");
     LimsUtils.writeFile(in, testSampleBulkInputXlsFile);
     User u = new UserImpl();
     u.setLoginName("testBulkImportUser");
     List<Sample> samples =
         FormUtils.importSampleInputSpreadsheet(
             testSampleBulkInputXlsFile,
             u,
             new MockFormTestRequestManager(),
             new DefaultLibraryNamingScheme());
     log.info("Imported :: " + LimsUtils.join(samples, " | "));
   } catch (Exception e) {
     e.printStackTrace();
     TestCase.fail();
   } finally {
     testSampleBulkInputXlsFile.delete();
   }
 }
 public JSONObject downloadPlateInputForm(HttpSession session, JSONObject json) {
   if (json.has("documentFormat")) {
     String documentFormat = json.getString("documentFormat");
     try {
       File f =
           misoFileManager.getNewFile(
               Plate.class,
               "forms",
               "PlateInputForm-" + LimsUtils.getCurrentDateAsString() + "." + documentFormat);
       FormUtils.createPlateInputSpreadsheet(f);
       return JSONUtils.SimpleJSONResponse("" + f.getName().hashCode());
     } catch (Exception e) {
       e.printStackTrace();
       return JSONUtils.SimpleJSONError("Failed to get plate input form: " + e.getMessage());
     }
   } else {
     return JSONUtils.SimpleJSONError("Missing project ID or document format supplied.");
   }
 }
Ejemplo n.º 5
0
  @Transactional(readOnly = false, rollbackFor = IOException.class)
  @TriggersRemove(
      cacheName = {"userCache", "lazyUserCache"},
      keyGenerator =
          @KeyGenerator(
              name = "HashCodeCacheKeyGenerator",
              properties = {
                @Property(name = "includeMethod", value = "false"),
                @Property(name = "includeParameterTypes", value = "false")
              }))
  public long saveUser(User user) throws IOException {
    Blob roleBlob = null;
    if (user.getRoles() != null) {
      List<String> roles = new ArrayList<String>(Arrays.asList(user.getRoles()));
      if (user.isExternal() && !roles.contains("ROLE_EXTERNAL")) roles.add("ROLE_EXTERNAL");
      if (user.isInternal() && !roles.contains("ROLE_INTERNAL")) roles.add("ROLE_INTERNAL");
      if (user.isAdmin() && !roles.contains("ROLE_ADMIN")) roles.add("ROLE_ADMIN");
      user.setRoles(roles.toArray(new String[user.getRoles().length]));

      try {
        if (user.getRoles().length > 0) {
          byte[] rbytes = LimsUtils.join(user.getRoles(), ",").getBytes();
          roleBlob = new SerialBlob(rbytes);
        }
      } catch (SerialException e) {
        e.printStackTrace();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    MapSqlParameterSource params = new MapSqlParameterSource();
    params
        .addValue("active", user.isActive())
        .addValue("admin", user.isAdmin())
        .addValue("external", user.isExternal())
        .addValue("fullName", user.getFullName())
        .addValue("internal", user.isInternal())
        .addValue("loginName", user.getLoginName())
        .addValue("roles", roleBlob)
        .addValue("email", user.getEmail());

    if (passwordCodecService != null) {
      params.addValue("password", passwordCodecService.encrypt(user.getPassword()));
    } else {
      log.warn(
          "No PasswordCodecService has been wired to this SQLSecurityDAO. This means your passwords may be being "
              + "stored in plaintext, if not already encrypted. Please specify a PasswordCodecService in your Spring config and (auto)wire it "
              + "to this DAO.");
      params.addValue("password", user.getPassword());
    }

    if (user.getUserId() == UserImpl.UNSAVED_ID) {
      SimpleJdbcInsert insert =
          new SimpleJdbcInsert(template).withTableName("User").usingGeneratedKeyColumns("userId");
      Number newId = insert.executeAndReturnKey(params);
      user.setUserId(newId.longValue());
    } else {
      params.addValue("userId", user.getUserId());
      NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
      namedTemplate.update(USER_UPDATE, params);
    }

    // sort User_Group

    // delete existing joins
    MapSqlParameterSource delparams = new MapSqlParameterSource();
    delparams.addValue("userId", user.getUserId());
    NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
    namedTemplate.update(USER_GROUP_DELETE_BY_USER_ID, delparams);

    if (user.getGroups() != null && !user.getGroups().isEmpty()) {
      SimpleJdbcInsert eInsert = new SimpleJdbcInsert(template).withTableName("User_Group");
      for (Group g : user.getGroups()) {
        MapSqlParameterSource ugParams = new MapSqlParameterSource();
        ugParams
            .addValue("users_userId", user.getUserId())
            .addValue("groups_groupId", g.getGroupId());

        eInsert.execute(ugParams);
      }
    }

    return user.getUserId();
  }
Ejemplo n.º 6
0
  @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() + "}";
  }