Пример #1
0
 @Before
 public void setup() {
   query = new PathQuery(flymine.getFactory().getModel());
   query.addViews("Gene.symbol", "Gene.length");
   query.addConstraint(Constraints.eq("Gene.symbol", "c*"));
   query.addConstraint(Constraints.isNotNull("Gene.length"));
   expectedSize = flymine.getCount(query);
 }
Пример #2
0
 /**
  * Return an API query fetching all Comments for Genes, ordered by type
  *
  * @author radek
  * @param proteinID
  * @param query
  * @return
  */
 private PathQuery proteinCommentsQuery(String proteinID, PathQuery query) {
   query.addViews(
       "Protein.comments.description", "Protein.comments.type", "Protein.primaryIdentifier");
   query.addOrderBy("Protein.comments.type", OrderDirection.ASC);
   query.addConstraint(Constraints.eq("Protein.id", proteinID));
   query.addConstraint(
       Constraints.oneOfValues("Protein.comments.type", Arrays.asList(allowedCommentTypes)));
   return query;
 }
  /**
   * Return an API query fetching all tissue expressions
   *
   * @author radek
   * @param genePrimaryID
   * @param query
   * @return
   */
  private PathQuery geneExpressionAtlasQuery(String genePrimaryID, PathQuery query) {
    query.addViews(
        "Gene.atlasExpression.condition",
        "Gene.atlasExpression.expression",
        "Gene.atlasExpression.pValue",
        "Gene.atlasExpression.tStatistic",
        "Gene.atlasExpression.type",
        "Gene.primaryIdentifier");
    query.addConstraint(Constraints.eq("Gene.primaryIdentifier", genePrimaryID));
    query.addConstraint(Constraints.eq("Gene.atlasExpression.type", "disease_state"));
    query.addConstraint(Constraints.notLike("Gene.atlasExpression.condition", "(empty)"));
    query.addOrderBy("Gene.atlasExpression.condition", OrderDirection.ASC);

    return query;
  }
Пример #4
0
 /* (non-Javadoc)
  * @see junit.framework.TestCase#setUp()
  */
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   expectedGoodQuery = new PathQuery(model);
   expectedGoodQuery.addViews("Employee.age", "Employee.name");
   expectedGoodQuery.addConstraint(Constraints.eq("Employee.name", "Tim Canterbury"));
 }
Пример #5
0
  public void setUp() throws Exception {
    super.setUp();

    userprofileOS.setModel(Model.getInstanceByName("userprofile"));
    Model testmodel = Model.getInstanceByName("testmodel");
    query = new PathQuery(testmodel);

    query.addView("Employee");
    query.addView("Employee.name");
    queryBag = new PathQuery(testmodel);

    queryBag.addView("Employee");
    queryBag.addView("Employee.name");
    queryBag.addConstraint(Constraints.in("Employee", "bag2"));
    sq = new SavedQuery("query1", date, query);
    sqBag = new SavedQuery("query3", date, queryBag);
    hist = new SavedQuery("query2", date, (PathQuery) query.clone());
    hist2 = new SavedQuery("query1", date, query.clone());
    template = new TemplateQuery("template", "ttitle", "tdesc", new PathQuery(testmodel));

    SessionMethods.initSession(this.getSession());
    Profile profile = (Profile) getSession().getAttribute(Constants.PROFILE);
    profile.saveQuery(sq.getName(), sq);
    profile.saveQuery(sqBag.getName(), sqBag);
    profile.saveHistory(hist);
    profile.saveHistory(hist2);
  }
