下面列出了org.apache.commons.lang3.ClassUtils#getClass ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private List<Class<?>> scanJaxrsClass() throws Exception {
try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAnnotationInfo().scan()) {
SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
"getClasses")) {
Path path = o.getAnnotation(Path.class);
JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
if (null != path && null != jaxrsDescribe) {
classes.add(o);
}
}
}
return classes;
}
}
private List<Class<?>> scanJaxrsClass(String name) throws Exception {
// String pack = "com." + name.replaceAll("_", ".");
String pack = "";
if (StringUtils.startsWith(name, "o2_")) {
pack = name.replaceAll("_", ".");
} else {
pack = "com." + name.replaceAll("_", ".");
}
try (ScanResult scanResult = new ClassGraph().whitelistPackages(pack).enableAllInfo().scan()) {
SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
"getClasses")) {
Path path = o.getAnnotation(Path.class);
JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
if (null != path && null != jaxrsDescribe) {
classes.add(o);
}
}
}
return classes;
}
}
private List<Class<?>> scanJaxrsClass() throws Exception {
try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAnnotationInfo().scan()) {
SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
"getClasses")) {
Path path = o.getAnnotation(Path.class);
JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
if (null != path && null != jaxrsDescribe) {
classes.add(o);
}
}
}
return classes;
}
}
private void setupAuthFilter(ServletContext servletContext, CoreSettings coreSettings) {
Settings authSettings = coreSettings.getAuthSettings();
String authProviderClassName = authSettings.get(CoreSettings.TAG_AUTH_PROVIDER, CoreSettings.class);
if (!StringHelper.isNullOrEmpty(authProviderClassName)) {
LOGGER.info("Turning on authentication.");
try {
Class<?> authConfigClass = ClassUtils.getClass(authProviderClassName);
if (AuthProvider.class.isAssignableFrom(authConfigClass)) {
Class<AuthProvider> filterConfigClass = (Class<AuthProvider>) authConfigClass;
AuthProvider filterConfigurator = filterConfigClass.getDeclaredConstructor().newInstance();
filterConfigurator.init(coreSettings);
filterConfigurator.addFilter(servletContext, coreSettings);
// If all went well, register the filter so it can upgrade its database.
coreSettings.addLiquibaseUser(filterConfigClass);
} else {
throw new IllegalArgumentException("Configured class does not implement AuthProvider.");
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
throw new IllegalArgumentException("Could not find or load auth class: " + authProviderClassName, ex);
}
}
}
public AuthWrapper(CoreSettings coreSettings, String authProviderClassName, String frostClientId) {
LOGGER.info("Initialising authentication.");
this.frostClientId = frostClientId;
Settings authSettings = coreSettings.getAuthSettings();
anonymousRead = authSettings.getBoolean(TAG_AUTH_ALLOW_ANON_READ, CoreSettings.class);
Map<AuthUtils.Role, String> roleMapping = AuthUtils.loadRoleMapping(authSettings);
roleRead = roleMapping.get(AuthUtils.Role.READ);
roleCeate = roleMapping.get(AuthUtils.Role.CREATE);
AuthProvider tempAuthProvider;
try {
Class<?> authConfigClass = ClassUtils.getClass(authProviderClassName);
if (AuthProvider.class.isAssignableFrom(authConfigClass)) {
Class<AuthProvider> filterConfigClass = (Class<AuthProvider>) authConfigClass;
tempAuthProvider = filterConfigClass.getDeclaredConstructor().newInstance();
tempAuthProvider.init(coreSettings);
} else {
LOGGER.error("Configured class does not implement AuthProvider: {}", authProviderClassName);
tempAuthProvider = AUTH_PROVIDER_DENY_ALL;
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException exc) {
LOGGER.error("Could not initialise auth class.", exc);
tempAuthProvider = AUTH_PROVIDER_DENY_ALL;
}
authProvider = tempAuthProvider;
}
@SuppressWarnings("unchecked")
@Override
public Object read(Kryo kryo, Input input, Class type) {
try {
ObjectMap graphContext = kryo.getGraphContext();
ObjectInputStream objectStream = (ObjectInputStream) graphContext.get(this);
if (objectStream == null) {
objectStream = new ObjectInputStream(input) {
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
return ClassUtils.getClass(KryoSerialization.class.getClassLoader(), desc.getName());
}
};
graphContext.put(this, objectStream);
}
return objectStream.readObject();
} catch (Exception ex) {
throw new KryoException("Error during Java deserialization.", ex);
}
}
@SuppressWarnings("unchecked")
protected void populatePageClasses(final Properties props) {
Enumeration<String> propNames = (Enumeration<String>) props.propertyNames();
while (propNames.hasMoreElements()) {
String className = propNames.nextElement();
if (className.startsWith("page.")) {
try {
Class<?> clazz = ClassUtils.getClass(props.getProperty(className));
if (BasePage.class.isAssignableFrom(clazz)) {
pageClasses.put(
StringUtils.substringAfter("page.", className), (Class<? extends BasePage>) clazz);
} else {
LOG.warn("{} does not extend {}, ignoring...", clazz.getName(), BasePage.class.getName());
}
} catch (ClassNotFoundException e) {
LOG.error("While looking for class identified by property '{}'", className, e);
}
}
}
}
/**
* Parses a string into a type. Returns null if it doesn't succeed.
* FIXME Only supports parameterized types with at most one type argument.
* Doesn't support wildcard types.
*
* TODO make a real parser someday
*/
private static Type parseType(String t) {
Matcher matcher = PARAM_TYPE_MATCHER.matcher(t.replaceAll("\\s+", ""));
if (matcher.matches()) {
String raw = matcher.group(1);
Type result;
try {
result = ClassUtils.getClass(raw);
} catch (ClassNotFoundException e) {
return null;
}
String param = matcher.group(3);
if (StringUtils.isNotBlank(param)) {
Type paramType = parseType(param);
if (paramType != null) {
result = TypeUtils.parameterize((Class) result, paramType);
}
}
String arrayDims = matcher.group(4);
if (StringUtils.isNotBlank(arrayDims)) {
int dimensions = StringUtils.countMatches(arrayDims, '[');
while (dimensions-- > 0) {
result = TypeUtils.genericArrayType(result);
}
}
return result;
}
return null;
}
/**
* 加载指定名称的类,并指定是否执行静态初始代码块
*
* @param className 类名
* @param initial true表示执行初始代码块,otherwise 不执行初始代码块
* @return 执行类名的Class对象
*/
public static Class<?> loadClass(String className, boolean initial) {
try {
Class<?> aClass = ClassUtils.getClass(className, initial);
return aClass;
} catch (ClassNotFoundException e) {
LOGGER.error(e.getMessage(), e);
return null;
}
}
public static Object getClass(String classname) {
try {
Class<?> cla = ClassUtils.getClass(getCurrentClassLoader(), classname);
return cla;
} catch (ClassNotFoundException e) {
return null;
}
}
/** Utility method to get an input stream to a class file */
public static InputStream getClassFileStream(String className) throws ClassNotFoundException {
Class<?> c = ClassUtils.getClass(className);
ClassLoader loader = c.getClassLoader();
if (loader == null) {
loader = ClassLoader.getSystemClassLoader();
while (loader != null && loader.getParent() != null) {
loader = loader.getParent();
}
}
if (loader == null) {
return null;
}
return loader.getResourceAsStream(c.getName().replace(".", "/") + ".class");
}
public Transformer(Map<String, byte[]> modifiedClassFiles) {
for (String className : modifiedClassFiles.keySet()) {
try {
Class<?> actualClass = ClassUtils.getClass(className);
classdata.put(actualClass, modifiedClassFiles.get(className));
} catch (ClassNotFoundException e) {
// If the class can't be found, just ignore it
log.warn("Unable to reload class " + className, e);
}
}
}
@Override
public boolean apply(@Nullable String s) {
if (s==null) return false;
if (preregisteredAutoType.containsKey(s)) return true;
try {
Class clazz = ClassUtils.getClass(s);
return DefaultSchemaMaker.class.isAssignableFrom(clazz);
} catch (ClassNotFoundException e) {
return false;
}
}
@SuppressWarnings("unchecked")
public static <T> Class<T> getClass(final String name) throws ClassNotFoundException {
try {
return (Class<T>) ClassUtils.getClass(name);
} catch (final Exception ex) {
return (Class<T>) Class.forName(name);
}
}
public void setValue(final Object value) throws ConfigurationRuntimeException
{
try
{
if (!(value instanceof String))
{
this.value = value;
return;
}
final String val = (String) value;
final String name = StringUtils.removeStartIgnoreCase(val, CLASS);
final Class<?> clazz = ClassUtils.getClass(name);
if (name.length() == val.length())
{
this.value = clazz.newInstance();
}
else
{
this.value = clazz;
}
}
catch (final Exception e)
{
throw new ConfigurationRuntimeException("Unable to create " + value, e);
}
}
public static Class loadClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
if (classLoader == null) {
classLoader = Thread.currentThread().getContextClassLoader();
}
return ClassUtils.getClass(classLoader, className);
}
@Override
public LocalServiceInvocationResult invoke(LocalServiceInvocation invocation) {
if (invocation == null) {
throw new IllegalArgumentException("Invocation is null");
}
LocalServiceInvocationResult result = new LocalServiceInvocationResult();
ClassLoader clientClassLoader = Thread.currentThread().getContextClassLoader();
try {
ClassLoader classLoader = target.getClass().getClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
String[] parameterTypeNames = invocation.getParameterTypeNames();
Class[] parameterTypes = new Class[parameterTypeNames.length];
for (int i = 0; i < parameterTypeNames.length; i++) {
Class<?> paramClass = ClassUtils.getClass(classLoader, parameterTypeNames[i]);
parameterTypes[i] = paramClass;
}
byte[][] argumentsData = invocation.getArgumentsData();
Object[] notSerializableArguments = invocation.getNotSerializableArguments();
Object[] arguments;
if (argumentsData == null) {
arguments = null;
} else {
arguments = new Object[argumentsData.length];
for (int i = 0; i < argumentsData.length; i++) {
if (argumentsData[i] == null) {
if (notSerializableArguments[i] == null) {
arguments[i] = null;
} else {
arguments[i] = notSerializableArguments[i];
}
} else {
arguments[i] = SerializationSupport.deserialize(argumentsData[i]);
}
}
}
SecurityContext targetSecurityContext = null;
if (invocation.getSessionId() != null) {
targetSecurityContext = new SecurityContext(invocation.getSessionId());
}
AppContext.setSecurityContext(targetSecurityContext);
if (invocation.getLocale() != null) {
Locale locale = Locale.forLanguageTag(invocation.getLocale());
UserInvocationContext.setRequestScopeInfo(invocation.getSessionId(), locale, invocation.getTimeZone(),
invocation.getAddress(), invocation.getClientInfo());
}
Method method = target.getClass().getMethod(invocation.getMethodName(), parameterTypes);
Object data = method.invoke(target, arguments);
if (invocation.canResultBypassSerialization()) {
result.setNotSerializableData(data);
} else {
result.setData(SerializationSupport.serialize(data));
}
return result;
} catch (Throwable t) {
if (t instanceof InvocationTargetException)
t = ((InvocationTargetException) t).getTargetException();
result.setException(SerializationSupport.serialize(t));
return result;
} finally {
Thread.currentThread().setContextClassLoader(clientClassLoader);
AppContext.setSecurityContext(null);
UserInvocationContext.clearRequestScopeInfo();
}
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void populateItem(final ListItem<ConnConfProperty> item) {
final ConnConfProperty property = item.getModelObject();
final String label = StringUtils.isBlank(property.getSchema().getDisplayName())
? property.getSchema().getName() : property.getSchema().getDisplayName();
final FieldPanel<? extends Serializable> field;
boolean required = false;
boolean isArray = false;
if (property.getSchema().isConfidential()
|| IdMConstants.GUARDED_STRING.equalsIgnoreCase(property.getSchema().getType())
|| IdMConstants.GUARDED_BYTE_ARRAY.equalsIgnoreCase(property.getSchema().getType())) {
field = new AjaxPasswordFieldPanel("panel", label, new Model<>(), false);
((PasswordTextField) field.getField()).setResetPassword(false);
required = property.getSchema().isRequired();
} else {
Class<?> propertySchemaClass;
try {
propertySchemaClass = ClassUtils.getClass(property.getSchema().getType());
if (ClassUtils.isPrimitiveOrWrapper(propertySchemaClass)) {
propertySchemaClass = ClassUtils.primitiveToWrapper(propertySchemaClass);
}
} catch (ClassNotFoundException e) {
LOG.error("Error parsing attribute type", e);
propertySchemaClass = String.class;
}
if (ClassUtils.isAssignable(Number.class, propertySchemaClass)) {
@SuppressWarnings("unchecked")
Class<Number> numberClass = (Class<Number>) propertySchemaClass;
field = new AjaxSpinnerFieldPanel.Builder<>().build("panel", label, numberClass, new Model<>());
required = property.getSchema().isRequired();
} else if (ClassUtils.isAssignable(Boolean.class, propertySchemaClass)) {
field = new AjaxCheckBoxPanel("panel", label, new Model<>());
} else {
field = new AjaxTextFieldPanel("panel", label, new Model<>());
required = property.getSchema().isRequired();
}
if (propertySchemaClass.isArray()) {
isArray = true;
}
}
field.setIndex(item.getIndex());
field.setTitle(property.getSchema().getHelpMessage(), true);
final AbstractFieldPanel<? extends Serializable> fieldPanel;
if (isArray) {
final MultiFieldPanel multiFieldPanel = new MultiFieldPanel.Builder(
new PropertyModel<>(property, "values")).setEventTemplate(true).build("panel", label, field);
item.add(multiFieldPanel);
fieldPanel = multiFieldPanel;
} else {
setNewFieldModel(field, property.getValues());
item.add(field);
fieldPanel = field;
}
if (required) {
fieldPanel.addRequiredLabel();
}
if (withOverridable) {
fieldPanel.showExternAction(addCheckboxToggle(property));
}
}
protected String formatValue(Object value, String parameterName, String fullParameterName, String stringFunction) {
checkThreadInterrupted();
String valueString;
String formatString = getFormatString(parameterName, fullParameterName);
if (formatString != null) {
if (Boolean.TRUE.equals(isGroovyScript(parameterName, fullParameterName))) {
valueString = scripting.evaluateGroovy(formatString, Collections.singletonMap(VALUE, value));
} else if (formatString.startsWith("class:")) {
String className = formatString.replaceFirst("class:", "");
ValueFormat valueFormat;
try {
Class<?> valueFormatterClass = ClassUtils.getClass(className);
valueFormat = (ValueFormat) ConstructorUtils.invokeConstructor(valueFormatterClass);
} catch (ReflectiveOperationException e) {
throw new ReportingException("An error occurred while applying custom format", e);
}
valueString = valueFormat.format(value);
} else if (value == null) {
valueString = "";
} else if (value instanceof Number) {
DecimalFormat decimalFormat = new DecimalFormat(formatString);
valueString = decimalFormat.format(value);
} else if (value instanceof Date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString);
valueString = dateFormat.format(value);
} else if (value instanceof TemporalAccessor) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatString);
valueString = dateTimeFormatter.format((TemporalAccessor) value);
} else if (value instanceof String && !formatString.startsWith("${")) {//do not use inliner alias as format string
valueString = String.format(formatString, value);
} else {
valueString = value.toString();
}
} else {
valueString = defaultFormat(value);
}
if (stringFunction != null) {
valueString = applyStringFunction(valueString, stringFunction);
}
return valueString != null ? valueString : "";
}
/**
* Returns a {@code java.lang.Class} object for the specified name.
* Because class loading can be tricky in some environments the code for
* retrieving a class by its name was extracted into this helper method. So
* if changes are necessary, they can be made at a single place.
*
* @param name the name of the class to be loaded
* @return the class object for the specified name
* @throws ClassNotFoundException if the class cannot be loaded
*/
static Class<?> loadClass(final String name) throws ClassNotFoundException
{
return ClassUtils.getClass(name);
}