com.alachisoft.ncache.client.internal.communication.Request Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ncache-professional-client Show documentation
Show all versions of ncache-professional-client Show documentation
NCache Professional client for java.
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