コード例 #1
2
 /**
  * Helper method to Perform Reflection to Get Static Field of Provided Type. Field is assumed
  * Private.
  *
  * @param fieldName
  * @param type
  * @return
  */
 public static <T> T getFieldFromReflection(
     String fieldName, Class<?> containingClass, Class<T> type) {
   try {
     Field desiredField = containingClass.getDeclaredField(fieldName);
     desiredField.setAccessible(true);
     return type.cast(desiredField.get(null));
   } catch (NoSuchFieldException e) {
     JASLog.log()
         .severe(
             "Obfuscation needs to be updated to access the %s %s. Please notify modmaker Immediately.",
             fieldName, type.getSimpleName());
     e.printStackTrace();
   } catch (IllegalArgumentException e) {
     JASLog.log()
         .severe(
             "Obfuscation needs to be updated to access the %s %s. Please notify modmaker Immediately.",
             fieldName, type.getSimpleName());
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     JASLog.log()
         .severe(
             "Obfuscation needs to be updated to access the %s %s. Please notify modmaker Immediately.",
             fieldName, type.getSimpleName());
     e.printStackTrace();
   } catch (SecurityException e) {
     JASLog.log()
         .severe(
             "Obfuscation needs to be updated to access the %s %s. Please notify modmaker Immediately.",
             fieldName, type.getSimpleName());
     e.printStackTrace();
   }
   return null;
 }
コード例 #2
1
 public static <T extends LanguageSourceSet> T create(
     Class<? extends LanguageSourceSet> publicType,
     Class<T> type,
     String name,
     String parentName,
     FileResolver fileResolver) {
   if (type.equals(BaseLanguageSourceSet.class)) {
     throw new ModelInstantiationException(
         "Cannot create instance of abstract class BaseLanguageSourceSet.");
   }
   nextSourceSetInfo.set(
       new SourceSetInfo(name, parentName, publicType.getSimpleName(), fileResolver));
   try {
     try {
       return DirectInstantiator.INSTANCE.newInstance(type);
     } catch (ObjectInstantiationException e) {
       throw new ModelInstantiationException(
           String.format(
               "Could not create LanguageSourceSet of type %s", publicType.getSimpleName()),
           e.getCause());
     }
   } finally {
     nextSourceSetInfo.set(null);
   }
 }
コード例 #3
1
ファイル: JPACommonDAO.java プロジェクト: orgranktest/webapp
  /*
   * Important! must return id in callback.
   */
  @SuppressWarnings("unchecked")
  public <T extends Serializable> void Walk(Class<T> type, Callback<T, Integer> callback) {
    int limit = 365;
    int count = 0;
    int nStartId = -1;

    List<T> models = null;
    while (true) {
      StringBuilder sb = new StringBuilder();
      sb.append("select m from ").append(type.getSimpleName()).append(" m");
      sb.append(" where m.id > :id order by m.id asc");
      Query query = entityManager.createQuery(sb.toString());
      query.setMaxResults(limit); // safe option.
      query.setParameter("id", nStartId);
      models = query.getResultList();

      if (null != models && models.size() > 0) {
        for (T model : models) {
          nStartId = callback.execute(model);

          // progress reporter
          if (count++ % 10000 == 0) {
            if (logger.isInfoEnabled()) {
              logger.info(String.format("walk %s, %d", type.getSimpleName(), count));
            }
          }
        }
      } else {
        break;
      }
    }
    models = null;
  }
 @Test
 public void should_generate_assertion_for_classes_in_package_using_provided_class_loader()
     throws Exception {
   ClassLoader customClassLoader =
       new MyClassLoader(Thread.currentThread().getContextClassLoader());
   Set<Class<?>> classes =
       collectClasses(customClassLoader, "org.assertj.assertions.generator.data");
   for (Class<?> clazz : classes) {
     assertThat(clazz.isAnonymousClass())
         .as("check that " + clazz.getSimpleName() + " is not anonymous")
         .isFalse();
     assertThat(clazz.isLocalClass())
         .as("check that " + clazz.getSimpleName() + " is not local")
         .isFalse();
     assertThat(isPublic(clazz.getModifiers()))
         .as("check that " + clazz.getSimpleName() + " is public")
         .isTrue();
     logger.info("Generating assertions for {}", clazz.getName());
     final ClassDescription classDescription = converter.convertToClassDescription(clazz);
     File customAssertionFile = assertionGenerator.generateCustomAssertionFor(classDescription);
     logger.info(
         "Generated {} assertions file -> {}",
         clazz.getSimpleName(),
         customAssertionFile.getAbsolutePath());
   }
 }
