Ejemplo n.º 1
0
 public static void setEnv(Map<String, String> newenv) {
   try {
     Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
     Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
     theEnvironmentField.setAccessible(true);
     Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
     env.putAll(newenv);
     Field theCaseInsensitiveEnvironmentField =
         processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
     theCaseInsensitiveEnvironmentField.setAccessible(true);
     Map<String, String> cienv =
         (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
     cienv.putAll(newenv);
   } catch (NoSuchFieldException e) {
     try {
       Class[] classes = Collections.class.getDeclaredClasses();
       Map<String, String> env = System.getenv();
       for (Class cl : classes) {
         if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
           Field field = cl.getDeclaredField("m");
           field.setAccessible(true);
           Object obj = field.get(env);
           Map<String, String> map = (Map<String, String>) obj;
           map.clear();
           map.putAll(newenv);
         }
       }
     } catch (Exception e2) {
       e2.printStackTrace();
     }
   } catch (Exception e1) {
     e1.printStackTrace();
   }
 }
Ejemplo n.º 2
0
 private static void netxsurgery() throws Exception {
   /* Force off NetX codebase classloading. */
   Class<?> nxc;
   try {
     nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader");
   } catch (ClassNotFoundException e1) {
     try {
       nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader");
     } catch (ClassNotFoundException e2) {
       throw (new Exception("No known NetX on classpath"));
     }
   }
   ClassLoader cl = MainFrame.class.getClassLoader();
   if (!nxc.isInstance(cl)) {
     throw (new Exception("Not running from a NetX classloader"));
   }
   Field cblf, lf;
   try {
     cblf = nxc.getDeclaredField("codeBaseLoader");
     lf = nxc.getDeclaredField("loaders");
   } catch (NoSuchFieldException e) {
     throw (new Exception("JNLPClassLoader does not conform to its known structure"));
   }
   cblf.setAccessible(true);
   lf.setAccessible(true);
   Set<Object> loaders = new HashSet<Object>();
   Stack<Object> open = new Stack<Object>();
   open.push(cl);
   while (!open.empty()) {
     Object cur = open.pop();
     if (loaders.contains(cur)) continue;
     loaders.add(cur);
     Object curl;
     try {
       curl = lf.get(cur);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
     for (int i = 0; i < Array.getLength(curl); i++) {
       Object other = Array.get(curl, i);
       if (nxc.isInstance(other)) open.push(other);
     }
   }
   for (Object cur : loaders) {
     try {
       cblf.set(cur, null);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
   }
 }
Ejemplo n.º 3
0
 private static List getBindingIncludeList(final Object object) {
   List includeList = Collections.emptyList();
   try {
     final Class<? extends Object> objectClass = object.getClass();
     if (CLASS_TO_BINDING_INCLUDE_LIST.containsKey(objectClass)) {
       includeList = CLASS_TO_BINDING_INCLUDE_LIST.get(objectClass);
     } else {
       final Field whiteListField =
           objectClass.getDeclaredField(DefaultASTDatabindingHelper.DEFAULT_DATABINDING_WHITELIST);
       if (whiteListField != null) {
         if ((whiteListField.getModifiers() & Modifier.STATIC) != 0) {
           final Object whiteListValue = whiteListField.get(objectClass);
           if (whiteListValue instanceof List) {
             includeList = (List) whiteListValue;
           }
         }
       }
       if (!Environment.getCurrent().isReloadEnabled()) {
         CLASS_TO_BINDING_INCLUDE_LIST.put(objectClass, includeList);
       }
     }
   } catch (Exception e) {
   }
   return includeList;
 }
Ejemplo n.º 4
0
 @SuppressWarnings("rawtypes")
 private void cleanup(GantResult result, GantBinding binding) {
   if (result != null) {
     Class cls = GantMetaClass.class;
     try {
       Field methodsInvoked = cls.getDeclaredField("methodsInvoked");
       methodsInvoked.setAccessible(true);
       Set methodsInvokedSet = (Set) methodsInvoked.get(cls);
       if (methodsInvokedSet != null) {
         methodsInvokedSet.clear();
       }
     } catch (NoSuchFieldException e) {
       // ignore
     } catch (IllegalAccessException e) {
       // ignore
     }
   }
   System.setIn(originalIn);
   System.setOut(originalOut);
   GrailsPluginUtils.clearCaches();
   Map variables = binding.getVariables();
   Object pluginsSettingsObject = variables.get("pluginsSettings");
   if (pluginsSettingsObject instanceof PluginBuildSettings) {
     ((PluginBuildSettings) pluginsSettingsObject).clearCache();
   }
   GroovySystem.getMetaClassRegistry().removeMetaClass(GantBinding.class);
   GroovySystem.getMetaClassRegistry().removeMetaClass(Gant.class);
 }
Ejemplo n.º 5
0
 public Field getDeclaredField(Class clazz, String fieldName) throws Exception {
   Field field = clazz.getDeclaredField(fieldName);
   if (field == null
       && clazz.getSuperclass() != null
       && !clazz.getSuperclass().equals(Object.class)) {
     return getDeclaredField(clazz.getSuperclass(), fieldName);
   }
   return field;
 }
Ejemplo n.º 6
0
 public String getname() {
   Class cl = this.getClass();
   try {
     Field name = cl.getDeclaredField("name");
     return (String) name.get(this);
   } catch (NoSuchFieldException | ClassCastException | IllegalAccessException nsfe) {
     return null;
   }
 }
Ejemplo n.º 7
0
  /**
   * @param methodName getter method
   * @param clazz value object class
   * @return attribute name related to the specified getter method
   */
  private String getAttributeName(String methodName, Class classType) {
    String attributeName = null;
    if (methodName.startsWith("is"))
      attributeName =
          methodName.substring(2, 3).toLowerCase()
              + (methodName.length() > 3 ? methodName.substring(3) : "");
    else
      attributeName =
          methodName.substring(3, 4).toLowerCase()
              + (methodName.length() > 4 ? methodName.substring(4) : "");

    // an attribute name "Xxxx" becomes "xxxx" and this is not correct!
    try {
      Class c = classType;
      boolean attributeFound = false;
      while (!c.equals(Object.class)) {
        try {
          c.getDeclaredField(attributeName);
          attributeFound = true;
          break;
        } catch (Throwable ex2) {
          c = c.getSuperclass();
        }
      }
      if (!attributeFound) {
        // now trying to find an attribute having the first character in upper case (e.g. "Xxxx")
        String name = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
        c = classType;
        while (!c.equals(Object.class)) {
          try {
            c.getDeclaredField(name);
            attributeFound = true;
            break;
          } catch (Throwable ex2) {
            c = c.getSuperclass();
          }
        }
        if (attributeFound) attributeName = name;
      }
    } catch (Throwable ex1) {
    }

    return attributeName;
  }
Ejemplo n.º 8
0
 private static Class<?> detectTypeParameter(Class clazz, String name, int idx)
     throws NoSuchFieldException {
   Field declaredField = clazz.getDeclaredField(name);
   Type genericType = declaredField.getGenericType();
   if (genericType instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) genericType;
     return (Class<?>) parameterizedType.getActualTypeArguments()[idx];
   }
   return Object.class;
 }
Ejemplo n.º 9
0
 // Unsafe mechanics
 static long objectFieldOffset(sun.misc.Unsafe UNSAFE, String field, Class<?> klazz) {
   try {
     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
   } catch (NoSuchFieldException e) {
     // Convert Exception to corresponding Error
     NoSuchFieldError error = new NoSuchFieldError(field);
     error.initCause(e);
     throw error;
   }
 }
Ejemplo n.º 10
0
  private static void cleanupSwingDataStructures() throws Exception {
    Class<?> aClass = Class.forName("javax.swing.KeyboardManager");

    Method get = aClass.getMethod("getCurrentManager");
    get.setAccessible(true);
    Object manager = get.invoke(null);
    {
      Field mapF = aClass.getDeclaredField("componentKeyStrokeMap");
      mapF.setAccessible(true);
      Object map = mapF.get(manager);
      ((Map) map).clear();
    }
    {
      Field mapF = aClass.getDeclaredField("containerMap");
      mapF.setAccessible(true);
      Object map = mapF.get(manager);
      ((Map) map).clear();
    }
  }
Ejemplo n.º 11
0
 public static void replaceField(Object newValue, String fieldName, Object owner, Class baseType) {
   Field field;
   try {
     field = baseType.getDeclaredField(fieldName);
     field.setAccessible(true);
     field.set(owner, newValue);
   } catch (Exception e) {
     throw new RuntimeException(e); // just to simplify exception handling
   }
 }
Ejemplo n.º 12
0
  static Field test() throws Exception {
    Class c = Java6Reflection.class;
    Field f = c.getDeclaredField("field1");
    f.setAccessible(true);

    Method m = c.getDeclaredMethod("testMethod");
    m.setAccessible(true);
    m.invoke(new Java6Reflection());

    return f;
  }
Ejemplo n.º 13
0
 /**
  * Set the current opcode. This sets four global fields: the currentOpcode, the
  * currentOpcodeArgTable, the currentFormat and the currentOpcodeSymbolicNames.
  *
  * @param opcode The IA32 architecture opcode to make the current opcode
  */
 static void setCurrentOpcode(String opcode) {
   try {
     currentOpcode = opcode;
     currentOpcodeArgTable = (int[]) opcodeArgTables.get(opcode);
     currentFormat = OperatorFormatTables.getFormat(opcode);
     Field f = formats.getDeclaredField(currentFormat + "ParameterNames");
     currentOpcodeSymbolicNames = (String[]) f.get(null);
   } catch (Throwable e) {
     throw new Error("Cannot handle Assembler opcode " + opcode, e);
   }
 }
Ejemplo n.º 14
0
 private static Field getFieldFromBean(
     Class<?> clazz, String fieldName, final Class<?> originalClass) {
   try {
     Field field = clazz.getDeclaredField(fieldName);
     // Allow access to private instance var's that dont have public setter.
     field.setAccessible(true);
     return field;
   } catch (NoSuchFieldException e) {
     if (clazz.getSuperclass() != null) {
       return getFieldFromBean(clazz.getSuperclass(), fieldName, originalClass);
     }
     throw new MappingException(
         "No such field found " + originalClass.getName() + "." + fieldName, e);
   }
 }
Ejemplo n.º 15
0
 public void registerConstant(final Class<?> c, final String privateFieldName) {
   try {
     final Field field = c.getDeclaredField(privateFieldName);
     field.setAccessible(true);
     final Object v = field.get(null);
     ignoredInstances.put(v, true);
   } catch (final SecurityException e) {
     throw new RuntimeException(e);
   } catch (final NoSuchFieldException e) {
     throw new RuntimeException(e);
   } catch (final IllegalArgumentException e) {
     throw new RuntimeException(e);
   } catch (final IllegalAccessException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 16
0
 public static Field makeAccessible(Class<?> target, String fieldName) {
   try {
     final Field field = target.getDeclaredField(fieldName);
     return (Field)
         AccessController.doPrivileged(
             new PrivilegedExceptionAction<Object>() {
               public Object run() throws IllegalAccessException, InvocationTargetException {
                 if (!field.isAccessible()) field.setAccessible(true);
                 return field;
               }
             });
   } catch (NoSuchFieldException | PrivilegedActionException e) {
     System.out.print("");
   } // keep quiet IError.printStackTrace(e); }
   return null;
 }
Ejemplo n.º 17
0
  // getField: Borrowed from WorldEdit
  @SuppressWarnings("unchecked")
  public static <T> T getField(Object from, String name) {
    Class<?> checkClass = from.getClass();
    do {
      try {
        Field field = checkClass.getDeclaredField(name);
        field.setAccessible(true);
        return (T) field.get(from);

      } catch (NoSuchFieldException ex) {
      } catch (IllegalAccessException ex) {
      }
    } while (checkClass.getSuperclass() != Object.class
        && ((checkClass = checkClass.getSuperclass()) != null));

    return null;
  }
Ejemplo n.º 18
0
 public static Object extractField(Class type, Object target, String fieldName) {
   while (true) {
     Field field;
     try {
       field = type.getDeclaredField(fieldName);
       field.setAccessible(true);
       return field.get(target);
     } catch (Exception e) {
       if (type.equals(Object.class)) {
         e.printStackTrace();
         return null;
       } else {
         // try with superclass!!
         type = type.getSuperclass();
       }
     }
   }
 }
Ejemplo n.º 19
0
  protected static void checkAllTimersAreDisposed() {
    try {
      Class<?> aClass = Class.forName("javax.swing.TimerQueue");

      Method inst = aClass.getDeclaredMethod("sharedInstance");
      inst.setAccessible(true);
      Object queue = inst.invoke(null);
      Field field = aClass.getDeclaredField("firstTimer");
      field.setAccessible(true);
      Object firstTimer = field.get(queue);
      if (firstTimer != null) {
        try {
          fail("Not disposed Timer: " + firstTimer.toString() + "; queue:" + queue);
        } finally {
          field.set(queue, null);
        }
      }
    } catch (Throwable e) {
      // Ignore
    }
  }
Ejemplo n.º 20
0
  private Object getFieldFromObject(Object obj, String field) throws FormatterException {
    if (obj == null) {
      return null;
    }

    try {
      Class<?> parent = obj.getClass();
      while (parent != null) {
        try {
          Field f = parent.getDeclaredField(field);
          f.setAccessible(true);
          return f.get(obj);
        } catch (NoSuchFieldException expt) {
          parent = parent.getSuperclass();
        }
      }

      return null;
    } catch (Exception expt) {
      throw new FormatterException("Can not access field " + field + " in " + obj.getClass());
    }
  }
  /** Initialize constants and try to collect information about the JVM internals. */
  static {
    // Initialize empirically measured defaults. We'll modify them to the current
    // JVM settings later on if possible.
    int referenceSize = Constants.JRE_IS_64BIT ? 8 : 4;
    int objectHeader = Constants.JRE_IS_64BIT ? 16 : 8;
    // The following is objectHeader + NUM_BYTES_INT, but aligned (object alignment)
    // so on 64 bit JVMs it'll be align(16 + 4, @8) = 24.
    int arrayHeader = Constants.JRE_IS_64BIT ? 24 : 12;

    supportedFeatures = EnumSet.noneOf(JvmFeature.class);

    Class<?> unsafeClass = null;
    Object tempTheUnsafe = null;
    try {
      unsafeClass = Class.forName("sun.misc.Unsafe");
      final Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
      unsafeField.setAccessible(true);
      tempTheUnsafe = unsafeField.get(null);
    } catch (Exception e) {
      // Ignore.
    }
    theUnsafe = tempTheUnsafe;

    // get object reference size by getting scale factor of Object[] arrays:
    try {
      final Method arrayIndexScaleM = unsafeClass.getMethod("arrayIndexScale", Class.class);
      referenceSize = ((Number) arrayIndexScaleM.invoke(theUnsafe, Object[].class)).intValue();
      supportedFeatures.add(JvmFeature.OBJECT_REFERENCE_SIZE);
    } catch (Exception e) {
      // ignore.
    }

    // "best guess" based on reference size. We will attempt to modify
    // these to exact values if there is supported infrastructure.
    objectHeader = Constants.JRE_IS_64BIT ? (8 + referenceSize) : 8;
    arrayHeader = Constants.JRE_IS_64BIT ? (8 + 2 * referenceSize) : 12;

    // get the object header size:
    // - first try out if the field offsets are not scaled (see warning in Unsafe docs)
    // - get the object header size by getting the field offset of the first field of a dummy object
    // If the scaling is byte-wise and unsafe is available, enable dynamic size measurement for
    // estimateRamUsage().
    Method tempObjectFieldOffsetMethod = null;
    try {
      final Method objectFieldOffsetM = unsafeClass.getMethod("objectFieldOffset", Field.class);
      final Field dummy1Field = DummyTwoLongObject.class.getDeclaredField("dummy1");
      final int ofs1 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy1Field)).intValue();
      final Field dummy2Field = DummyTwoLongObject.class.getDeclaredField("dummy2");
      final int ofs2 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy2Field)).intValue();
      if (Math.abs(ofs2 - ofs1) == NUM_BYTES_LONG) {
        final Field baseField = DummyOneFieldObject.class.getDeclaredField("base");
        objectHeader = ((Number) objectFieldOffsetM.invoke(theUnsafe, baseField)).intValue();
        supportedFeatures.add(JvmFeature.FIELD_OFFSETS);
        tempObjectFieldOffsetMethod = objectFieldOffsetM;
      }
    } catch (Exception e) {
      // Ignore.
    }
    objectFieldOffsetMethod = tempObjectFieldOffsetMethod;

    // Get the array header size by retrieving the array base offset
    // (offset of the first element of an array).
    try {
      final Method arrayBaseOffsetM = unsafeClass.getMethod("arrayBaseOffset", Class.class);
      // we calculate that only for byte[] arrays, it's actually the same for all types:
      arrayHeader = ((Number) arrayBaseOffsetM.invoke(theUnsafe, byte[].class)).intValue();
      supportedFeatures.add(JvmFeature.ARRAY_HEADER_SIZE);
    } catch (Exception e) {
      // Ignore.
    }

    NUM_BYTES_OBJECT_REF = referenceSize;
    NUM_BYTES_OBJECT_HEADER = objectHeader;
    NUM_BYTES_ARRAY_HEADER = arrayHeader;

    // Try to get the object alignment (the default seems to be 8 on Hotspot,
    // regardless of the architecture).
    int objectAlignment = 8;
    try {
      final Class<?> beanClazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean");
      // Try to get the diagnostic mxbean without calling {@link
      // ManagementFactory#getPlatformMBeanServer()}
      // which starts AWT thread (and shows junk in the dock) on a Mac:
      Object hotSpotBean;
      // Java 7+, HotSpot
      try {
        hotSpotBean =
            ManagementFactory.class
                .getMethod("getPlatformMXBean", Class.class)
                .invoke(null, beanClazz);
      } catch (Exception e1) {
        // Java 6, HotSpot
        try {
          Class<?> sunMF = Class.forName("sun.management.ManagementFactory");
          hotSpotBean = sunMF.getMethod("getDiagnosticMXBean").invoke(null);
        } catch (Exception e2) {
          // Last resort option is an attempt to get it from ManagementFactory's server anyway (may
          // start AWT).
          hotSpotBean =
              ManagementFactory.newPlatformMXBeanProxy(
                  ManagementFactory.getPlatformMBeanServer(),
                  "com.sun.management:type=HotSpotDiagnostic",
                  beanClazz);
        }
      }
      if (hotSpotBean != null) {
        final Method getVMOptionMethod = beanClazz.getMethod("getVMOption", String.class);
        final Object vmOption = getVMOptionMethod.invoke(hotSpotBean, "ObjectAlignmentInBytes");
        objectAlignment =
            Integer.parseInt(vmOption.getClass().getMethod("getValue").invoke(vmOption).toString());
        supportedFeatures.add(JvmFeature.OBJECT_ALIGNMENT);
      }
    } catch (Exception e) {
      // Ignore.
    }

    NUM_BYTES_OBJECT_ALIGNMENT = objectAlignment;

    JVM_INFO_STRING =
        "[JVM: "
            + Constants.JVM_NAME
            + ", "
            + Constants.JVM_VERSION
            + ", "
            + Constants.JVM_VENDOR
            + ", "
            + Constants.JAVA_VENDOR
            + ", "
            + Constants.JAVA_VERSION
            + "]";
  }
