Example usage for java.lang.reflect Proxy newProxyInstance

List of usage examples for java.lang.reflect Proxy newProxyInstance

Introduction

In this page you can find the example usage for java.lang.reflect Proxy newProxyInstance.

Prototype

private static Object newProxyInstance(Class<?> caller, 
            Constructor<?> cons, InvocationHandler h) 

Source Link

Usage

From source file:org.jspresso.framework.model.component.basic.AbstractComponentInvocationHandler.java

/**
 * Directly set a property value to the property store without any other
 * operation./*from   w  w  w. jav a2s .  c  om*/
 *
 * @param proxy
 *     the proxy to straight set the property to.
 * @param propertyName
 *     the name of the property.
 * @param newPropertyValue
 *     the property value or null.
 */
protected void straightSetProperty(Object proxy, String propertyName, Object newPropertyValue) {
    IPropertyDescriptor propertyDescriptor = componentDescriptor.getPropertyDescriptor(propertyName);
    if (propertyDescriptor == null
            || (propertyDescriptor.isComputed() && propertyDescriptor.getPersistenceFormula() == null)) {
        return;
    }
    Object currentPropertyValue = straightGetProperty(proxy, propertyName);
    if (propertyDescriptor instanceof IReferencePropertyDescriptor) {
        // reference must change sometimes even if entities are equal.
        if (/* !ObjectUtils.equals(currentPropertyValue, newPropertyValue) */currentPropertyValue != newPropertyValue) {
            storeReferenceProperty(proxy, (IReferencePropertyDescriptor<?>) propertyDescriptor,
                    currentPropertyValue, newPropertyValue);
        }
    } else if (propertyDescriptor instanceof ICollectionPropertyDescriptor) {
        storeCollectionProperty(proxy, (ICollectionPropertyDescriptor<?>) propertyDescriptor,
                currentPropertyValue, newPropertyValue);
        if (currentPropertyValue != null && currentPropertyValue == newPropertyValue
                && isInitialized(currentPropertyValue)) {
            currentPropertyValue = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class<?>[] { ((ICollectionPropertyDescriptor<?>) propertyDescriptor)
                            .getReferencedDescriptor().getCollectionInterface() },
                    new NeverEqualsInvocationHandler(
                            CollectionHelper.cloneCollection((Collection<?>) currentPropertyValue)));
        }
    } else {
        storeProperty(propertyName, newPropertyValue);
    }
    doFirePropertyChange(proxy, propertyName, currentPropertyValue, newPropertyValue);
}

From source file:org.apache.hive.jdbc.HiveConnection.java

