Exemplo n.º 1
0
 /**
  * Generates the getElementType method.
  *
  * @param cld the ClassDescriptor
  * @return a String with the method
  */
 public String generateGetElementType(ClassDescriptor cld) {
   StringBuffer sb = new StringBuffer();
   sb.append(INDENT).append("public Class<?> getElementType(final String fieldName) {\n");
   for (FieldDescriptor field : cld.getAllFieldDescriptors()) {
     if (field.isCollection()) {
       sb.append(INDENT + INDENT)
           .append("if (\"" + field.getName() + "\".equals(fieldName)) {\n")
           .append(INDENT + INDENT + INDENT)
           .append(
               "return " + ((CollectionDescriptor) field).getReferencedClassName() + ".class;\n")
           .append(INDENT + INDENT)
           .append("}\n");
     }
   }
   sb.append(INDENT + INDENT)
       .append("if (!" + cld.getName() + ".class.equals(getClass())) {\n")
       .append(INDENT + INDENT + INDENT)
       .append("return TypeUtil.getElementType(" + cld.getName() + ".class, fieldName);\n")
       .append(INDENT + INDENT)
       .append("}\n")
       .append(INDENT + INDENT)
       .append("throw new IllegalArgumentException(\"Unknown field \" + fieldName);\n")
       .append(INDENT)
       .append("}\n");
   return sb.toString();
 }
Exemplo n.º 2
0
 /**
  * Generate all FieldDescriptors for a class/interface
  *
  * @param cld the ClassDescriptor of the class
  * @param supers true if go up the inheritence tree and output fields
  * @return the generated String
  */
 protected String generateFieldDescriptors(ClassDescriptor cld, boolean supers) {
   Set<FieldDescriptor> superclassFields = Collections.emptySet();
   if (supers && (cld.getSuperclassDescriptor() != null)) {
     superclassFields = cld.getSuperclassDescriptor().getAllFieldDescriptors();
   }
   StringBuffer sb = new StringBuffer();
   Iterator<FieldDescriptor> iter;
   if (supers) {
     iter = cld.getAllFieldDescriptors().iterator();
   } else {
     iter = cld.getFieldDescriptors().iterator();
   }
   while (iter.hasNext()) {
     FieldDescriptor fd = iter.next();
     if (!superclassFields.contains(fd)) {
       if (fd instanceof AttributeDescriptor) {
         sb.append(generate((AttributeDescriptor) fd, supers));
       } else if (fd instanceof CollectionDescriptor) {
         sb.append(generate((CollectionDescriptor) fd, supers));
       } else if (fd instanceof ReferenceDescriptor) {
         sb.append(generate((ReferenceDescriptor) fd, supers));
       }
     }
   }
   return sb.toString();
 }
 /**
  * @return an unmodifiable set of the classes that the Class-Descriptors in this query
  *     represent.
  */
 public Set<Class<?>> getFeatureClasses() {
   Set<Class<?>> ftSet = new HashSet<Class<?>>();
   for (ClassDescriptor cld : getFeatureCds()) {
     ftSet.add(cld.getType());
   }
   return Collections.unmodifiableSet(ftSet);
 }
Exemplo n.º 4
0
 /** Perform the mapping. */
 public void process() {
   for (ClassDescriptor cld : model.getClassDescriptors()) {
     String cldName = cld.getName();
     if (!"org.intermine.model.InterMineObject".equals(cldName)) {
       String pkg = TypeUtil.packageName(cldName);
       String cls = TypeUtil.unqualifiedName(cld.getName());
       String separator = File.separator;
       // Escape windows path seperator
       if ("\\".equals(separator)) {
         separator = "\\\\";
       }
       File dir = new File(file, pkg.replaceAll("[.]", separator));
       dir.mkdirs();
       File path = new File(dir, cls + ".java");
       try {
         path.delete();
         BufferedWriter fos = new BufferedWriter(new FileWriter(path, true));
         fos.write(generate(cld, false));
         fos.close();
         if (cld.isInterface()) {
           path = new File(dir, cls + "Shadow.java");
           path.delete();
           fos = new BufferedWriter(new FileWriter(path, true));
           fos.write(generate(cld, true));
           fos.close();
         }
       } catch (IOException e) {
         throw new RuntimeException("Error creating java", e);
       }
     }
   }
 }
    /**
     * Set the feature types for this request. Immediately parses the class names to
     * ClassDescriptors and fails as soon as possible.
     *
     * @param featureTypes A collection of feature type names.
     * @throws BadRequestException if the feature types are not mappable to classes, and if those
     *     classes are not Sequence Features.
     */
    public void setFeatureTypes(Collection<String> featureTypes) {
      this.featureTypes = new HashSet<String>(featureTypes);
      this.featureCds = new HashSet<ClassDescriptor>();

      Set<String> badTypes = new HashSet<String>();
      Model model = api.getModel();
      ClassDescriptor sfCd = model.getClassDescriptorByName(sequenceFeature);
      for (String f : this.featureTypes) {
        ClassDescriptor cld = model.getClassDescriptorByName(f);
        if (cld == null) {
          badTypes.add(f);
        } else {
          try {
            if (!sequenceFeature.equals(f)
                && !sfCd.getUnqualifiedName().equals(f)
                && !ClassDescriptor.findSuperClassNames(model, f).contains(sequenceFeature)) {
              throw new BadRequestException(f + " is not a " + sequenceFeature);
            }
          } catch (MetaDataException e) {
            // This should never happen.
            throw new ServiceException(e);
          }
          featureCds.add(cld);
          for (ClassDescriptor subCld : model.getAllSubs(cld)) {
            featureCds.add(subCld);
          }
        }
      }
      if (!badTypes.isEmpty()) {
        throw new BadRequestException(
            "The following feature types are not " + "valid feature class names: " + badTypes);
      }
    }
 private static List<String> getAttributeView(ClassDescriptor cld) {
   List<String> view = new ArrayList<String>();
   String basePath = cld.getUnqualifiedName() + ".";
   for (AttributeDescriptor att : cld.getAllAttributeDescriptors()) {
     if (!"id".equals(att.getName())) {
       view.add(basePath + att.getName());
     }
   }
   return view;
 }
  /**
   * 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 = 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);
          // use type (e.g. Protein) not prefix (e.g. Gene.proteins) to do
          // attribute check
          Path checkIsOnlyAttribute = new Path(model, type + "." + relPath);
          if (checkIsOnlyAttribute.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;
  }
Exemplo n.º 8
0
  /**
   * Generate a .equals() method for the given class.
   *
   * @param cld descriptor for class in question
   * @return generated java code as string
   */
  protected String generateEquals(ClassDescriptor cld) {
    if (cld.getFieldDescriptorByName("id") != null) {
      String unqualifiedName = TypeUtil.unqualifiedName(cld.getName());

      StringBuffer sb = new StringBuffer();
      sb.append(INDENT)
          .append("@Override public boolean equals(Object o) { return (o instanceof ")
          .append(unqualifiedName)
          .append(" && id != null) ? id.equals(((")
          .append(unqualifiedName)
          .append(")o).getId()) : this == o; }" + ENDL);
      return sb.toString();
    } else {
      return "";
    }
  }
