/** * Gets credential selection predicate. * * @param selectionCriteria the selection criteria * @return the credential selection predicate */ public static Predicate<org.apereo.cas.authentication.Credential> newCredentialSelectionPredicate(final String selectionCriteria) { try { if (StringUtils.isBlank(selectionCriteria)) { return credential -> true; } if (selectionCriteria.endsWith(".groovy")) { final ResourceLoader loader = new DefaultResourceLoader(); final Resource resource = loader.getResource(selectionCriteria); if (resource != null) { final String script = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); final GroovyClassLoader classLoader = new GroovyClassLoader(Beans.class.getClassLoader(), new CompilerConfiguration(), true); final Class<Predicate> clz = classLoader.parseClass(script); return clz.newInstance(); } } final Class predicateClazz = ClassUtils.getClass(selectionCriteria); return (Predicate<org.apereo.cas.authentication.Credential>) predicateClazz.newInstance(); } catch (final Exception e) { final Predicate<String> predicate = Pattern.compile(selectionCriteria).asPredicate(); return credential -> predicate.test(credential.getId()); } }
private JdbcAnnotatedRepositoryQuery.Strategy chooseStrategy(JdbcQueryMethod method) { Class<?> returnType = method.getReturnedObjectType(); if (returnType.isPrimitive()) { returnType = ClassUtils.primitiveToWrapper(returnType); } // TODO think a better way of handling this by the method name if (Number.class.isAssignableFrom(returnType)) { return JdbcAnnotatedRepositoryQuery.Strategy.COUNT; } if (Boolean.class.isAssignableFrom(returnType)) { return JdbcAnnotatedRepositoryQuery.Strategy.EXISTS_QUERY; } if (method.isCollectionQuery()) { return JdbcAnnotatedRepositoryQuery.Strategy.COLLECTION_QUERY; } if (method.isQueryForEntity()) { return JdbcAnnotatedRepositoryQuery.Strategy.SINGLE_QUERY; } if (method.isPageQuery()) { return JdbcAnnotatedRepositoryQuery.Strategy.PAGE_QUERY; } if (void.class.isAssignableFrom(returnType)) { return JdbcAnnotatedRepositoryQuery.Strategy.UPDATE_QUERY; } throw new IllegalArgumentException("Don't know what strategy to follow!!"); }
@Override public JavaType handleUnknownTypeId(final DeserializationContext ctxt, final JavaType baseType, final String subTypeId, final TypeIdResolver idResolver, final String failureMsg) throws IOException { try { if (subTypeId.contains("org.jasig.")) { final String newTypeName = subTypeId.replaceAll("jasig", "apereo"); LOGGER.warn("Found legacy CAS JSON definition type identified as [{}]. " + "While CAS will attempt to convert the legacy definition to [{}] for the time being, " + "the definition SHOULD manually be upgraded to the new supported syntax", subTypeId, newTypeName); final Class newType = ClassUtils.getClass(newTypeName); return SimpleType.construct(newType); } return null; } catch (final Exception e) { throw Throwables.propagate(e); } }
private static MethodSpec getMethod(ClassName name, Key key) { Class<?> type = parseTypeFormat(key.getType(), key.getFormat()); if(type.isPrimitive()) { type = ClassUtils.primitiveToWrapper(type); } ParameterSpec parameter = ParameterSpec.builder(type, key.getId()).build(); return MethodSpec.methodBuilder(key.getId()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(parameter) .addStatement("this.$N = $N", key.getId(), parameter) .addJavadoc(key.getDescription()) .returns(name) .addStatement("return this") .build(); }
protected byte[] byteVectorToByteArray(Vector<?> _vector) { if (_vector == null) { return null; } if (_vector.isEmpty()) { return new byte[] {}; } if (!ClassUtils.isAssignable(byte.class, _vector.get(0).getClass())) { return null; } byte[] result = new byte[_vector.size()]; for (int i = 0; i < _vector.size(); i++) { Object x = _vector.get(i); result[i] = (byte) x; } return result; }
@SuppressWarnings("rawtypes") @Override public void scanToAutoEnable() { List<Object> autoEnabled = new ArrayList<>(); getScriptEngine().getBindings(ScriptContext.ENGINE_SCOPE).forEach((key, value) -> { Object evalResult = value != null ? eval(key + ".class") : null; if (evalResult != null && evalResult instanceof Class) { Class cls = (Class) evalResult; if (PROCESSOR_CLASSES.values().stream() .filter(processorClass -> !cls.equals(processorClass) && ClassUtils.isAssignable(cls, processorClass)).findFirst() .isPresent()) { if (!isProcessorAbstract(key)) { autoEnabled.add(key); ((NashornKnowledgeBaseEngineOperations) getEngineOperations()).enable(value); } } } }); if (logger.isDebugEnabled() && !autoEnabled.isEmpty()) { logger.debug("Auto-enabling: {}", autoEnabled); } }
@Override public void scanToAutoEnable() { List<String> autoEnabled = new ArrayList<>(); Stream.of(shell.getClassLoader().getLoadedClasses()).forEachOrdered(cls -> { if (PROCESSOR_CLASSES.values().stream().filter(processorClass -> ClassUtils.isAssignable(cls, processorClass)).findFirst() .isPresent()) { String name = cls.getName(); if (!isProcessorAbstract(name)) { autoEnabled.add(name); ((GroovyKnowledgeBaseEngineOperations) getEngineOperations()).enable(cls); } } }); if (logger.isDebugEnabled() && !autoEnabled.isEmpty()) { logger.debug("Auto-enabling: {}", autoEnabled); } }
@Override public void scanToAutoEnable() { List<String> autoEnabled = new ArrayList<>(); JvmClassMappingKt.getKotlinClass(getClass()).getNestedClasses().stream().filter(kclass -> !kclass.isAbstract()) .forEachOrdered(kclass -> { if (KotlinConstants.PROCESSOR_CLASSES.values().stream() .filter(processorClass -> ClassUtils.isAssignable(JvmClassMappingKt.getJavaClass(kclass), processorClass)) .findFirst().isPresent()) { autoEnabled.add(KotlinUtils.createProcessorName(kclass)); getEngineOperations().enable(kclass); } }); if (logger.isDebugEnabled() && !autoEnabled.isEmpty()) { logger.debug("Auto-enabling: {}", autoEnabled); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void scanToAutoEnable() { List<String> autoEnabled = new ArrayList<>(); Arrays.stream(getClass().getDeclaredClasses()).filter(cls -> !SpongeUtils.isAbstract(cls)).forEachOrdered(cls -> { if (JavaConstants.PROCESSOR_CLASSES.values().stream().filter(processorClass -> ClassUtils.isAssignable(cls, processorClass)) .findFirst().isPresent()) { autoEnabled.add(cls.getName()); getEngineOperations().enableJava((Class<? extends Processor>) cls); } }); if (logger.isDebugEnabled() && !autoEnabled.isEmpty()) { logger.debug("Auto-enabling: {}", autoEnabled); } }
@SuppressWarnings("unchecked") @Override public void onStartup() { if (server == null) { logger.info("Creating and starting the Py4J Server."); GatewayServerBuilder builder = new GatewayServerBuilder().javaPort(getJavaPort()).entryPoint(getEngine().getOperations()); if (getSecurity() != null) { SSLContext sslContext = createSslContext(); builder.serverSocketFactory(sslContext.getServerSocketFactory()); } server = build(builder); server.start(); } else { logger.info("Using the manually created Py4J Server. Note that the server should have already been started."); } if (getFacadeInterfaceName() != null) { try { setFacade((T) server.getPythonServerEntryPoint(new Class[] { ClassUtils.getClass(getFacadeInterfaceName()) })); } catch (Exception e) { throw SpongeUtils.wrapException(e); } } }
private void checkCast(Castable castable) { String internalNameOfCast = castable.getInternalName(); if (castable.getType().isPrimitive()) { Class<?> wrapperType = ClassUtils.primitiveToWrapper(castable.getType()); internalNameOfCast = Type.getInternalName(wrapperType); } mv.visitTypeInsn(CHECKCAST, internalNameOfCast); if (castable.getType().isPrimitive()) { mv.visitMethodInsn( INVOKEVIRTUAL, internalNameOfCast, castable.getType().getName() + "Value", "()" + castable.getDescriptor(), false); } }
private static JsonElement createVOInputTypeNode(Class inputType, Type genericType) throws Exception { // no input maps: if (isTerminalType(inputType)) { return new JsonPrimitive(ClassUtils.getSimpleName(inputType)); } else { boolean isCollection = Collection.class.isAssignableFrom(inputType); if (isCollection) { try { inputType = (Class) ((ParameterizedType) genericType).getActualTypeArguments()[0]; } catch (Exception e) { inputType = Object.class; } } Collection<Method> fields = AssociationPath.listMethods(inputType, VO_METHOD_TRANSFILTER); if (isTerminalType(inputType) || fields.size() == 0) { return markMapCollection(new JsonPrimitive(ClassUtils.getSimpleName(inputType)), null, false, isCollection); } else { return markMapCollection(createVONode(fields, true), null, false, isCollection); } } }
private static JsonObject createVONode(Collection<Method> fields, boolean recursive) throws Exception { JsonObject voNode = new JsonObject(); if (fields != null) { Iterator<Method> it = fields.iterator(); while (it.hasNext()) { Method field = it.next(); String fieldName = VO_METHOD_TRANSFILTER.transform(field.getName()); if (recursive) { voNode.add(fieldName, createVOReturnTypeNode(field.getReturnType(), field.getGenericReturnType())); } else { voNode.addProperty(fieldName, ClassUtils.getSimpleName(field.getReturnType())); } } } return voNode; }
/** * 拼装 短异常类名: 异常信息 <-- RootCause的短异常类名: 异常信息 */ public static String toStringWithRootCause(@Nullable Throwable t) { if (t == null) { return StringUtils.EMPTY; } final String clsName = ClassUtils.getShortClassName(t, null); final String message = StringUtils.defaultString(t.getMessage()); Throwable cause = getRootCause(t); StringBuilder sb = new StringBuilder(128).append(clsName).append(": ").append(message); if (cause != t) { sb.append("; <---").append(toStringWithShortName(cause)); } return sb.toString(); }
/** * 找出所有标注了该annotation的公共方法(含父类的公共函数),循环其接口. * * 暂未支持Spring风格Annotation继承Annotation * * 另,如果子类重载父类的公共函数,父类函数上的annotation不会继承,只有接口上的annotation会被继承. */ public static <T extends Annotation> Set<Method> getAnnotatedPublicMethods(Class<?> clazz, Class<T> annotation) { // 已递归到Objebt.class, 停止递归 if (Object.class.equals(clazz)) { return Collections.emptySet(); } List<Class<?>> ifcs = ClassUtils.getAllInterfaces(clazz); Set<Method> annotatedMethods = new HashSet<Method>(); // 遍历当前类的所有公共方法 Method[] methods = clazz.getMethods(); for (Method method : methods) { // 如果当前方法有标注,或定义了该方法的所有接口有标注 if (method.getAnnotation(annotation) != null || searchOnInterfaces(method, annotation, ifcs)) { annotatedMethods.add(method); } } return annotatedMethods; }
public String objToString(Object value) { final StringBuilder buf = new StringBuilder(); for (Field f : value.getClass().getDeclaredFields()) { f.setAccessible(true); try { buf.append("\"" + f.getName() + "\": "); if (ClassUtils.isPrimitiveOrWrapper(value.getClass()) || value instanceof String) { buf.append("\"" + value + "\""); } else { buf.append(valueToString(f.get(value))); } buf.append(", "); } catch (IllegalArgumentException | IllegalAccessException e) { // Silently ignore errors e.printStackTrace(); } } buf.replace(buf.length() - 2, buf.length(), ""); return buf.toString(); }
public String listToString(Collection<?> list) { final StringBuilder buf = new StringBuilder(); buf.append("'["); if (!list.isEmpty()) { for (Object o : list) { if (ClassUtils.isPrimitiveOrWrapper(o.getClass()) || o instanceof String) { buf.append("\"" + o + "\""); } else { buf.append(valueToString(o)); } buf.append(", "); } buf.replace(buf.length() - 2, buf.length(), ""); } buf.append("]'"); return buf.toString(); }
public String mapToString(Map<?, ?> map) { final StringBuilder buf = new StringBuilder(); buf.append("{"); if (!map.isEmpty()) { for (Entry<?, ?> o : map.entrySet()) { final Object v = o.getValue(); if (v != null) { buf.append("'" + o.getKey() + "': "); if (ClassUtils.isPrimitiveOrWrapper(v.getClass()) || v instanceof String) { buf.append("'" + v + "'"); } else { buf.append(valueToString(v)); } buf.append(", "); } } buf.replace(buf.length() - 2, buf.length(), ""); } buf.append("}"); return buf.toString(); }
private Object init(Class<?> clazz) { Object o = null; try { if(ClassUtils.isAssignable(clazz, ScriptListener.class)) { o = clazz.newInstance(); _listeners.add((ScriptListener)o); } } catch(Exception e) { _log.error("", e); } return o; }
private Number symmetric(Number value) { final Class<?> wrapper = ClassUtils.primitiveToWrapper(value.getClass()); if(Integer.class.equals(wrapper)) { return -value.intValue(); } else if(Short.class.equals(wrapper)) { return -value.shortValue(); } else if(Float.class.equals(wrapper)) { return -value.floatValue(); } else if(Double.class.equals(wrapper)) { return -value.doubleValue(); } else if(Long.class.equals(wrapper)) { return -value.longValue(); } else { throw new NumberFormatException(value + "is not in a valid format"); } }
private Number inverse(Number value) { final Class<?> wrapper = ClassUtils.primitiveToWrapper(value.getClass()); if(Integer.class.equals(wrapper)) { return 1.0/value.intValue(); } else if(Short.class.equals(wrapper)) { return 1.0/value.shortValue(); } else if(Float.class.equals(wrapper)) { return 1/value.floatValue(); } else if(Double.class.equals(wrapper)) { return 1/value.doubleValue(); } else if(Long.class.equals(wrapper)) { return 1.0/value.longValue(); } else { throw new NumberFormatException(value + "is not in a valid format"); } }
/** * returns full qualified class name * (inner & outer class) * * @param p_package package name * @param p_outerclass1 outer class readed value * @param p_outerclass2 outer class fixed value * @param p_innerclass inner class * @param p_label label (only firat element is used) * @return full-qualified class name */ private static String buildlabel( final String p_package, final String p_outerclass1, final String p_outerclass2, final String p_innerclass, final String p_label ) { final String l_outerclass = p_outerclass1.equals( p_outerclass2 ) ? p_outerclass1 : MessageFormat.format( "{0}{1}{2}", p_outerclass1, ClassUtils.PACKAGE_SEPARATOR, p_outerclass2 ); return MessageFormat.format( "{0}{1}{2}{3}{4}{5}", p_package, ClassUtils.PACKAGE_SEPARATOR, l_outerclass, p_innerclass.isEmpty() ? "" : ClassUtils.PACKAGE_SEPARATOR, p_innerclass, p_label.isEmpty() ? "" : CLASSSEPARATOR + p_label ); }
@Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { log.error("Unexpected errs occurred in handle request.", ex); // if handler is instance of HandlerMethod then it's a http request, // otherwise it's a websocket request or other service. if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; boolean returnResponseEntity = ClassUtils.isAssignable(handlerMethod.getMethod().getReturnType(), ResponseEntity.class); boolean hasResponseBodyAnnotation = Objects.nonNull(handlerMethod.getMethodAnnotation(ResponseBody.class)); if (returnResponseEntity || hasResponseBodyAnnotation) { return new ModelAndView(new RedirectView(view5xx)); } else { return new ModelAndView(new RedirectView(ajax5xx)); } } return null; }
public static <T extends Model> boolean isOfType(Class<T> modelClass, String fqn) { if (modelClass == null) return false; Class<T> clazz = getModelInterface(modelClass); if (clazz != null && clazz.getName().equals(fqn)) return true; List<Class<?>> interfaces = ClassUtils.getAllInterfaces(modelClass); if (interfaces != null && !interfaces.isEmpty()) { for (Class<?> interf : interfaces) { if (interf.getName().equals(fqn)) return true; } } return false; }
/** * Creates a new sharded DAO. The number of managed shards and bucketing is controlled by the {@link ShardManager}. * * @param sessionFactories a session provider for each shard */ public LookupDao(List<SessionFactory> sessionFactories, Class<T> entityClass, ShardManager shardManager, BucketIdExtractor<String> bucketIdExtractor) { this.shardManager = shardManager; this.bucketIdExtractor = bucketIdExtractor; this.daos = sessionFactories.stream().map(LookupDaoPriv::new).collect(Collectors.toList()); this.entityClass = entityClass; Field fields[] = FieldUtils.getFieldsWithAnnotation(entityClass, LookupKey.class); Preconditions.checkArgument(fields.length != 0, "At least one field needs to be sharding key"); Preconditions.checkArgument(fields.length == 1, "Only one field can be sharding key"); keyField = fields[0]; if(!keyField.isAccessible()) { try { keyField.setAccessible(true); } catch (SecurityException e) { log.error("Error making key field accessible please use a public method and mark that as LookupKey", e); throw new IllegalArgumentException("Invalid class, DAO cannot be created.", e); } } Preconditions.checkArgument(ClassUtils.isAssignable(keyField.getType(), String.class), "Key field must be a string"); }
/** * Returns the ConfigInstances classes from the annotation on the given Service class , * including the ConfigInstances annotated on any of its super classes. * NOTE: Only the super classes that are subclass of Service are inspected. */ private static Stream<Class<? extends ConfigInstance>> getConfigInstancesFromServiceAnnotations(Class<? extends Service> serviceClass) { List<Class<?>> classHierarchy = ClassUtils.getAllSuperclasses(serviceClass); classHierarchy.add(serviceClass); return classHierarchy.stream() .filter(Service.class::isAssignableFrom) .filter(clazz -> clazz.isAnnotationPresent(RestartConfigs.class)) .map(clazz -> { RestartConfigs annotation = clazz.getDeclaredAnnotation(RestartConfigs.class); if (annotation.value().length == 0) { throw new IllegalStateException(String.format( "%s has a %s annotation with no ConfigInstances given as argument.", clazz.getSimpleName(), RestartConfigs.class.getSimpleName())); } return annotation; }) .map(RestartConfigs::value) .flatMap(Arrays::stream) .distinct(); }
/** * Call a class constructor with an integer parameter * @param className name of the class to be constructed * @param parameter the value to be used in the constructor * @return an instance of the class * @throws JMeterException if class cannot be created */ public static Object construct(String className, int parameter) throws JMeterException { Object instance = null; try { Class<?> clazz = ClassUtils.getClass(className); Constructor<?> constructor = clazz.getConstructor(Integer.TYPE); instance = constructor.newInstance(Integer.valueOf(parameter)); } catch (ClassNotFoundException | InvocationTargetException | IllegalArgumentException | NoSuchMethodException | SecurityException | IllegalAccessException | InstantiationException e) { throw new JMeterException(e); } return instance; }
/** * Create getters for the key and time fields and setters for the include fields. */ private void generateSettersAndGetters() { for (int i = 0; i < 2; i++) { Class inputClass = inputFieldObjects[i].inputClass; try { inputFieldObjects[i].keyGet = PojoUtils.createGetter(inputClass, keyFieldExpressions.get(i), Object.class); if (timeFields != null && timeFields.size() == 2) { Class timeField = ClassUtils.primitiveToWrapper(inputClass.getDeclaredField(timeFields.get(i)).getType()); inputFieldObjects[i].timeFieldGet = PojoUtils.createGetter(inputClass, timeFields.get(i), timeField); } for (int j = 0; j < includeFields[i].length; j++) { Class inputField = ClassUtils.primitiveToWrapper(inputClass.getDeclaredField(includeFields[i][j]).getType()); Class outputField = ClassUtils.primitiveToWrapper(outputClass.getDeclaredField(includeFields[i][j]).getType()); if (inputField != outputField) { continue; } inputFieldObjects[i].fieldMap.put(PojoUtils.createGetter(inputClass, includeFields[i][j], inputField), PojoUtils.createSetter(outputClass, includeFields[i][j], outputField)); } } catch (NoSuchFieldException e) { throw new RuntimeException(e); } } }
/** * * * @param className . * @param property . * * @return . */ @Override public String getPropertyType(String className, String property) { Class<?> clazz; try { clazz = ClassUtils.getClass(className); BeanWrapper bw = new BeanWrapperImpl(clazz); return bw.getPropertyType(property).getName(); } catch (ClassNotFoundException e) { LOG.error("Oops", e); } return null; }
private void injectValueInFirstArg(List<SlimAssertion> assertions, boolean not, Object contentToCheck) { SlimAssertion.getInstructions(assertions).forEach(instruction -> { try { String valueToInject = FitnesseMarkup.SELECTOR_VALUE_SEPARATOR + (not ? FitnesseMarkup.SELECTOR_VALUE_DENY_INDICATOR : StringUtils.EMPTY) + contentToCheck; Object args = FieldUtils.readField(instruction, SeleniumScriptTable.CALL_INSTRUCTION_ARGS_FIELD, true); Object[] argsToInject; if (args instanceof Object[] && ArrayUtils.getLength(args) > NumberUtils.INTEGER_ZERO) { argsToInject = (Object[]) args; argsToInject[NumberUtils.INTEGER_ZERO] += valueToInject; } else { argsToInject = ArrayUtils.toArray(valueToInject); } String methodName = Objects.toString(FieldUtils.readField(instruction, SeleniumScriptTable.CALL_INSTRUCTION_METHODNAME_FIELD, true)); if (Objects.isNull(MethodUtils.getAccessibleMethod(SeleniumFixture.class, Objects.toString(methodName), ClassUtils.toClass(argsToInject)))) { SeleniumScriptTable.LOGGER.fine("Method for instruction not found on SeleniumFixture, injection aborted: " + instruction); return; } FieldUtils.writeField(instruction, SeleniumScriptTable.CALL_INSTRUCTION_ARGS_FIELD, argsToInject, true); } catch (IllegalArgumentException | ReflectiveOperationException e) { SeleniumScriptTable.LOGGER.log(Level.FINE, "Failed to inject check value using reflection", e); } }); }
protected static <T> T buildComponent(Class<T> componentClass, Supplier<T> defaultSupplier, Object ... args) { List<String> componentClassNames = SpringFactoriesLoader.loadFactoryNames(componentClass, AbstractCrigttApplicationRunListener.class.getClassLoader()); if (componentClassNames.isEmpty()) { return defaultSupplier.get(); } List<Class<?>> componentClasses = ClassUtils.convertClassNamesToClasses(componentClassNames); componentClasses.sort(AnnotationAwareOrderComparator.INSTANCE); Class<?> primaryComponentClass = componentClasses.get(0); try { return componentClass.cast(ConstructorUtils.invokeConstructor(primaryComponentClass, args)); } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { throw new ApplicationContextException(String.format("Unable to instantiate component (class=%s).", primaryComponentClass.getName()), e); } }
/** * Gets the number of steps required to promote a primitive number to another * type. * * @param srcClass the (primitive) source class * @param destClass the (primitive) destination class * @return The cost of promoting the primitive */ private static float getPrimitivePromotionCost(final Class<?> srcClass, final Class<?> destClass) { float cost = 0.0f; Class<?> cls = srcClass; if (!cls.isPrimitive()) { // slight unwrapping penalty cost += 0.1f; cls = ClassUtils.wrapperToPrimitive(cls); } for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) { if (cls == ORDERED_PRIMITIVE_TYPES[i]) { cost += 0.1f; if (i < ORDERED_PRIMITIVE_TYPES.length - 1) { cls = ORDERED_PRIMITIVE_TYPES[i + 1]; } } } return cost; }
@Test public void classUtilsDemo() { System.out.println(genHeader("ClassUtilsDemo")); System.out.println("获取类实现的所有接口."); System.out.println(ClassUtils.getAllInterfaces(Date.class)); System.out.println("获取类所有父类."); System.out.println(ClassUtils.getAllSuperclasses(Date.class)); System.out.println("获取简单类名."); System.out.println(ClassUtils.getShortClassName(Date.class)); System.out.println("获取包名."); System.out.println(ClassUtils.getPackageName(Date.class)); System.out.println("判断是否可以转型."); System.out.println(ClassUtils.isAssignable(Date.class, Object.class)); System.out.println(ClassUtils.isAssignable(Object.class, Date.class)); }
/** * Returns the value of the object getter it there is any for the wrapped java object. * * @param key Key that should be searched using the object getter. * @return Value of the property of the wrapped java object */ protected Object objectGetterGet(Object key) { Method method = null; Object result = Scriptable.NOT_FOUND; if (object instanceof ObjectGetter) { Object value = ((ObjectGetter)object).get(key); try { method = ClassUtils.getPublicMethod(objectClass, ObjectGetter.METHOD_NAME, ObjectGetter.METHOD_ARG_TYPES); } catch (Exception e) { throw new InternalException(e); } if (value != ObjectGetter.UNDEFINED_VALUE) { result = value; } } if (result != Scriptable.NOT_FOUND && method != null) { //result = new JavaMethodRedirectedWrapper(result, object, method); } return result; }
@SuppressWarnings("unchecked") @Override public T getValue() { Object value = storedValue; if (propertyValueEvaluator != null) { value = propertyValueEvaluator.evaluate(this, storedValue); } // else not evaluator so return the storedValue // try to convert the String to the enum if (value instanceof String) { try { Class<T> enumClass = (Class<T>) ClassUtils.getClass(getType()); return Enum.valueOf(enumClass, (String) value); } catch (ClassNotFoundException e) { TalendRuntimeException.unexpectedException(e); } } return (T) value; }
/** * Retrieves the sensor enrichment configuration from the function arguments. The manner * of retrieving the configuration can differ based on what the user passes in. * @param args The function arguments. * @param position The position from which the configuration will be extracted. * @return The sensor enrichment configuration. */ private static SensorEnrichmentConfig getSensorEnrichmentConfig(List<Object> args, int position) { Object arg0 = Util.getArg(position, Object.class, args); SensorEnrichmentConfig config = new SensorEnrichmentConfig(); if(arg0 instanceof String) { // deserialize the configuration from json String json = Util.getArg(0, String.class, args); if(json != null) { config = (SensorEnrichmentConfig) ENRICHMENT.deserialize(json); } } else if(arg0 instanceof ThreatTriageProcessor) { // extract the configuration from the engine ThreatTriageProcessor engine = Util.getArg(0, ThreatTriageProcessor.class, args); config = engine.getSensorConfig(); } else { // unexpected type throw new IllegalArgumentException(String.format("Unexpected type: got '%s'", ClassUtils.getShortClassName(arg0, "null"))); } return config; }
public AnnotationEditorExtensionRegistryImpl( @Autowired(required = false) List<AnnotationEditorExtension> aExtensions) { if (aExtensions != null) { OrderComparator.sort(aExtensions); for (AnnotationEditorExtension ext : aExtensions) { log.info("Found annotation editor extension: {}", ClassUtils.getAbbreviatedName(ext.getClass(), 20)); } extensions = Collections.unmodifiableList(aExtensions); } else { extensions = Collections.emptyList(); } }
@Override public void init() { SdcctBeanDefinitionParser beanDefParser; for (Class<?> beanDefClass : ClassUtils .convertClassNamesToClasses(SpringFactoriesLoader.loadFactoryNames(SdcctBeanDefinitionParser.class, this.getClass().getClassLoader()))) { try { beanDefParser = ((SdcctBeanDefinitionParser) ConstructorUtils.invokeConstructor(beanDefClass, this)); } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { throw new ApplicationContextException(String.format("Unable to instantiate bean definition parser (class=%s).", beanDefClass.getName()), e); } for (String beanDefParserElemLocalName : beanDefParser.getElementBeanClasses().keySet()) { this.beanDefParsers.put(beanDefParserElemLocalName, beanDefParser); this.registerBeanDefinitionParser(beanDefParserElemLocalName, beanDefParser); } } }
/** * Gets a message or messages from the function arguments. * * @param arg The function argument containing the message(s). * @return A list of messages */ private List<JSONObject> getMessages(Object arg) { List<JSONObject> messages; if (arg instanceof String) { messages = getMessagesFromString((String) arg); } else if (arg instanceof Iterable) { messages = getMessagesFromIterable((Iterable<String>) arg); } else if (arg instanceof JSONObject) { messages = Collections.singletonList((JSONObject) arg); } else { throw new IllegalArgumentException(format("invalid message: found '%s', expected String, List, or JSONObject", ClassUtils.getShortClassName(arg, "null"))); } return messages; }