public static TCLIService.Iface newSynchronizedClient(TCLIService.Iface client) {
    return (TCLIService.Iface) Proxy.newProxyInstance(HiveConnection.class.getClassLoader(),
            new Class[] { TCLIService.Iface.class }, new SynchronizedHandler(client));
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

/**
 * @see de.innovationgate.webgate.api.WGDatabaseCore#open(WGDatabase,
 *      String, String, String, boolean)
 *//*  ww w.  java  2 s  .c om*/
public WGUserAccess open(WGDatabase db, String path, String user, String pwd, boolean prepareOnly)
        throws WGAPIException {

    try {

        this._db = db;
        this._path = path;
        this._aclImpl = new ACLImpl(this);

        String jdbcDriver = (String) db.getCreationOptions().get("Driver");
        if (jdbcDriver == null) {
            jdbcDriver = (String) db.getCreationOptions().get("hibernate.connection.driver_class");
        }

        // Determine dll version
        _csVersion = determineCSVersion(db, jdbcDriver, path, user, pwd);
        _ddlVersion = _csVersion.getVersion();
        _fileHandling = createFileHandling();

        boolean useSharedPool = WGUtils.getBooleanMapValue(db.getCreationOptions(),
                WGDatabase.COPTION_SHAREDPOOL, true);
        if (useSharedPool && db.getCreationOptions().containsKey(Database.OPTION_PATH)
                && db.getServer() instanceof SharedPoolJDBCDatabaseServer) {
            SharedPoolJDBCDatabaseServer poolServer = (SharedPoolJDBCDatabaseServer) db.getServer();
            if (poolServer.isPoolAvailable(_csVersion)) {
                try {
                    _connProvider = poolServer.createPoolConnectionProvider(
                            (String) db.getCreationOptions().get(Database.OPTION_PATH));
                    WGFactory.getLogger()
                            .info("Database '" + db.getDbReference()
                                    + "' uses the shared connection pool of database server '"
                                    + db.getServer().getTitle(Locale.getDefault()) + "'");
                } catch (WGInvalidDatabaseException e) {
                    throw e;
                } catch (Exception e) {
                    throw new WGInvalidDatabaseException("Exception connecting to shared database server pool",
                            e);
                }
            }
        }

        // Create regular connection provider if no shared one available/allowed
        if (_connProvider == null) {
            Properties props = new Properties();
            if (path.startsWith("jdbc:")) {
                putDefaultConPoolProps(db, props);
            }
            if (user != null || pwd != null) {
                props.put("hibernate.connection.username", WGUtils.getValueOrDefault(user, ""));
                props.put("hibernate.connection.password", WGUtils.getValueOrDefault(pwd, ""));
            }
            String driverClass = (String) db.getCreationOptions().get("Driver");

            props.put(Environment.ISOLATION, String.valueOf(Connection.TRANSACTION_READ_COMMITTED));

            props.putAll(db.getCreationOptions());
            try {
                _connProvider = new JDBCConnectionProvider(path, driverClass, props, true);
            } catch (JDBCConnectionException e) {
                throw new WGInvalidDatabaseException("Exception creating connection pool", e);
            }
        }

        // Build Session factory and builder
        buildSessionFactory(db, path, user, pwd, _csVersion, _connProvider);
        if ("true".equals(System.getProperty("de.innovationgate.wga.hibernate.enable_jmx"))) {
            _sessionFactory.getStatistics().setStatisticsEnabled(true);
            try {
                Object statisticsMBean = Proxy.newProxyInstance(getClass().getClassLoader(),
                        new Class<?>[] { StatisticsMXBean.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                return method.invoke(_sessionFactory.getStatistics(), args);
                            }
                        });
                _jmxManager = new JmxManager(statisticsMBean,
                        new ObjectName("de.innovationgate.WGAMonitor:name=Hibernate-Statistics,db="
                                + JmxManager.normalizeJmxKey(db.getDbReference())));
            } catch (Exception e2) {
                WGFactory.getLogger().error("Exception enabling JMX for Hibernate statistics", e2);
            }
        }

        _sessionBuilder = _sessionFactory.withOptions();

        // Determine save isolation
        _saveIsolationActive = _ddlVersion >= WGDatabase.CSVERSION_WGA5;
        if (db.getCreationOptions().containsKey("SaveIsolation")) {
            _saveIsolationActive = Boolean.parseBoolean((String) db.getCreationOptions().get("SaveIsolation"));
        }

        // parse masterPersistenceTimeout
        if (db.getCreationOptions().containsKey(COPTION_MASTERPERSISTENCE_TIMEOUT)) {
            _masterPersistenceTimeout = Long
                    .parseLong((String) db.getCreationOptions().get(COPTION_MASTERPERSISTENCE_TIMEOUT));
        }

        // parse HQL query default type
        String hqlType = (String) db.getCreationOptions().get(COPTION_HQL_FETCH_TYPE);
        if (hqlType != null) {
            _hqlLazyByDefault = hqlType.equals(HQL_FETCHTYPE_LAZY);
        }

        String hqlLazyParentCheck = (String) db.getCreationOptions().get(COPTION_HQL_LAZY_PARENTCHECK);
        if (hqlLazyParentCheck != null) {
            _hqlLazyParentCheck = Boolean.parseBoolean(hqlLazyParentCheck);
        }

        // open session
        WGUserAccess accessLevel;
        try {
            accessLevel = openSession(MasterLoginAuthSession.getInstance(), pwd, true);
        } catch (WGUnavailableException e) {
            throw new WGInvalidDatabaseException("Error opening initial session", e);
        } catch (WGBackendException e) {
            throw new WGInvalidDatabaseException("Error opening initial session", e);
        }
        if (accessLevel.getAccessLevel() <= WGDatabase.ACCESSLEVEL_NOACCESS) {
            try {
                close();
            } catch (WGBackendException e1) {
                WGFactory.getLogger().error(e1);
            }
        }
        return accessLevel;

    } catch (WGInvalidDatabaseException e) {
        if (_connProvider != null) {
            if (_connProvider instanceof Stoppable) {
                ((Stoppable) _connProvider).stop();
            }
            _connProvider = null;
        }
        throw e;
    }

}

From source file:self.philbrown.droidQuery.$.java

/**
 * Binds the views in the current selection to the event. For example:
 * <pre>//from  w  ww  .j a  v a2s. co m
 * $.with(myView).bind("click", "Hello World!", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       Object data = args[0];
 *       droidQuery.alert((String) data);
 *    }
 * });
 * </pre>
 * @note that for events with multiple words, all words except the first are required to be 
 * capitalized. For example, to bind to a long-click event, both of the following are acceptable:
 * <pre>
 * $.with(myView).bind("longClick", "Hello World!", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       Object data = args[0];
 *       droidQuery.alert((String) data);
 *    }
 * });
 * 
 * $.with(myView).bind("LongClick", "Hello World!", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       Object data = args[0];
 *       droidQuery.alert((String) data);
 *    }
 * });
 * </pre>
 * However, this will fail:
 * <pre>
 * $.with(myView).bind("longclick", "Hello World!", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       Object data = args[0];
 *       droidQuery.alert((String) data);
 *    }
 * });
 * </pre>
 * @param eventType should be the verb in OnVerbListener
 * @param data an Object passed to {@code handler} when the event is triggered.
 * @param handler receives two arguments: a droidQuery with the affected view selected, and the {@code data} parameter
 * @return the current instance of {@code droidQuery}
 * @see #on(String, Function)
 * @see #one(String, Function)
 * @see #unbind(String)
 */
public $ bind(String eventType, Object data, Function handler) {
    String method = String.format(Locale.US, "setOn%sListener", capitalize(eventType));
    String listener = String.format(Locale.US, "On%sListener", capitalize(eventType));
    for (int i = 0; i < this.views.size(); i++) {
        View view = this.views.get(i);
        Class<?>[] classes = view.getClass().getClasses();
        try {
            //dynamically create instance of the listener interface

            Class<?> eventInterface = null;

            for (Class<?> clazz : classes) {
                if (clazz.getSimpleName().equalsIgnoreCase(listener)) {
                    eventInterface = clazz;
                    break;
                }
            }
            Method setEventListener = view.getClass().getMethod(method, new Class<?>[] { eventInterface });
            EventHandlerCreator proxy = new EventHandlerCreator($.with(view), handler, data);
            Object eventHandler = Proxy.newProxyInstance(eventInterface.getClassLoader(),
                    new Class<?>[] { eventInterface }, proxy);
            setEventListener.invoke(view, eventInterface.cast(eventHandler));

        } catch (Throwable t) {
            Log.w("droidQuery",
                    String.format(Locale.US, "Could not bind to event %s.\n%s", eventType, t.getMessage()));
        }
    }

    return this;
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Binds the views in the current selection to the event. For example:
 * <pre>/* ww  w .  java 2  s  .  c  o  m*/
 * $.with(myView).on("click", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       droidQuery.alert("View Clicked!");
 *    }
 * });
 * </pre>
 * @note that for events with multiple words, all words except the first are required to be 
 * capitalized. For example, to bind to a long-click event, both of the following are acceptable:
 * <pre>
 * $.with(myView).on("longClick", new Function() {
 *    public void invoke($droidQuery, Object... args) {
 *       droidQuery.alert("View LongClicked!");
 *    }
 * });
 * 
 * $.with(myView).on("LongClick", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       droidQuery.alert("View LongClicked!");
 *    }
 * });
 * </pre>
 * However, this will fail:
 * <pre>
 * $.with(myView).on("longclick", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       droidQuery.alert("View LongClicked!");
 *    }
 * });
 * </pre>
 * @param event should be the verb in OnVerbListener
 * @param handler receives one argument: a droidQuery with the affected view selected
 * @return the current instance of {@code droidQuery}
 * @see #bind(String, Object, Function)
 * @see #one(String, Function)
 * @see #unbind(String)
 */