Exemplo n.º 9
0
 /**
  * Make a feature track of the form (for a feature of the type <code>ClassName</code>):
  *
  * <pre>
  * {
  *   "type": "JBrowse/View/Track/CanvasFeatures",
  *   "storeClass": "JBrowse/Store/SeqFeature/REST",
  *   "category": "Features",
  *   "key": "Class Name",
  *   "label": "ClassName",
  *   "baseUrl": "http://www.foo.com/foomine/service/jbrowse/1234",
  *   "autocomplete": "all",
  *   "region_feature_densities": true,
  *   "query": { "type": "ClassName" }
  * }
  * </pre>
  *
  * @param feature The type of feature to build a track for.
  * @return A representation of the track configuration.
  */
 private Map<String, Object> featureTrack(ClassDescriptor feature) {
   Map<String, Object> ret = new HashMap<String, Object>();
   ret.put("type", "JBrowse/View/Track/CanvasFeatures");
   ret.put("storeClass", "JBrowse/Store/SeqFeature/REST");
   ret.put("category", featureCat);
   ret.put("key", WebUtil.formatClass(feature, config)); // In JBrowse "key" means human-readable.
   ret.put(
       "label",
       dataset + "-" + feature.getUnqualifiedName()); // and "label" means machine-readable.
   ret.put("baseUrl", getBaseUrl() + domain);
   Map<String, Object> query = new HashMap<String, Object>();
   query.put("type", feature.getUnqualifiedName());
   ret.put("query", query);
   ret.put("autocomplete", "all");
   ret.put("region_feature_densities", true);
   return ret;
 }
Exemplo n.º 10
0
 @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);
   }
 }
  /**
   * 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;
  }
Exemplo n.º 12
0
 private void setRefsAndCollections(List<String> parents, Item feature) {
   String clsName = feature.getClassName();
   Map<String, String> refsAndCollections = handler.getRefsAndCollections();
   if (refsAndCollections != null
       && refsAndCollections.containsKey(clsName)
       && parents != null
       && !parents.isEmpty()) {
     ClassDescriptor cld =
         tgtModel.getClassDescriptorByName(tgtModel.getPackageName() + "." + clsName);
     String refName = refsAndCollections.get(clsName);
     Iterator<String> parentIter = parents.iterator();
     if (cld.getReferenceDescriptorByName(refName, true) != null) {
       String parent = parentIter.next();
       feature.setReference(refName, getRefId(parent));
       if (parentIter.hasNext()) {
         String primaryIdent = feature.getAttribute("primaryIdentifier").getValue();
         throw new RuntimeException(
             "Feature has multiple relations for reference: "
                 + refName
                 + " for feature: "
                 + feature.getClassName()
                 + ", "
                 + feature.getIdentifier()
                 + ", "
                 + primaryIdent);
       }
     } else if (cld.getCollectionDescriptorByName(refName, true) != null) {
       List<String> refIds = new ArrayList<String>();
       while (parentIter.hasNext()) {
         refIds.add(getRefId(parentIter.next()));
       }
       feature.setCollection(refName, refIds);
     } else if (parentIter.hasNext()) {
       throw new RuntimeException(
           "No '"
               + refName
               + "' reference/collection found in "
               + "class: "
               + clsName
               + " - is map configured correctly?");
     }
   }
 }
  /**
   * 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;
  }
Exemplo n.º 14
0
 /**
  * Generates the getFieldType method.
  *
  * @param cld the ClassDescriptor
  * @return a String with the method
  */
 public String generateGetFieldType(ClassDescriptor cld) {
   StringBuffer sb = new StringBuffer();
   sb.append(INDENT).append("public Class<?> getFieldType(final String fieldName) {\n");
   for (FieldDescriptor field : cld.getAllFieldDescriptors()) {
     sb.append(INDENT + INDENT)
         .append("if (\"" + field.getName() + "\".equals(fieldName)) {\n")
         .append(INDENT + INDENT + INDENT);
     if (field instanceof AttributeDescriptor) {
       AttributeDescriptor attribute = (AttributeDescriptor) field;
       if ("boolean".equals(attribute.getType())) {
         sb.append("return Boolean.TYPE;\n");
       } else if ("short".equals(attribute.getType())) {
         sb.append("return Short.TYPE;\n");
       } else if ("int".equals(attribute.getType())) {
         sb.append("return Integer.TYPE;\n");
       } else if ("long".equals(attribute.getType())) {
         sb.append("return Long.TYPE;\n");
       } else if ("float".equals(attribute.getType())) {
         sb.append("return Float.TYPE;\n");
       } else if ("double".equals(attribute.getType())) {
         sb.append("return Double.TYPE;\n");
       } else {
         sb.append("return " + attribute.getType() + ".class;\n");
       }
     } else if (field.isReference()) {
       sb.append("return " + ((ReferenceDescriptor) field).getReferencedClassName() + ".class;\n");
     } else {
       sb.append("return java.util.Set.class;\n");
     }
     sb.append(INDENT + INDENT).append("}\n");
   }
   sb.append(INDENT + INDENT)
       .append("if (!" + cld.getName() + ".class.equals(getClass())) {\n")
       .append(INDENT + INDENT + INDENT)
       .append("return TypeUtil.getFieldType(" + cld.getName() + ".class, fieldName);\n")
       .append(INDENT + INDENT)
       .append("}\n")
       .append(INDENT + INDENT)
       .append("throw new IllegalArgumentException(\"Unknown field \" + fieldName);\n")
       .append(INDENT)
       .append("}\n");
   return sb.toString();
 }
