예제 #1
0
  /**
   * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually
   * should go to struct.
   *
   * @param from
   * @param to
   * @param excludes
   * @return
   * @throws Exception
   */
  public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception {
    Arrays.sort(excludes);
    for (Field f : from.fields()) {
      if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue;

      Object o = f.get(from);
      if (o == null) continue;

      Field tof = to.getField(f.getName());
      if (tof != null)
        try {
          tof.set(to, Converter.cnv(tof.getGenericType(), o));
        } catch (Exception e) {
          System.out.println(
              "Failed to convert "
                  + f.getName()
                  + " from "
                  + from.getClass()
                  + " to "
                  + to.getClass()
                  + " value "
                  + o
                  + " exception "
                  + e);
        }
    }

    return to;
  }
예제 #2
0
 // generates the 'select' part of the SQL select statement
 public String selectProperties(DataObj d) {
   StringBuilder s = new StringBuilder(1024);
   String name = d.getName();
   s.append("select ");
   boolean firstField = true;
   for (Field f : d.getFields()) {
     if (firstField) {
       firstField = false;
       s.append(name + "." + f.getName() + " ");
     } else {
       s.append(", " + name + "." + f.getName() + " ");
     }
   }
   return s.toString();
 }
  /**
   * Computes the serial version UID value for the given class. The code is taken from {@link
   * ObjectStreamClass#computeDefaultSUID(Class)}.
   *
   * @param cls A class.
   * @return A serial version UID.
   * @throws IOException If failed.
   */
  static long computeSerialVersionUid(Class cls) throws IOException {
    if (Serializable.class.isAssignableFrom(cls) && !Enum.class.isAssignableFrom(cls)) {
      return ObjectStreamClass.lookup(cls).getSerialVersionUID();
    }

    MessageDigest md;

    try {
      md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
      throw new IOException("Failed to get digest for SHA.", e);
    }

    md.update(cls.getName().getBytes(UTF_8));

    for (Field f : getFieldsForSerialization(cls)) {
      md.update(f.getName().getBytes(UTF_8));
      md.update(f.getType().getName().getBytes(UTF_8));
    }

    byte[] hashBytes = md.digest();

    long hash = 0;

    // Composes a single-long hash from the byte[] hash.
    for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--)
      hash = (hash << 8) | (hashBytes[i] & 0xFF);

    return hash;
  }
예제 #4
0
 public String toJsonObj(DataObj d) {
   StringBuilder s = new StringBuilder(1024);
   s.append(returnTab(2) + "var data = {\n");
   String name = d.getName();
   boolean firstField = true;
   for (Field f : d.getFields()) {
     // update will not change the auto-created id
     if (f.getName().equals("ID")) {
       continue;
     }
     if (firstField) {
       firstField = false;
       s.append(returnTab(3) + f.getName() + " : " + name + "." + f.getName() + " ");
     } else {
       s.append(",\n" + returnTab(3) + f.getName() + " : " + name + "." + f.getName() + " ");
     }
   }
   s.append("\n" + returnTab(2) + "};\n");
   return s.toString();
 }
예제 #5
0
  protected void generateView(Map<String, org.ektorp.support.DesignDocument.View> views, Field f) {
    DocumentReferences referenceMetaData = f.getAnnotation(DocumentReferences.class);
    if (referenceMetaData == null) {
      LOG.warn("No DocumentReferences annotation found in field: ", f.getName());
      return;
    }

    if (referenceMetaData.view().length() > 0) {
      LOG.debug("Skipping view generation for field {} as view is already specified", f.getName());
      return;
    }

    if (Set.class.isAssignableFrom(f.getType())) {
      generateSetBasedDocRefView(views, f, referenceMetaData);
    } else {
      throw new ViewGenerationException(
          String.format(
              "The type of the field: %s in %s annotated with DocumentReferences is not supported. (Must be assignable from java.util.Set)",
              f.getName(), f.getDeclaringClass()));
    }
  }
예제 #6
0
 private static LinkedHashMap<String, Prop> createProps() {
   Field[] fs = Configuration.class.getDeclaredFields();
   LinkedHashMap<String, Prop> res = new LinkedHashMap<String, Prop>();
   for (Field f : fs)
     if (!Modifier.isStatic(f.getModifiers())) {
       Description annotation = f.getAnnotation(Description.class);
       if (annotation != null) {
         String name = f.getName().replace('_', '.');
         res.put(name, new Prop(name, annotation.value(), f));
       }
     }
   return res;
 }
