Example usage for java.lang.reflect InvocationHandler InvocationHandler

List of usage examples for java.lang.reflect InvocationHandler InvocationHandler

Introduction

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

Prototype

InvocationHandler

Source Link

Usage

From source file:com.google.gdt.eclipse.designer.uibinder.model.util.NameSupport.java

/**
 * Adds <code>JField</code> with given name and @UiField annotation into "form" <code>JType</code>
 * .//www.j av  a  2s.c  om
 */
private void addFormJField(Class<?> componentClass, String name) throws Exception {
    IDevModeBridge bridge = m_context.getState().getDevModeBridge();
    ClassLoader devClassLoader = bridge.getDevClassLoader();
    // prepare "form" JType
    Object formType = bridge.findJType(m_context.getFormType().getFullyQualifiedName());
    // prepare @UiField annotation instance
    Class<?> uiFieldAnnotationClass = devClassLoader.loadClass("com.google.gwt.uibinder.client.UiField");
    java.lang.annotation.Annotation annotation = (java.lang.annotation.Annotation) Proxy.newProxyInstance(
            uiFieldAnnotationClass.getClassLoader(), new Class[] { uiFieldAnnotationClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) {
                    return Boolean.TRUE;
                }
            });
    // add new JField
    Object newField;
    {
        Constructor<?> fieldConstructor;
        Class<?> fieldClass;
        if (m_context.getState().getVersion().isHigherOrSame(Utils.GWT_2_2)) {
            fieldClass = devClassLoader.loadClass("com.google.gwt.dev.javac.typemodel.JField");
            fieldConstructor = ReflectionUtils.getConstructorBySignature(fieldClass,
                    "<init>(com.google.gwt.dev.javac.typemodel.JClassType,java.lang.String,java.util.Map)");
        } else {
            fieldClass = devClassLoader.loadClass("com.google.gwt.core.ext.typeinfo.JField");
            fieldConstructor = ReflectionUtils.getConstructorBySignature(fieldClass,
                    "<init>(com.google.gwt.core.ext.typeinfo.JClassType,java.lang.String,java.util.Map)");
        }
        newField = fieldConstructor.newInstance(formType, name,
                ImmutableMap.of(uiFieldAnnotationClass, annotation));
    }
    // set "widget" JType for JField
    Object widgetType = bridge.findJType(ReflectionUtils.getCanonicalName(componentClass));
    ReflectionUtils.invokeMethod(newField, "setType(com.google.gwt.core.ext.typeinfo.JType)", widgetType);
}

From source file:org.auraframework.http.AuraTestFilter.java

private String buildJsTestTargetUri(DefDescriptor<?> targetDescriptor, TestCaseDef testDef)
        throws QuickFixException {

    Map<String, Object> targetAttributes = testDef.getAttributeValues();

    // Force "legacy" style tests until ready
    if (!ENABLE_FREEFORM_TESTS && targetAttributes == null) {
        targetAttributes = ImmutableMap.of();
    }/*  w  w w .j  av  a2s.c o m*/

    if (targetAttributes != null) {
        // The test has attributes specified, so request for the target component with the test's attributes.
        String hash = "";
        List<NameValuePair> newParams = Lists.newArrayList();
        for (Entry<String, Object> entry : targetAttributes.entrySet()) {
            String key = entry.getKey();
            String value;
            if (entry.getValue() instanceof Map<?, ?> || entry.getValue() instanceof List<?>) {
                value = JsonEncoder.serialize(entry.getValue());
            } else {
                value = entry.getValue().toString();
            }
            if (key.equals("__layout")) {
                hash = value;
            } else {
                newParams.add(new BasicNameValuePair(key, value));
            }
        }
        String qs = URLEncodedUtils.format(newParams, "UTF-8") + hash;
        return createURI(targetDescriptor.getNamespace(), targetDescriptor.getName(),
                targetDescriptor.getDefType(), null, Format.HTML, Authentication.AUTHENTICATED.name(), NO_RUN,
                qs);
    } else {
        // Free-form tests will load only the target component's template.
        // TODO: Allow specifying the template on the test.
        // TODO: Load proxy app for cmps, apps must loadApplication.
        final BaseComponentDef originalDef = (BaseComponentDef) definitionService
                .getDefinition(targetDescriptor);
        final ComponentDef targetTemplate = originalDef.getTemplateDef();
        String newDescriptorString = String.format("%s$%s", targetDescriptor.getDescriptorName(),
                testDef.getName());
        final DefDescriptor<ApplicationDef> newDescriptor = definitionService
                .getDefDescriptor(newDescriptorString, ApplicationDef.class);
        final ApplicationDef dummyDef = definitionService.getDefinition("aurajstest:blank",
                ApplicationDef.class);
        BaseComponentDef targetDef = (BaseComponentDef) Proxy.newProxyInstance(
                originalDef.getClass().getClassLoader(), new Class<?>[] { ApplicationDef.class },
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        switch (method.getName()) {
                        case "getDescriptor":
                            return newDescriptor;
                        case "getTemplateDef":
                            return targetTemplate;
                        case "isLocallyRenderable":
                            return method.invoke(originalDef, args);
                        default:
                            return method.invoke(dummyDef, args);
                        }
                    }
                });
        TestContext testContext = testContextAdapter.getTestContext(testDef.getQualifiedName());
        testContext.getLocalDefs().add(targetDef);
        return createURI(newDescriptor.getNamespace(), newDescriptor.getName(), newDescriptor.getDefType(),
                null, Format.HTML, Authentication.AUTHENTICATED.name(), NO_RUN, null);
    }
}