Пример #6
0
 @SuppressWarnings("unchecked")
 @Override
 public boolean removeAll(@SuppressWarnings("rawtypes") Collection c) {
   int priorSize = getSize();
   if (c instanceof ItemList) {
     ItemList res = subtract(((ItemList) c));
     update(res);
     delete();
     res.rename(getName());
   } else if (!c.isEmpty()) {
     try {
       Item[] is = (Item[]) c.toArray(new Item[0]);
       String path = is[0].getType() + ".id";
       PathQuery pq = new PathQuery(services.getModel());
       pq.addView(path);
       pq.addConstraint(
           Constraints.oneOfValues(
               path,
               collect(
                   collect(Arrays.asList(is), invokerTransformer("getId")),
                   stringValueTransformer())));
       createListAndSubtract(pq);
     } catch (ArrayStoreException e) {
       // Do nothing - we didn't get a collection of items.
     }
   }
   return priorSize != getSize();
 }
 /**
  * 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;
 }
Пример #8
0
  @AfterClass
  public static void shutdown() {
    int deleted = 0;
    if (osw != null) {
      try {
        osw.beginTransaction();
        PathQuery pq = new PathQuery(osw.getModel());
        pq.addView("Types.id");
        pq.addConstraint(Constraints.eq("Types.name", "histo*"));

        Query q = MainHelper.makeQuery(pq, new HashMap(), new HashMap(), null, new HashMap());

        Results res = osw.execute(q, 50000, true, false, true);
        for (Object row : res) {
          Types thing = (Types) ((List) row).get(0);
          osw.delete(thing);
          deleted++;
        }

        osw.commitTransaction();
      } catch (ObjectStoreException e) {
        LOG.warn(e);
      }
      try {
        osw.close();
      } catch (ObjectStoreException e) {
        LOG.warn(e);
      }
    }
    System.out.printf("\n[CLEAN UP] Deleted %d things\n", deleted);
  }
Пример #9
0
 @Override
 public Iterator<Item> iterator() {
   PathQuery pq = new PathQuery(services.getModel());
   pq.addViews(PQUtil.getStar(services.getModel(), getType()));
   pq.addConstraint(Constraints.in(type, name));
   Iterator<Map<String, Object>> it = services.getQueryService().getRowMapIterator(pq);
   return new ItemIterator(it);
 }
Пример #10
0
 /**
  * Convenience method for finding members of a collection matching certain properties.
  *
  * <p>This search is implemented with a query that performs case-insensitive matching on values.
  * Null constraints will be honoured, but other lookups will be converted to strings. Wild-cards
  * are permitted wherever they are permitted in path-queries. <br>
  * Using a query to back the search means that finding matching members is efficient even over
  * large lists - you will not need to pull in and iterate over thousands of rows of data to find
  * items if you have specific conditions. <br>
  * These conditions must all match for the result to be included. For more specific and flexible
  * searching strategies, please see the {@link PathQuery} API.
  *
  * @param conditions The properties these elements should have.
  * @return A list of matching items.
  */
 public List<Item> find(Map<String, Object> conditions) {
   List<Item> ret = new ArrayList<Item>();
   PathQuery q = new PathQuery(services.getModel());
   q.addViews(PQUtil.getStar(services.getModel(), type));
   q.addConstraint(Constraints.in(type, name));
   for (Entry<String, Object> condition : conditions.entrySet()) {
     String path = type + "." + condition.getKey();
     if (condition.getValue() == null) {
       q.addConstraint(Constraints.isNull(path));
     } else {
       q.addConstraint(Constraints.eq(path, condition.getValue().toString()));
     }
   }
   List<Map<String, Object>> results = services.getQueryService().getRowsAsMaps(q);
   for (Map<String, Object> result : results) {
     ret.add(new Item(services, type, result));
   }
   return ret;
 }
Пример #11
0
 /**
  * Add items to this list by using a query.
  *
  * @param items The items to add to the list.
  */
 private void appendItems(Iterable<Item> items) {
   PathQuery pq = new PathQuery(services.getModel());
   pq.addViews(getType() + ".id");
   Set<String> values = new HashSet<String>();
   for (Item i : items) {
     values.add(Integer.toString(i.getId()));
   }
   pq.addConstraint(Constraints.oneOfValues(getType() + ".id", values));
   update(services.getListService().append(this, pq));
 }
