Search in sources :

Example 61 with FunctionContext

use of org.apache.geode.cache.execute.FunctionContext in project geode by apache.

the class DescribeDiskStoreFunctionJUnitTest method testExecuteThrowingRuntimeException.

@Test
public void testExecuteThrowingRuntimeException() throws Exception {
    final String diskStoreName = "testDiskStore";
    final String memberId = "mockMemberId";
    final String memberName = "mockMemberName";
    final InternalCache mockCache = mockContext.mock(InternalCache.class, "Cache");
    final InternalDistributedMember mockMember = mockContext.mock(InternalDistributedMember.class, "DistributedMember");
    final FunctionContext mockFunctionContext = mockContext.mock(FunctionContext.class, "FunctionContext");
    final TestResultSender testResultSender = new TestResultSender();
    mockContext.checking(new Expectations() {

        {
            oneOf(mockCache).getMyId();
            will(returnValue(mockMember));
            oneOf(mockCache).findDiskStore(diskStoreName);
            will(throwException(new RuntimeException("ExpectedStrings")));
            oneOf(mockMember).getId();
            will(returnValue(memberId));
            oneOf(mockMember).getName();
            will(returnValue(memberName));
            oneOf(mockFunctionContext).getArguments();
            will(returnValue(diskStoreName));
            oneOf(mockFunctionContext).getResultSender();
            will(returnValue(testResultSender));
        }
    });
    final DescribeDiskStoreFunction function = createDescribeDiskStoreFunction(mockCache);
    function.execute(mockFunctionContext);
    assertThatThrownBy(() -> testResultSender.getResults()).isInstanceOf(RuntimeException.class).hasMessage("ExpectedStrings");
}
Also used : Expectations(org.jmock.Expectations) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) InternalCache(org.apache.geode.internal.cache.InternalCache) FunctionContext(org.apache.geode.cache.execute.FunctionContext) UnitTest(org.apache.geode.test.junit.categories.UnitTest) Test(org.junit.Test)

Example 62 with FunctionContext

use of org.apache.geode.cache.execute.FunctionContext in project geode by apache.

the class DeployedJarJUnitTest method testDependencyBetweenJars.

@Test
public void testDependencyBetweenJars() throws Exception {
    final File parentJarFile = temporaryFolder.newFile("JarClassLoaderJUnitParent.jar");
    final File usesJarFile = temporaryFolder.newFile("JarClassLoaderJUnitUses.jar");
    // Write out a JAR files.
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("package jcljunit.parent;");
    stringBuffer.append("public class JarClassLoaderJUnitParent {");
    stringBuffer.append("public String getValueParent() {");
    stringBuffer.append("return \"PARENT\";}}");
    byte[] jarBytes = this.classBuilder.createJarFromClassContent("jcljunit/parent/JarClassLoaderJUnitParent", stringBuffer.toString());
    writeJarBytesToFile(parentJarFile, jarBytes);
    ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnitParent.jar", jarBytes);
    stringBuffer = new StringBuffer();
    stringBuffer.append("package jcljunit.uses;");
    stringBuffer.append("public class JarClassLoaderJUnitUses {");
    stringBuffer.append("public String getValueUses() {");
    stringBuffer.append("return \"USES\";}}");
    jarBytes = this.classBuilder.createJarFromClassContent("jcljunit/uses/JarClassLoaderJUnitUses", stringBuffer.toString());
    writeJarBytesToFile(usesJarFile, jarBytes);
    ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnitUses.jar", jarBytes);
    stringBuffer = new StringBuffer();
    stringBuffer.append("package jcljunit.function;");
    stringBuffer.append("import jcljunit.parent.JarClassLoaderJUnitParent;");
    stringBuffer.append("import jcljunit.uses.JarClassLoaderJUnitUses;");
    stringBuffer.append("import org.apache.geode.cache.execute.Function;");
    stringBuffer.append("import org.apache.geode.cache.execute.FunctionContext;");
    stringBuffer.append("public class JarClassLoaderJUnitFunction  extends JarClassLoaderJUnitParent implements Function {");
    stringBuffer.append("private JarClassLoaderJUnitUses uses = new JarClassLoaderJUnitUses();");
    stringBuffer.append("public boolean hasResult() {return true;}");
    stringBuffer.append("public void execute(FunctionContext context) {context.getResultSender().lastResult(getValueParent() + \":\" + uses.getValueUses());}");
    stringBuffer.append("public String getId() {return \"JarClassLoaderJUnitFunction\";}");
    stringBuffer.append("public boolean optimizeForWrite() {return false;}");
    stringBuffer.append("public boolean isHA() {return false;}}");
    ClassBuilder functionClassBuilder = new ClassBuilder();
    functionClassBuilder.addToClassPath(parentJarFile.getAbsolutePath());
    functionClassBuilder.addToClassPath(usesJarFile.getAbsolutePath());
    jarBytes = functionClassBuilder.createJarFromClassContent("jcljunit/function/JarClassLoaderJUnitFunction", stringBuffer.toString());
    ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnitFunction.jar", jarBytes);
    Function function = FunctionService.getFunction("JarClassLoaderJUnitFunction");
    assertThat(function).isNotNull();
    TestResultSender resultSender = new TestResultSender();
    FunctionContext functionContext = new FunctionContextImpl(function.getId(), null, resultSender);
    function.execute(functionContext);
    assertThat((String) resultSender.getResults()).isEqualTo("PARENT:USES");
}
Also used : Function(org.apache.geode.cache.execute.Function) FunctionContextImpl(org.apache.geode.internal.cache.execute.FunctionContextImpl) File(java.io.File) FunctionContext(org.apache.geode.cache.execute.FunctionContext) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 63 with FunctionContext

use of org.apache.geode.cache.execute.FunctionContext in project geode by apache.

the class DeployedJarJUnitTest method testFunctions.

@Test
public void testFunctions() throws Exception {
    // Test creating a JAR file with a function
    String functionString = "import java.util.Properties;" + "import org.apache.geode.cache.Declarable;" + "import org.apache.geode.cache.execute.Function;" + "import org.apache.geode.cache.execute.FunctionContext;" + "public class JarClassLoaderJUnitFunction implements Function {" + "public void init(Properties props) {}" + "public boolean hasResult() {return true;}" + "public void execute(FunctionContext context) {context.getResultSender().lastResult(\"GOODv1\");}" + "public String getId() {return \"JarClassLoaderJUnitFunction\";}" + "public boolean optimizeForWrite() {return false;}" + "public boolean isHA() {return false;}}";
    byte[] jarBytes = this.classBuilder.createJarFromClassContent("JarClassLoaderJUnitFunction", functionString);
    ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnit.jar", jarBytes);
    Function function = FunctionService.getFunction("JarClassLoaderJUnitFunction");
    assertThat(function).isNotNull();
    TestResultSender resultSender = new TestResultSender();
    FunctionContext functionContext = new FunctionContextImpl(function.getId(), null, resultSender);
    function.execute(functionContext);
    assertThat(resultSender.getResults()).isEqualTo("GOODv1");
    // Test updating the function with a new JAR file
    functionString = functionString.replace("v1", "v2");
    jarBytes = this.classBuilder.createJarFromClassContent("JarClassLoaderJUnitFunction", functionString);
    ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnit.jar", jarBytes);
    function = FunctionService.getFunction("JarClassLoaderJUnitFunction");
    assertThat(function).isNotNull();
    resultSender = new TestResultSender();
    functionContext = new FunctionContextImpl(function.getId(), null, resultSender);
    function.execute(functionContext);
    assertThat(resultSender.getResults()).isEqualTo("GOODv2");
    // Test returning null for the Id
    String functionNullIdString = functionString.replace("return \"JarClassLoaderJUnitFunction\"", "return null");
    jarBytes = this.classBuilder.createJarFromClassContent("JarClassLoaderJUnitFunction", functionNullIdString);
    ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnit.jar", jarBytes);
    assertThat(FunctionService.getFunction("JarClassLoaderJUnitFunction")).isNull();
    // Test removing the JAR
    ClassPathLoader.getLatest().getJarDeployer().undeploy("JarClassLoaderJUnit.jar");
    assertThat(FunctionService.getFunction("JarClassLoaderJUnitFunction")).isNull();
}
Also used : Function(org.apache.geode.cache.execute.Function) FunctionContextImpl(org.apache.geode.internal.cache.execute.FunctionContextImpl) FunctionContext(org.apache.geode.cache.execute.FunctionContext) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 64 with FunctionContext

use of org.apache.geode.cache.execute.FunctionContext in project geode by apache.

the class PRColocationDUnitTest method executeFunction.

public static void executeFunction() {
    Function inlineFunction = new FunctionAdapter() {

        @Override
        public void execute(FunctionContext context) {
            RegionFunctionContext rfContext = (RegionFunctionContext) context;
            Region r = rfContext.getDataSet();
            if (r.getName().equals(CustomerPartitionedRegionName)) {
                Map map = ColocationHelper.getColocatedLocalDataSetsForBuckets((PartitionedRegion) r, new HashSet<Integer>());
                assertEquals(2, map.size());
                rfContext.getResultSender().sendResult(map.size());
                map = ColocationHelper.constructAndGetAllColocatedLocalDataSet((PartitionedRegion) r, new HashSet<Integer>());
                assertEquals(3, map.size());
                rfContext.getResultSender().lastResult(map.size());
            } else if (r.getName().equals(OrderPartitionedRegionName)) {
                Map map = ColocationHelper.getColocatedLocalDataSetsForBuckets((PartitionedRegion) r, new HashSet<Integer>());
                assertEquals(2, map.size());
                rfContext.getResultSender().sendResult(map.size());
                map = ColocationHelper.constructAndGetAllColocatedLocalDataSet((PartitionedRegion) r, new HashSet<Integer>());
                assertEquals(3, map.size());
                rfContext.getResultSender().lastResult(map.size());
            } else if (r.getName().equals(ShipmentPartitionedRegionName)) {
                Map map = ColocationHelper.getColocatedLocalDataSetsForBuckets((PartitionedRegion) r, new HashSet<Integer>());
                assertEquals(2, map.size());
                rfContext.getResultSender().sendResult(map.size());
                map = ColocationHelper.constructAndGetAllColocatedLocalDataSet((PartitionedRegion) r, new HashSet<Integer>());
                assertEquals(3, map.size());
                rfContext.getResultSender().lastResult(map.size());
            }
        }

        @Override
        public String getId() {
            return "inlineFunction";
        }

        @Override
        public boolean hasResult() {
            return true;
        }

        @Override
        public boolean isHA() {
            return false;
        }

        @Override
        public boolean optimizeForWrite() {
            return false;
        }
    };
    PartitionedRegion prForCustomer = (PartitionedRegion) basicGetCache().getRegion(CustomerPartitionedRegionName);
    final Set testKeysSet = new HashSet();
    DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(10);
    testKeysSet.add(dummy);
    Execution dataSet = FunctionService.onRegion(prForCustomer);
    ResultCollector rc = dataSet.withFilter(testKeysSet).execute(inlineFunction);
    assertEquals(2, ((List) rc.getResult()).size());
    PartitionedRegion prForOrder = (PartitionedRegion) basicGetCache().getRegion(OrderPartitionedRegionName);
    dataSet = FunctionService.onRegion(prForOrder);
    rc = dataSet.withFilter(testKeysSet).execute(inlineFunction);
    assertEquals(2, ((List) rc.getResult()).size());
    PartitionedRegion prForShipment = (PartitionedRegion) basicGetCache().getRegion(ShipmentPartitionedRegionName);
    dataSet = FunctionService.onRegion(prForShipment);
    rc = dataSet.withFilter(testKeysSet).execute(inlineFunction);
    assertEquals(2, ((List) rc.getResult()).size());
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) RegionFunctionContext(org.apache.geode.cache.execute.RegionFunctionContext) FunctionContext(org.apache.geode.cache.execute.FunctionContext) RegionFunctionContext(org.apache.geode.cache.execute.RegionFunctionContext) Function(org.apache.geode.cache.execute.Function) Execution(org.apache.geode.cache.execute.Execution) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) FunctionAdapter(org.apache.geode.cache.execute.FunctionAdapter) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) Region(org.apache.geode.cache.Region) Map(java.util.Map) HashMap(java.util.HashMap) ResultCollector(org.apache.geode.cache.execute.ResultCollector) HashSet(java.util.HashSet)

Example 65 with FunctionContext

use of org.apache.geode.cache.execute.FunctionContext in project geode by apache.

the class PRFunctionExecutionDUnitTest method testBug40714.

