/**
  * オブジェクトのフィールドにデータを設定する<br>
  * Integer、Float、Float[]、Stringにしか対応していない
  *
  * @param obj 設定対象オブジェクト
  * @param fl 設定対象フィールド
  * @param ty 設定対象フィールドの型
  * @param data 設定データ
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 protected void dataSetter(Object obj, Field fl, Class ty, String data)
     throws IllegalArgumentException, IllegalAccessException {
   // Integer型のデータを設定
   if (ty.toString().equals("class java.lang.Integer")) {
     fl.set(obj, Integer.parseInt(data));
   }
   // Float型のデータを設定
   if (ty.toString().equals("class java.lang.Float")) {
     fl.set(obj, Float.parseFloat(data));
   }
   // String型のデータを設定(""の内側)
   if (ty.toString().equals("class java.lang.String")) {
     fl.set(obj, getDoubleQuoatString(data));
   }
   // Float[]型のデータを設定
   if (ty.toString().equals("class [Ljava.lang.Float;")) {
     String[] s;
     s = data.split(" ");
     Float[] f = new Float[s.length];
     for (int i = 0; i < s.length; i++) {
       f[i] = Float.parseFloat(s[i]);
     }
     fl.set(obj, f);
   }
 }
Example #2
0
 /**
  * Create a new instance of a class using a specific constructor or log the exception if the class
  * is not instanceable. This method will rethrow any exception as an unchecked {@link
  * RuntimeException}.
  *
  * @param <T> the type of the instance to create
  * @param cls the class which represents the type of the instance to create.
  * @param constructor the constructor to use.
  * @param args an array of the constructor arguments.
  * @return a new instance of the type given on the argument by using the specified constructor.
  */
 public static <T> T createInstance(Class<T> cls, Constructor constructor, Object... args) {
   try {
     return (T) constructor.newInstance(args);
   } catch (Throwable t) {
     logger.error("Could not create bean instance of class" + cls.toString(), t);
     throw new RuntimeException(t);
   }
 }
Example #3
0
 /**
  * Create a new instance of a class or log the exception if the class is not instanceable. This
  * method will rethrow any exception as an unchecked {@link RuntimeException}.
  *
  * @param <T>
  * @param cls
  * @return a new instance of the type given in the argument.
  */
 public static <T> T createInstance(Class<T> cls) {
   try {
     return cls.newInstance();
   } catch (Throwable t) {
     logger.error("Could not create bean instance of class " + cls.toString(), t);
     throw new RuntimeException(t);
   }
 }
Example #4
0
  /**
   * Given a map between a string and an object of unknown type, attempt to retrieve what value is
   * mapped to from the specified string and validate that the actual type matches the specified
   * class.
   *
   * @return Null if the types do not match, or the value
   */
  private static Object validateAndGet(Map<String, Object> m, String s, Class<?> c)
      throws MissingMappingException, UnexpectedTypeException {
    Object o = m.get(s);
    if (o == null) throw new MissingMappingException(s);

    if (!c.isAssignableFrom(o.getClass()))
      throw new UnexpectedTypeException(s, c.toString(), o.getClass().toString());
    else return o;
  }
  public TitanGraphIndex getExternalIndex(Class<? extends Element> clazz, String backingIndex) {
    String prefix;
    if (Vertex.class.isAssignableFrom(clazz)) prefix = "v";
    else if (Edge.class.isAssignableFrom(clazz)) prefix = "e";
    else if (TitanVertexProperty.class.isAssignableFrom(clazz)) prefix = "p";
    else throw new AssertionError(clazz.toString());

    String indexName = prefix + backingIndex;
    TitanGraphIndex index = mgmt.getGraphIndex(indexName);
    if (index == null) {
      index = mgmt.buildIndex(indexName, clazz).buildMixedIndex(backingIndex);
    }
    return index;
  }
  static String[] c_signature(Class c, String expr) {
    if (c.isPrimitive()) return strs("j" + c.toString(), expr, expr);
    if (c == Pointer.class)
      return strs(
          "void*",
          "createPointerFromIO(env, " + expr + ", NULL)",
          "getPointerPeer(env, " + expr + ")"); // TODO callIO
    if (c == CLong.class)
      return strs("long", "BoxCLong(env, " + expr + ")", "UnBoxCLong(env, " + expr + ")");
    if (c == SizeT.class)
      return strs("size_t", "BoxSizeT(env, " + expr + ")", "UnBoxSizeT(env, " + expr + ")");
    if (c == TimeT.class)
      return strs("time_t", "BoxTimeT(env, " + expr + ")", "UnBoxTimeT(env, " + expr + ")");

    throw new UnsupportedOperationException("Cannot compute C signature for " + c.getName());
  }
