/** * Adapts the source object to a view object. * * @param mapper An action that is invoked for each source object in the graph that is to be * adapted. The action can influence how the source object is adapted via the provided {@link * SourceObjectMapping}. */ public <T, S> T adapt( Class<T> targetType, S sourceObject, Action<? super SourceObjectMapping> mapper) { if (sourceObject == null) { return null; } Class<? extends T> wrapperType = targetTypeProvider.getTargetType(targetType, sourceObject); DefaultSourceObjectMapping mapping = new DefaultSourceObjectMapping(sourceObject, targetType, wrapperType); mapper.execute(mapping); wrapperType = mapping.wrapperType.asSubclass(targetType); if (wrapperType.isInstance(sourceObject)) { return wrapperType.cast(sourceObject); } if (targetType.isEnum()) { return adaptToEnum(targetType, sourceObject); } MixInMethodInvoker mixInMethodInvoker = null; if (mapping.mixInType != null) { mixInMethodInvoker = new MixInMethodInvoker( mapping.mixInType, new AdaptingMethodInvoker(mapper, new ReflectionMethodInvoker())); } MethodInvoker overrideInvoker = chainInvokers(mixInMethodInvoker, mapping.overrideInvoker); Object proxy = Proxy.newProxyInstance( wrapperType.getClassLoader(), new Class<?>[] {wrapperType}, new InvocationHandlerImpl(sourceObject, overrideInvoker, mapper)); if (mixInMethodInvoker != null) { mixInMethodInvoker.setProxy(proxy); } return wrapperType.cast(proxy); }
/** A clean way to specify which tests run on which platforms. */ public boolean isPlatformSupported(DatabasePlatform platform) { boolean supported = false; boolean notSupported = false; if ((unsupportedPlatforms == null) && (supportedPlatforms == null)) { return true; } if (supportedPlatforms != null) { for (Iterator iterator = supportedPlatforms.iterator(); iterator.hasNext(); ) { Class platformClass = (Class) iterator.next(); if (platformClass.isInstance(platform)) { supported = true; } } } else { supported = true; } if (unsupportedPlatforms != null) { for (Iterator iterator = unsupportedPlatforms.iterator(); iterator.hasNext(); ) { Class platformClass = (Class) iterator.next(); if (platformClass.isInstance(platform)) { notSupported = true; } } } return supported && (!notSupported); }
public static <T> T createFromArg(Class<T> clz, Object value) { if (value == null) { return null; } ClassMeta meta = ClassMeta.classMeta(clz); List<ConstructorAccess> constructors = meta.oneArgumentConstructors(); if (constructors.size() == 0) { return null; } else if (constructors.size() == 1) { ConstructorAccess constructorAccess = constructors.get(0); Class<?> arg1Type = constructorAccess.parameterTypes()[0]; if (arg1Type.isInstance(value)) { return (T) constructorAccess.create(value); } else { return (T) constructorAccess.create(coerce(arg1Type, value)); } } else { for (ConstructorAccess c : constructors) { Class<?> arg1Type = c.parameterTypes()[0]; if (arg1Type.isInstance(value)) { return (T) c.create(value); } } for (ConstructorAccess c : constructors) { Class<?> arg1Type = c.parameterTypes()[0]; if (arg1Type.isAssignableFrom(value.getClass())) { return (T) c.create(value); } } } return null; }
public <T extends Anim> void clearanims(Class<T> type) { for (Iterator<Anim> i = nanims.iterator(); i.hasNext(); ) { Anim a = i.next(); if (type.isInstance(a)) i.remove(); } for (Iterator<Anim> i = anims.iterator(); i.hasNext(); ) { Anim a = i.next(); if (type.isInstance(a)) i.remove(); } }
public <T> T unwrap(Class<T> clazz) { if (clazz.isInstance(this)) { return clazz.cast(this); } if (clazz.isInstance(OptiqSchema.this)) { return clazz.cast(OptiqSchema.this); } if (clazz.isInstance(OptiqSchema.this.schema)) { return clazz.cast(OptiqSchema.this.schema); } throw new ClassCastException("not a " + clazz); }
private static void netxsurgery() throws Exception { /* Force off NetX codebase classloading. */ Class<?> nxc; try { nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e1) { try { nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e2) { throw (new Exception("No known NetX on classpath")); } } ClassLoader cl = MainFrame.class.getClassLoader(); if (!nxc.isInstance(cl)) { throw (new Exception("Not running from a NetX classloader")); } Field cblf, lf; try { cblf = nxc.getDeclaredField("codeBaseLoader"); lf = nxc.getDeclaredField("loaders"); } catch (NoSuchFieldException e) { throw (new Exception("JNLPClassLoader does not conform to its known structure")); } cblf.setAccessible(true); lf.setAccessible(true); Set<Object> loaders = new HashSet<Object>(); Stack<Object> open = new Stack<Object>(); open.push(cl); while (!open.empty()) { Object cur = open.pop(); if (loaders.contains(cur)) continue; loaders.add(cur); Object curl; try { curl = lf.get(cur); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } for (int i = 0; i < Array.getLength(curl); i++) { Object other = Array.get(curl, i); if (nxc.isInstance(other)) open.push(other); } } for (Object cur : loaders) { try { cblf.set(cur, null); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } } }
public Map getBeansOfType(Class clazz, boolean includePrototypes, boolean allowEagerInit) throws BeansException { Map<String, Object> result = new HashMap<String, Object>(); Set<ControllerContext> contexts = kernelController.getContexts(clazz, ControllerState.INSTALLED); for (ControllerContext context : contexts) { Object target = context.getTarget(); result.put(context.getName().toString(), target); } if (includePrototypes) { Set<ControllerContext> factories = kernelController.getInstantiatedContexts(AbstractBeanFactory.class); if (factories != null && factories.isEmpty() == false) { for (ControllerContext kcc : factories) { Class<?> prototypeClass = getPrototypeClass(kcc); if (prototypeClass != null) { if (clazz.isAssignableFrom(prototypeClass)) result.put(kcc.getName().toString(), createBean(kcc.getTarget())); } else if (allowEagerInit) { Object bean = createBean(kcc.getTarget()); if (clazz.isInstance(bean)) result.put(kcc.getName().toString(), bean); } } } } return result; }
/** * Set the object to be edited. * * @param value The object to be edited. */ public void setObject(Object value) { if (!(_type.isInstance(value))) { throw new IllegalArgumentException(value.getClass() + " is not of type " + _type); } _value = value; // Disable event generation. _squelchChangeEvents = true; // Iterate over each property, doing a lookup on the associated editor // and setting the editor's value to the value of the property. Iterator it = _prop2Editor.keySet().iterator(); while (it.hasNext()) { PropertyDescriptor desc = (PropertyDescriptor) it.next(); PropertyEditor editor = (PropertyEditor) _prop2Editor.get(desc); Method reader = desc.getReadMethod(); if (reader != null) { try { Object val = reader.invoke(_value, null); editor.setValue(val); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.getTargetException().printStackTrace(); } } } // Enable event generation. _squelchChangeEvents = false; }
/** * Gets a component associated with the given parameter name. First search the component in * property table, then try to get component by name from the manager, then creates component with * default properties. * * @param name the parameter name * @return the component associated with the name * @throws edu.cmu.sphinx.util.props.PropertyException if the component does not exist or is of * the wrong type. */ public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); Configurable configurable = null; S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class<? extends Configurable> expectedType = s4Component.type(); Object propVal = propValues.get(name); if (propVal != null && propVal instanceof Configurable) { return (Configurable) propVal; } if (propVal != null && propVal instanceof String) { PropertySheet ps = cm.getPropertySheet(flattenProp(name)); if (ps != null) configurable = ps.getOwner(); else throw new InternalConfigurationException( getInstanceName(), name, "component '" + flattenProp(name) + "' is missing"); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException( getInstanceName(), name, "mismatch between annotation and component type"); if (configurable != null) { propValues.put(name, configurable); return configurable; } configurable = getComponentFromAnnotation(name, s4Component); propValues.put(name, configurable); return configurable; }
public String[] getBeanNamesForType( Class clazz, boolean includePrototypes, boolean allowEagerInit) { List<String> result = new ArrayList<String>(); Set<ControllerContext> contexts = kernelController.getInstantiatedContexts(clazz); if (contexts != null && contexts.isEmpty() == false) { for (ControllerContext context : contexts) { result.add(context.getName().toString()); } } if (includePrototypes) { Set<ControllerContext> factories = kernelController.getInstantiatedContexts(AbstractBeanFactory.class); if (factories != null && factories.isEmpty() == false) { for (ControllerContext kcc : factories) { Class<?> prototypeClass = getPrototypeClass(kcc); if (prototypeClass != null) { if (clazz.isAssignableFrom(prototypeClass)) result.add(kcc.getName().toString()); } else if (allowEagerInit) { Object bean = createBean(kcc.getTarget()); if (clazz.isInstance(bean)) result.add(kcc.getName().toString()); } } } } return result.toArray(new String[result.size()]); }
public ICFLibAnyObj getObjQualifier(Class qualifyingClass) { ICFLibAnyObj container = this; if (qualifyingClass != null) { while (container != null) { if (container instanceof ICFSecurityClusterObj) { break; } else if (container instanceof ICFSecurityTenantObj) { break; } else if (qualifyingClass.isInstance(container)) { break; } container = container.getObjScope(); } } else { while (container != null) { if (container instanceof ICFSecurityClusterObj) { break; } else if (container instanceof ICFSecurityTenantObj) { break; } container = container.getObjScope(); } } return (container); }
private void checkForEmptyAndDuplicatedNames( MyNode rootNode, String prefix, String title, Class<? extends NamedConfigurable> configurableClass, boolean recursively) throws ConfigurationException { final Set<String> names = new HashSet<String>(); for (int i = 0; i < rootNode.getChildCount(); i++) { final MyNode node = (MyNode) rootNode.getChildAt(i); final NamedConfigurable scopeConfigurable = node.getConfigurable(); if (configurableClass.isInstance(scopeConfigurable)) { final String name = scopeConfigurable.getDisplayName(); if (name.trim().length() == 0) { selectNodeInTree(node); throw new ConfigurationException("Name should contain non-space characters"); } if (names.contains(name)) { final NamedConfigurable selectedConfigurable = getSelectedConfigurable(); if (selectedConfigurable == null || !Comparing.strEqual(selectedConfigurable.getDisplayName(), name)) { selectNodeInTree(node); } throw new ConfigurationException( CommonBundle.message("smth.already.exist.error.message", prefix, name), title); } names.add(name); } if (recursively) { checkForEmptyAndDuplicatedNames(node, prefix, title, configurableClass, true); } } }
protected final AbstractAudioChunk findChunk(List<AbstractAudioChunk> chunks, Class c) { for (Iterator<AbstractAudioChunk> i = chunks.iterator(); i.hasNext(); ) { AbstractAudioChunk chunk = i.next(); if (c.isInstance(chunk)) return chunk; } return null; }
@SuppressWarnings("unchecked") @Nullable public static <T> T getToolWindowElement( @NotNull Class<T> clazz, @NotNull Project project, @NotNull DataKey<T> key, @NotNull ProjectSystemId externalSystemId) { if (project.isDisposed() || !project.isOpen()) { return null; } final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); if (toolWindowManager == null) { return null; } final ToolWindow toolWindow = ensureToolWindowContentInitialized(project, externalSystemId); if (toolWindow == null) { return null; } final ContentManager contentManager = toolWindow.getContentManager(); if (contentManager == null) { return null; } for (Content content : contentManager.getContents()) { final JComponent component = content.getComponent(); if (component instanceof DataProvider) { final Object data = ((DataProvider) component).getData(key.getName()); if (data != null && clazz.isInstance(data)) { return (T) data; } } } return null; }
public <T extends Item> T getItem(Class<T> c) { for (int i = 0; i < items.length; i++) { if (c.isInstance(items[i])) return c.cast(items[i]); } return null; }
public static <T extends CommandInterceptor> T findInterceptor( Cache<?, ?> cache, Class<T> interceptorToFind) { for (CommandInterceptor i : cache.getAdvancedCache().getInterceptorChain()) { if (interceptorToFind.isInstance(i)) return interceptorToFind.cast(i); } return null; }
private boolean invokeExistingSagas( EventProxy<?> event, Class<? extends Saga> sagaType, Collection<AssociationValue> associationValues) { Set<String> sagas = new TreeSet<>(); for (AssociationValue associationValue : associationValues) { sagas.addAll(sagaRepository.find(sagaType, associationValue)); } for (Saga sagaInCreation : sagasInCreation.values()) { if (sagaType.isInstance(sagaInCreation) && containsAny(sagaInCreation.getAssociationValues(), associationValues)) { sagas.add(sagaInCreation.getSagaIdentifier()); } } boolean sagaOfTypeInvoked = false; for (final String sagaId : sagas) { if (synchronizeSagaAccess) { lock.obtainLock(sagaId); Saga invokedSaga = null; try { invokedSaga = loadAndInvoke(event, sagaId, associationValues); if (invokedSaga != null) { sagaOfTypeInvoked = true; } } finally { doReleaseLock(sagaId, invokedSaga); } } else { loadAndInvoke(event, sagaId, associationValues); } } return sagaOfTypeInvoked; }
@Nullable public <T> T findChildByClass(Class<T> aClass) { for (PsiElement child : getChildren()) { if (aClass.isInstance(child)) return (T) child; } return null; }
@NotNull public <T> T[] findChildrenByClass(Class<T> aClass) { List<T> result = new ArrayList<T>(); for (PsiElement child : getChildren()) { if (aClass.isInstance(child)) result.add((T) child); } return result.toArray((T[]) Array.newInstance(aClass, result.size())); }
protected Decl getEnclosingScope(Class c) { for (int i = enclosingScopes.size() - 1; i >= 0; --i) { Decl d = enclosingScopes.get(i); if (c.isInstance(d)) { return d; } } return null; }
/** * Removes the property of the given type. * * @return The property that was just removed. * @since 1.279 */ public <T extends JobProperty> T removeProperty(Class<T> clazz) throws IOException { for (JobProperty<? super JobT> p : properties) { if (clazz.isInstance(p)) { removeProperty(p); return clazz.cast(p); } } return null; }
public static <T> T assertInstanceOf(Object o, Class<T> aClass) { Assert.assertNotNull("Expected instance of: " + aClass.getName() + " actual: " + null, o); Assert.assertTrue( "Expected instance of: " + aClass.getName() + " actual: " + o.getClass().getName(), aClass.isInstance(o)); @SuppressWarnings("unchecked") T t = (T) o; return t; }
private static Object checkValidSubject(final Object subject) { if (subject instanceof String) return ((String) subject).intern(); if (subject instanceof Method) return subject; for (Iterator it = validClasses.iterator(); it.hasNext(); ) { final Class vc = (Class) it.next(); if (vc.isInstance(subject)) return subject; } throw new RuntimeException("Unacceptable type for subject: " + subject); }
@Deprecated public <T extends Widget> T findchild(Class<T> cl) { for (Widget wdg = child; wdg != null; wdg = wdg.next) { if (cl.isInstance(wdg)) return (cl.cast(wdg)); T ret = wdg.findchild(cl); if (ret != null) return (ret); } return (null); }
private Set<Object> doFilter(Set<Object> elements) { Set<Object> result = new LinkedHashSet<Object>(); for (Object o : elements) { if (myElementClass.isInstance(o) && getFilter().isAccepted((T) o)) { result.add(o); } } return result; }
public boolean hasWrapper(Class c) { Assert.isTrue(FeatureCollectionWrapper.class.isAssignableFrom(c)); if (c.isInstance(this)) { return true; } return fc instanceof FeatureCollectionWrapper && ((FeatureCollectionWrapper) fc).hasWrapper(c); }
/** Obtain all the documents of a known type owned by this owner. */ @SuppressWarnings("unchecked") public <T extends PadDocument> Collection<T> documents(Class<T> clazz) { List<T> filtered = new ArrayList<T>(); for (PadDocument doc : documents.values()) { if (clazz.isInstance(doc)) { filtered.add((T) doc); } } return filtered; }
private List<String> collectModuleDepsNames(String moduleName, Class clazz) { List<String> actual = new ArrayList<String>(); for (OrderEntry e : getRootManager(moduleName).getOrderEntries()) { if (clazz.isInstance(e)) { actual.add(e.getPresentableName()); } } return actual; }
private void expect(Class<?> c) { if (!c.isInstance(stack.peek())) { throw new IllegalStateException( "Internal stack error: " + "Expected '" + c.getName() + "' found '" + stack.peek().getClass().getName() + "'"); } }
/** * Checks if the entity has the specified aspect. * * @param class1 * @return */ public final <T extends Aspect> boolean hasAspect(Class<T> type) { int count = m_aspects.size(); for (int i = 0; i < count; ++i) { Aspect aspect = m_aspects.get(i); if (type.isInstance(aspect)) { return true; } } return false; }