コード例 #5
1
ファイル: Move.java プロジェクト: jpollo/rcrss
  public void moveToShape(Collection<ShapeInArea> des, Class<? extends MoveType> type)
      throws SOSActionException {

    if (!(me.me() instanceof Human)) {
      log().warn("can't use move in Center Agent " + me + "\n");
      return;
    }
    try {
      checkTraffic(); // TODO uncomment
      MoveType mt = moves.get(type.hashCode());
      if (mt != null) {
        Path path = mt.getPathToShape(des);
        log().debug("MOVE " + type.getSimpleName() + "\nTO : " + path + "\n");
        move(path);
      } else log().error(new Error("in move can not found type=" + type.getSimpleName()));

    } catch (SOSActionException e) {
      throw e;
    } catch (Exception er) {
      log().error(er);
      log().warn("using bfs for finding path");
      ArrayList<Area> goals = new ArrayList<Area>();

      for (ShapeInArea shapeInArea : des) {
        goals.add(shapeInArea.getArea(me.model()));
      }
      move(bfs.breadthFirstSearch((Area) me.location(), goals));
    }
    log().error("in move can not found type=" + type.getSimpleName());
    me.problemRest("in move can not found type=" + type.getSimpleName());
  }
コード例 #6
1
ファイル: Convert.java プロジェクト: Osndok/javax-module
 private static String aOrAn(Class aClass) {
   if (aClass == int.class || aClass == Integer.class) {
     return "an " + aClass.getSimpleName();
   } else {
     return "a " + aClass.getSimpleName();
   }
 }
コード例 #7
0
ファイル: TikaCLI.java プロジェクト: slavianp/webscrap
  private void displayMetModels() {
    Class<?>[] modelClasses = Metadata.class.getInterfaces();
    Arrays.sort(
        modelClasses,
        new Comparator<Class<?>>() {
          public int compare(Class<?> o1, Class<?> o2) {
            return o1.getName().compareTo(o2.getName());
          }
        });

    for (Class<?> modelClass : modelClasses) {
      // we don't care about internal Tika met classes
      // if we do, then we can take this conditional out
      if (!modelClass.getSimpleName().contains("Tika")) {
        System.out.println(modelClass.getSimpleName());
        Field[] keyFields = modelClass.getFields();
        Arrays.sort(
            keyFields,
            new Comparator<Field>() {
              public int compare(Field o1, Field o2) {
                return o1.getName().compareTo(o2.getName());
              }
            });
        for (Field keyField : keyFields) {
          System.out.println(" " + keyField.getName());
        }
      }
    }
  }
コード例 #8
0
  public static void instantiateDownloaded(JLabel update) {
    // These are found in the downloadedListenerClasses list
    for (Class<?> clazz : downloadedListenerClasses) {
      ExternalListener instance;

      try {
        doUpdate(update, Messages.getString("NetworkTab.48") + " " + clazz.getSimpleName());
        postInstall(clazz);
        LOGGER.debug("do inst of " + clazz.getSimpleName());
        instance = (ExternalListener) clazz.newInstance();
        doUpdate(update, instance.name() + " " + Messages.getString("NetworkTab.49"));
        registerListener(instance);

        if (PMS.get().getFrame() instanceof LooksFrame) {
          LooksFrame frame = (LooksFrame) PMS.get().getFrame();

          if (!frame.getPt().appendPlugin(instance)) {
            LOGGER.warn("Plugin limit of 30 has been reached");
          }
        }
      } catch (InstantiationException | IllegalAccessException e) {
        LOGGER.error("Error instantiating plugin", e);
      }
    }

    downloadedListenerClasses.clear();
  }