Exemplo n.º 15
0
 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;
 }
Exemplo n.º 16
0
 /**
  * Generates the addCollectionElement method.
  *
  * @param cld the ClassDescriptor
  * @return a String with the method
  */
 public String generateAddCollectionElement(ClassDescriptor cld) {
   StringBuffer sb = new StringBuffer();
   sb.append(INDENT)
       .append("public void addCollectionElement(final String fieldName,")
       .append(" final org.intermine.model.InterMineObject element) {\n")
       .append(INDENT + INDENT);
   for (FieldDescriptor field : cld.getAllFieldDescriptors()) {
     if (field.isCollection()) {
       String fieldName = field.getName();
       if ("fieldName".equals(fieldName)) {
         fieldName = "this.fieldName";
       } else if ("element".equals(fieldName)) {
         fieldName = "this.element";
       }
       sb.append("if (\"" + field.getName() + "\".equals(fieldName)) {\n")
           .append(INDENT + INDENT + INDENT)
           .append(
               fieldName
                   + ".add(("
                   + ((CollectionDescriptor) field).getReferencedClassName()
                   + ") element);\n")
           .append(INDENT + INDENT)
           .append("} else ");
     }
   }
   sb.append("{\n")
       .append(INDENT + INDENT + INDENT)
       .append("if (!" + cld.getName() + ".class.equals(getClass())) {\n")
       .append(INDENT + INDENT + INDENT + INDENT)
       .append("TypeUtil.addCollectionElement(this, fieldName, element);\n")
       .append(INDENT + INDENT + INDENT + INDENT)
       .append("return;\n")
       .append(INDENT + INDENT + INDENT)
       .append("}\n")
       .append(INDENT + INDENT + INDENT)
       .append("throw new IllegalArgumentException(\"Unknown collection \" + fieldName);\n")
       .append(INDENT + INDENT)
       .append("}\n")
       .append(INDENT)
       .append("}\n");
   return sb.toString();
 }
Exemplo n.º 17
0
  /**
   * Generate a .toString() method for the given class .
   *
   * @param cld descriptor for the class in question
   * @return generated java code as a string
   */
  protected String generateToString(ClassDescriptor cld) {
    String unqualifiedName = TypeUtil.unqualifiedName(cld.getName());

    StringBuilder sb = new StringBuilder();
    Set<FieldDescriptor> keyFields = cld.getAllFieldDescriptors();
    if (keyFields.size() > 0) {
      sb.append(INDENT)
          .append("@Override public String toString() { ")
          .append("return \"")
          .append(unqualifiedName)
          .append(" [");
      TreeMap<String, FieldDescriptor> sortedMap = new TreeMap<String, FieldDescriptor>();
      for (FieldDescriptor field : keyFields) {
        sortedMap.put(field.getName(), field);
      }
      boolean needComma = false;
      for (Map.Entry<String, FieldDescriptor> entry : sortedMap.entrySet()) {
        FieldDescriptor field = entry.getValue();
        if (!(field instanceof CollectionDescriptor)) {
          if (needComma) {
            sb.append(", ");
          }
          needComma = true;
          sb.append(field.getName());
          if (field instanceof AttributeDescriptor) {
            sb.append("=\\\"\" + " + field.getName() + " + \"\\\"");
          } else {
            sb.append(
                "=\" + ("
                    + field.getName()
                    + " == null ? \"null\" : ("
                    + field.getName()
                    + ".getId() == null ? \"no id\" : "
                    + field.getName()
                    + ".getId().toString())) + \"");
          }
        }
      }
      sb.append("]\"; }" + ENDL);
    }
    return sb.toString();
  }
Exemplo n.º 18
0
  /**
   * 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;
  }
Exemplo n.º 19
0
  private void populateParentChildMap(Map<String, SOTerm> soTerms, String parentSOTermName) {
    String parentClsName = TypeUtil.javaiseClassName(parentSOTermName);
    ClassDescriptor cd = model.getClassDescriptorByName(parentClsName);
    if (cd == null) {
      LOG.error("couldn't find class in model:" + parentClsName);
      return;
    }
    Class<?> parentClass = cd.getType();

    // all collections for gene
    Map<String, Class<?>> childCollections = model.getCollectionsForClass(parentClass);

    Set<CollectionHolder> children = new HashSet<CollectionHolder>();

    // for each collection, see if this is a child class
    for (Map.Entry<String, Class<?>> entry : childCollections.entrySet()) {

      String childCollectionName = entry.getKey();
      String childClassName = entry.getValue().getSimpleName();

      // TODO use same method as in the oboparser
      // is this a child collection? e.g. transcript
      SOTerm soterm = soTerms.get(childClassName.toLowerCase());

      if (soterm == null) {
        // for testing
        continue;
      }

      // is gene in transcript parents collection
      for (OntologyTerm parent : soterm.getParents()) {
        if (parent.getName().equals(parentSOTermName)) {
          CollectionHolder h = new CollectionHolder(childClassName, childCollectionName);
          children.add(h);
        }
      }
    }
    if (children.size() > 0) {
      parentToChildren.put(parentSOTermName, children);
    }
  }
Exemplo n.º 20
0
 /**
  * Generate a .hashCode() method for the given class.
  *
  * @param cld descriptor for the class in question
  * @return generate java code as a string
  */
 protected String generateHashCode(ClassDescriptor cld) {
   if (cld.getFieldDescriptorByName("id") != null) {
     StringBuffer sb = new StringBuffer();
     sb.append(INDENT)
         .append("@Override public int hashCode() { ")
         .append("return (id != null) ? id.hashCode() : super.hashCode(); ")
         .append("}" + ENDL);
     return sb.toString();
   } else {
     return "";
   }
 }
 /**
  * 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);
 }
Exemplo n.º 22
0
 /**
  * Returns whether this primary key can be fetched now.
  *
  * @param pk the PrimaryKey
  * @param cld the ClassDescriptor that the PrimaryKey is in
  * @param pksNotDone a Map of pks not yet fetched
  * @return a boolean
  */
 protected boolean canDoPkNow(
     PrimaryKey pk, ClassDescriptor cld, Map<PrimaryKey, ClassDescriptor> pksNotDone) {
   boolean canDoPkNow = true;
   Iterator<String> fieldNameIter = pk.getFieldNames().iterator();
   while (fieldNameIter.hasNext() && canDoPkNow) {
     String fieldName = fieldNameIter.next();
     FieldDescriptor fd = cld.getFieldDescriptorByName(fieldName);
     if (fd.isReference()) {
       Iterator<ClassDescriptor> otherCldIter = pksNotDone.values().iterator();
       while (otherCldIter.hasNext() && canDoPkNow) {
         ClassDescriptor otherCld = otherCldIter.next();
         Class<? extends FastPathObject> fieldClass =
             ((ReferenceDescriptor) fd).getReferencedClassDescriptor().getType();
         if (otherCld.getType().isAssignableFrom(fieldClass)
             || fieldClass.isAssignableFrom(otherCld.getType())) {
           canDoPkNow = false;
         }
       }
     }
   }
   return canDoPkNow;
 }
