Example #1
0
  /**
   * Send an event to all registered listeners, except the named one.
   *
   * @param event the event to be sent: public void method_name( event_class event)
   */
  public void sendEventExcludeSource(java.util.EventObject event) {
    if (!hasListeners) {
      return;
    }

    Object source = event.getSource();
    Object[] args = new Object[1];
    args[0] = event;

    // send event to all listeners except the source
    ListIterator iter = listeners.listIterator();
    while (iter.hasNext()) {
      Object client = iter.next();
      if (client == source) {
        continue;
      }

      try {
        method.invoke(client, args);
      } catch (IllegalAccessException e) {
        iter.remove();
        System.err.println("ListenerManager IllegalAccessException = " + e);
      } catch (IllegalArgumentException e) {
        iter.remove();
        System.err.println("ListenerManager IllegalArgumentException = " + e);
      } catch (InvocationTargetException e) {
        iter.remove();
        System.err.println("ListenerManager InvocationTargetException on " + method);
        System.err.println("   threw exception " + e.getTargetException());
        e.printStackTrace();
      }
    }
  }
Example #2
0
  private void bindEventHandler(
      Component componentRoot, Object controller, Method method, UiHandler eventListener) {
    String componentId = eventListener.value();
    Component component = Clara.findComponentById(componentRoot, componentId);
    if (component == null) {
      throw new BinderException("No component found for id: " + componentId + ".");
    }

    Class<?> eventType =
        (method.getParameterTypes().length > 0 ? method.getParameterTypes()[0] : null);
    if (eventType == null) {
      throw new BinderException("Couldn't figure out event type for method " + method + ".");
    }

    Method addListenerMethod = getAddListenerMethod(component.getClass(), eventType);
    if (addListenerMethod != null) {
      try {
        Object listener =
            createListenerProxy(
                addListenerMethod.getParameterTypes()[0], eventType, method, controller);
        addListenerMethod.invoke(component, listener);
        // TODO exception handling
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
Example #3
0
  private void bindDataSource(
      Component componentRoot, Object controller, Method method, UiDataSource dataSource) {
    String componentId = dataSource.value();
    Component component = Clara.findComponentById(componentRoot, componentId);
    Class<?> dataSourceClass = method.getReturnType();

    try {
      // Vaadin data model consists of Property/Item/Container
      // objects and each of them have a Viewer interface.
      if (isContainer(dataSourceClass) && component instanceof Container.Viewer) {
        ((Container.Viewer) component)
            .setContainerDataSource((Container) method.invoke(controller));
      } else if (isProperty(dataSourceClass) && component instanceof Property.Viewer) {
        ((Property.Viewer) component).setPropertyDataSource((Property) method.invoke(controller));
      } else if (isItem(dataSourceClass) && component instanceof Item.Viewer) {
        ((Item.Viewer) component).setItemDataSource((Item) method.invoke(controller));
      }
      // TODO exception handling
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
Example #4
0
 /**
  * Insert the source code details, if available.
  *
  * @param ped The given program element.
  */
 public void addSourcePosition(ProgramElementDoc ped, int indent) {
   if (!addSrcInfo) return;
   if (JDiff.javaVersion.startsWith("1.1")
       || JDiff.javaVersion.startsWith("1.2")
       || JDiff.javaVersion.startsWith("1.3")) {
     return; // position() only appeared in J2SE1.4
   }
   try {
     // Could cache the method for improved performance
     Class c = ProgramElementDoc.class;
     Method m = c.getMethod("position", null);
     Object sp = m.invoke(ped, null);
     if (sp != null) {
       for (int i = 0; i < indent; i++) outputFile.print(" ");
       outputFile.println("src=\"" + sp + "\"");
     }
   } catch (NoSuchMethodException e2) {
     System.err.println("Error: method \"position\" not found");
     e2.printStackTrace();
   } catch (IllegalAccessException e4) {
     System.err.println("Error: class not permitted to be instantiated");
     e4.printStackTrace();
   } catch (InvocationTargetException e5) {
     System.err.println("Error: method \"position\" could not be invoked");
     e5.printStackTrace();
   } catch (Exception e6) {
     System.err.println("Error: ");
     e6.printStackTrace();
   }
 }
  public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException {

    try {
      if (method.getName().startsWith("get")) {
        return method.invoke(person, args);
      } else if (method.getName().equals("setHotOrNotRating")) {
        throw new IllegalAccessException();
      } else if (method.getName().startsWith("set")) {
        return method.invoke(person, args);
      }
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
    return null;
  }
Example #6
0
  /**
   * 通过反射关闭应用 android:sharedUserId="android.uid.system"
   *
   * <p>需添加<uses-permission android:name="android.permission.FORCE_STOP_PACKAGES"/>
   *
   * @param context 上下文
   * @param packageName 应用包名
   * @return
   */
  public static boolean closeAppWithReflect(Context context, String packageName) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    Method forceStopPackage;
    try {
      forceStopPackage = am.getClass().getDeclaredMethod("forceStopPackage", String.class);
      forceStopPackage.setAccessible(true);
      forceStopPackage.invoke(am, packageName);

      return true;
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
    return false;
  }
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
Example #8
0
  /** Clears the view. */
  @Override
  public void clear() {
    final Drawing newDrawing = createDrawing();
    try {
      SwingUtilities.invokeAndWait(
          new Runnable() {

            @Override
            public void run() {
              view.getDrawing().removeUndoableEditListener(undo);
              view.setDrawing(newDrawing);
              view.getDrawing().addUndoableEditListener(undo);
              undo.discardAllEdits();
            }
          });
    } catch (InvocationTargetException ex) {
      ex.printStackTrace();
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }
  }
  /** Look on disk for an editor with the class name 'ocName'. */
  PluggableEditor loadEditorFromDisk(String ocName) {
    // if here, we need to look on disk for a pluggable editor class...
    log.finer("looking for ocName: " + ocName);
    try {
      Class c = myLoader.loadClass(ocName);
      Constructor constructor = c.getConstructor(new Class[0]);

      // XXX If the pluggable editor has an error in the constructor, under some
      // XXX circumstances it can fail so badly that this call never returns, and
      // XXX the thread hangs!  It doesn't even get to the exception handler below...
      // XXX but sometimes if the constructor fails everything works as expected.  Wierd.
      PluggableEditor editor = (PluggableEditor) constructor.newInstance(new Object[0]);

      editors.put(ocName, editor); // add the new editor to our list
      return editor;
    } catch (Exception e) // expected condition - just means no pluggable editor available
    {
      if (e
          instanceof
          InvocationTargetException) // rare exception - an error was encountered in the plugin's
                                     // constructor.
      {
        log.warning("unable to load special editor for: '" + ocName + "' " + e);
        if (JXConfig.debugLevel >= 1) {
          log.warning("Error loading plugin class: ");
          ((InvocationTargetException) e).getTargetException().printStackTrace();
        }
      }

      log.log(Level.FINEST, "'Expected' Error loading " + ocName, e);
      editors.put(ocName, NONE); // add a blank place holder - we can't load
      // an editor for this, and there's no point looking again. (change if want dynamic loading,
      // i.e. look *every* time)
    }
    return null; // only here if an error has occured.
  }
  /**
   * オブジェクトのメソッドを呼び出す
   *
   * @param Object o メソッドを呼び出したいオブジェクト
   * @param String methodName 呼び出したいメソッドの名前
   * @param Object... args メソッドのパラメータ
   * @throws NoSuchMethodException
   */
  public static Object invoke(Object o, String methodName, Object... args)
      throws SecurityException, ClassNotFoundException, NoSuchMethodException {
    StringBuffer tempMessage = new StringBuffer();
    Method method = null;

    //		//argsArray:メソッドの引数の型配列
    //		Class<?>[] argsArray = new Class<?>[args.length];
    //		for(int i = 0; i < args.length; i++){
    //			argsArray[i] = getClassObject(args[i]);
    //			//スーパークラスを引数にとれるように修正
    //		}
    //		try {
    //			method = o.getClass().getMethod(methodName, argsArray);
    //		} catch (NoSuchMethodException e) {
    //			try{
    //				method = o.getClass().getDeclaredMethod(methodName, argsArray);
    //			}catch (NoSuchMethodException e2) {
    //					message = "NoSuchMethodException\r\n";
    //					display.append(message);
    //			}
    //		}
    /////////////////////////////////////////
    // argsArray:メソッドの引数の型配列
    Class<?>[] argsArray = new Class<?>[args.length];
    for (int i = 0; i < args.length; i++) {
      argsArray[i] = getClassObject(args[i]);
    }
    method = getMethod(o, args, methodName, argsArray);

    ////////////////////////////////////////
    tempMessage.append("method: " + method.getName() + " is called.\r\n");

    if (Modifier.isPrivate(method.getModifiers())) {
      method.setAccessible(true);
    }
    if (o.equals(null)) {
      if (Modifier.isStatic(method.getModifiers()) == false) {
        throw new NoSuchMethodException();
      }
    }

    try {
      Type returnType = method.getGenericReturnType();
      tempMessage.append("return type: " + returnType.toString() + "\r\n");
      if (returnType.equals(Void.TYPE)) {
        tempMessage.append("return value: " + "なし\r\n");
      } else {
        tempMessage.append("return value: " + method.invoke(o, args).toString() + "\r\n");
      }
      message = tempMessage.toString();
      display.append(message);
      return method.invoke(o, args);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      message = tempMessage.append("IllegalArgumentException\r\n").toString();
      display.append(message);
    } catch (IllegalAccessException e) {
      e.printStackTrace();
      message = tempMessage.append("IllegalAccessException\r\n").toString();
      display.append(message);
    } catch (InvocationTargetException e) {
      e.printStackTrace();
      tempMessage.append("InvocationTargetException\r\n");
      message = tempMessage.append(e.getCause().toString() + "\r\n").toString();
      display.append(message);
    }
    return null;
  }
Example #11
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());
    }
  }
  public static void main(String[] args) {

    // Obtain the class object if we know the name of the class
    Class rental = RentCar.class;
    try {
      // get the absolute name of the class
      String rentalClassPackage = rental.getName();
      System.out.println("Class Name is: " + rentalClassPackage);

      // get the simple name of the class (without package info)
      String rentalClassNoPackage = rental.getSimpleName();
      System.out.println("Class Name without package is: " + rentalClassNoPackage);

      // get the package name of the class
      Package rentalPackage = rental.getPackage();
      System.out.println("Package Name is: " + rentalPackage);

      // get all the constructors of the class
      Constructor[] constructors = rental.getConstructors();
      System.out.println("Constructors are: " + Arrays.toString(constructors));

      // get constructor with specific argument
      Constructor constructor = rental.getConstructor(Integer.TYPE);

      // initializing an object of the RentCar class
      RentCar rent = (RentCar) constructor.newInstance(455);

      // get all methods of the class including declared methods of
      // superclasses
      // in that case, superclass of RentCar is the class java.lang.Object
      Method[] allmethods = rental.getMethods();
      System.out.println("Methods are: " + Arrays.toString(allmethods));
      for (Method method : allmethods) {
        System.out.println("method = " + method.getName());
      }

      // get all methods declared in the class
      // but excludes inherited methods.
      Method[] declaredMethods = rental.getDeclaredMethods();
      System.out.println("Declared Methods are: " + Arrays.toString(declaredMethods));
      for (Method dmethod : declaredMethods) {
        System.out.println("method = " + dmethod.getName());
      }

      // get method with specific name and parameters
      Method oneMethod = rental.getMethod("computeRentalCost", new Class[] {Integer.TYPE});
      System.out.println("Method is: " + oneMethod);

      // call computeRentalCost method with parameter int
      oneMethod.invoke(rent, 4);

      // get all the parameters of computeRentalCost
      Class[] parameterTypes = oneMethod.getParameterTypes();
      System.out.println(
          "Parameter types of computeRentalCost() are: " + Arrays.toString(parameterTypes));

      // get the return type of computeRentalCost
      Class returnType = oneMethod.getReturnType();
      System.out.println("Return type is: " + returnType);

      // gets all the public member fields of the class RentCar
      Field[] fields = rental.getFields();

      System.out.println("Public Fields are: ");
      for (Field oneField : fields) {
        // get public field name
        Field field = rental.getField(oneField.getName());
        String fieldname = field.getName();
        System.out.println("Fieldname is: " + fieldname);

        // get public field type
        Object fieldType = field.getType();
        System.out.println("Type of field " + fieldname + " is: " + fieldType);

        // get public field value
        Object value = field.get(rent);
        System.out.println("Value of field " + fieldname + " is: " + value);
      }

      // How to access private member fields of the class

      // getDeclaredField() returns the private field
      Field privateField = RentCar.class.getDeclaredField("type");

      String name = privateField.getName();
      System.out.println("One private Fieldname is: " + name);
      // makes this private field instance accessible
      // for reflection use only, not normal code
      privateField.setAccessible(true);

      // get the value of this private field
      String fieldValue = (String) privateField.get(rent);
      System.out.println("fieldValue = " + fieldValue);

    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }