List of usage examples for java.lang.reflect InvocationHandler InvocationHandler
InvocationHandler
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 ww w .j a va 2 s.c om public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { return assertPredicateWaiting(predicate, maxTimeToWait, objectToProxy, method, args); } }); }
From source file:org.apache.atlas.TestUtils.java
/** * Adds a proxy wrapper around the specified MetadataService that automatically * resets the request context before every call. * * @param delegate/*from w w w. j a v a2 s . c o m*/ * @return */ public static MetadataService addSessionCleanupWrapper(final MetadataService delegate) { return (MetadataService) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { MetadataService.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { resetRequestContext(); Object result = method.invoke(delegate, args); return result; } catch (InvocationTargetException e) { e.getCause().printStackTrace(); throw e.getCause(); } catch (Throwable t) { t.printStackTrace(); throw t; } } }); }
From source file:org.nuunframework.kernel.Kernel.java
private InitContext proxyfy(final InitContext initContext, final Collection<Plugin> requiredPlugins, final Collection<Plugin> dependentPlugins) { return (InitContext) Proxy.newProxyInstance( // initContext.getClass().getClassLoader(), // new Class[] { InitContext.class }, // new InvocationHandler() { @Override//from w w w. j a va 2 s.c om public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("pluginsRequired")) { return requiredPlugins; } else if (method.getName().equals("dependentPlugins")) { return dependentPlugins; } else { return method.invoke(initContext, args); } } }); }
From source file:org.apache.atlas.TestUtils.java
/** * Adds a proxy wrapper around the specified MetadataRepository that automatically * resets the request context before every call and either commits or rolls * back the graph transaction after every call. * * @param delegate//from w ww . jav a 2s. c o m * @return */ public static MetadataRepository addTransactionWrapper(final MetadataRepository delegate) { return (MetadataRepository) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { MetadataRepository.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { boolean useTransaction = GraphBackedMetadataRepository.class .getMethod(method.getName(), method.getParameterTypes()) .isAnnotationPresent(GraphTransaction.class); try { resetRequestContext(); Object result = method.invoke(delegate, args); if (useTransaction) { System.out.println("Committing changes"); getGraph().commit(); System.out.println("Commit succeeded."); } return result; } catch (InvocationTargetException e) { e.getCause().printStackTrace(); if (useTransaction) { System.out.println("Rolling back changes due to exception."); getGraph().rollback(); } throw e.getCause(); } catch (Throwable t) { t.printStackTrace(); if (useTransaction) { System.out.println("Rolling back changes due to exception."); getGraph().rollback(); } throw t; } } }); }
From source file:org.sparkcommerce.core.catalog.domain.SkuImpl.java
@Override @Deprecated/*from w ww.j av a2 s .c o m*/ public List<ProductOptionValue> getProductOptionValues() { //Changing this API to Set is ill-advised (especially in a patch release). The tendrils are widespread. Instead //we just migrate the call from the List to the internal Set representation. This is in response //to https://github.com/SparkCommerce/SparkCommerce/issues/917. return (List<ProductOptionValue>) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { List.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return MethodUtils.invokeMethod(productOptionValues, method.getName(), args, method.getParameterTypes()); } }); }
From source file:com.openddal.test.BaseTestCase.java
/** * Verify the next method call on the object will throw an exception. * * @param <T> the class of the object * @param verifier the result verifier to call * @param obj the object to wrap// w w w. j a va 2s.c om * @return a proxy for the object */ @SuppressWarnings("unchecked") protected <T> T assertThrows(final ResultVerifier verifier, final T obj) { Class<?> c = obj.getClass(); InvocationHandler ih = new InvocationHandler() { private Exception called = new Exception("No method called"); @Override protected void finalize() { if (called != null) { called.printStackTrace(System.err); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Exception { try { called = null; Object ret = method.invoke(obj, args); verifier.verify(ret, null, method, args); return ret; } catch (InvocationTargetException e) { verifier.verify(null, e.getTargetException(), method, args); Class<?> retClass = method.getReturnType(); if (!retClass.isPrimitive()) { return null; } if (retClass == boolean.class) { return false; } else if (retClass == byte.class) { return (byte) 0; } else if (retClass == char.class) { return (char) 0; } else if (retClass == short.class) { return (short) 0; } else if (retClass == int.class) { return 0; } else if (retClass == long.class) { return 0L; } else if (retClass == float.class) { return 0F; } else if (retClass == double.class) { return 0D; } return null; } } }; if (!ProxyCodeGenerator.isGenerated(c)) { Class<?>[] interfaces = c.getInterfaces(); if (Modifier.isFinal(c.getModifiers()) || (interfaces.length > 0 && getClass() != c)) { // interface class proxies if (interfaces.length == 0) { throw new RuntimeException("Can not create a proxy for the class " + c.getSimpleName() + " because it doesn't implement any interfaces and is final"); } return (T) Proxy.newProxyInstance(c.getClassLoader(), interfaces, ih); } } try { Class<?> pc = ProxyCodeGenerator.getClassProxy(c); Constructor<?> cons = pc.getConstructor(InvocationHandler.class); return (T) cons.newInstance(ih); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.broadleafcommerce.core.catalog.domain.SkuImpl.java
@Override @Deprecated/*from w w w .jav a2 s .c o m*/ public List<ProductOptionValue> getProductOptionValues() { //Changing this API to Set is ill-advised (especially in a patch release). The tendrils are widespread. Instead //we just migrate the call from the List to the internal Set representation. This is in response //to https://github.com/BroadleafCommerce/BroadleafCommerce/issues/917. return (List<ProductOptionValue>) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { List.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return MethodUtils.invokeMethod(getProductOptionValuesCollection(), method.getName(), args, method.getParameterTypes()); } }); }
From source file:com.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java
@Test public void testOffsetLagMetric() throws Exception { final File testDataDir = new File("target", UUID.randomUUID().toString()); Assert.assertTrue(testDataDir.mkdirs()); final File file = new File(testDataDir, "file.txt-1"); Files.write(file.toPath(), Arrays.asList("A", "B", "C"), StandardCharsets.UTF_8); FileInfo fileInfo = new FileInfo(); fileInfo.fileFullPath = testDataDir.getAbsolutePath() + "/file.txt-1"; fileInfo.fileRollMode = FileRollMode.ALPHABETICAL; fileInfo.firstFile = ""; fileInfo.patternForToken = ".*"; FileTailConfigBean conf = new FileTailConfigBean(); conf.dataFormat = DataFormat.TEXT;/* w w w . ja v a 2 s . co m*/ conf.multiLineMainPattern = ""; conf.batchSize = 25; conf.maxWaitTimeSecs = 1; conf.fileInfos = Arrays.asList(fileInfo); conf.postProcessing = PostProcessingOptions.NONE; conf.dataFormatConfig.textMaxLineLen = 1024; FileTailSource source = PowerMockito.spy(new FileTailSource(conf, SCAN_INTERVAL)); //Intercept getOffsetsLag private method which calculates the offsetLag //in the files and write some data to file so there is an offset lag. PowerMockito.replace(MemberMatcher.method(FileTailSource.class, "calculateOffsetLagMetric", Map.class)) .with(new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //This will add 6 more (D, E, F) to the file and move the file size to 12 bytes //but we would have read just 6 bytes (A, B, C). Files.write(file.toPath(), Arrays.asList("D", "E", "F"), StandardCharsets.UTF_8, StandardOpenOption.APPEND); //call the real getOffsetsLag private method return method.invoke(proxy, args); } }); SourceRunner runner = createRunner(source); try { runner.runInit(); StageRunner.Output output = runner.runProduce(null, 10); // Make sure there are only three records. Assert.assertEquals(3, output.getRecords().get("lane").size()); Map<String, Counter> offsetLag = (Map<String, Counter>) Whitebox.getInternalState(source, "offsetLagMetric"); Assert.assertEquals(6L, offsetLag.get(file.getAbsolutePath() + "||" + ".*").getCount()); } finally { runner.runDestroy(); } }
From source file:com.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java
@Test public void testPendingFilesMetric() throws Exception { final File testDataDir = new File("target", UUID.randomUUID().toString()); Assert.assertTrue(testDataDir.mkdirs()); final List<File> files = Arrays.asList(new File(testDataDir, "file.txt-1"), new File(testDataDir, "file.txt-2"), new File(testDataDir, "file.txt-3"), new File(testDataDir, "file.txt-4"), new File(testDataDir, "file.txt-5"), new File(testDataDir, "file.txt-6"), new File(testDataDir, "file.txt-7"), new File(testDataDir, "file.txt-8")); //We will create first 4 files here. Rest of the four files will be created //before we calculate the pending files metric. for (int i = 0; i < 4; i++) { File file = files.get(i); Files.write(file.toPath(), Arrays.asList("A", "B", "C"), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); }//from w ww .j av a 2 s .c om FileTailSource source = PowerMockito.spy((FileTailSource) createSourceForPeriodicFile( testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}", "[0-9]")); //Intercept calculatePendingFilesMetric private method which calculates the pendingFiles //and create new files. PowerMockito.replace(MemberMatcher.method(FileTailSource.class, "calculatePendingFilesMetric")) .with(new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //Create the remaining 4 files so as to have files which are pending and not being started for processing. for (int i = 4; i < 8; i++) { File file = files.get(i); Files.write(file.toPath(), Arrays.asList("A", "B", "C"), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); } //call the real getOffsetsLag private method return method.invoke(proxy, args); } }); SourceRunner runner = createRunner(source); try { runner.runInit(); StageRunner.Output output = runner.runProduce(null, 36); // Make sure there are only 12 (3 for each file we read). Assert.assertEquals(12, output.getRecords().get("lane").size()); Map<String, Counter> pendingFilesMetric = (Map<String, Counter>) Whitebox.getInternalState(source, "pendingFilesMetric"); Assert.assertEquals(4L, pendingFilesMetric .get(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}||[0-9]").getCount()); } finally { runner.runDestroy(); } }
From source file:com.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java
private void setSleepTimeForFindingPaths(final long dirFindTime, final long fileFindTime) { PowerMockito.replace(MemberMatcher.method(GlobFileContextProvider.class, "findCreatedDirectories")) .with(new InvocationHandler() { @Override//w w w. j a va2 s.c o m public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //Give some time for it to find new directories. Thread.sleep(dirFindTime); //call the real getOffsetsLag private method return method.invoke(proxy, args); } }); PowerMockito.replace(MemberMatcher.method(GlobFileContextProvider.class, "findNewFileContexts")) .with(new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //Give some time for it to find new files. Thread.sleep(fileFindTime); //call the real getOffsetsLag private method return method.invoke(proxy, args); } }); }