Exemplo n.º 23
0
  private void setNames(
      List<?> names,
      String symbol,
      List<String> synonyms,
      Set<Item> synonymsToAdd,
      String primaryIdentifier,
      Item feature,
      ClassDescriptor cd) {
    if (cd.getFieldDescriptorByName("symbol") == null) { // if symbol is not in the model
      String name = (String) names.get(0);
      feature.setAttribute("name", name);
      for (Iterator<?> i = names.iterator(); i.hasNext(); ) {
        String recordName = (String) i.next();
        if (!recordName.equals(primaryIdentifier) && !recordName.equals(name)) {
          synonymsToAdd.add(getSynonym(feature, recordName));
        }
      }

      if (synonyms != null) {
        for (Iterator<?> i = synonyms.iterator(); i.hasNext(); ) {
          String recordName = (String) i.next();
          if (!recordName.equals(primaryIdentifier) && !recordName.equals(name)) {
            synonymsToAdd.add(getSynonym(feature, recordName));
          }
        }
      }
    } else {
      if (symbol == null) {
        symbol = (String) names.get(0);
      }
      feature.setAttribute("symbol", symbol);
      for (Iterator<?> i = names.iterator(); i.hasNext(); ) {
        String recordName = (String) i.next();
        if (!recordName.equals(primaryIdentifier) && !recordName.equals(symbol)) {
          synonymsToAdd.add(getSynonym(feature, recordName));
        }
      }

      if (synonyms != null) {
        for (Iterator<?> i = synonyms.iterator(); i.hasNext(); ) {
          String recordName = (String) i.next();
          if (!recordName.equals(primaryIdentifier) && !recordName.equals(symbol)) {
            synonymsToAdd.add(getSynonym(feature, recordName));
          }
        }
      }
    }
  }
Exemplo n.º 24
0
 private void setNames(
     List<?> names, Set<Item> synonymsToAdd, String recordId, Item feature, ClassDescriptor cd) {
   if (cd.getFieldDescriptorByName("symbol") == null) {
     String name = (String) names.get(0);
     feature.setAttribute("name", name);
     for (Iterator<?> i = names.iterator(); i.hasNext(); ) {
       String recordName = (String) i.next();
       if (!recordName.equals(recordId) && !recordName.equals(name)) {
         synonymsToAdd.add(getSynonym(feature, recordName));
       }
     }
   } else {
     String symbol = (String) names.get(0);
     feature.setAttribute("symbol", (String) names.get(0));
     for (Iterator<?> i = names.iterator(); i.hasNext(); ) {
       String recordName = (String) i.next();
       if (!recordName.equals(recordId) && !recordName.equals(symbol)) {
         synonymsToAdd.add(getSynonym(feature, recordName));
       }
     }
   }
 }
  /**
   * Search for the classes in a collection for a given InterMineObject, for example find all of the
   * sub-classes of Employee in the Department.employees collection of a given Department. If there
   * are no subclasses or the collection is empty a list with the type of the collection is
   * returned.
   *
   * @param object an InterMineObject to inspect
   * @param field the name if the collection to check
   * @param os the ObjectStore in which to execute the query
   * @return a list of classes in the collection
   */
  public static List<Class<?>> queryForTypesInCollection(
      InterMineObject object, String field, ObjectStore os) {
    List<Class<?>> typesInCollection = new ArrayList<Class<?>>();

    // if there are no subclasses there can only be one type in the collection
    Model model = os.getModel();
    ClassDescriptor startCld =
        model.getClassDescriptorByName(DynamicUtil.getSimpleClassName(object));
    CollectionDescriptor col = startCld.getCollectionDescriptorByName(field, true);
    ClassDescriptor colCld = col.getReferencedClassDescriptor();

    if (model.getAllSubs(colCld).isEmpty()) {
      // there aren't any subclasses, so no need to do a query
      typesInCollection.add(colCld.getType());
    } else {
      // there may be multiple subclasses in the collection, need to run a query
      Query query = new Query();
      QueryClass qc = new QueryClass(colCld.getType());
      query.addFrom(qc);
      query.addToSelect(new QueryField(qc, "class"));
      query.setDistinct(true);
      query.setConstraint(
          new ContainsConstraint(
              new QueryCollectionReference(object, field), ConstraintOp.CONTAINS, qc));
      for (Object o : os.executeSingleton(query)) {
        typesInCollection.add((Class<?>) o);
      }

      // Collection was empty but add collection type to be consistent with collection types
      // without subclasses.
      if (typesInCollection.isEmpty()) {
        typesInCollection.add(colCld.getType());
      }
    }
    return typesInCollection;
  }
