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.apache.axis2.jaxws.spi.ServiceDelegate.java

@Override
public <T> T getPort(QName portName, Class<T> sei, WebServiceFeature... features) {
    verifyServiceDescriptionActive();//from   w  w w . j ava 2  s.  c o m
    /* TODO Check to see if WSDL Location is provided.
     * if not check WebService annotation's WSDLLocation
     * if both are not provided then throw exception.
     * (JLB): I'm not sure lack of WSDL should cause an exception
     */

    if (!isValidWSDLLocation()) {
        //TODO: Should I throw Exception if no WSDL
        //throw ExceptionFactory.makeWebServiceException("WSLD Not found");
    }
    if (sei == null) {
        throw ExceptionFactory
                .makeWebServiceException(Messages.getMessage("getPortInvalidSEI", portName.toString(), "null"));
    }

    DescriptionBuilderComposite sparseComposite = getPortMetadata();
    resetPortMetadata();
    EndpointDescription endpointDesc = null;
    if (sparseComposite != null) {
        endpointDesc = DescriptionFactory.updateEndpoint(serviceDescription, sei, portName,
                DescriptionFactory.UpdateType.GET_PORT, sparseComposite, this);
    } else {
        endpointDesc = DescriptionFactory.updateEndpoint(serviceDescription, sei, portName,
                DescriptionFactory.UpdateType.GET_PORT, null, this);

    }
    if (endpointDesc == null) {
        throw ExceptionFactory.makeWebServiceException(Messages.getMessage("portErr", portName.toString()));
    }

    String[] interfacesNames = new String[] { sei.getName(),
            org.apache.axis2.jaxws.spi.BindingProvider.class.getName() };

    // As required by java.lang.reflect.Proxy, ensure that the interfaces
    // for the proxy are loadable by the same class loader. 
    Class[] interfaces = null;
    // First, let's try loading the interfaces with the SEI classLoader
    ClassLoader classLoader = getClassLoader(sei);
    try {
        interfaces = loadClasses(classLoader, interfacesNames);
    } catch (ClassNotFoundException e1) {
        // Let's try with context classLoader now
        classLoader = getContextClassLoader();
        try {
            interfaces = loadClasses(classLoader, interfacesNames);
        } catch (ClassNotFoundException e2) {
            throw ExceptionFactory.makeWebServiceException(Messages.getMessage("portErr1"), e2);
        }
    }

    JAXWSProxyHandler proxyHandler = new JAXWSProxyHandler(this, interfaces[0], endpointDesc, features);
    Object proxyClass = Proxy.newProxyInstance(classLoader, interfaces, proxyHandler);
    return sei.cast(proxyClass);
}

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")));
    }// www.j a  va  2 s .  c  o  m
    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: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  ww  w . j a  va2  s  .c o m*/
 * @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:io.coala.json.DynaBean.java

/**
 * @param om the {@link ObjectMapper} for get and set de/serialization
 * @param type the type of {@link Proxy} to generate
 * @param bean the (prepared) {@link DynaBean} for proxied getters/setters
 * @param imports default value {@link Properties} of the bean
 * @return a {@link Proxy} instance backed by an empty {@link DynaBean}
 *///from   w  w w  .j  a  va  2s.c o  m
@SuppressWarnings("unchecked")
public static <T> T proxyOf(final ObjectMapper om, final Class<T> type, final DynaBean bean,
        final Properties... imports) {
    //      if( !type.isAnnotationPresent( BeanProxy.class ) )
    //         throw ExceptionFactory.createUnchecked( "{} is not a @{}", type,
    //               BeanProxy.class.getSimpleName() );

    return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type },
            new DynaBeanInvocationHandler(om, type, bean, imports));
}

From source file:org.broadleafcommerce.core.catalog.domain.SkuImpl.java

