Exemplo n.º 1
0
  public <T> T putWor(
      String url,
      String resourcePath,
      Object object,
      Class<T> responseClass,
      Map<String, Object> queryParams,
      String worToken) {
    WebTarget target = client.target("https://" + url).path(resourcePath);
    if (queryParams != null) {
      for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
        target = target.queryParam(entry.getKey(), entry.getValue());
      }
    }

    Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    setHeaders(invocationBuilder, worToken);
    Response putResponse =
        invocationBuilder.put(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE));
    if (putResponse.getStatus() != Response.Status.OK.getStatusCode()) {
      Logger.error(
          "PUT call to "
              + url
              + "/"
              + resourcePath
              + " returned status of "
              + putResponse.getStatus());
      return null;
    }

    if (responseClass != null
        && putResponse.hasEntity()
        && putResponse.getStatus() == Response.Status.OK.getStatusCode())
      return putResponse.readEntity(responseClass);
    return null;
  }
Exemplo n.º 2
0
  public PartData retrieveEntryDetails(String userId, String id) {
    try {
      Entry entry = getEntry(id);
      if (entry == null) return null;

      return retrieveEntryDetails(userId, entry);
    } catch (Exception e) {
      Logger.error(e);
      return null;
    }
  }
Exemplo n.º 3
0
  public boolean deleteTraceSequence(String userId, long entryId, long traceId) {
    Entry entry = dao.get(entryId);
    if (entry == null) return false;

    TraceSequenceDAO traceSequenceDAO = DAOFactory.getTraceSequenceDAO();
    TraceSequence traceSequence = traceSequenceDAO.get(traceId);
    if (traceSequence == null || !canEdit(userId, traceSequence.getDepositor(), entry))
      return false;

    try {
      new SequenceAnalysisController().removeTraceSequence(traceSequence);
    } catch (Exception e) {
      Logger.error(e);
      return false;
    }
    return true;
  }
Exemplo n.º 4
0
  private static Entry infoToSeedForField(Entry entry, String value, EntryField field) {
    if (!entry.getRecordType().equalsIgnoreCase(EntryType.ARABIDOPSIS.toString())) return entry;

    ArabidopsisSeed seed = (ArabidopsisSeed) entry;

    switch (field) {
      case HOMOZYGOSITY:
        seed.setHomozygosity(value);
        return seed;

      case ECOTYPE:
        seed.setEcotype(value);
        return seed;

      case HARVEST_DATE:
        if (value != null && !value.isEmpty()) {
          try {
            Date date = SimpleDateFormat.getDateInstance(DateFormat.SHORT).parse(value);
            seed.setHarvestDate(date);
          } catch (ParseException ia) {
            Logger.error(ia);
          }
        }
        return seed;

      case GENERATION:
        seed.setGeneration(Generation.fromString(value));
        return seed;

      case SENT_TO_ABRC:
        seed.setSentToABRC("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value));
        return seed;

      case PLANT_TYPE:
        seed.setPlantType(PlantType.fromString(value));
        return seed;

      case PARENTS:
        seed.setParents(value);
        return seed;

      default:
        return seed;
    }
  }
Exemplo n.º 5
0
 @Override
 public Key getKey(final String keyId) {
   try {
     // find file named by keyId in the directory
     final File keyFile = new File(directory, keyId);
     // collect all lines in the file to a buffer
     final StringBuilder encoded = new StringBuilder();
     try (final FileReader reader = new FileReader(keyFile);
         final BufferedReader buffered = new BufferedReader(reader); ) {
       String line;
       while ((line = buffered.readLine()) != null) {
         encoded.append(line);
       }
       // after reading all lines, decode value into a Key object
       return HmacSignatureFactory.decodeKey(encoded.toString());
     }
   } catch (final Throwable t) {
     Logger.error("Failed to load rest-auth key " + keyId);
   }
   return null;
 }
Exemplo n.º 6
0
  public <T> T put(String url, String resourcePath, Object object, Class<T> responseClass) {
    WebTarget target = client.target("https://" + url).path(resourcePath);
    Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response putResponse =
        invocationBuilder.put(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE));
    if (putResponse.getStatus() != Response.Status.OK.getStatusCode()) {
      Logger.error(
          "PUT call to "
              + url
              + "/"
              + resourcePath
              + " returned status of "
              + putResponse.getStatus());
      return null;
    }

    if (responseClass != null
        && putResponse.hasEntity()
        && putResponse.getStatus() == Response.Status.OK.getStatusCode())
      return putResponse.readEntity(responseClass);
    return null;
  }