Exemplo n.º 26
0
 /**
  * Generates the setoBJECT method for deserialising objects.
  *
  * @param cld a ClassDescriptor
  * @return a String containing the method
  */
 public String generateSetObject(ClassDescriptor cld) {
   StringBuffer sb = new StringBuffer();
   sb.append(INDENT)
       .append("public void setoBJECT(String notXml, ObjectStore os) {\n")
       .append(INDENT + INDENT)
       .append("setoBJECT(NotXmlParser.SPLITTER.split(notXml), os);\n")
       .append(INDENT)
       .append("}\n")
       .append(INDENT)
       .append("public void setoBJECT(final String[] notXml, final ObjectStore os) {\n")
       .append(INDENT + INDENT)
       .append(
           "if (!"
               + cld.getName()
               + (cld.isInterface() ? "Shadow" : "")
               + ".class.equals(getClass())) {\n")
       .append(INDENT + INDENT + INDENT)
       .append(
           "throw new IllegalStateException(\"Class \" + getClass().getName() + \""
               + " does not match code ("
               + cld.getName()
               + ")\");\n")
       .append(INDENT + INDENT)
       .append("}\n")
       .append(INDENT + INDENT)
       .append("for (int i = 2; i < notXml.length;) {\n")
       .append(INDENT + INDENT + INDENT)
       .append("int startI = i;\n");
   for (FieldDescriptor field : cld.getAllFieldDescriptors()) {
     String fieldName = field.getName();
     if ("notXml".equals(fieldName)) {
       fieldName = "this.notXml";
     } else if ("os".equals(fieldName)) {
       fieldName = "this.os";
     }
     if (field instanceof AttributeDescriptor) {
       AttributeDescriptor attribute = (AttributeDescriptor) field;
       sb.append(INDENT + INDENT + INDENT)
           .append("if ((i < notXml.length) && \"a" + fieldName + "\".equals(notXml[i])) {\n")
           .append(INDENT + INDENT + INDENT + INDENT)
           .append("i++;\n")
           .append(INDENT + INDENT + INDENT + INDENT);
       if ("boolean".equals(attribute.getType())) {
         sb.append(fieldName + " = Boolean.parseBoolean(notXml[i]);\n");
       } else if ("short".equals(attribute.getType())) {
         sb.append(fieldName + " = Short.parseShort(notXml[i]);\n");
       } else if ("int".equals(attribute.getType())) {
         sb.append(fieldName + " = Integer.parseInt(notXml[i]);\n");
       } else if ("long".equals(attribute.getType())) {
         sb.append(fieldName + " = Long.parseLong(notXml[i]);\n");
       } else if ("float".equals(attribute.getType())) {
         sb.append(fieldName + " = Float.parseFloat(notXml[i]);\n");
       } else if ("double".equals(attribute.getType())) {
         sb.append(fieldName + " = Double.parseDouble(notXml[i]);\n");
       } else if ("java.lang.Boolean".equals(attribute.getType())) {
         sb.append(fieldName + " = Boolean.valueOf(notXml[i]);\n");
       } else if ("java.lang.Short".equals(attribute.getType())) {
         sb.append(fieldName + " = Short.valueOf(notXml[i]);\n");
       } else if ("java.lang.Integer".equals(attribute.getType())) {
         sb.append(fieldName + " = Integer.valueOf(notXml[i]);\n");
       } else if ("java.lang.Long".equals(attribute.getType())) {
         sb.append(fieldName + " = Long.valueOf(notXml[i]);\n");
       } else if ("java.lang.Float".equals(attribute.getType())) {
         sb.append(fieldName + " = Float.valueOf(notXml[i]);\n");
       } else if ("java.lang.Double".equals(attribute.getType())) {
         sb.append(fieldName + " = Double.valueOf(notXml[i]);\n");
       } else if ("java.util.Date".equals(attribute.getType())) {
         sb.append(fieldName + " = new java.util.Date(Long.parseLong(notXml[i]));\n");
       } else if ("java.math.BigDecimal".equals(attribute.getType())) {
         sb.append(fieldName + " = new java.math.BigDecimal(notXml[i]);\n");
       } else if ("org.intermine.objectstore.query.ClobAccess".equals(attribute.getType())) {
         sb.append(
             fieldName
                 + " = org.intermine.objectstore.query.ClobAccess"
                 + ".decodeDbDescription(os, notXml[i]);\n");
       } else if ("java.lang.String".equals(attribute.getType())) {
         sb.append("StringBuilder string = null;\n")
             .append(INDENT + INDENT + INDENT + INDENT)
             .append(
                 "while ((i + 1 < notXml.length) && (notXml[i + 1].charAt(0) == '"
                     + ENCODED_DELIM
                     + "')) {\n")
             .append(INDENT + INDENT + INDENT + INDENT + INDENT)
             .append("if (string == null) string = new StringBuilder(notXml[i]);\n")
             .append(INDENT + INDENT + INDENT + INDENT + INDENT)
             .append("i++;\n")
             .append(INDENT + INDENT + INDENT + INDENT + INDENT)
             .append("string.append(\"" + DELIM + "\").append(notXml[i].substring(1));\n")
             .append(INDENT + INDENT + INDENT + INDENT)
             .append("}\n")
             .append(INDENT + INDENT + INDENT + INDENT)
             .append(fieldName + " = string == null ? notXml[i] : string.toString();\n");
       } else {
         throw new IllegalArgumentException("Unknown type " + attribute.getType());
       }
       sb.append(INDENT + INDENT + INDENT + INDENT)
           .append("i++;\n")
           .append(INDENT + INDENT + INDENT)
           .append("}\n");
     } else if (field.isReference()) {
       ReferenceDescriptor reference = (ReferenceDescriptor) field;
       sb.append(INDENT + INDENT + INDENT)
           .append("if ((i < notXml.length) &&\"r" + fieldName + "\".equals(notXml[i])) {\n")
           .append(INDENT + INDENT + INDENT + INDENT)
           .append("i++;\n")
           .append(INDENT + INDENT + INDENT + INDENT)
           .append(
               fieldName
                   + " = new ProxyReference(os, Integer.valueOf(notXml[i])"
                   + ", "
                   + reference.getReferencedClassName()
                   + ".class);\n")
           .append(INDENT + INDENT + INDENT + INDENT)
           .append("i++;\n")
           .append(INDENT + INDENT + INDENT)
           .append("};\n");
     }
   }
   sb.append(INDENT + INDENT + INDENT)
       .append("if (startI == i) {\n")
       .append(INDENT + INDENT + INDENT + INDENT)
       .append("throw new IllegalArgumentException(\"Unknown field \" + notXml[i]);\n")
       .append(INDENT + INDENT + INDENT)
       .append("}\n")
       .append(INDENT + INDENT)
       .append("}\n");
   for (FieldDescriptor field : cld.getAllFieldDescriptors()) {
     String fieldName = field.getName();
     if ("notXml".equals(fieldName)) {
       fieldName = "this.notXml";
     } else if ("os".equals(fieldName)) {
       fieldName = "this.os";
     }
     if (field instanceof CollectionDescriptor) {
       CollectionDescriptor coll = (CollectionDescriptor) field;
       sb.append(INDENT + INDENT)
           .append(
               fieldName
                   + " = new ProxyCollection<"
                   + coll.getReferencedClassName()
                   + ">(os, this, \""
                   + fieldName
                   + "\", "
                   + coll.getReferencedClassName()
                   + ".class);\n");
     }
   }
   sb.append(INDENT).append("}\n");
   return sb.toString();
 }