Пример #12
0
  /**
   * Query all nodes of worm regulatory network.
   *
   * @param model the Model
   * @param executor to run the query
   * @return interactionNodeSet
   */
  private static void queryWormRegulatoryNodes(Model model, PathQueryExecutor executor) {

    interactionNodeSetWorm = new LinkedHashSet<CytoscapeNetworkNodeData>();

    PathQuery query = new PathQuery(model);
    query.addViews(
        "NetworkProperty.node.primaryIdentifier",
        "NetworkProperty.node.symbol",
        "NetworkProperty.node.id",
        "NetworkProperty.type",
        "NetworkProperty.value");

    query.addConstraint(Constraints.eq("NetworkProperty.node.organism.shortName", "C. elegans"));

    ExportResultsIterator result;
    try {
      result = executor.execute(query);
    } catch (ObjectStoreException e) {
      throw new RuntimeException("Error retrieving results.", e);
    }

    while (result.hasNext()) {
      List<ResultElement> row = result.next();

      String featurePId = (String) row.get(0).getField();
      String featureSymbol = (String) row.get(1).getField();
      Integer id = (Integer) row.get(2).getField();
      String key = (String) row.get(3).getField();
      String value = (String) row.get(4).getField();

      CytoscapeNetworkNodeData aNode = new CytoscapeNetworkNodeData();
      aNode.setInterMineId(id);
      aNode.setSourceId(String.valueOf(id)); // Use IM Id instead of PId

      if (featureSymbol == null || featureSymbol.length() < 1) {
        aNode.setSourceLabel(featurePId);
      } else {
        aNode.setSourceLabel(featureSymbol);
      }

      if (interactionNodeSetWorm.contains(aNode)) {
        for (CytoscapeNetworkNodeData n : interactionNodeSetWorm) {
          if (n.getInterMineId() == id) {
            n.getExtraInfo().put(key, value);
          }
        }
      } else {
        Map<String, String> extraInfo = new HashMap<String, String>();
        extraInfo.put(key, value);
        aNode.setExtraInfo(extraInfo);
      }

      interactionNodeSetWorm.add(aNode);
    }
  }
 /**
  * Called by makePathQueryForCollection
  *
  * @param webConfig the webConfig
  * @param model the object model
  * @param object the InterMineObject
  * @param field the name of the field for the collection in the InterMineObject
  * @param sr the list of classes and subclasses
  * @return a PathQuery
  */
 private static PathQuery makePathQueryForCollectionForClass(
     WebConfig webConfig, Model model, InterMineObject object, String field, List<Class<?>> sr) {
   Class<?> commonClass = CollectionUtil.findCommonSuperclass(sr);
   String typeOfCollection = TypeUtil.unqualifiedName(DynamicUtil.getSimpleClassName(commonClass));
   String startClass = TypeUtil.unqualifiedName(DynamicUtil.getSimpleClassName(object.getClass()));
   String collectionPath = startClass + "." + field;
   PathQuery pathQuery =
       getQueryWithDefaultView(typeOfCollection, model, webConfig, collectionPath);
   pathQuery.addConstraint(Constraints.eq(startClass + ".id", object.getId().toString()));
   return pathQuery;
 }
Пример #14
0
  @Test
  public void test() throws Exception {
    Model m = osw.getModel();

    Long start = System.currentTimeMillis();

    PathQuery pq = new PathQuery(m);

    pq.addViews("Types.name", "Types.intType", "Types.doubleType");
    pq.addConstraint(Constraints.eq("Types.name", "histo*"));

    Query q = MainHelper.makeSummaryQuery(pq, "Types.intType", new HashMap(), new HashMap(), null);

    Results res = osw.execute(q, 100000, true, false, false);

    Long sum = 0L;
    Map<Integer, Long> actual = new TreeMap<Integer, Long>();

    for (Object o : res) {
      // System.out.println("ROW:" + o);
      List row = (List) o;
      Integer bucket = (Integer) row.get(5);
      Integer min = (Integer) row.get(0);
      Integer max = (Integer) row.get(1);
      Integer buckets = (Integer) row.get(4);
      Integer width = (max - min) / (buckets - 1);
      Integer group = min + ((bucket - 1) * width);
      Long count = ((BigDecimal) row.get(6)).longValue();
      actual.put(group, count);
      sum += count;
    }
    Long postExecution = System.currentTimeMillis();
    showHistogram("Actual", actual);
    System.out.printf(
        "MIN:        %d\nMAX:        %d\nAVG:        %.03f\nSTD-DEV:    %.03f\n",
        ((List) res.get(0)).subList(0, 4).toArray());
    System.out.println("TOTAL THINGS: " + sum);
    System.out.printf(
        "Query composition and execution took %.4f seconds",
        Double.valueOf(postExecution - start) / 1000);

    res = osw.execute(getCheckQuery());
    Long countFromOSQ = null;
    for (Object o : res) {
      List row = (List) o;
      countFromOSQ = (Long) row.get(0);
    }
    // int scale = generator.nextInt(MAX_SCALE - MIN_SCALE) + MIN_SCALE;

    assertEquals("Sum of buckets and total count agrees", sum, countFromOSQ);
    assertEquals("Sum of buckets agrees with what we inserted", made, sum.intValue());
  }
