Example #1
1
 /**
  * Factory method, equivalent to a "fromXML" for step creation. Looks for a class with the same
  * name as the XML tag, with the first letter capitalized. For example, <call /> is
  * abbot.script.Call.
  */
 public static Step createStep(Resolver resolver, Element el) throws InvalidScriptException {
   String tag = el.getName();
   Map attributes = createAttributeMap(el);
   String name = tag.substring(0, 1).toUpperCase() + tag.substring(1);
   if (tag.equals(TAG_WAIT)) {
     attributes.put(TAG_WAIT, "true");
     name = "Assert";
   }
   try {
     name = "abbot.script." + name;
     Log.debug("Instantiating " + name);
     Class cls = Class.forName(name);
     try {
       // Steps with contents require access to the XML element
       Class[] argTypes = new Class[] {Resolver.class, Element.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, el, attributes});
     } catch (NoSuchMethodException nsm) {
       // All steps must support this ctor
       Class[] argTypes = new Class[] {Resolver.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, attributes});
     }
   } catch (ClassNotFoundException cnf) {
     String msg = Strings.get("step.unknown_tag", new Object[] {tag});
     throw new InvalidScriptException(msg);
   } catch (InvocationTargetException ite) {
     Log.warn(ite);
     throw new InvalidScriptException(ite.getTargetException().getMessage());
   } catch (Exception exc) {
     Log.warn(exc);
     throw new InvalidScriptException(exc.getMessage());
   }
 }
  public CircuitElementView instantiateElement(
      UUID elementUUID,
      float positionX,
      float positionY,
      CircuitElementManager elementManager,
      WireManager wireManager)
      throws InvocationTargetException, IllegalAccessException, InstantiationException,
          NoSuchMethodException {
    Class<? extends CircuitElementView> viewType = ElementTypeUUID.VIEW_MAP.get(elementUUID);
    if (viewType == null) throw new IllegalArgumentException("Missing element view UUID");

    Class<? extends CircuitElement> elementType = ElementTypeUUID.ELEMENT_MAP.get(elementUUID);
    if (elementType == null) throw new IllegalArgumentException("Missing element type UUID");

    Constructor<? extends CircuitElementView> viewConstructor;
    viewConstructor =
        viewType.getConstructor(
            Context.class, CircuitElement.class, float.class, float.class, WireManager.class);

    Constructor<? extends CircuitElement> elementConstructor;
    elementConstructor = elementType.getConstructor(CircuitElementManager.class);

    CircuitElement element = elementConstructor.newInstance(elementManager);

    return viewConstructor.newInstance(context, element, 0, 0, wireManager);
  }