Example #7
0
  /**
   * Binds data from reference model instance to XML binding classes
   *
   * @param obj
   * @return
   * @throws XMLBindingException
   */
  public Object bindToXML(Object obj) throws XMLBindingException {
    if (obj == null) {
      return null;
    }
    String className = obj.getClass().getSimpleName();
    Method[] methods = obj.getClass().getMethods();

    try {
      Class xmlClass = Class.forName(XML_BINDING_PACKAGE + className.toUpperCase());

      // debug code only
      if (xmlClass.getClasses().length != 1) {
        log.debug("XMLBinding: bindToXML(): xmlClass.getClass()=" + xmlClass.getClass());
        log.debug("XMLBinding: bindToXML(): xmlClass.toString()=" + xmlClass.toString());
        for (Class clazz : xmlClass.getClasses()) {
          log.debug("\t clazz.getClass()=" + clazz.getClass());
          log.debug("\t clazz.toString()=" + clazz.toString());
        }
      }

      Class factoryClass = xmlClass.getClasses()[0];

      // ES modification: Add xmlOptions containing openehr (default) and xsi namespaces

      // Method factoryMethod = factoryClass.getMethod(NEW_INSTANCE, null);
      // Changed to pick the method with an XmlOptions parameter instead
      Method factoryMethod = factoryClass.getMethod(NEW_INSTANCE, XmlOptions.class);

      // First prameter null because it's a static method, see:
      // http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html
      // Second parameter should be the parameter of XmlObject.Factory.newInstance(XmlOptions
      // options)
      // see:
      // http://xmlbeans.apache.org/docs/2.2.0/reference/org/apache/xmlbeans/XmlObject.Factory.html
      //
      // Previous code was: Object xmlObj = factoryMethod.invoke(null, null);
      Object xmlObj = factoryMethod.invoke(null, xopt);

      Map<String, Class> attributes = builder.retrieveAttribute(className);
      Set<String> attributeNames = attributes.keySet();
      Object attributeValue = null;
      Method setterMethod = null;

      for (Method method : methods) {
        String name = method.getName();

        // cause dead-loop
        if ("getParent".equals(name)) {
          continue; //
        }

        if (isGetter(name, attributeNames)) {

          log.debug("getter: " + name);

          if (method.getParameterTypes().length > 0) {
            continue;
          }

          attributeValue = method.invoke(obj, null);

          if (attributeValue == null) {
            continue;
          }

          log.debug("value.class: " + attributeValue.getClass());

          boolean isList = false;

          if (attributeValue.getClass().isArray()) {
            Object[] array = (Object[]) attributeValue;
            if (array.length == 0) {
              continue;
            }
            Object[] done = new Object[array.length];
            for (int i = 0; i < array.length; i++) {
              done[i] = bindToXML(array[i]);
            }
            attributeValue = done;

          } else if (ProportionKind.class.equals(attributeValue.getClass())) {

            ProportionKind kind = (ProportionKind) attributeValue;
            attributeValue = BigInteger.valueOf(kind.getValue());

          } else if (isOpenEHRRMClass(attributeValue)) {

            attributeValue = bindToXML(attributeValue);

          } else if (List.class.isAssignableFrom(attributeValue.getClass())) {

            isList = true;
            List list = (List) attributeValue;

            log.debug("list.size: " + list.size());

            String attributeName = getAttributeNameFromGetter(name);
            setterMethod = findSetter(attributeName, xmlClass, isList);

            Method addNew = findAddNew(attributeName, xmlClass);

            log.debug("setter: " + setterMethod.getName() + ", xmlClass: " + xmlClass);

            for (int i = 0, j = list.size() - 1; i <= j; i++) {
              Object value = list.get(i);

              Object[] array = new Object[2];

              addNew.invoke(xmlObj, null);

              array[0] = new Integer(i);
              array[1] = bindToXML(value);
              setterMethod.invoke(xmlObj, array);

              log.debug("list.member value set!!!!");
            }
          }

          if (!isList) {
            String attributeName = getAttributeNameFromGetter(name);

            log.debug(
                "attribute: "
                    + attributeName
                    + ", value("
                    + attributeValue
                    + "), "
                    + "type: "
                    + attributeValue.getClass());

            // TODO fix for mismatched attribute name in XSD and RM
            if ("nullFlavor".equals(attributeName)) {
              attributeName = "nullFlavour";
            }

            // skip function according to specs
            if ("isMerged".equals(attributeName)) {
              continue;
            }

            setterMethod = findSetter(attributeName, xmlClass, isList);

            if (setterMethod == null) {
              log.error(
                  "failed to find setterMethod for attribute: "
                      + attributeName
                      + " with type: "
                      + xmlClass);
              continue;
            }

            // special handling deals with 'real' typed
            // attributes in specs but typed 'float' in xsd
            String setter = setterMethod.getName();
            if ("setAccuracy".equals(setter)
                || "setDenominator".equals(setter)
                || "setNumerator".equals(setter)) {

              Double d = (Double) attributeValue;
              attributeValue = d.floatValue();
            }

            log.debug(
                "setter: "
                    + setterMethod.getName()
                    + ", xmlClass: "
                    + xmlClass
                    + ", attributeValue: "
                    + attributeValue
                    + ", attributeValue.class: "
                    + attributeValue.getClass());

            setterMethod.invoke(xmlObj, attributeValue);
          }
        }
      }

      return xmlObj;

    } catch (Exception e) {
      e.printStackTrace();
      throw new XMLBindingException(
          "exception caught when bind obj to " + className + ", " + e.getMessage());
    }
  }