Пример #15
0
 @Override
 public boolean remove(Object i) {
   int priorSize = getSize();
   if (i instanceof Item) {
     Item item = (Item) i;
     String path = item.getType() + ".id";
     PathQuery pq = new PathQuery(services.getModel());
     pq.addView(path);
     pq.addConstraint(Constraints.eq(path, Integer.toString(item.getId())));
     createListAndSubtract(pq);
   }
   return priorSize != getSize();
 }
Пример #16
0
  /**
   * Tell the requester about all the reference sequences that have data (are of non-zero length)
   * and are in the correct domain.
   */
  private void serveRefSeqs() {
    Model m = im.getModel();
    ClassDescriptor ref = m.getClassDescriptorByName(refType);
    if (ref == null) {
      throw new ResourceNotFoundException("No class called " + ref);
    }
    PathQuery pq = new PathQuery(m);
    pq.addView(refType + ".id");
    pq.addConstraint(Constraints.greaterThan(refType + "." + lengthPath, "0"));
    pq.addConstraint(Constraints.eq(refType + "." + domainPath, domain));

    Query q = pathQueryToOSQ(pq);
    SingletonResults res = im.getObjectStore().executeSingleton(q);
    if (res.size() == 0) {
      throw new ResourceNotFoundException("No " + refType + "s on " + domain);
    }
    Iterator<Object> it = res.iterator();

    while (it.hasNext()) {
      FastPathObject o = (FastPathObject) it.next();
      Map<String, Object> refseq = makeRefSeq(o);
      addResultItem(refseq, it.hasNext());
    }
  }
  /**
   * Used for making a query for a reference or collection. Only used when a user clicks on [show
   * all] under an inline table on an Object's report page. The type of that object is
   * "startingPath", eg. Department. This path will be prepended to every path in the query. The
   * "type" is the type of the reference/collection, eg. Employee.
   *
   * <p>TODO use getDefaultViewForClass() instead
   *
   * @param objType class of object we are querying for eg. Manager
   * @param model the model
   * @param webConfig the webconfig
   * @param fieldType the type of the field this object is in, eg Employee
   * @return query, eg. Department.employees.name
   */
  protected static PathQuery getQueryWithDefaultView(
      String objType, Model model, WebConfig webConfig, String fieldType) {
    String prefix = fieldType;
    PathQuery query = new PathQuery(model);
    ClassDescriptor cld = model.getClassDescriptorByName(objType);
    List<FieldConfig> fieldConfigs = getClassFieldConfigs(webConfig, cld);

    if (!StringUtils.isBlank(prefix)) {
      try {
        // if the type is different to the end of the prefix path, add a subclass constraint
        Path fieldPath = new Path(model, fieldType);
        String fieldEndType = TypeUtil.unqualifiedName(fieldPath.getEndType().getName());
        if (!fieldEndType.equals(objType)) {
          query.addConstraint(Constraints.type(fieldType, objType));
        }
      } catch (PathException e) {
        LOG.error("Invalid path configured in webconfig for class: " + objType);
      }
    }

    for (FieldConfig fieldConfig : fieldConfigs) {
      if (fieldConfig.getShowInResults()) {
        String path = prefix + "." + fieldConfig.getFieldExpr();
        int from = prefix.length() + 1;
        while (path.indexOf('.', from) != -1) {
          int dotPos = path.indexOf('.', from);
          int nextDot = path.indexOf('.', dotPos + 1);
          String outerJoin = nextDot == -1 ? path.substring(0, dotPos) : path.substring(0, nextDot);
          query.setOuterJoinStatus(outerJoin, OuterJoinStatus.OUTER);
          from = dotPos + 1;
        }
        query.addView(path);
      }
    }
    if (query.getView().size() == 0) {
      for (AttributeDescriptor att : cld.getAllAttributeDescriptors()) {
        if (!"id".equals(att.getName())) {
          query.addView(prefix + "." + att.getName());
        }
      }
    }
    return query;
  }
