/**
  * 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;
 }
  @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);
      }
    }
  }
Exemple #3
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);
    }
  }