Search in sources :

Example 1 with ResultSender

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

the class DumpDirectoryFilesJUnitTest method createMocks.

@Before
public void createMocks() throws BucketNotFoundException {
    GemFireCacheImpl cache = Fakes.cache();
    context = mock(RegionFunctionContext.class);
    ResultSender sender = mock(ResultSender.class);
    Region region = mock(Region.class);
    InternalLuceneService service = mock(InternalLuceneService.class);
    InternalLuceneIndex index = mock(InternalLuceneIndex.class);
    RepositoryManager repoManager = mock(RepositoryManager.class);
    IndexRepository repo = mock(IndexRepository.class);
    IndexWriter writer = mock(IndexWriter.class);
    RegionDirectory directory = mock(RegionDirectory.class);
    fileSystem = mock(FileSystem.class);
    Region bucket = mock(Region.class);
    when(bucket.getFullPath()).thenReturn(bucketName);
    when(context.getArguments()).thenReturn(new String[] { directoryName, indexName });
    when(context.getResultSender()).thenReturn(sender);
    when(context.getDataSet()).thenReturn(region);
    when(region.getCache()).thenReturn(cache);
    when(cache.getService(any())).thenReturn(service);
    when(repoManager.getRepositories(eq(context))).thenReturn(Collections.singleton(repo));
    when(index.getRepositoryManager()).thenReturn(repoManager);
    when(index.getName()).thenReturn(indexName);
    when(service.getIndex(eq(indexName), any())).thenReturn(index);
    when(directory.getFileSystem()).thenReturn(fileSystem);
    when(writer.getDirectory()).thenReturn(directory);
    when(repo.getWriter()).thenReturn(writer);
    when(repo.getRegion()).thenReturn(bucket);
}
Also used : IndexRepository(org.apache.geode.cache.lucene.internal.repository.IndexRepository) IndexWriter(org.apache.lucene.index.IndexWriter) InternalLuceneIndex(org.apache.geode.cache.lucene.internal.InternalLuceneIndex) FileSystem(org.apache.geode.cache.lucene.internal.filesystem.FileSystem) GemFireCacheImpl(org.apache.geode.internal.cache.GemFireCacheImpl) Region(org.apache.geode.cache.Region) RegionFunctionContext(org.apache.geode.cache.execute.RegionFunctionContext) RepositoryManager(org.apache.geode.cache.lucene.internal.repository.RepositoryManager) InternalLuceneService(org.apache.geode.cache.lucene.internal.InternalLuceneService) ResultSender(org.apache.geode.cache.execute.ResultSender) Before(org.junit.Before)

Example 2 with ResultSender

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

the class LuceneSearchIndexFunctionJUnitTest method testExecute.

@Test
@SuppressWarnings("unchecked")
public void testExecute() throws LuceneQueryException {
    FunctionContext context = mock(FunctionContext.class);
    ResultSender resultSender = mock(ResultSender.class);
    GemFireCacheImpl cache = Fakes.cache();
    LuceneQueryInfo queryInfo = createMockQueryInfo("index", "region", "field1:region1", "field1", 1);
    InternalLuceneService service = getMockLuceneService("A", "Value", "1.2");
    Region mockRegion = mock(Region.class);
    LuceneSearchIndexFunction function = spy(LuceneSearchIndexFunction.class);
    doReturn(queryInfo).when(context).getArguments();
    doReturn(resultSender).when(context).getResultSender();
    doReturn(cache).when(function).getCache();
    when(cache.getService(eq(InternalLuceneService.class))).thenReturn(service);
    when(cache.getRegion(queryInfo.getRegionPath())).thenReturn(mockRegion);
    function.execute(context);
    ArgumentCaptor<Set> resultCaptor = ArgumentCaptor.forClass(Set.class);
    verify(resultSender).lastResult(resultCaptor.capture());
    Set<LuceneSearchResults> result = resultCaptor.getValue();
    assertEquals(1, result.size());
    for (LuceneSearchResults searchResult : result) {
        assertEquals("A", searchResult.getKey());
        assertEquals("Value", searchResult.getValue());
        assertEquals(1.2, searchResult.getScore(), .1);
    }
}
Also used : Set(java.util.Set) LuceneSearchResults(org.apache.geode.cache.lucene.internal.cli.LuceneSearchResults) GemFireCacheImpl(org.apache.geode.internal.cache.GemFireCacheImpl) Region(org.apache.geode.cache.Region) InternalLuceneService(org.apache.geode.cache.lucene.internal.InternalLuceneService) FunctionContext(org.apache.geode.cache.execute.FunctionContext) ResultSender(org.apache.geode.cache.execute.ResultSender) LuceneQueryInfo(org.apache.geode.cache.lucene.internal.cli.LuceneQueryInfo) Test(org.junit.Test) UnitTest(org.apache.geode.test.junit.categories.UnitTest)