Example #3
0
  /**
   * Returns the correct implementation instance for the interface <code>type</code>. For convention
   * the implentation is named <code>InterfaceName + Impl</code>.
   *
   * @param type The interface type
   * @return The correct ModelProxy subclass (if exists), a ModelProxy instance otherwise
   * @throws MalformedModelException is the interface or the implementation are not well formed
   *     (they don't respect the conventions).
   * @throws ModelRuntimeException is any error occurs during the instantiation
   */
  protected ModelProxy createInstance(Class type) {
    Class backClass;
    if (implementations.containsKey(type)) backClass = implementations.get(type);
    else {
      /* type never seen */

      try {
        Package pkg = type.getPackage();
        String pkgN = pkg == null ? "" : pkg.getName();

        backClass = Class.forName(pkgN + tableName(type) + CommonStatic.getImplementationSuffix());

      } catch (Exception e) {
        backClass = ModelProxy.class;
      }

      Validator.validateModel(type, backClass);

      initFieldsTypes(type);
      implementations.put(type, backClass);
    }

    ModelProxy impl = null;
    try {
      impl = (ModelProxy) backClass.newInstance();
    } catch (Exception e) {
      throw new ModelRuntimeException(e.getMessage());
    }

    return impl;
  }
  public String constructDN(final T o, final String parentDN) throws LDAPPersistException {
    final String existingDN = getEntryDN(o);
    if (existingDN != null) {
      return existingDN;
    }

    final LinkedHashMap<String, Attribute> attrMap = new LinkedHashMap<String, Attribute>(1);

    for (final FieldInfo i : rdnFields) {
      final Attribute a = i.encode(o, true);
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_FIELD_MISSING_VALUE.get(type.getName(), i.getField().getName()));
      }

      attrMap.put(toLowerCase(i.getAttributeName()), a);
    }

    for (final GetterInfo i : rdnGetters) {
      final Attribute a = i.encode(o);
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_GETTER_MISSING_VALUE.get(
                type.getName(), i.getMethod().getName()));
      }

      attrMap.put(toLowerCase(i.getAttributeName()), a);
    }

    return constructDN(o, parentDN, attrMap);
  }
    public void addGetter(MetaBeanProperty property) throws Exception {
      MetaMethod getter = property.getGetter();

      // GENERATE private boolean <prop>Set;

      String flagName = String.format("%sSet", property.getName());
      visitor.visitField(
          Opcodes.ACC_PRIVATE, flagName, Type.BOOLEAN_TYPE.getDescriptor(), null, null);

      addConventionGetter(getter.getName(), flagName, property);

      String getterName = getter.getName();
      Class<?> returnType = getter.getReturnType();

      // If it's a boolean property, there can be get or is type variants.
      // If this class has both, decorate both.
      if (returnType.equals(Boolean.TYPE)) {
        boolean getterIsIsMethod = getterName.startsWith("is");
        String propertyNameComponent = getterName.substring(getterIsIsMethod ? 2 : 3);
        String alternativeGetterName =
            String.format("%s%s", getterIsIsMethod ? "get" : "is", propertyNameComponent);

        try {
          type.getMethod(alternativeGetterName);
          addConventionGetter(alternativeGetterName, flagName, property);
        } catch (NoSuchMethodException e) {
          // ignore, no method to override
        }
      }
    }
  /**
   * Creates a new entity enumeration icon chooser.
   *
   * @param enumeration the enumeration to display in this combo box
   */
  public EnumerationIconChooser(Class<E> enumeration) {
    super();

    this.enumeration = enumeration;

    try {
      this.icons = (ImageIcon[]) enumeration.getMethod("getIcons").invoke(null);
      for (int i = 0; i < icons.length; i++) {
        addItem(icons[i]);
      }
    } catch (NoSuchMethodException ex) {
      System.err.println(
          "The method 'getIcons()' is missing in enumeration " + enumeration.getName());
      ex.printStackTrace();
      System.exit(1);
    } catch (IllegalAccessException ex) {
      System.err.println(
          "Cannot access method 'getIcons()' in enumeration "
              + enumeration.getName()
              + ": ex.getMessage()");
      ex.printStackTrace();
      System.exit(1);
    } catch (InvocationTargetException ex) {
      ex.getCause().printStackTrace();
      System.exit(1);
    }
  }
Example #7
0
  public static void validatePassivating(Class<?> cl, Bean<?> bean, String typeName) {
    Class<?> beanClass = bean.getBeanClass();

    if (!Serializable.class.isAssignableFrom(beanClass) && false) {
      ConfigException exn =
          new ConfigException(
              L.l(
                  "{0}: {1} is an invalid {2} because it is not serializable.",
                  cl.getName(), bean, typeName));

      throw exn;
      // InjectManager.create().addDefinitionError(exn);
    }

    for (InjectionPoint ip : bean.getInjectionPoints()) {
      if (ip.isTransient() || ip.isDelegate()) continue;

      Class<?> type = getRawClass(ip.getType());

      if (type.isInterface()) continue;

      if (!Serializable.class.isAssignableFrom(type)) {
        ConfigException exn =
            new ConfigException(
                L.l(
                    "{0}: {1} is an invalid {4} because its injection point '{2}' of type {3} is not serializable.",
                    cl.getName(), bean, ip.getMember().getName(), ip.getType(), typeName));

        throw exn;
      }
    }
  }
 static boolean derivesFrom(Class<?> c, String className) {
   while (c != null) {
     if (c.getName().equals(className)) return true;
     c = c.getSuperclass();
   }
   return false;
 }
