示例#1
0
  private int findfd(Object fdObj) throws Exception {
    Class cl;
    Field f;
    Object val, implVal;

    if ((fdObj instanceof java.net.Socket) || (fdObj instanceof java.net.ServerSocket)) {
      cl = fdObj.getClass();
      f = cl.getDeclaredField("impl");
      f.setAccessible(true);
      val = f.get(fdObj);
      cl = f.getType();
      f = cl.getDeclaredField("fd");
      f.setAccessible(true);
      implVal = f.get(val);
      cl = f.getType();
      f = cl.getDeclaredField("fd");
      f.setAccessible(true);
      return ((Integer) f.get(implVal)).intValue();
    } else if (fdObj instanceof java.io.FileDescriptor) {
      cl = fdObj.getClass();
      f = cl.getDeclaredField("fd");
      f.setAccessible(true);
      return ((Integer) f.get(fdObj)).intValue();
    } else {
      throw new IllegalArgumentException("Illegal Object type.");
    }
  }
 @Override
 public Map parse() {
   if (field.getType().compareTo("json") == 0
       // if the signature is *-> * then guess using {
       || field.getType().startsWith("{")) {
     if (jsonObject instanceof String) {
       logger.debug("json object is string " + jsonObject);
       return null;
     } else return (Map) jsonObject;
   } else return null;
 }
  @Override
  public String getString() throws SQLException {
    int type = JSONTypes.jsonTypes.get(field.getType());
    switch (type) {
      case JSONTypes.JSON_ARRAY:
      case JSONTypes.JSON_OBJECT:
      case JSONTypes.JSON_MAP:
        toJson();
        return sqlJson;
      case JSONTypes.JSON_NULL:
        return null;
      case JSONTypes.JSON_STRING:
        if (sqlJson != null) return sqlJson;
        if (jsonObject != null) return (String) jsonObject;
        isNull = true;
        return null;

        // let the default implementation of toString figure it out
      case JSONTypes.JSON_BOOLEAN:
      case JSONTypes.JSON_NUMBER:
        return jsonObject.toString();
      default:
        return "";
    }
  }
  /**
   * 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;
  }
示例#5
0
 @SuppressWarnings("unchecked")
 private void addFields(List list, boolean isStatic) {
   int count = klass.getFieldCount(isStatic);
   for (int i = 0; i != count; ++i) {
     Field field = klass.getField(i, isStatic);
     FieldID fid = new FieldID(JDWP.getTag(field.getType()), field.getOffset(), isStatic, getID());
     ProxyField proxyField = new ProxyField(fid, field);
     list.add(proxyField);
   }
 }
 private Field findSqlMapExecutorDelegate(SqlMapClient sqlMapClient) {
   Class<?> searchType = sqlMapClient.getClass();
   while (!Object.class.equals(searchType) && searchType != null) {
     Field[] fields = searchType.getDeclaredFields();
     for (Field field : fields) {
       if (SqlMapExecutorDelegate.class.isAssignableFrom(field.getType())) return field;
     }
     searchType = searchType.getSuperclass();
   }
   return null;
 }
示例#7
0
 public void checki(boolean basic, Var x, Field f, Var y, Field g) {
   fail = false;
   if (!basic) {
     if (x.getType().getKind() == TypeIR.Kind.VOID) fail = true;
     if (y.getType().getKind() == TypeIR.Kind.VOID) fail = true;
     if (fail) {
       assert (false);
     }
   }
   assertion(basic, x, f);
   assertion(basic, y, g);
   if (fail) {
     assert (false);
     System.out.println(" Overall ! ");
     System.out.println(x.getType());
     if (f != null) System.out.println(" f " + f.getType());
     System.out.println(y.getType());
     if (g != null) System.out.println(" g " + g.getType());
   }
 }
示例#8
0
 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;
     }
   }
 }
  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
 private static void linkChildren(RArray parentRealView, ViewTrace parentTrace) {
   Class viewClass = parentRealView.getClass();
   Field[] fields = getAllFields(viewClass);
   for (Field f : fields) {
     if (f.isSynthetic()) {
       continue;
     }
     Class fieldClass = f.getType();
     if (RArray.class.isAssignableFrom(fieldClass)) {
       try {
         f.setAccessible(true);
         Object o = f.get(parentRealView);
         if (o instanceof TracingView) {
           ((TracingView) o).getTrace().parentView = parentTrace;
         }
       } catch (IllegalAccessException e) {
         assert Utils.check(false, "can't read a view field " + e);
       }
     }
   }
 }
示例#11
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()));
    }
  }
示例#12
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())));
 }
示例#13
0
  public boolean getBoolean() throws SQLException {
    int type = JSONTypes.jsonTypes.get(field.getType());

    switch (type) {
      case JSONTypes.JSON_BOOLEAN:
        return (boolean) jsonObject;
      case JSONTypes.JSON_NUMBER:
        Number number = (Number) jsonObject;
        return !number.equals((Number) 0);
      case JSONTypes.JSON_STRING:
        String string = (String) jsonObject;
        return !string.isEmpty();
      case JSONTypes.JSON_MAP:
      case JSONTypes.JSON_OBJECT:
        Map map = (Map) jsonObject;
        return !map.isEmpty();
      case JSONTypes.JSON_ARRAY:
        List list = (List) jsonObject;
        return !list.isEmpty();

      default:
        return false;
    }
  }
示例#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);
        }
      }
    }
示例#15
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);
        }
      }
    }
示例#16
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();
  }
示例#17
0
 public int getJDBCType() {
   return JSONTypes.jdbcTypes.get(field.getType());
 }
示例#18
0
  public TypeUniverse() {
    Providers providers =
        Graal.getRequiredCapability(RuntimeProvider.class).getHostBackend().getProviders();
    metaAccess = providers.getMetaAccess();
    constantReflection = providers.getConstantReflection();
    snippetReflection = Graal.getRequiredCapability(SnippetReflectionProvider.class);
    Unsafe theUnsafe = null;
    try {
      theUnsafe = Unsafe.getUnsafe();
    } catch (Exception e) {
      try {
        Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeField.setAccessible(true);
        theUnsafe = (Unsafe) theUnsafeField.get(null);
      } catch (Exception e1) {
        throw (InternalError) new InternalError("unable to initialize unsafe").initCause(e1);
      }
    }
    unsafe = theUnsafe;

    Class<?>[] initialClasses = {
      void.class,
      boolean.class,
      byte.class,
      short.class,
      char.class,
      int.class,
      float.class,
      long.class,
      double.class,
      Object.class,
      Class.class,
      ClassLoader.class,
      String.class,
      Serializable.class,
      Cloneable.class,
      Test.class,
      TestMetaAccessProvider.class,
      List.class,
      Collection.class,
      Map.class,
      Queue.class,
      HashMap.class,
      LinkedHashMap.class,
      IdentityHashMap.class,
      AbstractCollection.class,
      AbstractList.class,
      ArrayList.class
    };
    for (Class<?> c : initialClasses) {
      addClass(c);
    }
    for (Field f : Constant.class.getDeclaredFields()) {
      int mods = f.getModifiers();
      if (f.getType() == Constant.class
          && Modifier.isPublic(mods)
          && Modifier.isStatic(mods)
          && Modifier.isFinal(mods)) {
        try {
          Constant c = (Constant) f.get(null);
          if (c != null) {
            constants.add(c);
          }
        } catch (Exception e) {
        }
      }
    }
    for (Class<?> c : classes) {
      if (c != void.class && !c.isArray()) {
        constants.add(snippetReflection.forObject(Array.newInstance(c, 42)));
      }
    }
    constants.add(snippetReflection.forObject(new ArrayList<>()));
    constants.add(snippetReflection.forObject(new IdentityHashMap<>()));
    constants.add(snippetReflection.forObject(new LinkedHashMap<>()));
    constants.add(snippetReflection.forObject(new TreeMap<>()));
    constants.add(snippetReflection.forObject(new ArrayDeque<>()));
    constants.add(snippetReflection.forObject(new LinkedList<>()));
    constants.add(snippetReflection.forObject("a string"));
    constants.add(snippetReflection.forObject(42));
    constants.add(snippetReflection.forObject(String.class));
    constants.add(snippetReflection.forObject(String[].class));
  }