예제 #7
0
파일: Graph.java 프로젝트: safdariqbal/frex
 private void assertion(boolean basic, Var x, Field f) {
   if (basic) {
     if (x.getType().getKind() != TypeIR.Kind.BASIC) {
       if (f == null) {
         System.out.println(" 1mm " + x.getType());
         fail = true;
       }
       if (f.getType().getKind() != TypeIR.Kind.BASIC) {
         System.out.println(" xxmm " + x.getType());
         System.out.println(" 2mm " + f.getName() + " " + f.getType());
         fail = true;
       }
     }
   } else {
     if (x.getType().getKind() == TypeIR.Kind.BASIC) {
       System.out.println(" 3mm " + x.getType());
       fail = true;
     }
     if (f != null && f.getType().getKind() == TypeIR.Kind.BASIC) {
       System.out.println(" 4mm " + f.getName() + " " + f.getType());
       fail = true;
     }
   }
 }
예제 #8
0
  private MutableTreeNode populateAttributes(CavityDBObject obj) {
    DefaultMutableTreeNode tree = new DefaultMutableTreeNode("attrs");
    Class cls = obj.getClass();
    for (Field f : cls.getFields()) {
      int mod = f.getModifiers();
      if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
        String fieldName = f.getName();
        try {
          Object value = f.get(obj);
          tree.add(
              new DefaultMutableTreeNode(String.format("%s=%s", fieldName, String.valueOf(value))));

        } catch (IllegalAccessException e) {
          // do nothing.
        }
      }
    }
    return tree;
  }
  private void importField(DbJVClass dbClaz, Field field) throws DbException {
    if (dbClaz == null) {
      return;
    }

    DbJVDataMember member = new DbJVDataMember(dbClaz);
    member.setName(field.getName());

    // set field type
    Type type = field.getType();
    member.setType(toAdt(type));
    member.setTypeUse(toTypeUse(type));

    // set field modifiers
    member.setFinal(field.isFinal());
    member.setStatic(field.isStatic());
    member.setTransient(field.isTransient());
    member.setVisibility(toVisibility(field));
    member.setVolatile(field.isVolatile());
  }
예제 #10
0
 /** Reflect operations demo */
 public static void reflect(Object obj) {
   // `cls用于描述对象所属的类`
   Class cls = obj.getClass();
   print("Class Name: " + cls.getCanonicalName());
   // `fields包含对象的所有属性`
   Field[] fields = cls.getDeclaredFields();
   print("List of fields:");
   for (Field f : fields) {
     print(String.format("%30s %15s", f.getType(), f.getName()));
   }
   // `methods包含对象的所有方法`
   Method[] methods = cls.getDeclaredMethods();
   print("List of methods:");
   for (Method m : methods)
     print(
         String.format(
             "%30s %15s %30s",
             m.getReturnType(), m.getName(), Arrays.toString(m.getParameterTypes())));
   Constructor[] constructors = cls.getConstructors();
   print("List of contructors:");
   for (Constructor c : constructors)
     print(String.format("%30s %15s", c.getName(), Arrays.toString(c.getParameterTypes())));
 }
 @Override
 public int compare(Field f1, Field f2) {
   return f1.getName().compareTo(f2.getName());
 }
