All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.alachisoft.ncache.client.internal.communication.Request Maven / Gradle / Ivy

There is a newer version: 5.3.0
Show newest version
package com.alachisoft.ncache.client.internal.communication;

import Alachisoft.NCache.Caching.CompressedValueEntry;
import Alachisoft.NCache.Common.BitSet;
import Alachisoft.NCache.Common.Caching.UserBinaryObject;
import Alachisoft.NCache.Common.DataReader.ReaderResultSet;
import Alachisoft.NCache.Common.DataStructures.*;
import Alachisoft.NCache.Common.DataStructures.EnumerationDataChunk;
import Alachisoft.NCache.Common.Enum.AggregateFunctionType;
import Alachisoft.NCache.Common.Enum.ExceptionType;
import Alachisoft.NCache.Common.Extensibility.Client.RPC.Partition;
import Alachisoft.NCache.Common.Net.Address;
import Alachisoft.NCache.Common.Queries.AverageResult;
import Util.ResponseHelper;

import com.alachisoft.ncache.client.MessageItem;
import com.alachisoft.ncache.client.internal.command.*;
import com.alachisoft.ncache.client.internal.util.DictionaryEntry;
import com.alachisoft.ncache.client.internal.util.Logs;
import com.alachisoft.ncache.common.caching.EntryType;
import com.alachisoft.ncache.common.protobuf.*;
import com.alachisoft.ncache.runtime.exceptions.CommandException;
import com.alachisoft.ncache.runtime.exceptions.ConnectionException;
import com.alachisoft.ncache.runtime.exceptions.InvalidReaderException;
import com.alachisoft.ncache.runtime.exceptions.OperationFailedException;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

//  Copyright (c) 2020 Alachisoft
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//     http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License


public class Request {
    private long _requestId = -1;
    private boolean _isBulk = false;
    private CommandResponse _finalResponse = null;
    private Object _responseMutex = new Object();
    private int _commandID = 0;
    private ResponseProtocol.Response.Type _type;
    private java.util.HashMap> _responses;
    private java.util.HashMap _commands;
    private java.util.HashMap _chunks;
    private java.util.ArrayList _failedCommands;
    private java.util.ArrayList _rawResponses = null;
    private java.util.HashMap _surrogateCommands = new java.util.HashMap<>();
    private boolean isRequestTimeoutReset;
    private long requestTimeout;
    private String name;
    private boolean isAyncCallbackSpecified = false;
    private boolean isAsync = false;
    private Address reRoutedAddress;
    private String cacheId;
    private AtomicInteger commandIDCounter = new AtomicInteger(0);

    private Logs privateLogger = new Logs();

    public Request(boolean isBulk, long timeout) {
        _isBulk = isBulk;
        setRequestTimeout(timeout);
    }


    public final boolean getIsDedicatedRequest() {
        for (Command command : _commands.values()) {
            if (command.getClientLastViewId() == Broker.ForcedViewId) {
                return true;
            }
        }

        return false;
    }

    public final int getNextCommandID() {
        return commandIDCounter.incrementAndGet();
    }

    public final boolean getIsRequestTimeoutReset() {
        return isRequestTimeoutReset;
    }

    public final void setIsRequestTimeoutReset(boolean value) {
        isRequestTimeoutReset = value;
    }

    public final long getRequestTimeout() {
        return requestTimeout;
    }

    public final void setRequestTimeout(long value) {
        requestTimeout = value;
    }

    public final String getName() {
        return name;
    }

    public final void setName(String value) {
        name = value;
    }

    public final java.util.ArrayList getFailedCommands() {
        if (_failedCommands == null) {
            _failedCommands = new java.util.ArrayList<>();
        }
        return _failedCommands;
    }

    public final boolean getIsAyncCallbackSpecified() {
        return isAyncCallbackSpecified;
    }

    public final void setIsAyncCallbackSpecified(boolean value) {
        isAyncCallbackSpecified = value;
    }

    public final boolean getIsAsync() {
        return isAsync;
    }

    public final void setIsAsync(boolean value) {
        isAsync = value;
    }

