Exemple #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();
 }
 private String getTaggedType(FieldDescriptor fd) {
   if (fd.isCollection()) {
     return "collection";
   } else if (fd.isReference()) {
     return "reference";
   }
   return "attribute";
 }
Exemple #3
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();
 }
Exemple #4
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();
 }
 /**
  * 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;
 }
Exemple #6
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();
  }
 /**
  * For a given FieldDescriptor, look up its 'aspect:' tags and place it in the correct map within
  * placementRefsAndCollections. If categorised, remove it from the supplied miscRefs map.
  *
  * @param fd the FieldDecriptor (a references or collection)
  * @param taggedType 'reference' or 'collection'
  * @param dispRef the corresponding DisplayReference or DisplayCollection
  * @param miscRefs map that contains dispRef (may be removed by this method)
  * @param tagManager the tag manager
  * @param sup the superuser account name
  * @param placementRefsAndCollections take from the ReportObject
  * @param isSuperUser if current user is superuser
  */
 public static void categoriseBasedOnTags(
     FieldDescriptor fd,
     String taggedType,
     DisplayField dispRef,
     Map<String, DisplayField> miscRefs,
     TagManager tagManager,
     String sup,
     Map<String, Map<String, DisplayField>> placementRefsAndCollections,
     boolean isSuperUser) {
   List<Tag> tags =
       tagManager.getTags(
           null,
           fd.getClassDescriptor().getUnqualifiedName() + "." + fd.getName(),
           taggedType,
           sup);
   for (Tag tag : tags) {
     String tagName = tag.getTagName();
     if (!isSuperUser && tagName.equals(TagNames.IM_HIDDEN)) {
       // miscRefs.remove(fd.getName());
       // Maybe it was added already to some placement and
       // that's why it must be removed
       removeField(fd.getName(), placementRefsAndCollections);
       return;
     }
     if (AspectTagUtil.isAspectTag(tagName)) {
       Map<String, DisplayField> refs = placementRefsAndCollections.get(tagName);
       if (refs != null) {
         refs.put(fd.getName(), dispRef);
         miscRefs.remove(fd.getName());
       }
     } else if (tagName.equals(TagNames.IM_SUMMARY)) {
       Map<String, DisplayField> summary = placementRefsAndCollections.get(TagNames.IM_SUMMARY);
       if (summary != null) {
         summary.put(fd.getName(), dispRef);
         miscRefs.remove(fd.getName());
       }
       miscRefs.remove(fd.getName());
     }
   }
 }
Exemple #8
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();
 }
Exemple #9
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();
 }
Exemple #10
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();
 }
