/**
   * Returns an object that implements the given interface to allow access to non-standard methods,
   * or standard methods not exposed by the proxy. The result may be either the object found to
   * implement the interface or a proxy for that object. If the receiver implements the interface
   * then that is the object. If the receiver is a wrapper and the wrapped object implements the
   * interface then that is the object. Otherwise the object is the result of calling <code>unwrap
   * </code> recursively on the wrapped object. If the receiver is not a wrapper and does not
   * implement the interface, then an <code>SQLException</code> is thrown.
   *
   * @param iface A Class defining an interface that the result must implement.
   * @return an object that implements the interface. May be a proxy for the actual implementing
   *     object.
   * @throws java.sql.SQLException If no object found that implements the interface
   * @since 1.6
   */
  public synchronized <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException {
    try {
      if ("java.sql.Statement".equals(iface.getName())
          || "java.sql.PreparedStatement".equals(iface.getName())
          || "java.sql.Wrapper.class".equals(iface.getName())) {
        return iface.cast(this);
      }

      if (unwrappedInterfaces == null) {
        unwrappedInterfaces = new HashMap();
      }

      Object cachedUnwrapped = unwrappedInterfaces.get(iface);

      if (cachedUnwrapped == null) {
        if (cachedUnwrapped == null) {
          cachedUnwrapped =
              Proxy.newProxyInstance(
                  this.wrappedStmt.getClass().getClassLoader(),
                  new Class[] {iface},
                  new ConnectionErrorFiringInvocationHandler(this.wrappedStmt));
          unwrappedInterfaces.put(iface, cachedUnwrapped);
        }
        unwrappedInterfaces.put(iface, cachedUnwrapped);
      }

      return iface.cast(cachedUnwrapped);
    } catch (ClassCastException cce) {
      throw SQLError.createSQLException(
          "Unable to unwrap to " + iface.toString(),
          SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
          this.exceptionInterceptor);
    }
  }
  /*
   * Create a new ObjectStreamClass_1_3_1 from a loaded class.
   * Don't call this directly, call lookup instead.
   */
  private ObjectStreamClass_1_3_1(
      java.lang.Class cl, ObjectStreamClass_1_3_1 superdesc, boolean serial, boolean extern) {
    ofClass = cl; /* created from this class */

    if (Proxy.isProxyClass(cl)) {
      forProxyClass = true;
    }

    name = cl.getName();
    superclass = superdesc;
    serializable = serial;
    if (!forProxyClass) {
      // proxy classes are never externalizable
      externalizable = extern;
    }

    /*
     * Enter this class in the table of known descriptors.
     * Otherwise, when the fields are read it may recurse
     * trying to find the descriptor for itself.
     */
    insertDescriptorFor(this);

    /*
     * The remainder of initialization occurs in init(), which is called
     * after the lock on the global class descriptor table has been
     * released.
     */
  }
示例#3
0
 private static boolean lookForInterface(
     java.lang.Class<?> klass, String className, Set<java.lang.Class<?>> alreadyVisited) {
   if (klass.getName().equals(className)) return true;
   // did we already visit this type?
   if (!alreadyVisited.add(klass)) return false;
   // first see if it satisfies it directly
   SatisfiedTypes satisfiesAnnotation = klass.getAnnotation(SatisfiedTypes.class);
   if (satisfiesAnnotation != null) {
     for (String satisfiedType : satisfiesAnnotation.value()) {
       satisfiedType = declClassName(satisfiedType);
       int i = satisfiedType.indexOf('<');
       if (i > 0) {
         satisfiedType = satisfiedType.substring(0, i);
       }
       try {
         if (lookForInterface(
             java.lang.Class.forName(satisfiedType, true, klass.getClassLoader()),
             className,
             alreadyVisited)) {
           return true;
         }
       } catch (ClassNotFoundException e) {
         throw new RuntimeException(e);
       }
     }
   }
   // now look at this class's interfaces
   for (java.lang.Class<?> intrface : klass.getInterfaces()) {
     if (lookForInterface(intrface, className, alreadyVisited)) return true;
   }
   // no luck
   return false;
 }
 @SuppressWarnings("unchecked")
 private boolean hasValidConstructor(java.lang.Class<?> aClass) {
   // The cast below is not necessary with the Java 5 compiler, but necessary with the Java 6
   // compiler,
   // where the return type of Class.getDeclaredConstructors() was changed
   // from Constructor<T>[] to Constructor<?>[]
   Constructor<? extends TestCase>[] constructors =
       (Constructor<? extends TestCase>[]) aClass.getConstructors();
   for (Constructor<? extends TestCase> constructor : constructors) {
     if (Modifier.isPublic(constructor.getModifiers())) {
       java.lang.Class<?>[] parameterTypes = constructor.getParameterTypes();
       if (parameterTypes.length == 0
           || (parameterTypes.length == 1 && parameterTypes[0] == String.class)) {
         return true;
       }
     }
   }
   Log.i(
       LOG_TAG,
       String.format(
           "TestCase class %s is missing a public constructor with no parameters "
               + "or a single String parameter - skipping",
           aClass.getName()));
   return false;
 }
