コード例 #1
0
 /**
  * Internal function to set the value on the target object, using the setter set up earlier on
  * this PropertyValuesHolder object. This function is called by ObjectAnimator to handle turning
  * the value calculated by ValueAnimator into a value set on the object according to the name of
  * the property.
  *
  * @param target The target object on which the value is set
  */
 @Override
 void setAnimatedValue(Object target) {
   // if (mFloatProperty != null) {
   //    mFloatProperty.setValue(target, mFloatAnimatedValue);
   //    return;
   // }
   // if (mProperty != null) {
   //    mProperty.set(target, mFloatAnimatedValue);
   //    return;
   // }
   // if (mJniSetter != 0) {
   //    nCallFloatMethod(target, mJniSetter, mFloatAnimatedValue);
   //    return;
   // }
   if (mSetter != null) {
     try {
       mTmpValueArray[0] = mFloatAnimatedValue;
       mSetter.invoke(target, mTmpValueArray);
     } catch (InvocationTargetException e) {
       Log.e("PropertyValuesHolder", e.toString());
     } catch (IllegalAccessException e) {
       Log.e("PropertyValuesHolder", e.toString());
     }
   }
 }
コード例 #2
0
 private int test02SendSmsReflect3(long subId) {
   try {
     String packageName = ActivityThread.currentPackageName();
     Log.i(TAG, "test02SendSmsReflect3 " + packageName + ", " + smsNumber());
     Method method =
         Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
     method.setAccessible(true);
     IBinder binder = (IBinder) method.invoke(null, new Object[] {"isms"});
     ISms simISms = (ISms) ISms.Stub.asInterface(binder);
     List<String> parts = new ArrayList<String>();
     parts.add("SMS message (Reflect 3)");
     List<PendingIntent> intents = new ArrayList<PendingIntent>();
     intents.add(null);
     simISms.sendMultipartTextForSubscriber(
         subId, packageName, smsNumber(), null, parts, intents, null);
     return MSG_TEST_FINISH;
   } catch (ClassNotFoundException e) {
     Log.e(TAG, e.toString());
   } catch (NoSuchMethodException e) {
     Log.e(TAG, e.toString());
   } catch (InvocationTargetException e) {
     Log.e(TAG, e.toString());
   } catch (IllegalAccessException e) {
     Log.e(TAG, e.toString());
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
   }
   return MSG_TEST_FAILED;
 }
コード例 #3
0
 Engine() {
   super();
   prefs = GalleryWallpaper.this.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
   prefs.registerOnSharedPreferenceChangeListener(this);
   this.onSharedPreferenceChanged(prefs, GalleryWallpaper.SHARED_PREFS_REPLACEIMAGE);
   this.onSharedPreferenceChanged(prefs, GalleryWallpaper.SHARED_PREFS_SYNC);
   onSharedPreferenceChanged(prefs, null);
   backgroundPaint.setFilterBitmap(false);
   backgroundPaint.setAntiAlias(true);
   backgroundPaint.setColor(Color.BLACK);
   textPaint.setAntiAlias(true);
   textPaint.setColor(Color.WHITE);
   textPaint.setShadowLayer(5f, 1f, 1f, Color.GRAY);
   textPaint.setSubpixelText(true);
   textPaint.setTextAlign(Paint.Align.LEFT);
   textPaint.setTextSize(18);
   textPaint.setTypeface(Typeface.MONOSPACE);
   this.setTouchEventsEnabled(true);
   if (Build.VERSION.SDK_INT >= 14) {
     try {
       // hinting = textPaint.HINTING_ON;
       int hinting = textPaint.getClass().getField("HINTING_ON").getInt(textPaint);
       // textPaint.setHinting(hinting);
       textPaint.getClass().getMethod("setHinting", int.class).invoke(textPaint, hinting);
     } catch (IllegalAccessException e) {
       System.err.println(e.toString());
     } catch (InvocationTargetException e) {
       System.err.println(e.toString());
     } catch (NoSuchMethodException e) {
       System.err.println(e.toString());
     } catch (NoSuchFieldException e) {
       System.err.println(e.toString());
     }
   }
 }
コード例 #4
0
 private int test02SendSmsReflect2(long subId) {
   try {
     String packageName = ActivityThread.currentPackageName();
     Log.i(TAG, "test02SendSmsReflect2 " + packageName + ", " + smsNumber());
     Method method =
         Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
     method.setAccessible(true);
     IBinder binder = (IBinder) method.invoke(null, new Object[] {"isms"});
     ISms simISms = (ISms) ISms.Stub.asInterface(binder);
     byte[] bytes = "SMS message (Reflect 2)".getBytes("GBK");
     simISms.sendDataForSubscriber(subId, packageName, smsNumber(), null, 0, bytes, null, null);
     return MSG_TEST_FINISH;
   } catch (ClassNotFoundException e) {
     Log.e(TAG, e.toString());
   } catch (NoSuchMethodException e) {
     Log.e(TAG, e.toString());
   } catch (InvocationTargetException e) {
     Log.e(TAG, e.toString());
   } catch (IllegalAccessException e) {
     Log.e(TAG, e.toString());
   } catch (UnsupportedEncodingException e) {
     Log.e(TAG, e.toString());
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
   }
   return MSG_TEST_FAILED;
 }
コード例 #5
0
ファイル: FuncTestSuite.java プロジェクト: hyohannes/security
 /** Create a test out of the specified class with the specified method name. */
 public static Test createTest(Class theClass, String name) {
   Constructor constructor;
   try {
     constructor = getTestConstructor(theClass);
   } catch (NoSuchMethodException e) {
     return warning(
         "Class "
             + theClass.getName()
             + " has no public constructor TestCase(String name) or TestCase()");
   }
   Object test;
   try {
     if (constructor.getParameterTypes().length == 0) {
       test = constructor.newInstance(new Object[0]);
       if (test instanceof TestCase) ((TestCase) test).setName(name);
     } else {
       test = constructor.newInstance(new Object[] {name});
     }
   } catch (InstantiationException e) {
     return (warning("Cannot instantiate test case: " + name + " (" + e.toString() + ")"));
   } catch (InvocationTargetException e) {
     return (warning("Exception in constructor: " + name + " (" + e.toString() + ")"));
   } catch (IllegalAccessException e) {
     return (warning("Cannot access test case: " + name + " (" + e.toString() + ")"));
   }
   return (Test) test;
 }