    public final Address getReRoutedAddress() {
        return reRoutedAddress;
    }


    public final void setReRoutedAddress(Address value) {
        reRoutedAddress = value;
    }

    public final boolean getIsBulk() {
        return _commands.size() > 1 || _isBulk;
    }

    public final RequestType getCommandRequestType() {
        for (Command command : _commands.values()) {
            return command.getCommandRequestType();
        }

        return RequestType.InternalCommand;
    }

    public final long getRequestId() {
        return _requestId;
    }

    public final void setRequestId(long value) {
        _requestId = value;

        for (Command command : _commands.values()) {
            command.setRequestId(value);
        }
    }

    public final java.util.HashMap getCommands() {
        if (_commands == null) {
            _commands = new java.util.HashMap<>();
        }
        return _commands;
    }

    public final int NumberOfCompleteResponses(boolean includeFailedResponsesOnly) throws CommandException {
        int count = 0;
        synchronized (_responseMutex) {
           DeserializeRawResponsesIfPresent();
            for (java.util.HashMap allResponses : _responses.values()) {
                for (ResponseList responseList : allResponses.values()) {
                    if (responseList.IsComplete(includeFailedResponsesOnly)) {
                        count++;
                    }
                }
            }
        }

        return count;
    }

    public final String getTimeoutMessage() throws CommandException {
        StringBuilder sb = new StringBuilder("Operation timed out. No response from the server(s).");
        sb.append(" [");
        synchronized (_responseMutex) {
            for (Address ip : _commands.keySet()) {
                if (!_responses.containsKey(ip)) {
                    sb.append(ip + ", ");
                } else {
                    if (ExpectingResponseFrom(ip)) {
                        sb.append(ip + ", ");
                    }
                }
            }
        }
        int length = sb.length();
        sb.delete(length - 2, length);
        sb.append("]");
        return sb.toString();
    }

    public final CommandResponse getResponse() throws InvalidReaderException, CommandException {
        synchronized (_responseMutex) {
            DeserializeRawResponsesIfPresent();
            for (java.util.Map.Entry> allResponses : _responses.entrySet()) {
                //Iterates over all ResponseList objects against one IP
                for (ResponseList responses : allResponses.getValue().values()) {
                    //Iterates over all CommandResponse objects in each ResponseList
                    for (CommandResponse rsp : responses.getResponses()) {
                        //in case exception is not thrown from 1st server.
                        if (rsp.getExpMessage() != null && !rsp.getExpMessage().isEmpty() &&
                                rsp.getExpValue() != null && rsp.getExpValue() != ExceptionProtocol.Exception.Type.STATE_TRANSFER_EXCEPTION && rsp.getExpValue()
                                != ExceptionProtocol.Exception.Type.ATTRIBUTE_INDEX_NOT_FOUND && rsp.getExpValue() != ExceptionProtocol.Exception.Type.TYPE_INDEX_NOT_FOUND) {
                            _finalResponse = rsp;
                            return _finalResponse;
                        }
                        MergeResponse(allResponses.getKey(), rsp);
                    }
                }
            }
        }
//        if (getLogger().getIsErrorLogsEnabled()) {
//            getLogger().getNCacheLog().Error("Request.getResponse", "Recieved response request ID: "+_finalResponse.getRequestId());
//        }
        return _finalResponse;
    }
    public void setLogger(Logs logger)
    {
        privateLogger=logger;
    }

    private Logs getLogger() {
        return privateLogger;
    }

    public final java.util.HashMap getResponses() {
        java.util.HashMap responses = new java.util.HashMap();

        for (java.util.Map.Entry> allResponses : _responses.entrySet()) {
            for (ResponseList rspList : allResponses.getValue().values()) {
                ResponseList existingList = null;
                if ((existingList = responses.get(allResponses.getKey())) != null) {
                    existingList.MergeWith(rspList);
                } else {
                    responses.put(allResponses.getKey(), rspList);
                }
            }
        }

        return responses;
    }

    public final boolean getIsCompleteResponseReceived() throws CommandException {

            return NumberOfCompleteResponses(false) >= _commands.size();

    }