Example #9
0
 public Bean(String classPackage, String clazz, ClassLoaderStrategy cls, Bean topLevelBean)
     throws Exception {
   // Get the no-arg constructor and create the bean
   try {
     Class classOfBean = ObjectXml.getClassOfBean((ClassLoader) cls, classPackage + "." + clazz);
     Constructor ct = null;
     // check whether this class is an inner class
     if (classOfBean.getEnclosingClass() != null) {
       ct = classOfBean.getConstructor(new Class[] {classOfBean.getEnclosingClass()});
       beanObject = ct.newInstance(new Object[] {topLevelBean.getBeanObject()});
     } else {
       ct = classOfBean.getConstructor((Class[]) null);
       beanObject = ct.newInstance((Object[]) null);
     }
     // Get an array of property descriptors
     beanInfo = Introspector.getBeanInfo(classOfBean);
     PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
     // load property descriptors into hashtable
     propDesc = new Properties();
     for (int i = 0; i < pds.length; i++) {
       propDesc.put(pds[i].getName(), pds[i]);
     }
   } catch (Exception e) {
     System.err.println("Exception creating bean: " + e.getMessage());
     e.printStackTrace();
     throw e;
   }
 }
Example #10
0
 static Method get_sigaction_method(String cls, String meth)
     throws ClassNotFoundException, NoSuchMethodException {
   return Class.forName(cls)
       .getMethod(
           meth,
           new Class[] {Integer.TYPE, Class.forName("jtux.UProcess$siginfo_t"), Long.TYPE});
 }
 public static void main(String[] args) throws Exception {
   Class clazz = Class.forName("com.mtl.spring.aop.helloworld.ArithmeticCalculatorLoggingProxy");
   Object object = clazz.newInstance();
   Method[] methods = clazz.getMethods();
   StringBuffer sb = new StringBuffer();
   sb.append("public class ")
       .append(object.getClass().getCanonicalName())
       .append("{\n")
       .append("Object object ")
       .append("\n");
   Constructor[] constructors = clazz.getConstructors();
   for (Constructor constructor : constructors) {
     sb.append("\npublic ").append(constructor.getName()).append("(");
     Class<?> p[] = constructor.getParameterTypes();
     for (int j = 0; j < p.length; ++j) {
       sb.append(p[j].getName() + " arg" + j);
       if (j < p.length - 1) {
         sb.delete(sb.length() - 1, sb.length());
       }
     }
     sb.append(") {").append("\n\n");
     sb.append("user.role.cotain(\"/admin/add\") {");
     sb.append("\n System.currentTimeMillis();\n");
     sb.append("this.object  = ").append("arg0");
     sb.append("}");
     sb.append(" \nSystem.currentTimeMillis();\n");
     sb.append("\n}");
   }
   sb.append("\n\n}");
   System.out.println(sb);
   for (Method method : methods) {
     System.out.println(method.getName());
   }
 }
 /** Make a clone of the given object. */
 protected static Object makeClone(Object obj) {
   Object clone_obj = obj;
   if (obj instanceof String) {
     String string = (String) obj;
     clone_obj = (Object) new String(string);
   } else if (obj instanceof Integer) {
     clone_obj = new Integer(((Integer) obj).intValue());
   } else if (obj instanceof Float) {
     clone_obj = new Float(((Float) obj).floatValue());
   } else if (obj instanceof Double) {
     clone_obj = new Double(((Double) obj).doubleValue());
   } else if (obj instanceof Long) {
     clone_obj = new Long(((Long) obj).longValue());
   } else {
     // If a clone method exists for the object, then
     // invoke it
     try {
       Class cl = obj.getClass();
       Method meth = cl.getMethod("clone", null);
       clone_obj = meth.invoke(obj, null);
     } catch (SecurityException ex) {
       clone_obj = obj;
     } catch (IllegalArgumentException ex) {
       InternalErrorHandler.handleException(ex);
     } catch (IllegalAccessException ex) {
       clone_obj = obj;
     } catch (InvocationTargetException ex) {
       clone_obj = obj;
     } catch (NoSuchMethodException ex) {
       clone_obj = obj;
     }
   }
   return clone_obj;
 }