示例#5
0
 private static boolean classExtendsClass(java.lang.Class<?> klass, String className) {
   if (klass == null) return false;
   if (klass.getName().equals(className)) return true;
   if ((className.equals("ceylon.language.Basic"))
       && klass != java.lang.Object.class
       && !isSubclassOfString(klass)
       // && klass!=java.lang.String.class
       && !klass.isAnnotationPresent(Class.class)
       && (!klass.isInterface() || !klass.isAnnotationPresent(Ceylon.class))) {
     // TODO: this is broken for a Java class that
     //      extends a Ceylon class
     return true;
   }
   Class classAnnotation = klass.getAnnotation(Class.class);
   if (classAnnotation != null) {
     String superclassName = declClassName(classAnnotation.extendsType());
     int i = superclassName.indexOf('<');
     if (i > 0) {
       superclassName = superclassName.substring(0, i);
     }
     if (superclassName.isEmpty()) {
       return false;
     }
     try {
       return classExtendsClass(
           java.lang.Class.forName(superclassName, true, klass.getClassLoader()), className);
     } catch (ClassNotFoundException e) {
       throw new RuntimeException(e);
     }
   }
   return classExtendsClass(klass.getSuperclass(), className);
 }
示例#6
0
 /**
  * Casts this {@code Class} to represent a subclass of the specified class. If successful, this
  * {@code Class} is returned; otherwise a {@code ClassCastException} is thrown.
  *
  * @param clazz the required type.
  * @return this {@code Class} cast as a subclass of the given type.
  * @throws ClassCastException if this {@code Class} cannot be cast to the specified type.
  */
 @SuppressWarnings("unchecked")
 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
   if (clazz.isAssignableFrom(this)) {
     return (Class<? extends U>) this;
   }
   String actualClassName = this.getName();
   String desiredClassName = clazz.getName();
   throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName);
 }
示例#7
0
  public static int removeTimer(Class handlerClass) {
    String hashKey = handlerClass.getName();
    String handlerNum = (String) timerHashTable.get(hashKey);

    timerHashTable.remove(hashKey);
    timerHashTable.remove(handlerNum);

    return IPC_removeTimer(Integer.parseInt(handlerNum));
  }
示例#8
0
 public static int unsubscribeConnect(Class connectHandlerClass) {
   if (!removeFromHandlerList(connectHandlers, connectHandlerClass)) {
     System.out.println("No connection handler found of class " + connectHandlerClass.getName());
     return IPC_Error;
   } else if (connectHandlers.size() == 0) {
     return IPC_unsubscribeConnect();
   } else {
     return IPC_OK;
   }
 }
示例#9
0
  public static int unsubscribe(String msgName, Class msgHandlerClass) {
    /* Do it this way because multiple handlers can be subscribed for the
    same message */
    String handlerName = msgName + msgHandlerClass.getName();
    String hashKey = (String) msgHashTable.get(handlerName);

    msgHashTable.remove(handlerName);
    msgHashTable.remove(hashKey);

    return IPC_unsubscribe(msgName, handlerName);
  }
示例#10
0
  @SuppressWarnings("unchecked")
  private Constructor<T> findConstructor(Constructor<?>[] candidates, Class<?>... parameterTypes)
      throws NoSuchMethodException, SecurityException {

    for (Constructor<?> c : candidates) {
      if (R.matchParameterTypes(c, parameterTypes)) {
        return (Constructor<T>) c;
      }
    }
    throw new NoSuchMethodException(
        clazz.getName() + '(' + parameterTypesToString(parameterTypes) + ')');
  }
示例#11
0
 public GElement newGElement(java.lang.Class<? extends GElement> elementClass)
     throws NoProductException {
   try {
     Constructor<? extends GElement> constructor = elementClass.getConstructor(String.class);
     String id = IDgenerator.getInstance().generate(elementClass);
     GElement result = constructor.newInstance(id);
     result.initDefault();
     return result;
   } catch (Exception ex) {
     ex.printStackTrace();
     throw new NoProductException(elementClass.getName());
   }
 }
 public ProducedType toProducedType(
     ProducedType qualifyingType, RuntimeModuleManager moduleManager) {
   // FIXME: is this really enough?
   String typeName = klass.getName();
   Module module = moduleManager.findModuleForClass(klass);
   TypeDeclaration decl =
       (TypeDeclaration)
           moduleManager.getModelLoader().getDeclaration(module, typeName, DeclarationType.TYPE);
   List<ProducedType> typeArgs = new ArrayList<ProducedType>(typeArguments.length);
   for (TypeDescriptor typeArg : typeArguments) {
     typeArgs.add(typeArg.toProducedType(moduleManager));
   }
   return decl.getProducedType(qualifyingType, typeArgs);
 }