    public final boolean getHasFailedResponses() throws CommandException {
        return NumberOfCompleteResponses(true) > 0;
    }

    public final void addCommand(Address address, Command command) {
        setName(command.getCommandName());
        command.setParent(this);
        command.setCommandID(this.getNextCommandID());

        if (_commands == null) {
            _commands = new java.util.HashMap();
        }

        if (!_commands.containsKey(address)) {
            _commands.put(address, command);
        }
    }

    public final void addResponse(Address address, CommandResponse response) {
        _type = response.getType();

        if (response.isSurrogate()) {
            Address actualAddress = null;
            if (_surrogateCommands != null && _surrogateCommands.containsKey(address)) {
                actualAddress = _surrogateCommands.get(address).getActualTargetNode();
                _surrogateCommands.remove(address);
            }
            address = actualAddress;
            response.setActualTargetNode(actualAddress);
        }

        synchronized (_responseMutex) {

            if (_responses.containsKey(address)) {
                if (!response.getIsInternalResponse() && response.isNeedsDeserialization()) {
                    if (_rawResponses == null) {
                        _rawResponses = new java.util.ArrayList<>();
                    }

                    _rawResponses.add(response);
                } else {
                    ResponseList responseList;
                    if (response.getCommandId() <= 0) {
                        java.util.HashMap responses = _responses.get(address);
                        for (ResponseList rsp : responses.values()) {
                            if (!rsp.IsComplete(false)) {
                                rsp.AddResponse(response);
                                break;
                            }
                        }
                        return;
                    }


                    if ((responseList = _responses.get(address).get(response.getCommandId())) != null) {
                        if (Connection.WriteRequestIdInResponse || !responseList.IsComplete(false)) {
                            responseList.AddResponse(response);
                        }
                    }
                }
            }
        }
    }

    private void DeserializeRawResponsesIfPresent()  throws CommandException{
        if (_rawResponses != null && _rawResponses.size() > 0) {
            for (int i = 0; i < _rawResponses.size(); i++) {
                CommandResponse respnse = _rawResponses.get(i);
                InputStream targetStream = new ByteArrayInputStream(respnse.getRawResult());
                try {
                    try {
                        respnse.setResult(ResponseHelper.deserializeResponse(respnse.getType(), targetStream));
                    } finally {
                        targetStream.close();
                    }
                } catch (Exception ex) {
                    throw new CommandException(ex.getMessage());
                }

                respnse.setNeedsDeserialization(false);
                addResponse(respnse.getSourceAddress(), respnse);
            }
            _rawResponses.clear();
        }
    }

    public final void InitializeResponse(Address address, Command command) {
        if (command instanceof SurrogateCommand) {
            //in case of surrogate command, we initialize response against the actual targetnode
            address = ((SurrogateCommand) command).getActualTargetNode();
        }

        synchronized (_responseMutex) {
            if (_responses == null) {
                _responses = new java.util.HashMap<>();
            }
            if (!_responses.containsKey(address)) {
                _responses.put(address, new java.util.HashMap());
            }

            java.util.HashMap allResponses = _responses.get(address);
            allResponses.put(command.getCommandID(), new ResponseList(command));
        }
        command.setFinalDestinationAddress(address);
    }

    public final void InitializeFailedResponse(Address address, Command command) {
        synchronized (_responseMutex) {
            if (_responses == null) {
                _responses = new java.util.HashMap<>();
            }
            if (!_responses.containsKey(address)) {
                _responses.put(address, new java.util.HashMap<>());
            }

            java.util.HashMap allResponses = _responses.get(address);
            allResponses.put(command.getCommandID(), new ResponseList(command));
            allResponses.get(command.getCommandID()).AddResponse(new CommandResponse(true, address));
        }
        command.setFinalDestinationAddress(address);
    }

    public final void RemoveResponse(Address address, int commandId) {
        synchronized (_responseMutex) {
            if (address != null && _responses.containsKey(address)) {
                _responses.get(address).remove(commandId);
                if (_responses.get(address).isEmpty()) {
                    _responses.remove(address);
                }
            }
        }
    }