Exemplo n.º 27
0
 /**
  * Fetches equivalent objects for a particular primary key.
  *
  * @param pk the PrimaryKey
  * @param cld the ClassDescriptor of the PrimaryKey
  * @param results a Map to hold results that are to be added to the cache
  * @param objectsForCld a List of objects relevant to this PrimaryKey
  * @param fetchedObjectIds a Set to hold ids of objects that are fetched, to prefetch from the
  *     data tracker later
  * @throws ObjectStoreException if something goes wrong
  */
 protected void doPk(
     PrimaryKey pk,
     ClassDescriptor cld,
     Map<InterMineObject, Set<InterMineObject>> results,
     List<InterMineObject> objectsForCld,
     Set<Integer> fetchedObjectIds)
     throws ObjectStoreException {
   Iterator<InterMineObject> objectsForCldIter = objectsForCld.iterator();
   while (objectsForCldIter.hasNext()) {
     int objCount = 0;
     int origObjCount = 0;
     Query q = new Query();
     QueryClass qc = new QueryClass(cld.getType());
     q.addFrom(qc);
     q.addToSelect(qc);
     ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
     q.setConstraint(cs);
     Map<String, Set<Object>> fieldNameToValues = new HashMap<String, Set<Object>>();
     for (String fieldName : pk.getFieldNames()) {
       try {
         QueryField qf = new QueryField(qc, fieldName);
         q.addToSelect(qf);
         Set<Object> values = new HashSet<Object>();
         fieldNameToValues.put(fieldName, values);
         cs.addConstraint(new BagConstraint(qf, ConstraintOp.IN, values));
       } catch (IllegalArgumentException e) {
         QueryForeignKey qf = new QueryForeignKey(qc, fieldName);
         q.addToSelect(qf);
         Set<Object> values = new HashSet<Object>();
         fieldNameToValues.put(fieldName, values);
         cs.addConstraint(new BagConstraint(qf, ConstraintOp.IN, values));
       }
     }
     // Now make a map from the primary key values to source objects
     Map<List<Object>, InterMineObject> keysToSourceObjects =
         new HashMap<List<Object>, InterMineObject>();
     while (objectsForCldIter.hasNext() && (objCount < 500)) {
       InterMineObject object = objectsForCldIter.next();
       origObjCount++;
       try {
         if (DataLoaderHelper.objectPrimaryKeyNotNull(model, object, cld, pk, source, idMap)) {
           List<Collection<Object>> values = new ArrayList<Collection<Object>>();
           boolean skipObject = false;
           Map<String, Set<Object>> fieldsValues = new HashMap<String, Set<Object>>();
           for (String fieldName : pk.getFieldNames()) {
             try {
               Object value = object.getFieldProxy(fieldName);
               Set<Object> fieldValues;
               if (value instanceof InterMineObject) {
                 Integer id = idMap.get(((InterMineObject) value).getId());
                 if (id == null) {
                   Set<InterMineObject> eqs = results.get(value);
                   if (eqs == null) {
                     value = object.getFieldValue(fieldName);
                     eqs = queryEquivalentObjects((InterMineObject) value, source);
                   }
                   fieldValues = new HashSet<Object>();
                   for (InterMineObject obj : eqs) {
                     fieldValues.add(obj.getId());
                   }
                 } else {
                   fieldValues = Collections.singleton((Object) id);
                 }
               } else {
                 fieldValues = Collections.singleton(value);
               }
               values.add(fieldValues);
               fieldsValues.put(fieldName, fieldValues);
               for (Object fieldValue : fieldValues) {
                 long time = System.currentTimeMillis();
                 boolean pkQueryFruitless =
                     hints.pkQueryFruitless(cld.getType(), fieldName, fieldValue);
                 String summaryName = Util.getFriendlyName(cld.getType()) + "." + fieldName;
                 if (!savedTimes.containsKey(summaryName)) {
                   savedTimes.put(summaryName, new Long(System.currentTimeMillis() - time));
                   savedCounts.put(summaryName, new Integer(0));
                 }
                 if (pkQueryFruitless) {
                   skipObject = true;
                 }
               }
             } catch (IllegalAccessException e) {
               throw new RuntimeException(e);
             }
           }
           if (!skipObject) {
             objCount++;
             for (String fieldName : pk.getFieldNames()) {
               fieldNameToValues.get(fieldName).addAll(fieldsValues.get(fieldName));
             }
             for (List<Object> valueSet : CollectionUtil.fanOutCombinations(values)) {
               if (keysToSourceObjects.containsKey(valueSet)) {
                 throw new ObjectStoreException(
                     "Duplicate objects found for pk "
                         + cld.getName()
                         + "."
                         + pk.getName()
                         + ": "
                         + object);
               }
               keysToSourceObjects.put(valueSet, object);
             }
           }
         }
       } catch (MetaDataException e) {
         throw new ObjectStoreException(e);
       }
     }
     // Prune BagConstraints using the hints system.
     // boolean emptyQuery = false;
     // Iterator<String> fieldNameIter = pk.getFieldNames().iterator();
     // while (fieldNameIter.hasNext() && (!emptyQuery)) {
     //    String fieldName = fieldNameIter.next();
     //    Set values = fieldNameToValues.get(fieldName);
     // Iterator valueIter = values.iterator();
     // while (valueIter.hasNext()) {
     //    if (hints.pkQueryFruitless(cld.getType(), fieldName, valueIter.next())) {
     //        valueIter.remove();
     //    }
     // }
     //    if (values.isEmpty()) {
     //        emptyQuery = true;
     //    }
     // }
     if (objCount > 0) {
       // Iterate through query, and add objects to results
       // long time = System.currentTimeMillis();
       int matches = 0;
       Results res = lookupOs.execute(q, 2000, false, false, false);
       @SuppressWarnings("unchecked")
       List<ResultsRow<Object>> tmpRes = (List) res;
       for (ResultsRow<Object> row : tmpRes) {
         List<Object> values = new ArrayList<Object>();
         for (int i = 1; i <= pk.getFieldNames().size(); i++) {
           values.add(row.get(i));
         }
         Set<InterMineObject> set = results.get(keysToSourceObjects.get(values));
         if (set != null) {
           set.add((InterMineObject) row.get(0));
           matches++;
         }
         fetchedObjectIds.add(((InterMineObject) row.get(0)).getId());
       }
       // LOG.info("Fetched " + res.size() + " equivalent objects for " + objCount
       //        + " objects in " + (System.currentTimeMillis() - time) + " ms for "
       //        + cld.getName() + "." + pk.getName());
     }
   }
 }