Пример #18
0
  /**
   * Query all nodes of fly regulatory network.
   *
   * @param model the Model
   * @param executor to run the query
   * @return interactionNodeSet
   */
  private static void queryFlyRegulatoryNodes(Model model, PathQueryExecutor executor) {

    interactionNodeSetFly = new LinkedHashSet<CytoscapeNetworkNodeData>();

    PathQuery query = new PathQuery(model);
    query.addViews(
        "NetworkProperty.node.primaryIdentifier",
        "NetworkProperty.node.symbol",
        "NetworkProperty.node.id",
        "NetworkProperty.value");

    query.addConstraint(Constraints.eq("NetworkProperty.node.primaryIdentifier", "FBgn*"));

    ExportResultsIterator result;
    try {
      result = executor.execute(query);
    } catch (ObjectStoreException e) {
      throw new RuntimeException("Error retrieving results.", e);
    }

    while (result.hasNext()) {
      List<ResultElement> row = result.next();

      String featurePId = (String) row.get(0).getField();
      String featureSymbol = (String) row.get(1).getField();
      Integer featureIMId = (Integer) row.get(2).getField();
      String position = (String) row.get(3).getField();

      CytoscapeNetworkNodeData aNode = new CytoscapeNetworkNodeData();
      aNode.setInterMineId(featureIMId);
      aNode.setSourceId(featurePId);

      if (featureSymbol == null || featureSymbol.length() < 1) {
        aNode.setSourceLabel(featurePId);
      } else {
        aNode.setSourceLabel(featureSymbol);
      }

      aNode.setPosition(position);

      interactionNodeSetFly.add(aNode);
    }
  }