From source file:net.wequick.small.ApkBundleLauncher.java

@Override
public void setUp(Context context) {
    super.setUp(context);

    Field f;/*from   w  w w .ja va 2  s  . com*/

    // AOP for pending intent
    try {
        f = TaskStackBuilder.class.getDeclaredField("IMPL");
        f.setAccessible(true);
        final Object impl = f.get(TaskStackBuilder.class);
        InvocationHandler aop = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Intent[] intents = (Intent[]) args[1];
                for (Intent intent : intents) {
                    sBundleInstrumentation.wrapIntent(intent);
                    intent.setAction(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                }
                return method.invoke(impl, args);
            }
        };
        Object newImpl = Proxy.newProxyInstance(context.getClassLoader(), impl.getClass().getInterfaces(), aop);
        f.set(TaskStackBuilder.class, newImpl);
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils.java

private static Object createDelegate(final String configKey, Class<?> interfaceClass, Class<?> implClass) {

    try {//  ww  w . ja  v  a 2  s. c  om
        storeInContext(configKey, implClass.newInstance());
    } catch (InstantiationException impossible) {
        // impossible with regular java.util classes
    } catch (IllegalAccessException impossible) {
        // impossible with regular java.util classes
    }

    return Proxy.newProxyInstance(implClass.getClassLoader(), new Class[] { interfaceClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    return method.invoke(getFromContext(configKey), args);
                }
            });
}

From source file:org.apache.juneau.rest.client.RestClient.java

/**
 * Same as {@link #getRemoteableProxy(Class, Object)} but allows you to override the serializer and parser used.
 *
 * @param interfaceClass The interface to create a proxy for.
 * @param restUrl The URL of the REST interface.
 * @param serializer The serializer used to serialize POJOs to the body of the HTTP request.
 * @param parser The parser used to parse POJOs from the body of the HTTP response.
 * @return The new proxy interface.//from   w  w w. j  av a 2  s.  c om
 */