Ejemplo n.º 22
0
 public static Object getAdapterSelf(Class<?> adapterClass, Object adapter)
     throws NoSuchFieldException, IllegalAccessException {
   Field self = adapterClass.getDeclaredField("self");
   return self.get(adapter);
 }
Ejemplo n.º 23
0
  public Type navigateQualified(String name, Type[] qualifiers) throws OclTypeException {
    Type theQualifier = null;

    if (qualifiers != null) {
      if (qualifiers.length == 1) theQualifier = qualifiers[0];
      else throw new OclTypeException("ReflectionFacade can handle one qualifier only");
    }
    // System.out.println("ClassAny.navigateQualified:"+this+" "+name);
    Type ret = Basic.navigateAnyQualified(name, this, qualifiers);
    if (ret != null) return ret;
    String[] javaNames = rf.nameAdapter.getNames(name);
    Field f = null;
    for (int i = 0; i < javaNames.length && f == null; i++) {
      Class nextClass = c;
      while (nextClass != null && f == null) {
        try {
          f = nextClass.getDeclaredField(javaNames[i]);
        } catch (NoSuchFieldException nsf) {
          // try next class
        }
        nextClass = nextClass.getSuperclass();
      }
    }
    if (f == null) {
      throw new OclTypeException(c.getName() + " has no field " + name);
    }
    Class type = f.getType();
    Type modeltype = getTypeForClass(type);

    if (modeltype instanceof Collection) {
      Class elementtype = rf.getElementType(f);

      if (rf.reflAdapter.isMap(type)) {
        if (theQualifier == null) {
          if (elementtype != null)
            return new Collection(
                ((Collection) modeltype).getCollectionKind(), getTypeForClass(elementtype));
          else return modeltype;
        } else {
          Class keytype_class = rf.getKeyType(f);
          Type keytype = null;
          if (keytype_class != null) keytype = getTypeForClass(keytype_class);

          if (keytype != null) {
            if (!theQualifier.equals(keytype))
              throw new OclTypeException(
                  "feature "
                      + name
                      + " in classifier "
                      + c
                      + ": expected qualifier type "
                      + keytype
                      + " found "
                      + theQualifier
                      + ".");
            if (elementtype != null) return getTypeForClass(elementtype);
            else
              throw new OclTypeException(
                  "feature "
                      + name
                      + "["
                      + keytype
                      + "] in classifier "
                      + c
                      + " has no @element-type tag.");
          } else
            throw new OclTypeException(
                "feature "
                    + name
                    + " in classifier "
                    + c
                    + ": qualified with type "
                    + theQualifier
                    + ", but feature has no @keytype tag.");
        }
      } else {
        if (theQualifier != null)
          throw new OclTypeException(
              "feature " + name + " in classifier " + c + " cannot be qualified.");

        if (elementtype != null)
          return new Collection(
              ((Collection) modeltype).getCollectionKind(), getTypeForClass(elementtype));
        else return modeltype;
      }
    } else {
      if (theQualifier != null)
        throw new OclTypeException(
            "feature " + name + " in classifier " + c + " cannot be qualified.");
      return modeltype;
    }
  }