예제 #12
0
  // query NO starts at 0
  // queryNoNext starts at 1
  // depth starts at 0
  // DataObj d - data object that's foreign keys are being expanded from ids to JSON objects
  // depth - tab placement
  // queryNo - which query is currently
  public String evaluateFK(
      DataObj d, int depth, String lastQueryFrom, String lastQueryWhere, String dbQueryParam) {
    StringBuilder s = new StringBuilder(4028);
    HashMap<DataObj, List<String>> dataObjsMap = new HashMap<DataObj, List<String>>();
    // First, evaluate all the foreign keys on the current object
    for (Field f : d.getFields()) {
      if (f.getType() == Field.Type.FOREIGN_KEY) {
        // get the object corresponding to the foreign key field str
        // so that you know what fields to get in sql statement
        for (DataObj fkObj : d.getDependencies()) {
          if ((fkObj.getName()).equals(f.getTypeStr())) {
            String parentRow = "rows" + Integer.toString(queryNo);
            String fkRow = "rows" + Integer.toString(queryNoNext);
            String fkName = fkObj.getName();
            String parName = d.getName();

            // The 'from' part of a SQL select FROM where
            String queryFrom = lastQueryFrom + " " + fkName + " as " + fkName + " ";

            // The 'where' part of a SQL select from WHERE
            String queryWhere =
                lastQueryWhere + " " + fkName + ".id = " + parName + "." + f.getName();

            // Recursive calls do need this text
            if (queryNo == 0) {
              queryFrom += " inner join " + parName + " as " + parName + " ";
              queryWhere += " and " + parName + ".id = ?";
            }

            if (depth == 0) {
              s.append(returnTab(2 + depth) + "totalCount += rows0.length;\n");
            }
            s.append(returnTab(2 + depth) + parentRow + ".forEach(function(row) { \n");
            s.append(returnTab(3 + depth) + "query = \"" + selectProperties(fkObj) + "\";\n");
            s.append(returnTab(3 + depth) + "query += \"from " + queryFrom + "\";\n");
            s.append(returnTab(3 + depth) + "query += \"where " + queryWhere + "\";\n");
            s.append(
                returnTab(3 + depth)
                    + "con.query(query, "
                    + dbQueryParam
                    + ", function(err, "
                    + fkRow
                    + ",fields) {\n");
            s.append(returnTab(4 + depth) + "if (err) throw err;\n");
            s.append(returnTab(4 + depth) + "row." + f.getName() + " = " + fkRow + "[0];\n");

            // Store this object, so below you can check if it has
            // foreign keys that have to be evaluated
            ArrayList<String> a = new ArrayList<String>();
            a.add(queryFrom + " inner join ");
            a.add(queryWhere + " and ");
            a.add(Integer.toString(queryNoNext));
            dataObjsMap.put(fkObj, a);
            depth += 2;
            queryNoNext++;
            break;
          }
        }
      }
    }

    // Second, recursively evaluate all of the foreign key objects
    // The keys of dataObjsMap are all of the objects that  are
    // DataObj d's object dependencies
    // The value is an array [0] - queryFrom
    //						 [1] - queryWhere
    //						 [2] - queryNo
    // The dataObjsMap is populated roughly 10 lines up
    Iterator it = dataObjsMap.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry one = (Map.Entry) it.next();
      DataObj key = (DataObj) one.getKey();

      List<String> values = (List<String>) dataObjsMap.get(key);

      // reset global variable queryNo
      // why are we parsing ints? Need to parse the int because
      // [2] queryNo is an int
      queryNo = Integer.parseInt(values.get(2));
      s.append(
          evaluateFK(key, depth, (String) values.get(0), (String) values.get(1), dbQueryParam));
    }
    if (depth > tabDepth) {
      tabDepth = depth;
    }
    return s.toString();
  }
예제 #13
0
    private static void extractViewPattern(int depth, ViewTrace trace, StringBuilder p) {
      if (!processedViewsForPatterns.add(trace)) {
        p.append("(ALIASED) ");
      }

      p.append(trace.realView.getClass() + " size = " + trace.realView.size() + "\n");
      indent(depth, p);

      p.append("    use:");
      if (trace.materializeCount == 0 && trace.sumCount == 0 && trace.getCount == 0) {
        p.append(" UNUSED");
      } else {
        if (trace.getCount > 0) {
          p.append(" get");
        }
        if (trace.materializeCount > 0) {
          p.append(" materialize");
        }
        if (trace.sumCount > 0) {
          p.append(" sum");
        }
      }
      p.append("\n");

      if (false) {
        p.append("    allocationSite =");
        Site.printSite(trace.allocationSite, p);
        p.append("\n");
        indent(depth, p);
      }

      RArray view = trace.realView;
      Class viewClass = view.getClass();
      Field[] fields = getAllFields(viewClass);
      boolean printedField = false;

      for (Field f : fields) {
        if (f.isSynthetic()) {
          continue;
        }
        Class fieldClass = f.getType();
        if (RArray.class.isAssignableFrom(fieldClass)) {
          continue; // these later
        }
        indent(depth, p);
        p.append("    " + f.getName() + " ");
        try {
          f.setAccessible(true);
          Object o = f.get(view);
          p.append(o == null ? "null (" + fieldClass + ")" : o.getClass());
          p.append("\n");
          printedField = true;
        } catch (IllegalAccessException e) {
          assert Utils.check(false, "can't read a view field " + e);
        }
      }

      boolean printNewline = printedField;
      for (Field f : fields) {
        if (f.isSynthetic()) {
          continue;
        }
        Class fieldClass = f.getType();
        if (!RArray.class.isAssignableFrom(fieldClass)) {
          continue;
        }
        if (printNewline) {
          p.append("\n");
          printNewline = false;
        }
        indent(depth, p);
        p.append("    " + f.getName() + " ");
        try {
          f.setAccessible(true);
          Object o = f.get(view);
          if (o instanceof TracingView) {
            p.append("VIEW ");
            TracingView child = (TracingView) o;
            extractViewPattern(depth + 2, child.getTrace(), p);
          } else {
            p.append("ARRAY " + o.getClass() + " size = " + ((RArray) o).size());
            if (o instanceof View) {
              ps.println("MISSED VIEW " + o);
            }
          }
          p.append("\n");
        } catch (IllegalAccessException e) {
          assert Utils.check(false, "can't read a view field " + e);
        }
      }
    }