@Test
public void testBug40714() throws Exception {
    final String rName = getUniqueName();
    Host host = Host.getHost(0);
    final VM datastore0 = host.getVM(0);
    final VM datastore1 = host.getVM(1);
    final VM datastore2 = host.getVM(2);
    final VM datastore3 = host.getVM(3);
    getCache();
    SerializableCallable dataStoreCreate = new SerializableCallable("Create PR with Function Factory") {

        public Object call() throws Exception {
            RegionAttributes ra = PartitionedRegionTestHelper.createRegionAttrsForPR(0, 10);
            AttributesFactory raf = new AttributesFactory(ra);
            PartitionAttributesImpl pa = new PartitionAttributesImpl();
            pa.setAll(ra.getPartitionAttributes());
            pa.setTotalNumBuckets(17);
            raf.setPartitionAttributes(pa);
            getCache().createRegion(rName, raf.create());
            FunctionService.registerFunction(new FunctionAdapter() {

                @Override
                public void execute(FunctionContext context) {
                    if (context.getArguments() instanceof String) {
                        context.getResultSender().lastResult("Failure");
                    } else if (context.getArguments() instanceof Boolean) {
                        context.getResultSender().lastResult(Boolean.FALSE);
                    }
                }

                @Override
                public String getId() {
                    return "Function";
                }

                @Override
                public boolean hasResult() {
                    return true;
                }
            });
            return Boolean.TRUE;
        }
    };
    datastore0.invoke(dataStoreCreate);
    datastore1.invoke(dataStoreCreate);
    datastore2.invoke(dataStoreCreate);
    datastore3.invoke(dataStoreCreate);
    Object o = datastore3.invoke(new SerializableCallable("Create data, invoke exectuable") {

        public Object call() throws Exception {
            PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(rName);
            DistributedSystem.setThreadsSocketPolicy(false);
            final HashSet testKeys = new HashSet();
            for (int i = (pr.getTotalNumberOfBuckets() * 3); i > 0; i--) {
                testKeys.add("execKey-" + i);
            }
            int j = 0;
            for (Iterator i = testKeys.iterator(); i.hasNext(); ) {
                Integer val = new Integer(j++);
                pr.put(i.next(), val);
            }
            // Assert there is data in each bucket
            for (int bid = 0; bid < pr.getTotalNumberOfBuckets(); bid++) {
                assertTrue(pr.getBucketKeys(bid).size() > 0);
            }
            Execution dataSet = FunctionService.onRegion(pr);
            ResultCollector rc1 = dataSet.setArguments(Boolean.TRUE).execute(new FunctionAdapter() {

                @Override
                public void execute(FunctionContext context) {
                    if (context.getArguments() instanceof String) {
                        context.getResultSender().lastResult("Success");
                    } else if (context.getArguments() instanceof Boolean) {
                        context.getResultSender().lastResult(Boolean.TRUE);
                    }
                }

                @Override
                public String getId() {
                    return "Function";
                }

                @Override
                public boolean hasResult() {
                    return true;
                }
            });
            List l = ((List) rc1.getResult());
            LogWriterUtils.getLogWriter().info("PRFunctionExecutionDUnitTest#testExecutionOnAllNodes_byName : Result size :" + l.size() + " Result : " + l);
            assertEquals(4, l.size());
            Iterator iterator = l.iterator();
            for (int i = 0; i < 4; i++) {
                Boolean res = (Boolean) iterator.next();
                assertEquals(Boolean.TRUE, res);
            }
            return Boolean.TRUE;
        }
    });
    assertEquals(Boolean.TRUE, o);
}
Also used : RegionAttributes(org.apache.geode.cache.RegionAttributes) Host(org.apache.geode.test.dunit.Host) FunctionContext(org.apache.geode.cache.execute.FunctionContext) RegionFunctionContext(org.apache.geode.cache.execute.RegionFunctionContext) IgnoredException(org.apache.geode.test.dunit.IgnoredException) FunctionException(org.apache.geode.cache.execute.FunctionException) AttributesFactory(org.apache.geode.cache.AttributesFactory) PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) PartitionAttributesImpl(org.apache.geode.internal.cache.PartitionAttributesImpl) Execution(org.apache.geode.cache.execute.Execution) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) Iterator(java.util.Iterator) FunctionAdapter(org.apache.geode.cache.execute.FunctionAdapter) List(java.util.List) ArrayList(java.util.ArrayList) ResultCollector(org.apache.geode.cache.execute.ResultCollector) HashSet(java.util.HashSet) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) Test(org.junit.Test)

Aggregations

FunctionContext (org.apache.geode.cache.execute.FunctionContext)68 FunctionAdapter (org.apache.geode.cache.execute.FunctionAdapter)38 Test (org.junit.Test)35 HashSet (java.util.HashSet)30 RegionFunctionContext (org.apache.geode.cache.execute.RegionFunctionContext)30 ArrayList (java.util.ArrayList)29 FunctionException (org.apache.geode.cache.execute.FunctionException)28 ResultCollector (org.apache.geode.cache.execute.ResultCollector)28 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)28 Region (org.apache.geode.cache.Region)27 Execution (org.apache.geode.cache.execute.Execution)26 IgnoredException (org.apache.geode.test.dunit.IgnoredException)24 List (java.util.List)20 Set (java.util.Set)19 Iterator (java.util.Iterator)16 FunctionInvocationTargetException (org.apache.geode.cache.execute.FunctionInvocationTargetException)15 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)15 UnitTest (org.apache.geode.test.junit.categories.UnitTest)15 DistributedMember (org.apache.geode.distributed.DistributedMember)14 InternalCache (org.apache.geode.internal.cache.InternalCache)14