@SuppressWarnings({ "unchecked", "hiding" })
public <T> T getRemoteableProxy(final Class<T> interfaceClass, Object restUrl, final Serializer serializer,
        final Parser parser) {

    if (restUrl == null) {
        Remoteable r = ReflectionUtils.getAnnotation(Remoteable.class, interfaceClass);

        String path = r == null ? "" : trimSlashes(r.path());
        if (path.indexOf("://") == -1) {
            if (path.isEmpty())
                path = interfaceClass.getName();
            if (rootUrl == null)
                throw new RemoteableMetadataException(interfaceClass,
                        "Root URI has not been specified.  Cannot construct absolute path to remoteable proxy.");
            path = trimSlashes(rootUrl) + '/' + path;
        }
        restUrl = path;
    }

    final String restUrl2 = restUrl.toString();

    try {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass },
                new InvocationHandler() {

                    final RemoteableMeta rm = new RemoteableMeta(interfaceClass, restUrl2);

                    @Override /* InvocationHandler */
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        RemoteableMethodMeta rmm = rm.getMethodMeta(method);

                        if (rmm == null)
                            throw new RuntimeException("Method is not exposed as a remoteable method.");

                        try {
                            String url = rmm.getUrl();
                            String httpMethod = rmm.getHttpMethod();
                            RestCall rc = (httpMethod.equals("POST") ? doPost(url) : doGet(url));
                            rc.serializer(serializer).parser(parser);

                            for (RemoteMethodArg a : rmm.getPathArgs())
                                rc.path(a.name, args[a.index], a.serializer);

                            for (RemoteMethodArg a : rmm.getQueryArgs())
                                rc.query(a.name, args[a.index], a.skipIfNE, a.serializer);

                            for (RemoteMethodArg a : rmm.getFormDataArgs())
                                rc.formData(a.name, args[a.index], a.skipIfNE, a.serializer);

                            for (RemoteMethodArg a : rmm.getHeaderArgs())
                                rc.header(a.name, args[a.index], a.skipIfNE, a.serializer);

                            if (rmm.getBodyArg() != null)
                                rc.input(args[rmm.getBodyArg()]);

                            if (rmm.getRequestBeanArgs().length > 0) {
                                BeanSession bs = getBeanContext().createSession();

                                for (Integer i : rmm.getRequestBeanArgs()) {
                                    BeanMap<?> bm = bs.toBeanMap(args[i]);
                                    for (BeanPropertyValue bpv : bm.getValues(true)) {
                                        BeanPropertyMeta pMeta = bpv.getMeta();
                                        Object val = bpv.getValue();

                                        Path p = pMeta.getAnnotation(Path.class);
                                        if (p != null)
                                            rc.path(getName(p.value(), pMeta), val,
                                                    getPartSerializer(p.serializer()));

                                        Query q1 = pMeta.getAnnotation(Query.class);
                                        if (q1 != null)
                                            rc.query(getName(q1.value(), pMeta), val, false,
                                                    getPartSerializer(q1.serializer()));

                                        QueryIfNE q2 = pMeta.getAnnotation(QueryIfNE.class);
                                        if (q2 != null)
                                            rc.query(getName(q2.value(), pMeta), val, true,
                                                    getPartSerializer(q2.serializer()));

                                        FormData f1 = pMeta.getAnnotation(FormData.class);
                                        if (f1 != null)
                                            rc.formData(getName(f1.value(), pMeta), val, false,
                                                    getPartSerializer(f1.serializer()));

                                        FormDataIfNE f2 = pMeta.getAnnotation(FormDataIfNE.class);
                                        if (f2 != null)
                                            rc.formData(getName(f2.value(), pMeta), val, true,
                                                    getPartSerializer(f2.serializer()));

                                        org.apache.juneau.remoteable.Header h1 = pMeta
                                                .getAnnotation(org.apache.juneau.remoteable.Header.class);
                                        if (h1 != null)
                                            rc.header(getName(h1.value(), pMeta), val, false,
                                                    getPartSerializer(h1.serializer()));

                                        HeaderIfNE h2 = pMeta.getAnnotation(HeaderIfNE.class);
                                        if (h2 != null)
                                            rc.header(getName(h2.value(), pMeta), val, true,
                                                    getPartSerializer(h2.serializer()));
                                    }
                                }
                            }

                            if (rmm.getOtherArgs().length > 0) {
                                Object[] otherArgs = new Object[rmm.getOtherArgs().length];
                                int i = 0;
                                for (Integer otherArg : rmm.getOtherArgs())
                                    otherArgs[i++] = args[otherArg];
                                rc.input(otherArgs);
                            }

                            return rc.getResponse(method.getGenericReturnType());

                        } catch (RestCallException e) {
                            // Try to throw original exception if possible.
                            e.throwServerException(interfaceClass.getClassLoader());
                            throw new RuntimeException(e);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.universAAL.itests.IntegrationTest.java

/**
 * This method processes configured urls of pax artifacts (composites and
 * bundles) and returns single list of bundles.
 *
 * @return Returns list of resources.//from   www .j  ava2s  .  c om
 * @throws Exception
 *             This method can throw multiple exceptions so it was
 *             aggregated to the most general one - the Exception.
 */
private List<Resource> processPaxArtifactUrls() throws Exception {
    InvocationHandler dummyProxyHandler = new InvocationHandler() {
        public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
            return null;
        }
    };
    PropertyResolver dummyPropertyResolver = new PropertyResolver() {
        public String get(final String arg0) {
            return null;
        }
    };
    BundleContext dummyBundleContext = (BundleContext) Proxy.newProxyInstance(
            BundleContext.class.getClassLoader(), new Class[] { BundleContext.class }, dummyProxyHandler);

    ProvisionServiceImpl provisionService = new ProvisionServiceImpl(dummyBundleContext);
    CompositeScanner compositeScanner = new CompositeScanner(dummyPropertyResolver, provisionService);
    BundleScanner bundleScanner = new BundleScanner(dummyPropertyResolver);

    provisionService.addScanner(bundleScanner, "scan-bundle");
    provisionService.addScanner(compositeScanner, "scan-composite");
    List<Resource> bundleResource = new ArrayList<Resource>();
    for (String compositeUrl : paxArtifactsUrls) {
        List<ScannedBundle> scannedBundles = provisionService.scan(compositeUrl);
        Set<String> bundlesAlreadyAdded = new HashSet<String>();
        for (ScannedBundle scannedBundle : scannedBundles) {
            BundleToLaunch bToLaunch = filterArtifactUrl(scannedBundle.getLocation());
            if (bToLaunch != null) {
                if (!bundlesAlreadyAdded.contains(bToLaunch.bundleUrl)) {
                    bundlesAlreadyAdded.add(bToLaunch.bundleUrl);
                    bundleResource.add(new UrlResource(bToLaunch.bundleUrl));
                }
            }
        }
    }
    return bundleResource;
}

From source file:org.kchine.r.server.http.RHttpProxy.java

public static RServices getR(final String url, final String sessionId, final boolean handleCallbacks,
        final int maxNbrRactionsOnPop) {
    final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    if (System.getProperty("proxy_host") != null && !System.getProperty("proxy_host").equals("")) {
        httpClient.getHostConfiguration().setProxy(System.getProperty("proxy_host"),
                Integer.decode(System.getProperty("proxy_port")));
    }/* w w w  . j  a  va  2  s . c om*/
    final Object proxy = Proxy.newProxyInstance(RHttpProxy.class.getClassLoader(), new Class<?>[] {
            RServices.class, ScilabServices.class, OpenOfficeServices.class, HttpMarker.class },
            new InvocationHandler() {

                Vector<RCallBack> rCallbacks = new Vector<RCallBack>();
                Vector<RCollaborationListener> rCollaborationListeners = new Vector<RCollaborationListener>();
                Vector<RConsoleActionListener> rConsoleActionListeners = new Vector<RConsoleActionListener>();

                GenericCallbackDevice genericCallBackDevice = null;
                Thread popThread = null;

                boolean _stopThreads = false;
                {
                    if (handleCallbacks) {

                        try {
                            genericCallBackDevice = newGenericCallbackDevice(url, sessionId);
                            popThread = new Thread(new Runnable() {
                                public void run() {
                                    while (true && !_stopThreads) {
                                        popActions();

                                        try {
                                            Thread.sleep(10);
                                        } catch (Exception e) {
                                        }
                                    }

                                }
                            });
                            popThread.start();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                private synchronized void popActions() {
                    try {

                        Vector<RAction> ractions = genericCallBackDevice.popRActions(maxNbrRactionsOnPop);
                        if (ractions != null) {

                            for (int i = 0; i < ractions.size(); ++i) {
                                final RAction action = ractions.elementAt(i);
                                if (action.getActionName().equals("notify")) {
                                    HashMap<String, String> parameters = (HashMap<String, String>) action
                                            .getAttributes().get("parameters");
                                    for (int j = 0; j < rCallbacks.size(); ++j) {
                                        rCallbacks.elementAt(j).notify(parameters);
                                    }
                                }
                                if (action.getActionName().equals("rConsoleActionPerformed")) {
                                    RConsoleAction consoleAction = (RConsoleAction) action.getAttributes()
                                            .get("consoleAction");
                                    for (int j = 0; j < rConsoleActionListeners.size(); ++j) {
                                        rConsoleActionListeners.elementAt(j)
                                                .rConsoleActionPerformed(consoleAction);
                                    }
                                } else if (action.getActionName().equals("chat")) {
                                    String sourceUID = (String) action.getAttributes().get("sourceUID");
                                    String user = (String) action.getAttributes().get("user");
                                    String message = (String) action.getAttributes().get("message");
                                    for (int j = 0; j < rCollaborationListeners.size(); ++j) {
                                        rCollaborationListeners.elementAt(j).chat(sourceUID, user, message);
                                    }
                                } else if (action.getActionName().equals("consolePrint")) {
                                    String sourceUID = (String) action.getAttributes().get("sourceUID");
                                    String user = (String) action.getAttributes().get("user");
                                    String expression = (String) action.getAttributes().get("expression");
                                    String result = (String) action.getAttributes().get("result");
                                    for (int j = 0; j < rCollaborationListeners.size(); ++j) {
                                        rCollaborationListeners.elementAt(j).consolePrint(sourceUID, user,
                                                expression, result);
                                    }
                                }
                            }

                        }

                    } catch (NotLoggedInException nle) {

                        nle.printStackTrace();
                    } catch (Exception e) {

                        e.printStackTrace();
                    }

                }

                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = null;
                    if (method.getName().equals("newDevice")) {
                        result = newDevice(url, sessionId, (Integer) args[0], (Integer) args[1], false);
                    } else if (method.getName().equals("newBroadcastedDevice")) {
                        result = newDevice(url, sessionId, (Integer) args[0], (Integer) args[1], true);
                    } else if (method.getName().equals("listDevices")) {
                        result = listDevices(url, sessionId);
                    } else if (method.getName().equals("addRCallback")) {
                        rCallbacks.add((RCallBack) args[0]);
                    } else if (method.getName().equals("removeRCallback")) {
                        rCallbacks.remove((RCallBack) args[0]);
                    } else if (method.getName().equals("removeAllRCallbacks")) {
                        rCallbacks.removeAllElements();
                    }

            else if (method.getName().equals("addRCollaborationListener")) {
                        rCollaborationListeners.add((RCollaborationListener) args[0]);
                    } else if (method.getName().equals("removeRCollaborationListener")) {
                        rCollaborationListeners.remove((RCollaborationListener) args[0]);
                    } else if (method.getName().equals("removeAllRCollaborationListeners")) {
                        rCollaborationListeners.removeAllElements();
                    }

            else if (method.getName().equals("addRConsoleActionListener")) {
                        rConsoleActionListeners.add((RConsoleActionListener) args[0]);
                    } else if (method.getName().equals("removeRConsoleActionListener")) {
                        rConsoleActionListeners.remove((RConsoleActionListener) args[0]);
                    } else if (method.getName().equals("removeAllRConsoleActionListeners")) {
                        rConsoleActionListeners.removeAllElements();
                    }

            else if (method.getName().equals("newSpreadsheetTableModelRemote")) {
                        SpreadsheetModelDevice d = newSpreadsheetModelDevice(url, sessionId, "",
                                ((Integer) args[0]).toString(), ((Integer) args[1]).toString());
                        result = new SpreadsheetModelRemoteProxy(d);
                    } else if (method.getName().equals("getSpreadsheetTableModelRemote")) {
                        SpreadsheetModelDevice d = newSpreadsheetModelDevice(url, sessionId, (String) args[0],
                                "", "");
                        result = new SpreadsheetModelRemoteProxy(d);
                    }

            else if (method.getName().equals("stopThreads")) {
                        _stopThreads = true;
                        popThread.join();
                        try {
                            // IMPORTANT !!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            // genericCallBackDevice.dispose();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (method.getName().equals("popActions")) {
                        popActions();
                    }

            else {

                        result = RHttpProxy.invoke(url, sessionId, "R", method.getName(),
                                method.getParameterTypes(), args, httpClient);
                    }

                    if (method.getName().equals("asynchronousConsoleSubmit")) {
                        popActions();
                    }

                    return result;

                }
            });

    return (RServices) proxy;
}

From source file:com.ikanow.aleph2.data_model.utils.CrudServiceUtils.java

/** CRUD service proxy that optionally adds an extra term and allows the user to modify the results after they've run (eg to apply security service settings) 
 * @author Alex//from   w  w w.j  a v  a2  s  .  c o  m
 */
@SuppressWarnings("unchecked")
public static <T> ICrudService<T> intercept(final Class<T> clazz, final ICrudService<T> delegate,
        final Optional<QueryComponent<T>> extra_query,
        final Optional<Function<QueryComponent<T>, QueryComponent<T>>> query_transform,
        final Map<String, BiFunction<Object, Object[], Object>> interceptors,
        final Optional<BiFunction<Object, Object[], Object>> default_interceptor) {
    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            final Method m = delegate.getClass().getMethod(method.getName(), method.getParameterTypes());

            // First off, apply the extra term to any relevant args:
            final Object[] args_with_extra_query_pretransform = query_transform.map(q -> {
                return (null != args) ? Arrays.stream(args)
                        .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                ? q.apply((QueryComponent<T>) o)
                                : o)
                        .collect(Collectors.toList()).toArray() : args;
            }).orElse(args);

            final Object[] args_with_extra_query = extra_query.map(q -> {
                return (null != args_with_extra_query_pretransform)
                        ? Arrays.stream(args_with_extra_query_pretransform)
                                .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                        ? CrudUtils.allOf((QueryComponent<T>) o, q)
                                        : o)
                                .collect(Collectors.toList()).toArray()
                        : args_with_extra_query_pretransform;
            }).orElse(args_with_extra_query_pretransform);

            // Special cases for: readOnlyVersion, getFilterdRepo / countObjects / getRawService / *byId
            final Object o = Lambdas.get(() -> {
                final SingleQueryComponent<T> base_query = JsonNode.class.equals(clazz)
                        ? (SingleQueryComponent<T>) CrudUtils.allOf()
                        : CrudUtils.allOf(clazz);

                try {
                    if (extra_query.isPresent() && m.getName().equals("countObjects")) { // special case....change method and apply spec
                        return delegate.countObjectsBySpec(extra_query.get());
                    } else if (extra_query.isPresent() && m.getName().equals("getObjectById")) { // convert from id to spec and append extra_query
                        if (1 == args.length) {
                            return delegate.getObjectBySpec(CrudUtils.allOf(extra_query.get(),
                                    base_query.when(JsonUtils._ID, args[0])));
                        } else {
                            return delegate.getObjectBySpec(
                                    CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                    (List<String>) args[1], (Boolean) args[2]);
                        }
                    } else if (extra_query.isPresent() && m.getName().equals("deleteDatastore")) {
                        CompletableFuture<Long> l = delegate.deleteObjectsBySpec(extra_query.get());
                        return l.thenApply(ll -> ll > 0);
                    } else if (extra_query.isPresent() && m.getName().equals("deleteObjectById")) { // convert from id to spec and append extra_query
                        return delegate.deleteObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])));
                    } else if (extra_query.isPresent() && m.getName().equals("updateObjectById")) { // convert from id to spec and append extra_query
                        return delegate.updateObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                Optional.empty(), (UpdateComponent<T>) args[1]);
                    } else if (m.getName().equals("getRawService")) { // special case....convert the default query to JSON, if present
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        Optional<QueryComponent<JsonNode>> json_extra_query = extra_query
                                .map(qc -> qc.toJson());
                        return intercept(JsonNode.class, (ICrudService<JsonNode>) o_internal, json_extra_query,
                                Optional.empty(), interceptors, default_interceptor);
                    } else { // wrap any CrudService types
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        return (null != o_internal)
                                && ICrudService.class.isAssignableFrom(o_internal.getClass())
                                        ? intercept(clazz, (ICrudService<T>) o_internal, extra_query,
                                                Optional.empty(), interceptors, default_interceptor)
                                        : o_internal;
                    }
                } catch (IllegalAccessException ee) {
                    throw new RuntimeException(ee);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e.getCause().getMessage(), e);
                }
            });

            return interceptors
                    .getOrDefault(m.getName(),
                            default_interceptor.orElse(CrudServiceUtils::identityInterceptor))
                    .apply(o, args_with_extra_query);
        }
    };

    return ICrudService.IReadOnlyCrudService.class.isAssignableFrom(delegate.getClass())
            ? (ICrudService<T>) Proxy.newProxyInstance(ICrudService.IReadOnlyCrudService.class.getClassLoader(),
                    new Class[] { ICrudService.IReadOnlyCrudService.class }, handler)
            : (ICrudService<T>) Proxy.newProxyInstance(ICrudService.class.getClassLoader(),
                    new Class[] { ICrudService.class }, handler);
}