示例#13
0
 public java.lang.Class getClass(java.lang.String name, java.lang.Class defaultValue) {
   java.lang.String className = null;
   if (defaultValue == null) {
     className = this.getString(name, name);
   } else {
     className = this.getString(name, defaultValue.getName());
   }
   java.lang.Class retClass = null;
   try {
     retClass = Class.forName(className);
   } catch (java.lang.ClassNotFoundException e) {
     retClass = defaultValue;
   }
   return retClass;
 }
示例#14
0
 /**
  * Get the package for the specified class. The class's class loader is used to find the package
  * instance corresponding to the specified class. If the class loader is the bootstrap class
  * loader, which may be represented by {@code null} in some implementations, then the set of
  * packages loaded by the bootstrap class loader is searched to find the package.
  *
  * <p>Packages have attributes for versions and specifications only if the class loader created
  * the package instance with the appropriate attributes. Typically those attributes are defined in
  * the manifests that accompany the classes.
  *
  * @param class the class to get the package of.
  * @return the package of the class. It may be null if no package information is available from
  *     the archive or codebase.
  */
 static Package getPackage(Class<?> c) {
   String name = c.getName();
   int i = name.lastIndexOf('.');
   if (i != -1) {
     name = name.substring(0, i);
     ClassLoader cl = c.getClassLoader();
     if (cl != null) {
       return cl.getPackage(name);
     } else {
       return getSystemPackage(name);
     }
   } else {
     return null;
   }
 }
示例#15
0
 private static void appendTypeName(StringBuilder out, Class<?> c) {
   if (c == null) {
     out.append("null");
   } else {
     int dimensions = 0;
     while (c.isArray()) {
       c = c.getComponentType();
       dimensions++;
     }
     out.append(c.getName());
     for (int d = 0; d < dimensions; d++) {
       out.append("[]");
     }
   }
 }
示例#16
0
 public static int unsubscribeHandlerChange(String msgName, Class handlerChangeHandlerClass) {
   List handlerList = (List) handlerChangeHashTable.get(msgName);
   if (handlerList == null) {
     return IPC_Error;
   } else if (!removeFromHandlerList(handlerList, handlerChangeHandlerClass)) {
     System.out.println(
         "No change handler found for message "
             + msgName
             + " of class "
             + handlerChangeHandlerClass.getName());
     return IPC_Error;
   } else if (handlerList.size() == 0) {
     return IPC_unsubscribeHandlerChange(msgName);
   } else {
     return IPC_OK;
   }
 }
 private static <T> T __check_arg__(java.lang.Class<T> expectedClass, Object argument) {
   T result = null;
   if (java.lang.Integer.class.equals(expectedClass) && argument instanceof Double) {
     result = (T) new java.lang.Integer(((Double) argument).intValue());
   } else if (java.lang.Float.class.equals(expectedClass) && argument instanceof Double) {
     result = (T) new java.lang.Float(((Double) argument).floatValue());
   } else {
     try {
       result = expectedClass.cast(argument);
     } catch (Throwable ex) {
       throw new IllegalArgumentException(
           String.format(
               "Bad parameter type in call to %s. Found '%s' when expected '%s'.",
               "nbActions", argument.getClass().getName(), expectedClass.getName()));
     }
   }
   return result;
 }
示例#18
0
  public <S> S getBusinessObject(Object ejbRef, java.lang.Class<S> businessInterface) {

    EJBLocalObjectImpl localObjectImpl = getEJBLocalObject(ejbRef);

    if (localObjectImpl == null) {
      throw new IllegalStateException("Invalid ejb ref");
    }

    Container container = localObjectImpl.getContainer();
    EjbDescriptor ejbDesc = container.getEjbDescriptor();

    S businessObject = null;

    if (businessInterface != null) {
      String intfName = businessInterface.getName();
      if (ejbDesc.getLocalBusinessClassNames().contains(intfName)) {

        // Get proxy corresponding to this business interface.
        businessObject = (S) localObjectImpl.getClientObject(intfName);

      } else if (ejbDesc.isLocalBean()) {
        // If this is a no-interface view session bean, the bean
        // can be accessed through interfaces in its superclass as well
        boolean isValidBusinessInterface =
            ejbDesc.getNoInterfaceLocalBeanClasses().contains(intfName);
        if ((intfName.equals(ejbDesc.getEjbClassName())) || isValidBusinessInterface) {
          businessObject = (S) localObjectImpl.getClientObject(ejbDesc.getEjbClassName());
        }
      }
    }

    if (businessObject == null) {
      throw new IllegalStateException(
          "Unable to convert ejbRef for ejb "
              + ejbDesc.getName()
              + " to a business object of type "
              + businessInterface);
    }

    return businessObject;
  }