Example #13
0
 /**
  * Gets the datatype of the object.
  *
  * @param obj the object
  * @return the type
  */
 public static String getDataType(Object obj) {
   if (obj == null) {
     return null;
   }
   if (obj instanceof String) {
     return "string"; //$NON-NLS-1$
   } else if (obj instanceof Collection) {
     return "collection"; //$NON-NLS-1$
   } else if (obj.getClass().isArray()) {
     // make sure ultimate component class is acceptable
     Class componentType = obj.getClass().getComponentType();
     while (componentType.isArray()) {
       componentType = componentType.getComponentType();
     }
     String type = componentType.getName();
     if (type.indexOf(".") == -1
         && "intdoubleboolean".indexOf(type) == -1) { // $NON-NLS-1$ //$NON-NLS-2$
       return null;
     }
     return "array"; //$NON-NLS-1$
   } else if (obj instanceof Double) {
     return "double"; //$NON-NLS-1$
   } else if (obj instanceof Integer) {
     return "int"; //$NON-NLS-1$
   } else {
     return "object"; //$NON-NLS-1$
   }
 }
 private static <T> T getParamXPath(
     final Class<T> pClass, final String pXpath, final CompactFragment pBody) throws XmlException {
   // TODO Avoid JAXB where possible, use XMLDeserializer instead
   final boolean string = CharSequence.class.isAssignableFrom(pClass);
   Node match;
   DocumentFragment fragment =
       DomUtil.childrenToDocumentFragment(XMLFragmentStreamReader.from(pBody));
   for (Node n = fragment.getFirstChild(); n != null; n = n.getNextSibling()) {
     match = xpathMatch(n, pXpath);
     if (match != null) {
       if (!string) {
         XmlDeserializer deserializer = pClass.getAnnotation(XmlDeserializer.class);
         if (deserializer != null) {
           try {
             XmlDeserializerFactory<?> factory = deserializer.value().newInstance();
             factory.deserialize(XmlStreaming.newReader(new DOMSource(n)));
           } catch (InstantiationException | IllegalAccessException e) {
             throw new RuntimeException(e);
           }
         } else {
           return JAXB.unmarshal(new DOMSource(match), pClass);
         }
       } else {
         return pClass.cast(nodeToString(match));
       }
     }
   }
   return null;
 }
