コード例 #1
0
 /**
  * Set the import log file's size in the database to its current size on the filesystem.
  *
  * @throws ServerError if the import log's size could not be updated in the database
  */
 private void setLogFileSize() throws ServerError {
   final OriginalFile logFile =
       (OriginalFile)
           sf.getQueryService().get(OriginalFile.class.getSimpleName(), logPath.getId());
   logFile.setSize(omero.rtypes.rlong(logPath.size()));
   sf.getUpdateService().saveObject(logFile);
 }
コード例 #2
0
  /**
   * Retrieve the log file.
   *
   * @param id The id of the file to load.
   * @param session The OMERO session.
   * @return See above.
   * @throws Throwable Thrown if an error occurred while loading file.
   */
  private File retrieveLogFile(Long id, ServiceFactoryPrx session) throws Throwable {
    if (id == null) return null;
    // dowload the file
    StringBuffer buf = new StringBuffer();
    buf.append("importLog_");
    buf.append(id);
    File logfile = File.createTempFile(buf.toString(), ".log");
    logfile.deleteOnExit();
    IQueryPrx svc = session.getQueryService();
    ParametersI param = new ParametersI();
    param.map.put("id", omero.rtypes.rlong(id));
    OriginalFile of =
        (OriginalFile) svc.findByQuery("select p from OriginalFile as p where p.id = :id", param);
    if (of == null) return null;

    final String path = logfile.getAbsolutePath();

    RawFileStorePrx store = null;
    try {
      store = session.createRawFileStore();
      store.setFileId(id);
    } catch (Throwable e) {
      store.close();
      return null; // Never reached.
    }
    try {
      long size = -1;
      long offset = 0;
      int INC = 262144;
      FileOutputStream stream = new FileOutputStream(logfile);
      try {
        try {
          size = store.size();
          for (offset = 0; (offset + INC) < size; ) {
            stream.write(store.read(offset, INC));
            offset += INC;
          }
        } finally {
          stream.write(store.read(offset, (int) (size - offset)));
          stream.close();
        }
      } catch (Exception e) {
        log.error("Cannot write log file", e);
        if (stream != null) stream.close();
      }
    } catch (IOException e) {
      log.error("Cannot write log file", e);
    } finally {
      store.close();
    }
    return logfile;
  }
コード例 #3
0
 /**
  * Use {@link RawFileStorePrx#getFileId()} in order to load the {@link OriginalFile} that the
  * service argument is acting on.
  *
  * @param uploader not null
  * @return
  * @throws ServerError
  */
 public OriginalFile loadOriginalFile(RawFileStorePrx uploader) throws ServerError {
   omero.RLong rid = uploader.getFileId();
   long id = rid.getValue();
   Map<String, String> ctx = new HashMap<String, String>();
   ctx.put("omero.group", "-1");
   return (OriginalFile) sf.getQueryService().get("OriginalFile", id, ctx);
 }
コード例 #4
0
  public ImportLibrary(
      OMEROMetadataStoreClient client,
      OMEROWrapper reader,
      FileTransfer transfer,
      List<FileExclusion> exclusions,
      int minutesToWait) {
    if (client == null || reader == null) {
      throw new NullPointerException("All arguments to ImportLibrary() must be non-null.");
    }

    this.store = client;
    this.transfer = transfer;
    if (exclusions != null) {
      this.exclusions.addAll(exclusions);
    }
    this.minutesToWait = minutesToWait;
    repo = lookupManagedRepository();
    // Adapter which should be used for callbacks. This is more
    // complicated than it needs to be at the moment. We're only sure that
    // the OMSClient has a ServiceFactory (and not necessarily a client)
    // so we have to inspect various fields to get the adapter.
    sf = store.getServiceFactory();
    oa = sf.ice_getConnection().getAdapter();
    final Ice.Communicator ic = oa.getCommunicator();
    category = omero.client.getRouter(ic).getCategoryForClient();
  }
コード例 #5
0
 private void hasSystemPrivileges(Experimenter e) {
   try {
     ServiceFactoryPrx sf = c.createSession(e.getOmeName().getValue(), "");
     sf.getAdminService().synchronizeLoginCache();
   } catch (ServerError e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
     throw new RuntimeException("Unimplemented exception.");
   } catch (CannotCreateSessionException e2) {
     // TODO Auto-generated catch block
     e2.printStackTrace();
     throw new RuntimeException("Unimplemented exception.");
   } catch (PermissionDeniedException e3) {
     // TODO Auto-generated catch block
     e3.printStackTrace();
     throw new RuntimeException("Unimplemented exception.");
   }
 }