コード例 #6
0
  /**
   * <b>Note:</b> This method is used by the <em>feynman.framework.Controller</em>. Unless you are
   * not using those classes to build your simulation, you should not have to use this factory class
   * directly. If you do, then follow the instructions given below.
   *
   * <p>Use this method to create a <b>PhysicalSystem</b> of <b>PhysicalObjects</b>. The
   * <em>className</em> is the name of the class to be instantiated for the type of physical system
   * to be created. For example, if the client wants to to create a system included in the
   * framework, then the following call to this factory will work:
   *
   * <p>
   *
   * <pre>
   * Simulation simulation = Marshaller.unmarshall("MyProps.properties");
   * PhysicalSystemFactory sf = PhysicalSystemFactory.getInstance();
   * PhysicalSystem ps = sf.create(simulation);
   * </pre>
   */
  public static PhysicalSystem create(Simulation simulation) throws PhysicalSystemFactoryException {

    try {

      // Create the system specified for study in the simulation bean.
      Class psClazz = Class.forName(simulation.getPhysicalSystemClass());
      PhysicalSystem ps = (PhysicalSystem) psClazz.newInstance();

      // Get the number of physical objects for the simulation.
      int numberPhysicalObjects = simulation.getNumberPhysicalObjects();

      // Get the factory for the Physical Objects.
      Class ofClazz = Class.forName(simulation.getPhysicalObjectFactoryClass());
      Method method = ofClazz.getMethod("getInstance", new Class[] {});
      PhysicalObjectFactory of = (PhysicalObjectFactory) method.invoke(null, null);

      // Create the objects and add them to the system.
      PhysicalObject po;

      for (int i = 0; i < numberPhysicalObjects; i++) {

        try {

          po = (PhysicalObject) of.create(simulation);

          if (!(ps.add(po))) {
            throw new PhysicalSystemFactoryException(
                "Attempting to add "
                    + ofClazz.getName()
                    + " that is not a valid type for the "
                    + psClazz.getName());
          }

        } catch (PhysicalObjectFactoryException e) {
          throw new PhysicalSystemFactoryException(e.toString());
        }
      }

      return ps;

    } catch (ClassNotFoundException e) {
      throw new PhysicalSystemFactoryException(e.toString());
    } catch (InstantiationException e) {
      throw new PhysicalSystemFactoryException(e.toString());
    } catch (IllegalAccessException e) {
      throw new PhysicalSystemFactoryException(e.toString());
    } catch (NoSuchMethodException e) {
      throw new PhysicalSystemFactoryException(e.toString());
    } catch (InvocationTargetException e) {
      throw new PhysicalSystemFactoryException(e.toString());
    }
  }
コード例 #7
0
 /**
  * Internal function to set the value on the target object, using the setter set up earlier on
  * this PropertyValuesHolder object. This function is called by ObjectAnimator to handle turning
  * the value calculated by ValueAnimator into a value set on the object according to the name of
  * the property.
  *
  * @param target The target object on which the value is set
  */
 void setAnimatedValue(Object target) {
   // if (mProperty != null) {
   //    mProperty.set(target, getAnimatedValue());
   // }
   if (mSetter != null) {
     try {
       mTmpValueArray[0] = getAnimatedValue();
       mSetter.invoke(target, mTmpValueArray);
     } catch (InvocationTargetException e) {
       Log.e("PropertyValuesHolder", e.toString());
     } catch (IllegalAccessException e) {
       Log.e("PropertyValuesHolder", e.toString());
     }
   }
 }
コード例 #8
0
 /**
  * Utility function to set the value stored in a particular Keyframe. The value used is whatever
  * the value is for the property name specified in the keyframe on the target object.
  *
  * @param target The target object from which the current value should be extracted.
  * @param kf The keyframe which holds the property name and value.
  */
 private void setupValue(Object target, Keyframe kf) {
   // if (mProperty != null) {
   //    kf.setValue(mProperty.get(target));
   // }
   try {
     if (mGetter == null) {
       Class targetClass = target.getClass();
       setupGetter(targetClass);
     }
     kf.setValue(mGetter.invoke(target));
   } catch (InvocationTargetException e) {
     Log.e("PropertyValuesHolder", e.toString());
   } catch (IllegalAccessException e) {
     Log.e("PropertyValuesHolder", e.toString());
   }
 }
コード例 #9
0
  /**
   * Compare two JavaBeans by their shared property. If {@link #getProperty} is null then the actual
   * objects will be compared.
   *
   * @param o1 Object The first bean to get data from to compare against
   * @param o2 Object The second bean to get data from to compare
   * @return int negative or positive based on order
   */
  public int compare(Object o1, Object o2) {

    if (property == null) {
      // compare the actual objects
      return comparator.compare(o1, o2);
    }

    try {
      Object value1 = PropertyUtils.getProperty(o1, property);
      Object value2 = PropertyUtils.getProperty(o2, property);
      return comparator.compare(value1, value2);
    } catch (IllegalAccessException iae) {
      throw new RuntimeException("IllegalAccessException: " + iae.toString());
    } catch (InvocationTargetException ite) {
      throw new RuntimeException("InvocationTargetException: " + ite.toString());
    } catch (NoSuchMethodException nsme) {
      throw new RuntimeException("NoSuchMethodException: " + nsme.toString());
    }
  }