コード例 #9
0
ファイル: DLNAHeader.java プロジェクト: ruipires/cling
  /**
   * Create a new instance of a {@link DLNAHeader} subtype that matches the given type and value.
   *
   * <p>This method iterates through all potential header subtype classes as declared in {@link
   * Type}. It creates a new instance of the subtype class and calls its {@link #setString(String)}
   * method. If no {@link org.fourthline.cling.model.message.header.InvalidHeaderException} is
   * thrown, the subtype instance is returned.
   *
   * @param type The type (or name) of the header.
   * @param headerValue The value of the header.
   * @return The best matching header subtype instance, or <code>null</code> if no subtype can be
   *     found.
   */
  public static DLNAHeader newInstance(DLNAHeader.Type type, String headerValue) {

    // Try all the UPnP headers and see if one matches our value parsers
    DLNAHeader upnpHeader = null;
    for (int i = 0; i < type.getHeaderTypes().length && upnpHeader == null; i++) {
      Class<? extends DLNAHeader> headerClass = type.getHeaderTypes()[i];
      try {
        log.finest("Trying to parse '" + type + "' with class: " + headerClass.getSimpleName());
        upnpHeader = headerClass.newInstance();
        if (headerValue != null) {
          upnpHeader.setString(headerValue);
        }
      } catch (InvalidHeaderException ex) {
        log.finest(
            "Invalid header value for tested type: "
                + headerClass.getSimpleName()
                + " - "
                + ex.getMessage());
        upnpHeader = null;
      } catch (Exception ex) {
        log.severe("Error instantiating header of type '" + type + "' with value: " + headerValue);
        log.log(Level.SEVERE, "Exception root cause: ", Exceptions.unwrap(ex));
      }
    }
    return upnpHeader;
  }
コード例 #10
0
ファイル: Reflections.java プロジェクト: yungoo/apple-qos
  /**
   * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
   *
   * <p>如public UserDao extends HibernateDao<User,Long>
   *
   * @param clazz clazz The class to introspect
   * @param index the Index of the generic ddeclaration,start from 0.
   * @return the index generic declaration, or Object.class if cannot be determined
   */
  @SuppressWarnings("rawtypes")
  public static Class getSuperClassGenricType(final Class clazz, final int index) {

    Type genType = clazz.getGenericSuperclass();

    if (!(genType.getClass().isAssignableFrom(ParameterizedType.class))) {
      log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
      return Object.class;
    }

    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

    if (index >= params.length || index < 0) {
      log.warn(
          "Index: "
              + index
              + ", Size of "
              + clazz.getSimpleName()
              + "'s Parameterized Type: "
              + params.length);
      return Object.class;
    }
    if (!(params[index].getClass().isAssignableFrom(Class.class))) {
      log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
      return Object.class;
    }

    return (Class) params[index];
  }
コード例 #11
0
ファイル: CachedData.java プロジェクト: kajar9/Plugin
 CachedDataType(Class<?> process) {
   try {
     this.process = (CachedDataProcess) process.newInstance();
   } catch (InstantiationException e) {
     Message.log(
         Level.SEVERE,
         "Error while instantiating a cache process! ("
             + process.getSimpleName()
             + " InstantiationException)");
     return;
   } catch (IllegalAccessException e) {
     Message.log(
         Level.SEVERE,
         "Error while instantiating a cache process! ("
             + process.getSimpleName()
             + " IllegalAccessException)");
     return;
   } catch (Exception e) {
     Message.log(
         Level.SEVERE,
         "Error while instantiating a cache process! ("
             + process.getSimpleName()
             + " "
             + e.getMessage()
             + ")");
     return;
   }
 }
コード例 #12
0
 @Test
 public void acceptedCommandsCanBeSerializedTest() throws Exception {
   Field commandsField = JaxbCommandsRequest.class.getDeclaredField("commands");
   XmlElements xmlElemsAnno = (XmlElements) commandsField.getAnnotations()[0];
   XmlElement[] xmlElems = xmlElemsAnno.value();
   Set<Class> cmdSet = new HashSet<Class>(AcceptedCommands.getSet());
   assertEquals(cmdSet.size(), xmlElems.length);
   Set<String> xmlElemNameSet = new HashSet<String>();
   for (XmlElement xmlElemAnno : xmlElems) {
     Class cmdClass = xmlElemAnno.type();
     String name = xmlElemAnno.name();
     assertTrue(name + " is used twice as a name.", xmlElemNameSet.add(name));
     assertTrue(
         cmdClass.getSimpleName()
             + " is present in "
             + JaxbCommandsRequest.class.getSimpleName()
             + " but not in "
             + AcceptedCommands.class.getSimpleName(),
         cmdSet.remove(cmdClass));
   }
   for (Class cmdClass : cmdSet) {
     System.out.println("Missing: " + cmdClass.getSimpleName());
   }
   assertTrue(
       "See output for classes in "
           + AcceptedCommands.class.getSimpleName()
           + " that are not in "
           + JaxbCommandsRequest.class.getSimpleName(),
       cmdSet.size() == 0);
 }