Exemplo n.º 28
0
  /**
   * Fetches the equivalent object information for a whole batch of objects.
   *
   * @param batch the objects
   * @throws ObjectStoreException if something goes wrong
   */
  protected void getEquivalentsFor(List<ResultsRow<Object>> batch) throws ObjectStoreException {
    long time = System.currentTimeMillis();
    long time1 = time;
    boolean databaseEmpty = hints.databaseEmpty();
    if (savedDatabaseEmptyFetch == -1) {
      savedDatabaseEmptyFetch = System.currentTimeMillis() - time;
    }
    if (databaseEmpty) {
      savedDatabaseEmpty++;
      return;
    }
    // TODO: add all the objects that are referenced by these objects, and follow primary keys
    // We can make use of the ObjectStoreFastCollectionsForTranslatorImpl's ability to work this
    // all out for us.
    Set<InterMineObject> objects = new HashSet<InterMineObject>();
    for (ResultsRow<Object> row : batch) {
      for (Object object : row) {
        if (object instanceof InterMineObject) {
          InterMineObject imo = (InterMineObject) object;
          if (idMap.get(imo.getId()) == null) {
            objects.add(imo);
            for (String fieldName : TypeUtil.getFieldInfos(imo.getClass()).keySet()) {
              Object fieldValue;
              try {
                fieldValue = imo.getFieldProxy(fieldName);
              } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
              }
              if ((fieldValue instanceof InterMineObject)
                  && (!(fieldValue instanceof ProxyReference))) {
                objects.add((InterMineObject) fieldValue);
              } else if (fieldValue instanceof Collection<?>) {
                for (Object collectionElement : ((Collection<?>) fieldValue)) {
                  if ((collectionElement instanceof InterMineObject)
                      && (!(collectionElement instanceof ProxyReference))) {
                    objects.add((InterMineObject) collectionElement);
                  }
                }
              }
            }
          }
        }
      }
    }
    objects.removeAll(equivalents.keySet());
    // Now objects contains all the objects we need to fetch data for.
    Map<InterMineObject, Set<InterMineObject>> results =
        new HashMap<InterMineObject, Set<InterMineObject>>();
    for (InterMineObject object : objects) {
      results.put(object, Collections.synchronizedSet(new HashSet<InterMineObject>()));
    }

    Map<PrimaryKey, ClassDescriptor> pksToDo = new IdentityHashMap<PrimaryKey, ClassDescriptor>();
    Map<ClassDescriptor, List<InterMineObject>> cldToObjectsForCld =
        new IdentityHashMap<ClassDescriptor, List<InterMineObject>>();
    Map<Class<?>, List<InterMineObject>> categorised = CollectionUtil.groupByClass(objects, false);
    Map<ClassDescriptor, Boolean> cldsDone = new IdentityHashMap<ClassDescriptor, Boolean>();
    for (Class<?> c : categorised.keySet()) {
      Set<ClassDescriptor> classDescriptors = model.getClassDescriptorsForClass(c);
      for (ClassDescriptor cld : classDescriptors) {
        if (!cldsDone.containsKey(cld)) {
          cldsDone.put(cld, Boolean.TRUE);
          Set<PrimaryKey> keysForClass;
          if (source == null) {
            keysForClass = new HashSet<PrimaryKey>(PrimaryKeyUtil.getPrimaryKeys(cld).values());
          } else {
            keysForClass = DataLoaderHelper.getPrimaryKeys(cld, source, lookupOs);
          }
          if (!keysForClass.isEmpty()) {
            time = System.currentTimeMillis();
            boolean classNotExists = hints.classNotExists(cld.getType());
            String className = Util.getFriendlyName(cld.getType());
            if (!savedTimes.containsKey(className)) {
              savedTimes.put(className, new Long(System.currentTimeMillis() - time));
            }
            if (!classNotExists) {
              // LOG.error("Inspecting class " + className);
              List<InterMineObject> objectsForCld = new ArrayList<InterMineObject>();
              for (Map.Entry<Class<?>, List<InterMineObject>> category : categorised.entrySet()) {
                if (cld.getType().isAssignableFrom(category.getKey())) {
                  objectsForCld.addAll(category.getValue());
                }
              }
              cldToObjectsForCld.put(cld, objectsForCld);
              // So now we have a list of objects for this CLD.
              for (PrimaryKey pk : keysForClass) {
                // LOG.error("Adding pk " + cld.getName() + "." + pk.getName());
                pksToDo.put(pk, cld);
              }
            } else {
              // LOG.error("Empty class " + className);
            }
          }
        }
      }
    }
    doPks(pksToDo, results, cldToObjectsForCld, time1);
    batchQueried += results.size();
    equivalents.putAll(results);
  }