From source file:org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.java

/**
 * Wrap the given {@code SessionFactory} with a proxy, if demanded.
 * <p>The default implementation wraps the given {@code SessionFactory} as a Spring
 * {@link DisposableBean} proxy in order to call {@link SessionFactory#close()} on
 * {@code ApplicationContext} {@linkplain ConfigurableApplicationContext#close() shutdown}.
 * <p>Subclasses may override this to implement transaction awareness through
 * a {@code SessionFactory} proxy for example, or even to avoid creation of the
 * {@code DisposableBean} proxy altogether.
 * @param rawSf the raw {@code SessionFactory} as built by {@link #buildSessionFactory()}
 * @return the {@code SessionFactory} reference to expose
 * @see #buildSessionFactory()//  www. ja va2s.  c om
 */
protected SessionFactory wrapSessionFactoryIfNecessary(final SessionFactory rawSf) {
    return (SessionFactory) Proxy.newProxyInstance(this.beanClassLoader,
            new Class<?>[] { SessionFactory.class, DisposableBean.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (ReflectionUtils.isToStringMethod(method)) {
                        return String.format("DisposableBean proxy for SessionFactory [%s]", rawSf.toString());
                    }
                    if (method.equals(DisposableBean.class.getMethod("destroy"))) {
                        closeHibernateSessionFactory(SessionFactoryBuilderSupport.this, rawSf);
                        rawSf.close();
                        return null;
                    }
                    return method.invoke(rawSf, args);
                }
            });
}