示例#19
0
  private Method findMethod(Method[] candidates, String name, Class<?>... parameterTypes)
      throws NoSuchMethodException {

    Method firstMatch = null;
    List<Method> allMatches = null;
    for (Method m : candidates) {
      if (name.equals(m.getName()) && R.matchParameterTypes(m, parameterTypes)) {
        if (firstMatch == null) {
          firstMatch = m;
        } else {
          if (allMatches == null) {
            allMatches = new ArrayList<Method>();
            allMatches.add(firstMatch);
          }
          allMatches.add(m);
        }
      }
    }
    if (firstMatch == null) {
      throw new NoSuchMethodException(
          clazz.getName() + "." + name + '(' + parameterTypesToString(parameterTypes) + ')');
    }
    if (allMatches == null) {
      return firstMatch;
    }
    // There are multiple methods with the same name and parameter types. The RI's docs says
    // pick the method with the most specific return type or pick an arbitrary if there are
    // no such methods. Dalvik just filters out synthetic methods and then picks an arbitrary
    // one (if the source language is Java there should only be one non-synthetic match).
    Method result = null;
    for (Method m : allMatches) {
      if (!m.isSynthetic()) {
        return m;
      }
      result = m;
    }
    return result;
  }
示例#20
0
 private static boolean isSubclassOfString(java.lang.Class<?> klass) {
   return klass.getName().equals("com.redhat.ceylon.compiler.java.language.EmptyString")
       || klass.getName().equals("com.redhat.ceylon.compiler.java.language.SequenceString");
 }
示例#21
0
 public Path(final java.lang.Class<?> classObject) {
   this.path = classObject.getName().replaceAll("\\$", ".");
 }
  private void createXMLOutputDoc(
      Document doc, List<GridElement> entities, Element current, Group group) {
    // list of elements that are not inserted yet (to increase performance)
    List<GridElement> toBeCheckedAgain = new ArrayList<GridElement>();
    List<Group> insert_groups = new ArrayList<Group>();
    for (GridElement e : entities) {
      // only insert element in right grouping element
      boolean insert_here = false;
      if ((group == null) && (e.getGroup() == null)) insert_here = true;
      else if (group != null) if (group.equals(e.getGroup())) insert_here = true;

      if (insert_here) {
        if (e instanceof Group) insert_groups.add((Group) e);
        else { // insert normal entity element
          java.lang.Class<? extends GridElement> c = e.getClass();
          String sElType = c.getName();
          int[] coor = e.getCoordinates();
          String sElPanelAttributes = e.getPanelAttributes();
          String sElAdditionalAttributes = e.getAdditionalAttributes();

          Element el = doc.createElement("element");
          current.appendChild(el);

          Element elType = doc.createElement("type");
          elType.appendChild(doc.createTextNode(sElType));
          el.appendChild(elType);

          Element elCoor = doc.createElement("coordinates");
          el.appendChild(elCoor);

          Element elX = doc.createElement("x");
          elX.appendChild(doc.createTextNode("" + coor[0]));
          elCoor.appendChild(elX);

          Element elY = doc.createElement("y");
          elY.appendChild(doc.createTextNode("" + coor[1]));
          elCoor.appendChild(elY);

          Element elW = doc.createElement("w");
          elW.appendChild(doc.createTextNode("" + coor[2]));
          elCoor.appendChild(elW);

          Element elH = doc.createElement("h");
          elH.appendChild(doc.createTextNode("" + coor[3]));
          elCoor.appendChild(elH);

          Element elPA = doc.createElement("panel_attributes");
          elPA.appendChild(doc.createTextNode(sElPanelAttributes));
          el.appendChild(elPA);

          Element elAA = doc.createElement("additional_attributes");
          elAA.appendChild(doc.createTextNode(sElAdditionalAttributes));
          el.appendChild(elAA);

          if (e instanceof CustomElement) {
            Element elCO = doc.createElement("custom_code");
            elCO.appendChild(doc.createTextNode(((CustomElement) e).getCode()));
            el.appendChild(elCO);
          }
        }
      } else toBeCheckedAgain.add(e);
    }

    for (Group g : insert_groups) {
      Element el = doc.createElement("group");
      current.appendChild(el);
      createXMLOutputDoc(doc, toBeCheckedAgain, el, g);
    }
  }