コード例 #10
0
ファイル: AgentShell.java プロジェクト: prakaashhk/cloudstack
 private void launchAgentFromClassInfo(String resourceClassNames) throws ConfigurationException {
   String[] names = resourceClassNames.split("\\|");
   for (String name : names) {
     Class<?> impl;
     try {
       impl = Class.forName(name);
       final Constructor<?> constructor = impl.getDeclaredConstructor();
       constructor.setAccessible(true);
       ServerResource resource = (ServerResource) constructor.newInstance();
       launchAgent(getNextAgentId(), resource);
     } catch (final ClassNotFoundException e) {
       throw new ConfigurationException(
           "Resource class not found: " + name + " due to: " + e.toString());
     } catch (final SecurityException e) {
       throw new ConfigurationException(
           "Security excetion when loading resource: " + name + " due to: " + e.toString());
     } catch (final NoSuchMethodException e) {
       throw new ConfigurationException(
           "Method not found excetion when loading resource: "
               + name
               + " due to: "
               + e.toString());
     } catch (final IllegalArgumentException e) {
       throw new ConfigurationException(
           "Illegal argument excetion when loading resource: "
               + name
               + " due to: "
               + e.toString());
     } catch (final InstantiationException e) {
       throw new ConfigurationException(
           "Instantiation excetion when loading resource: " + name + " due to: " + e.toString());
     } catch (final IllegalAccessException e) {
       throw new ConfigurationException(
           "Illegal access exception when loading resource: " + name + " due to: " + e.toString());
     } catch (final InvocationTargetException e) {
       throw new ConfigurationException(
           "Invocation target exception when loading resource: "
               + name
               + " due to: "
               + e.toString());
     }
   }
 }