Example #8
0
  public Type navigateParameterized(String name, Type[] params) throws OclTypeException {
    Type ret = Basic.navigateAnyParameterized(name, params);
    if (ret != null) return ret;

    Method foundmethod = null;

    // this is very similar to tudresden.ocl.lib.OclAnyImpl.findMethod
    // if you find a bug here, its probably there as well.

    // suprisingly one has not to go after interfaces since methods
    // inherited from interfaces are automatically included into the
    // implementing class. This does not happen for methods inherited
    // from the superclass, so we have to ascend to all superclasses.

    // unfortunately the above is only true for classes, getSuperclass invoked
    // on an interface returns null, regardless of the interfaces extended by the
    // interface. Therefore, we need to check out getInterfaces() if iclass is
    // an interface
    HashSet hsVisited = new HashSet();
    LinkedList llToVisit = new LinkedList();
    if (c.isInterface()) {
      // as we're dealing with actual instances, it can be assumed that Object is
      // a superclass
      llToVisit.add(java.lang.Object.class);
    }

    classloop:
    for (Class iclass = c; iclass != null; ) // iclass=iclass.getSuperclass())
    {
      Method[] methods = iclass.getDeclaredMethods();
      methodloop:
      for (int i = 0; i < methods.length; i++) {
        if (!name.equals(methods[i].getName())) continue methodloop;
        Class[] methodparams = methods[i].getParameterTypes();
        if (params.length != methodparams.length) continue methodloop;

        System.err.print("Checking method " + name + " (");
        for (int j = 0; j < methodparams.length; j++) {
          if (j != 0) {
            System.err.print(", ");
          }

          System.err.print(methodparams[j]);
        }
        System.err.println(")");

        for (int j = 0; j < params.length; j++)
          if (!params[j].conformsTo(getTypeForClass(methodparams[j]))) {
            System.err.println("No conformance for paramter # " + j);
            continue methodloop;
          }
        if (foundmethod == null) foundmethod = methods[i];
        else throw new OclTypeException("ambigious method " + name + " of " + c + ") queried.");
        break classloop;
      }

      // determine classes to be visited
      if (iclass.isInterface()) {
        Class[] ca = iclass.getInterfaces();
        for (int i = 0; i < ca.length; i++) {
          if (!hsVisited.contains(ca[i])) {
            llToVisit.add(ca[i]);
          }
        }
      } else {
        if (!hsVisited.contains(iclass.getSuperclass())) {
          llToVisit.add(iclass.getSuperclass());
        }
      }

      // mark current class visited
      hsVisited.add(iclass);

      // go to next class
      if (!llToVisit.isEmpty()) {
        iclass = (Class) llToVisit.remove(0);
      } else {
        iclass = null;
      }
    }

    if (foundmethod == null) {
      StringBuffer sb = new StringBuffer();
      sb.append(c.toString() + " has no method " + name + " with parameters (");
      for (int i = 0; i < params.length; i++) {
        if (i != 0) sb.append(", ");
        sb.append(params[i] + "/" + params[i]);
      }
      sb.append(")");
      throw new OclTypeException(sb.toString());
    }

    return getTypeForClass(foundmethod.getReturnType());
  }