Exemplo n.º 29
0
 /**
  * Generates the getFieldValue method.
  *
  * @param cld the ClassDescriptor
  * @param proxy false to make the getFieldValue method, true to make the getFieldProxy method
  * @return a String with the method
  */
 public String generateGetFieldValue(ClassDescriptor cld, boolean proxy) {
   StringBuffer sb = new StringBuffer();
   sb.append(INDENT)
       .append(
           "public Object getField"
               + (proxy ? "Proxy" : "Value")
               + "(final String fieldName) throws IllegalAccessException {\n");
   for (FieldDescriptor field : cld.getAllFieldDescriptors()) {
     sb.append(INDENT + INDENT).append("if (\"" + field.getName() + "\".equals(fieldName)) {\n");
     String fieldName = field.getName();
     if ("fieldName".equals(fieldName)) {
       fieldName = "this.fieldName";
     }
     if (field instanceof AttributeDescriptor) {
       AttributeDescriptor attribute = (AttributeDescriptor) field;
       if ("boolean".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT)
             .append("return Boolean.valueOf(" + fieldName + ");\n");
       } else if ("short".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT).append("return Short.valueOf(" + fieldName + ");\n");
       } else if ("int".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT)
             .append("return Integer.valueOf(" + fieldName + ");\n");
       } else if ("long".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT).append("return Long.valueOf(" + fieldName + ");\n");
       } else if ("float".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT).append("return Float.valueOf(" + fieldName + ");\n");
       } else if ("double".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT).append("return Double.valueOf(" + fieldName + ");\n");
       } else {
         sb.append(INDENT + INDENT + INDENT).append("return " + fieldName + ";\n");
       }
     } else if (field.isReference()) {
       sb.append(INDENT + INDENT + INDENT);
       if (proxy) {
         sb.append("return " + fieldName + ";\n");
       } else {
         sb.append("if (" + fieldName + " instanceof ProxyReference) {\n")
             .append(INDENT + INDENT + INDENT + INDENT)
             .append("return ((ProxyReference) " + fieldName + ").getObject();\n")
             .append(INDENT + INDENT + INDENT)
             .append("} else {\n")
             .append(INDENT + INDENT + INDENT + INDENT)
             .append("return " + fieldName + ";\n")
             .append(INDENT + INDENT + INDENT)
             .append("}\n");
       }
     } else {
       sb.append(INDENT + INDENT + INDENT).append("return " + fieldName + ";\n");
     }
     sb.append(INDENT + INDENT).append("}\n");
   }
   sb.append(INDENT + INDENT)
       .append("if (!" + cld.getName() + ".class.equals(getClass())) {\n")
       .append(INDENT + INDENT + INDENT)
       .append("return TypeUtil.getField" + (proxy ? "Proxy" : "Value") + "(this, fieldName);\n")
       .append(INDENT + INDENT)
       .append("}\n")
       .append(INDENT + INDENT)
       .append("throw new IllegalArgumentException(\"Unknown field \" + fieldName);\n")
       .append(INDENT)
       .append("}\n");
   return sb.toString();
 }
Exemplo n.º 30
0
 /**
  * Generates the setFieldValue method.
  *
  * @param cld the ClassDescriptor
  * @return a String with the method
  */
 public String generateSetFieldValue(ClassDescriptor cld) {
   StringBuffer sb = new StringBuffer();
   sb.append(INDENT)
       .append("public void setFieldValue(final String fieldName, final Object value) {\n")
       .append(INDENT + INDENT);
   for (FieldDescriptor field : cld.getAllFieldDescriptors()) {
     sb.append("if (\"" + field.getName() + "\".equals(fieldName)) {\n");
     String fieldName = field.getName();
     if ("value".equals(fieldName)) {
       fieldName = "this.value";
     } else if ("fieldName".equals(fieldName)) {
       fieldName = "this.fieldName";
     }
     if (field instanceof AttributeDescriptor) {
       AttributeDescriptor attribute = (AttributeDescriptor) field;
       if ("boolean".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT)
             .append(fieldName + " = ((Boolean) value).booleanValue();\n");
       } else if ("short".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT)
             .append(fieldName + " = ((Short) value).shortValue();\n");
       } else if ("int".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT)
             .append(fieldName + " = ((Integer) value).intValue();\n");
       } else if ("long".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT)
             .append(fieldName + " = ((Long) value).longValue();\n");
       } else if ("float".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT)
             .append(fieldName + " = ((Float) value).floatValue();\n");
       } else if ("double".equals(attribute.getType())) {
         sb.append(INDENT + INDENT + INDENT)
             .append(fieldName + " = ((Double) value).doubleValue();\n");
       } else {
         sb.append(INDENT + INDENT + INDENT)
             .append(fieldName + " = (" + attribute.getType() + ") value;\n");
       }
     } else if (field.isReference()) {
       sb.append(INDENT + INDENT + INDENT)
           .append(fieldName + " = (org.intermine.model.InterMineObject) value;\n");
     } else {
       sb.append(INDENT + INDENT + INDENT).append(fieldName + " = (java.util.Set) value;\n");
     }
     sb.append(INDENT + INDENT).append("} else ");
   }
   sb.append("{\n")
       .append(INDENT + INDENT + INDENT)
       .append("if (!" + cld.getName() + ".class.equals(getClass())) {\n")
       .append(INDENT + INDENT + INDENT + INDENT)
       .append("TypeUtil.setFieldValue(this, fieldName, value);\n")
       .append(INDENT + INDENT + INDENT + INDENT)
       .append("return;\n")
       .append(INDENT + INDENT + INDENT)
       .append("}\n")
       .append(INDENT + INDENT + INDENT)
       .append("throw new IllegalArgumentException(\"Unknown field \" + fieldName);\n")
       .append(INDENT + INDENT)
       .append("}\n")
       .append(INDENT)
       .append("}\n");
   return sb.toString();
 }