コード例 #6
0
 /**
  * Retrieves the first managed repository from the list of current active repositories.
  *
  * @return Active proxy for the legacy repository.
  */
 public ManagedRepositoryPrx lookupManagedRepository() {
   try {
     ManagedRepositoryPrx rv = null;
     ServiceFactoryPrx sf = store.getServiceFactory();
     RepositoryMap map = sf.sharedResources().repositories();
     for (int i = 0; i < map.proxies.size(); i++) {
       RepositoryPrx proxy = map.proxies.get(i);
       if (proxy != null) {
         rv = ManagedRepositoryPrxHelper.checkedCast(proxy);
         if (rv != null) {
           return rv;
         }
       }
     }
     return null;
   } catch (ServerError e) {
     throw new RuntimeException(e);
   }
 }
コード例 #7
0
 private void cleanupSession() {
   try {
     if (sf != null) {
       try {
         sf.destroy();
       } finally {
         sf = null;
       }
     }
   } catch (Throwable e) {
     log.error("Failed on cleanupSession", e);
   }
 }
コード例 #8
0
  @Override
  protected void initFile(String id) throws FormatException, IOException {
    LOGGER.debug("OmeroReader.initFile({})", id);

    super.initFile(id);

    if (!id.startsWith("omero:")) {
      throw new IllegalArgumentException("Not an OMERO id: " + id);
    }

    // parse credentials from id string

    LOGGER.info("Parsing credentials");

    String address = server, user = username, pass = password;
    int port = thePort;
    long iid = -1;

    final String[] tokens = id.substring(6).split("\n");
    for (String token : tokens) {
      final int equals = token.indexOf("=");
      if (equals < 0) continue;
      final String key = token.substring(0, equals);
      final String val = token.substring(equals + 1);
      if (key.equals("server")) address = val;
      else if (key.equals("user")) user = val;
      else if (key.equals("pass")) pass = val;
      else if (key.equals("port")) {
        try {
          port = Integer.parseInt(val);
        } catch (NumberFormatException exc) {
        }
      } else if (key.equals("session")) {
        sessionID = val;
      } else if (key.equals("groupName")) {
        group = val;
      } else if (key.equals("groupID")) {
        groupID = new Long(val);
      } else if (key.equals("iid")) {
        try {
          iid = Long.parseLong(val);
        } catch (NumberFormatException exc) {
        }
      }
    }

    if (address == null) {
      throw new FormatException("Invalid server address");
    }
    if (user == null && sessionID == null) {
      throw new FormatException("Invalid username");
    }
    if (pass == null && sessionID == null) {
      throw new FormatException("Invalid password");
    }
    if (iid < 0) {
      throw new FormatException("Invalid image ID");
    }

    try {
      // authenticate with OMERO server

      LOGGER.info("Logging in");

      client = new omero.client(address, port);
      ServiceFactoryPrx serviceFactory = null;
      if (user != null && pass != null) {
        serviceFactory = client.createSession(user, pass);
      } else {
        serviceFactory = client.createSession(sessionID, sessionID);
      }

      if (!encrypted) {
        client = client.createClient(false);
        serviceFactory = client.getSession();
      }

      if (group != null || groupID != null) {
        IAdminPrx iAdmin = serviceFactory.getAdminService();
        IQueryPrx iQuery = serviceFactory.getQueryService();
        EventContext eventContext = iAdmin.getEventContext();
        ExperimenterGroup defaultGroup = iAdmin.getDefaultGroup(eventContext.userId);
        if (!defaultGroup.getName().getValue().equals(group)
            && !new Long(defaultGroup.getId().getValue()).equals(groupID)) {
          Experimenter exp = iAdmin.getExperimenter(eventContext.userId);

          ParametersI p = new ParametersI();
          p.addId(eventContext.userId);
          List<IObject> groupList =
              iQuery.findAllByQuery(
                  "select distinct g from ExperimenterGroup as g "
                      + "join fetch g.groupExperimenterMap as map "
                      + "join fetch map.parent e "
                      + "left outer join fetch map.child u "
                      + "left outer join fetch u.groupExperimenterMap m2 "
                      + "left outer join fetch m2.parent p "
                      + "where g.id in "
                      + "  (select m.parent from GroupExperimenterMap m "
                      + "  where m.child.id = :id )",
                  p);

          Iterator<IObject> i = groupList.iterator();

          ExperimenterGroup g = null;

          boolean in = false;
          while (i.hasNext()) {
            g = (ExperimenterGroup) i.next();
            if (g.getName().getValue().equals(group)
                || new Long(g.getId().getValue()).equals(groupID)) {
              in = true;
              groupID = g.getId().getValue();
              break;
            }
          }
          if (in) {
            iAdmin.setDefaultGroup(exp, iAdmin.getGroup(groupID));
            serviceFactory.setSecurityContext(new ExperimenterGroupI(groupID, false));
          }
        }
      }

      // get raw pixels store and pixels

      store = serviceFactory.createRawPixelsStore();

      final GatewayPrx gateway = serviceFactory.createGateway();
      img = gateway.getImage(iid);

      if (img == null) {
        throw new FormatException(
            "Could not find Image with ID=" + iid + " in group '" + group + "'.");
      }

      long pixelsId = img.getPixels(0).getId().getValue();

      store.setPixelsId(pixelsId, false);

      pix = gateway.getPixels(pixelsId);
      final int sizeX = pix.getSizeX().getValue();
      final int sizeY = pix.getSizeY().getValue();
      final int sizeZ = pix.getSizeZ().getValue();
      final int sizeC = pix.getSizeC().getValue();
      final int sizeT = pix.getSizeT().getValue();
      final String pixelType = pix.getPixelsType().getValue().getValue();

      // populate metadata

      LOGGER.info("Populating metadata");

      core[0].sizeX = sizeX;
      core[0].sizeY = sizeY;
      core[0].sizeZ = sizeZ;
      core[0].sizeC = sizeC;
      core[0].sizeT = sizeT;
      core[0].rgb = false;
      core[0].littleEndian = false;
      core[0].dimensionOrder = "XYZCT";
      core[0].imageCount = sizeZ * sizeC * sizeT;
      core[0].pixelType = FormatTools.pixelTypeFromString(pixelType);

      RDouble x = pix.getPhysicalSizeX();
      Double px = x == null ? null : x.getValue();
      RDouble y = pix.getPhysicalSizeY();
      Double py = y == null ? null : y.getValue();
      RDouble z = pix.getPhysicalSizeZ();
      Double pz = z == null ? null : z.getValue();
      RDouble t = pix.getTimeIncrement();
      Double time = t == null ? null : t.getValue();

      RString imageName = img.getName();
      String name = imageName == null ? null : imageName.getValue();

      if (name != null) {
        currentId = name;
      } else {
        currentId = "Image ID " + iid;
      }

      RString imgDescription = img.getDescription();
      String description = imgDescription == null ? null : imgDescription.getValue();
      RTime date = img.getAcquisitionDate();

      MetadataStore store = getMetadataStore();
      MetadataTools.populatePixels(store, this);
      store.setImageName(name, 0);
      store.setImageDescription(description, 0);
      if (date != null) {
        store.setImageAcquisitionDate(
            new Timestamp(DateTools.convertDate(date.getValue(), (int) DateTools.UNIX_EPOCH)), 0);
      }

      if (px != null && px > 0) {
        store.setPixelsPhysicalSizeX(new PositiveFloat(px), 0);
      }
      if (py != null && py > 0) {
        store.setPixelsPhysicalSizeY(new PositiveFloat(py), 0);
      }
      if (pz != null && pz > 0) {
        store.setPixelsPhysicalSizeZ(new PositiveFloat(pz), 0);
      }
      if (time != null) {
        store.setPixelsTimeIncrement(time, 0);
      }

      List<Channel> channels = pix.copyChannels();
      for (int c = 0; c < channels.size(); c++) {
        LogicalChannel channel = channels.get(c).getLogicalChannel();

        RInt emWave = channel.getEmissionWave();
        RInt exWave = channel.getExcitationWave();
        RDouble pinholeSize = channel.getPinHoleSize();
        RString cname = channel.getName();

        Integer emission = emWave == null ? null : emWave.getValue();
        Integer excitation = exWave == null ? null : exWave.getValue();
        String channelName = cname == null ? null : cname.getValue();
        Double pinhole = pinholeSize == null ? null : pinholeSize.getValue();

        if (channelName != null) {
          store.setChannelName(channelName, 0, c);
        }
        if (pinhole != null) {
          store.setChannelPinholeSize(pinhole, 0, c);
        }
        if (emission != null && emission > 0) {
          store.setChannelEmissionWavelength(new PositiveInteger(emission), 0, c);
        }
        if (excitation != null && excitation > 0) {
          store.setChannelExcitationWavelength(new PositiveInteger(excitation), 0, c);
        }
      }
    } catch (CannotCreateSessionException e) {
      throw new FormatException(e);
    } catch (PermissionDeniedException e) {
      throw new FormatException(e);
    } catch (ServerError e) {
      throw new FormatException(e);
    }
  }