Пример #19
0
  /**
   * Query all edges of fly regulatory network.
   *
   * @param model the Model
   * @param executor to run the query
   * @return interactionEdgeSet
   */
  private static void queryFlyRegulatoryEdges(Model model, PathQueryExecutor executor) {

    interactionEdgeSetFly = new LinkedHashSet<CytoscapeNetworkEdgeData>();

    // TODO fly doesn't use IM Object id
    PathQuery query = new PathQuery(model);
    query.addViews(
        "Regulation.type", // interaction type, e.g. TF-TF
        "Regulation.source.primaryIdentifier",
        "Regulation.source.symbol",
        "Regulation.target.primaryIdentifier",
        "Regulation.target.symbol");

    query.addConstraint(Constraints.eq("Regulation.source.primaryIdentifier", "FBgn*"), "A");
    query.addConstraint(Constraints.eq("Regulation.target.primaryIdentifier", "FBgn*"), "B");

    query.setConstraintLogic("A and B");

    ExportResultsIterator result;
    try {
      result = executor.execute(query);
    } catch (ObjectStoreException e) {
      throw new RuntimeException("Error retrieving results.", e);
    }

    while (result.hasNext()) {
      List<ResultElement> row = result.next();

      String interactionType = (String) row.get(0).getField();
      String sourceNodePId = (String) row.get(1).getField();
      String sourceNodeSymbol = (String) row.get(2).getField();
      String targetNodePId = (String) row.get(3).getField();
      String targetNodeSymbol = (String) row.get(4).getField();

      CytoscapeNetworkEdgeData aEdge = new CytoscapeNetworkEdgeData();

      // Handle bidirectional edges
      if (interactionEdgeSetFly.isEmpty()) {
        aEdge.setSourceId(sourceNodePId);

        if (sourceNodeSymbol == null || sourceNodeSymbol.length() < 1) {
          aEdge.setSourceLabel(sourceNodePId);
        } else {
          aEdge.setSourceLabel(sourceNodeSymbol);
        }

        aEdge.setTargetId(targetNodePId);

        if (targetNodeSymbol == null || targetNodeSymbol.length() < 1) {
          aEdge.setTargetLabel(targetNodePId);
        } else {
          aEdge.setTargetLabel(targetNodeSymbol);
        }

        aEdge.setInteractionType(interactionType);
        aEdge.setDirection("one");

        interactionEdgeSetFly.add(aEdge);
      } else {
        aEdge.setSourceId(sourceNodePId);

        if (sourceNodeSymbol == null || sourceNodeSymbol.length() < 1) {
          aEdge.setSourceLabel(sourceNodePId);
        } else {
          aEdge.setSourceLabel(sourceNodeSymbol);
        }

        aEdge.setTargetId(targetNodePId);

        if (targetNodeSymbol == null || targetNodeSymbol.length() < 1) {
          aEdge.setTargetLabel(targetNodePId);
        } else {
          aEdge.setTargetLabel(targetNodeSymbol);
        }

        // miRNA-TF and TF-miRNA are the same interaction type
        if ("TF-miRNA".equals(interactionType) || "miRNA-TF".equals(interactionType)) {
          String uniType = "miRNA-TF";
          aEdge.setInteractionType(uniType);
        } else {
          aEdge.setInteractionType(interactionType);
        }

        String interactingString = aEdge.generateInteractionString();
        String interactingStringRev = aEdge.generateReverseInteractionString();

        // Get a list of interactionString from interactionSet
        LinkedHashSet<String> intcStrSet = new LinkedHashSet<String>();
        for (CytoscapeNetworkEdgeData edgedata : interactionEdgeSetFly) {
          intcStrSet.add(edgedata.generateInteractionString());
        }
        // A none dulipcated edge
        if (!(intcStrSet.contains(interactingString)
            || intcStrSet.contains(interactingStringRev))) {
          aEdge.setDirection("one");
          interactionEdgeSetFly.add(aEdge);
        } else { // duplicated edge
          // Pull out the CytoscapeNetworkEdgeData which contains the current
          // interactionString
          for (CytoscapeNetworkEdgeData edgedata : interactionEdgeSetFly) {
            if (edgedata.generateInteractionString().equals(interactingString)
                || edgedata.generateInteractionString().equals(interactingStringRev)) {
              edgedata.setDirection("both");
              aEdge.setInteractionType(interactionType);
            }
          }
        }
      }
    }
  }
  /** {@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;
  }
Пример #21
0
  /**
   * Query all edges of worm regulatory network.
   *
   * @param model the Model
   * @param executor to run the query
   * @return interactionEdgeSet
   */
  private static void queryWormRegulatoryEdges(Model model, PathQueryExecutor executor) {

    interactionEdgeSetWorm = new LinkedHashSet<CytoscapeNetworkEdgeData>();

    PathQuery query = new PathQuery(model);
    query.addViews(
        "Regulation.type", // interaction type, e.g. TF-TF
        "Regulation.source.primaryIdentifier",
        "Regulation.source.symbol",
        "Regulation.source.id",
        "Regulation.target.primaryIdentifier",
        "Regulation.target.symbol",
        "Regulation.target.id");

    query.addConstraint(Constraints.eq("Regulation.source.organism.shortName", "C. elegans"));

    ExportResultsIterator result;
    try {
      result = executor.execute(query);
    } catch (ObjectStoreException e) {
      throw new RuntimeException("Error retrieving results.", e);
    }

    while (result.hasNext()) {
      List<ResultElement> row = result.next();

      String interactionType = (String) row.get(0).getField();
      String sourcePId = (String) row.get(1).getField();
      String sourceSymbol = (String) row.get(2).getField();
      Integer sourceId = (Integer) row.get(3).getField();
      String targetPId = (String) row.get(4).getField();
      String targetSymbol = (String) row.get(5).getField();
      Integer targetId = (Integer) row.get(6).getField();

      // TODO Hack for a database issue
      //            if ("blmp-1".equals(targetSymbol)) {
      //                targetId = 1644007904;
      //            }
      //
      //            if ("unc-130".equals(targetSymbol)) {
      //                targetId = 1644015202;
      //            }
      //
      //            if ("mab-5".equals(targetSymbol)) {
      //                targetId = 1644006300;
      //            }
      //
      //            if ("mdl-1".equals(targetSymbol)) {
      //                targetId = 1644006399;
      //            }
      //
      //            if ("elt-3".equals(targetSymbol)) {
      //                targetId = 1644003204;
      //            }
      //
      //            if ("lin-11".equals(targetSymbol)) {
      //                targetId = 1644006039;
      //            }
      //
      //            if ("skn-1".equals(targetSymbol)) {
      //                targetId = 1644009973;
      //            }
      //
      //            if ("egl-27".equals(targetSymbol)) {
      //                targetId = 1644003074;
      //            }

      CytoscapeNetworkEdgeData aEdge = new RegulatoryNetworkEdgeData();

      aEdge.setSourceId(String.valueOf(sourceId));

      if (sourceSymbol == null || sourceSymbol.length() < 1) {
        aEdge.setSourceLabel(sourcePId);
      } else {
        aEdge.setSourceLabel(sourceSymbol);
      }

      aEdge.setTargetId(String.valueOf(targetId));

      if (targetSymbol == null || targetSymbol.length() < 1) {
        aEdge.setTargetLabel(targetPId);
      } else {
        aEdge.setTargetLabel(targetSymbol);
      }

      aEdge.setInteractionType(interactionType);

      interactionEdgeSetWorm.add(aEdge);
    }
  }