Exemplo n.º 7
0
  /**
   * Moves the specified list of entries to the deleted folder
   *
   * @param userId unique identifier for user making the request. Must have write access privileges
   *     on the entries in the list
   * @param list unique identifiers for entries
   * @return true or false if operation succeeds on all listed entries or not
   */
  public boolean moveEntriesToTrash(String userId, ArrayList<PartData> list) {
    List<Entry> toTrash = new LinkedList<>();
    for (PartData data : list) {
      Entry entry = dao.get(data.getId());
      if (entry == null || !authorization.canWriteThoroughCheck(userId, entry)) return false;

      toTrash.add(entry);
    }

    // add to bin
    try {
      for (Entry entry : toTrash) {
        entry.setVisibility(Visibility.DELETED.getValue());
        dao.update(entry);
      }
    } catch (DAOException de) {
      Logger.error(de);
      return false;
    }

    return true;
  }
Exemplo n.º 8
0
  protected static Entry setSeedFields(ArabidopsisSeedData seedData, Entry entry) {
    ArabidopsisSeed seed = (ArabidopsisSeed) entry;
    if (seedData == null) return entry;

    if (seedData.getHomozygosity() != null) seed.setHomozygosity(seedData.getHomozygosity());

    if (StringUtils.isNotEmpty(seedData.getHarvestDate())) {
      DateFormat format = new SimpleDateFormat("MM/dd/YYYY");
      try {
        Date date = format.parse(seedData.getHarvestDate());
        seed.setHarvestDate(date);
      } catch (ParseException e) {
        Logger.error("Could not parse date " + seedData.getHarvestDate());
        return null;
      }
    }

    String ecoType = seedData.getEcotype() == null ? "" : seedData.getEcotype();
    seed.setEcotype(ecoType);
    String parents = seedData.getSeedParents() == null ? "" : seedData.getSeedParents();

    seed.setParents(parents);

    if (seedData.getGeneration() != null) {
      Generation generation = Generation.fromString(seedData.getGeneration().name());
      seed.setGeneration(generation);
    } else {
      seed.setGeneration(Generation.UNKNOWN);
    }

    if (seedData.getPlantType() != null) {
      PlantType plantType = PlantType.fromString(seedData.getPlantType().name());
      seed.setPlantType(plantType);
    } else {
      seed.setPlantType(PlantType.NULL);
    }
    seed.setSentToABRC(seedData.isSentToAbrc());
    return entry;
  }
Exemplo n.º 9
0
  // uploads trace sequence file and builds or rebuilds alignment
  private boolean parseTraceSequence(String userId, Entry entry, String fileName, byte[] bytes) {
    DNASequence dnaSequence = sequenceAnalysisController.parse(bytes);
    if (dnaSequence == null || dnaSequence.getSequence() == null) {
      String errMsg =
          ("Could not parse \"" + fileName + "\". Only Fasta, GenBank & ABI files are supported.");
      Logger.error(errMsg);
      return false;
    }

    TraceSequence traceSequence =
        sequenceAnalysisController.uploadTraceSequence(
            entry,
            fileName,
            userId,
            dnaSequence.getSequence().toLowerCase(),
            new ByteArrayInputStream(bytes));

    if (traceSequence == null) return false;

    Sequence sequence = DAOFactory.getSequenceDAO().getByEntry(entry);
    if (sequence == null) return true;
    sequenceAnalysisController.buildOrRebuildAlignment(traceSequence, sequence);
    return true;
  }