Example #15
0
 /**
  * Returns all public methods declared by the specified class. This excludes inherited methods.
  *
  * @param clazz the class from which to pull public declared methods
  * @return the public methods declared in the specified class
  * @see Class#getDeclaredMethods()
  */
 static Method[] getMethodList(Class clazz) {
   Method[] methods = null;
   try {
     // getDeclaredMethods may be rejected by the security manager
     // but getMethods is more expensive
     if (!sawSecurityException) {
       methods = clazz.getDeclaredMethods();
     }
   } catch (SecurityException e) {
     // If we get an exception once, give up on getDeclaredMethods
     sawSecurityException = true;
   }
   if (methods == null) {
     methods = clazz.getMethods();
   }
   int count = 0;
   for (int i = 0; i < methods.length; i++) {
     if (sawSecurityException
         ? methods[i].getDeclaringClass() != clazz
         : !Modifier.isPublic(methods[i].getModifiers())) {
       methods[i] = null;
     } else {
       count++;
     }
   }
   Method[] result = new Method[count];
   int j = 0;
   for (int i = 0; i < methods.length; i++) {
     if (methods[i] != null) {
       result[j++] = methods[i];
     }
   }
   return result;
 }
 /**
  * オブジェクトのフィールドにデータを設定する<br>
  * Integer、Float、Float[]、Stringにしか対応していない
  *
  * @param obj 設定対象オブジェクト
  * @param fl 設定対象フィールド
  * @param ty 設定対象フィールドの型
  * @param data 設定データ
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 protected void dataSetter(Object obj, Field fl, Class ty, String data)
     throws IllegalArgumentException, IllegalAccessException {
   // Integer型のデータを設定
   if (ty.toString().equals("class java.lang.Integer")) {
     fl.set(obj, Integer.parseInt(data));
   }
   // Float型のデータを設定
   if (ty.toString().equals("class java.lang.Float")) {
     fl.set(obj, Float.parseFloat(data));
   }
   // String型のデータを設定(""の内側)
   if (ty.toString().equals("class java.lang.String")) {
     fl.set(obj, getDoubleQuoatString(data));
   }
   // Float[]型のデータを設定
   if (ty.toString().equals("class [Ljava.lang.Float;")) {
     String[] s;
     s = data.split(" ");
     Float[] f = new Float[s.length];
     for (int i = 0; i < s.length; i++) {
       f[i] = Float.parseFloat(s[i]);
     }
     fl.set(obj, f);
   }
 }
  /**
   * Returns the clone of <code>o_</code>. It calls <code>o_.clone()</code>, if possible, and either
   * raises an exception or returns null if fails.
   *
   * @param raiseException_ set to true if one wishes to get exception instead of receiving null
   *     when this method fails to call <code>o_.clone()</code>.
   */
  public static Object clone(Object o_, boolean raiseException_) {
    if (o_ == null) return null;
    if (o_ instanceof String) return o_;

    try {
      if (o_ instanceof drcl.ObjectCloneable) return ((drcl.ObjectCloneable) o_).clone();
      if (o_.getClass().isArray()) {
        int length_ = Array.getLength(o_);
        Class componentType_ = o_.getClass().getComponentType();
        Object that_ = Array.newInstance(componentType_, length_);
        if (componentType_.isPrimitive()) System.arraycopy(o_, 0, that_, 0, length_);
        else {
          for (int i = 0; i < length_; i++)
            Array.set(that_, i, clone(Array.get(o_, i), raiseException_));
        }
        return that_;
      }
      Method m_ = o_.getClass().getMethod("clone", null);
      return m_.invoke(o_, null);
    } catch (Exception e_) {
      if (raiseException_) {
        Thread t_ = Thread.currentThread();
        t_.getThreadGroup().uncaughtException(t_, e_);
      }
      return null;
    }
  }
Example #18
0
  private static void testPotato(
      Class<? extends Collection> implClazz, Class<? extends List> argClazz) throws Throwable {
    try {
      System.out.printf("implClazz=%s, argClazz=%s\n", implClazz.getName(), argClazz.getName());
      final int iterations = 100000;
      final List<Integer> list = (List<Integer>) argClazz.newInstance();
      final Integer one = Integer.valueOf(1);
      final List<Integer> oneElementList = Collections.singletonList(one);
      final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class);
      final Thread t =
          new CheckedThread() {
            public void realRun() {
              for (int i = 0; i < iterations; i++) {
                list.add(one);
                list.remove(one);
              }
            }
          };
      t.setDaemon(true);
      t.start();

      for (int i = 0; i < iterations; i++) {
        Collection<?> coll = constr.newInstance(list);
        Object[] elts = coll.toArray();
        check(elts.length == 0 || (elts.length == 1 && elts[0] == one));
      }
    } catch (Throwable t) {
      unexpected(t);
    }
  }
Example #19
0
 private String getExifData(ImagePlus imp) {
   FileInfo fi = imp.getOriginalFileInfo();
   if (fi == null) return null;
   String directory = fi.directory;
   String name = fi.fileName;
   if (directory == null) return null;
   if ((name == null || name.equals("")) && imp.getStack().isVirtual())
     name = imp.getStack().getSliceLabel(imp.getCurrentSlice());
   if (name == null || !(name.endsWith("jpg") || name.endsWith("JPG"))) return null;
   String path = directory + name;
   String metadata = null;
   try {
     Class c = IJ.getClassLoader().loadClass("Exif_Reader");
     if (c == null) return null;
     String methodName = "getMetadata";
     Class[] argClasses = new Class[1];
     argClasses[0] = methodName.getClass();
     Method m = c.getMethod("getMetadata", argClasses);
     Object[] args = new Object[1];
     args[0] = path;
     Object obj = m.invoke(null, args);
     metadata = obj != null ? obj.toString() : null;
   } catch (Exception e) {
     return null;
   }
   if (metadata != null && !metadata.startsWith("Error:")) return metadata;
   else return null;
 }