コード例 #11
0
 private int test03DataConnectReflect() {
   Log.i(TAG, "test03DataConnectReflect");
   try {
     TelephonyManager mTelephonyManager =
         (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
     Class ownerClass = mTelephonyManager.getClass();
     Class[] argsClass = new Class[1];
     argsClass[0] = boolean.class;
     Method method = ownerClass.getMethod("setDataEnabled", argsClass);
     method.invoke(mTelephonyManager, true);
     return MSG_TEST_FINISH;
   } catch (NoSuchMethodException e) {
     Log.e(TAG, e.toString());
   } catch (IllegalAccessException e) {
     Log.e(TAG, e.toString());
   } catch (InvocationTargetException e) {
     Log.e(TAG, e.toString());
   }
   return MSG_TEST_FAILED;
 }
コード例 #12
0
  private <T> T init(T obj, String arg) {
    try {
      Object tmp = null;
      Method met;

      met = obj.getClass().getMethod(arg);
      tmp = met.invoke(obj);
      Hibernate.initialize(tmp);
      /*  if (obj instanceof HibernateProxy) {
          obj = (T) ((HibernateProxy) obj).getHibernateLazyInitializer()
                  .getImplementation();
      }*/
      return obj;
    } catch (NoSuchMethodException e) {
      System.out.println(e.toString());
    } catch (IllegalAccessException e) {
      System.out.println(e.toString());
    } catch (InvocationTargetException e) {
      System.out.println(e.toString());
    }
    return null;
  }
コード例 #13
0
ファイル: Formats.java プロジェクト: NYULibraries/citero
 /**
  * Dynamically creates a new instance of a Format class mapped to the enum type.
  *
  * @param input An Object that represents the argument value of a Format type (String).
  * @return Returns an instance of a Format class that is mapped to the enum.
  * @throws IllegalArgumentException If the object could not be constructed, there must have been
  *     an illegal argument.
  */
 public Format getInstance(final Object input) throws IllegalArgumentException {
   if (input.getClass() == clazz) return (Format) input;
   Class<?>[] argClass = new Class<?>[] {input.getClass()};
   Object[] args = new Object[] {input};
   Constructor<?> constructor;
   try {
     constructor = clazz.getConstructor(argClass);
     return (Format) constructor.newInstance(args);
   } catch (SecurityException e) {
     throw new IllegalArgumentException("Invalid access to formats.");
   } catch (NoSuchMethodException e) {
     throw new IllegalArgumentException("Formats constructor could not be found.");
   } catch (InstantiationException e) {
     throw new IllegalArgumentException("Cannot create this format.");
   } catch (IllegalAccessException e) {
     throw new IllegalArgumentException("Class could not be found.");
   } catch (InvocationTargetException e) {
     // e.printStackTrace();
     logger.debug(e.toString());
     throw new IllegalArgumentException("Check if data is consistent with format.");
   }
 }
コード例 #14
0
 private int test01PhoneCallEnd() {
   try {
     Log.i(TAG, "test01PhoneCallEnd");
     Method method =
         Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
     method.setAccessible(true);
     IBinder binder = (IBinder) method.invoke(null, new Object[] {TELEPHONY_SERVICE});
     ITelephony phone = (ITelephony) ITelephony.Stub.asInterface(binder);
     phone.endCall();
     return MSG_TEST_FINISH;
   } catch (ClassNotFoundException e) {
     Log.e(TAG, e.toString());
   } catch (NoSuchMethodException e) {
     Log.e(TAG, e.toString());
   } catch (InvocationTargetException e) {
     Log.e(TAG, e.toString());
   } catch (IllegalAccessException e) {
     Log.e(TAG, e.toString());
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
   }
   return MSG_TEST_FAILED;
 }
コード例 #15
0
 /**
  * Internal function (called from ObjectAnimator) to set up the setter and getter prior to running
  * the animation. If the setter has not been manually set for this object, it will be derived
  * automatically given the property name, target object, and types of values supplied. If no
  * getter has been set, it will be supplied iff any of the supplied values was null. If there is a
  * null value, then the getter (supplied or derived) will be called to set those null values to
  * the current value of the property on the target object.
  *
  * @param target The object on which the setter (and possibly getter) exist.
  */
 void setupSetterAndGetter(Object target) {
   // if (mProperty != null) {
   //    // check to make sure that mProperty is on the class of target
   //    try {
   //        Object testValue = mProperty.get(target);
   //        for (Keyframe kf : mKeyframeSet.mKeyframes) {
   //            if (!kf.hasValue()) {
   //                kf.setValue(mProperty.get(target));
   //            }
   //        }
   //        return;
   //    } catch (ClassCastException e) {
   //        Log.e("PropertyValuesHolder","No such property (" + mProperty.getName() +
   //                ") on target object " + target + ". Trying reflection instead");
   //        mProperty = null;
   //    }
   // }
   Class targetClass = target.getClass();
   if (mSetter == null) {
     setupSetter(targetClass);
   }
   for (Keyframe kf : mKeyframeSet.mKeyframes) {
     if (!kf.hasValue()) {
       if (mGetter == null) {
         setupGetter(targetClass);
       }
       try {
         kf.setValue(mGetter.invoke(target));
       } catch (InvocationTargetException e) {
         Log.e("PropertyValuesHolder", e.toString());
       } catch (IllegalAccessException e) {
         Log.e("PropertyValuesHolder", e.toString());
       }
     }
   }
 }
コード例 #16
0
  public void fetchAllProperties() {
    // getMethods key is a property Class object
    // getMethods value is the Method that returns the instance of the Property
    Hashtable getMethods = new Hashtable();
    Class thisClass = asset.getClass();
    Field fields[] = null;
    Vector fieldVector = new Vector(2);
    Method methods[] = null;
    Object result = null;

    // retrieve all public methods of this class and its ancestor classes
    // retrieve all attributes of this class and ancestors
    try {
      methods = thisClass.getMethods();
      Class ancestorClass = thisClass;
      while (Asset.class.isAssignableFrom(ancestorClass)) {
        fields = ancestorClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
          fieldVector.addElement(fields[i]);
        }
        ancestorClass = ancestorClass.getSuperclass();
      }
    } catch (SecurityException se) {
      System.out.println("In Asset.fetchAllProperties: " + se.toString());
    }

    // Build a Hashtable of the methods with the right signature, where
    // "right signature" means the method returns a subtype of Property
    // and requires no arguments.
    for (int methodIndex = 0; methodIndex < methods.length; methodIndex++) {
      Class returntype = methods[methodIndex].getReturnType();
      if (returntype != null
          && PropertyGroup.class.isAssignableFrom(returntype)
          && methods[methodIndex].getParameterTypes().length == 0) {
        getMethods.put(methods[methodIndex].getReturnType(), methods[methodIndex]);
      }
    }

    // Walk through the list of fields looking for subtypes of Property.
    // If the field's Class is in the Hashtable, do introspection
    // this section is a bit complex because we want to introspect
    // on the DECLARED return property CLASS to determine what
    // attributes to fetch, but we want to fetch
    // the attributes by invoking methods on the actual property object
    Enumeration fieldEnum = fieldVector.elements();
    while (fieldEnum.hasMoreElements()) {
      Field currentField = (Field) fieldEnum.nextElement();
      Method currentMethod = (Method) getMethods.get(currentField.getType());
      if (currentMethod != null) {
        try {
          // invoke the get property method on the asset
          Object returnedObject = currentMethod.invoke(asset, null);
          if (returnedObject != null) {
            Class returnType = currentMethod.getReturnType();
            // introspect on property class to get attributes
            // throws Introspection exception
            // System.out.println("Introspecting on: " + returnType +
            // " for " + asset.toString());
            BeanInfo info = Introspector.getBeanInfo(returnType);
            PropertyDescriptor[] pds = info.getPropertyDescriptors();
            // invoke read methods to get attributes of property
            for (int j = 0; j < pds.length; j++) {
              Method readMethod = pds[j].getReadMethod();
              if (readMethod != null) {
                try {
                  // System.out.println("Invoking: " + readMethod.getName() +
                  // " on " + returnedObject);
                  result = readMethod.invoke(returnedObject, null);

                  String s =
                      prettyName(returnType.toString()) + ": " + pds[j].getName() + ": " + result;
                  insert(new UIStringNode(s), treeIndex++);
                } catch (NullPointerException e) {
                  System.out.println("In Asset.fetchAllProperties: " + e.toString());
                  e.printStackTrace();
                } catch (InvocationTargetException e) {
                  System.out.println(
                      "Invocation target error; method: "
                          + currentMethod.getName()
                          + " exception: "
                          + e.toString());
                  e.printStackTrace();
                }
              }
            }
          }
        } catch (Exception e) {
          System.out.println(
              "Exception caught; method: "
                  + currentMethod.getName()
                  + " exception: "
                  + e.toString());
          e.printStackTrace();
        }
      }
    }

    // now handle the dynamically added properties
    Method readAttributeMethod = null;
    Enumeration dynamic = asset.getOtherProperties();
    while (dynamic.hasMoreElements()) {
      Object o = dynamic.nextElement();
      try {
        PropertyGroup p = (PropertyGroup) o;
        Class interfaceToUse = p.getPrimaryClass();
        //	System.out.println("Introspecting on: " + interfaceToUse);
        // System.out.println("Introspecting on: " + interfaceToUse +
        // " for " + asset.toString());
        BeanInfo propertyBeanInfo = Introspector.getBeanInfo(interfaceToUse);
        PropertyDescriptor[] attributePds = propertyBeanInfo.getPropertyDescriptors();
        for (int k = 0; k < attributePds.length; k++) {
          readAttributeMethod = attributePds[k].getReadMethod();
          if (readAttributeMethod != null) {
            //	    System.out.println("From other properties, Invoking: " +
            // readAttributeMethod.getName() +
            //			       " on " + o);
            result = readAttributeMethod.invoke(o, null);
            String s =
                prettyName(interfaceToUse.toString())
                    + ": "
                    + attributePds[k].getName()
                    + ": "
                    + result;
            insert(new UIStringNode(s), treeIndex++);
          }
        }
      } catch (Exception e) {
        String n = "(null method)";
        if (readAttributeMethod != null) n = readAttributeMethod.getName();
        System.out.println(
            "Exception introspecting on other properties: "
                + e.toString()
                + " while invoking "
                + n
                + " on "
                + o.getClass());
      }
    }
  }
コード例 #17
0
 /**
  * Populates the given object with the specified parameter. For the parameter-name the given
  * object needs to specify either set[param-name]( String ), set[param-name]( File ) or
  * set[param-name]( boolean ). When the parameter "message" is provided, either the method
  * setMessage( String value ), setMessage( File value ) or setMessage( boolean ) needs to be
  * defined by the given object. When the object defines both methods, it cannot be foreseen which
  * one of them will be called.
  *
  * @param object the object which should be populated.
  * @param parameterName the name of the parameter.
  * @param parameterValue the value of the parameter
  * @param baseDir the base directory for the population.
  * @throws IllegalArgumentException when a parameter has a syntax error or when a needed method
  *     has not be found.
  */
 public static final void populate(
     Object object, String parameterName, String parameterValue, File baseDir) {
   String methodName = parameterName;
   if (methodName == null) {
     throw new IllegalArgumentException("The parameter does not contain a name.");
   }
   methodName = "set" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1);
   Class objectClass = object.getClass();
   Method method = null;
   Object argument = null;
   String value = parameterValue;
   try {
     method = objectClass.getMethod(methodName, new Class[] {String.class});
     argument = value;
   } catch (NoSuchMethodException e) {
     try {
       method = objectClass.getMethod(methodName, new Class[] {File.class});
       if (value != null) {
         File file = new File(value);
         if (!file.isAbsolute()) {
           file = new File(baseDir, value);
         }
         argument = file;
       }
     } catch (NoSuchMethodException e2) {
       try {
         method = objectClass.getMethod(methodName, new Class[] {Boolean.TYPE});
         argument = new Boolean(CastUtil.getBoolean(value));
       } catch (NoSuchMethodException e3) {
         throw new IllegalArgumentException(
             "Unable to retrieve method " + methodName + ": " + e3.toString());
       }
     }
   } catch (SecurityException e) {
     e.printStackTrace();
     throw new IllegalArgumentException(
         "Unable to retrieve method " + methodName + ": " + e.toString());
   }
   try {
     // okay, we've now have a method and an argument, so let's invoke it:
     method.invoke(object, new Object[] {argument});
   } catch (IllegalArgumentException e) {
     throw e;
   } catch (IllegalAccessException e) {
     e.printStackTrace();
     String message =
         "Unable to set the parameter ["
             + parameterName
             + "] with value ["
             + parameterValue
             + "] for class ["
             + object.getClass().getName()
             + "]: "
             + e.toString();
     throw new IllegalArgumentException(message);
   } catch (InvocationTargetException e) {
     e.printStackTrace();
     String message =
         "Unable to set the parameter ["
             + parameterName
             + "] with value ["
             + parameterValue
             + "] for class ["
             + object.getClass().getName()
             + "]: "
             + e.toString();
     throw new IllegalArgumentException(message);
   }
 }
コード例 #18
0
  /**
   * Populates the given object with the specified parameters. For each parameter-name the given
   * object needs to specify either set[param-name]( String ), set[param-name]( File ) or
   * set[param-name]( boolean ). When the parameter "message" is provided, either the method
   * setMessage( String value ), setMessage( File value ) or setMessage( boolean ) needs to be
   * defined by the given object. When the object defines both methods, it cannot be foreseen which
   * one of them will be called.
   *
   * @param object the object which should be populated.
   * @param parameters the parameters.
   * @param baseDir the base directory for the population.
   * @throws IllegalArgumentException when a parameter has a syntax error or when a needed method
   *     has not be found.
   */
  public static final void populate(Object object, Object[] parameters, File baseDir) {
    Class objectClass = object.getClass();
    try {
      // first check whether the object in question has implmented the setParameters( Variable[]
      // parameters, File baseDir ) method.
      Method setParametersMethod =
          objectClass.getMethod("setParameters", new Class[] {parameters.getClass(), File.class});
      setParametersMethod.invoke(object, new Object[] {parameters, baseDir});
      return;
    } catch (Exception e) {
      // okay, try the traditional settings...
    }
    // put all methods into a hash map:
    Method[] methods = objectClass.getMethods();
    HashMap methodsByName = new HashMap();
    for (int i = 0; i < methods.length; i++) {
      Method method = methods[i];
      Class[] parameterTypes = method.getParameterTypes();
      if (parameterTypes.length == 1) {
        Class parameterType = parameterTypes[0];
        if (parameterType == String.class
            || parameterType == File.class
            || parameterType == Boolean.TYPE) {
          methodsByName.put(method.getName(), method);
        }
      }
    }

    // split parameters into single ones:
    String parameterValue = "unknown";
    for (int i = 0; i < parameters.length; i++) {
      Object param = parameters[i];
      String parameterName = param.toString();
      try {
        parameterName = (String) callMethod("getName", param);
        parameterValue = (String) callMethod("getValue", param);
        populate(object, baseDir, parameterName, parameterValue, methodsByName);
      } catch (IllegalArgumentException e) {
        throw e;
      } catch (IllegalAccessException e) {
        e.printStackTrace();
        String message =
            "Unable to set the parameter ["
                + parameterName
                + "] with value ["
                + parameterValue
                + "] for class ["
                + object.getClass().getName()
                + "]: "
                + e.toString();
        throw new IllegalArgumentException(message);
      } catch (InvocationTargetException e) {
        e.printStackTrace();
        String message =
            "Unable to set the parameter ["
                + parameterName
                + "] with value ["
                + parameterValue
                + "] for class ["
                + object.getClass().getName()
                + "]: "
                + e.toString();
        throw new IllegalArgumentException(message);
      } catch (NoSuchMethodException e) {
        String message =
            "Unable to set the parameter ["
                + parameterName
                + "] with value ["
                + parameterValue
                + "] for class ["
                + object.getClass().getName()
                + "]: "
                + e.toString();
        throw new IllegalArgumentException(message);
      }
    }
  }
