/**
   * Create summary information of the paths currently in a query and their constraints for display
   * in the QueryBuilder summary section. The list of SummaryPath objects collect information for
   * simple display in the JSP.
   *
   * @param query the query to create summary information from
   * @return a list if summary information about paths on the query
   * @throws PathException if the PathQuery is invalid
   */
  public static List<SummaryPath> getDisplaySummary(PathQuery query) throws PathException {
    Set<SummaryPath> summaryPaths = new TreeSet<SummaryPath>();

    Set<String> constrainedPaths = new HashSet<String>();
    for (PathConstraint con : query.getConstraints().keySet()) {
      if (con instanceof PathConstraintSubclass) {
        // Do nothing
      } else if (con instanceof PathConstraintLoop) {
        // Put both paths in
        constrainedPaths.add(con.getPath());
        constrainedPaths.add(((PathConstraintLoop) con).getLoopPath());
      } else {
        constrainedPaths.add(con.getPath());
      }
    }

    List<String> lockedPaths = findLockedPaths(query);
    List<String> forcedInnerJoins = findForcedInnerJoins(query);

    Set<String> paths = new HashSet<String>();
    paths.addAll(constrainedPaths);
    paths.addAll(query.getView());
    paths.addAll(query.getOuterJoinGroups().keySet());

    for (String stringPath : paths) {
      Path path = query.makePath(stringPath);

      boolean isLocked = lockedPaths.contains(path.toStringNoConstraints());
      boolean isForcedInner = forcedInnerJoins.contains(path.toStringNoConstraints());
      SummaryPath summaryPath = new SummaryPath(path, isLocked, isForcedInner);

      for (PathConstraint con : query.getConstraintsForPath(path.toStringNoConstraints())) {
        boolean editable = false;
        String description = null;
        String switchable = SwitchOffAbility.LOCKED.toString().toLowerCase();
        if (query instanceof TemplateQuery) {
          TemplateQuery template = (TemplateQuery) query;
          editable = template.getEditableConstraints().contains(con);
          description = template.getConstraintDescriptions().get(con);
          SwitchOffAbility constraintSwitchOffAbility =
              template.getConstraintSwitchOffAbility().get(con);
          if (SwitchOffAbility.ON.equals(constraintSwitchOffAbility)) {
            switchable = SwitchOffAbility.ON.toString().toLowerCase();
          } else if (SwitchOffAbility.OFF.equals(constraintSwitchOffAbility)) {
            switchable = SwitchOffAbility.OFF.toString().toLowerCase();
          }
        }
        // subclass constraints aren't display
        if (!(con instanceof PathConstraintSubclass)) {
          String code = query.getConstraints().get(con);
          summaryPath.addSummaryConstraint(
              new SummaryConstraint(con, code, editable, description, switchable));
        } else {
          summaryPath.setSubclass(((PathConstraintSubclass) con).getType());
        }
      }
      summaryPaths.add(summaryPath);
    }
    return new ArrayList<SummaryPath>(summaryPaths);
  }
  /**
   * Return the query specified in the request, shorn of all duplicate classes in the view. Note, it
   * is the users responsibility to ensure that there are only SequenceFeatures in the view.
   *
   * @return A query.
   */
  protected PathQuery getQuery() {
    String xml = getRequiredParameter(XML_PARAM);
    PathQueryBuilder builder = getQueryBuilder(xml);
    PathQuery pq = builder.getQuery();

    List<String> newView = new ArrayList<String>();
    Set<ClassDescriptor> seenTypes = new HashSet<ClassDescriptor>();

    for (String viewPath : pq.getView()) {
      Path p;
      try {
        p = new Path(pq.getModel(), viewPath);
      } catch (PathException e) {
        throw new BadRequestException("Query is invalid", e);
      }
      ClassDescriptor cd = p.getLastClassDescriptor();
      if (!seenTypes.contains(cd)) {
        newView.add(viewPath);
      }
      seenTypes.add(cd);
    }
    if (!newView.equals(pq.getView())) {
      pq.clearView();
      pq.addViews(newView);
    }

    return pq;
  }
  /**
   * Create a PathQuery to get results for a collection of items from an InterMineObject
   *
   * @param webConfig the WebConfig
   * @param os the production ObjectStore
   * @param object the InterMineObject
   * @param referencedClassName the collection type
   * @param field the name of the field for the collection in the InterMineObject
   * @return a PathQuery
   */
  public static PathQuery makePathQueryForCollection(
      WebConfig webConfig,
      ObjectStore os,
      InterMineObject object,
      String referencedClassName,
      String field) {

    String className = TypeUtil.unqualifiedName(DynamicUtil.getSimpleClassName(object.getClass()));
    Path path;
    try {
      path = new Path(os.getModel(), className + "." + field);
    } catch (PathException e) {
      throw new IllegalArgumentException(
          "Could not build path for \"" + className + "." + field + "\".");
    }
    List<Class<?>> types = new ArrayList<Class<?>>();
    if (path.endIsCollection()) {
      CollectionDescriptor end = (CollectionDescriptor) path.getEndFieldDescriptor();
      // Only look for types if the refClass exactly matches the path type.
      if (end.getReferencedClassName().equals(referencedClassName)) {
        types = queryForTypesInCollection(object, field, os);
      }
      if (types.isEmpty()) {
        // the collection was empty, but still generate a query with the collection type
        types.add(os.getModel().getClassDescriptorByName(referencedClassName).getType());
      }
    } else if (path.endIsReference()) {
      types.add(path.getLastClassDescriptor().getType());
    }
    return makePathQueryForCollectionForClass(webConfig, os.getModel(), object, field, types);
  }
 // replace final dot in path with '+' if path represents and attribute, used for path ordering
 private String replaceAttributeDots(Path p) {
   String strPath = p.toStringNoConstraints();
   if (p.endIsAttribute()) {
     int lastIndex = strPath.lastIndexOf('.');
     strPath = strPath.substring(0, lastIndex) + "+" + strPath.substring(lastIndex + 1);
   }
   return strPath;
 }
 /**
  * Returns a List of paths, being the given path and all its parents.
  *
  * @param pathString a path String
  * @param pathQuery a PathQuery object to use to create a Path object
  * @return a List of path Strings
  * @throws PathException if something goes wrong
  */
 protected static List<String> findParentPaths(String pathString, PathQuery pathQuery)
     throws PathException {
   Path path = pathQuery.makePath(pathString);
   List<String> retval = new ArrayList<String>();
   retval.add(path.getNoConstraintsString());
   while (!path.isRootPath()) {
     path = path.getPrefix();
     retval.add(path.getNoConstraintsString());
   }
   return retval;
 }
 private static List<String> getSubview(WebConfig webConfig, Model m, Path path)
     throws PathException {
   List<String> subview = new ArrayList<String>();
   String basePath = path.toStringNoConstraints() + ".";
   List<FieldConfig> subconfs = getClassFieldConfigs(webConfig, path.getEndClassDescriptor());
   for (FieldConfig fc : subconfs) {
     String pathString = basePath + fc.getFieldExpr();
     Path pathToAdd = new Path(m, pathString);
     if (pathToAdd.endIsAttribute() && (fc.getDisplayer() == null && fc.getShowInSummary())) {
       subview.add(pathToAdd.getNoConstraintsString());
     }
   }
   return subview;
 }
  /**
   * Return a list of string paths that are defined as WebConfig to be shown in results. This will
   * include only attributes of the given class and not follow references. Optionally provide a
   * prefix to for creating a view for references/collections.
   *
   * @param type the class name to create a view for
   * @param model the model
   * @param webConfig we configuration
   * @param startingPath a path to prefix the class, can be null
   * @return the configured view paths for the class
   */
  public static List<String> getDefaultViewForClass(
      String type, Model model, WebConfig webConfig, String startingPath) {
    String prefix = startingPath;
    List<String> view = new ArrayList<String>();
    ClassDescriptor cld = model.getClassDescriptorByName(type);
    List<FieldConfig> fieldConfigs = FieldConfigHelper.getClassFieldConfigs(webConfig, cld);
    if (!StringUtils.isEmpty(prefix)) {
      try {
        // we can't add a subclass constraint, type must be same as the end of the prefix
        Path prefixPath = new Path(model, prefix);
        String prefixEndType = TypeUtil.unqualifiedName(prefixPath.getEndType().getName());
        if (!prefixEndType.equals(type)) {
          throw new IllegalArgumentException(
              "Mismatch between end type of prefix: "
                  + prefixEndType
                  + " and type parameter: "
                  + type);
        }
      } catch (PathException e) {
        LOG.error("Invalid path configured in webconfig for class: " + type);
      }
    } else {
      prefix = type;
    }

    for (FieldConfig fieldConfig : fieldConfigs) {
      String relPath = fieldConfig.getFieldExpr();
      // only add attributes, don't follow references, following references can be problematic
      // when subclasses get involved.
      if (fieldConfig.getShowInResults()) {
        try {
          Path path = new Path(model, prefix + "." + relPath);
          if (path.isOnlyAttribute()) {
            view.add(path.getNoConstraintsString());
          }
        } catch (PathException e) {
          LOG.error("Invalid path configured in webconfig for class: " + type);
        }
      }
    }
    if (view.size() == 0) {
      for (AttributeDescriptor att : cld.getAllAttributeDescriptors()) {
        if (!"id".equals(att.getName())) {
          view.add(prefix + "." + att.getName());
        }
      }
    }
    return view;
  }
 @Override
 protected void checkPathQuery(PathQuery pq) throws Exception {
   if (pq.getView().size() > 1) {
     throw new BadRequestException("Queries to this service may only have one view.");
   }
   Path path = pq.makePath(pq.getView().get(0));
   ClassDescriptor klazz = path.getLastClassDescriptor();
   ClassDescriptor sf = im.getModel().getClassDescriptorByName("SequenceFeature");
   ClassDescriptor protein = im.getModel().getClassDescriptorByName("Protein");
   if (sf == klazz
       || protein == klazz
       || klazz.getAllSuperDescriptors().contains(sf)
       || klazz.getAllSuperDescriptors().contains(protein)) {
     return; // OK
   } else {
     throw new BadRequestException("Unsuitable type for export: " + klazz);
   }
 }
 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;
 }
  /**
   * From the columns of the PagedTable, return a List of the Paths that this exporter will use to
   * find sequences to export. The returned Paths are a subset of the prefixes of the column paths.
   * eg. if the columns are ("Gene.primaryIdentifier", "Gene.secondaryIdentifier",
   * "Gene.proteins.primaryIdentifier") return ("Gene", "Gene.proteins").
   *
   * @param pt the PagedTable
   * @return a list of Paths that have sequence
   */
  public static LinkedHashMap<Path, Integer> getExportClassPaths(PagedTable pt) {
    LinkedHashMap<Path, Integer> retPaths = new LinkedHashMap<Path, Integer>();

    List<Column> columns = pt.getColumns();

    for (int index = 0; index < columns.size(); index++) {
      Path prefix = columns.get(index).getPath().getPrefix();
      ClassDescriptor prefixCD = prefix.getLastClassDescriptor();
      Class<? extends FastPathObject> prefixClass = DynamicUtil.getSimpleClass(prefixCD.getType());
      // Chromosome is treated as a sequence feature in the model
      if (SequenceFeature.class.isAssignableFrom(prefixClass)
          && !Chromosome.class.isAssignableFrom(prefixClass)) {
        if (!retPaths.keySet().contains(prefix)) {
          retPaths.put(prefix, index);
        }
      }
    }
    return retPaths;
  }
  /**
   * 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;
  }
  /**
   * 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);
      }
    }
  }
Exemple #13
0
  private void addColumnsInternal(List<Path> columnPaths) {
    List<String> types = new ArrayList<String>();
    int i = columns.size();
    for (Path columnPath : columnPaths) {
      String type = TypeUtil.unqualifiedName(columnPath.getLastClassDescriptor().getName());
      Class typeCls = columnPath.getLastClassDescriptor().getType();

      String columnDescription =
          pathQuery.getGeneratedPathDescription(columnPath.toStringNoConstraints());
      Column column;

      if (columnDescription.equals(columnPath.toStringNoConstraints())) {
        column = new Column(columnPath, i, typeCls);
      } else {
        column = new Column(columnPath, columnDescription, i, typeCls);
      }

      if (!types.contains(column.getColumnId())) {
        String fieldName = columnPath.getEndFieldDescriptor().getName();
        boolean isKeyField = ClassKeyHelper.isKeyField(classKeys, type, fieldName);
        if (isKeyField) {
          column.setSelectable(true);
          types.add(column.getColumnId());
        }
      }

      columns.add(column);

      i++;
    }
  }
 /**
  * Get the view as configured in the webconfig. Guarantees to return a non-empty non-null list.
  *
  * @param type The type we are trying to get a view for.
  * @param model The data model
  * @param webConfig The web-configuration.
  * @param fieldConfigs
  * @return The list of paths that we can use to construct a query.
  * @throws UnconfiguredException if the class has not configured view.
  */
 private static List<String> getConfiguredView(ClassDescriptor cld, WebConfig webConfig)
     throws UnconfiguredException {
   Collection<String> view = new LinkedHashSet<String>(); // Preserve order and uniqueness.
   Model m = cld.getModel();
   for (FieldConfig fieldConfig : resultConfigs(webConfig, cld)) {
     try {
       Path p = new Path(m, cld.getUnqualifiedName() + "." + fieldConfig.getFieldExpr());
       // add subpaths of references and roots, attrs themselves, ignore collections.
       if (p.isRootPath() || p.endIsReference()) {
         view.addAll(getSubview(webConfig, m, p));
       } else if (p.endIsAttribute()) {
         view.add(p.getNoConstraintsString());
       }
     } catch (PathException e) {
       LOG.error("Invalid path configured in webconfig for class: " + cld);
     }
   }
   if (view.isEmpty()) {
     throw new UnconfiguredException();
   }
   return new ArrayList<String>(view);
 }
  @Override
  protected void execute() throws Exception {
    String pathString = request.getParameter("path");

    Map<String, Object> attributes = getHeaderAttributes();
    output.setHeaderAttributes(attributes);

    if (isEmpty(pathString)) {
      throw new BadRequestException("No path provided");
    }
    attributes.put("path", pathString);
    kvPairs.put("path", pathString);

    String typeConstraintStr = request.getParameter("typeConstraints");
    Map<String, String> typeMap = new HashMap<String, String>();
    if (!isEmpty(typeConstraintStr)) {
      logger.debug(typeConstraintStr);
      JSONObject typeJO = new JSONObject(typeConstraintStr);
      Iterator<String> it = (Iterator<String>) typeJO.keys();
      while (it.hasNext()) {
        String name = it.next();
        String subType = typeJO.getString(name);
        typeMap.put(name, subType);
      }
    }

    Model model = im.getModel();

    Path path;
    try {
      if (typeMap.isEmpty()) {
        path = new Path(model, pathString);
      } else {
        path = new Path(model, pathString, typeMap);
      }
    } catch (PathException e) {
      throw new BadRequestException("Bad path given: " + pathString, e);
    }

    Query q = new Query();

    attributes.put("class", path.getLastClassDescriptor().getUnqualifiedName());
    attributes.put("field", path.getLastElement());
    String type = ((AttributeDescriptor) path.getEndFieldDescriptor()).getType();
    String[] parts = split(type, '.');
    reverse(parts);
    attributes.put("type", parts[0]);

    QueryClass qc = new QueryClass(path.getPrefix().getEndType());
    q.addFrom(qc);

    QueryField qf1 = new QueryField(qc, path.getLastElement());
    q.addToSelect(qf1);

    QueryFunction qf = new QueryFunction();
    q.addToSelect(qf);
    q.addToGroupBy(qf1);

    int count = im.getObjectStore().count(q, ObjectStore.SEQUENCE_IGNORE);

    if (formatIsCount()) {
      output.addResultItem(Arrays.asList(String.valueOf(count)));
    } else {
      attributes.put("count", count);

      Results results = im.getObjectStore().execute(q, DEFAULT_BATCH_SIZE, true, true, false);
      Iterator<Object> iter = results.iterator();

      while (iter.hasNext()) {
        @SuppressWarnings("rawtypes")
        List row = (List) iter.next();
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("value", row.get(0));
        jsonMap.put("count", row.get(1));
        JSONObject jo = new JSONObject(jsonMap);
        List<String> forOutput = new ArrayList<String>();
        forOutput.add(jo.toString());
        if (iter.hasNext()) {
          // Standard hack to ensure commas
          forOutput.add("");
        }
        output.addResultItem(forOutput);
      }
    }
  }
  /** {@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;
  }
Exemple #17
0
  // TODO javadoc to describe what this does
  private MultiRow<ResultsRow<MultiRowValue<ResultElement>>> translateRow(
      MultiRow<ResultsRow<MultiRowValue>> multiRow) {
    try {
      MultiRow<ResultsRow<MultiRowValue<ResultElement>>> retval =
          new MultiRow<ResultsRow<MultiRowValue<ResultElement>>>();
      for (ResultsRow<MultiRowValue> initialList : multiRow) {
        ResultsRow<MultiRowValue<ResultElement>> rowCells =
            new ResultsRow<MultiRowValue<ResultElement>>();
        for (Path columnPath : columnPaths) {
          String columnName = columnPath.toStringNoConstraints();
          Integer columnIndexInteger = pathToIndex.get(columnName);
          String parentColumnName = columnPath.getPrefix().toStringNoConstraints();
          if (columnIndexInteger == null) {
            columnIndexInteger = pathToIndex.get(parentColumnName);
          }

          if (columnIndexInteger == null) {
            throw new NullPointerException(
                "Path: \""
                    + columnName
                    + "\", pathToIndex: \""
                    + pathToIndex
                    + "\", prefix: \""
                    + parentColumnName
                    + "\", query: \""
                    + PathQueryBinding.marshal(
                        pathQuery,
                        "",
                        pathQuery.getModel().getName(),
                        PathQuery.USERPROFILE_VERSION)
                    + "\"");
          }
          int columnIndex = columnIndexInteger.intValue();
          MultiRowValue origO = initialList.get(columnIndex);
          FastPathObject o = (FastPathObject) (origO == null ? null : origO.getValue());
          int rowspan = -1;
          if (origO == null) {
            rowspan = 1;
          } else if (origO instanceof MultiRowFirstValue) {
            rowspan = ((MultiRowFirstValue) origO).getRowspan();
          }
          String lastCd;
          if (columnPath.endIsAttribute()) {
            lastCd = columnPath.getLastClassDescriptor().getName();
          } else {
            // special case for columns that contain objects eg. Gene.chromosomeLocation
            lastCd = columnPath.getLastClassDescriptor().getName();
          }
          String type = TypeUtil.unqualifiedName(lastCd);
          Path path;
          String fieldName = null;
          try {
            if (columnPath.endIsAttribute()) {
              fieldName = columnName.substring(columnName.lastIndexOf(".") + 1);
              path = new Path(model, type + '.' + fieldName);
            } else {
              // special case for columns that contain objects
              path = new Path(model, type);
            }
          } catch (PathException e) {
            // Should never happen if the field name is valid
            throw new Error("There must be a bug", e);
          }

          // Three cases:
          // 1) attribute has a value so create a result element
          // 2) we have an object but attribute is null -> create a ResultElement with
          // value null
          // 3) the object is null (outer join) so add null value rowCells
          //                    Object fieldValue;
          //                    try {
          //                        fieldValue = (o == null ? null : PathUtil.resolvePath(path, o));
          //                    } catch (PathException e) {
          //                        throw new IllegalArgumentException("Path: \"" + columnName
          //                                + "\", pathToIndex: \"" + pathToIndex + "\", prefix: \""
          //                                + parentColumnName + "\", query: \""
          //                                + PathQueryBinding.marshal(pathQuery, "",
          // pathQuery.getModel()
          //                                    .getName(), PathQuery.USERPROFILE_VERSION)
          //                                + "\", columnIndex: \"" + columnIndex + "\",
          // initialList: \""
          //                                + initialList + "\"", e);
          //                    }
          if (o != null) {
            String fieldCDName = path.getLastClassDescriptor().getName();
            String unqualifiedFieldCD = TypeUtil.unqualifiedName(fieldCDName);
            boolean isKeyField;
            if (fieldName == null) {
              // special case for columns that contain objects
              isKeyField = false;
            } else {
              isKeyField = ClassKeyHelper.isKeyField(classKeys, unqualifiedFieldCD, fieldName);
            }
            ResultElement resultElement = new ResultElement(o, path, isKeyField);
            // link to report page by default, unless it says otherwise in config

            if (redirector != null) {
              try {
                String linkRedirect = redirector.generateLink(im, (InterMineObject) o);
                if (linkRedirect != null) {
                  resultElement.setLinkRedirect(linkRedirect);
                }
              } catch (ClassCastException e) {
                // Simple objects cannot be consumed by redirectors.
              }
            }

            if (rowspan >= 0) {
              rowCells.add(new MultiRowFirstValue(resultElement, rowspan));
            } else {
              rowCells.add(null);
            }
          } else {
            if (rowspan >= 0) {
              rowCells.add(new MultiRowFirstValue(null, rowspan));
            } else {
              rowCells.add(null);
            }
          }
        }
        retval.add(rowCells);
      }
      return retval;
    } catch (IndexOutOfBoundsException e) {
      throw new RuntimeException(e);
    }
  }
  /**
   * Return a list of string paths that are defined as WebConfig to be shown in results. This will
   * include attributes of the given class and follow references.
   *
   * @param type the class name to create a view for
   * @param model the model
   * @param webConfig we configuration
   * @return the configured view paths for the class
   */
  public static List<String> getDefaultViewForClass(String type, Model model, WebConfig webConfig) {
    List<String> view = new ArrayList<String>();
    ClassDescriptor cld = model.getClassDescriptorByName(type);
    List<FieldConfig> fieldConfigs = FieldConfigHelper.getClassFieldConfigs(webConfig, cld);

    for (FieldConfig fieldConfig : fieldConfigs) {
      String relPath = fieldConfig.getFieldExpr();
      // only add attributes, don't follow references, following references can be problematic
      // when subclasses get involved.
      if (fieldConfig.getShowInResults()) {
        try {
          Path path = new Path(model, type + "." + relPath);
          // add references
          if (path.isRootPath() || path.endIsReference()) {
            for (FieldConfig fc :
                FieldConfigHelper.getClassFieldConfigs(webConfig, path.getEndClassDescriptor())) {
              Path pathToAdd =
                  new Path(model, path.toStringNoConstraints() + "." + fc.getFieldExpr());
              if (pathToAdd.endIsAttribute()
                  && (!view.contains(pathToAdd.getNoConstraintsString()))
                  && (fc.getDisplayer() == null && fc.getShowInSummary())) {
                view.add(pathToAdd.getNoConstraintsString());
              }
            }
            // add collections
          } else if (!path.endIsCollection()) {
            view.add(path.getNoConstraintsString());
          }
        } catch (PathException e) {
          LOG.error("Invalid path configured in webconfig for class: " + type);
        }
      }
    }
    if (view.size() == 0) {
      for (AttributeDescriptor att : cld.getAllAttributeDescriptors()) {
        if (!"id".equals(att.getName())) {
          view.add(type + "." + att.getName());
        }
      }
    }
    return view;
  }