예제 #14
0
    private static void dumpView(int depth, ViewTrace trace) {
      printedIndividualViews.add(trace);

      ps.println(trace.realView + " size = " + trace.realView.size());
      if (TRACE_ALLOCATION_SITE) {
        indent(depth);
        ps.print("    allocationSite =");
        Site.printSite(trace.allocationSite);
        ps.println();
      }

      int unused = trace.unusedElements();
      int redundant = trace.redundantGets();

      boolean singleUse;
      Site[] useSites;

      if (TRACE_USE_SITES) {
        useSites = trace.useSites.toArray(new Site[trace.useSites.size()]);
        singleUse = (useSites.length == 1);
      } else if (TRACE_SINGLE_USE_SITE) {
        useSites = null;
        singleUse = !trace.multipleUseSites;
      } else {
        useSites = null;
        singleUse = false;
      }
      if (singleUse) {
        indent(depth);
        ps.print("    singleUseSite = US");
        Site.printSite(useSites != null ? useSites[0] : trace.singleUseSite);

        if (trace.getCount > 0) {
          ps.println(" (get)");
        } else if (trace.sumCount > 0) {
          ps.println(" (sum)");
        } else {
          ps.println(" (materialize)");
        }

      } else if (trace.getCount > 0) {
        if (TRACE_FIRST_GET_SITE) {
          indent(depth);
          ps.print("    firstGetSite =");
          Site.printSite(trace.firstGetSite);
          ps.println();
        }
        if (trace.materializeCount == 0 && trace.sumCount == 0) {
          if (unused > 0) {
            indent(depth);
            ps.println("    unusedElements = " + unused);
          }
          if (redundant > 0) {
            indent(depth);
            ps.println("    redundantGets = " + redundant + " (no materialize, sum)");
          }
        }
      } else {
        if (trace.materializeCount == 0 && trace.sumCount == 0) {
          indent(depth);
          ps.println("    UNUSED");
        } else {
          indent(depth);
          ps.println(
              "    materializeCount = "
                  + trace.materializeCount
                  + " sumCount = "
                  + trace.sumCount
                  + " getCount = "
                  + trace.getCount);
        }
      }
      if (TRACE_FIRST_MATERIALIZE_SITE && trace.materializeCount > 0 && !singleUse) {
        indent(depth);
        ps.print("    firstMaterializeSite =");
        Site.printSite(trace.firstMaterializeSite);
        ps.println();
      }
      if (TRACE_FIRST_SUM_SITE && trace.sumCount > 0 && !singleUse) {
        indent(depth);
        ps.print("    firstSumSite =");
        Site.printSite(trace.firstSumSite);
        ps.println();
      }
      if (TRACE_USE_SITES) {
        if (useSites.length != 1) {
          indent(depth);
          ps.println("    useSites (" + useSites.length + "):");
          for (Site s : useSites) {
            indent(depth);
            ps.print("        US");
            Site.printSite(s);
            ps.println();
          }
        }
      }

      ps.println();
      RArray view = trace.realView;
      Class viewClass = view.getClass();
      Field[] fields = getAllFields(viewClass);
      boolean printedField = false;

      for (Field f : fields) {
        if (f.isSynthetic()) {
          continue;
        }
        Class fieldClass = f.getType();
        if (RArray.class.isAssignableFrom(fieldClass)) {
          continue; // these later
        }
        indent(depth);
        ps.print("    " + f.getName() + " ");
        try {
          f.setAccessible(true);
          ps.println(f.get(view));
          printedField = true;
        } catch (IllegalAccessException e) {
          assert Utils.check(false, "can't read a view field " + e);
        }
      }

      boolean printNewline = printedField;
      for (Field f : fields) {
        if (f.isSynthetic()) {
          continue;
        }
        Class fieldClass = f.getType();
        if (!RArray.class.isAssignableFrom(fieldClass)) {
          continue;
        }
        if (printNewline) {
          ps.println();
          printNewline = false;
        }
        indent(depth);
        ps.print("    " + f.getName() + " ");
        try {
          f.setAccessible(true);
          Object o = f.get(view);
          if (o instanceof TracingView) {
            ps.print("VIEW ");
            TracingView child = (TracingView) o;
            dumpView(depth + 2, child.getTrace());
          } else {
            ps.print("ARRAY " + o + " size = " + ((RArray) o).size());
            if (o instanceof View) {
              ps.println("MISSED VIEW " + o);
            }
          }
          ps.println();
        } catch (IllegalAccessException e) {
          assert Utils.check(false, "can't read a view field " + e);
        }
      }
    }