List of usage examples for java.lang.reflect Proxy newProxyInstance
private static Object newProxyInstance(Class<?> caller, Constructor<?> cons, InvocationHandler h)
From source file:org.apache.cassandra.utils.JMXServerUtils.java
private static MBeanServerForwarder configureJmxAuthorization(Map<String, Object> env) { // If a custom authz proxy is supplied (Cassandra ships with AuthorizationProxy, which // delegates to its own role based IAuthorizer), then instantiate and return one which // can be set as the JMXConnectorServer's MBeanServerForwarder. // If no custom proxy is supplied, check system properties for the location of the // standard access file & stash it in env String authzProxyClass = System.getProperty("cassandra.jmx.authorizer"); if (authzProxyClass != null) { final InvocationHandler handler = FBUtilities.construct(authzProxyClass, "JMX authz proxy"); final Class[] interfaces = { MBeanServerForwarder.class }; Object proxy = Proxy.newProxyInstance(MBeanServerForwarder.class.getClassLoader(), interfaces, handler); return MBeanServerForwarder.class.cast(proxy); } else {/* ww w. j a va 2 s . co m*/ String accessFile = System.getProperty("com.sun.management.jmxremote.access.file"); if (accessFile != null) { env.put("jmx.remote.x.access.file", accessFile); } return null; } }
From source file:com.qmetry.qaf.automation.ui.webdriver.ElementFactory.java
private Object initList(By by, SearchContext context) throws Exception { return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { List.class }, new QAFExtendedWebElementListHandler(context, by)); }
From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderParser.java
/** * Handle object before setting attributes, so get default property values. *//*w w w . j a va 2s. c o m*/ private void createModels(Object binder) throws Exception { ClassLoader classLoader = binder.getClass().getClassLoader(); String handlerClassName = binder.getClass().getName() + "$DTObjectHandler"; Class<?> handlerClass = classLoader.loadClass(handlerClassName); Object handler = Proxy.newProxyInstance(classLoader, new Class[] { handlerClass }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("handle")) { String path = (String) args[0]; Object object = args[1]; createModel(path, object); } if (method.getName().equals("provideFactory")) { Class<?> factoryType = (Class<?>) args[0]; String methodName = (String) args[1]; Object[] factoryArgs = (Object[]) args[2]; return createProvidedFactory(m_context, factoryType, methodName, factoryArgs); } if (method.getName().equals("provideField")) { Class<?> fieldType = (Class<?>) args[0]; String fieldName = (String) args[1]; return createProvidedField(m_context, fieldType, fieldName); } return null; } }); ReflectionUtils.setField(binder, "dtObjectHandler", handler); }
From source file:ch.digitalfondue.npjt.QueryFactory.java
@SuppressWarnings("unchecked") public <T> T from(final Class<T> clazz) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() { @Override/*from ww w . ja v a 2s . c om*/ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { boolean hasAnnotation = method.getAnnotation(Query.class) != null; if (hasAnnotation) { QueryTypeAndQuery qs = extractQueryAnnotation(clazz, method); return qs.type.apply(qs.query, qs.rowMapperClass, jdbc, method, args, columnMapperFactories.set, parameterConverters.set); } else if (method.getReturnType().equals(NamedParameterJdbcTemplate.class) && args == null) { return jdbc; } else if (IS_DEFAULT_METHOD != null && (boolean) IS_DEFAULT_METHOD.invoke(method)) { final Class<?> declaringClass = method.getDeclaringClass(); return LOOKUP_CONSTRUCTOR.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE) .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args); } else { throw new IllegalArgumentException( String.format("missing @Query annotation for method %s in interface %s", method.getName(), clazz.getSimpleName())); } } } ); }
From source file:org.pegadi.client.ApplicationLauncher.java
/** * This method registers a listener for the Quit-menuitem on OS X application menu. * To avoid platform dependent compilation, reflection is utilized. * <p/>// ww w .ja v a2 s. c om * Basically what happens, is this: * <p/> * Application app = Application.getApplication(); * app.addApplicationListener(new ApplicationAdapter() { * public void handleQuit(ApplicationEvent e) { * e.setHandled(false); * conditionalExit(); * } * }); */ private void registerOSXApplicationMenu() { try { ClassLoader cl = getClass().getClassLoader(); // Create class-objects for the classes and interfaces we need final Class comAppleEawtApplicationClass = cl.loadClass("com.apple.eawt.Application"); final Class comAppleEawtApplicationListenerInterface = cl .loadClass("com.apple.eawt.ApplicationListener"); final Class comAppleEawtApplicationEventClass = cl.loadClass("com.apple.eawt.ApplicationEvent"); final Method applicationEventSetHandledMethod = comAppleEawtApplicationEventClass .getMethod("setHandled", new Class[] { boolean.class }); // Set up invocationhandler-object to recieve events from OS X application menu InvocationHandler handler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("handleQuit")) { applicationEventSetHandledMethod.invoke(args[0], new Object[] { Boolean.FALSE }); conditionalExit(); } return null; } }; // Create applicationlistener proxy Object applicationListenerProxy = Proxy.newProxyInstance(cl, new Class[] { comAppleEawtApplicationListenerInterface }, handler); // Get a real Application-object Method applicationGetApplicationMethod = comAppleEawtApplicationClass.getMethod("getApplication", new Class[0]); Object theApplicationObject = applicationGetApplicationMethod.invoke(null, new Object[0]); // Add the proxy application object as listener Method addApplicationListenerMethod = comAppleEawtApplicationClass.getMethod("addApplicationListener", new Class[] { comAppleEawtApplicationListenerInterface }); addApplicationListenerMethod.invoke(theApplicationObject, new Object[] { applicationListenerProxy }); } catch (Exception e) { log.info("we are not on OSX"); } }
From source file:org.apache.olingo.ext.proxy.commons.EntityContainerInvocationHandler.java
@SuppressWarnings("unchecked") public <T extends Serializable, NEC extends PrimitiveCollection<T>> NEC newPrimitiveCollection( final Class<T> ref) { return (NEC) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { PrimitiveCollection.class }, new PrimitiveCollectionInvocationHandler<T>(getService(), ref)); }
From source file:org.apache.hive.service.cli.thrift.RetryingThriftCLIServiceClient.java
public static CLIServiceClient newRetryingCLIServiceClient(HiveConf conf) throws HiveSQLException { RetryingThriftCLIServiceClient retryClient = new RetryingThriftCLIServiceClient(conf); retryClient.connectWithRetry(/*from w w w .j a va 2 s. com*/ conf.getIntVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_CLIENT_CONNECTION_RETRY_LIMIT)); ICLIService cliService = (ICLIService) Proxy.newProxyInstance( RetryingThriftCLIServiceClient.class.getClassLoader(), CLIServiceClient.class.getInterfaces(), retryClient); return new CLIServiceClientWrapper(cliService); }
From source file:org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext.java
protected ImageInputStream createImageInputStream(InputStream in) throws IOException { ImageInputStream iin = ImageIO.createImageInputStream(in); return (ImageInputStream) Proxy.newProxyInstance(ImageInputStream.class.getClassLoader(), new Class[] { ImageInputStream.class }, new ObservingImageInputStreamInvocationHandler(iin, in)); }
From source file:hu.netmind.beankeeper.db.impl.ConnectionSourceImpl.java
/** * Get a new pooled connection. This method get a connection from the * pool, or allocates a new connection is no pooled ones are available. * @return A new connection object./*from w w w. j av a 2 s. co m*/ */ public synchronized Connection getConnection() { // Find an available connection, if a connection becomes unusable, it // is removed long currentTime = System.currentTimeMillis(); ConnectionWrapper wrapper = null; Iterator iterator = new LinkedList(pool).iterator(); int usedCount = 0; while (iterator.hasNext()) { ConnectionWrapper current = (ConnectionWrapper) iterator.next(); boolean usable = true; // If the connection is pooled elsewhere, and it is used, // then we have no business with it if ((current.used) && (isDataSourcePooled())) continue; // Check whether connection became closed somehow try { usable = !current.connection.isClosed(); } catch (Exception e) { // Ok, probably closed logger.debug("while checking closed status, connection threw", e); usable = false; } // Check for timeout if (current.lastUsed + TIMEOUT < currentTime) { usable = false; if (current.used) logger.warn( "a connection is used, but reached timeout and will be reclaimed, possible unbalanced transaction handling!"); } // If usable, then return this wrapper, else close it if (usable) { if (!current.used) { // This is usable but not used, so return it. Next iterations // can override this still, so always the last usable // connection will be used. wrapper = current; } else { // Connection is used usedCount++; } } } // Allocate connection if not yet found if (wrapper == null) { // Allocate connection wrapper = new ConnectionWrapper(); try { logger.debug("connection pool has: " + pool.size() + " connections, maximum connections allocated at any given time: " + maxConnections + ", need new connection."); wrapper.connection = dataSource.getConnection(); wrapper.connection.setAutoCommit(false); } catch (StoreException e) { throw e; } catch (Exception e) { throw new StoreException( "could not get a new connection from datasouce, current pool size: " + pool.size(), e); } // Add to pool pool.add(wrapper); wrappers.put(wrapper.connection, wrapper); // Successful connection if (pool.size() > maxConnections) maxConnections = pool.size(); } // Profile snapshotLogger.log("connectionpool", "Connection used/pool/wrappers: " + usedCount + "/" + pool.size() + "/" + wrappers.size()); // Return connection if one has been found wrapper.used = true; wrapper.lastUsed = currentTime; // Create a wrapper on the connection object, so each use // of it's prepareStatement() can update it's wrapper's last used time. try { return (Connection) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Connection.class }, new WrapperHandler(wrapper)); } catch (Exception e) { throw new StoreException("exception while creating connection proxy", e); } }
From source file:org.apache.olingo.ext.proxy.commons.EntitySetInvocationHandler.java
@SuppressWarnings("unchecked") public <S extends T, SEC extends EntityCollection<S, ?, ?>> SEC execute(final Class<SEC> collTypeRef) { final Class<S> ref = (Class<S>) ClassUtils.extractTypeArg(collTypeRef, AbstractEntitySet.class, AbstractSingleton.class, EntityCollection.class); final Class<S> oref = (Class<S>) ClassUtils.extractTypeArg(this.collItemRef, AbstractEntitySet.class, AbstractSingleton.class, EntityCollection.class); if (!oref.equals(ref)) { uri.appendDerivedEntityTypeSegment( new FullQualifiedName(ClassUtils.getNamespace(ref), ClassUtils.getEntityTypeName(ref)) .toString());/*from w ww . ja v a2 s . c om*/ } final List<ClientAnnotation> anns = new ArrayList<ClientAnnotation>(); final Triple<List<T>, URI, List<ClientAnnotation>> entitySet = fetchPartial(uri.build(), (Class<T>) ref); anns.addAll(entitySet.getRight()); final EntityCollectionInvocationHandler<S> entityCollectionHandler = new EntityCollectionInvocationHandler<S>( service, (List<S>) entitySet.getLeft(), collTypeRef, this.baseURI, uri); entityCollectionHandler.setAnnotations(anns); entityCollectionHandler.nextPageURI = entitySet.getMiddle(); return (SEC) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { collTypeRef }, entityCollectionHandler); }