@Override public String getId(Class<?> permissionClass) { String permission = permissionClass.getCanonicalName(); int firstFolderIndex = permission.indexOf("."); firstFolderIndex++; // remove dot too. return permissionClass.getCanonicalName().substring(firstFolderIndex); }
public void addToCache( Class<? extends Plugin> plugin, final RemoteManagerEndpoint manager, final DiscoveredPlugin src) { synchronized (this.cache) { // 1) get all managers providing this plugin HashMap<RemoteManagerEndpoint, Entry> managers = this.cache.get(plugin); if (null == managers) { // if we dont have one, so create managers = new HashMap<RemoteManagerEndpoint, Entry>(); managers.put(manager, new Entry(plugin.getCanonicalName(), manager, src)); this.cache.put(plugin, managers); return; } // 2) get the entry providing this plugin. Entry entry = managers.get(manager); if (null == entry) { // no entry managers.put(manager, new Entry(plugin.getCanonicalName(), manager, src)); return; } // 3) here it means we have already an entry... so skip!!! } }
/** * Overwrite this method if you want to filter the input, apply hashing, etc. * * @param feature the current feature. * @param document the current document. * @param featureFieldName the field hashFunctionsFileName of the feature. */ protected void addToDocument(LireFeature feature, Document document, String featureFieldName) { if (run == 0) { } // just count documents else if (run == 1) { // Select the representatives ... if (representativesID.contains(docCount) && feature .getClass() .getCanonicalName() .equals(featureClass.getCanonicalName())) { // it's a representative. // put it into a temporary data structure ... representatives.add(feature); } } else if (run == 2) { // actual hashing: find the nearest representatives and put those as a hash into a // document. if (feature .getClass() .getCanonicalName() .equals(featureClass.getCanonicalName())) { // it's a feature to be hashed int[] hashes = getHashes(feature); document.add( new TextField( featureFieldName + "_hash", createDocumentString(hashes, hashes.length), Field.Store.YES)); document.add( new TextField( featureFieldName + "_hash_q", createDocumentString(hashes, 10), Field.Store.YES)); } document.add(new StoredField(featureFieldName, feature.getByteArrayRepresentation())); } }
/** * Find a constructor in the class for the argument types. This method converts any checked * exception in unchecked exception. * * @param cls the class whos constructor will be found. * @param types the types of the parameters of the constructor. * @return the constructor of the given class which has the given parameter types. */ public static Constructor safeGetConstructor(Class cls, Class[] types) { try { return cls.getDeclaredConstructor(types); } catch (Exception ex) { logger.error( "Error while trying to find constructor for class " + cls.getCanonicalName(), ex); throw new RuntimeException( "Error while trying to find constructor for class " + cls.getCanonicalName(), ex); } }
public <T> T unwrap(Class<T> clazz) { if (!clazz.isAssignableFrom(nativeImpl.getClass())) throw new IllegalArgumentException( "HazelcastStore can't be unwrapped into " + clazz.getCanonicalName() + " instance"); return clazz.cast(nativeImpl); }
public final boolean assertInstanceOf(String $label, Class<?> $klass, Object $obj) { if ($obj == null) { $unitFailures++; $log.warn( messageFail( $label, "null is never an instance of anything, and certainly not " + $klass + "."), new AssertionFailed()); return false; } try { $klass.cast($obj); $log.debug( messagePass( $label, "\"" + $obj.getClass().getCanonicalName() + "\" is an instance of \"" + $klass.getCanonicalName() + "\"")); return true; } catch (ClassCastException $e) { $unitFailures++; $log.warn(messageFail($label, $e.getMessage() + "."), new AssertionFailed()); return false; } }
@Override public void serviceInit(Configuration conf) throws Exception { Constructor<?> cons; try { if (conf instanceof TajoConf) { this.conf = (TajoConf) conf; } else { throw new TajoInternalError("conf must be a TajoConf instance"); } Class<?> storeClass = this.conf.getClass(CatalogConstants.STORE_CLASS, DerbyStore.class); LOG.info("Catalog Store Class: " + storeClass.getCanonicalName()); cons = storeClass.getConstructor(new Class[] {Configuration.class}); this.store = (CatalogStore) cons.newInstance(this.conf); initBuiltinFunctions(builtingFuncs); } catch (Throwable t) { LOG.error("CatalogServer initialization failed", t); throw new TajoInternalError(t); } super.serviceInit(conf); }
@SuppressWarnings({"boxing", "unchecked"}) public void loadCache() { this.cache.clear(); try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(CACHE_FILE)); this.remoteDiscoveryImpl.syso("load cache"); try { final int cacheSize = (Integer) in.readObject(); // syso("size "+cacheSize); for (int i = 0; i < cacheSize; ++i) { HashMap<RemoteManagerEndpoint, Entry> rmee = new HashMap<RemoteManagerEndpoint, Entry>(); Class<? extends Plugin> plugin = (Class<? extends Plugin>) in.readObject(); this.remoteDiscoveryImpl.syso(plugin.getCanonicalName()); // syso("\t"+i+"'"+pluginName+"'"); int numEntries = (Integer) in.readObject(); // syso("\t"+numEntries); for (int j = 0; j < numEntries; ++j) { Entry entry = (Entry) in.readObject(); // syso("\t\t"+entry); rmee.put(entry.manager, entry); } this.cache.put(plugin, rmee); } } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { in.close(); } } catch (FileNotFoundException e) { this.remoteDiscoveryImpl.logger.warning("Loading cache file" + CACHE_FILE + " failed."); } catch (IOException e) { e.printStackTrace(); } }
public void apply() throws IllegalAccessException, InvocationTargetException, InstantiationException { if (type.isEnum()) { for (T instance : type.getEnumConstants()) { assertThat( instance.toString(), is( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "." + ((Enum<?>) instance).name())); } return; } for (Constructor<?> constructor : type.getDeclaredConstructors()) { if (constructor.isSynthetic() && skipSynthetic) { continue; } constructor.setAccessible(true); Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] actualArguments = new Object[parameterTypes.length]; Object[] otherArguments = new Object[parameterTypes.length]; int index = 0; for (Class<?> parameterType : parameterTypes) { putInstance(parameterType, actualArguments, otherArguments, index++); } int testIndex = 0; @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(actualArguments); assertThat(instance, is(instance)); assertThat(instance, not(is((Object) null))); assertThat(instance, not(is(new Object()))); Object similarInstance = constructor.newInstance(actualArguments); assertThat(instance.hashCode(), is(similarInstance.hashCode())); assertThat(instance, is(similarInstance)); if (skipToString) { assertThat(instance.toString(), notNullValue()); } else if (optionalToStringRegex == null) { checkString(instance); } else { assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex)); } for (Object otherArgument : otherArguments) { Object[] compareArguments = new Object[actualArguments.length]; int argumentIndex = 0; for (Object actualArgument : actualArguments) { if (argumentIndex == testIndex) { compareArguments[argumentIndex] = otherArgument; } else { compareArguments[argumentIndex] = actualArgument; } argumentIndex++; } Object unlikeInstance = constructor.newInstance(compareArguments); assertThat(instance.hashCode(), not(is(unlikeInstance))); assertThat(instance, not(is(unlikeInstance))); testIndex++; } } }
/** * Invoke a static method on a class and return the result without throwing exceptions. Just * Silently return null if something bad happens. * * @param cls the class in which to invoke the static method. * @param methodName the name of the method to be invoked. * @param args the arguments that will be sent to the method. * @return the result of the invocaiton (which may be null) or null if something goes wrong. * @since 1.2 */ public static Object invokeStaticMethod(Class cls, String methodName, Object[] args) { try { return MethodUtils.invokeStaticMethod(cls, methodName, args); } catch (Exception ex) { logger.error( "Got exception while trying to invoke static method: " + methodName + " on class: " + cls.getCanonicalName(), ex); return null; } }
private List<String> getIgnoreSignFieldNames(Class<? extends RopRequest> requestType) { if (logger.isDebugEnabled()) { logger.debug("获取" + requestType.getCanonicalName() + "需要签名的属性"); } final ArrayList<String> igoreSignFieldNames = new ArrayList<String>(10); ReflectionUtils.doWithFields( requestType, new ReflectionUtils.FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { igoreSignFieldNames.add(field.getName()); } }, new ReflectionUtils.FieldFilter() { public boolean matches(Field field) { IgnoreSign ignoreSign = field.getAnnotation(IgnoreSign.class); return ignoreSign != null; } }); if (logger.isDebugEnabled()) { logger.debug(requestType.getCanonicalName() + "需要签名的属性:" + igoreSignFieldNames.toString()); } return igoreSignFieldNames; }
private void checkString(T instance) { assertThat( instance.toString(), CoreMatchers.startsWith( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "{")); assertThat(instance.toString(), endsWith("}")); Class<?> currentType = type; do { for (Field field : type.getDeclaredFields()) { if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !ignoredFields.contains(field.getName())) { assertThat(instance.toString(), containsString(field.getName())); } } } while ((currentType = currentType.getSuperclass()) != Object.class); }
/** * Verifies that an object created from the given Class can be serialized to/from a JSON and the * resulting object is equal to the original. * * @param clazz - the Class to be verified * @throws InstantiationException, IllegalAccessException - if the object can't be instantiated */ public static <T> void verifySerialization(Class<T> clazz) throws InstantiationException, IllegalAccessException { T t = clazz.newInstance(); populateFields(clazz, t); String json = serialize(t); T newT = deserialize(json, clazz); String newJson = serialize(newT); // TODO: Verify that this is a good test. Assert.assertTrue( json.equals(newJson), "Pre and post serialization JSONs are not equal for class " + clazz.getCanonicalName()); }
/** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public void prettyLog(RedwoodChannels channels, String description) { Redwood.startTrack(description); // sort keys by class name List<Class> sortedKeys = new ArrayList<Class>(this.keySet()); Collections.sort(sortedKeys, (a, b) -> a.getCanonicalName().compareTo(b.getCanonicalName())); // log key/value pairs for (Class key : sortedKeys) { String keyName = key.getCanonicalName().replace("class ", ""); Object value = this.get(key); if (PrettyLogger.dispatchable(value)) { PrettyLogger.log(channels, keyName, value); } else { channels.logf("%s = %s", keyName, value); } } Redwood.endTrack(description); }
/** * Test the setter method for the provided property. This is a simple test to ensure that the * setter sets the value in the field. * * @param instance Instance of class to operate on. * @param property Property to validate. * @return Optional with message if error occurred, otherwise empty. */ private Optional<String> testSetter(T instance, PropertyDescriptor property) { if (property.getWriteMethod() == null) { return Optional.empty(); } try { Field field = declaredFields.get(property.getName()); if (field == null) { // This is a setter without a property. Nothing to test. return Optional.empty(); } Class<?> fieldType = field.getType(); field.setAccessible(true); PropertyValue val = PropertyValues.fromString(fieldType.getCanonicalName()); Optional<String> message = testSetterWithVal(instance, property, field, val.getValue()); if (message.isPresent()) return message; message = testSetterWithVal(instance, property, field, val.getSmallValue()); if (message.isPresent()) return message; message = testSetterWithVal(instance, property, field, val.getLargeValue()); if (message.isPresent()) return message; if (!fieldType.isPrimitive()) { message = testSetterWithVal(instance, property, field, val.getDefaultValue()); if (message.isPresent()) return message; } if (message.isPresent()) return message; } catch (Exception e) { throw new TestAidException( String.format( "Exception during setter test: %s.%s", getClassName(), property.getWriteMethod().getName()), e); } return Optional.empty(); }
private void load(Class<? extends Plugin> pluginClass, Properties properties) { // A plugin can be instantiated only once if (PLUGINS.containsKey(pluginClass)) { Application.LOGGER.error("Plugin for " + pluginClass + " is already loaded"); return; } Plugin plugin; try { plugin = pluginClass.newInstance(); } catch (InstantiationException e) { Application.LOGGER.error("Error while instantiating plugin from " + pluginClass, e); return; } catch (IllegalAccessException e) { Application.LOGGER.error( "Plugin class default constructor not accessible for " + pluginClass, e); return; } // register the plugin PLUGINS.put(pluginClass, plugin); // Load the properties if available if (properties != null) { plugin.name = properties.getProperty("plugin.name"); plugin.version = Version.parse(properties.getProperty("plugin.version")); plugin.description = properties.getProperty("plugin.description"); } else { // in case the application is loading the plugin directly plugin.name = pluginClass.getSimpleName(); plugin.version = null; plugin.description = null; } // Let the plugin initialize Application.LOGGER.trace( "Initializing Plugin - " + plugin.name + " - " + pluginClass.getCanonicalName()); plugin.onInit(app); }
@NotNull public static FqName fqNameByClass(@NotNull Class<?> clazz) { return new FqName(clazz.getCanonicalName()); }
/* PROTECTED METHODS */ protected void getBeanElements( Element parentElement, String objectName, String objectType, Object bean) throws IntrospectionException, IllegalAccessException { if (objectName == null) { // Get just the class name by lopping off the package name StringBuffer sb = new StringBuffer(bean.getClass().getName()); sb.delete(0, sb.lastIndexOf(".") + 1); objectName = sb.toString(); } // Check if the bean is a standard Java object type or a byte[] (encoded as a base 64 array) Element element = getStandardObjectElement(document, bean, objectName); // If the body element object is null then the bean is not a standard Java object type if (element != null) { if (includeNullValues || !element .getAttribute( NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + org.apache.axis.Constants.ATTR_TYPE) .equals("anyType")) { if (!includeTypeInfo) { element.removeAttribute( NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + org.apache.axis.Constants.ATTR_TYPE); element.removeAttribute(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null"); } parentElement.appendChild(element); } } else { // Analyze the bean Class classOfBean = null; if (bean != null) classOfBean = bean.getClass(); // If the object is an array, then serialize each of the beans in the array. if ((classOfBean != null) && (classOfBean.isArray())) { String[] arrayInfo = getXsdSoapArrayInfo(classOfBean.getCanonicalName(), nsPrefix); int arrayLen = Array.getLength(bean); StringBuffer arrayType = new StringBuffer(arrayInfo[1]); arrayType.insert(arrayType.indexOf("[]") + 1, arrayLen); if (objectName.charAt(objectName.length() - 1) == ';') objectName = new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString(); element = document.createElement(objectName); parentElement.appendChild(element); // Get the bean objects from the array and serialize each for (int i = 0; i < arrayLen; i++) { Object b = Array.get(bean, i); if (b != null) { String name = null; if (objectName.charAt(objectName.length() - 1) == 's') { name = formatName(objectName.substring(0, objectName.length() - 1)); } getBeanElements(element, name, b.getClass().getName(), b); } else { // Array element is null, so don't include it and decrement the # elements in the array int index = arrayType.indexOf("["); arrayType.replace(index + 1, index + 2, String.valueOf(--arrayLen)); } if (includeTypeInfo) { element.setAttributeNS( NamespaceConstants.NSURI_SCHEMA_XSI, NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE, NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":Array"); element.setAttributeNS( NamespaceConstants.NSURI_SOAP_ENCODING, NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE, arrayInfo[0] + ":" + arrayType.toString()); } } } else { int beanType = 0; String beanName = null; if (classOfBean != null) { if (classOfBean == Vector.class) { beanType = 1; beanName = "Vector"; } else if (classOfBean == ArrayList.class) { beanType = 2; beanName = "ArrayList"; } else if (classOfBean == LinkedList.class) { beanType = 3; beanName = "LinkedList"; } else if (classOfBean == Hashtable.class) { beanType = 4; beanName = "Hashtable"; } else if (classOfBean == Properties.class) { beanType = 5; beanName = "Properties"; } else if ((classOfBean == HashMap.class) || (classOfBean == SortedMap.class)) { beanType = 6; beanName = "Map"; } } if (beanType > 0) { String prefix = null; if ((beanType == 1) || (beanType == 5)) prefix = NamespaceConstants.NSPREFIX_SOAP_ENCODING; if (beanType == 6) prefix = Constants.NS_PREFIX_XMLSOAP; else prefix = DEFAULT_NS_PREFIX; element = document.createElement(objectName); if (includeTypeInfo) { element.setAttributeNS( NamespaceConstants.NSURI_SCHEMA_XSI, NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE, prefix + ":" + beanName); if (bean == null) element.setAttributeNS( NamespaceConstants.NSURI_SCHEMA_XSI, NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null", "true"); } parentElement.appendChild(element); if ((beanType >= 1) && (beanType <= 3)) { AbstractCollection collection = (AbstractCollection) bean; // Get the bean objects from the vector and serialize each Iterator it = collection.iterator(); while (it.hasNext()) { Object b = it.next(); String name = null; if (b != null) { if (objectName.charAt(objectName.length() - 1) == 's') { name = formatName(objectName.substring(0, objectName.length() - 1)); } else name = "item"; } getBeanElements(element, name, b.getClass().getName(), b); } } else if ((beanType == 4) || (beanType == 5)) { Hashtable hashtable = (Hashtable) bean; // Get the bean objects from the hashtable or properties and serialize each Enumeration en = hashtable.keys(); while (en.hasMoreElements()) { Object key = en.nextElement(); String keyClassName = key.getClass().getName(); Object value = hashtable.get(key); String beanClassName = null; if (value != null) beanClassName = value.getClass().getName(); Element itemElement = document.createElement("item"); element.appendChild(itemElement); getBeanElements(itemElement, "key", keyClassName, key); getBeanElements(itemElement, "value", beanClassName, value); } } else if (beanType == 6) { Map map = null; if (classOfBean == HashMap.class) map = (HashMap) bean; else if (classOfBean == SortedMap.class) map = (SortedMap) bean; // Get the bean objects from the hashmap and serialize each Set set = map.keySet(); Iterator it = set.iterator(); while (it.hasNext()) { Object key = it.next(); String keyClassName = key.getClass().getName(); Object value = map.get(key); String beanClassName = null; if (value != null) beanClassName = value.getClass().getName(); Element itemElement = document.createElement("item"); element.appendChild(itemElement); getBeanElements(itemElement, "key", keyClassName, key); getBeanElements(itemElement, "value", beanClassName, value); } } } else { // Create a parent element for this bean's properties if (objectName.charAt(objectName.length() - 1) == ';') objectName = new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString(); objectName = formatName(objectName); element = document.createElement(objectName); parentElement.appendChild(element); if (includeTypeInfo) { StringBuffer className = new StringBuffer(objectType); element.setAttributeNS( NamespaceConstants.NSURI_SCHEMA_XSI, NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE, nsPrefix + ":" + className.delete(0, className.lastIndexOf(".") + 1).toString()); } if (classOfBean != null) { // Get an array of property descriptors BeanInfo bi = Introspector.getBeanInfo(classOfBean); PropertyDescriptor[] pds = bi.getPropertyDescriptors(); // For each property of the bean, get a SOAPBodyElement that // represents the individual property. Append that SOAPBodyElement // to the class name element of the SOAP body. for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; getBeanElementProperties(element, bean, pd); } } else { if (includeTypeInfo) element.setAttributeNS( NamespaceConstants.NSURI_SCHEMA_XSI, NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null", "true"); } } } } }
@Test public void testCanonicalName() throws Exception { for (Class<?> type : standardTypes) { assertThat(describe(type).getCanonicalName(), is(type.getCanonicalName())); } }
// Helper method for loadDocuments() private Map<String, SpringResource> analyzeController( Class<?> clazz, Map<String, SpringResource> resourceMap, String description) throws ClassNotFoundException { String controllerCanonicalName = clazz.getCanonicalName(); String[] controllerRequestMappingValues = null; // Determine if we will use class-level requestmapping or dummy string if (clazz.getAnnotation(RequestMapping.class) != null && clazz.getAnnotation(RequestMapping.class).value() != null) { controllerRequestMappingValues = clazz.getAnnotation(RequestMapping.class).value(); } else { controllerRequestMappingValues = new String[1]; controllerRequestMappingValues[0] = ""; } // Iterate over all value attributes of the class-level RequestMapping annotation for (int i = 0; i < controllerRequestMappingValues.length; i++) { // Iterate over all methods inside the controller Method[] methods = clazz.getMethods(); for (Method method : methods) { RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class); // Look for method-level @RequestMapping annotation if (methodRequestMapping instanceof RequestMapping) { RequestMethod[] requestMappingRequestMethods = methodRequestMapping.method(); // For each method-level @RequestMapping annotation, iterate over HTTP Verb for (RequestMethod requestMappingRequestMethod : requestMappingRequestMethods) { String[] methodRequestMappingValues = methodRequestMapping.value(); // Check for cases where method-level @RequestMapping#value is not set, and use the // controllers @RequestMapping if (methodRequestMappingValues == null || methodRequestMappingValues.length == 0) { // The map key is a concat of the following: // 1. The controller package // 2. The controller class name // 3. The controller-level @RequestMapping#value String resourceKey = controllerCanonicalName + controllerRequestMappingValues[i] + requestMappingRequestMethod; if ((!(resourceMap.containsKey(resourceKey)))) { resourceMap.put( resourceKey, new SpringResource( clazz, controllerRequestMappingValues[i], resourceKey, description)); } resourceMap.get(resourceKey).addMethod(method); } else { // Here we know that method-level @RequestMapping#value is populated, so // iterate over all the @RequestMapping#value attributes, and add them to the resource // map. for (String methodRequestMappingValue : methodRequestMappingValues) { String resourceName = methodRequestMappingValue; // The map key is a concat of the following: // 1. The controller package // 2. The controller class name // 3. The controller-level @RequestMapping#value // 4. The method-level @RequestMapping#value // 5. The method-level @RequestMapping#method String resourceKey = controllerCanonicalName + controllerRequestMappingValues[i] + resourceName + requestMappingRequestMethod; if (!(resourceName.equals(""))) { if ((!(resourceMap.containsKey(resourceKey)))) { resourceMap.put( resourceKey, new SpringResource(clazz, resourceName, resourceKey, description)); } resourceMap.get(resourceKey).addMethod(method); } } } } } } } clazz.getFields(); clazz .getDeclaredFields(); // <--In case developer declares a field without an associated // getter/setter. // this will allow NoClassDefFoundError to be caught before it triggers bamboo failure. return resourceMap; }