Example #20
0
  public JavaType findType(String name) {
    if (_bindings == null) {
      _resolve();
    }
    JavaType t = _bindings.get(name);
    if (t != null) {
      return t;
    }
    if (_placeholders != null && _placeholders.contains(name)) {
      return UNBOUND;
    }
    // New with 1.7: check parent context
    if (_parentBindings != null) {
      return _parentBindings.findType(name);
    }
    // nothing found, so...
    // Should we throw an exception or just return null?

    /* [JACKSON-499] 18-Feb-2011, tatu: There are some tricky type bindings within
     *   java.util, such as HashMap$KeySet; so let's punt the problem
     *   (honestly not sure what to do -- they are unbound for good, I think)
     */
    if (_contextClass != null) {
      Class<?> enclosing = _contextClass.getEnclosingClass();
      if (enclosing != null) {
        // [JACKSON-572]: Actually, let's skip this for all non-static inner classes
        //   (which will also cover 'java.util' type cases...
        if (!Modifier.isStatic(_contextClass.getModifiers())) {
          return UNBOUND;
        }

        // ... so this piece of code should not be needed any more
        /*
        Package pkg = enclosing.getPackage();
        if (pkg != null) {
            // as per [JACKSON-533], also include "java.util.concurrent":
            if (pkg.getName().startsWith("java.util")) {
                return UNBOUND;
            }
        }
        */
      }
    }

    String className;
    if (_contextClass != null) {
      className = _contextClass.getName();
    } else if (_contextType != null) {
      className = _contextType.toString();
    } else {
      className = "UNKNOWN";
    }
    throw new IllegalArgumentException(
        "Type variable '"
            + name
            + "' can not be resolved (with context of class "
            + className
            + ")");
    // t = UNBOUND;
  }
  /** Determine whether the current user has Windows administrator privileges. */
  public static boolean isWinAdmin() {
    if (!isWinPlatform()) return false;
    //    for (String group : new com.sun.security.auth.module.NTSystem().getGroupIDs()) {
    //      if (group.equals("S-1-5-32-544")) return true; // "S-1-5-32-544" is a well-known
    // security identifier in Windows. If the current user has it then he/she/it is an
    // administrator.
    //    }
    //    return false;

    try {
      Class<?> ntsys = Class.forName("com.sun.security.auth.module.NTSystem");
      if (ntsys != null) {
        Object groupObj =
            SystemUtils.invoke(
                ntsys.newInstance(), ntsys.getDeclaredMethod("getGroupIDs"), (Object[]) null);
        if (groupObj instanceof String[]) {
          for (String group : (String[]) groupObj) {
            if (group.equals("S-1-5-32-544"))
              return true; // "S-1-5-32-544" is a well-known security identifier in Windows. If the
                           // current user has it then he/she/it is an administrator.
          }
        }
      }
    } catch (ReflectiveOperationException e) {
      System.err.println(e);
    }
    return false;
  }