コード例 #13
0
 public static boolean isRetryableException(Throwable th) {
   if (th == null) {
     Log.debug(Log.FRAMEWORK, "isRetryableException Unknown exception !");
     return false;
   } else if (th instanceof JMSException) {
     Log.debug(Log.FRAMEWORK, "isRetryableException JMSException detected.");
     return true;
   } else if (th instanceof NameNotFoundException) {
     Log.debug(Log.FRAMEWORK, "isRetryableException:  NameNotFoundException catched");
     return true;
   } else if (th instanceof NestingException) {
     NestingException nex = (NestingException) th;
     Class nextedExceptionClass = nex.getNestedExceptionClass();
     if (NameNotFoundException.class
         .getSimpleName()
         .equals(nextedExceptionClass.getSimpleName())) {
       Log.debug(
           Log.FRAMEWORK,
           "isRetryableException: GT nestedException: NameNotFoundException catched");
       return true;
     } else if (JMSException.class.getSimpleName().equals(nextedExceptionClass.getSimpleName())) {
       Log.debug(Log.FRAMEWORK, "isRetryableException: GT nestedException: JMSException catched");
       return true;
     } else {
       return false;
     }
   } else {
     Throwable ex = th.getCause();
     return isRetryableException(ex);
   }
 }
コード例 #14
0
 private Method findServerMethod(Object cel, int performative) {
   Class c = cel.getClass();
   String performativeName = performativeNames[performative];
   String key = c.getSimpleName() + performativeName;
   // NOTE: cachedMethods is transient --> If the agent has just moved it must be recreated
   if (cachedMethods == null) {
     cachedMethods = new HashMap<String, Method>();
   }
   Method m = (Method) cachedMethods.get(key);
   if (m != null) {
     // Cache hit!
     return m;
   }
   // Note that we may have received a ContentElement that extends another one --> Possibly there
   // is no serving
   // method for the received ContentElement, but there is one for the parent ContentElement
   while (!c.equals(Object.class)) {
     String methodName = "serve" + c.getSimpleName() + performativeName;
     Class[] methodParamTypes = new Class[] {c, ACLMessage.class};
     try {
       m = serverDelegate.getClass().getMethod(methodName, methodParamTypes);
       cachedMethods.put(key, m);
       break;
     } catch (NoSuchMethodException nsme) {
       // Try with the ContentElement superclass
       c = c.getSuperclass();
     }
   }
   return m;
 }
コード例 #15
0
 @Override
 public <T extends ObjectType> PrismObject<T> getObject(
     Class<T> type,
     String oid,
     Collection<SelectorOptions<GetOperationOptions>> options,
     OperationResult parentResult)
     throws ObjectNotFoundException, SchemaException {
   if (!isCacheable(type) || !nullOrHarmlessOptions(options)) {
     log("Cache: PASS {} ({})", oid, type.getSimpleName());
     return repository.getObject(type, oid, options, parentResult);
   }
   Cache cache = getCache();
   if (cache == null) {
     log("Cache: NULL {} ({})", oid, type.getSimpleName());
   } else {
     PrismObject<T> object = (PrismObject) cache.getObject(oid);
     if (object != null) {
       // TODO: result?
       log("Cache: HIT {} ({})", oid, type.getSimpleName());
       return object.clone();
     }
     log("Cache: MISS {} ({})", oid, type.getSimpleName());
   }
   PrismObject<T> object = repository.getObject(type, oid, null, parentResult);
   cacheObject(cache, object);
   return object;
 }