コード例 #19
0
  /**
   * Processes the request coming to the servlet and grabs the attributes set by the servlet and
   * uses them to fire off pre-determined methods set in the setupActionMethods function of the
   * servlet.
   *
   * @param request the http request coming from the browser.
   * @param response the http response going to the browser.
   * @throws javax.servlet.ServletException
   * @throws java.io.IOException
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (!actionInitialized) {
      LogController.write(this, "This dispatcher servlet is not initialized properly!");
      return;
    }

    if (actionTag == null) {
      LogController.write(this, "There is no action attribute tag name!");
      return;
    }

    HttpSession httpSession = request.getSession();
    UserSession userSession = (UserSession) httpSession.getAttribute("user_session");

    if (userSession == null) {
      LogController.write(this, "User session is no longer available in this http session.");

      userSession = new UserSession();

      // We always want a user session though...
      httpSession.setAttribute("user_session", userSession);
    }

    String action = (String) request.getAttribute(actionTag);

    try {
      if (action == null) {
        // There is no action attribute specified, check parameters.
        String external_action = (String) request.getParameter(actionTag);

        if (external_action != null) {
          Method method = externalActions.get(external_action);

          if (method != null) {
            LogController.write(this, "Performing external action: " + external_action);
            method.invoke(this, new Object[] {userSession, request, response});
          } else {
            if (defaultExternalMethod != null) {
              LogController.write(this, "Performing default external action.");
              defaultExternalMethod.invoke(this, new Object[] {userSession, request, response});
            } else {
              LogController.write(this, "Unable to perform default external action.");
            }
          }
        } else {
          if (defaultExternalMethod != null) {
            LogController.write(this, "Performing default external action.");
            defaultExternalMethod.invoke(this, new Object[] {userSession, request, response});
          } else {
            LogController.write(this, "Unable to perform default external action.");
          }
        }
      } else {
        Method method = internalActions.get(action);

        if (method != null) {
          LogController.write(this, "Performing internal action: " + action);
          method.invoke(this, new Object[] {userSession, request, response});
        } else {
          if (defaultInternalMethod != null) {
            LogController.write(this, "Performing default internal action.");
            defaultInternalMethod.invoke(this, new Object[] {userSession, request, response});
          } else {
            LogController.write(this, "Unable to perform default internal action.");
          }
        }

        request.removeAttribute("application_action");
      }
    } catch (IllegalAccessException accessEx) {
      LogController.write(this, "Exception while processing request: " + accessEx.getMessage());
    } catch (InvocationTargetException invokeEx) {
      LogController.write(this, "Exception while processing request: " + invokeEx.toString());
      invokeEx.printStackTrace();
    } catch (Exception ex) {
      LogController.write(this, "Unknown exception: " + ex.toString());
    }
  }
コード例 #20
0
ファイル: JOXBeanInput.java プロジェクト: blueocci/codes
  /**
   * Reads an XML element into a bean property by first locating the XML element corresponding to
   * this property.
   *
   * @param ob The bean whose property is being set
   * @param desc The property that will be set
   * @param nodes The list of XML items that may contain the property
   * @throws IOException If there is an error reading the document
   */
  public void readProperty(Object ob, PropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs)
      throws IOException {
    int numAttrs = attrs.getLength();

    for (int i = 0; i < numAttrs; i++) {
      // See if the attribute name matches the property name
      if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) {
        // Get the method used to set this property
        Method setter = desc.getWriteMethod();

        // If this object has no setter, don't bother writing it
        if (setter == null) continue;

        // Get the value of the property
        Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue());
        if (obValue != null) {
          try {
            // Set the property value
            setter.invoke(ob, new Object[] {obValue});
          } catch (InvocationTargetException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          } catch (IllegalAccessException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          }
        }

        return;
      }
    }

    int numNodes = nodes.getLength();

    Vector arrayBuild = null;

    for (int i = 0; i < numNodes; i++) {
      Node node = nodes.item(i);

      // If this node isn't an element, skip it
      if (!(node instanceof Element)) continue;

      Element element = (Element) node;

      // See if the tag name matches the property name
      if (namesMatch(desc.getName(), element.getTagName())) {
        // Get the method used to set this property
        Method setter = desc.getWriteMethod();

        // If this object has no setter, don't bother writing it
        if (setter == null) continue;

        // Get the value of the property
        Object obValue = getObjectValue(desc, element);

        // 070201 MAW: Modified from change submitted by Steve Poulson
        if (setter.getParameterTypes()[0].isArray()) {
          if (arrayBuild == null) {
            arrayBuild = new Vector();
          }
          arrayBuild.addElement(obValue);

          // 070201 MAW: Go ahead and read through the rest of the nodes in case
          //             another one matches the array. This has the effect of skipping
          //             over the "return" statement down below
          continue;
        }

        if (obValue != null) {
          try {
            // Set the property value
            setter.invoke(ob, new Object[] {obValue});
          } catch (InvocationTargetException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          } catch (IllegalAccessException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          }
        }
        return;
      }
    }

    // If we build a vector of array members, convert the vector into
    // an array and save it in the property
    if (arrayBuild != null) {
      // Get the method used to set this property
      Method setter = desc.getWriteMethod();

      if (setter == null) return;

      Object[] obValues = (Object[]) Array.newInstance(desc.getPropertyType(), arrayBuild.size());

      arrayBuild.copyInto(obValues);

      try {
        setter.invoke(ob, new Object[] {obValues});
      } catch (InvocationTargetException exc) {
        throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
      }

      return;
    }
  }
