Beispiel #1
0
 /**
  * Create a new WebResults object.
  *
  * @param pathQuery used to get the paths of the columns
  * @param results the underlying Results object
  * @param im intermine API
  * @param pathToQueryNode the mapping between Paths (in the columnPaths argument) and the
  *     QueryNodes in the results object
  * @param pathToBagQueryResult a Map containing results from LOOKUP operations
  */
 public WebResults(
     InterMineAPI im,
     PathQuery pathQuery,
     Results results,
     Map<String, QuerySelectable> pathToQueryNode,
     Map<String, BagQueryResult> pathToBagQueryResult) {
   this.im = im;
   this.osResults = results;
   this.flatResults = new ResultsFlatOuterJoinsImpl(((List) osResults), osResults.getQuery());
   model = im.getModel();
   this.columnPaths = new ArrayList<Path>();
   try {
     for (String pathString : pathQuery.getView()) {
       this.columnPaths.add(pathQuery.makePath(pathString));
     }
   } catch (PathException e) {
     throw new RuntimeException("Error creating WebResults because PathQuery is invalid", e);
   }
   classKeys = im.getClassKeys();
   this.pathToQueryNode = new HashMap<String, QuerySelectable>();
   if (pathToQueryNode != null) {
     this.pathToQueryNode.putAll(pathToQueryNode);
   }
   this.pathToBagQueryResult = new HashMap<String, BagQueryResult>();
   if (pathToBagQueryResult != null) {
     this.pathToBagQueryResult.putAll(pathToBagQueryResult);
   }
   this.pathQuery = pathQuery;
   pathToIndex = getPathToIndex();
   redirector = im.getLinkRedirector();
   addColumnsInternal(columnPaths);
 }
  @SuppressWarnings("unchecked")
  @Override
  public void display(HttpServletRequest request, ReportObject reportObject) {

    // get the gene/protein in question from the request
    InterMineObject object = reportObject.getObject();
    // wrapper for the result so we can say what type it is
    HashMap<String, Object> result = new HashMap();

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

    // dealing with genes...
    if (object instanceof Gene) {
      // cast me Gene
      Gene gene = (Gene) object;
      String geneID = String.valueOf(gene.getId());
      query = geneCommentsQuery(geneID, query);

      Profile profile = SessionMethods.getProfile(session);
      PathQueryExecutor executor = im.getPathQueryExecutor(profile);
      ExportResultsIterator values;
      try {
        values = executor.execute(query);
      } catch (ObjectStoreException e) {
        throw new RuntimeException(e);
      }

      result.put("gene", geneComments2(values));

      // result.put("gene", geneComments(gene));
    } else if (object instanceof Protein) {
      // cast me Protein
      Protein protein = (Protein) object;
      String proteinID = String.valueOf(protein.getId());
      query = proteinCommentsQuery(proteinID, query);

      Profile profile = SessionMethods.getProfile(session);
      PathQueryExecutor executor = im.getPathQueryExecutor(profile);
      ExportResultsIterator values;
      try {
        values = executor.execute(query);
      } catch (ObjectStoreException e) {
        throw new RuntimeException(e);
      }

      result.put("protein", proteinComments2(values));

      // result.put("protein", proteinComments(protein));
    } else {
      // big fat fail
    }

    request.setAttribute("response", result);
  }
 private Map<String, Object> getObjectDetails(InterMineObject imo) {
   WebConfig webConfig = InterMineContext.getWebConfig();
   Model m = im.getModel();
   Map<String, Object> objectDetails = new HashMap<String, Object>();
   String className = DynamicUtil.getSimpleClassName(imo.getClass());
   ClassDescriptor cd = m.getClassDescriptorByName(className);
   for (FieldConfig fc : FieldConfigHelper.getClassFieldConfigs(webConfig, cd)) {
     try {
       Path p = new Path(m, cd.getUnqualifiedName() + "." + fc.getFieldExpr());
       if (p.endIsAttribute() && fc.getShowInSummary()) {
         objectDetails.put(
             p.getNoConstraintsString().replaceAll("^[^.]*\\.", ""), PathUtil.resolvePath(p, imo));
       }
     } catch (PathException e) {
       LOG.error(e);
     }
   }
   return objectDetails;
 }
  /** {@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;
  }
  /** {@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;
  }
  /**
   * 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();
  }
  @Override
  public void display(HttpServletRequest request, ReportObject reportObject) {

    // get the gene/protein in question from the request
    InterMineObject object = reportObject.getObject();

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

    // cast me Gene
    Gene gene = (Gene) object;
    Object genePrimaryIDObj = gene.getPrimaryIdentifier();
    if (genePrimaryIDObj != null) {
      // fetch the expression
      String genePrimaryID = String.valueOf(genePrimaryIDObj);
      query = geneExpressionAtlasQuery(genePrimaryID, query);

      // execute the query
      Profile profile = SessionMethods.getProfile(session);
      PathQueryExecutor executor = im.getPathQueryExecutor(profile);
      ExportResultsIterator values = executor.execute(query);

      // convert to a map
      GeneExpressionAtlasDiseasesExpressions geae =
          new GeneExpressionAtlasDiseasesExpressions(values);

      // attach to results
      request.setAttribute("expressions", geae);
      request.setAttribute("url", "http://www.ebi.ac.uk/gxa/experiment/E-MTAB-62/" + genePrimaryID);
      request.setAttribute("defaultPValue", "1e-4");
      request.setAttribute("defaultTValue", "4");

      // get the corresponding collection
      for (FieldDescriptor fd : reportObject.getClassDescriptor().getAllFieldDescriptors()) {
        if ("atlasExpression".equals(fd.getName()) && fd.isCollection()) {
          // fetch the collection
          Collection<?> collection = null;
          try {
            collection = (Collection<?>) reportObject.getObject().getFieldValue("atlasExpression");
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }

          List<Class<?>> lc =
              PathQueryResultHelper.queryForTypesInCollection(
                  reportObject.getObject(), "atlasExpression", im.getObjectStore());

          // create an InlineResultsTable
          InlineResultsTable t =
              new InlineResultsTable(
                  collection,
                  fd.getClassDescriptor().getModel(),
                  SessionMethods.getWebConfig(request),
                  im.getClassKeys(),
                  collection.size(),
                  false,
                  lc);

          request.setAttribute("collection", t);
          break;
        }
      }
    }
  }