Example #9
0
 @Override
 public int compare(Class o1, Class o2) {
   return o1.toString().compareTo(o2.toString());
 }
  private Operation parseMethod(Method method) {
    Operation operation = new Operation();

    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
    Class<?> responseClass = null;
    List<String> produces = new ArrayList<String>();
    List<String> consumes = new ArrayList<String>();
    String responseContainer = null;
    String operationId = method.getName();
    Map<String, Property> defaultResponseHeaders = null;
    Set<Map<String, Object>> customExtensions = null;

    ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);

    if (apiOperation.hidden()) return null;
    if (!"".equals(apiOperation.nickname())) operationId = apiOperation.nickname();

    defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());

    operation.summary(apiOperation.value()).description(apiOperation.notes());

    customExtensions = parseCustomExtensions(apiOperation.extensions());
    if (customExtensions != null) {
      for (Map<String, Object> extension : customExtensions) {
        if (extension != null) {
          for (Map.Entry<String, Object> map : extension.entrySet()) {
            operation.setVendorExtension(
                map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue());
          }
        }
      }
    }

    if (apiOperation.response() != null && !Void.class.equals(apiOperation.response()))
      responseClass = apiOperation.response();
    if (!"".equals(apiOperation.responseContainer()))
      responseContainer = apiOperation.responseContainer();

    /// security
    if (apiOperation.authorizations() != null) {
      List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
      for (Authorization auth : apiOperation.authorizations()) {
        if (auth.value() != null && !"".equals(auth.value())) {
          SecurityRequirement security = new SecurityRequirement();
          security.setName(auth.value());
          AuthorizationScope[] scopes = auth.scopes();
          for (AuthorizationScope scope : scopes) {
            if (scope.scope() != null && !"".equals(scope.scope())) {
              security.addScope(scope.scope());
            }
          }
          securities.add(security);
        }
      }
      if (securities.size() > 0) {
        for (SecurityRequirement sec : securities) operation.security(sec);
      }
    }

    if (responseClass == null) {
      // pick out response from method declaration
      LOG.info("picking up response class from method " + method);
      Type t = method.getGenericReturnType();
      responseClass = method.getReturnType();
      if (responseClass.equals(ResponseEntity.class)) {
        responseClass = getGenericSubtype(method.getReturnType(), method.getGenericReturnType());
      }
      if (!responseClass.equals(Void.class)
          && !"void".equals(responseClass.toString())
          && responseClass.getAnnotation(Api.class) == null) {
        LOG.info("reading model " + responseClass);
        Map<String, Model> models = ModelConverters.getInstance().readAll(t);
      }
    }
    if (responseClass != null
        && !responseClass.equals(Void.class)
        && !responseClass.equals(ResponseEntity.class)
        && responseClass.getAnnotation(Api.class) == null) {
      if (isPrimitive(responseClass)) {
        Property responseProperty = null;
        Property property = ModelConverters.getInstance().readAsProperty(responseClass);
        if (property != null) {
          if ("list".equalsIgnoreCase(responseContainer))
            responseProperty = new ArrayProperty(property);
          else if ("map".equalsIgnoreCase(responseContainer))
            responseProperty = new MapProperty(property);
          else responseProperty = property;
          operation.response(
              200,
              new Response()
                  .description("successful operation")
                  .schema(responseProperty)
                  .headers(defaultResponseHeaders));
        }
      } else if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString())) {
        Map<String, Model> models = ModelConverters.getInstance().read(responseClass);
        if (models.size() == 0) {
          Property pp = ModelConverters.getInstance().readAsProperty(responseClass);
          operation.response(
              200,
              new Response()
                  .description("successful operation")
                  .schema(pp)
                  .headers(defaultResponseHeaders));
        }
        for (String key : models.keySet()) {
          Property responseProperty = null;

          if ("list".equalsIgnoreCase(responseContainer))
            responseProperty = new ArrayProperty(new RefProperty().asDefault(key));
          else if ("map".equalsIgnoreCase(responseContainer))
            responseProperty = new MapProperty(new RefProperty().asDefault(key));
          else responseProperty = new RefProperty().asDefault(key);
          operation.response(
              200,
              new Response()
                  .description("successful operation")
                  .schema(responseProperty)
                  .headers(defaultResponseHeaders));
          swagger.model(key, models.get(key));
        }
        models = ModelConverters.getInstance().readAll(responseClass);
        for (String key : models.keySet()) {
          swagger.model(key, models.get(key));
        }
      }
    }

    operation.operationId(operationId);

    if (requestMapping.produces() != null) {
      for (String str : Arrays.asList(requestMapping.produces())) {
        if (!produces.contains(str)) {
          produces.add(str);
        }
      }
    }
    if (requestMapping.consumes() != null) {
      for (String str : Arrays.asList(requestMapping.consumes())) {
        if (!consumes.contains(str)) {
          consumes.add(str);
        }
      }
    }

    ApiResponses responseAnnotation = method.getAnnotation(ApiResponses.class);
    if (responseAnnotation != null) {
      updateApiResponse(operation, responseAnnotation);
    } else {
      ResponseStatus responseStatus = method.getAnnotation(ResponseStatus.class);
      if (responseStatus != null) {
        operation.response(
            responseStatus.value().value(), new Response().description(responseStatus.reason()));
      }
    }

    boolean isDeprecated = false;
    Deprecated annotation = method.getAnnotation(Deprecated.class);
    if (annotation != null) isDeprecated = true;

    boolean hidden = false;
    if (apiOperation != null) hidden = apiOperation.hidden();

    // process parameters
    Class[] parameterTypes = method.getParameterTypes();
    Type[] genericParameterTypes = method.getGenericParameterTypes();
    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    // paramTypes = method.getParameterTypes
    // genericParamTypes = method.getGenericParameterTypes
    for (int i = 0; i < parameterTypes.length; i++) {
      Type type = genericParameterTypes[i];
      List<Annotation> annotations = Arrays.asList(paramAnnotations[i]);
      List<Parameter> parameters = getParameters(type, annotations);

      for (Parameter parameter : parameters) {
        operation.parameter(parameter);
      }
    }

    if (operation.getResponses() == null) {
      operation.defaultResponse(new Response().description("successful operation"));
    }

    // Process @ApiImplicitParams
    this.readImplicitParameters(method, operation);

    return operation;
  }
