Ejemplo n.º 1
0
  public Matrix createVector(BitVector selector) {
    int rows = selector != null ? selector.countOnBits() : frame.size();
    Matrix m = new Matrix(rows, 1);

    for (int i = 0, j = 0; j < frame.size(); j++) {
      if (selector == null || selector.isOn(j)) {
        M rowValue = frame.object(j);

        try {
          Number numValue = (Number) numericField.get(rowValue);
          m.set(i, 0, numValue.doubleValue());

        } catch (IllegalAccessException e) {
          e.printStackTrace();
          throw new IllegalStateException(
              String.format(
                  "Couldn't access field %s: %s", numericField.getName(), e.getMessage()));
        }

        i++;
      }
    }

    return m;
  }
Ejemplo n.º 2
0
  /** 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. */
  public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
      throw new IllegalArgumentException(
          "Could not find field [" + fieldName + "] on target [" + obj + "]");
    }

    try {
      field.set(obj, value);
    } catch (IllegalAccessException e) {
      logger.error("不可能抛出的异常:{}", e.getMessage());
    }
  }
Ejemplo n.º 3
0
  /** 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. */
  public static Object getFieldValue(final Object obj, final String fieldName) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
      throw new IllegalArgumentException(
          "Could not find field [" + fieldName + "] on target [" + obj + "]");
    }

    Object result = null;
    try {
      result = field.get(obj);
    } catch (IllegalAccessException e) {
      logger.error("不可能抛出的异常{}", e.getMessage());
    }
    return result;
  }
Ejemplo n.º 4
0
  public Matrix createVector() {
    int rows = frame.size();
    Matrix m = new Matrix(rows, 1);

    for (int i = 0; i < rows; i++) {
      M rowValue = frame.object(i);
      try {
        Number numValue = (Number) numericField.get(rowValue);
        m.set(i, 0, numValue.doubleValue());

      } catch (IllegalAccessException e) {
        e.printStackTrace();
        throw new IllegalStateException(
            String.format("Couldn't access field %s: %s", numericField.getName(), e.getMessage()));
      }
    }

    return m;
  }
 /**
  * Parses array from given JSONArray. Supports parsing of primitive types and {@link
  * com.vk.sdk.api.model.VKApiModel} instances.
  *
  * @param array JSONArray to parse
  * @param arrayClass type of array field in class.
  * @return object to set to array field in class
  * @throws org.json.JSONException if given array have incompatible type with given field.
  */
 private static Object parseArrayViaReflection(JSONArray array, Class arrayClass)
     throws JSONException {
   Object result = Array.newInstance(arrayClass.getComponentType(), array.length());
   Class<?> subType = arrayClass.getComponentType();
   for (int i = 0; i < array.length(); i++) {
     try {
       Object item = array.opt(i);
       if (VKApiModel.class.isAssignableFrom(subType) && item instanceof JSONObject) {
         VKApiModel model = (VKApiModel) subType.newInstance();
         item = model.parse((JSONObject) item);
       }
       Array.set(result, i, item);
     } catch (InstantiationException e) {
       throw new JSONException(e.getMessage());
     } catch (IllegalAccessException e) {
       throw new JSONException(e.getMessage());
     } catch (IllegalArgumentException e) {
       throw new JSONException(e.getMessage());
     }
   }
   return result;
 }
Ejemplo n.º 6
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());
    }
  }
  /**
   * Parses object with follow rules:
   *
   * <p>1. All fields should had a public access. 2. The name of the filed should be fully equal to
   * name of JSONObject key. 3. Supports parse of all Java primitives, all {@link String}, arrays of
   * primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s, list
   * implementation line {@link VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or
   * {@link com.vk.sdk.api.model.VKPhotoSizes}, {@link com.vk.sdk.api.model.VKApiModel}s.
   *
   * <p>4. Boolean fields defines by vk_int == 1 expression.
   *
   * @param object object to initialize
   * @param source data to read values
   * @param <T> type of result
   * @return initialized according with given data object
   * @throws org.json.JSONException if source object structure is invalid
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
      source = source.optJSONObject("response");
    }
    if (source == null) {
      return object;
    }
    for (Field field : object.getClass().getFields()) {
      field.setAccessible(true);
      String fieldName = field.getName();
      Class<?> fieldType = field.getType();

      Object value = source.opt(fieldName);
      if (value == null) {
        continue;
      }
      try {
        if (fieldType.isPrimitive() && value instanceof Number) {
          Number number = (Number) value;
          if (fieldType.equals(int.class)) {
            field.setInt(object, number.intValue());
          } else if (fieldType.equals(long.class)) {
            field.setLong(object, number.longValue());
          } else if (fieldType.equals(float.class)) {
            field.setFloat(object, number.floatValue());
          } else if (fieldType.equals(double.class)) {
            field.setDouble(object, number.doubleValue());
          } else if (fieldType.equals(boolean.class)) {
            field.setBoolean(object, number.intValue() == 1);
          } else if (fieldType.equals(short.class)) {
            field.setShort(object, number.shortValue());
          } else if (fieldType.equals(byte.class)) {
            field.setByte(object, number.byteValue());
          }
        } else {
          Object result = field.get(object);
          if (value.getClass().equals(fieldType)) {
            result = value;
          } else if (fieldType.isArray() && value instanceof JSONArray) {
            result = parseArrayViaReflection((JSONArray) value, fieldType);
          } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKAttachments.class.isAssignableFrom(fieldType)
              && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKList.class.equals(fieldType)) {
            ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
            Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
            if (VKApiModel.class.isAssignableFrom(genericType)
                && Parcelable.class.isAssignableFrom(genericType)
                && Identifiable.class.isAssignableFrom(genericType)) {
              if (value instanceof JSONArray) {
                result = new VKList((JSONArray) value, genericType);
              } else if (value instanceof JSONObject) {
                result = new VKList((JSONObject) value, genericType);
              }
            }
          } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
            result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
          }
          field.set(object, result);
        }
      } catch (InstantiationException e) {
        throw new JSONException(e.getMessage());
      } catch (IllegalAccessException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodException e) {
        throw new JSONException(e.getMessage());
      } catch (InvocationTargetException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodError e) {
        // Примечание Виталия:
        // Вы не поверите, но у некоторых вендоров getFields() вызывает ВОТ ЭТО.
        // Иногда я всерьез задумываюсь, правильно ли я поступил, выбрав Android в качестве
        // платформы разработки.
        throw new JSONException(e.getMessage());
      }
    }
    return object;
  }