Exemple #11
0
 /**
  * Generates the getoBJECT method for producing NotXml.
  *
  * @param cld the ClassDescriptor
  * @return generated java code as a String
  */
 protected String generateGetObject(ClassDescriptor cld) {
   StringBuffer sb = new StringBuffer();
   sb.append(INDENT)
       .append("public StringConstructor getoBJECT() {\n")
       .append(INDENT + INDENT)
       .append(
           "if (!"
               + cld.getName()
               + (cld.isInterface() ? "Shadow" : "")
               + ".class.equals(getClass())) {\n")
       .append(INDENT + INDENT + INDENT)
       .append("return NotXmlRenderer.render(this);\n")
       .append(INDENT + INDENT)
       .append("}\n")
       .append(INDENT + INDENT)
       .append("StringConstructor sb = new StringConstructor();\n")
       .append(INDENT + INDENT)
       .append("sb.append(\"" + DELIM + cld.getName() + "\");\n");
   for (FieldDescriptor field : cld.getAllFieldDescriptors()) {
     if (field instanceof AttributeDescriptor) {
       AttributeDescriptor attribute = (AttributeDescriptor) field;
       if (attribute.getType().startsWith("java.")) {
         sb.append(INDENT + INDENT)
             .append("if (" + attribute.getName() + " != null) {\n")
             .append(INDENT + INDENT + INDENT)
             .append("sb.append(\"" + DELIM + "a" + field.getName() + DELIM + "\")");
         if ("java.util.Date".equals(attribute.getType())) {
           sb.append(".append(" + attribute.getName() + ".getTime());\n");
         } else if ("java.lang.String".equals(attribute.getType())) {
           sb.append(";\n")
               .append(INDENT + INDENT + INDENT)
               .append("String string = " + attribute.getName() + ";\n")
               .append(INDENT + INDENT + INDENT)
               .append("while (string != null) {\n")
               .append(INDENT + INDENT + INDENT + INDENT)
               .append("int delimPosition = string.indexOf(\"" + DELIM + "\");\n")
               .append(INDENT + INDENT + INDENT + INDENT)
               .append("if (delimPosition == -1) {\n")
               .append(INDENT + INDENT + INDENT + INDENT + INDENT)
               .append("sb.append(string);\n")
               .append(INDENT + INDENT + INDENT + INDENT + INDENT)
               .append("string = null;\n")
               .append(INDENT + INDENT + INDENT + INDENT)
               .append("} else {\n")
               .append(INDENT + INDENT + INDENT + INDENT + INDENT)
               .append("sb.append(string.substring(0, delimPosition + 3));\n")
               .append(INDENT + INDENT + INDENT + INDENT + INDENT)
               .append("sb.append(\"" + ENCODED_DELIM + "\");\n")
               .append(INDENT + INDENT + INDENT + INDENT + INDENT)
               .append("string = string.substring(delimPosition + 3);\n")
               .append(INDENT + INDENT + INDENT + INDENT)
               .append("}\n")
               .append(INDENT + INDENT + INDENT)
               .append("}\n");
         } else {
           sb.append(".append(" + attribute.getName() + ");\n");
         }
         sb.append(INDENT + INDENT).append("}\n");
       } else if ("org.intermine.objectstore.query.ClobAccess".equals(attribute.getType())) {
         sb.append(INDENT + INDENT)
             .append("if (" + attribute.getName() + " != null) {\n")
             .append(INDENT + INDENT + INDENT)
             .append("sb.append(\"" + DELIM + "a" + field.getName() + DELIM + "\" + ")
             .append(attribute.getName() + ".getDbDescription());\n")
             .append(INDENT + INDENT)
             .append("}\n");
       } else {
         sb.append(INDENT)
             .append(INDENT)
             .append("sb.append(\"" + DELIM + "a" + field.getName() + DELIM + "\")")
             .append(".append(" + field.getName() + ");\n");
       }
     } else if (field.isReference()) {
       sb.append(INDENT + INDENT)
           .append("if (" + field.getName() + " != null) {\n")
           .append(INDENT + INDENT + INDENT)
           .append("sb.append(\"" + DELIM + "r" + field.getName() + DELIM + "\")")
           .append(".append(" + field.getName() + ".getId());\n")
           .append(INDENT + INDENT)
           .append("}\n");
     }
   }
   sb.append(INDENT + INDENT).append("return sb;\n").append(INDENT).append("}\n");
   return sb.toString();
 }
Exemple #12
0
  /**
   * Write code for getters and setters for given field.
   *
   * @param field descriptor for field
   * @param fieldPresent true if this class has the associated field
   * @return string with generated java code
   */
  protected String generateGetSet(FieldDescriptor field, boolean fieldPresent) {
    String name = field.getName();
    String type = getType(field);

    StringBuffer sb = new StringBuffer();

    // Get method
    sb.append(INDENT)
        .append("public ")
        .append(type)
        .append(" get")
        .append(StringUtil.reverseCapitalisation(name))
        .append("()");
    if (!fieldPresent) {
      sb.append(";" + ENDL);
    } else {
      sb.append(" { ");
      if ((field instanceof ReferenceDescriptor) && (!(field instanceof CollectionDescriptor))) {
        // This is an object reference.
        sb.append("if (")
            .append(name)
            .append(" instanceof org.intermine.objectstore.proxy.ProxyReference) { return ")
            .append("((")
            .append(type)
            .append(") ((org.intermine.objectstore.proxy.ProxyReference) ")
            .append(name)
            .append(").getObject()); }; return (")
            .append(type)
            .append(") ")
            .append(name)
            .append("; }" + ENDL);
      } else {
        sb.append("return ").append(name).append("; }" + ENDL);
      }
    }

    // Set method
    sb.append(INDENT)
        .append("public void ")
        .append("set")
        .append(StringUtil.reverseCapitalisation(name))
        .append("(final ")
        .append(type)
        .append(" ")
        .append(name)
        .append(")");
    if (!fieldPresent) {
      sb.append(";" + ENDL);
    } else {
      sb.append(" { ").append("this.").append(name).append(" = ").append(name).append("; }" + ENDL);
    }

    if (field instanceof ReferenceDescriptor) {
      if (field instanceof CollectionDescriptor) {
        sb.append(INDENT)
            .append("public void add")
            .append(StringUtil.reverseCapitalisation(name))
            .append("(final ")
            .append(((CollectionDescriptor) field).getReferencedClassDescriptor().getName())
            .append(" arg)");
        if (fieldPresent) {
          sb.append(" { ").append(name).append(".add(arg); }" + ENDL);
        } else {
          sb.append(";" + ENDL);
        }
      } else {
        // This is an object reference.
        sb.append(INDENT)
            .append("public void proxy")
            .append(StringUtil.reverseCapitalisation(name))
            .append("(final org.intermine.objectstore.proxy.ProxyReference ")
            .append(name)
            .append(")");
        if (fieldPresent) {
          sb.append(" { this.").append(name).append(" = ").append(name).append("; }" + ENDL);
        } else {
          sb.append(";" + ENDL);
        }
        sb.append(INDENT)
            .append("public org.intermine.model.InterMineObject proxGet")
            .append(StringUtil.reverseCapitalisation(name))
            .append("()");
        if (fieldPresent) {
          sb.append(" { return ").append(name).append("; }" + ENDL);
        } else {
          sb.append(";" + ENDL);
        }
      }
    }

    return sb.toString();
  }
  @Override
  public void display(HttpServletRequest request, ReportObject reportObject) {

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

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

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

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

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

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

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

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

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

          request.setAttribute("collection", t);
          break;
        }
      }
    }
  }
  /**
   * Create a new DelimitedFileConfiguration from an InputStream.
   *
   * @param model The model to use when looking for ClassDescriptors and FieldDescriptors
   * @param inputStream The InputStream to read the configuration from
   * @throws IOException throws if the read fails
   */
  public DelimitedFileConfiguration(Model model, InputStream inputStream) throws IOException {

    Properties properties = new Properties();

    properties.load(inputStream);

    String className = properties.getProperty("className");

    if (className == null) {
      throw new IllegalArgumentException(
          "className not set in property file for " + "DelimitedFileConfiguration");
    }
    configClassDescriptor = model.getClassDescriptorByName(className);

    if (configClassDescriptor == null) {
      throw new IllegalArgumentException("cannot find ClassDescriptor for: " + className);
    }

    Map columnFieldDescriptorMap = new TreeMap();

    Enumeration enumeration = properties.propertyNames();

    while (enumeration.hasMoreElements()) {
      String key = (String) enumeration.nextElement();

      if (key.startsWith("column.")) {
        String columnNumberString = key.substring(7);

        try {
          int keyColumnNumber = Integer.valueOf(columnNumberString).intValue();

          String fieldName = properties.getProperty(key);

          FieldDescriptor columnFD = configClassDescriptor.getFieldDescriptorByName(fieldName);

          if (columnFD == null) {
            throw new IllegalArgumentException(
                "cannot find FieldDescriptor for " + fieldName + " in " + className);
          }

          if (!columnFD.isAttribute()) {
            String message =
                "field: "
                    + fieldName
                    + " in "
                    + className
                    + " is not an attribute field so cannot be used as a "
                    + "className in DelimitedFileConfiguration";
            throw new IllegalArgumentException(message);
          }

          columnFieldDescriptorMap.put(new Integer(keyColumnNumber), columnFD);
        } catch (NumberFormatException e) {
          throw new IllegalArgumentException(
              "column number ("
                  + key
                  + ") not parsable "
                  + "in property file for "
                  + "DelimitedFileConfiguration");
        }
      }
    }

    int mapMax = findMapMaxKey(columnFieldDescriptorMap);

    columnFieldDescriptors = new ArrayList(mapMax + 1);

    for (int columnNumber = 0; columnNumber < mapMax + 1; columnNumber++) {
      FieldDescriptor columnFD =
          (FieldDescriptor) columnFieldDescriptorMap.get(new Integer(columnNumber));

      columnFieldDescriptors.add(columnFD);
    }
  }
  /** {@inheritDoc} */
  @SuppressWarnings("unused")
  @Override
  public ActionForward execute(
      @SuppressWarnings("unused") ActionMapping mapping,
      @SuppressWarnings("unused") ActionForm form,
      HttpServletRequest request,
      @SuppressWarnings("unused") HttpServletResponse response)
      throws Exception {

    long startTime = System.currentTimeMillis();

    HttpSession session = request.getSession();
    InterMineAPI im = SessionMethods.getInterMineAPI(session);

    if (im.getBagManager().isAnyBagToUpgrade(SessionMethods.getProfile(session))) {
      recordError(new ActionMessage("login.upgradeListManually"), request);
    }
    // fetch & set requested object
    InterMineObject requestedObject = getRequestedObject(im, request);

    if (requestedObject != null) {
      ReportObjectFactory reportObjectFactory = SessionMethods.getReportObjects(session);
      ReportObject reportObject = reportObjectFactory.get(requestedObject);

      request.setAttribute("object", reportObject);
      request.setAttribute("reportObject", reportObject);

      request.setAttribute("requestedObject", requestedObject);

      // hell starts here
      TagManager tagManager = im.getTagManager();
      ServletContext servletContext = session.getServletContext();
      ObjectStore os = im.getObjectStore();
      String superuser = im.getProfileManager().getSuperuser();
      if (superuser.equals(SessionMethods.getProfile(session).getUsername())) {
        request.setAttribute("SHOW_TAGS", true);
      }
      // place InlineLists based on TagManager, reportObject is cached while Controller is not
      Map<String, List<InlineList>> placedInlineLists = new TreeMap<String, List<InlineList>>();
      // traverse all unplaced (non-header) InlineLists
      for (InlineList list : reportObject.getNormalInlineLists()) {
        FieldDescriptor fd = list.getDescriptor();
        String taggedType = getTaggedType(fd);

        // assign lists to any aspects they are tagged to or put in unplaced lists
        String fieldPath = fd.getClassDescriptor().getUnqualifiedName() + "." + fd.getName();
        List<Tag> tags = tagManager.getTags(null, fieldPath, taggedType, superuser);
        for (Tag tag : tags) {
          String tagName = tag.getTagName();
          if (AspectTagUtil.isAspectTag(tagName)) {
            List<InlineList> listsForAspect = placedInlineLists.get(tagName);
            if (listsForAspect == null) {
              listsForAspect = new ArrayList<InlineList>();
              placedInlineLists.put(tagName, listsForAspect);
            }
            listsForAspect.add(list);
          } else if (tagName.equals(TagNames.IM_SUMMARY)) {
            List<InlineList> summaryLists = placedInlineLists.get(tagName);
            if (summaryLists == null) {
              summaryLists = new ArrayList<InlineList>();
              placedInlineLists.put(tagName, summaryLists);
            }
            summaryLists.add(list);
          }
        }
      }

      // any lists that aren't tagged will be 'unplaced'
      List<InlineList> unplacedInlineLists =
          new ArrayList<InlineList>(reportObject.getNormalInlineLists());
      unplacedInlineLists.removeAll(placedInlineLists.values());

      long now = System.currentTimeMillis();
      LOG.info("TIME placed inline lists: " + (now - startTime) + "ms");
      long stepTime = now;

      request.setAttribute("mapOfInlineLists", placedInlineLists);
      request.setAttribute("listOfUnplacedInlineLists", unplacedInlineLists);

      Map<String, Map<String, DisplayField>> placementRefsAndCollections =
          new TreeMap<String, Map<String, DisplayField>>();
      Set<String> aspects = new LinkedHashSet<String>(SessionMethods.getCategories(servletContext));

      Set<ClassDescriptor> cds =
          os.getModel().getClassDescriptorsForClass(requestedObject.getClass());

      for (String aspect : aspects) {
        placementRefsAndCollections.put(
            TagNames.IM_ASPECT_PREFIX + aspect,
            new TreeMap<String, DisplayField>(String.CASE_INSENSITIVE_ORDER));
      }

      Map<String, DisplayField> miscRefs =
          new TreeMap<String, DisplayField>(reportObject.getRefsAndCollections());
      placementRefsAndCollections.put(TagNames.IM_ASPECT_MISC, miscRefs);

      // summary refs and colls
      Map<String, DisplayField> summaryRefsCols = new TreeMap<String, DisplayField>();
      placementRefsAndCollections.put(TagNames.IM_SUMMARY, summaryRefsCols);

      for (Iterator<Entry<String, DisplayField>> iter =
              reportObject.getRefsAndCollections().entrySet().iterator();
          iter.hasNext(); ) {
        Map.Entry<String, DisplayField> entry = iter.next();
        DisplayField df = entry.getValue();
        if (df instanceof DisplayReference) {
          categoriseBasedOnTags(
              ((DisplayReference) df).getDescriptor(),
              "reference",
              df,
              miscRefs,
              tagManager,
              superuser,
              placementRefsAndCollections,
              SessionMethods.isSuperUser(session));
        } else if (df instanceof DisplayCollection) {
          categoriseBasedOnTags(
              ((DisplayCollection) df).getDescriptor(),
              "collection",
              df,
              miscRefs,
              tagManager,
              superuser,
              placementRefsAndCollections,
              SessionMethods.isSuperUser(session));
        }
      }

      // remove any fields overridden by displayers
      removeFieldsReplacedByReportDisplayers(reportObject, placementRefsAndCollections);
      request.setAttribute("placementRefsAndCollections", placementRefsAndCollections);

      String type = reportObject.getType();
      request.setAttribute("objectType", type);

      String stableLink = PortalHelper.generatePortalLink(reportObject.getObject(), im, request);
      if (stableLink != null) {
        request.setAttribute("stableLink", stableLink);
      }

      stepTime = System.currentTimeMillis();
      startTime = stepTime;

      // attach only non empty categories
      Set<String> allClasses = new HashSet<String>();
      for (ClassDescriptor cld : cds) {
        allClasses.add(cld.getUnqualifiedName());
      }
      TemplateManager templateManager = im.getTemplateManager();
      Map<String, List<ReportDisplayer>> displayerMap = reportObject.getReportDisplayers();

      stepTime = System.currentTimeMillis();
      startTime = stepTime;

      List<String> categories = new LinkedList<String>();
      for (String aspect : aspects) {
        // 1) Displayers
        // 2) Inline Lists
        if ((displayerMap != null && displayerMap.containsKey(aspect))
            || placedInlineLists.containsKey(aspect)) {
          categories.add(aspect);
        } else {
          // 3) Templates
          if (!templateManager.getReportPageTemplatesForAspect(aspect, allClasses).isEmpty()) {
            categories.add(aspect);
          } else {
            // 4) References & Collections
            if (placementRefsAndCollections.containsKey("im:aspect:" + aspect)
                && placementRefsAndCollections.get("im:aspect:" + aspect) != null) {
              for (DisplayField df :
                  placementRefsAndCollections.get("im:aspect:" + aspect).values()) {
                categories.add(aspect);
                break;
              }
            }
          }
        }
      }
      if (!categories.isEmpty()) {
        request.setAttribute("categories", categories);
      }
      now = System.currentTimeMillis();
      LOG.info("TIME made list of categories: " + (now - stepTime) + "ms");
    }

    return null;
  }
  /**
   * Look a the values of the given primary key in the object and return true if and only if some
   * part of the primary key is null. If the primary key contains a reference it is sufficient for
   * any of the primary keys of the referenced object to be non-null (ie objectPrimaryKeyIsNull()
   * returning true).
   *
   * @param model the Model in which to find ClassDescriptors
   * @param obj the Object to check
   * @param cld one of the classes that obj is. Only primary keys for this classes will be checked
   * @param pk the primary key to check
   * @param source the Source database
   * @param idMap an IntToIntMap from source IDs to destination IDs
   * @return true if the the given primary key is non-null for the given object
   * @throws MetaDataException if anything goes wrong
   */
  public static boolean objectPrimaryKeyNotNull(
      Model model,
      InterMineObject obj,
      ClassDescriptor cld,
      PrimaryKey pk,
      Source source,
      IntToIntMap idMap)
      throws MetaDataException {
    for (String fieldName : pk.getFieldNames()) {
      FieldDescriptor fd = cld.getFieldDescriptorByName(fieldName);
      if (fd instanceof AttributeDescriptor) {
        Object value;
        try {
          value = obj.getFieldValue(fieldName);
        } catch (IllegalAccessException e) {
          throw new MetaDataException(
              "Failed to get field " + fieldName + " for key " + pk + " from " + obj, e);
        }
        if (value == null) {
          return false;
        }
      } else if (fd instanceof CollectionDescriptor) {
        throw new MetaDataException(
            "Primary key "
                + pk.getName()
                + " for class "
                + cld.getName()
                + " cannot contain collection "
                + fd.getName()
                + ": collections cannot be part of a primary key. Please edit"
                + model.getName()
                + "_keyDefs.properties");
      } else if (fd instanceof ReferenceDescriptor) {
        InterMineObject refObj;
        try {
          refObj = (InterMineObject) obj.getFieldProxy(fieldName);
        } catch (IllegalAccessException e) {
          throw new MetaDataException(
              "Failed to get field " + fieldName + " for key " + pk + " from " + obj, e);
        }
        if (refObj == null) {
          return false;
        }

        if ((refObj.getId() != null) && (idMap.get(refObj.getId()) != null)) {
          // We have previously loaded the object in this reference.
          continue;
        }

        if (refObj instanceof ProxyReference) {
          refObj = ((ProxyReference) refObj).getObject();
        }

        boolean foundNonNullKey = false;
        boolean foundKey = false;
        Set<ClassDescriptor> classDescriptors =
            model.getClassDescriptorsForClass(refObj.getClass());

        CLDS:
        for (ClassDescriptor refCld : classDescriptors) {
          Set<PrimaryKey> primaryKeys;

          if (source == null) {
            primaryKeys =
                new LinkedHashSet<PrimaryKey>(PrimaryKeyUtil.getPrimaryKeys(refCld).values());
          } else {
            primaryKeys = DataLoaderHelper.getPrimaryKeys(refCld, source, null);
          }

          for (PrimaryKey refPK : primaryKeys) {
            foundKey = true;

            if (objectPrimaryKeyNotNull(model, refObj, refCld, refPK, source, idMap)) {
              foundNonNullKey = true;
              break CLDS;
            }
          }
        }

        if (foundKey && (!foundNonNullKey)) {
          return false;
        }
      }
    }

    return true;
  }