Example #11
0
  /**
   * Generates code to convert a wrapped value type to a primitive type. Handles unwrapping
   * java.lang.Boolean, and java.lang.Number types. Generates the appropriate RETURN bytecode.
   */
  static void generateReturnResult(
      ClassFileWriter cfw, Class<?> retType, boolean callConvertResult) {
    // wrap boolean values with java.lang.Boolean, convert all other
    // primitive values to java.lang.Double.
    if (retType == Void.TYPE) {
      cfw.add(ByteCode.POP);
      cfw.add(ByteCode.RETURN);

    } else if (retType == Boolean.TYPE) {
      cfw.addInvoke(
          ByteCode.INVOKESTATIC, "aurora/javascript/Context", "toBoolean", "(Ljava/lang/Object;)Z");
      cfw.add(ByteCode.IRETURN);

    } else if (retType == Character.TYPE) {
      // characters are represented as strings in JavaScript.
      // return the first character.
      // first convert the value to a string if possible.
      cfw.addInvoke(
          ByteCode.INVOKESTATIC,
          "aurora/javascript/Context",
          "toString",
          "(Ljava/lang/Object;)Ljava/lang/String;");
      cfw.add(ByteCode.ICONST_0);
      cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/String", "charAt", "(I)C");
      cfw.add(ByteCode.IRETURN);

    } else if (retType.isPrimitive()) {
      cfw.addInvoke(
          ByteCode.INVOKESTATIC, "aurora/javascript/Context", "toNumber", "(Ljava/lang/Object;)D");
      String typeName = retType.getName();
      switch (typeName.charAt(0)) {
        case 'b':
        case 's':
        case 'i':
          cfw.add(ByteCode.D2I);
          cfw.add(ByteCode.IRETURN);
          break;
        case 'l':
          cfw.add(ByteCode.D2L);
          cfw.add(ByteCode.LRETURN);
          break;
        case 'f':
          cfw.add(ByteCode.D2F);
          cfw.add(ByteCode.FRETURN);
          break;
        case 'd':
          cfw.add(ByteCode.DRETURN);
          break;
        default:
          throw new RuntimeException("Unexpected return type " + retType.toString());
      }

    } else {
      String retTypeStr = retType.getName();
      if (callConvertResult) {
        cfw.addLoadConstant(retTypeStr);
        cfw.addInvoke(
            ByteCode.INVOKESTATIC,
            "java/lang/Class",
            "forName",
            "(Ljava/lang/String;)Ljava/lang/Class;");

        cfw.addInvoke(
            ByteCode.INVOKESTATIC,
            "aurora/javascript/JavaAdapter",
            "convertResult",
            "(Ljava/lang/Object;" + "Ljava/lang/Class;" + ")Ljava/lang/Object;");
      }
      // Now cast to return type
      cfw.add(ByteCode.CHECKCAST, retTypeStr);
      cfw.add(ByteCode.ARETURN);
    }
  }
 @Test
 public void testToString() throws Exception {
   for (Class<?> type : standardTypes) {
     assertThat(describe(type).toString(), is(type.toString()));
   }
 }