From source file:com.google.dart.tools.ui.internal.text.SemanticHighlightingTest.java

private void preparePositions() throws Exception {
    final IDocument document = new Document(testCode);
    SemanticHighlightingReconciler reconciler = new SemanticHighlightingReconciler();
    // configure//from  w w w .  j  av  a2 s.  c o m
    ReflectionUtils.setField(reconciler, "fSourceViewer", Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class[] { ISourceViewer.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("getDocument")) {
                        return document;
                    }
                    return null;
                }
            }));
    ReflectionUtils.setField(reconciler, "fJobSemanticHighlightings", highlighters);
    ReflectionUtils.setField(reconciler, "fJobHighlightings", styles);
    ReflectionUtils.setField(reconciler, "fJobPresenter", new SemanticHighlightingPresenter());
    // call "reconcilePositions"
    ReflectionUtils.invokeMethod(reconciler, "reconcilePositions(com.google.dart.engine.ast.CompilationUnit)",
            testUnit);
    // get result
    positions = ReflectionUtils.getFieldObject(reconciler, "fAddedPositions");
    // touch "default"
    for (HighlightedPosition position : positions) {
        Highlighting style = position.getHighlighting();
        SemanticHighlighting highlighting = styleToHighlighting.get(style);
        highlighting.getDisplayName();
        highlighting.isEnabledByDefault();
        highlighting.isBoldByDefault();
        highlighting.isItalicByDefault();
        highlighting.isStrikethroughByDefault();
        highlighting.isUnderlineByDefault();
        highlighting.getDefaultDefaultTextColor();
        highlighting.getDefaultStyle();
        highlighting.getDefaultTextColor();
    }
}