protected Money getRetailPriceInternal() {
    Money returnPrice = null;/*from w w  w  . ja v  a2 s .  c  o  m*/
    Money optionValueAdjustments = null;

    if (SkuPricingConsiderationContext.hasDynamicPricing()) {
        // We have dynamic pricing, so we will pull the retail price from there
        if (dynamicPrices == null) {
            DefaultDynamicSkuPricingInvocationHandler handler = new DefaultDynamicSkuPricingInvocationHandler(
                    this);
            Sku proxy = (Sku) Proxy.newProxyInstance(getClass().getClassLoader(),
                    ClassUtils.getAllInterfacesForClass(getClass()), handler);

            dynamicPrices = SkuPricingConsiderationContext.getSkuPricingService().getSkuPrices(proxy,
                    SkuPricingConsiderationContext.getSkuPricingConsiderationContext());
        }

        returnPrice = dynamicPrices.getRetailPrice();
        optionValueAdjustments = dynamicPrices.getPriceAdjustment();
    } else if (retailPrice != null) {
        returnPrice = new Money(retailPrice, getCurrency());
    }

    if (returnPrice == null && hasDefaultSku()) {
        // Otherwise, we'll pull the retail price from the default sku
        returnPrice = lookupDefaultSku().getRetailPrice();
        optionValueAdjustments = getProductOptionValueAdjustments();
    }

    if (returnPrice != null && optionValueAdjustments != null) {
        returnPrice = returnPrice.add(optionValueAdjustments);
    }

    return returnPrice;
}

From source file:org.broadleafcommerce.core.catalog.domain.SkuImpl.java

@Override
public DynamicSkuPrices getPriceData() {
    if (SkuPricingConsiderationContext.hasDynamicPricing()) {
        if (dynamicPrices == null) {
            DefaultDynamicSkuPricingInvocationHandler handler = new DefaultDynamicSkuPricingInvocationHandler(
                    this);
            Sku proxy = (Sku) Proxy.newProxyInstance(getClass().getClassLoader(),
                    ClassUtils.getAllInterfacesForClass(getClass()), handler);

            dynamicPrices = SkuPricingConsiderationContext.getSkuPricingService().getSkuPrices(proxy,
                    SkuPricingConsiderationContext.getSkuPricingConsiderationContext());
        }/*from w ww  .  java 2 s.  c o m*/
        return dynamicPrices;
    } else {
        DynamicSkuPrices dsp = new DynamicSkuPrices();
        BroadleafCurrency tmpCurrency;
        if (currency != null) {
            tmpCurrency = currency;
        } else {
            tmpCurrency = BroadleafRequestContext.getCurrency();
        }
        if (retailPrice != null) {
            dsp.setRetailPrice(new Money(retailPrice, tmpCurrency));
        }
        if (salePrice != null) {
            dsp.setSalePrice(new Money(salePrice, tmpCurrency));
        }
        return dsp;
    }
}

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/*  ww  w  .ja va  2s.  com*/
    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();
    }
}

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

/**
 * Gets a collection property value.//from w  w w  . ja va 2  s.  co  m
 *
 * @param proxy
 *     the proxy to get the property of.
 * @param propertyDescriptor
 *     the property descriptor to get the value for.
 * @return the property value.
 */
