/** * Method description * * @param ht_def_key * @param ht_dev_val * @param st_def_key * @param st_def_val * @param prop_key * @param prop_val_class * @param params * @param props * @param <T> */ protected <T> void checkHighThroughputProperty( String ht_def_key, T ht_dev_val, String st_def_key, T st_def_val, String prop_key, Class<T> prop_val_class, Map<String, Object> params, Map<String, Object> props) { T tmp = st_def_val; String str_tmp = null; if (isHighThroughput()) { tmp = ht_dev_val; str_tmp = (String) params.get(ht_def_key); } else { tmp = st_def_val; str_tmp = (String) params.get(st_def_key); } if (prop_val_class.isAssignableFrom(Integer.class)) { tmp = prop_val_class.cast(DataTypes.parseNum(str_tmp, Integer.class, (Integer) tmp)); } if (prop_val_class.isAssignableFrom(Long.class)) { tmp = prop_val_class.cast(DataTypes.parseNum(str_tmp, Long.class, (Long) tmp)); } if (prop_val_class.isAssignableFrom(String.class)) { tmp = prop_val_class.cast(str_tmp); } props.put(prop_key, tmp); }
/** * 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); }
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); }
public <T extends BlockPayload> T read(BlockPointer pos, Class<T> payloadType) { T block = payloadType.cast(dirty.get(pos)); if (block != null) { return block; } block = payloadType.cast(indexBlockCache.get(pos)); if (block != null) { return block; } block = store.read(pos, payloadType); maybeCache(block); return block; }
@Override @Nullable protected <T extends VcsExtension> T getVcsCustomExtension( @NotNull final Class<T> extensionClass) { if (ChangesInfoBuilder.class.equals(extensionClass)) { return extensionClass.cast(getCollectChangesPolicy()); } if (myExtensions != null) { for (GitServerExtension e : myExtensions) { if (extensionClass.isInstance(e)) return extensionClass.cast(e); } } return super.getVcsCustomExtension(extensionClass); }
public <T> T getAs(final String key, final Class<T> clazz) { if (!this.is(key, clazz)) { throw new IllegalArgumentException(); } else { return clazz.cast(this.contentMap.get(key)); } }
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; }
/** * Returns the property names <code>name</code> which is still wrapped into the annotation * instance. * * @param name the name of the property * @param propertyClass the class of the property * @return the wrapper around property * @throws PropertyException if there is no such property */ public S4PropWrapper getProperty(String name, Class<?> propertyClass) throws PropertyException { if (!propValues.containsKey(name)) throw new InternalConfigurationException( getInstanceName(), name, "Unknown property '" + name + "' ! Make sure that you've annotated it."); S4PropWrapper s4PropWrapper = registeredProperties.get(name); if (s4PropWrapper == null) { throw new InternalConfigurationException( getInstanceName(), name, "Property is not an annotated property of " + getConfigurableClass()); } try { propertyClass.cast(s4PropWrapper.getAnnotation()); } catch (ClassCastException e) { throw new InternalConfigurationException( e, getInstanceName(), name, "Property annotation " + s4PropWrapper.getAnnotation() + " doesn't match the required type " + propertyClass.getName()); } return s4PropWrapper; }
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 <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 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; } }
@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); }
protected E1 getParentOf(E2 child) { Collection<? extends RefObject> c = super.query(false, child); assert (c.size() <= 1); if (c.isEmpty()) { return null; } else { return end1GenericClass.cast(c.iterator().next()); } }
/** * 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; }
protected E2 getChildOf(E1 parent) { Collection<? extends RefObject> c = super.query(true, parent); assert (c.size() <= 1); if (c.isEmpty()) { return null; } else { return end2GenericClass.cast(c.iterator().next()); } }
@Override public void onMessage(final String message) { try { AbstractMessage msg = (AbstractMessage) (new XMLBuilder().fromXML(message)); final int requestID = msg.getId(); String messageType = msg.getType(); final String destination = msg.getEndpoint(); switch (messageType) { case "request": { if (DEBUG) System.out.println("Receiving the request: \n" + message); final Request request = (Request) msg; executors.submit( new Callable<Object>() { @Override public Object call() throws Exception { try { Object result = invokeOperation(request.getOpName(), request.getParams()); if (result instanceof OperationAborted) return null; sendResponse(requestID, result, destination); } catch (Exception e) { e.printStackTrace(); } return null; } }); break; } case "response": { if (DEBUG) System.out.println("Receiving the response: \n" + message); Response response = (Response) msg; if (response.getReturnType() != null) { Class<?> type = (Class<?>) response.getReturnType(); results.put(response.getRequestID(), type.cast(response.getReturnValue())); } else { results.put(response.getRequestID(), NullObject); } synchronized (this) { this.notifyAll(); } break; } default: break; } } catch (Exception e) { e.printStackTrace(); } }
public <T> T nodeByTypeElement(Class<T> baseType) { int len = children.size(); for (int i = 0; i < len; i++) { Child child = children.get(i); if (child instanceof NodeChild) { NodeChild nc = (NodeChild) child; if (model.elements.containsKey(nc.name)) continue; // match with named if (baseType.isAssignableFrom(nc.dom.getImplementationClass())) return baseType.cast(nc.dom.get()); } } return null; }
/** * Constructs new instance of the specified class. * * @param exp Expected class for the new instance. * @param clsName Class name to create new instance for. * @param <T> Expected class type for the new instance. * @return New instance of specified class. * @throws GridClientException If loading failed. */ private static <T> T newInstance(Class<T> exp, String clsName) throws GridClientException { Object obj; try { obj = Class.forName(clsName).newInstance(); } // Catch all for convenience. catch (Exception e) { throw new GridClientException("Failed to create class instance: " + clsName, e); } return exp.cast(obj); }
public synchronized <T> Iterable<T> getPlugins(Class<T> wantedType) { // Iterable<CRaSHPlugin<?>> plugins = getPlugins(); // List<T> tmp = Collections.emptyList(); // for (CRaSHPlugin<?> plugin : plugins) { Class<?> pluginType = plugin.getType(); if (wantedType.isAssignableFrom(pluginType)) { switch (plugin.status) { default: case CRaSHPlugin.FAILED: case CRaSHPlugin.INITIALIZED: // Do nothing break; case CRaSHPlugin.CONSTRUCTED: int status = CRaSHPlugin.FAILED; try { plugin.status = CRaSHPlugin.INITIALIZING; plugin.init(); log.info("Initialized plugin " + plugin); status = CRaSHPlugin.INITIALIZED; } catch (Exception e) { log.error("Could not initialize plugin " + plugin, e); } finally { plugin.status = status; } break; case CRaSHPlugin.INITIALIZING: throw new RuntimeException("Circular dependency"); } // if (plugin.status == CRaSHPlugin.INITIALIZED) { if (tmp.isEmpty()) { tmp = new ArrayList<T>(); } T t = wantedType.cast(plugin); tmp.add(t); } } } // return tmp; }
@NotNull private static <T extends Configurable> T findConfigurable( ConfigurableEP<Configurable>[] extensions, Class<T> configurableClass) { for (ConfigurableEP<Configurable> extension : extensions) { if (extension.providerClass != null || extension.instanceClass != null || extension.implementationClass != null) { final Configurable configurable = extension.createConfigurable(); if (configurableClass.isInstance(configurable)) { return configurableClass.cast(configurable); } } } throw new IllegalArgumentException("Cannot find configurable of " + configurableClass); }
public <T> T generateRandom(Class<T> objectClass) { Random r = new Random(); if (objectClass.isInstance(String.class)) { String s = ""; for (int i = 0; i < 10; i++) { char c = (char) (r.nextInt() / ('Z' - 'A') + 'A'); s = s + c; } return objectClass.cast(s); } else if (objectClass.isInstance(Integer.class)) { Integer s = r.nextInt(); return objectClass.cast(s); } else if (objectClass.isInstance(Long.class)) { Long s = r.nextLong(); return objectClass.cast(s); } else if (objectClass.isInstance(java.util.Date.class)) { java.util.Calendar c = java.util.Calendar.getInstance(); c.set(java.util.Calendar.MONTH, r.nextInt() / 12); c.set(java.util.Calendar.DAY_OF_MONTH, r.nextInt() / 30); c.setLenient(false); return objectClass.cast(c.getTime()); } return null; }
@Override public <DS> DS getDatastoreSession(Class<DS> sessionType) { DatastoreSession< EntityId, Entity, EntityMetadata, EntityDiscriminator, RelationId, Relation, RelationMetadata, RelationDiscriminator, PropertyMetadata> datastoreSession = sessionContext.getDatastoreSession(); return sessionType.cast(datastoreSession); }
/** * Return the first fetch response item of the given class for the given message number. * * @param r the responses * @param msgno the message number * @param c the class * @param <T> the type of fetch item * @return the fetch item */ public static <T extends Item> T getItem(Response[] r, int msgno, Class<T> c) { if (r == null) return null; for (int i = 0; i < r.length; i++) { if (r[i] == null || !(r[i] instanceof FetchResponse) || ((FetchResponse) r[i]).getNumber() != msgno) continue; FetchResponse f = (FetchResponse) r[i]; for (int j = 0; j < f.items.length; j++) { if (c.isInstance(f.items[j])) return c.cast(f.items[j]); } } return null; }
@Nullable public static <T> T cast(@NotNull Class<T> type, UnnamedConfigurable configurable) { if (configurable instanceof ConfigurableWrapper) { ConfigurableWrapper wrapper = (ConfigurableWrapper) configurable; if (wrapper.myConfigurable == null) { Class<?> configurableType = wrapper.getExtensionPoint().getConfigurableType(); if (configurableType != null) { if (!type.isAssignableFrom(configurableType)) { return null; // do not create configurable that cannot be cast to the specified type } } else if (type == Configurable.Assistant.class || type == OptionalConfigurable.class) { return null; // do not create configurable from ConfigurableProvider which replaces // OptionalConfigurable } } configurable = wrapper.getConfigurable(); } return type.isInstance(configurable) ? type.cast(configurable) : null; }
/** * Return all fetch response items of the given class for the given message number. * * @param r the responses * @param msgno the message number * @param c the class * @param <T> the type of fetch items * @return the list of fetch items * @since JavaMail 1.5.2 */ public static <T extends Item> List<T> getItems(Response[] r, int msgno, Class<T> c) { List<T> items = new ArrayList<T>(); if (r == null) return items; for (int i = 0; i < r.length; i++) { if (r[i] == null || !(r[i] instanceof FetchResponse) || ((FetchResponse) r[i]).getNumber() != msgno) continue; FetchResponse f = (FetchResponse) r[i]; for (int j = 0; j < f.items.length; j++) { if (c.isInstance(f.items[j])) items.add(c.cast(f.items[j])); } } return items; }
public static <T extends ClientBehavior> T findClientBehavior( Class<T> behaviorClass, String eventName, UIComponent component) { if (!(component instanceof ClientBehaviorHolder)) return null; T foundBehavior = null; Map<String, List<ClientBehavior>> behaviorsMap = ((ClientBehaviorHolder) component).getClientBehaviors(); if (behaviorsMap != null && behaviorsMap.size() > 0) { List<ClientBehavior> behaviors = behaviorsMap.get(eventName); if (behaviors != null) for (ClientBehavior behavior : behaviors) { if (behaviorClass.isInstance(behavior)) { foundBehavior = behaviorClass.cast(behavior); break; } } } return foundBehavior; }
private static <T, S> T adaptToEnum(Class<T> targetType, S sourceObject) { try { String literal; if (sourceObject instanceof Enum) { literal = ((Enum<?>) sourceObject).name(); } else if (sourceObject instanceof String) { literal = (String) sourceObject; } else { literal = sourceObject.toString(); } NotationParser<String, T> parser = new NotationConverterToNotationParserAdapter<String, T>( new EnumFromCharSequenceNotationParser(targetType)); T parsedLiteral = parser.parseNotation(literal); return targetType.cast(parsedLiteral); } catch (TypeConversionException e) { throw new IllegalArgumentException( String.format( "Can't convert '%s' to enum type '%s'", sourceObject, targetType.getSimpleName()), e); } }
public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return iface.cast(this); } throw statement.connection.helper.createException("does not implement '" + iface + "'"); }
/** * Returns the first provider in the registry for the specified category, using the specified map * of hints (if any). This method may {@linkplain #scanForPlugins scan for plugins} the first time * it is invoked. Except as a result of this scan, no new provider instance is created by the * default implementation of this method. The {@link FactoryCreator} class change this behavior * however. * * @param <T> The class represented by the {@code category} argument. * @param category The category to look for. Must be one of the categories declared to the * constructor. Usually an interface class (not the actual implementation class). * @param filter An optional filter, or {@code null} if none. This is used for example in order to * select the first factory for some {@linkplain * org.opengis.referencing.AuthorityFactory#getAuthority authority}. * @param hints A {@linkplain Hints map of hints}, or {@code null} if none. * @param key The key to use for looking for a user-provided instance in the hints, or {@code * null} if none. * @return A factory {@linkplain OptionalFactory#isAvailable available} for use for the specified * category and hints. The returns type is {@code Object} instead of {@link Factory} because * the factory implementation doesn't need to be a Geotools one. * @throws FactoryNotFoundException if no factory was found for the specified category, filter and * hints. * @throws FactoryRegistryException if a factory can't be returned for some other reason. * @see #getServiceProviders(Class, Filter, Hints) * @see FactoryCreator#getServiceProvider */ public <T> T getServiceProvider( final Class<T> category, final Filter filter, Hints hints, final Hints.Key key) throws FactoryRegistryException { synchronizeIteratorProviders(); final boolean debug = LOGGER.isLoggable(DEBUG_LEVEL); if (debug) { /* * We are not required to insert the method name ("GetServiceProvider") in the * message because it is part of the informations already stored by LogRecord, * and formatted by the default java.util.logging.SimpleFormatter. * * Conventions for the message part according java.util.logging.Logger javadoc: * - "ENTRY" at the begining of a method. * - "RETURN" at the end of a method, if successful. * - "THROW" in case of failure. * - "CHECK" ... is our own addition to Sun's convention for this method ... */ debug("ENTRY", category, key, null, null); } Class<?> implementation = null; if (key != null) { /* * Sanity check: make sure that the key class is appropriate for the category. */ final Class<?> valueClass = key.getValueClass(); if (!category.isAssignableFrom(valueClass)) { if (debug) { debug("THROW", category, key, "unexpected type:", valueClass); } throw new IllegalArgumentException(Errors.format(ErrorKeys.ILLEGAL_KEY_$1, key)); } if (hints != null) { final Object hint = hints.get(key); if (hint != null) { if (debug) { debug("CHECK", category, key, "user provided a", hint.getClass()); } if (category.isInstance(hint)) { /* * The factory implementation was given explicitly by the user. * Nothing to do; we are done. */ if (debug) { debug("RETURN", category, key, "return hint as provided.", null); } return category.cast(hint); } /* * Before to pass the hints to the private 'getServiceImplementation' method, * remove the hint for the user-supplied key. This is because this hint has * been processed by this public 'getServiceProvider' method, and the policy * is to remove the processed hints before to pass them to child dependencies * (see the "Check recursively in factory dependencies" comment elswhere in * this class). * * Use case: DefaultDataSourceTest invokes indirectly 'getServiceProvider' * with a "CRS_AUTHORITY_FACTORY = ThreadedEpsgFactory.class" hint. However * ThreadedEpsgFactory (in the org.geotools.referencing.factory.epsg package) * is a wrapper around DirectEpsgFactory, and defines this dependency through * a "CRS_AUTHORITY_FACTORY = DirectEpsgFactory.class" hint. There is no way * to match this hint for both factories in same time. Since we must choose * one, we assume that the user is interrested in the most top level one and * discart this particular hint for the dependencies. */ hints = new Hints(hints); if (hints.remove(key) != hint) { // Should never happen except on concurrent modification in an other thread. throw new AssertionError(key); } /* * If the user accepts many implementation classes, then try all of them in * the preference order given by the user. The last class (or the singleton * if the hint was not an array) will be tried using the "normal" path * (oustide the loop) in order to get the error message in case of failure. */ if (hint instanceof Class<?>[]) { final Class<?>[] types = (Class<?>[]) hint; final int length = types.length; for (int i = 0; i < length - 1; i++) { final Class<?> type = types[i]; if (debug) { debug("CHECK", category, key, "consider hint[" + i + ']', type); } final T candidate = getServiceImplementation(category, type, filter, hints); if (candidate != null) { if (debug) { debug("RETURN", category, key, "found implementation", candidate.getClass()); } return candidate; } } if (length != 0) { implementation = types[length - 1]; // Last try to be done below. } } else { implementation = (Class<?>) hint; } } } } if (debug && implementation != null) { debug("CHECK", category, key, "consider hint[last]", implementation); } final T candidate = getServiceImplementation(category, implementation, filter, hints); if (candidate != null) { if (debug) { debug("RETURN", category, key, "found implementation", candidate.getClass()); } return candidate; } if (debug) { debug("THROW", category, key, "could not find implementation.", null); } throw new FactoryNotFoundException( Errors.format( ErrorKeys.FACTORY_NOT_FOUND_$1, implementation != null ? implementation : category)); }
public <T extends Widget> T getparent(Class<T> cl) { for (Widget w = this; w != null; w = w.parent) { if (cl.isInstance(w)) return (cl.cast(w)); } return (null); }