コード例 #21
0
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {

    // Check if we are closing down
    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    if (window == null) {
      return null;
    }

    ISelection selection = HandlerUtil.getCurrentSelection(event);
    TmfTraceElement selectedTrace = null;
    if (selection instanceof IStructuredSelection) {
      Object element = ((IStructuredSelection) selection).getFirstElement();
      if (element instanceof TmfTraceElement) {
        selectedTrace = (TmfTraceElement) element;
      }
    }
    if (selectedTrace == null) {
      return null;
    }

    // If trace is under an experiment, use the original trace from the traces folder
    final TmfTraceElement oldTrace = selectedTrace.getElementUnderTraceFolder();

    RenameTraceDialog dialog = new RenameTraceDialog(window.getShell(), oldTrace);
    if (dialog.open() != Window.OK) {
      return null;
    }

    final TmfTraceFolder traceFolder = (TmfTraceFolder) oldTrace.getParent();
    final String newName = (String) dialog.getFirstResult();

    IFolder parentFolder = (IFolder) oldTrace.getParent().getResource();
    final TmfTraceFolder tracesFolder = oldTrace.getProject().getTracesFolder();
    final IPath newPath = parentFolder.getFullPath().append(newName);

    WorkspaceModifyOperation operation =
        new WorkspaceModifyOperation() {
          @Override
          public void execute(IProgressMonitor monitor) throws CoreException {
            try {
              monitor.beginTask("", 1000); // $NON-NLS-1$
              if (monitor.isCanceled()) {
                throw new OperationCanceledException();
              }
              // Close the trace if open
              Display.getDefault()
                  .syncExec(
                      new Runnable() {
                        @Override
                        public void run() {
                          oldTrace.closeEditors();
                        }
                      });

              if (oldTrace.getResource() instanceof IFolder) {
                IFolder folder = (IFolder) oldTrace.getResource();
                IFile bookmarksFile = oldTrace.getBookmarksFile();
                if (bookmarksFile.exists()) {
                  IFile newBookmarksFile =
                      folder.getFile(bookmarksFile.getName().replace(oldTrace.getName(), newName));
                  if (!newBookmarksFile.exists()) {
                    IPath newBookmarksPath = newBookmarksFile.getFullPath();
                    bookmarksFile.move(
                        newBookmarksPath, IResource.FORCE | IResource.SHALLOW, monitor);
                  }
                }
              }

              String newElementPath = newPath.makeRelativeTo(tracesFolder.getPath()).toString();
              oldTrace.renameSupplementaryFolder(newElementPath);
              oldTrace.getResource().move(newPath, IResource.FORCE | IResource.SHALLOW, monitor);
              if (monitor.isCanceled()) {
                throw new OperationCanceledException();
              }
            } finally {
              monitor.done();
            }
          }
        };

    try {
      PlatformUI.getWorkbench().getProgressService().busyCursorWhile(operation);
    } catch (InterruptedException e) {
      return null;
    } catch (InvocationTargetException e) {
      MessageDialog.openError(window.getShell(), e.toString(), e.getTargetException().toString());
      return null;
    }

    /* We need to split the WorkspaceModifyOperation so that the new model
     * elements get created by the resource changed event */
    operation =
        new WorkspaceModifyOperation() {
          @Override
          protected void execute(IProgressMonitor monitor)
              throws CoreException, InvocationTargetException, InterruptedException {

            // Locate the new trace object
            TmfTraceElement newTrace = null;
            String newElementPath =
                oldTrace
                    .getParent()
                    .getPath()
                    .append(newName)
                    .makeRelativeTo(tracesFolder.getPath())
                    .toString();
            for (TmfTraceElement element : traceFolder.getTraces()) {
              if (element.getElementPath().equals(newElementPath)) {
                newTrace = element;
                break;
              }
            }
            if (newTrace == null) {
              return;
            }

            TmfExperimentFolder experimentFolder = newTrace.getProject().getExperimentsFolder();
            for (final TmfExperimentElement experiment : experimentFolder.getExperiments()) {
              for (final TmfTraceElement expTrace : experiment.getTraces()) {
                if (expTrace.getElementPath().equals(oldTrace.getElementPath())) {
                  experiment.removeTrace(expTrace);
                  experiment.addTrace(newTrace);
                }
              }
            }
          }
        };

    try {
      PlatformUI.getWorkbench().getProgressService().busyCursorWhile(operation);
    } catch (InterruptedException e) {
    } catch (InvocationTargetException e) {
      MessageDialog.openError(window.getShell(), e.toString(), e.getTargetException().toString());
    }

    return null;
  }