    public final void ClearResponses() {
        synchronized (_responseMutex) {
            if (_responses != null) {
                _responses.clear();
            }
        }
    }

    public final boolean ExpectingResponseFrom(Address address) throws CommandException {
        synchronized (_responseMutex) {
            DeserializeRawResponsesIfPresent();

            if (_responses !=null &&  _responses.containsKey(address)) {
                //True if response from specified ip address is not completed, else false
                for (ResponseList responseList : _responses.get(address).values()) {
                    if (!responseList.IsComplete(false)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public final void Reset(Address ip) throws CommandException {
        ResetInternal(ip);

        if (_surrogateCommands != null) {
            if (_surrogateCommands.containsKey(ip)) {
                SurrogateCommand surrogateCommand = _surrogateCommands.get(ip);
                _surrogateCommands.remove(ip);
                if (surrogateCommand != null) {
                    //as surrogate command was executed this faulity node, therefore we need to reset it as well.
                    ResetInternal(surrogateCommand.getActualTargetNode());
                }
            }
        }

    }

    private void ResetInternal(Address ip) throws CommandException {
        synchronized (_responseMutex) {

                DeserializeRawResponsesIfPresent();

            if (_responses.containsKey(ip)) {
                java.util.HashMap allResponses = _responses.get(ip);
                for (ResponseList responseList : allResponses.values()) {
                    if (!responseList.IsComplete(false)) {
                        responseList.Clear();
                        responseList.AddResponse(new CommandResponse(true, ip));
                        if (_failedCommands == null) {
                            _failedCommands = new java.util.ArrayList<>();
                        }
                        _failedCommands.add(responseList.getCommand());
                    }
                }
            }
        }
    }

    public final void SetAggregateFunctionResult() {

        switch (_finalResponse.getQueryResultSet().getAggregateFunctionType()) {
            case MAX:
                _finalResponse.getQueryResultSet().setAggregateFunctionResult(new DictionaryEntry(AggregateFunctionType.MAX, _finalResponse.getQueryResultSet().getAggregateFunctionResult().getValue()));
                break;
            case MIN:
                _finalResponse.getQueryResultSet().setAggregateFunctionResult(new DictionaryEntry(AggregateFunctionType.MIN, _finalResponse.getQueryResultSet().getAggregateFunctionResult().getValue()));
                break;
            case COUNT:
                _finalResponse.getQueryResultSet().setAggregateFunctionResult(new DictionaryEntry(AggregateFunctionType.COUNT, _finalResponse.getQueryResultSet().getAggregateFunctionResult().getValue()));
                break;
            case SUM:
                _finalResponse.getQueryResultSet().setAggregateFunctionResult(new DictionaryEntry(AggregateFunctionType.SUM, _finalResponse.getQueryResultSet().getAggregateFunctionResult().getValue()));
                break;
            case AVG:
                _finalResponse.getQueryResultSet().setAggregateFunctionResult(new DictionaryEntry(AggregateFunctionType.AVG, _finalResponse.getQueryResultSet().getAggregateFunctionResult().getValue()));
                break;
            case TERMFREQ:
                _finalResponse.getQueryResultSet().setAggregateFunctionResult(new DictionaryEntry(AggregateFunctionType.TERMFREQ, _finalResponse.getQueryResultSet().getAggregateFunctionResult().getValue()));
        }
    }

    public final void MergeResponse(Address address, CommandResponse response) throws InvalidReaderException {
        if (_finalResponse == null && (response.getType() != com.alachisoft.ncache.common.protobuf.ResponseProtocol.Response.Type.GET_NEXT_CHUNK &&
                response.getType() != com.alachisoft.ncache.common.protobuf.ResponseProtocol.Response.Type.GET_READER_CHUNK
                && response.getType() != com.alachisoft.ncache.common.protobuf.ResponseProtocol.Response.Type.EXECUTE_READER
               ))
        {
            _finalResponse = response;
            if (response.isBrokerReset()) {
                MergeFailedResponse(response);
            }
        }
        else
        {
            if (response.isBrokerReset()) {
                MergeFailedResponse(response);
            } else {
                switch (response.getType()) {
                    case POLL:
                        _finalResponse.getPollingResult().getRemovedKeys().addAll(response.getPollingResult().getRemovedKeys());
                        _finalResponse.getPollingResult().getUpdatedKeys().addAll(response.getPollingResult().getUpdatedKeys());
                        break;

                    case ADD_BULK:
                    case INSERT_BULK:
                    case GET_BULK:
                    case BULK_GET_CACHEITEM:
                    case REMOVE_BULK:
                    case GET_TAG:
                    case MESSAGE_ACKNOWLEDGEMENT:

                        HashMap hashMap = response.getResultMap();
                        HashMap finalMap = _finalResponse.getResultMap();
                        if (finalMap != null && hashMap != null) {
                            finalMap.putAll(hashMap);
                        }

                        HashMap map = response.getVersionMap();
                        finalMap = _finalResponse.getVersionMap();
                        if (finalMap != null && map != null) {
                            finalMap.putAll(map);
                        }

                        break;
                    case CONTAINS_BULK:
                        hashMap = response.getResultMap();
                        finalMap = _finalResponse.getResultMap();
                        if (finalMap != null && hashMap != null) {
                            Iterator iterator = hashMap.entrySet().iterator();
                            while (iterator.hasNext()) {
                                Map.Entry entry = (Map.Entry) iterator.next();
                                if (finalMap.containsKey(entry.getKey())) {
                                    ((ArrayList) finalMap.get(entry.getKey())).addAll((ArrayList) entry.getValue());
                                } else {
                                    finalMap.put(entry.getKey(), entry.getValue());
                                }
                            }
                        }
                        break;
                    case GET_MESSAGE:
                        for (Map.Entry> entry : response.getMessageDic().entrySet()) {
                            if (!_finalResponse.getMessageDic().containsKey(entry.getKey())) {
                                _finalResponse.getMessageDic().put(entry.getKey(), entry.getValue());
                            } else {
                                for (MessageItem message : entry.getValue()) {
                                    _finalResponse.getMessageDic().get(entry.getKey()).add(message);
                                }
                            }
                        }

                        break;
//                    case GET_GROUP_KEYS:
                    case GET_KEYS_TAG:
                        _finalResponse.getResultList().addAll(response.getResultList());
                        break;

                    case GET_READER_CHUNK:

                        if (_finalResponse == null) {
                            _finalResponse = response;
                        }

                        ReaderResultSetProtocol.ReaderResultSet protoReaderChunkResultSet = response.getProtobufResponse().getGetReaderChunkResponse().getReaderResultSets();
                        ReaderResultSet readerChunkResultSet = _finalResponse.getReaderNextChunk();

                        if (readerChunkResultSet != null) {
                            PopulateRows(readerChunkResultSet.getRecordSet(), protoReaderChunkResultSet.getRecordSet().getRowsList());
                        } else {
                            readerChunkResultSet = ConvertToReaderResult(protoReaderChunkResultSet);
                            _finalResponse.setReaderNextChunk(readerChunkResultSet);
                        }

                        break;

                    case DELETE_QUERY:
                    case REMOVE_QUERY:

                        if ((_finalResponse.getExpValue() == ExceptionProtocol.Exception.Type.TYPE_INDEX_NOT_FOUND)
                                || (_finalResponse.getExpValue() == ExceptionProtocol.Exception.Type.ATTRIBUTE_INDEX_NOT_FOUND)) {
                            if ((response.getExpValue() != ExceptionProtocol.Exception.Type.ATTRIBUTE_INDEX_NOT_FOUND)
                                    && (response.getExpValue() != ExceptionProtocol.Exception.Type.TYPE_INDEX_NOT_FOUND)) {
                                _finalResponse = response;
                            }
                        } else if (_finalResponse != null && (response.getExpValue() != ExceptionProtocol.Exception.Type.ATTRIBUTE_INDEX_NOT_FOUND)
                                || (response.getExpValue() != ExceptionProtocol.Exception.Type.TYPE_INDEX_NOT_FOUND)) {
                            _finalResponse.setRemovedKeyCount(_finalResponse.getRemovedKeyCount() + response.getRemovedKeyCount());
                        }

                        break;
                    case SEARCH:

                        if ((_finalResponse.getExpValue() == ExceptionProtocol.Exception.Type.TYPE_INDEX_NOT_FOUND) || (_finalResponse.getExpValue()
                                == ExceptionProtocol.Exception.Type.ATTRIBUTE_INDEX_NOT_FOUND)) {
                            _finalResponse = response;
                            break;
                        }

                        switch (response.getQueryResultSet().getAggregateFunctionType()) {
                            case NOTAPPLICABLE:
                                ArrayList list = response.getResultList();
                                if (list != null) {
                                    _finalResponse.getResultList().addAll(list);
                                }
                                break;

                            default:
                                if (!_finalResponse.getQueryResultSet().getIsInitialized()) {
                                    SetAggregateFunctionResult();
                                    _finalResponse.getQueryResultSet().Initialize(_finalResponse.getQueryResultSet());
                                }
                                _finalResponse.getQueryResultSet().Compile(response.getQueryResultSet());
                                break;
                        }
                        break;
                    case GET_SERVER_MAPPING:
                        _finalResponse.setServerMappingList(response.getServerMappingList());
                        break;


                    case GET_NEXT_CHUNK:
                        if (_finalResponse == null) {
                            _finalResponse = response;
                        }

                        if (_chunks == null) {
                            _chunks = new java.util.HashMap<>();
                        }

                        EnumerationDataChunk chunk;
                        if (_chunks.containsKey(address)) {
                            chunk = _chunks.get(address);
                        } else {
                            chunk = new EnumerationDataChunk();
                            chunk.setData(new java.util.ArrayList<>());
                            _chunks.put(address, chunk);
                        }

                        for (int i = 0; i < response.getNextChunk().size(); i++) {
                            EnumerationDataChunk enumerationDataChunk = response.getNextChunk().get(i);
                            chunk.getData().addAll(enumerationDataChunk.getData());
                            chunk.setPointer(enumerationDataChunk.getPointer());
                            if (chunk.getPointer().getNodeIpAddress() == null) {
                                chunk.getPointer().setNodeIpAddress(address);
                            }
                        }
                        _finalResponse.setNextChunk(new java.util.ArrayList<>(_chunks.values()));

                        break;

                    case EXCEPTION:
                        if (response.getExpValue().getNumber() == ExceptionType.STATE_TRANSFER_EXCEPTION.getValue()) {
                            _finalResponse = response;
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private Alachisoft.NCache.Common.DataReader.ReaderResultSet ConvertToReaderResult(ReaderResultSetProtocol.ReaderResultSet readerResultSetProto) throws InvalidReaderException {
        if (readerResultSetProto == null) {
            return null;
        }
        Alachisoft.NCache.Common.DataReader.ReaderResultSet readerResultSet = new Alachisoft.NCache.Common.DataReader.ReaderResultSet();
        readerResultSet.setIsGrouped(readerResultSetProto.getIsGrouped());
        readerResultSet.setNodeAddress(readerResultSetProto.getNodeAddress());
        readerResultSet.setNextIndex(readerResultSetProto.getNextIndex());
        readerResultSet.setReaderID(readerResultSetProto.getReaderId());

        java.util.ArrayList orderByArgs = new java.util.ArrayList<>();
        for (OrderByArgumentProtocol.OrderByArgument obaProto : readerResultSetProto.getOrderByArgumentsList()) {
            Alachisoft.NCache.Common.Queries.OrderByArgument arg = new Alachisoft.NCache.Common.Queries.OrderByArgument();
            arg.setAttributeName(obaProto.getAttributeName());
            arg.setOrder(obaProto.getOrder().getNumber());
            orderByArgs.add(arg);
        }

        readerResultSet.setOrderByArguments(orderByArgs);
        Alachisoft.NCache.Common.DataReader.RecordSetImpl recordSet = null;
        if (readerResultSetProto.getRecordSet() != null) {
            recordSet = new Alachisoft.NCache.Common.DataReader.RecordSetImpl();
            RecordSetProtocol.RecordSet recordSetProto = readerResultSetProto.getRecordSet();
            for (RecordColumnProtocol.RecordColumn columnProto : recordSetProto.getColumnsList()) {
                Alachisoft.NCache.Common.DataReader.RecordColumn column = new Alachisoft.NCache.Common.DataReader.RecordColumn(columnProto.getName());
                column.setAggregateFunctionType(AggregateFunctionType.forValue(columnProto.getAggregateFunctionType().getNumber()));
                column.setColumnType(ColumnType.forValue(columnProto.getColumnType().getNumber()));
                column.setDataType(ColumnDataType.forValue(columnProto.getDataType().getNumber()));
                column.setIsFilled(columnProto.getIsFilled());
                column.setIsHidden(columnProto.getIsHidden());
                column.setUserSpecifiedColumn(columnProto.getIsUserSpecifiedColumn());
                recordSet.addColumn(column);
            }

            PopulateRows(recordSet, recordSetProto.getRowsList());
        }
        readerResultSet.setRecordSet(recordSet);
        return readerResultSet;
    }

    private void PopulateRows(Alachisoft.NCache.Common.DataReader.RecordSetImpl recordSet, java.util.List rows) throws InvalidReaderException {
        try {
            if (recordSet != null && rows != null) {
                for (RecordRowProtocol.RecordRow rowProto : rows) {
                    Alachisoft.NCache.Common.DataReader.RecordRow row = recordSet.createRow();
                    if (recordSet.getColumns() != null) {
                        for (int i = 0; i < recordSet.getColumns().getCount(); i++) {
                            if (rowProto.getValues(i) != null) {
                                ColumnDataType columnDataType = recordSet.getColumns().get(i).getDataType();
                                if (columnDataType != null) {
                                    switch (columnDataType) {
                                        case AverageResult:
                                            AverageResult avgResult = new AverageResult();
                                            avgResult.setSum(new BigDecimal(rowProto.getValues(i).getAvgResult().getSum()));
                                            avgResult.setCount(new BigDecimal(rowProto.getValues(i).getAvgResult().getCount()));
                                            row.set(i, avgResult);
                                            break;
                                        case CompressedValueEntry:
                                            ValueProtocol.Value val = rowProto.getValues(i).getBinaryObject();
                                            UserBinaryObject ubObject = UserBinaryObject.createUserBinaryObject(val.getDataList());
                                            byte[] bytes = ubObject.getFullObject();
                                            CompressedValueEntry cmpEntry = new CompressedValueEntry();
                                            cmpEntry.flag = new BitSet((byte) rowProto.getValues(i).getFlag());
                                            cmpEntry.setType(EntryType.forValue(rowProto.getValues(i).getType()));
                                            cmpEntry.value = bytes;
                                            row.set(i, cmpEntry);

                                            break;
                                        case Metadata:
                                            row.set(i, rowProto.getValues(i).getStringValue());
                                            if (EntryType.getMappings().containsValue(row.get(i).toString()))
                                                row.set(i, EntryType.valueOf(row.get(i).toString()));
                                            break;
                                        default:
                                            if (rowProto.getValues(i).getFlag() != Integer.MIN_VALUE) {
                                                row.set(i, RecordSet.ToObject(rowProto.getValues(i).getStringValue(), recordSet.getColumns().get(i).getDataType()));
                                            }
                                            break;
                                    }
                                }
                            }
                        }
                    }
                    recordSet.addRow(row);
                }
            }
        } catch (IllegalArgumentException ex) {
            throw new InvalidReaderException("Reader state has been lost.: ", ex);
        }
    }

    public final String getCacheId() {
        return cacheId;
    }

    public final void setCacheId(String value) {
        cacheId = value;
    }

    private void MergeFailedResponse(CommandResponse response) {
        Command command = null;
        boolean success = (command = _commands.get(response.getResetConnectionIP())) != null;
        if (!success) {
            try {
                command = _commands.get(new Address(InetAddress.getLocalHost().getHostAddress(), 9800));
            } catch (UnknownHostException e) {

            }
        }

        switch (_type) {
            case ADD_BULK:
            case INSERT_BULK:
            case GET_BULK:
            case REMOVE_BULK:

            case GET_KEYS_TAG:
            case SEARCH:
            case SEARCH_ENTRIES:
            case POLL:
            case EXECUTE_READER:
            case GET_TAG:
            case MESSAGE_ACKNOWLEDGEMENT:
            case GET_MESSAGE:
                _finalResponse.setBrokerRequested(true);
                _finalResponse.setResetConnectionIP(response.getResetConnectionIP());
                break;
        }

    }

    public final java.util.ArrayList> GetSendFailureCommands() throws CommandException {
        java.util.ArrayList> failedSendCommands = null;

        synchronized (_responseMutex) {
            DeserializeRawResponsesIfPresent();
            for (java.util.Map.Entry> allResponses : _responses.entrySet()) {
                //Iterates over all ResponseList objects against one IP
                for (ResponseList responses : allResponses.getValue().values()) {
                    //Iterates over all CommandResponse objects in each ResponseList
                    for (CommandResponse rsp : responses.getResponses()) {
                        //in case exception is not thrown from 1st server.
                        if (rsp.getIsSendFailure()) {
                            if (failedSendCommands == null) {
                                failedSendCommands = new java.util.ArrayList<>();
                            }

                            failedSendCommands.add(new AbstractMap.SimpleEntry(allResponses.getKey(), responses.getCommand()));
                            break;
                        }
                    }
                }
            }
        }

        return failedSendCommands;
    }

    public final void InitializeFailedSendResponse(Address address, Command command) {
        synchronized (_responseMutex) {
            if (_responses == null) {
                _responses = new java.util.HashMap<>();
            }
            if (!_responses.containsKey(address)) {
                _responses.put(address, new java.util.HashMap<>());
            }

            java.util.HashMap allResponses = _responses.get(address);
            allResponses.put(command.getCommandID(), new ResponseList(command));
            CommandResponse response = new CommandResponse(false, address);
            response.setSendFailure(true);
            allResponses.get(command.getCommandID()).AddResponse(response);
        }
        command.setFinalDestinationAddress(address);
    }


    public final void RemoveResponse(java.util.ArrayList> failedSendCommands) {
        synchronized (_responseMutex) {
            for (java.util.Map.Entry pair : failedSendCommands) {
                Address address = pair.getKey();
                Command command = pair.getValue();

                if (address != null && _responses.containsKey(address)) {
                    _responses.get(address).remove(command.getCommandID());
                    if (_responses.get(address).isEmpty()) {
                        _responses.remove(address);
                    }
                }
            }
        }
    }

    public final void AddSurrogateCommand(SurrogateCommand surrogateCommand, Address address) {
        if (_surrogateCommands == null) {
            _surrogateCommands = new java.util.HashMap<>();
        }
        surrogateCommand.setParent(this);
        _surrogateCommands.put(address, surrogateCommand);
    }

    public final void RemoveSurrogateCommand(Address address) {
        if (_surrogateCommands != null) {
            _surrogateCommands.remove(address);
        }
    }

    public void getModuleResponses(ModuleOperation operation) throws OperationFailedException {

        java.util.HashMap responses = getResponses();

        if (responses != null) {
            for (java.util.Map.Entry perServerResponse : responses.entrySet()) {
                for (CommandResponse response : perServerResponse.getValue().getResponses()) {
                    Partition tempVar = new Partition();
                    tempVar.setAddress(perServerResponse.getKey());
                    Partition partition = tempVar;
                    try {
                        response.parseResponse();
                        ;
                    } catch (Exception e) {
                        operation.AddFailure(partition, e);
                        continue;
                    }

                    if (response.getProtobufResponse().getModuleResponse() == null) {
                        throw new OperationFailedException("protobuff response is null");
                    }

                    operation.AddResult(partition, response.getProtobufResponse().getModuleResponse().getPayload(0).toByteArray());
                }
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy