Ejemplo n.º 1
0
  /**
   * Save a single object to an existing bag.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @return an ActionForward object defining where control goes next
   */
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {
    int id = Integer.parseInt(request.getParameter("object"));
    HttpSession session = request.getSession();

    final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());

    Profile profile = SessionMethods.getProfile(session);
    String bagName = request.getParameter("bag");

    InterMineBag existingBag = profile.getSavedBags().get(bagName);
    if (existingBag != null) {
      // TODO add a warning when object already in bag ??
      try {
        InterMineObject o = im.getObjectStore().getObjectById(id);
        existingBag.addIdToBag(id, DynamicUtil.getFriendlyName(o.getClass()));
        recordMessage(new ActionMessage("bag.addedToBag", existingBag.getName()), request);
      } catch (IncompatibleTypesException e) {
        recordError(new ActionMessage("bag.typesDontMatch"), request);
      } catch (ObjectStoreException e) {
        recordError(new ActionMessage("bag.error"), request, e);
      }
    } else {
      recordError(new ActionMessage("bag.noSuchBag"), request);
    }
    return mapping.findForward("report");
  }
Ejemplo n.º 2
0
 protected InterMineBag createEmployeeList() throws Exception {
   ObjectStoreWriter osw = null;
   try {
     Profile superUser = im.getProfileManager().getSuperuserProfile();
     osw = ObjectStoreWriterFactory.getObjectStoreWriter("osw.unittest");
     Employee e1 = new Employee();
     e1.setName("Employee1");
     Employee e2 = new Employee();
     e2.setName("Employee2");
     Department d1 = new Department();
     d1.setName("department");
     Company company = new CompanyShadow();
     company.setName("company");
     Contractor contractor = new Contractor();
     contractor.setName("contractor");
     osw.store(contractor);
     company.addContractors(contractor);
     osw.store(company);
     d1.setCompany(company);
     osw.store(d1);
     e1.setDepartment(d1);
     e2.setDepartment(d1);
     osw.store(e1);
     osw.store(e2);
     InterMineBag list = superUser.createBag("employeeList", "Employee", "", im.getClassKeys());
     Collection<Integer> ids = new ArrayList<Integer>();
     ids.add(e1.getId());
     ids.add(e2.getId());
     list.addIdsToBag(ids, "Employee");
     return list;
   } finally {
     osw.close();
   }
 }
Ejemplo n.º 3
0
  /**
   * Adds objects to the a bag for the matches against a set of identifiers.
   *
   * @param ids A collection of identifiers
   * @param bag The bag to add the objects to
   * @param type The type of this bag
   * @param extraFieldValue An extra value for disambiguation.
   * @param unmatchedIds An accumulator to store the failed matches.
   * @param acceptableIssues the list of issues that are OK to ignore.
   * @throws ClassNotFoundException if the type is not a valid class.
   * @throws InterMineException If something goes wrong building the bag.
   * @throws ObjectStoreException If there is a problem on the database level.
   */
  protected void addIdsToList(
      final Collection<? extends String> ids,
      final InterMineBag bag,
      final String type,
      final String extraFieldValue,
      final Set<String> unmatchedIds,
      final Collection<String> acceptableIssues)
      throws ClassNotFoundException, InterMineException, ObjectStoreException {
    final BagQueryResult result =
        runner.searchForBag(
            type,
            new ArrayList<String>(ids),
            extraFieldValue,
            acceptableIssues.contains(BagQueryResult.WILDCARD));
    bag.addIdsToBag(result.getMatches().keySet(), type);

    for (final String issueType : result.getIssues().keySet()) {
      if (acceptableIssues.contains(issueType)) {
        bag.addIdsToBag(result.getIssueIds(issueType), type);
      } else {
        unmatchedIds.addAll(result.getInputIdentifiersForIssue(issueType));
      }
    }
    unmatchedIds.addAll(result.getUnresolvedIdentifiers());
  }
 /**
  * Create a PathQuery to get the contents of an InterMineBag
  *
  * @param imBag the bag
  * @param webConfig the WebConfig
  * @param model the Model
  * @return a PathQuery
  */
 public static PathQuery makePathQueryForBag(
     InterMineBag imBag, WebConfig webConfig, Model model) {
   PathQuery query = new PathQuery(model);
   query.addViews(getDefaultViewForClass(imBag.getType(), model, webConfig));
   query.addConstraint(Constraints.in(imBag.getType(), imBag.getName()));
   return query;
 }
Ejemplo n.º 5
0
 private ActionForward createBagAndGoToBagDetails(
     ActionMapping mapping, InterMineBag imBag, List<Integer> bagList)
     throws ObjectStoreException {
   imBag.addIdsToBag(bagList, imBag.getType());
   return new ForwardParameters(mapping.findForward("bagDetails"))
       .addParameter("bagName", imBag.getName())
       .forward();
 }
Ejemplo n.º 6
0
 private static int performBagOperation(BagOperation operation) throws BagOperationException {
   InterMineBag newBag = operation.operate();
   try {
     return newBag.size();
   } catch (ObjectStoreException e) {
     // Really shouldn't happen.
     throw new BagOperationException("Could not read size");
   }
 }
Ejemplo n.º 7
0
 private boolean createBag(InterMineBag origBag, String newBagName, Profile profile)
     throws ObjectStoreException {
   // Clone method clones the bag in the database
   InterMineBag newBag = (InterMineBag) origBag.clone();
   newBag.setDate(new Date());
   newBag.setName(newBagName);
   profile.saveBag(newBagName, newBag);
   newBag.addBagValues();
   return true;
 }
Ejemplo n.º 8
0
  @Override
  protected void makeList(
      final ListInput listInput,
      final String type,
      final Profile profile,
      final Set<String> temporaryBagNamesAccumulator)
      throws Exception {

    if (StringUtils.isBlank(type)) {
      throw new BadRequestException("No list type provided");
    }

    ListCreationInput input = (ListCreationInput) listInput;

    if (input.doReplace()) {
      ListServiceUtils.ensureBagIsDeleted(profile, input.getListName());
    }
    if (profile.getAllBags().containsKey(input.getListName())) {
      throw new BadRequestException(
          "Attempt to overwrite an existing bag - name: '" + input.getListName() + "'");
    }

    final Set<String> ids = new LinkedHashSet<String>();
    final Set<String> unmatchedIds = new HashSet<String>();
    final InterMineBag tempBag =
        profile.createBag(
            input.getTemporaryListName(), type, input.getDescription(), im.getClassKeys());

    processIdentifiers(type, input, ids, unmatchedIds, tempBag);

    setListSize(tempBag.size());

    for (final Iterator<String> i = unmatchedIds.iterator(); i.hasNext(); ) {
      final List<String> row = new ArrayList<String>(Arrays.asList(i.next()));
      if (i.hasNext()) {
        row.add("");
      }
      output.addResultItem(row);
    }

    if (!input.getTags().isEmpty()) {
      im.getBagManager().addTagsToBag(input.getTags(), tempBag, profile);
    }
    profile.renameBag(input.getTemporaryListName(), input.getListName());
  }
Ejemplo n.º 9
0
 private void delete(ActionForm form, HttpServletRequest request) throws Exception {
   HttpSession session = request.getSession();
   Profile profile = SessionMethods.getProfile(session);
   ModifyBagForm mbf = (ModifyBagForm) form;
   for (int i = 0; i < mbf.getSelectedBags().length; i++) {
     String bagName = mbf.getSelectedBags()[i];
     InterMineBag bag = profile.getSavedBags().get(bagName);
     if (bag != null) {
       deleteQueriesThatMentionBag(profile, bag.getName());
       deleteBag(session, profile, bag);
     } else {
       bag = profile.getSharedBags().get(bagName);
       if (bag == null) {
         LOG.error("Asked to delete a bag this user does not have access to.");
       } else {
         unshareBag(session, profile, bag);
       }
     }
   }
 }
Ejemplo n.º 10
0
  /** {@inheritDoc} */
  @Override
  public ActionForward execute(
      ComponentContext context,
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);

    InterMineBag imBag = (InterMineBag) request.getAttribute("bag");
    WebConfig webConfig = SessionMethods.getWebConfig(request);
    Model model = im.getModel();
    TemplateManager templateManager = im.getTemplateManager();

    Map<Class, ApiTemplate> conversionTypesMap =
        TypeConverter.getConversionTemplates(
            templateManager.getConversionTemplates(),
            TypeUtil.instantiate(model.getPackageName() + "." + imBag.getType()));
    ArrayList<String> conversionTypes = new ArrayList<String>();
    Map<Type, Boolean> fastaMap = new HashMap<Type, Boolean>();
    for (Class<?> clazz : conversionTypesMap.keySet()) {
      conversionTypes.add(TypeUtil.unqualifiedName(clazz.getName()));
      Type type = webConfig.getTypes().get(clazz.getName());
      FieldConfig fieldConfig = type.getFieldConfigMap().get("length");
      if (fieldConfig != null && fieldConfig.getDisplayer() != null) {
        fastaMap.put(type, Boolean.TRUE);
      } else {
        fastaMap.put(type, Boolean.FALSE);
      }
    }
    // Use custom converters
    BagQueryConfig bagQueryConfig = im.getBagQueryConfig();
    String bagType = imBag.getType();
    Set<AdditionalConverter> additionalConverters = bagQueryConfig.getAdditionalConverters(bagType);
    request.setAttribute("customConverters", additionalConverters);
    request.setAttribute("conversionTypes", conversionTypes);
    request.setAttribute("fastaMap", fastaMap);
    return null;
  }
Ejemplo n.º 11
0
 protected InterMineBag createCompanyList() throws Exception {
   ObjectStoreWriter osw = null;
   try {
     osw = ObjectStoreWriterFactory.getObjectStoreWriter("osw.unittest");
     Profile superUser = im.getProfileManager().getSuperuserProfile();
     Company c1 = new CompanyShadow();
     c1.setName("CompanyA");
     Company c2 = new CompanyShadow();
     c2.setName("CompanyB");
     osw.store(c1);
     osw.store(c2);
     InterMineBag list = superUser.createBag("companyList", "Company", "", im.getClassKeys());
     Collection<Integer> ids = new ArrayList<Integer>();
     ids.add(c1.getId());
     ids.add(c2.getId());
     list.addIdsToBag(ids, "Company");
     return list;
   } finally {
     osw.close();
   }
 }
Ejemplo n.º 12
0
  /**
   * Generate a list from a pathquery.
   *
   * @param pq The pathquery
   * @param name The name of the list
   * @param description The description of the list
   * @param tags A list of tags to add to the list
   * @param profile The profile the list should belong to
   * @throws ObjectStoreException If there is an issue running the queries that generate the list.
   * @throws PathException If the paths supplied are illegal.
   */
  protected void generateListFromQuery(
      PathQuery pq, String name, String description, List<String> tags, Profile profile)
      throws ObjectStoreException, PathException {

    Query q = getQuery(pq, profile);

    String tempName = name + TEMP;

    String viewPathString = pq.getView().get(0);
    Path viewPath = pq.makePath(viewPathString);
    String type = viewPath.getLastClassDescriptor().getUnqualifiedName();

    try {
      InterMineBag newList = profile.createBag(tempName, type, description, im.getClassKeys());
      newList.addToBagFromQuery(q);
      try {
        im.getBagManager().addTagsToBag(tags, newList, profile);
      } catch (TagManager.TagNameException e) {
        throw new BadRequestException(e.getMessage());
      } catch (TagManager.TagNamePermissionException e) {
        throw new ServiceForbiddenException(e.getMessage());
      }
      profile.renameBag(tempName, name);

      output.addResultItem(Arrays.asList("" + newList.size()));

    } catch (CompletelyFalseException e) {
      output.addResultItem(Arrays.asList("0"));
      throw new BadRequestException("List not created - it would be of size 0");
    } catch (UnknownBagTypeException e) {
      output.addResultItem(Arrays.asList("0"));
      throw new InternalErrorException(e.getMessage(), e);
    } catch (ClassKeysNotFoundException cke) {
      throw new BadRequestException("Bag has not class key set", cke);
    } finally {
      if (profile.getSavedBags().containsKey(tempName)) {
        profile.deleteBag(tempName);
      }
    }
  }
Ejemplo n.º 13
0
 // Remove a bag from userprofile database and session cache
 private void deleteBag(HttpSession session, Profile profile, InterMineBag bag)
     throws ObjectStoreException {
   // removed a cached bag table from the session
   SessionMethods.invalidateBagTable(session, bag.getName());
   profile.deleteBag(bag.getName());
 }
Ejemplo n.º 14
0
  private void copy(ActionForm form, HttpServletRequest request) throws ObjectStoreException {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);
    Profile profile = SessionMethods.getProfile(session);
    ModifyBagForm frm = (ModifyBagForm) form;
    String[] selectedBagNames = frm.getSelectedBags();

    BagManager bagManager = im.getBagManager();
    Map<String, InterMineBag> allBags = bagManager.getBags(profile);

    String newNameTextBox = getNewNameTextBox(request, frm.getNewBagName());

    if (selectedBagNames.length == 1) {
      String selectedBagName = selectedBagNames[0];
      InterMineBag origBag = allBags.get(selectedBagName);

      if (origBag == null) {
        recordError(new ActionMessage("errors.bag.notfound"), request);
        return;
      }

      String newBagName = "";
      if (newNameTextBox != null) {
        newBagName = NameUtil.validateName(allBags.keySet(), newNameTextBox);
        if (newBagName.isEmpty()) {
          recordError(new ActionMessage("bag.createdlists.notvalidname", newNameTextBox), request);
          return;
        }
      }
      if (newNameTextBox == null) {
        newBagName = NameUtil.generateNewName(allBags.keySet(), selectedBagName);
      }

      if (createBag(origBag, newBagName, profile)) {
        recordMessage(new ActionMessage("bag.createdlists", newBagName), request);
        // track the list creation
        im.getTrackerDelegate()
            .trackListCreation(
                origBag.getType(),
                origBag.getSize(),
                ListBuildMode.OPERATION,
                profile,
                session.getId());
      }
    } else {
      if (newNameTextBox != null) {
        recordError(new ActionMessage("errors.bag.namecannotbespecified"), request);
        return;
      }
      String msg = "";
      for (int i = 0; i < selectedBagNames.length; i++) {

        String selectedBagName = selectedBagNames[i];
        InterMineBag origBag = allBags.get(selectedBagName);

        if (origBag == null) {
          recordError(new ActionMessage("errors.bag.notfound"), request);
          return;
        }

        String newBagName = NameUtil.generateNewName(allBags.keySet(), selectedBagName);
        if (createBag(origBag, newBagName, profile)) {
          msg += newBagName + ", ";
        }
      }
      if (msg.length() > 2) {
        msg = msg.substring(0, msg.length() - 2);
      }
      if (msg.length() > 0) {
        recordMessage(new ActionMessage("bag.createdlists", msg), request);
      }
    }
  }
  /** {@inheritDoc} */
  @Override
  public ActionForward execute(
      ComponentContext context,
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    boolean canExportAsBED = false;

    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);
    Model model = im.getModel();
    PathQuery query = new PathQuery(model);

    // org and dbkey for galaxy use
    Set<String> orgSet = new HashSet<String>();
    Set<String> genomeBuildSet = new HashSet<String>();

    // Build GenomicRegion pathquery, the request is from GenomicRegionSearch "export to Galaxy"
    if (request.getParameter("featureIds") != null) {
      String featureIds = request.getParameter("featureIds").trim();
      String orgName = request.getParameter("orgName");

      if (orgName != null && !"".equals(orgName)) {
        orgSet.add(orgName);
      }

      // Refer to GenomicRegionSearchService.getExportFeaturesQuery method
      String path = "SequenceFeature";
      query.addView(path + ".primaryIdentifier");
      query.addView(path + ".chromosomeLocation.locatedOn.primaryIdentifier");
      query.addView(path + ".chromosomeLocation.start");
      query.addView(path + ".chromosomeLocation.end");
      query.addView(path + ".organism.name");

      // use ids or pids
      String[] idsInStr = featureIds.split(",");
      Set<Integer> ids = new HashSet<Integer>();
      boolean isIds = true;
      for (String id : idsInStr) {
        id = id.trim();
        if (!Pattern.matches("^\\d+$", id)) {
          isIds = false;
          break;
        }
        ids.add(Integer.valueOf(id));
      }

      if (isIds) {
        query.addConstraint(Constraints.inIds(path, ids));
      } else {
        if (featureIds.contains("'")) {
          featureIds = featureIds.replaceAll("'", "\\\\'");
        }
        query.addConstraint(Constraints.lookup(path, featureIds, null));
      }

      canExportAsBED = true;

    } else { // request from normal result table
      String tableName = request.getParameter("table");
      request.setAttribute("table", tableName);
      PagedTable pt = SessionMethods.getResultsTable(session, tableName);

      // Null check to page table, maybe session timeout?
      if (pt == null) {
        LOG.error("Page table is NULL...");
        return null;
      }

      // Check if can export as BED
      TableHttpExporter tableExporter = new BEDHttpExporter();

      try {
        canExportAsBED = tableExporter.canExport(pt);
      } catch (Exception e) {
        canExportAsBED = false;

        LOG.error("Caught an error running canExport() for: BEDHttpExporter. " + e);
        e.printStackTrace();
      }

      LinkedHashMap<Path, Integer> exportClassPathsMap = getExportClassPaths(pt);
      List<Path> exportClassPaths = new ArrayList<Path>(exportClassPathsMap.keySet());

      Map<String, String> pathMap = new LinkedHashMap<String, String>();
      for (Path path : exportClassPaths) {
        String pathString = path.toStringNoConstraints();
        String displayPath = pathString.replace(".", " &gt; ");
        pathMap.put(pathString, displayPath);
      }

      Map<String, Integer> pathIndexMap = new LinkedHashMap<String, Integer>();
      for (int index = 0; index < exportClassPaths.size(); index++) {
        String pathString = exportClassPaths.get(index).toStringNoConstraints();
        Integer idx = exportClassPathsMap.get(exportClassPaths.get(index));
        pathIndexMap.put(pathString, idx);
      }

      request.setAttribute("exportClassPaths", pathMap);
      request.setAttribute("pathIndexMap", pathIndexMap);

      // Support export public and private lists to Galaxy
      query = pt.getWebTable().getPathQuery();
      ObjectStore os = im.getObjectStore();

      Map<PathConstraint, String> constrains = query.getConstraints();
      for (PathConstraint constraint : constrains.keySet()) {
        if (constraint instanceof PathConstraintBag) {
          String bagName = ((PathConstraintBag) constraint).getBag();
          InterMineBag imBag =
              im.getBagManager().getBag(SessionMethods.getProfile(session), bagName);

          // find the classKeys
          Set<String> classKeySet = new LinkedHashSet<String>();
          for (Integer id : imBag.getContentsAsIds()) {
            String classKey = pt.findClassKeyValue(im.getClassKeys(), os.getObjectById(id));
            classKeySet.add(classKey);
          }

          String path = ((PathConstraintBag) constraint).getPath();
          // replace constraint in the pathquery
          PathConstraintLookup newConstraint =
              new PathConstraintLookup(
                  path,
                  classKeySet.toString().substring(1, classKeySet.toString().length() - 1),
                  null);
          query.replaceConstraint(constraint, newConstraint);
        }
      }

      orgSet = SequenceFeatureExportUtil.getOrganisms(query, session);
    }

    if (query instanceof TemplateQuery) {
      TemplateQuery templateQuery = (TemplateQuery) query;
      Map<PathConstraint, SwitchOffAbility> constraintSwitchOffAbilityMap =
          templateQuery.getConstraintSwitchOffAbility();
      for (Map.Entry<PathConstraint, SwitchOffAbility> entry :
          constraintSwitchOffAbilityMap.entrySet()) {
        if (entry.getValue().compareTo(SwitchOffAbility.OFF) == 0) {
          templateQuery.removeConstraint(entry.getKey());
        }
      }
    }

    String queryXML =
        PathQueryBinding.marshal(query, "", model.getName(), PathQuery.USERPROFILE_VERSION);

    //        String encodedQueryXML = URLEncoder.encode(queryXML, "UTF-8");

    String tableViewURL =
        new URLGenerator(request).getPermanentBaseURL() + "/service/query/results";

    request.setAttribute("tableURL", tableViewURL);
    request.setAttribute("queryXML", queryXML);
    request.setAttribute("size", 1000000);

    // If can export as BED
    request.setAttribute("canExportAsBED", canExportAsBED);
    if (canExportAsBED) {
      String bedURL =
          new URLGenerator(request).getPermanentBaseURL() + "/service/query/results/bed";

      request.setAttribute("bedURL", bedURL);

      genomeBuildSet =
          (Set<String>) OrganismGenomeBuildLookup.getGenomeBuildByOrgansimCollection(orgSet);

      String org =
          (orgSet.size() < 1) ? "Organism information not available" : StringUtil.join(orgSet, ",");

      // possible scenario: [null, ce3, null], should remove all null element and then join
      genomeBuildSet.removeAll(Collections.singleton(null));
      String dbkey =
          (genomeBuildSet.size() < 1)
              ? "Genome Build information not available"
              : StringUtil.join(genomeBuildSet, ",");

      request.setAttribute("org", org);
      request.setAttribute("dbkey", dbkey);
    }

    // PathMap
    Map<String, String> pathsMap = new LinkedHashMap<String, String>();
    List<String> views = query.getView();
    for (String view : views) {
      String title = query.getGeneratedPathDescription(view);
      title = WebUtil.formatColumnName(title);
      pathsMap.put(view, title);
    }

    request.setAttribute("pathsMap", pathsMap);

    return null;
  }
Ejemplo n.º 16
0
  /**
   * Forward to the correct method based on the button pressed
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @return an ActionForward object defining where control goes next
   * @exception Exception if the application business logic throws an exception
   */
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);
    Profile profile = SessionMethods.getProfile(session);

    Model model = im.getModel();
    ModifyBagDetailsForm mbdf = (ModifyBagDetailsForm) form;
    BagManager bagManager = im.getBagManager();

    InterMineBag imBag = bagManager.getBag(profile, mbdf.getBagName());
    String bagIdentifier = "bag." + imBag.getName();

    if (request.getParameter("removeFromBag") != null) {
      PagedTable pc = SessionMethods.getResultsTable(session, bagIdentifier);
      String msg = "";

      if (pc.isAllRowsSelected()) {
        // TODO these messages need to be moved to properties file
        msg = "You can't remove all items from your list.  Try deleting your list instead.";
      } else {
        int removed = pc.removeSelectedFromBag(imBag, session);
        msg = "You have removed " + removed + " items from your list.";
      }
      SessionMethods.recordMessage(msg, session);
      // return new ForwardParameters(mapping.findForward("bagDetails"))
      // .addParameter("bagName", mbdf.getBagName()).forward();

      // pass an extra parameter telling the JSP to open up the results table
      return new ForwardParameters(mapping.findForward("bagDetails"))
          .addParameter("bagName", mbdf.getBagName())
          .addParameter("table", "open")
          .forward();

    } else if (request.getParameter("addToBag") != null) {
      InterMineBag newBag = bagManager.getBag(profile, mbdf.getExistingBagName());
      String msg = "";
      if (newBag.getType().equals(imBag.getType())) {
        PagedTable pc = SessionMethods.getResultsTable(session, bagIdentifier);
        int oldSize = newBag.size();
        pc.addSelectedToBag(newBag);
        int newSize = newBag.size();
        int added = newSize - oldSize;
        msg =
            "You have added "
                + added
                + " items from list <strong>"
                + imBag.getName()
                + "</strong> to list <strong>"
                + newBag.getName()
                + "</strong>";
      } else {
        msg = "You can only add objects to other lists of the same type";
      }
      SessionMethods.recordMessage(msg, session);
      // orthologues form
    } else if (request.getParameter("convertToThing") != null) {
      BagQueryConfig bagQueryConfig = im.getBagQueryConfig();
      Set<AdditionalConverter> additionalConverters =
          bagQueryConfig.getAdditionalConverters(imBag.getType());
      if (additionalConverters != null && !additionalConverters.isEmpty()) {
        for (AdditionalConverter additionalConverter : additionalConverters) {
          BagConverter bagConverter =
              PortalHelper.getBagConverter(
                  im, SessionMethods.getWebConfig(request), additionalConverter.getClassName());
          List<Integer> converted =
              bagConverter.getConvertedObjectIds(
                  profile, imBag.getType(), imBag.getContentsAsIds(), mbdf.getExtraFieldValue());

          if (converted.size() == 1) {
            return goToReport(mapping, converted.get(0).toString());
          }

          String bagName =
              NameUtil.generateNewName(
                  profile.getSavedBags().keySet(),
                  mbdf.getExtraFieldValue() + " orthologues of " + imBag.getName());

          InterMineBag newBag = profile.createBag(bagName, imBag.getType(), "", im.getClassKeys());
          return createBagAndGoToBagDetails(mapping, newBag, converted);
        }
      }

      // "use in bag" link
    } else if (request.getParameter("useBag") != null) {
      PagedTable pc = SessionMethods.getResultsTable(session, bagIdentifier);
      PathQuery pathQuery = pc.getWebTable().getPathQuery().clone();
      SessionMethods.setQuery(session, pathQuery);
      session.setAttribute("path", imBag.getType());
      session.setAttribute("prefix", imBag.getType());
      String msg = "You can now create a query using your list " + imBag.getName();
      SessionMethods.recordMessage(msg, session);
      return mapping.findForward("query");

      // convert links
    } else if (request.getParameter("convert") != null && request.getParameter("bagName") != null) {
      String type2 = request.getParameter("convert");
      TemplateManager templateManager = im.getTemplateManager();
      PathQuery q =
          BagConversionHelper.getConvertedObjects(
              session,
              templateManager.getConversionTemplates(),
              TypeUtil.instantiate(model.getPackageName() + "." + imBag.getType()),
              TypeUtil.instantiate(model.getPackageName() + "." + type2),
              imBag);
      q.setTitle(type2 + "s from list '" + imBag.getName() + "'");
      SessionMethods.loadQuery(q, session, response);
      String qid = SessionMethods.startQueryWithTimeout(request, false, q);
      Thread.sleep(200); // slight pause in the hope of avoiding holding page
      final String trail = "|bag." + imBag.getName();
      return new ForwardParameters(mapping.findForward("waiting"))
          .addParameter("trail", trail)
          .addParameter("qid", qid)
          .forward();
    }
    return new ForwardParameters(mapping.findForward("bagDetails"))
        .addParameter("bagName", mbdf.getBagName())
        .forward();
  }