Example 3 with ResultSender

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

the class LuceneGetPageFunctionJUnitTest method shouldReturnMapWithKeyAndValue.

@Test
public void shouldReturnMapWithKeyAndValue() {
    PartitionedRegion region = mock(PartitionedRegion.class);
    InternalRegionFunctionContext context = mock(InternalRegionFunctionContext.class);
    when(context.getDataSet()).thenReturn(region);
    ResultSender resultSender = mock(ResultSender.class);
    when(context.getResultSender()).thenReturn(resultSender);
    LuceneGetPageFunction function = new LuceneGetPageFunction();
    when(context.getLocalDataSet(any())).thenReturn(region);
    final EntrySnapshot entry = mock(EntrySnapshot.class);
    when(region.getEntry(any())).thenReturn(entry);
    final RegionEntry regionEntry = mock(RegionEntry.class);
    when(entry.getRegionEntry()).thenReturn(regionEntry);
    when(regionEntry.getValue(any())).thenReturn("value");
    when(context.getFilter()).thenReturn((Set) Collections.singleton("key"));
    function.execute(context);
    PageResults expectedResults = new PageResults();
    expectedResults.add(new PageEntry("key", "value"));
    verify(resultSender).lastResult(eq(expectedResults));
}
Also used : PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) InternalRegionFunctionContext(org.apache.geode.internal.cache.execute.InternalRegionFunctionContext) RegionEntry(org.apache.geode.internal.cache.RegionEntry) ResultSender(org.apache.geode.cache.execute.ResultSender) EntrySnapshot(org.apache.geode.internal.cache.EntrySnapshot) Test(org.junit.Test) UnitTest(org.apache.geode.test.junit.categories.UnitTest)

Example 4 with ResultSender

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

the class TestFunction method executeResultSender.

private void executeResultSender(FunctionContext context) {
    ResultSender resultSender = context.getResultSender();
    if (context instanceof RegionFunctionContext) {
        RegionFunctionContext rfContext = (RegionFunctionContext) context;
        rfContext.getDataSet().getCache().getLogger().info("Executing function :  TestFunctionexecuteResultSender.execute " + rfContext);
        if (rfContext.getArguments() instanceof Boolean) {
            if (this.hasResult()) {
                resultSender.lastResult((Serializable) rfContext.getArguments());
            }
        } else if (rfContext.getArguments() instanceof Set) {
            Set origKeys = (Set) rfContext.getArguments();
            Object[] objectArray = origKeys.toArray();
            int size = objectArray.length;
            int i = 0;
            for (; i < (size - 1); i++) {
                Object val = PartitionRegionHelper.getLocalDataForContext(rfContext).get(objectArray[i]);
                if (val != null) {
                    resultSender.sendResult((Serializable) val);
                }
            }
            resultSender.lastResult((Serializable) objectArray[i]);
        } else {
            resultSender.lastResult(Boolean.FALSE);
        }
    } else {
        resultSender.lastResult(Boolean.FALSE);
    }
}
Also used : Serializable(java.io.Serializable) Set(java.util.Set) RegionFunctionContext(org.apache.geode.cache.execute.RegionFunctionContext) ResultSender(org.apache.geode.cache.execute.ResultSender)

Example 5 with ResultSender

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