Exemplo n.º 10
0
  public boolean addTraceSequence(String userId, long partId, File file, String uploadFileName) {
    Entry entry = dao.get(partId);
    if (entry == null) return false;

    authorization.expectRead(userId, entry);

    FileInputStream inputStream;
    try {
      inputStream = new FileInputStream(file);
    } catch (FileNotFoundException e) {
      Logger.error(e);
      return false;
    }

    if (uploadFileName.toLowerCase().endsWith(".zip")) {
      try (ZipInputStream zis = new ZipInputStream(inputStream)) {
        ZipEntry zipEntry;
        while (true) {
          zipEntry = zis.getNextEntry();

          if (zipEntry != null) {
            if (!zipEntry.isDirectory() && !zipEntry.getName().startsWith("__MACOSX")) {
              ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
              int c;
              while ((c = zis.read()) != -1) {
                byteArrayOutputStream.write(c);
              }

              boolean parsed =
                  parseTraceSequence(
                      userId, entry, zipEntry.getName(), byteArrayOutputStream.toByteArray());
              if (!parsed) {
                String errMsg =
                    ("Could not parse \""
                        + zipEntry.getName()
                        + "\". Only Fasta, GenBank & ABI files are supported.");
                Logger.error(errMsg);
                return false;
              }
            }
          } else {
            break;
          }
        }
      } catch (IOException e) {
        String errMsg = ("Could not parse zip file.");
        Logger.error(errMsg);
        return false;
      }
    } else {
      try {
        boolean parsed =
            parseTraceSequence(userId, entry, uploadFileName, IOUtils.toByteArray(inputStream));
        if (!parsed) {
          String errMsg =
              ("Could not parse \""
                  + uploadFileName
                  + "\". Only Fasta, GenBank & ABI files are supported.");
          Logger.error(errMsg);
          return false;
        }
      } catch (IOException e) {
        Logger.error(e);
        return false;
      }
    }

    return true;
  }
Exemplo n.º 11
0
  protected PartData retrieveEntryDetails(String userId, Entry entry) {
    // user must be able to read if not public entry
    if (!permissionsController.isPubliclyVisible(entry)) authorization.expectRead(userId, entry);

    PartData partData = ModelToInfoFactory.getInfo(entry);
    if (partData == null) return null;
    boolean hasSequence = sequenceDAO.hasSequence(entry.getId());

    partData.setHasSequence(hasSequence);
    boolean hasOriginalSequence = sequenceDAO.hasOriginalSequence(entry.getId());
    partData.setHasOriginalSequence(hasOriginalSequence);

    // permissions
    partData.setCanEdit(authorization.canWriteThoroughCheck(userId, entry));
    partData.setPublicRead(permissionsController.isPubliclyVisible(entry));

    // create audit event if not owner
    // todo : remote access check
    if (userId != null
        && authorization.getOwner(entry) != null
        && !authorization.getOwner(entry).equalsIgnoreCase(userId)) {
      try {
        Audit audit = new Audit();
        audit.setAction(AuditType.READ.getAbbrev());
        audit.setEntry(entry);
        audit.setUserId(userId);
        audit.setLocalUser(true);
        audit.setTime(new Date(System.currentTimeMillis()));
        auditDAO.create(audit);
      } catch (Exception e) {
        Logger.error(e);
      }
    }

    // retrieve more information about linked entries if any (default only contains id)
    if (partData.getLinkedParts() != null) {
      ArrayList<PartData> newLinks = new ArrayList<>();
      for (PartData link : partData.getLinkedParts()) {
        Entry linkedEntry = dao.get(link.getId());
        if (!authorization.canRead(userId, linkedEntry)) continue;

        link = ModelToInfoFactory.createTipView(linkedEntry);
        Sequence sequence = sequenceDAO.getByEntry(linkedEntry);
        if (sequence != null) {
          link.setBasePairCount(sequence.getSequence().length());
          link.setFeatureCount(sequence.getSequenceFeatures().size());
        }

        newLinks.add(link);
      }
      partData.getLinkedParts().clear();
      partData.getLinkedParts().addAll(newLinks);
    }

    // check if there is a parent available
    List<Entry> parents = dao.getParents(entry.getId());
    if (parents == null) return partData;

    for (Entry parent : parents) {
      if (!authorization.canRead(userId, parent)) continue;

      if (parent.getVisibility() != Visibility.OK.getValue()
          && !authorization.canWriteThoroughCheck(userId, entry)) continue;

      EntryType type = EntryType.nameToType(parent.getRecordType());
      PartData parentData = new PartData(type);
      parentData.setId(parent.getId());
      parentData.setName(parent.getName());
      parentData.setVisibility(Visibility.valueToEnum(parent.getVisibility()));
      partData.getParents().add(parentData);
    }

    return partData;
  }
Exemplo n.º 12
0
 /**
  * Used to log user actions
  *
  * @param userId unique user identifier
  * @param message log message
  */
 protected void log(final String userId, final String message) {
   final String who = (userId == null) ? "Unknown" : userId;
   Logger.info(who + ": " + message);
 }