コード例 #22
0
  @Override
  public void read(final DataInput in) throws IOException {

    // Read job id
    this.jobID.read(in);

    // Read the job name
    this.jobName = StringRecord.readString(in);

    // Read required jar files
    readRequiredJarFiles(in);

    // First read total number of vertices;
    final int numVertices = in.readInt();

    // First, recreate each vertex and add it to reconstructionMap
    for (int i = 0; i < numVertices; i++) {
      final String className = StringRecord.readString(in);
      final JobVertexID id = new JobVertexID();
      id.read(in);
      final String vertexName = StringRecord.readString(in);

      Class<? extends IOReadableWritable> c;
      try {
        c = ClassUtils.getRecordByName(className);
      } catch (ClassNotFoundException cnfe) {
        throw new IOException(cnfe.toString());
      }

      // Find constructor
      Constructor<? extends IOReadableWritable> cst;
      try {
        cst = c.getConstructor(String.class, JobVertexID.class, JobGraph.class);
      } catch (SecurityException e1) {
        throw new IOException(e1.toString());
      } catch (NoSuchMethodException e1) {
        throw new IOException(e1.toString());
      }

      try {
        cst.newInstance(vertexName, id, this);
      } catch (IllegalArgumentException e) {
        throw new IOException(e.toString());
      } catch (InstantiationException e) {
        throw new IOException(e.toString());
      } catch (IllegalAccessException e) {
        throw new IOException(e.toString());
      } catch (InvocationTargetException e) {
        throw new IOException(e.toString());
      }
    }

    final JobVertexID tmpID = new JobVertexID();
    for (int i = 0; i < numVertices; i++) {

      AbstractJobVertex jv;

      tmpID.read(in);
      if (inputVertices.containsKey(tmpID)) {
        jv = inputVertices.get(tmpID);
      } else {
        if (outputVertices.containsKey(tmpID)) {
          jv = outputVertices.get(tmpID);
        } else {
          if (taskVertices.containsKey(tmpID)) {
            jv = taskVertices.get(tmpID);
          } else {
            throw new IOException("Cannot find vertex with ID " + tmpID + " in any vertex map.");
          }
        }
      }

      // Read the vertex data
      jv.read(in);
    }

    // Find the class loader for the job
    final ClassLoader cl = LibraryCacheManager.getClassLoader(this.jobID);
    if (cl == null) {
      throw new IOException("Cannot find class loader for job graph " + this.jobID);
    }

    // Re-instantiate the job configuration object and read the configuration
    this.jobConfiguration = new Configuration(cl);
    this.jobConfiguration.read(in);
  }
コード例 #23
0
ファイル: JOXBeanInput.java プロジェクト: blueocci/codes
  /**
   * Reads XML element(s) into an indexed bean property by first locating the XML element(s)
   * corresponding to this property.
   *
   * @param ob The bean whose property is being set
   * @param desc The property that will be set
   * @param nodes The list of XML items that may contain the property
   * @throws IOException If there is an error reading the document
   */
  public void readIndexedProperty(
      Object ob, IndexedPropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs)
      throws IOException {
    // Create a vector to hold the property values
    Vector v = new Vector();

    int numAttrs = attrs.getLength();

    for (int i = 0; i < numAttrs; i++) {
      // See if this attribute matches the property name
      if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) {
        // Get the property value
        Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue());

        if (obValue != null) {
          // Add the value to the list of values to be set
          v.addElement(obValue);
        }
      }
    }

    int numNodes = nodes.getLength();

    for (int i = 0; i < numNodes; i++) {
      Node node = nodes.item(i);

      // Skip non-element nodes
      if (!(node instanceof Element)) continue;

      Element element = (Element) node;

      // See if this element tag matches the property name
      if (namesMatch(desc.getName(), element.getTagName())) {
        // Get the property value
        Object obValue = getObjectValue(desc, element);

        if (obValue != null) {
          // Add the value to the list of values to be set
          v.addElement(obValue);
        }
      }
    }

    // Get the method used to set the property value
    Method setter = desc.getWriteMethod();

    // If this property has no setter, don't write it
    if (setter == null) return;

    // Create a new array of property values
    Object propArray = Array.newInstance(desc.getPropertyType().getComponentType(), v.size());

    // Copy the vector into the array
    v.copyInto((Object[]) propArray);

    try {
      // Store the array of property values
      setter.invoke(ob, new Object[] {propArray});
    } catch (InvocationTargetException exc) {
      throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
    } catch (IllegalAccessException exc) {
      throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
    }
  }
コード例 #24
0
  @TargetApi(10)
  void connect(Context context) {

    try {

      MetaWatchService.fakeWatch = false;
      if (Preferences.watchMacAddress.equals("DIGITAL")) {
        MetaWatchService.fakeWatch = true;
        MetaWatchService.watchType = MetaWatchService.WatchType.DIGITAL;
      }
      if (Preferences.watchMacAddress.equals("ANALOG")) {
        MetaWatchService.fakeWatch = true;
        MetaWatchService.watchType = MetaWatchService.WatchType.ANALOG;
      }

      if (Preferences.logging)
        Log.d(MetaWatch.TAG, "Remote device address: " + Preferences.watchMacAddress);
      if (!Preferences.loaded) loadPreferences(context);

      if (!MetaWatchService.fakeWatch) {

        if (bluetoothAdapter == null) {
          sendToast(getResources().getString(R.string.error_bluetooth_not_supported));
          return;
        } else if (!bluetoothAdapter.isEnabled()) {
          sendToast(getResources().getString(R.string.error_bluetooth_not_enabled));
          return;
        }

        wakeLock.acquire(5000);

        BluetoothDevice bluetoothDevice =
            bluetoothAdapter.getRemoteDevice(Preferences.watchMacAddress);

        if (Preferences.skipSDP) {
          Method method =
              bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
          bluetoothSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1);
        } else {
          UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

          int currentapiVersion = android.os.Build.VERSION.SDK_INT;

          if (Preferences.insecureBtSocket
              && currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
            bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
          } else {
            bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
          }
        }

        bluetoothAdapter.cancelDiscovery();
        bluetoothSocket.connect();

        inputStream = bluetoothSocket.getInputStream();
        outputStream = bluetoothSocket.getOutputStream();
      }

      connectionState = ConnectionState.CONNECTED;
      updateNotification();

      Protocol.startProtocolSender();

      // RM: This is disabled for now, as it seems to confuse the watch fw (3.1.0S tested)
      // and get it into a state where it won't accept any date/time format updates :-S

      // if( Preferences.autoClockFormat )
      //	Protocol.setTimeDateFormat(this);

      Protocol.getRealTimeClock();
      Protocol.getDeviceType();

      Notification.startNotificationSender(this);

      Idle.updateIdle(this, true);

    } catch (IOException ioexception) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, ioexception.toString());
    } catch (SecurityException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (NoSuchMethodException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (IllegalArgumentException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (IllegalAccessException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (InvocationTargetException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (NullPointerException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } finally {
      if (wakeLock != null && wakeLock.isHeld()) {
        wakeLock.release();
      }
    }

    return;
  }