Example #22
0
  /**
   * Initialization method that will recursively collect Jackson annotations for this class and all
   * super classes and interfaces.
   *
   * <p>Starting with 1.2, it will also apply mix-in annotations, as per [JACKSON-76]
   */
  protected void resolveClassAnnotations() {
    _classAnnotations = new AnnotationMap();
    // add mix-in annotations first (overrides)
    if (_primaryMixIn != null) {
      _addClassMixIns(_classAnnotations, _class, _primaryMixIn);
    }
    // first, annotations from the class itself:
    for (Annotation a : _class.getDeclaredAnnotations()) {
      if (_annotationIntrospector.isHandled(a)) {
        _classAnnotations.addIfNotPresent(a);
      }
    }

    // and then from super types
    for (Class<?> cls : _superTypes) {
      // and mix mix-in annotations in-between
      _addClassMixIns(_classAnnotations, cls);
      for (Annotation a : cls.getDeclaredAnnotations()) {
        if (_annotationIntrospector.isHandled(a)) {
          _classAnnotations.addIfNotPresent(a);
        }
      }
    }

    /* and finally... any annotations there might be for plain
     * old Object.class: separate because for all other purposes
     * it is just ignored (not included in super types)
     */
    /* 12-Jul-2009, tatu: Should this be done for interfaces too?
     *   For now, yes, seems useful for some cases, and not harmful
     *   for any?
     */
    _addClassMixIns(_classAnnotations, Object.class);
  }
 /**
  * This method returns the maximum representation size of an object. <code>sizeSoFar</code> is the
  * object's size measured so far. <code>f</code> is the field being probed.
  *
  * <p>The returned offset will be the maximum of whatever was measured so far and <code>f</code>
  * field's offset and representation size (unaligned).
  */
 private static long adjustForField(long sizeSoFar, final Field f) {
   final Class<?> type = f.getType();
   final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF;
   if (objectFieldOffsetMethod != null) {
     try {
       final long offsetPlusSize =
           ((Number) objectFieldOffsetMethod.invoke(theUnsafe, f)).longValue() + fsize;
       return Math.max(sizeSoFar, offsetPlusSize);
     } catch (IllegalAccessException ex) {
       throw new RuntimeException("Access problem with sun.misc.Unsafe", ex);
     } catch (InvocationTargetException ite) {
       final Throwable cause = ite.getCause();
       if (cause instanceof RuntimeException) throw (RuntimeException) cause;
       if (cause instanceof Error) throw (Error) cause;
       // this should never happen (Unsafe does not declare
       // checked Exceptions for this method), but who knows?
       throw new RuntimeException(
           "Call to Unsafe's objectFieldOffset() throwed "
               + "checked Exception when accessing field "
               + f.getDeclaringClass().getName()
               + "#"
               + f.getName(),
           cause);
     }
   } else {
     // TODO: No alignments based on field type/ subclass fields alignments?
     return sizeSoFar + fsize;
   }
 }