コード例 #16
0
ファイル: Explorer.java プロジェクト: BreizhBeans/ThriftUI
  /**
   * For each method of the client which *looks like* a service invocation, get the necessary
   * instances in the structures map and fire the invoke.
   *
   * @param client the client to explore
   * @param structures the ParsedThrift structures to use
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  private static void runClient(TServiceClient client, HashMap<String, Object> structures)
      throws IllegalAccessException, InvocationTargetException {
    for (Method method : client.getClass().getDeclaredMethods()) {
      // for each method, retrieve its parameters
      // and invoke with default values.
      // Note that send_, recv_ and Client methods are
      // of no interest here (thrift internal plumbering).
      if (method.getName().startsWith("send_")
          || method.getName().startsWith("recv_")
          || method.getName().equalsIgnoreCase("Client")) {
        continue;
      }

      Class<?>[] parameters = method.getParameterTypes();
      int arraySize = parameters.length;
      Object[] defaults = new Object[arraySize];
      int i = 0;
      for (Class<?> parameter : parameters) {
        // if the parameter is a thrift structure,
        // we're likely to have it in our Map
        if (structures.containsKey(parameter.getSimpleName())) {
          defaults[i] = structures.get(parameter.getSimpleName());
        } else {
          // or it is a base type
          defaults[i] = Constants.defaultValue(parameter);
        }
        // or... we're screwed with the current
        // org.breizhbeans.thriftui.engine.reflection.Constants.getDefault().
        // TODO : unscrew ourselves.
        i++;
      }

      method.invoke(client, defaults);
    }
  }
コード例 #17
0
  @Override
  public <T extends ObjectType> SearchResultList<PrismObject<T>> searchObjects(
      Class<T> type,
      ObjectQuery query,
      Collection<SelectorOptions<GetOperationOptions>> options,
      OperationResult parentResult)
      throws SchemaException {
    if (!isCacheable(type) || !nullOrHarmlessOptions(options)) {
      log("Cache: PASS ({})", type.getSimpleName());
      return repository.searchObjects(type, query, options, parentResult);
    }
    Cache cache = getCache();
    if (cache == null) {
      log("Cache: NULL ({})", type.getSimpleName());
    } else {
      SearchResultList queryResult = cache.getQueryResult(type, query, prismContext);
      if (queryResult != null) {
        log("Cache: HIT {} ({})", query, type.getSimpleName());
        return queryResult.clone();
      }
      log("Cache: MISS {} ({})", query, type.getSimpleName());
    }

    // Cannot satisfy from cache, pass down to repository
    SearchResultList<PrismObject<T>> objects =
        repository.searchObjects(type, query, options, parentResult);
    if (cache != null && options == null) {
      for (PrismObject<T> object : objects) {
        cacheObject(cache, object);
      }
      cache.putQueryResult(type, query, objects, prismContext);
    }
    return objects;
  }
コード例 #18
0
  /**
   * 取得父类泛型的参数
   *
   * <pre>public UserDao extends HibernateDao<User,Long></pre>
   *
   * @param targetClass 要反射的目标对象
   * @param index 要反射的参数位置,从0开始计算
   * @return
   */
  public static Class<?> getSuperClassGenricType(final Class<?> targetClass, final int index) {
    Assert.notNull(targetClass, "targetClass不能为空");
    Type type = targetClass.getGenericSuperclass();
    if (!(type instanceof ParameterizedType)) {
      logger.warn("{}'s super class not parameterized type.", targetClass.getSimpleName());
      return Object.class;
    }

    // 泛型的列表
    Type[] argTypes = ((ParameterizedType) type).getActualTypeArguments();
    if (index < 0 || index > argTypes.length) {
      logger.warn(
          "index {} not range in {} parameter type length 0 - {}",
          index,
          targetClass.getSimpleName(),
          argTypes.length);
      return Object.class;
    }
    if (!(argTypes[index] instanceof Class<?>)) {
      logger.warn("{} not type of class", argTypes[index]);
      return Object.class;
    }

    // return argTypes[index].getClass();
    return (Class<?>) argTypes[index];
  }