public $ on(String event, Function handler) {
    String method = String.format(Locale.US, "setOn%sListener", capitalize(event));
    String listener = String.format(Locale.US, "On%sListener", capitalize(event));
    for (int i = 0; i < this.views.size(); i++) {
        View view = this.views.get(i);
        Class<?>[] classes = view.getClass().getClasses();

        try {

            Class<?> eventInterface = null;

            for (Class<?> clazz : classes) {
                if (clazz.getSimpleName().equalsIgnoreCase(listener)) {
                    eventInterface = clazz;
                    break;
                }
            }

            Method setEventListener = view.getClass().getMethod(method, new Class<?>[] { eventInterface });
            EventHandlerCreator proxy = new EventHandlerCreator($.with(view), handler);
            Object eventHandler = Proxy.newProxyInstance(eventInterface.getClassLoader(),
                    new Class<?>[] { eventInterface }, proxy);
            setEventListener.invoke(view, eventInterface.cast(eventHandler));
        } catch (Throwable t) {
            Log.w("droidQuery", String.format(Locale.US, "Could not bind to event %s.", event));
        }
    }

    return this;
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Registers change listeners for TextViews, EditTexts, and CompoundButtons. For all other
 * view types, this will trigger a function when the view's layout has been changed.
 * @param function the Function to call when the change event occurs. This will receive a
 * droidQuery instance for the changed view
 * @return this/*  www  .j a  v a  2s . c o  m*/
 */
public $ change(final Function function) {
    for (int i = 0; i < this.views.size(); i++) {
        View view = this.views.get(i);
        final int index = i;
        if (view instanceof TextView) {
            ((TextView) view).addTextChangedListener(new TextWatcher() {

                @Override
                public void afterTextChanged(Editable arg0) {
                    function.invoke($.with($.this.views.get(index)));
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

            });
        } else if (view instanceof EditText) {//this is overkill, but what the hey
            ((EditText) view).addTextChangedListener(new TextWatcher() {

                @Override
                public void afterTextChanged(Editable arg0) {
                    function.invoke($.with($.this.views.get(index)));
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

            });
        } else if (view instanceof CompoundButton) {
            ((CompoundButton) view).setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    function.invoke($.with($.this.views.get(index)));
                }

            });
        } else if (android.os.Build.VERSION.SDK_INT >= 11) {
            //default to size for API 11+
            try {
                Class<?> eventInterface = Class.forName("android.view.View.OnLayoutChangeListener");
                Method addOnLayoutChangeListener = view.getClass().getMethod("addOnLayoutChangeListener",
                        new Class<?>[] { eventInterface });
                InvocationHandler proxy = new InvocationHandler() {

                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        function.invoke($.with($.this.views.get(index)));
                        return null;
                    }

                };
                Object eventHandler = Proxy.newProxyInstance(eventInterface.getClassLoader(),
                        new Class<?>[] { eventInterface }, proxy);
                addOnLayoutChangeListener.invoke(view, eventInterface.cast(eventHandler));
            } catch (Throwable t) {
                //unknown error
            }
        }
    }

    return this;
}

From source file:org.apache.hadoop.hive.metastore.HiveMetaStoreClient.java

/**
 * Creates a synchronized wrapper for any {@link IMetaStoreClient}.
 * This may be used by multi-threaded applications until we have
 * fixed all reentrancy bugs.//from   w  ww  .  j  a va  2 s. c  o  m
 *
 * @param client unsynchronized client
 *
 * @return synchronized client
 */
public static IMetaStoreClient newSynchronizedClient(IMetaStoreClient client) {
    return (IMetaStoreClient) Proxy.newProxyInstance(HiveMetaStoreClient.class.getClassLoader(),
            new Class[] { IMetaStoreClient.class }, new SynchronizedHandler(client));
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Remove a previously-attached event handler from the views in the current selection. 
 * This can remove events registered/*w w w.j  av a 2  s .  c  o  m*/
 * by {@link #bind(String, Object, Function)}, {@link #on(String, Function)}, {@link #click()}, 
 * etc.- or directly on the view.
 * @param eventType the name of the event to unbind
 */
public void unbind(String eventType) {
    String method = String.format(Locale.US, "setOn%sListener", capitalize(eventType));
    for (int i = 0; i < this.views.size(); i++) {
        View view = this.views.get(i);
        String listener = String.format(Locale.US, "%s.On%sListener", view.getClass().getName(),
                capitalize(eventType));
        try {
            //dynamically create instance of the listener interface

            Class<?> eventInterface = Class.forName(listener);
            Method setEventListener = view.getClass().getMethod(method, new Class<?>[] { eventInterface });
            EventHandlerCreator proxy = new EventHandlerCreator($.with(view), $.noop());
            Object eventHandler = Proxy.newProxyInstance(eventInterface.getClassLoader(),
                    new Class<?>[] { eventInterface }, proxy);
            setEventListener.invoke(view, eventInterface.cast(eventHandler));

        } catch (Throwable t) {
            Log.w("droidQuery", String.format(Locale.US, "Could not unbind from event %s.", eventType));
        }
    }

}

From source file:org.apache.hadoop.hive.metastore.HiveMetaStoreClientPreCatalog.java

/**
 * Creates a synchronized wrapper for any {@link IMetaStoreClient}.
 * This may be used by multi-threaded applications until we have
 * fixed all reentrancy bugs./*from  w ww.j  a  va2 s.c o  m*/
 *
 * @param client unsynchronized client
 *
 * @return synchronized client
 */
public static IMetaStoreClient newSynchronizedClient(IMetaStoreClient client) {
    return (IMetaStoreClient) Proxy.newProxyInstance(HiveMetaStoreClientPreCatalog.class.getClassLoader(),
            new Class[] { IMetaStoreClient.class }, new SynchronizedHandler(client));
}