Example #24
0
 protected void _addClassMixIns(AnnotationMap annotations, Class<?> toMask, Class<?> mixin) {
   if (mixin == null) {
     return;
   }
   // Ok, first: annotations from mix-in class itself:
   for (Annotation a : mixin.getDeclaredAnnotations()) {
     if (_annotationIntrospector.isHandled(a)) {
       annotations.addIfNotPresent(a);
     }
   }
   /* And then from its supertypes, if any. But note that we will
    *  only consider super-types up until reaching the masked
    * class (if found); this because often mix-in class
    * is a sub-class (for convenience reasons). And if so, we
    * absolutely must NOT include super types of masked class,
    * as that would inverse precedence of annotations.
    */
   for (Class<?> parent : ClassUtil.findSuperTypes(mixin, toMask)) {
     for (Annotation a : parent.getDeclaredAnnotations()) {
       if (_annotationIntrospector.isHandled(a)) {
         annotations.addIfNotPresent(a);
       }
     }
   }
 }
  private BrowserLauncher createBrowserLauncher(
      Class c, String browserStartCommand, String sessionId, SeleneseQueue queue) {
    try {
      BrowserLauncher browserLauncher;
      if (null == browserStartCommand) {
        Constructor ctor = c.getConstructor(new Class[] {int.class, String.class});
        Object[] args = new Object[] {new Integer(server.getPort()), sessionId};
        browserLauncher = (BrowserLauncher) ctor.newInstance(args);
      } else {
        Constructor ctor = c.getConstructor(new Class[] {int.class, String.class, String.class});
        Object[] args =
            new Object[] {
              new Integer(SeleniumServer.getPortDriversShouldContact()),
              sessionId,
              browserStartCommand
            };
        browserLauncher = (BrowserLauncher) ctor.newInstance(args);
      }

      if (browserLauncher instanceof SeleneseQueueAware) {
        ((SeleneseQueueAware) browserLauncher).setSeleneseQueue(queue);
      }

      return browserLauncher;
    } catch (InvocationTargetException e) {
      throw new RuntimeException(
          "failed to contruct launcher for "
              + browserStartCommand
              + "for"
              + e.getTargetException());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Example #26
0
 protected void _addFields(Map<String, AnnotatedField> fields, Class<?> c) {
   /* First, a quick test: we only care for regular classes (not
    * interfaces, primitive types etc), except for Object.class.
    * A simple check to rule out other cases is to see if there
    * is a super class or not.
    */
   Class<?> parent = c.getSuperclass();
   if (parent != null) {
     // Let's add super-class' fields first, then ours.
     /* 21-Feb-2010, tatu: Need to handle masking: as per [JACKSON-226]
      *    we otherwise get into trouble...
      */
     _addFields(fields, parent);
     for (Field f : c.getDeclaredFields()) {
       // static fields not included, nor transient
       if (!_isIncludableField(f)) {
         continue;
       }
       /* Ok now: we can (and need) not filter out ignorable fields
        * at this point; partly because mix-ins haven't been
        * added, and partly because logic can be done when
        * determining get/settability of the field.
        */
       fields.put(f.getName(), _constructField(f));
     }
     // And then... any mix-in overrides?
     if (_mixInResolver != null) {
       Class<?> mixin = _mixInResolver.findMixInClassFor(c);
       if (mixin != null) {
         _addFieldMixIns(mixin, fields);
       }
     }
   }
 }
  private void setDNAndEntryFields(final T o, final Entry e) throws LDAPPersistException {
    if (dnField != null) {
      try {
        dnField.set(o, e.getDN());
      } catch (Exception ex) {
        debugException(ex);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_SETTING_DN.get(
                type.getName(), e.getDN(), dnField.getName(), getExceptionMessage(ex)),
            ex);
      }
    }

    if (entryField != null) {
      try {
        entryField.set(o, new ReadOnlyEntry(e));
      } catch (Exception ex) {
        debugException(ex);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_SETTING_ENTRY.get(
                type.getName(), entryField.getName(), getExceptionMessage(ex)),
            ex);
      }
    }
  }
 private void readActualTypeParametersOnDeclaringClass() {
   registerTypeParametersOn(clazz.getTypeParameters());
   registerTypeVariablesOn(clazz.getGenericSuperclass());
   for (Type genericInterface : clazz.getGenericInterfaces()) {
     registerTypeVariablesOn(genericInterface);
   }
 }
 private static Class<?> getClassObject(Object o) throws ClassNotFoundException {
   if (o == null) {
     System.out.println("null");
   }
   // 基本データ型の場合
   if (o instanceof Boolean) {
     return boolean.class;
   } else if (o instanceof Integer) {
     return int.class;
   } else if (o instanceof Double) {
     return double.class;
   } else if (o instanceof Long) {
     return long.class;
   } else if (o instanceof Short) {
     return short.class;
   } else if (o instanceof Character) {
     return char.class;
   } else if (o instanceof Byte) {
     return byte.class;
   } else if (o instanceof Float) {
     return float.class;
   }
   // 基本データ型以外の場合:forName()でクラスオブジェクトを取得
   else {
     System.out.println(Class.forName(strip(o.getClass().toString(), "class ")));
     return Class.forName(strip(o.getClass().toString(), "class "));
   }
 }
 Document parseDocument(String filename) throws Exception {
   FileReader reader = new FileReader(filename);
   String firstLine = new BufferedReader(reader).readLine();
   reader.close();
   Document document = null;
   if (firstLine.startsWith("<?xml")) {
     System.err.println("XML detected; using default XML parser.");
   } else {
     try {
       Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser");
       Object parser = nekoParserClass.newInstance();
       Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class});
       Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]);
       parse.invoke(parser, filename);
       document = (Document) getDocument.invoke(parser);
     } catch (Exception e) {
       System.err.println("NekoHTML HTML parser not found; HTML4 support disabled.");
     }
   }
   if (document == null) {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic
       factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     } catch (ParserConfigurationException e) {
       System.err.println("Warning: Could not disable external DTD loading");
     }
     DocumentBuilder builder = factory.newDocumentBuilder();
     document = builder.parse(filename);
   }
   return document;
 }