Ejemplo n.º 24
0
  /**
   * Serializes the given class to the getCurrentDirectory() directory. The static
   * serializedInstance() method of clazz will be called to get an examplar of clazz. This examplar
   * will then be serialized out to a file stored in getCurrentDirectory().
   *
   * @param clazz the class to serialize.
   * @throws RuntimeException if clazz cannot be serialized. This exception has an informative
   *     message and wraps the originally thrown exception as root cause.
   * @see #getCurrentDirectory()
   */
  private void serializeClass(Class clazz, Map<String, List<String>> classFields)
      throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
      throw new IllegalStateException(
          "There is no "
              + current.getAbsolutePath()
              + " directory. "
              + "\nThis is where the serialized classes should be. "
              + "Please run serializeCurrentDirectory() first.");
    }

    try {
      Field field = clazz.getDeclaredField("serialVersionUID");

      int modifiers = field.getModifiers();
      boolean _static = Modifier.isStatic(modifiers);
      boolean _final = Modifier.isFinal(modifiers);
      field.setAccessible(true);

      if (!_static || !_final || !(23L == field.getLong(null))) {
        throw new RuntimeException(
            "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
      }

      int numFields = getNumNonSerialVersionUIDFields(clazz);

      if (numFields > 0) {
        Method method = clazz.getMethod("serializableInstance");
        Object object = method.invoke(null);

        File file = new File(current, clazz.getName() + ".ser");
        boolean created = file.createNewFile();

        FileOutputStream out = new FileOutputStream(file);
        ObjectOutputStream objOut = new ObjectOutputStream(out);
        objOut.writeObject(object);
        out.close();
      }

      // Make entry in list of class fields.
      ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
      String className = objectStreamClass.getName();
      ObjectStreamField[] fields = objectStreamClass.getFields();
      @SuppressWarnings("Convert2Diamond")
      List<String> fieldList = new ArrayList<>();

      for (ObjectStreamField objectStreamField : fields) {
        String fieldName = objectStreamField.getName();
        fieldList.add(fieldName);
      }

      classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(
          ("There is no static final long field "
              + "'serialVersionUID' in "
              + clazz
              + ". Please make one and set it "
              + "to 23L."));
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(
          "Class " + clazz + "does not " + "have a public static serializableInstance constructor.",
          e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(
          "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException(
          "Unable to statically call the "
              + "serializableInstance() method of class "
              + clazz
              + ".",
          e);
    } catch (IOException e) {
      throw new RuntimeException(
          "Could not create a new, writeable file "
              + "in "
              + getCurrentDirectory()
              + " when trying to serialize "
              + clazz
              + ".",
          e);
    }
  }
Ejemplo n.º 25
0
    public Writer getErrorReport(
        Writer to, final HttpServletRequest request, CharTransformer escape) throws IOException {
      final Writer logMsg = new StringWriter();
      final Writer tee = new org.mmbase.util.ChainedWriter(to, logMsg);
      Writer msg = tee;

      LinkedList<Throwable> stack = getStack();
      String ticket = new Date().toString();

      Map<String, String> props;
      try {
        props = org.mmbase.util.ApplicationContextReader.getProperties("mmbase_errorpage");
      } catch (javax.naming.NamingException ne) {
        props = Collections.emptyMap();
        log.info(ne);
      }

      if (request != null) {
        {
          msg.append("Headers\n----------\n");
          // request properties
          for (Object name : Collections.list(request.getHeaderNames())) {
            msg.append(
                escape.transform(
                    name + ": " + escape.transform(request.getHeader((String) name)) + "\n"));
          }
        }
        {
          msg.append("\nAttributes\n----------\n");
          Pattern p = requestIgnore;
          if (p == null && props.get("request_ignore") != null) {
            p = Pattern.compile(props.get("request_ignore"));
          }
          for (Object name : Collections.list(request.getAttributeNames())) {
            if (p == null || !p.matcher((String) name).matches()) {
              msg.append(
                  escape.transform(name + ": " + request.getAttribute((String) name) + "\n"));
            }
          }
        }
        if (Boolean.TRUE.equals(showSession)
            || (showSession == null && !"false".equals(props.get("show_session")))) {
          HttpSession ses = request.getSession(false);
          if (ses != null) {
            msg.append("\nSession\n----------\n");
            Pattern p = sessionIgnore;
            if (p == null && props.get("session_ignore") != null) {
              p = Pattern.compile(props.get("session_ignore"));
            }
            for (Object name : Collections.list(ses.getAttributeNames())) {
              if (p == null || !p.matcher((String) name).matches()) {
                msg.append(escape.transform(name + ": " + ses.getAttribute((String) name) + "\n"));
              }
            }
          }
        }
      }
      msg.append("\n");
      msg.append("Misc. properties\n----------\n");

      if (request != null) {
        msg.append("method: ").append(escape.transform(request.getMethod())).append("\n");
        msg.append("querystring: ").append(escape.transform(request.getQueryString())).append("\n");
        msg.append("requesturl: ")
            .append(escape.transform(request.getRequestURL().toString()))
            .append("\n");
      }
      if (Boolean.TRUE.equals(showMMBaseVersion)
          || (showMMBaseVersion == null && !"false".equals(props.get("show_mmbase_version")))) {
        msg.append("mmbase version: ").append(org.mmbase.Version.get()).append("\n");
      }
      msg.append("status: ").append("").append(String.valueOf(status)).append("\n\n");

      if (request != null) {
        msg.append("Parameters\n----------\n");
        // request parameters
        Enumeration en = request.getParameterNames();
        while (en.hasMoreElements()) {
          String name = (String) en.nextElement();
          msg.append(name)
              .append(": ")
              .append(escape.transform(request.getParameter(name)))
              .append("\n");
        }
      }
      msg.append("\nException ")
          .append(ticket)
          .append("\n----------\n\n")
          .append(
              exception != null
                  ? (escape.transform(exception.getClass().getName()))
                  : "NO EXCEPTION")
          .append(": ");

      int wroteCauses = 0;
      while (!stack.isEmpty()) {

        Throwable t = stack.removeFirst();
        // add stack stacktraces
        if (t != null) {
          if (stack.isEmpty()) { // write last message always
            msg = tee;
          }
          String message = t.getMessage();
          if (msg != tee) {
            to.append("\n=== skipped(see log)  : ")
                .append(escape.transform(t.getClass().getName()))
                .append(": ")
                .append(message)
                .append("\n");
          }

          msg.append("\n\n").append(escape.transform(t.getClass().getName() + ": " + message));
          StackTraceElement[] stackTrace = t.getStackTrace();
          for (StackTraceElement e : stackTrace) {
            msg.append("\n        at ").append(escape.transform(e.toString()));
          }
          if (!stack.isEmpty()) {
            msg.append("\n-------caused:\n");
          }
          wroteCauses++;
          if (wroteCauses >= MAX_CAUSES) {
            msg = logMsg;
          }
        }
      }
      // write errors to  log
      if (status == 500) {
        try {
          if (props.get("to") != null && props.get("to").length() > 0) {
            javax.naming.Context initCtx = new javax.naming.InitialContext();
            javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env");
            Object mailSession = envCtx.lookup("mail/Session");
            Class sessionClass = Class.forName("javax.mail.Session");
            Class recipientTypeClass = Class.forName("javax.mail.Message$RecipientType");
            Class messageClass = Class.forName("javax.mail.internet.MimeMessage");
            Object mail = messageClass.getConstructor(sessionClass).newInstance(mailSession);
            messageClass
                .getMethod("addRecipients", recipientTypeClass, String.class)
                .invoke(mail, recipientTypeClass.getDeclaredField("TO").get(null), props.get("to"));
            messageClass.getMethod("setSubject", String.class).invoke(mail, ticket);
            mail.getClass().getMethod("setText", String.class).invoke(mail, logMsg.toString());
            Class.forName("javax.mail.Transport")
                .getMethod("send", Class.forName("javax.mail.Message"))
                .invoke(null, mail);
            tee.append("\nmailed to (").append(String.valueOf(props)).append(")");
          }

        } catch (Exception nnfe) {
          tee.append("\nnot mailed (").append(String.valueOf(nnfe)).append(")");
          if (log.isDebugEnabled()) {
            log.debug(nnfe.getMessage(), nnfe);
          }
        }
        log.error("TICKET " + ticket + ":\n" + logMsg);
      }
      return to;
    }