@SuppressWarnings({ "unchecked", "ConstantConditions" })
protected Object getCollectionProperty(Object proxy,
        ICollectionPropertyDescriptor<? extends IComponent> propertyDescriptor) {
    String propertyName = propertyDescriptor.getName();
    try {
        Object property = straightGetProperty(proxy, propertyName);
        if (property == null) {
            property = collectionFactory.createComponentCollection(
                    propertyDescriptor.getReferencedDescriptor().getCollectionInterface());
            storeProperty(propertyName, property);
        }
        if (property instanceof List<?>) {
            List<IComponent> propertyAsList = (List<IComponent>) property;
            for (int i = 0; i < propertyAsList.size(); i++) {
                IComponent referent = propertyAsList.get(i);
                IComponent decorated = decorateReferent(referent, propertyDescriptor.getReferencedDescriptor()
                        .getElementDescriptor().getComponentDescriptor());
                if (decorated != referent) {
                    propertyAsList.set(i, decorated);
                }
                if (referent == null) {
                    if (proxy instanceof IEntity) {
                        LOG.warn("A null element was detected in indexed list [{}] on {}, id {} at index {}",
                                propertyName, ((IEntity) proxy).getComponentContract().getName(),
                                ((IEntity) proxy).getId(), i);
                        LOG.warn(
                                "This might be normal but sometimes it reveals a mis-use of indexed collection property accessors.");
                    }
                } else if (EntityHelper.isInlineComponentReference(
                        propertyDescriptor.getReferencedDescriptor().getElementDescriptor())) {
                    if (decorated != null) {
                        decorated.setOwningComponent((IComponent) proxy, propertyDescriptor);
                    }
                }
            }
        } else if (property instanceof Set<?>) {
            Set<IComponent> propertyAsSet = (Set<IComponent>) property;
            for (IComponent referent : new THashSet<>(propertyAsSet)) {
                IComponent decorated = decorateReferent(referent, propertyDescriptor.getReferencedDescriptor()
                        .getElementDescriptor().getComponentDescriptor());
                if (decorated != referent) {
                    propertyAsSet.add(decorated);
                }
                if (EntityHelper.isInlineComponentReference(
                        propertyDescriptor.getReferencedDescriptor().getElementDescriptor())) {
                    if (decorated != null) {
                        decorated.setOwningComponent((IComponent) proxy, propertyDescriptor);
                    }
                }
            }
        }
        if (isCollectionSortOnReadEnabled() && collectionSortEnabled) {
            inlineComponentFactory.sortCollectionProperty((IComponent) proxy, propertyName);
        }
        if (property instanceof ICollectionWrapper<?>) {
            return property;
        }
        List<Class<?>> implementedInterfaces = new ArrayList<>();
        implementedInterfaces.add(ICollectionWrapper.class);
        implementedInterfaces.addAll(Arrays.asList(property.getClass().getInterfaces()));
        return Proxy.newProxyInstance(AbstractComponentInvocationHandler.class.getClassLoader(),
                implementedInterfaces.toArray(new Class[implementedInterfaces.size()]),
                new PersistentCollectionWrapper<>(
                        (Collection<IComponent>) property, (IComponent) proxy, propertyName, propertyDescriptor
                                .getCollectionDescriptor().getElementDescriptor().getComponentContract(),
                        accessorFactory));
    } catch (RuntimeException re) {
        LOG.error("Error when retrieving [{}] collection property on {}", propertyName, proxy);
        throw (re);
    }
}

From source file:com.hortonworks.registries.schemaregistry.client.SchemaRegistryClient.java

private <T> T createInstance(SerDesInfo serDesInfo, Set<Class<?>> interfaceClasses) {
    if (interfaceClasses == null || interfaceClasses.isEmpty()) {
        throw new IllegalArgumentException("interfaceClasses array must be neither null nor empty.");
    }/*  ww w. jav  a  2s  .  co  m*/

    // loading serializer, create a class loader and and keep them in cache.
    String fileId = serDesInfo.getFileId();
    // get class loader for this file ID
    ClassLoader classLoader = classLoaderCache.getClassLoader(fileId);

    T t;
    try {
        String className = serDesInfo.getClassName();
        Class<T> clazz = (Class<T>) Class.forName(className, true, classLoader);
        t = clazz.newInstance();
        List<Class<?>> classes = new ArrayList<>();
        for (Class<?> interfaceClass : interfaceClasses) {
            if (interfaceClass.isAssignableFrom(clazz)) {
                classes.add(interfaceClass);
            }
        }

        if (classes.isEmpty()) {
            throw new RuntimeException(
                    "Given Serialize/Deserializer " + className + " class does not implement any "
                            + "one of the registered interfaces: " + interfaceClasses);
        }

        Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                classes.toArray(new Class[classes.size()]),
                new ClassLoaderAwareInvocationHandler(classLoader, t));
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new SerDesException(e);
    }

    return t;
}

From source file:de.javakaffee.web.msm.integration.TestUtils.java

@java.lang.SuppressWarnings("unchecked")
public static <T, V> T assertWaitingWithProxy(final Predicate<V> predicate, final long maxTimeToWait,
        final T objectToProxy) {
    final Class<?>[] interfaces = objectToProxy.getClass().getInterfaces();
    return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces,
            new InvocationHandler() {
                @Override//from www  .  j a  v  a2s . c o  m
                public Object invoke(final Object proxy, final Method method, final Object[] args)
                        throws Throwable {
                    return assertPredicateWaiting(predicate, maxTimeToWait, objectToProxy, method, args);
                }
            });
}