コード例 #19
0
ファイル: Reflections.java プロジェクト: liyq1406/melonePos
  /**
   * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
   *
   * <p>如public UserDao extends HibernateDao<User,Long>
   *
   * @param clazz clazz The class to introspect
   * @param index the Index of the generic ddeclaration,start from 0.
   * @return the index generic declaration, or Object.class if cannot be determined
   */
  public static Class getClassGenricType(final Class clazz, final int index) {

    Type genType = clazz.getGenericSuperclass();

    if (!(genType instanceof ParameterizedType)) {
      logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
      return Object.class;
    }

    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

    if ((index >= params.length) || (index < 0)) {
      logger.warn(
          "Index: "
              + index
              + ", Size of "
              + clazz.getSimpleName()
              + "'s Parameterized Type: "
              + params.length);
      return Object.class;
    }
    if (!(params[index] instanceof Class)) {
      logger.warn(
          clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
      return Object.class;
    }

    return (Class) params[index];
  }
コード例 #20
0
ファイル: CasDoctor.java プロジェクト: jianlins/webanno
  public CasDoctor(Class<?>... aChecksRepairs) {
    // For testing
    StringBuilder checks = new StringBuilder();
    StringBuilder repairs = new StringBuilder();
    for (Class<?> clazz : aChecksRepairs) {
      boolean isCheck = Check.class.isAssignableFrom(clazz);
      boolean isRepair = Repair.class.isAssignableFrom(clazz);

      if (isCheck) {
        if (checks.length() > 0) {
          checks.append(',');
        }
        checks.append(clazz.getSimpleName());
      }

      if (isRepair) {
        if (repairs.length() > 0) {
          repairs.append(',');
        }
        repairs.append(clazz.getSimpleName());
      }

      if (!isCheck && !isRepair) {
        throw new IllegalArgumentException(
            "[" + clazz.getName() + "] is neither a check nor a repair");
      }
    }
    activeChecks = checks.toString();
    fatalChecks = false;

    activeRepairs = repairs.toString();

    afterPropertiesSet();
  }
コード例 #21
0
ファイル: Waiter.java プロジェクト: EvanRespaut/robotium
  /**
   * Waits for and returns a View.
   *
   * @param index the index of the view
   * @param classToFilterby the class to filter
   * @return the specified View
   */
  public <T extends View> T waitForAndGetView(int index, Class<T> classToFilterBy) {
    long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
    while (SystemClock.uptimeMillis() <= endTime
        && !waitForView(classToFilterBy, index, true, true)) ;
    int numberOfUniqueViews = searcher.getNumberOfUniqueViews();
    ArrayList<T> views =
        RobotiumUtils.removeInvisibleViews(viewFetcher.getCurrentViews(classToFilterBy));

    if (views.size() < numberOfUniqueViews) {
      int newIndex = index - (numberOfUniqueViews - views.size());
      if (newIndex >= 0) index = newIndex;
    }

    T view = null;
    try {
      view = views.get(index);
    } catch (IndexOutOfBoundsException exception) {
      int match = index + 1;
      if (match > 1) {
        Assert.fail(match + " " + classToFilterBy.getSimpleName() + "s" + " are not found!");
      } else {
        Assert.fail(classToFilterBy.getSimpleName() + " is not found!");
      }
    }
    views = null;
    return view;
  }
コード例 #22
0
ファイル: EntityUtil.java プロジェクト: vpcaiyc/gw
 public static Map<String, String> getEntityPropertiesToStringMap(
     Object entity, Map<String, String> fieldClassMapping, String... entityIdentifier) {
   Map<String, String> propertiesMap = new HashMap<String, String>();
   StringBuffer sb = new StringBuffer();
   if (entityIdentifier.length > 0) {
     for (String ei : entityIdentifier) {
       sb.append(ei + ".");
     }
   }
   String prefixStr = sb.toString();
   PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(entity.getClass());
   for (PropertyDescriptor pd : pds) {
     Method readMethod = pd.getReadMethod();
     if (null == readMethod) continue;
     Class<?> returnType = readMethod.getReturnType();
     Object returnValue = null;
     try {
       returnValue = readMethod.invoke(entity);
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (InvocationTargetException e) {
       e.printStackTrace();
     }
     if (null != returnValue) {
       String value = "";
       if (returnType.isAssignableFrom(Set.class)) {
         continue;
       } else if (isTenwaEntity(returnType)) {
         String fieldName = null;
         if (null != fieldClassMapping) {
           fieldName = fieldClassMapping.get(returnType.getSimpleName());
         }
         if (StringUtils.isBlank(fieldName)) {
           fieldName = "id";
         }
         Method method = BeanUtils.getPropertyDescriptor(returnType, fieldName).getReadMethod();
         // System.out.println("####:"+method.getName()+","+returnValue);
         try {
           value = StringUtil.nullToString(method.invoke(returnValue));
         } catch (IllegalArgumentException e) {
           e.printStackTrace();
         } catch (IllegalAccessException e) {
           e.printStackTrace();
         } catch (InvocationTargetException e) {
           e.printStackTrace();
         }
       } else {
         if (returnType.getSimpleName().equalsIgnoreCase("double")) {
           value = MathUtil.decimal((Double) returnValue, 8);
         } else {
           value = returnValue.toString();
         }
       }
       propertiesMap.put(prefixStr + pd.getName().toLowerCase(), value);
     }
   }
   return propertiesMap;
 }
コード例 #23
0
ファイル: DirectSkeleton.java プロジェクト: GEFFROY/Quercus
  static String getPortType(Class impl, Class api) throws WebServiceException {
    WebService webService = (WebService) impl.getAnnotation(WebService.class);

    if (webService != null) {
      if ("".equals(webService.name()) && "".equals(webService.endpointInterface()))
        return impl.getSimpleName();

      if (!"".equals(webService.name()) && "".equals(webService.endpointInterface()))
        return webService.name();

      if ("".equals(webService.name()) && !"".equals(webService.endpointInterface())) {
        webService = (WebService) api.getAnnotation(WebService.class);

        if (webService != null && !"".equals(webService.name())) return webService.name();
        else return api.getSimpleName();
      }

      if (!"".equals(webService.name()) && !"".equals(webService.endpointInterface()))
        throw new WebServiceException(
            L.l(
                "Cannot specify both name and endpointInterface properties in a WebService annotation: {0}",
                impl));
    }

    return impl.getSimpleName();
  }
コード例 #24
0
 @Override
 public List<T> findByField(Class<T> clazz, String field, Serializable value, String aSchema)
     throws PersistenceBusinessException {
   List<T> objects = null;
   EntityManager em = getEntityManager();
   String jpql = null;
   if (aSchema == null) {
     aSchema = "";
   } else {
     aSchema = aSchema + ".";
   }
   if (value != null) {
     jpql =
         "Select e from " + aSchema + clazz.getSimpleName() + " e where e." + field + " = :field";
   } else {
     jpql =
         "Select e from " + aSchema + clazz.getSimpleName() + " e where e." + field + " IS NULL";
   }
   try {
     TypedQuery<T> q = em.createQuery(jpql, clazz);
     if (value != null) {
       q.setParameter("field", value);
     }
     objects = q.getResultList();
   } catch (Exception e) {
     throw new PersistenceBusinessException(e);
   } finally {
     if (em != null) {
       em.close();
     }
   }
   return objects;
 }
コード例 #25
0
ファイル: Move.java プロジェクト: jpollo/rcrss
 public void moveXY(
     Collection<Pair<? extends Area, Point2D>> destinations, Class<? extends MoveType> type)
     throws SOSActionException {
   if (!(me.me() instanceof Human)) {
     log().warn("can't use move in Center Agent " + me + "\n");
     return;
   }
   try {
     checkTraffic();
     MoveType mt = moves.get(type.hashCode());
     if (mt != null) {
       Path path = mt.getPathToPoints(destinations);
       log().debug("MOVE XY" + type.getSimpleName() + "\nTO : " + path + "\n");
       move(path);
     } else log().error(new Error("in move can not found type=" + type.getSimpleName()));
   } catch (SOSActionException e) {
     throw e;
   } catch (Exception er) {
     log().error(er);
     log().warn("using bfs for finding path");
     move(bfs.breadthFirstSearchXY((Area) me.location(), destinations));
   }
   log().error("in move can not found type=" + type.getSimpleName());
   me.problemRest("in move can not found type=" + type.getSimpleName());
 }
コード例 #26
0
ファイル: OSchemaShared.java プロジェクト: jango2015/orientdb
  public OClass createClass(final Class<?> clazz) {
    OClass result;

    int[] clusterIds = null;
    int retry = 0;

    while (true)
      try {
        acquireSchemaWriteLock();
        try {
          // TODO: revisit this logic: interfaces should be also taken into concederation
          // TODO: Remove code duplication of this kind!
          final Class<?> superClass = clazz.getSuperclass();
          final OClass cls;
          if (superClass != null
              && superClass != Object.class
              && existsClass(superClass.getSimpleName()))
            cls = getClass(superClass.getSimpleName());
          else cls = null;

          result = doCreateClass(clazz.getSimpleName(), clusterIds, retry, cls);
          break;
        } finally {
          releaseSchemaWriteLock();
        }

      } catch (ClusterIdsAreEmptyException e) {
        clusterIds = createClusters(clazz.getSimpleName());
        retry++;
      }

    return result;
  }
    @Override
    public <T extends IBaseResource> T load(Class<T> theType, IIdType theId)
        throws ResourceNotFoundException {

      /*
       * The QuestionnaireResponse validator uses RI structures, so for now we need to convert between that and HAPI
       * structures. This is a bit hackish, but hopefully it will go away at some point.
       */
      if ("ValueSet".equals(theType.getSimpleName())) {
        IFhirResourceDao<ValueSet> dao = getDao(ValueSet.class);
        ValueSet in = dao.read(theId);
        String encoded = getContext().newJsonParser().encodeResourceToString(in);

        // TODO: this is temporary until structures-dstu2 catches up to structures-hl7org.dstu2
        encoded = encoded.replace("\"define\"", "\"codeSystem\"");

        return myRefImplCtx.newJsonParser().parseResource(theType, encoded);
      } else if ("Questionnaire".equals(theType.getSimpleName())) {
        IFhirResourceDao<Questionnaire> dao = getDao(Questionnaire.class);
        Questionnaire vs = dao.read(theId);
        return myRefImplCtx
            .newJsonParser()
            .parseResource(theType, getContext().newJsonParser().encodeResourceToString(vs));
      } else {
        // Should not happen, validator will only ask for these two
        throw new IllegalStateException("Unexpected request to load resource of type " + theType);
      }
    }
コード例 #28
0
ファイル: OSchemaShared.java プロジェクト: jango2015/orientdb
  @Override
  public OClass createAbstractClass(final Class<?> iClass) {
    OClass cls;
    int[] clusterIds = new int[] {-1};
    int retry = 0;

    while (true)
      try {
        acquireSchemaWriteLock();
        try {
          // TODO: revisit this logic: interfaces should be also taken into concederation
          final Class<?> superClass = iClass.getSuperclass();
          if (superClass != null
              && superClass != Object.class
              && existsClass(superClass.getSimpleName()))
            cls = getClass(superClass.getSimpleName());
          else cls = null;
          cls = doCreateClass(iClass.getSimpleName(), clusterIds, retry, cls);
        } finally {
          releaseSchemaWriteLock();
        }

        break;
      } catch (ClusterIdsAreEmptyException e) {
        clusterIds = createClusters(iClass.getSimpleName());
        retry++;
      }

    return cls;
  }
コード例 #29
0
  private static <T> T lookupMBean(
      final Map<String, String> props,
      final Class<T> type,
      final Predicate<T> tester,
      final long timeout) {
    long until = System.currentTimeMillis() + timeout;
    do
      try {
        final T bean = Mbeans.lookup(jdbcJmxDomain, props, type);
        tester.apply(bean);
        return bean;
      } catch (UndeclaredThrowableException e) {
        if (Exceptions.isCausedBy(e, InstanceNotFoundException.class)) {
          if (System.currentTimeMillis() < until) {
            try {
              TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e1) {
              Thread.interrupted();
              break;
            }
            LOG.debug("Waiting for MBean " + type.getSimpleName() + "/" + props);
            continue;
          }
          throw new NoSuchElementException(type.getSimpleName() + " " + props.toString());
        } else {
          throw Exceptions.toUndeclared(e);
        }
      }
    while (System.currentTimeMillis() < until);

    throw new NoSuchElementException(type.getSimpleName() + " " + props.toString());
  }
コード例 #30
0
ファイル: JavaWriter.java プロジェクト: SynBioDex/libSBOLj
  public void field(int modifiers, Class type, String name, String init, Class... annotations) {

    if (annotations != null && annotations.length > 0) {
      writer.println();
      for (Class annotation : annotations) {
        writer.println(String.format("%s@%s", indent(), annotation.getSimpleName()));
      }
      useClasses(annotations);
    }

    doIndent();
    printIfAccess(modifiers);
    printIfStatic(modifiers);

    writer.print(type.getSimpleName() + " ");
    writer.print(name);

    if (init != null) {
      if (isSubclass(type, String.class)) {
        writer.print(String.format(" = \"%s\";", init.replace("\"", "\\\"")));
      } else {
        writer.print(String.format(" = %s;", init));
      }
    }

    writer.println();

    useClasses(type);
  }