the class ExecuteFunction65 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection servConn, long start) throws IOException {
    Object function = null;
    Object args = null;
    MemberMappedArgument memberMappedArg = null;
    byte hasResult = 0;
    byte functionState = 0;
    boolean isReexecute = false;
    try {
        functionState = clientMessage.getPart(0).getSerializedForm()[0];
        if (functionState == AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE_REEXECUTE) {
            functionState = AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE;
            isReexecute = true;
        } else if (functionState == AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE_REEXECUTE) {
            functionState = AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE;
            isReexecute = true;
        }
        if (functionState != 1) {
            hasResult = (byte) ((functionState & 2) - 1);
        } else {
            hasResult = functionState;
        }
        if (hasResult == 1) {
            servConn.setAsTrue(REQUIRES_RESPONSE);
            servConn.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
        }
        function = clientMessage.getPart(1).getStringOrObject();
        args = clientMessage.getPart(2).getObject();
        Part part = clientMessage.getPart(3);
        if (part != null) {
            memberMappedArg = (MemberMappedArgument) part.getObject();
        }
    } catch (ClassNotFoundException exception) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), exception);
        if (hasResult == 1) {
            writeChunkedException(clientMessage, exception, servConn);
            servConn.setAsTrue(RESPONDED);
            return;
        }
    }
    if (function == null) {
        final String message = LocalizedStrings.ExecuteFunction_THE_INPUT_FUNCTION_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL.toLocalizedString();
        logger.warn("{}: {}", servConn.getName(), message);
        sendError(hasResult, clientMessage, message, servConn);
        return;
    }
    // Execute function on the cache
    try {
        Function functionObject = null;
        if (function instanceof String) {
            functionObject = FunctionService.getFunction((String) function);
            if (functionObject == null) {
                final String message = LocalizedStrings.ExecuteFunction_FUNCTION_NAMED_0_IS_NOT_REGISTERED.toLocalizedString(function);
                logger.warn("{}: {}", servConn.getName(), message);
                sendError(hasResult, clientMessage, message, servConn);
                return;
            } else {
                byte functionStateOnServerSide = AbstractExecution.getFunctionState(functionObject.isHA(), functionObject.hasResult(), functionObject.optimizeForWrite());
                if (logger.isDebugEnabled()) {
                    logger.debug("Function State on server side: {} on client: {}", functionStateOnServerSide, functionState);
                }
                if (functionStateOnServerSide != functionState) {
                    String message = LocalizedStrings.FunctionService_FUNCTION_ATTRIBUTE_MISMATCH_CLIENT_SERVER.toLocalizedString(function);
                    logger.warn("{}: {}", servConn.getName(), message);
                    sendError(hasResult, clientMessage, message, servConn);
                    return;
                }
            }
        } else {
            functionObject = (Function) function;
        }
        FunctionStats stats = FunctionStats.getFunctionStats(functionObject.getId());
        this.securityService.authorizeDataWrite();
        // check if the caller is authorized to do this operation on server
        AuthorizeRequest authzRequest = servConn.getAuthzRequest();
        ExecuteFunctionOperationContext executeContext = null;
        if (authzRequest != null) {
            executeContext = authzRequest.executeFunctionAuthorize(functionObject.getId(), null, null, args, functionObject.optimizeForWrite());
        }
        ChunkedMessage m = servConn.getFunctionResponseMessage();
        m.setTransactionId(clientMessage.getTransactionId());
        ResultSender resultSender = new ServerToClientFunctionResultSender65(m, MessageType.EXECUTE_FUNCTION_RESULT, servConn, functionObject, executeContext);
        InternalDistributedMember localVM = (InternalDistributedMember) servConn.getCache().getDistributedSystem().getDistributedMember();
        FunctionContext context = null;
        if (memberMappedArg != null) {
            context = new FunctionContextImpl(functionObject.getId(), memberMappedArg.getArgumentsForMember(localVM.getId()), resultSender, isReexecute);
        } else {
            context = new FunctionContextImpl(functionObject.getId(), args, resultSender, isReexecute);
        }
        HandShake handShake = (HandShake) servConn.getHandshake();
        int earlierClientReadTimeout = handShake.getClientReadTimeout();
        handShake.setClientReadTimeout(0);
        try {
            long startExecution = stats.startTime();
            stats.startFunctionExecution(functionObject.hasResult());
            if (logger.isDebugEnabled()) {
                logger.debug("Executing Function on Server: {} with context: {}", servConn, context);
            }
            InternalCache cache = servConn.getCache();
            HeapMemoryMonitor hmm = ((InternalResourceManager) cache.getResourceManager()).getHeapMonitor();
            if (functionObject.optimizeForWrite() && cache != null && hmm.getState().isCritical() && !MemoryThresholds.isLowMemoryExceptionDisabled()) {
                Set<DistributedMember> sm = Collections.singleton((DistributedMember) cache.getMyId());
                Exception e = new LowMemoryException(LocalizedStrings.ResourceManager_LOW_MEMORY_FOR_0_FUNCEXEC_MEMBERS_1.toLocalizedString(new Object[] { functionObject.getId(), sm }), sm);
                sendException(hasResult, clientMessage, e.getMessage(), servConn, e);
                return;
            }
            functionObject.execute(context);
            if (!((ServerToClientFunctionResultSender65) resultSender).isLastResultReceived() && functionObject.hasResult()) {
                throw new FunctionException(LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT.toString(functionObject.getId()));
            }
            stats.endFunctionExecution(startExecution, functionObject.hasResult());
        } catch (FunctionException functionException) {
            stats.endFunctionExecutionWithException(functionObject.hasResult());
            throw functionException;
        } catch (Exception exception) {
            stats.endFunctionExecutionWithException(functionObject.hasResult());
            throw new FunctionException(exception);
        } finally {
            handShake.setClientReadTimeout(earlierClientReadTimeout);
        }
    } catch (IOException ioException) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), ioException);
        String message = LocalizedStrings.ExecuteFunction_SERVER_COULD_NOT_SEND_THE_REPLY.toLocalizedString();
        sendException(hasResult, clientMessage, message, servConn, ioException);
    } catch (InternalFunctionInvocationTargetException internalfunctionException) {
        // 2> in case of HA member departed
        if (logger.isDebugEnabled()) {
            logger.debug(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, new Object[] { function }), internalfunctionException);
        }
        final String message = internalfunctionException.getMessage();
        sendException(hasResult, clientMessage, message, servConn, internalfunctionException);
    } catch (Exception e) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), e);
        final String message = e.getMessage();
        sendException(hasResult, clientMessage, message, servConn, e);
    }
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) InternalCache(org.apache.geode.internal.cache.InternalCache) ResultSender(org.apache.geode.cache.execute.ResultSender) InternalResourceManager(org.apache.geode.internal.cache.control.InternalResourceManager) Function(org.apache.geode.cache.execute.Function) HandShake(org.apache.geode.internal.cache.tier.sockets.HandShake) MemberMappedArgument(org.apache.geode.internal.cache.execute.MemberMappedArgument) FunctionStats(org.apache.geode.internal.cache.execute.FunctionStats) LowMemoryException(org.apache.geode.cache.LowMemoryException) FunctionContextImpl(org.apache.geode.internal.cache.execute.FunctionContextImpl) ExecuteFunctionOperationContext(org.apache.geode.cache.operations.ExecuteFunctionOperationContext) ServerToClientFunctionResultSender65(org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender65) FunctionException(org.apache.geode.cache.execute.FunctionException) HeapMemoryMonitor(org.apache.geode.internal.cache.control.HeapMemoryMonitor) IOException(java.io.IOException) FunctionContext(org.apache.geode.cache.execute.FunctionContext) FunctionException(org.apache.geode.cache.execute.FunctionException) LowMemoryException(org.apache.geode.cache.LowMemoryException) IOException(java.io.IOException) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) Part(org.apache.geode.internal.cache.tier.sockets.Part) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) DistributedMember(org.apache.geode.distributed.DistributedMember) ChunkedMessage(org.apache.geode.internal.cache.tier.sockets.ChunkedMessage)

Aggregations

ResultSender (org.apache.geode.cache.execute.ResultSender)13 FunctionContext (org.apache.geode.cache.execute.FunctionContext)6 FunctionException (org.apache.geode.cache.execute.FunctionException)5 FunctionStats (org.apache.geode.internal.cache.execute.FunctionStats)5 IOException (java.io.IOException)4 Set (java.util.Set)4 GemFireCacheImpl (org.apache.geode.internal.cache.GemFireCacheImpl)4 UnitTest (org.apache.geode.test.junit.categories.UnitTest)4 Test (org.junit.Test)4 Region (org.apache.geode.cache.Region)3 InternalLuceneService (org.apache.geode.cache.lucene.internal.InternalLuceneService)3 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)3 ServerToClientFunctionResultSender (org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender)3 HashSet (java.util.HashSet)2 CancelException (org.apache.geode.CancelException)2 CacheClosedException (org.apache.geode.cache.CacheClosedException)2 LowMemoryException (org.apache.geode.cache.LowMemoryException)2 Function (org.apache.geode.cache.execute.Function)2 RegionFunctionContext (org.apache.geode.cache.execute.RegionFunctionContext)2 LuceneIndexImpl (org.apache.geode.cache.lucene.internal.LuceneIndexImpl)2