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

com.alachisoft.ncache.client.internal.caching.RemoteCache Maven / Gradle / Ivy

/* CacheOld.java
 *
 * Created on August 29, 2006, 2:53 PM
 *
 * Copyright 2005 Alachisoft, Inc. All rights reserved.
 * ALACHISOFT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.alachisoft.ncache.client.internal.caching;
import Alachisoft.NCache.Caching.Messaging.Message;
import Alachisoft.NCache.Caching.OpCode;
import Alachisoft.NCache.Common.*;
import Alachisoft.NCache.Common.BitSet;
import Alachisoft.NCache.Common.DataReader.*;
import Alachisoft.NCache.Common.DataStructures.EnumerationPointer;
import Alachisoft.NCache.Common.DataStructures.GroupEnumerationPointer;
import Alachisoft.NCache.Common.Enum.NotificationsType;
import Alachisoft.NCache.Common.Enum.SubscriptionType;
import Alachisoft.NCache.Common.Enum.TopicOperationType;
import Alachisoft.NCache.Common.Enum.UserObjectType;
import Alachisoft.NCache.Common.Extensibility.Client.RPC.Partition;
import Alachisoft.NCache.Common.Extensibility.Client.RPC.PartitioningStrategy;
import Alachisoft.NCache.Common.Locking.LockAccessType;
import Alachisoft.NCache.Common.Logger.ILogger;
import Alachisoft.NCache.Common.Net.Address;
import Alachisoft.NCache.Common.Threading.ThreadPool;
import Alachisoft.NCache.Common.Util.DependencyHelper;
import Alachisoft.NCache.Management.Statistics.StatisticsCounter;

import com.alachisoft.ncache.client.*;
import com.alachisoft.ncache.client.ClientInfo;
import com.alachisoft.ncache.client.internal.command.*;
import com.alachisoft.ncache.client.internal.communication.*;
import com.alachisoft.ncache.client.internal.messaging.ReceivedMessages;
import com.alachisoft.ncache.client.internal.util.ConversionUtil;
import com.alachisoft.ncache.client.internal.util.HelperUtil;
import com.alachisoft.ncache.client.internal.util.NotificationType;
import Alachisoft.NCache.Common.ErrorHandling.ErrorCodes;
import Alachisoft.NCache.Common.ErrorHandling.ErrorMessages;
import com.alachisoft.ncache.client.util.SerializationUtil;
import com.alachisoft.ncache.common.monitoring.ClientMetaData;
import com.alachisoft.ncache.common.monitoring.MetricsTransporter;
import com.alachisoft.ncache.common.protobuf.DependencyProtocol;
import com.alachisoft.ncache.ncactivate.utils.RegUtil;
import com.alachisoft.ncache.runtime.CacheItemPriority;
import com.alachisoft.ncache.runtime.caching.*;
import com.alachisoft.ncache.runtime.dependencies.CacheDependency;
import com.alachisoft.ncache.runtime.events.EventDataFilter;
import com.alachisoft.ncache.runtime.events.EventType;
import com.alachisoft.ncache.runtime.events.ListenerType;
import com.alachisoft.ncache.runtime.exceptions.SecurityException;
import com.alachisoft.ncache.runtime.exceptions.*;
import com.alachisoft.ncache.runtime.exceptions.runtime.OperationFailedRuntimeException;
import com.alachisoft.ncache.runtime.util.TimeSpan;
import com.alachisoft.ncache.serialization.core.io.surrogates.NCacheArgumentException;
import com.alachisoft.ncache.serialization.standard.FormatterServices;
import com.alachisoft.ncache.serialization.standard.io.ObjectInputStream;
import com.alachisoft.ncache.serialization.util.TypeInfoMap;
import com.fasterxml.jackson.core.JsonProcessingException;
import tangible.RefObject;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.lang.reflect.Field;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Implements the clustered cache for an application. This class cannot be
 * inherited.
 *
 * @author Administrator
 * @version 1.0
 */
public final class RemoteCache extends CacheImplBase implements RecordSetLoader {


    /**
     * Disable lock expiration
     */
    public static final TimeSpan NoLockingExpiration = null;
    /**
     * @return
     */
    // Types of Enumerations/Iterations
    private static final int KEYS = 0;
    private static final int VALUES = 1;
    private static final int ENTRIES = 2;
    /**
     * specify no absolute expiration.
     */
    public static Date NoAbsoluteExpiration = null;
    /**
     * specify no sliding expiration.
     */
    public static TimeSpan NoSlidingExpiration = null;
    StatisticsCounter _perfStatsCollector;

    List _cacheCleared = Collections.synchronizedList(new ArrayList());

    /* The Broker object to handle the requests. */
    List _cacheItemAdded = Collections.synchronizedList(new ArrayList());
    List _cacheItemUpdated = Collections.synchronizedList(new ArrayList());
    List _cacheItemRemoved = Collections.synchronizedList(new ArrayList());
    List _memberJoined = Collections.synchronizedList(new ArrayList());
    List _memberLeft = Collections.synchronizedList(new ArrayList());
    List _cacheStopped = Collections.synchronizedList(new ArrayList());
    List _customListener = Collections.synchronizedList(new ArrayList());
    boolean _clientConnectivityRegistered;
    boolean _clientCacheEnabled = false;
    /**
     *
     */
    FormatterServices impl;
    /**
     *
     */
    HashMap _compactTypes;
    /**
     *
     */
    HashMap _attributeOrder;
    /**
     *
     */
    HashMap _portablity;
    private String cacheId = null;
    private String _monitoringSessionId;
    private String _cacheConfigId;
    private boolean exceptionsEnabled = true;
    private boolean memberjoinedFlag = false;
    private boolean memberleftFlag = false;
    private boolean cachestoppedFlag = false;
    private Level _level = Level.SEVERE;
    /**
     * The Command Broker.
     */
    private com.alachisoft.ncache.client.internal.communication.Broker Broker = null;
    private int _compressed = BitSetConstants.Compressed;
    /*collection for the callbacks*/
    private Vector callbackQue = new Vector();
    //    private CustomListener[] customListenersList = new CustomListener[0];
    private com.alachisoft.ncache.serialization.util.TypeInfoMap typeMap = null;
    private long _compressionThresholdSize;
    private boolean _compressionEnabled;
    private boolean _addNotifRegistered;
    private boolean _updateNotifRegistered;
    private boolean _removeNotifRegistered;
    private boolean _clearNotifRegistered;
    private boolean _customNotifRegistered;
    private int _refCounter = 0;
    private int forcedViewId = -5;
    private String _bridgeTargetCacheUniqueID;
    /// Serialization context (actually name of the cache.)used for Compact Framework 
    private String _serializationContext;
    private HashMap _encryption;
    private HashMap _expirations;
    private CacheImpl _parent;
    private CacheAsyncEventsListener _asyncListener;

    private RemoteCacheClusterEventsListener _clusterListener;
    private RemoteCacheEventsListener _EventsListener;
    //-Sami:20140203
    private RemoteCacheClusterEventsListener cacheClusterEventsListener;
    private HashMap> validReaders = new HashMap<>();
    StopWatch _dedicatedCallMonitoring = new StopWatch();
    boolean _isDedicatedCall = false;
    Object _mutexlock = new Object();


    /**
     * Maximum threads allowed at a time is 25, but if they ever exceed the old
     * threads if inactive will be given a grace period of 60 seconds before
     * terminating them
     * 

* NOTE: Avoid using wait or sleep in a thread assigned to * this pool. This pool is used for 'Do things and get out ' stuff

*/ // private ExecutorService pool = Executors.newFixedThreadPool(25, tExec.getThreadFactory()); // // private RemoteCache() { // to avoid instantiation. } public RemoteCache(String cacheId, CacheImpl parent, CacheConnectionOptions cacheConnectionOptions, StatisticsCounter perfStatsCol) throws GeneralFailureException, ConfigurationException, SecurityException, Exception { _perfStatsCollector = perfStatsCol; _parent = parent; if (_parent != null) { _asyncListener = new CacheAsyncEventsListener(_parent); _EventsListener = new RemoteCacheEventsListener(_parent.getEventListener()); _clusterListener = new RemoteCacheClusterEventsListener(_parent); } if (cacheId == null) { throw new IllegalArgumentException("Value cannot be null.\nParamenter name: cacheId"); } this.cacheId = cacheId.toLowerCase(); Broker = new Broker(this, cacheConnectionOptions, perfStatsCol, getLocalClientInfo()); ServerInfo rServer = Broker.GetInitialServer(); try { Broker.StartServices(cacheId, rServer.getName(), rServer.getPort()); _cacheConfigId = Broker.getCacheConfigID(); _monitoringSessionId = Broker.getMonitoringSessionId(); }catch(SecurityException sec) { throw sec; } catch (CacheException ex) { throw new GeneralFailureException(ex.getMessage()); } if (!Broker.getIsConnected()) { Broker.dispose(); throw new OperationFailedException(ErrorCodes.Common.NO_SERVER_AVAILABLE_FOR_CACHE, ErrorMessages.getErrorMessage(ErrorCodes.Common.NO_SERVER_AVAILABLE_FOR_CACHE, this.cacheId)); } } public CacheAsyncEventsListener getAsyncEventListener(){ return _asyncListener; } public RemoteCacheClusterEventsListener getCacheClusterEventsListener() { return _clusterListener; } public void setCacheClusterEventsListener(RemoteCacheClusterEventsListener cacheClusterEventsListener) { this._clusterListener = cacheClusterEventsListener; } public RemoteCacheEventsListener getEventsListener() { return this._EventsListener; } protected List getCustomEventListenerList() { return this._customListener; } @Override boolean isInproc() { return false; } @Override public String getMonitoringSessionId() { return _monitoringSessionId; } @Override public String getCacheConfigId() { return _cacheConfigId; } String getSerializationContext() { return _serializationContext; } void setSerializationContext(String value) { _serializationContext = value; } String getTargetCacheUniqueID() { return _bridgeTargetCacheUniqueID; } void setTargetCacheUniqueID(String value) { _bridgeTargetCacheUniqueID = value; } void setParentCache(CacheImpl parentCache) { _parent = parentCache; } // public String getName() { return cacheId; } @Override public ILogger getNCacheLog() { return Broker.getNCacheLog(); } @Override Vector getCallbackQueue() { return callbackQue; } @Override public void setItem(String key, Object value) { } @Override public HashMap getEncryptionInfo() { return _encryption; } @Override public void touch(ArrayList keys) throws OperationFailedException, LicensingException, CommandException, StreamAlreadyLockedException, GeneralFailureException, OperationNotSupportedException, SecurityException, StreamException, ConfigurationException, StreamNotFoundException, AggregateException { java.util.HashMap> keysDistributionMap = new java.util.HashMap>(); Request request; if (Broker.getImportHashmap()) { request = new Request(true, Broker.getOperationTimeout()); tangible.RefObject>> tempRef_keysDistributionMap = new tangible.RefObject>>(keysDistributionMap); boolean isMrgKeys = Broker.getKeysDistributionMap(ConversionUtil.toArray(keys,String.class), null,keysDistributionMap); keysDistributionMap = tempRef_keysDistributionMap.argvalue; for (Address serverAddress : keysDistributionMap.keySet()) { java.util.Map.Entry keysAndItems = keysDistributionMap.get(serverAddress); java.util.ArrayList list = new java.util.ArrayList(); for(String key: keysAndItems.getKey()) { list.add(key); } TouchCommand command = new TouchCommand(list); if (isMrgKeys) { command.setClientLastViewId(Broker.ForcedViewId); } else { command.setClientLastViewId (Broker.getClientLastViewId()); } request.addCommand(serverAddress, command); } } else { TouchCommand command = new TouchCommand(keys); request = Broker.createRequest(command); } Broker.executeRequest(request); CommandResponse res = request.getResponse(); res.parseResponse(); } @Override protected com.alachisoft.ncache.serialization.util.TypeInfoMap getTypeMap() { return this.typeMap; } @Override protected void setTypeMap(TypeInfoMap value) { this.typeMap=value; } // @Override // public HashMap insert(String[] keys, com.alachisoft.ncache.client.caching.CacheItem[] items, int[] removeCallbackIds, int[] updateCallbackIds, short onDsItemsUpdatedCallback, String providerName, long[] sizes) throws CacheException { // return null; // } /** * Keeps the number of initializations of this cache, used at dispose when * all threads have called in the dispose method */ synchronized void addRef() { _refCounter++; } @Override public String toString() { return cacheId; } //- Asad:20110330 // /** * If this property is set the Cache object throws exceptions from public * operations. If not set no exception is thrown and the operation fails * silently. Setting this flag is especially helpful during development * phase of application since exceptions provide more information about the * specific causes of failure. * * @return true if exceptions are enabled, otherwise false. */ public boolean isExceptionsEnabled() { return exceptionsEnabled; } /** * If this property is set the Cache object throws exceptions from public * operations. If not set no exception is thrown and the operation fails * silently. Setting this flag is especially helpful during development * phase of application since exceptions provide more information about the * specific causes of failure. * * @param exceptionsEnabled boolean value to enable/disable the exceptions. */ public void setExceptionsEnabled(boolean exceptionsEnabled) { this.exceptionsEnabled = exceptionsEnabled; }// // //- Asad:20110330 @Override public CacheItemVersion add(String key, Object value, CacheDependency dependency, CacheSyncDependency syncDependency, java.util.Date absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, short onRemoveCallback, short onUpdateCallback, short onDsItemAddedCallback, boolean isResyncExpiredItems, String group, java.util.HashMap queryInfo, BitSet flagMap, String providerName, EventDataFilter itemUpdateDataFilter, EventDataFilter itemRemovedDataFilter, long size, boolean encryptionEnabled, String clientId,String typeName) throws OperationFailedException, AggregateException, SecurityException, GeneralFailureException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { AddCommand command = new AddCommand(key, (byte[]) value, dependency, syncDependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, onUpdateCallback, onDsItemAddedCallback, isResyncExpiredItems, group, (short)-1,false, queryInfo, flagMap, providerName, getEncryptionEnabled(), this.cacheId, itemUpdateDataFilter, itemRemovedDataFilter,TargetMethodAttribute.getMethodOverload() ,clientId,typeName); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); return HelperUtil.createCacheItemVersion(response.getVersion()); } @Override public Object addAsync(String key, Object value, CacheDependency dependency, CacheSyncDependency syncDependency, Date absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, short onRemoveCallback, short onUpdateCallback, short onAsyncItemAddCallback, short dsItemAddedCallback, boolean isResyncExpiredItems, String group, HashMap queryInfo, BitSet flagMap, String providerName, String resyncProviderName, EventDataFilter itemUpdateDataFilter, EventDataFilter itemRemovedDataFilter, long size, String clientId, short updateCallbackId, short removeCallbackId, short dsItemAddedCallbackId) throws Exception { return null; } @Override public java.util.HashMap add(String[] keys, com.alachisoft.ncache.client.CacheItem[] items , String providerName, long[] sizes, boolean encryptionEnabled , String clientID , short updateCallbackId , short removeCallbackId , EventDataFilter updateCallbackFilter , EventDataFilter removeCallbackFilter ,boolean returnVersions , Map itemVersions , ListenerType listenerType) throws OperationFailedException, SecurityException, AggregateException, GeneralFailureException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { java.util.HashMap> keysDistributionMap = new HashMap<>(); Request request; if (Broker.getImportHashmap()) { if (Broker.poolFullyDisConnected()) { throw new OperationFailedException("No server is available to process the request"); } if (!Broker.getPoolFullyConnected()) { BulkAddCommand command = new BulkAddCommand(keys, items, _parent ,providerName, encryptionEnabled, cacheId, 0, clientID , updateCallbackId , removeCallbackId , updateCallbackFilter ,removeCallbackFilter ,returnVersions ,listenerType); request = Broker.createDedicatedRequest(command); } else { request = new Request(true, Broker.getOperationTimeout()); boolean isMrgKeys = Broker.getKeysDistributionMap(keys, items, keysDistributionMap); for (Address serverAddress : keysDistributionMap.keySet()) { java.util.Map.Entry keysAndItems = keysDistributionMap.get(serverAddress); BulkAddCommand command = new BulkAddCommand(keysAndItems.getKey(), keysAndItems.getValue() , _parent , providerName , encryptionEnabled , cacheId , 0 , clientID , updateCallbackId , removeCallbackId , updateCallbackFilter , removeCallbackFilter , returnVersions , listenerType); command.setClientLastViewId(Broker.getClientLastViewId()); request.addCommand(serverAddress, command); if (isMrgKeys) { command.setClientLastViewId(Broker.ForcedViewId); } else { command.setClientLastViewId(Broker.getClientLastViewId()); } request.addCommand(serverAddress, command); } } } else { BulkAddCommand command = new BulkAddCommand(keys, items, _parent ,providerName, encryptionEnabled, cacheId, 0, clientID , updateCallbackId , removeCallbackId , updateCallbackFilter ,removeCallbackFilter ,returnVersions ,listenerType); request = Broker.createRequest(command); } try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } return response.getResultMap(); } // // //region Insert Overloads @Override public CacheItemVersion insert(String key, Object value, CacheDependency dependency, CacheSyncDependency syncDependency, java.util.Date absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, short onRemoveCallback, short onUpdateCallback, boolean isResyncExpiredItems, String group, java.util.HashMap queryInfo, BitSet flagMap, String lockId, CacheItemVersion version, LockAccessType accessType, EventDataFilter updateCallbackFilter, EventDataFilter removeCallabackFilter, long size, boolean encryptionEnabled, String clientId, String typeName, ListenerType listenerType) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { InsertCommand command = new InsertCommand(key, (byte[]) value, dependency, syncDependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, onUpdateCallback,isResyncExpiredItems, group, (short)-1, false, queryInfo , flagMap, lockId,version == null ? 0 : version.getVersion(), accessType, null, encryptionEnabled, cacheId, updateCallbackFilter, removeCallabackFilter,TargetMethodAttribute.getMethodOverload(), clientId,typeName,listenerType); Request request =null; request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } return HelperUtil.createCacheItemVersion(response.getVersion()); } //- Asad:20110330 @Override public java.util.HashMap insert(String[] keys, com.alachisoft.ncache.client.CacheItem[] items, long[] sizes, boolean encryptionEnabled, String clientId, short updateCallbackId, short removeCallbackId, EventDataFilter updateCallbackFilter, EventDataFilter removeCallbackFilter, boolean returnVersions, Map itemVersions, ListenerType listenerType) throws OperationFailedException, AggregateException, SecurityException, GeneralFailureException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { java.util.HashMap> keysDistributionMap = new HashMap<>(); Request request; if (Broker.getImportHashmap()) { if (Broker.poolFullyDisConnected()) { throw new OperationFailedException("No server is available to process the request"); } if (!Broker.getPoolFullyConnected()) { BulkInsertCommand command = new BulkInsertCommand(keys, items, _parent ,null, encryptionEnabled, cacheId, 0, clientId , updateCallbackId , removeCallbackId , updateCallbackFilter , removeCallbackFilter,returnVersions ,listenerType); request = Broker.createDedicatedRequest(command); } else { request = new Request(true, Broker.getOperationTimeout()); boolean isMrgKeys = Broker.getKeysDistributionMap(keys, items, keysDistributionMap); for (Address serverAddress : keysDistributionMap.keySet()) { java.util.Map.Entry keysAndItems = keysDistributionMap.get(serverAddress); BulkInsertCommand command = new BulkInsertCommand(keysAndItems.getKey(), keysAndItems.getValue() , _parent , null , encryptionEnabled , cacheId , 0 , clientId , updateCallbackId , removeCallbackId , updateCallbackFilter , removeCallbackFilter, returnVersions , listenerType); if (isMrgKeys) { command.setClientLastViewId(Broker.ForcedViewId); } else { command.setClientLastViewId(Broker.getClientLastViewId()); } request.addCommand(serverAddress, command); } } } else { BulkInsertCommand command = new BulkInsertCommand(keys, items, _parent ,null, encryptionEnabled, cacheId, 0, clientId , updateCallbackId , removeCallbackId , updateCallbackFilter , removeCallbackFilter,returnVersions ,listenerType); request = Broker.createRequest(command); } try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } return response.getResultMap(); } // //+ Asad:20110330 // //+ Asad:20110330 @Override public Alachisoft.NCache.Caching.CompressedValueEntry remove(String key, BitSet flagMap, short dsItemRemovedCallbackId, String lockId, CacheItemVersion version, LockAccessType accessType, String providerName) throws CacheException { Command command = new RemoveCommand(key, flagMap, (short)-1 , false , dsItemRemovedCallbackId, lockId ,version == null ? 0 : version.getVersion() , accessType, providerName , 0); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } response.getFlagValueEntry().setValue(response.getValue()); return response.getFlagValueEntry(); } @Override public java.util.HashMap remove(String[] keys, BitSet flagMap, String providerName, short onDsItemsRemovedCallback) throws CacheException { java.util.HashMap> keysDistributionMap = new HashMap<>(); Request request; if (Broker.getImportHashmap()) { if (Broker.poolFullyDisConnected()) { throw new OperationFailedException("No server is available to process the request"); } if (!Broker.getPoolFullyConnected()) { BulkRemoveCommand command = new BulkRemoveCommand(keys, flagMap, providerName, onDsItemsRemovedCallback , 0); request = Broker.createDedicatedRequest(command); } else { request = new Request(true, Broker.getOperationTimeout()); boolean isMrgKeys = Broker.getKeysDistributionMap(keys, null, keysDistributionMap); for (Address serverAddress : keysDistributionMap.keySet()) { java.util.Map.Entry keysAndItems = keysDistributionMap.get(serverAddress); BulkRemoveCommand command = new BulkRemoveCommand(keysAndItems.getKey(), flagMap, providerName, onDsItemsRemovedCallback , 0); if (isMrgKeys) { command.setClientLastViewId(Broker.ForcedViewId); } else { command.setClientLastViewId(Broker.getClientLastViewId()); } request.addCommand(serverAddress, command); } } } else { BulkRemoveCommand command = new BulkRemoveCommand(keys, flagMap, providerName, onDsItemsRemovedCallback , 0); request = Broker.createRequest(command); } try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } return (HashMap) response.getResultMap(); // HashMap resultMap = (HashMap) response.getResultMap(); // if (resultMap == null) // { // return null; // } // // HashMap deflatMap = new HashMap(resultMap.size()); // ///Do decompression (if necessary) and deserialization of data // ///and add to a new table // // for (Object entry : resultMap.entrySet()) // { // Map.Entry pair = // (Map.Entry) entry; // // CompressedValueEntry valEntry = pair.getValue(); // byte[] deflatValue = (byte[]) valEntry.Value; // if (deflatValue == null) // { // deflatMap.put(pair.getKey(), null); // } // else // { // if (valEntry.Flag.IsBitSet((byte) BitSetConstants.Compressed) == true) // { // try // { // deflatValue = CompressionUtil.Decompress(deflatValue); // } // catch (Exception e) // { // } // } // deflatMap.put(pair.getKey(), getDeserializedObject(deflatValue, valEntry.Flag)); // // } // } // // return deflatMap; } @Override public void delete(String key, BitSet flagMap, short dsItemRemovedCallbackId, String lockId, CacheItemVersion version, LockAccessType accessType, String providerName) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { Command command = new DeleteCommand(key, flagMap,(short)-1, false , dsItemRemovedCallbackId , lockId, version == null ? 0 : version.getVersion(), accessType, providerName , 0); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override public void delete(String[] keys, BitSet flagMap, String providerName, short onDsItemsRemovedCallback) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { HashMap> keysDistributionMap = new HashMap(); Request request; if (Broker.getImportHashmap()) { if (Broker.poolFullyDisConnected()) { throw new OperationFailedException("No server is available to process the request"); } if (!Broker.getPoolFullyConnected()) { BulkDeleteCommand command = new BulkDeleteCommand(keys, flagMap, providerName, onDsItemsRemovedCallback , 0); request = Broker.createDedicatedRequest(command); } else { request = new Request(true, Broker.getOperationTimeout()); boolean isMrgKeys = Broker.getKeysDistributionMap(keys, null, keysDistributionMap); for (Address serverAddress : keysDistributionMap.keySet()) { java.util.Map.Entry keysAndItems = keysDistributionMap.get(serverAddress); BulkDeleteCommand command = new BulkDeleteCommand(keysAndItems.getKey(), flagMap, providerName, onDsItemsRemovedCallback , 0); if (isMrgKeys) { command.setClientLastViewId(Broker.ForcedViewId); } else { command.setClientLastViewId(Broker.getClientLastViewId()); } request.addCommand(serverAddress, command); } } } else { BulkDeleteCommand command = new BulkDeleteCommand(keys, flagMap, providerName, onDsItemsRemovedCallback , 0); request = Broker.createRequest(command); } try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } /** * Remove the group from cache. * * @param group group to be removed. * @param subGroup subGroup to be removed. * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ @Override public void remove(String group) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException { }// //#endif /** * Removes all elements from the Cache. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ @Override public void clear(BitSet flagMap, short onDsClearedCallback, String providerName) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { Command command = new ClearCommand((short)-1 , false , flagMap , onDsClearedCallback , providerName , 0); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } /** * Removes all elements from the Cache asynchronously. *

* operation * source is cleared. * * @throws GeneralFailureException * @throws OperationFailedException * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ //- Asad:20110330 // // @Override public Alachisoft.NCache.Caching.Queries.QueryResultSet search(String query, java.util.HashMap values) throws OperationFailedException, GeneralFailureException, AggregateException { Command command = new SearchCommand(query, values, false, false); Request request = Broker.createRequest(command); CommandResponse response = null; OperationFailedException exception = null; try { Broker.executeRequest(request); response = request.getResponse(); } catch (Exception ex) { exception = new OperationFailedException(ex.getMessage()); } try { response.parseResponse(); } catch (StateTransferInProgressException ex) { try { command = new SearchCommand(query, values, false, false); request = Broker.createDedicatedRequest(command); Broker.executeRequest(request); response = request.getResponse(); response.parseResponse(); } catch (Exception e) { exception = new OperationFailedException(e.getMessage()); } } catch (Exception ex) { exception = new OperationFailedException(ex.getMessage()); } if (this.isExceptionsEnabled() && exception != null) { throw exception; } Alachisoft.NCache.Caching.Queries.QueryResultSet queryResultSet = response.getQueryResultSet(); return queryResultSet; } // // // /** * Remove on the based on the query specified. * * @param query simple SQL like query syntax t oquery objects from cache * @return Returns a dictionary containing removed cache keys and associated * objects * * These operators are supported by NCache Queries. 1. Comparison Operators * = , == , != , <> , < , > , <=, >=, IN 2. Logical Operators AND , OR , NOT * 3. Miscellaneous () , DateTime.Now , DateTime("any date time compatible * string") * * *

* "delete Test.Application.Employee where this.Name = 'Paul Jones'" * "delete Test.Application.Employee where this.Salary > 2000" * "delete Test.Application.Employee where this.Name = 'Paul Jones' and this.Salary > 2000" * "delete Test.Application.Employee where Not(this.Name = 'Paul Jones' and this.Salary > 2000)" * * * */ @Override public int executeNonQuery(String query, HashMap values) throws OperationFailedException, Exception { return -1; } /** * Registers the notifications based on the specified ContinuousQuery. * * @param query ContinuousQuery to register notifications for. * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws OperationFailedException Thrown whenever an API fails. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ @Override public void registerKeyNotificationListener(String key, short update, short remove, EventDataFilter datafilter, boolean notifyOnItemExpiration, ListenerType listenerType) throws OperationFailedException, CommandException, StreamNotFoundException, StreamException, OperationNotSupportedException, StreamAlreadyLockedException, AggregateException, GeneralFailureException, ConfigurationException, LicensingException, SecurityException { Command command = new RegisterKeyNotificationCommand(key,update,remove,datafilter,notifyOnItemExpiration); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch(Exception e) { throw new OperationFailedException(e.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); } @Override public void registerKeyNotificationListener(String[] keys, short update, short remove, EventDataFilter datafilter, boolean notifyOnItemExpiration, ListenerType listenerType) throws OperationFailedException, CommandException, StreamNotFoundException, StreamException, OperationNotSupportedException, StreamAlreadyLockedException, AggregateException, GeneralFailureException, ConfigurationException, LicensingException, SecurityException { Command command = new RegisterBulkKeyNotificationCommand(keys,update,remove,datafilter,notifyOnItemExpiration); Request request= Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); } @Override public void unRegisterGeneralNotificationListener(EventTypeInternal eventTypeInternal, short sequenceNumber) throws CacheException { NotificationsType notificationsType; if (eventTypeInternal == EventTypeInternal.ItemAdded) { notificationsType = NotificationsType.UnregAddNotif; } else if (eventTypeInternal == EventTypeInternal.ItemRemoved) { notificationsType = NotificationsType.UnregRemoveNotif; } else if (eventTypeInternal == EventTypeInternal.ItemUpdated) { notificationsType = NotificationsType.UnregUpdateNotif; } else { return; } RegisterNotification command = new RegisterNotification(notificationsType.getValue(), sequenceNumber); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); } /** * Determines whether the cache contains a specific key. * * @param key The key to locate in the Cache. * @return true if the Cache contains an element with the specified key; * otherwise, false. * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ @Override public boolean contains(String key) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamAlreadyLockedException, StreamException, OperationNotSupportedException, LicensingException, StreamNotFoundException, CommandException { boolean containsResult = false; Map bulkResult = containsBulk(new String[] {key}); if (bulkResult.size() > 0) { containsResult = bulkResult.get(key) == null ? false : bulkResult.get(key); } return containsResult; } public Map containsBulk(String[] keys) throws OperationFailedException, SecurityException, AggregateException, GeneralFailureException, StreamNotFoundException, OperationNotSupportedException, StreamException, ConfigurationException, LicensingException, StreamAlreadyLockedException, CommandException { Request request = null; HashMap> keysDistributionMap = new HashMap>(); if (Broker.getImportHashmap()) { request = new Request(true, Broker.getOperationTimeout()); boolean isMergeKeys = Broker.getKeysDistributionMap(keys, null, keysDistributionMap); for (Address serverAddress : keysDistributionMap.keySet()) { Map.Entry keysAndItems = keysDistributionMap.get(serverAddress); // TODO 5.0 SP3: Using static MethodOverload variable instead of 0. ContainsBulkCommand command = new ContainsBulkCommand(keysAndItems.getKey(), 0); if (isMergeKeys) { command.setClientLastViewId(Broker.ForcedViewId); } else { command.setClientLastViewId(Broker.getClientLastViewId()); } request.addCommand(serverAddress, command); } } else { ContainsBulkCommand command = new ContainsBulkCommand(keys, 0); request = Broker.createRequest(command); } CommandResponse response = null; Broker.executeRequest(request); response = request.getResponse(); response.parseResponse(); //Check logic below. return extractKeyStatus(response.getResultMap(),keys); } public static Map extractKeyStatus(HashMap hashMap, String[] keys) { java.util.ArrayList availableKeys = null; java.util.Map keyStatus = new java.util.HashMap(); if (hashMap.containsKey("items-found")) { availableKeys = (java.util.ArrayList)hashMap.get("items-found"); } for (String key : keys) { keyStatus.put(key, false); if (availableKeys != null && availableKeys.contains(key)) { keyStatus.put(key, true); } } return keyStatus; } //- Asad:20110330 // // @Override // public String openStream(String key, StreamMode mode, String group, java.util.Date absExpiration, TimeSpan slidingExpiration, CacheDependency dependency, CacheItemPriority priority) // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, // StreamAlreadyLockedException, StreamCloseException, StreamInvalidLockException, StreamException, StreamNotFoundException, ConnectionException, Exception { // OpenStreamCommand command = new OpenStreamCommand(key, mode, group, absExpiration, slidingExpiration, dependency, priority , 0); // Request request = Broker.createRequest(command); // try { // Broker.executeRequest(request); // } catch (Exception ex) { // throw new OperationFailedException(ex.getMessage()); // } // // CommandResponse response = request.getResponse(); // // if (this.isExceptionsEnabled()) { // response.parseResponse(); // //This is checked separately as these exceptions are specific to Stream // } // return response.getLockId(); // } // // @Override // public void closeStream(String key, String lockHandle) throws Exception { // CloseStreamCommand command = new CloseStreamCommand(key, lockHandle , 0); // Request request = Broker.createRequest(command); // try { // Broker.executeRequest(request); // } catch (Exception ex) { // throw new OperationFailedException(ex.getMessage()); // } // // CommandResponse response = request.getResponse(); // // if (this.isExceptionsEnabled()) { // response.parseResponse(); // //This is checked separately as these exceptions are specific to Stream // // } // } // // @Override // public int readFromStream(tangible.RefObject buffer, String key, String lockHandle, int offset, int streamOffset, int length) throws Exception { // ReadFromStreamCommand command = new ReadFromStreamCommand(key, lockHandle, streamOffset, length); // Request request = Broker.createRequest(command); // try { // Broker.executeRequest(request); // } catch (Exception ex) { // throw new OperationFailedException(ex.getMessage()); // } // // CommandResponse response = request.getResponse(); // // if (this.isExceptionsEnabled()) { // response.parseResponse(); // //This is checked separately as these exceptions are specific to Stream // // } // // if (response.BytesRead() > 0) { // /*VirtualArray vBuffer = new VirtualArray(res.DataList); // vBuffer.CopyData(buffer, offset, length); // */ // VirtualArray vBuffer = new VirtualArray(response.DataList()); // vBuffer.CopyData(buffer.argvalue, offset, length); // } // // return response.BytesRead(); // } // // @Override // public void writeToStream(String key, String lockHandle, byte[] buffer, int srcOffset, int dstOffset, int length) throws Exception { // WriteToStreamCommand command = new WriteToStreamCommand(key, lockHandle, srcOffset, dstOffset, length, buffer); // Request request = Broker.createRequest(command); // try { // Broker.executeRequest(request); // } catch (Exception ex) { // throw new OperationFailedException(ex.getMessage()); // } // // CommandResponse response = request.getResponse(); // if (this.isExceptionsEnabled()) { // response.parseResponse(); // //This is checked separately as these exceptions are specific to Stream // } // } // // @Override // public long getStreamLength(String key, String lockHandle) throws Exception { // GetStreamLengthCommand command = new GetStreamLengthCommand(key, lockHandle); // Request request = Broker.createRequest(command); // try { // Broker.executeRequest(request); // } catch (Exception ex) { // throw new OperationFailedException(ex.getMessage()); // } // // CommandResponse response = request.getResponse(); // if (this.isExceptionsEnabled()) { // response.parseResponse(); // //This is checked separately as these exceptions are specific to Stream // // } // // return response.StreamLegnth(); // } // // @Override public Alachisoft.NCache.Caching.CompressedValueEntry get(String key, BitSet flagMap, String group, CacheItemVersion version, LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, CommandException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException { String lockId = lockHandle.getLockId(); long itemVersion = version.getVersion(); GetCommand command = new GetCommand(key, flagMap, group, accessType, lockId, lockTimeout, itemVersion, ProcessHandle.current().pid(),TargetMethodAttribute.getMethodOverload()); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } lockHandle.setLockId(response.getLockId()); lockHandle.setLockDate(response.getLockDate().getDate()); version.setVersion(response.getVersion()); response.getFlagValueEntry().getFlag().setData((byte) (response.getFlagValueEntry().getFlag().getData() | flagMap.getData())); response.getFlagValueEntry().setType(response.getEntryType()); return response.getFlagValueEntry(); } // if (_clientCacheEnabled && obj != null) // { // _clientCache.insert(key, new CacheItem(obj)); // } public final CommandResponse ExecuteCacheRequest(Command command, boolean isDedicated) throws Exception { Request request = null; if (getIsDedicated()) { request = Broker.createDedicatedRequest(command); } else { request = Broker.createRequest(command); } Broker.executeRequest(request); return request.getResponse(); } @Override public java.util.Map get(String[] keys, BitSet flagMap) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException { java.util.HashMap> keysDistributionMap = new HashMap(); Request request; if (Broker.getImportHashmap() && Broker.getPoolFullyConnected()) { request = new Request(true, Broker.getOperationTimeout()); boolean isMrgKeys = Broker.getKeysDistributionMap(keys, null, keysDistributionMap); for (Address serverAddress : keysDistributionMap.keySet()) { java.util.Map.Entry keysAndItems = keysDistributionMap.get(serverAddress); BulkGetCommand command = new BulkGetCommand(keysAndItems.getKey(), flagMap , 0); if (isMrgKeys) { command.setClientLastViewId(Broker.ForcedViewId); } else { command.setClientLastViewId(Broker.getClientLastViewId()); } request.addCommand(serverAddress, command); } } else { BulkGetCommand command = new BulkGetCommand(keys, flagMap, 0); request = Broker.createRequest(command); } CommandResponse response = null; try { Broker.executeRequest(request); response = request.getResponse(); } catch (Exception ex) { if(ex instanceof ActivityBlockedException) { if (request.getCommandRequestType() == RequestType.KeyBulkRead) { BulkGetCommand command = new BulkGetCommand(keys, flagMap , 0); try { response = ExecuteCacheRequest(command, true); } catch (Exception ex1) { throw new OperationFailedException(ex1.getMessage()); } } } throw new OperationFailedException(ex.getMessage()); } if (this.isExceptionsEnabled()) { response.parseResponse(); } return response.getResultMap(); } @Override public Map getCacheItemBulk(String[] keysList, BitSet flagMap) throws OperationFailedException, SecurityException, AggregateException, GeneralFailureException, StreamNotFoundException, OperationNotSupportedException, StreamException, ConfigurationException, LicensingException, StreamAlreadyLockedException { java.util.HashMap> keysDistributionMap = new HashMap(); Request request; if (Broker.getImportHashmap() && Broker.getPoolFullyConnected()) { request = new Request(true, Broker.getOperationTimeout()); boolean isMrgKeys = Broker.getKeysDistributionMap(keysList, null, keysDistributionMap); for (Address serverAddress : keysDistributionMap.keySet()) { java.util.Map.Entry keysAndItems = keysDistributionMap.get(serverAddress); BulkGetCacheItemCommand command = new BulkGetCacheItemCommand(keysAndItems.getKey(), flagMap , TargetMethodAttribute.getMethodOverload()); if (isMrgKeys) { command.setClientLastViewId(Broker.ForcedViewId); } else { command.setClientLastViewId(Broker.getClientLastViewId()); } request.addCommand(serverAddress, command); } } else { BulkGetCacheItemCommand command = new BulkGetCacheItemCommand(keysList, flagMap , TargetMethodAttribute.getMethodOverload()); request = Broker.createRequest(command); } CommandResponse response = null; try { Broker.executeRequest(request); response = request.getResponse(); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } if (this.isExceptionsEnabled()) { response.parseResponse(); } return response.getResultMap(); } // /** * Retrieves the key and value pairs in a group or sub group. If only group * is specified, data for the group and all the sub groups of the group are * returned. If both the group and sub group are specified. Only the data * related to the sub group are returned. * * @param group The group whose keys are to be returned. * @param subGroup The sub group of the group foe which keys are to be * returned. * @return The list of keys of a group or a sub group. * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ @Override public Collection getGroupKeys(String group) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException { return null; } @Override public java.util.HashMap getGroupData(String group) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException { return null; } @Override public Object getCacheItem(String key, BitSet flagMap, String group, CacheItemVersion version, LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { String lockId = lockHandle.getLockId(); long itemVersion = version.getVersion(); Command command = new GetCacheItemCommand(key, flagMap , group, accessType, lockId, lockTimeout, itemVersion,TargetMethodAttribute.getMethodOverload()); Request request=null; try { request = Broker.createRequest(command); Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } lockHandle.setLockId(response.getLockId()); lockHandle.setLockDate(response.getLockDate().getDate()); if (response.getItem() == null) { return null; } version.setVersion(response.getItem().getCacheItemVersion()!=null ? response.getItem().getCacheItemVersion().getVersion(): 0); // // Object obj = null; // // //Compression already bieng performed in GetCacheItem case in CommandResponse.parseResponse() // //Correct place to execute decompression is another issue // // obj = getDeserializedObject((byte[]) response.getItem().getValue(), response.getFlagValueEntry().Flag); // // response.getItem().setValue(obj); return response.getItem(); } /** * @return * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // public CacheItem getCacheItem(String key, Date lockTimeout, LockHandle lockHandle, boolean acquireLock) { // return null; // }// // // private HashMap getDeserializedValueMap(HashMap map) throws GeneralFailureException { if (map == null) { return null; } HashMap result = new HashMap(map.size()); for (Object entry : map.entrySet()) { Map.Entry pair = (Map.Entry) entry; Alachisoft.NCache.Caching.CompressedValueEntry valEntry = pair.getValue(); byte[] deflatValue = (byte[]) valEntry.value; if (valEntry.flag.IsBitSet((byte) BitSetConstants.Compressed) == true) { try { deflatValue = CompressionUtil.Decompress(deflatValue); } catch (Exception e) { } } // Object obj = null; // try // { // ByteArrayInputStream val = new ByteArrayInputStream((byte[]) deflatValue); // ObjectInput ow = new ObjectInputStream(val, this.cacheId); // obj = ow.readObject(); // } // catch (IOException iOException) // { // throw new GeneralFailureException(iOException.getMessage()); // } // catch (ClassNotFoundException classNotFoundException) // { // throw new GeneralFailureException(classNotFoundException.getMessage()); // } // result.put(pair.getKey(), obj); result.put(pair.getKey(), getDeserializedObject(deflatValue, valEntry.flag)); } return result; } /** * * * Acquire a lock on an item in cache. * * @param key key of cached item to be locked. * @param lockTimeout TimeSpan after which the lock is automatically * released. * @param lockHandle An instance of LockHandle that will be filled in with * the lock information if lock is acquired successfully. * @return True if the lock was acquired successfully, false otherwise * @throws OperationFailedException Thrown whenever an API fails. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ @Override public boolean lock(String key, TimeSpan lockTimeout, LockHandle lockHandle) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, CommandException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException { Command command = new LockCommand(key , lockTimeout , ProcessHandle.current().pid() , TargetMethodAttribute.getMethodOverload()); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); LockHandle respHandle = response.getLockHandle(); if (respHandle != null) { lockHandle.setLockDate(respHandle.getLockDate()); lockHandle.setLockId(respHandle.getLockId()); } return response.getLockAcquired(); } /** * @param key * @param lockHandle * @return * @throws OperationFailedException * @throws SecurityException * @throws GeneralFailureException * @throws AggregateException * @throws ConfigurationException */ @Override public boolean isLocked(String key, LockHandle lockHandle) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, CommandException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException { Command command = new IsLockedCommand(key, lockHandle.getLockId()); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } LockHandle respHandle = response.getLockHandle(); if (respHandle != null) { lockHandle.setLockDate(respHandle.getLockDate()); //deal with empty string instead of null coz protobuf dont accept null lockHandle.setLockId(respHandle.getLockId()==null||respHandle.getLockId().equals("") ? null : respHandle.getLockId()); } return response.getLockAcquired(); } @Override public void unlock(String key) throws Exception { Command command = new UnlockCommand(key , TargetMethodAttribute.getMethodOverload()); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override protected String getBridgeTargetCacheUniqueID() { return _bridgeTargetCacheUniqueID; } @Override protected void setBridgeTargetCacheUniqueID(String value) { } @Override public void unlock(String key, String lockId) throws Exception { Command command = new UnlockCommand(key, lockId , TargetMethodAttribute.getMethodOverload()); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } /** * Add dependency to the cache item. * * @param isResyncRequired If true cache autmatically synchronizes this item * with the database on expiration. * @param key The cache key used to reference the item. * @param dep CacheDependency to be added * @return True if the operation was successfull. * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ public boolean addDependency(String key, CacheDependency dep, boolean isResyncRequired) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, CommandException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException { return false; } /** * Add CacheSyncDependency to the cache item. * * @param key The cache key used to reference the item. * @param dep CacheSyncDependency to be added * @return True if the operation was successfull. * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ public boolean addDependency(String key, CacheSyncDependency dep) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, CommandException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException { return false; } /** * Add Attribute existing cache item * * @param key Key used to reference the required object * @param attributes Set of attributes to be added * @return True of the operation succeeds otherwise false * @throws OperationFailedException */ public boolean setAttributes(String key, CacheItemAttributes attributes) throws CacheException { AddAttributeCommand command = null; try { DependencyProtocol.Dependency dependency= null; if(attributes.getDependency() !=null) dependency = DependencyHelper.getDependencyProtocol(attributes.getDependency()); command = new AddAttributeCommand(key, attributes.getAbsoluteExpiration(), dependency); } catch (Exception e) { throw new OperationFailedException(e.getMessage()); } Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } return response.isOperationSuccess(); } // // @Override public void registerKeyNotificationListener(String key, short updateCallbackid, short removeCallbackid, EventDataFilter datafilter, boolean notifyOnItemExpiration) throws CacheException { Command command = new RegisterKeyNotificationCommand(key, updateCallbackid, removeCallbackid, datafilter, notifyOnItemExpiration); Request request; request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (ConnectionException e) { throw new ConnectionException(e.getMessage()); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override public void registerKeyNotificationListener(String key, short updateCallbackid, short removeCallbackid, boolean notifyOnItemExpiration) throws CacheException { Command command = new RegisterKeyNotificationCommand(key, updateCallbackid, removeCallbackid, notifyOnItemExpiration); Request request; request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (ConnectionException e) { throw new ConnectionException(e.getMessage()); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override public boolean subscribe(String topicName, String subscriptionName, SubscriptionType subscriptionType, long creationTime, long expiration, SubscriptionPolicyType subscriptionPolicyType) throws CacheException{ Command command = new SubscribeTopicCommand(topicName, subscriptionName, subscriptionType, creationTime, expiration, subscriptionPolicyType); Request request = Broker.createRequest(command); Broker.executeRequest(request); CommandResponse res = request.getResponse(); res.parseResponse(); return res.success(); } @Override public long getMessageCount(String topicName) throws OperationFailedException, CommandException, StreamNotFoundException, StreamException, OperationNotSupportedException, StreamAlreadyLockedException, AggregateException, GeneralFailureException, ConfigurationException, LicensingException, SecurityException { MessageCountCommand command = new MessageCountCommand(topicName); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse res = request.getResponse(); res.parseResponse(); return res.getMessageCount(); } @Override public void unRegisterKeyNotificationListener(String key, short updateCallbackid, short removeCallbackid) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, CommandException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException { Command command = new UnRegisterKeyNotification(key, updateCallbackid, removeCallbackid); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override public void registerKeyNotificationListener(String[] keys, short updateCallbackid, short removeCallbackid) throws CacheException { Command command = new RegisterBulkKeyNotificationCommand(keys, updateCallbackid, removeCallbackid); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override public void registerKeyNotificationListener(String[] keys, short updateCallbackid, short removeCallbackid, EventDataFilter dataFilter, boolean notifyOnItemExpiration) throws CacheException { Command command = new RegisterBulkKeyNotificationCommand(keys, updateCallbackid, removeCallbackid, dataFilter, notifyOnItemExpiration); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override public boolean checkSecurityAuthorization(String cacheId, byte[] password, String userId) throws OperationFailedException, SecurityException, AggregateException, GeneralFailureException, CommandException, StreamNotFoundException, OperationNotSupportedException, StreamException, ConfigurationException, LicensingException, StreamAlreadyLockedException { CheckSecurityAuthorization command = new CheckSecurityAuthorization(cacheId, userId, password); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse res = request.getResponse(); res.parseResponse(); return res.isIsAuthorized(); } @Override public void InvalidateReaders(String serverAddress) { synchronized (validReaders) { if (validReaders.containsKey(serverAddress)) { HashMap readers = validReaders.get(serverAddress); if (readers != null) { for (RecordSetEnumerator partition : readers.keySet()) { ((PartitionRSEnumerator) partition).setIsValid(false); } } validReaders.remove(serverAddress); } } } @Override public void setCompressionThresholdSize(long compressionThreshold) { } @Override public void getThresholdSize(Connection connection) throws InternalCommandException, SecurityException, LicensingException, OperationFailedException { } @Override public Map publishMessage(String topicName, Map keyMessageBulk, boolean notifyDeliveryFailure) throws OperationFailedException, LicensingException, CommandException, StreamAlreadyLockedException, GeneralFailureException, OperationNotSupportedException, SecurityException, StreamException, ConfigurationException, StreamNotFoundException, AggregateException { return null; } private void addToDistributionMap(Address serverAddress, HashMap> messagesDistributionMap, Message value) { if (!messagesDistributionMap.containsKey(serverAddress)) { messagesDistributionMap.put(serverAddress, new java.util.ArrayList(java.util.Arrays.asList(new Message[] {value}))); } else { messagesDistributionMap.get(serverAddress).add(value); } } public final void reRegisterGeneralNotification(Connection connection) throws OperationFailedException, SecurityException, ConfigurationException, LicensingException { try { if (_clearNotifRegistered) { registerNotification(connection, NotificationType.REGISTER_CLEAR, true); this._clearNotifRegistered = true; } if (_customNotifRegistered) { registerNotification(connection, NotificationType.REGISTER_CUSTOM, true); this._customNotifRegistered = true; } if (_clientConnectivityRegistered) { registerNotification(connection, NotificationType.REGISTER_ClIENT_CONNECTIVITY, true); this._customNotifRegistered = true; } registerNotification(connection, NotificationType.REGISTER_MEMBER_JOINED, true); registerNotification(connection, NotificationType.REGISTER_MEMBER_LEFT, true); } catch (ConfigurationException | LicensingException | SecurityException e) { throw e; } catch (CacheException e) { throw new OperationFailedException(e); } } @Override public void ExecuteModuleOperation(ModuleOperation operation) throws OperationFailedException, CommandException, LicensingException { if (operation != null) { Request request = new Request(true, Broker.getOperationTimeout()); for (java.util.Map.Entry commandPair : operation.GetPayloads()) { ModuleCommand command = new ModuleCommand(commandPair.getValue(), operation.getModule(), operation.getVersion()); request.addCommand(commandPair.getKey().getAddress(), command); } Broker.executeRequest(request); request.getModuleResponses(operation); } } @Override public PartitioningStrategy getPartitioningStrategy() { if (Broker != null) return Broker.getPartitioningStrategy(); return null; } public final void registerHashmapChangedEvent(Connection connection) throws OperationFailedException, SecurityException, ConfigurationException, LicensingException { try { registerNotification(connection, NotificationType.REGISTER_HASHMAP_RECIEVED, true); } catch (ConfigurationException | LicensingException | SecurityException e) { throw e; } catch (CacheException e) { throw new OperationFailedException(e); } } public final void getTypeInfoMap(Connection connection) throws InternalCommandException, SecurityException, LicensingException, OperationFailedException { Command command = new GetTypeInfoMapCommand(false); CommandResponse res = commandRegisterForExecution(connection, command); this.setTypeMap(res.getTypeMap()); } public final void getCompactTypesFromServer(Connection connection) throws InternalCommandException, SecurityException, LicensingException, OperationFailedException { GetCompactTypesCommand command = new GetCompactTypesCommand(false); CommandResponse res = commandRegisterForExecution(connection, command); if (res.getResultMap() != null) { //TODO: 5.0 Sp3 HashTable implement IEqualityComparer to generate same type handler . //Hashtable typesMap = HashtableUtil.CreateCustomComparerHashtable(res.getResultMap()); try { setCompactTypes(com.alachisoft.ncache.serialization.util.SerializationUtil.getCompactTypes(res.getResultMap(), false, getName())); } catch (Exception e) { throw new OperationFailedRuntimeException(e); } } } // public final void getEncryptionKeyFromServer(Connection connection) throws InternalCommandException, OperationFailedException, LicensingException, SecurityException { } public final void getExpirationFromServer(Connection connection) throws InternalCommandException, OperationFailedException, LicensingException, SecurityException { } public final void getSerializationFormat(Connection connection) throws InternalCommandException, OperationFailedException, LicensingException, SecurityException { Command command = new GetSerializationFormatCommand(false); CommandResponse res = commandRegisterForExecution(connection, command); _parent.setSerializationFormat(res.getSerializationFormat()); } private CommandResponse commandRegisterForExecution(Connection connection, Command executingCommand) throws InternalCommandException, OperationFailedException, SecurityException, LicensingException { Request request = new Request(false, Broker.getOperationTimeout()); Address ipAddress = connection.getServerAddress(); request.addCommand(ipAddress, executingCommand); CommandResponse res = null; try { Broker.executeRequest(request, connection, true, true); res = request.getResponse(); res.parseResponse(); } catch (InternalCommandException e) { throw e; } catch (SecurityException e) { throw e; } catch (LicensingException e) { throw e; } catch (Exception e) { throw new OperationFailedException(e.getMessage()); } return res; } public void unRegisterKeyNotificationListener(String key, short updateCallbackid, short removeCallbackid, EventType eventType) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { Command command = new UnRegisterKeyNotification(key, updateCallbackid, removeCallbackid); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } public void unRegisterKeyNotificationListener(String[] key, short update, short remove, EventType eventType) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { Command command = new UnRegisterBulkKeyNotification(key, update, remove); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override public void unRegisterKeyNotificationListener(String[] key, short update, short remove) throws OperationFailedException, GeneralFailureException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { Command command = new UnRegisterBulkKeyNotification(key, update, remove); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override public void makeTargetCacheActivePassive(boolean makeActive) throws CacheException { } /** * Raises a custom event. * * @param key The key of the event. * @param value The value. * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ public void raiseCustomEvent(Object key, Object value) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { Command command = new RaiseCustomEventCommand(key, value, false); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); } /** * Returns the cache count. Note that this count is the total item count in * the whole cluster. * * @return The count of the cache elements. * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws OperationFailedException Thrown whenever an API fails. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ public long getCount() throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { Command command = new GetCountCommand(TargetMethodAttribute.getMethodOverload()); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (response != null) { if (this.isExceptionsEnabled()) { response.parseResponse(); } return response.getCount(); //return Integer.parseInt(new String(res.getValue())); } else { return 0L; } } /** * Disposes this cache instance. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ public void dispose(boolean disposing) throws GeneralFailureException, OperationFailedException, ConfigurationException { if (Broker != null) { Broker.dispose(disposing); } this.Broker = null; _parent = null; _encryption = null; _expirations = null; _perfStatsCollector = null; } @Override public Object getItem(String key) throws Exception { return null; } private void streamExceptionOccured(CommandResponse res) throws StreamAlreadyLockedException, StreamException, StreamInvalidLockException, StreamNotFoundException, StreamCloseException { if (res != null && res.getExpMessage() != null) { switch (res.getExpValue()) { case STREAM_ALREADY_LOCKED: throw new StreamAlreadyLockedException(new String(res.getExpMessage())); case STREAM_CLOSED: throw new StreamCloseException(new String(res.getExpMessage())); case STREAM_EXC: throw new StreamException(new String(res.getExpMessage())); case STREAM_INVALID_LOCK: throw new StreamInvalidLockException(new String(res.getExpMessage())); case STREAM_NOT_FOUND: throw new StreamNotFoundException(new String(res.getExpMessage())); } } } // @Override public Object safeSerialize(Object serializableObject, String serializationContext, BitSet flag, CacheImplBase cacheImpl, RefObject size, UserObjectType userObjectType, boolean isCustomerAtributeBaseSerialized) throws GeneralFailureException, OperationFailedException { return SerializationUtil.safeSerializeOutProc(serializableObject, serializationContext, flag, cacheImpl.getSerializationEnabled(), _parent.getSerializationFormat(),size, userObjectType, isCustomerAtributeBaseSerialized); } @Override public T safeDeserialize(Object serializedObject, String serializationContext, BitSet flag, CacheImplBase cacheImpl, UserObjectType userObjectType, Class cls) throws OperationFailedException { Object deserialized = serializedObject; try { deserialized = (T)SerializationUtil.safeDeserializeOutProc(serializedObject, serializationContext, flag, cacheImpl.getSerializationEnabled(), userObjectType, cls); } catch (UnsupportedOperationException e) { // Because of trying to Json format data that is binary serialized deserialized = serializedObject; throw e; } catch (ClassNotFoundException e2) { // Because of trying to Json format data that is binary serialized deserialized = serializedObject; } catch (JsonProcessingException e3){ throw new OperationFailedException(e3.getMessage()); } catch(ClassCastException ex) { throw ex; } catch (Exception e4) { //Kill the exception; it is possible that object was serialized by Java //or from any other domain which can not be deserialized by us. deserialized = serializedObject; } return (T)deserialized; } // private Object getDeserializedObject(byte[] value, Alachisoft.NCache.Common.BitSet flag) throws GeneralFailureException { // // // if (flag.IsBitSet((byte) BitSetConstants.Utf8Encoded)) // { // try // { // String utf8String = new String(value, "UTF8"); // return (Object) utf8String; // } // catch (UnsupportedEncodingException unsupportedEncodingException) // { // return (Object) value; // } // } // else // { // Object obj = null; // ByteArrayInputStream bis = new ByteArrayInputStream(value); // ObjectInputStream ois; // try // { // ois = new ObjectInputStream(bis, this.cacheId); // obj = ois.readObject(); // } // catch (Exception ex) // { // obj = value; // //throw new GeneralFailureException(ex.getMessage()); // } // return obj; // }// try { ByteArrayInputStream val = new ByteArrayInputStream(value); ObjectInput ow = new ObjectInputStream(val, this.cacheId); return ow.readObject(); } catch (IOException iOException) { return value; } catch (ClassNotFoundException classNotFoundException) { throw new GeneralFailureException(classNotFoundException.getMessage()); } } // // //+Sami:20143001 @Override public void registerGeneralNotification(EventTypeInternal eventTypeInternal, EventDataFilter dataFilter, short sequenceNumber) throws CacheException { NotificationsType notificationType; if (eventTypeInternal == EventTypeInternal.ItemAdded) { notificationType = NotificationsType.RegAddNotif; } else if (eventTypeInternal == EventTypeInternal.ItemRemoved) { notificationType = NotificationsType.RegRemoveNotif; } else if (eventTypeInternal == EventTypeInternal.ItemUpdated) { notificationType = NotificationsType.RegUpdateNotif; } else { return; } RegisterNotification notif = new RegisterNotification(notificationType.getValue(), dataFilter.getValue(), sequenceNumber); Request request = Broker.createRequest(notif); // response.parseResponse(); try { Broker.executeRequest(request); } catch (ConnectionException e) { throw new ConnectionException(e.getMessage()); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } // @Override public void registerKeyNotificationListener(String[] keys, short updateCallbackid, short removeCallbackid, String clientId, ListenerType listenerType) { } //-Sami:20143001 @Override protected void registerCacheEventlistener(CacheListener listener, EnumSet registerAgainst) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamNotFoundException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, CommandException { boolean cleared = false, added = false, removed = false, updated = false; CacheListenerWrapper wrapper = new CacheListenerWrapper(listener); if (registerAgainst.contains(CacheNotificationType.ALL)) { if (!_cacheCleared.contains(wrapper)) { _cacheCleared.add(wrapper); cleared = true; } if (!_cacheItemAdded.contains(wrapper)) { _cacheItemAdded.add(wrapper); added = true; } if (!_cacheItemRemoved.contains(wrapper)) { _cacheItemRemoved.add(wrapper); removed = true; } if (!_cacheItemUpdated.contains(wrapper)) { _cacheItemUpdated.add(wrapper); updated = true; } } else { if (registerAgainst.contains(CacheNotificationType.CacheCleared) && !_cacheCleared.contains(wrapper)) { _cacheCleared.add(wrapper); cleared = true; } if (registerAgainst.contains(CacheNotificationType.ItemAdded) && !_cacheItemAdded.contains(wrapper)) { _cacheItemAdded.add(wrapper); added = true; } if (registerAgainst.contains(CacheNotificationType.ItemRemoved) && !_cacheItemRemoved.contains(wrapper)) { _cacheItemRemoved.add(wrapper); removed = true; } if (registerAgainst.contains(CacheNotificationType.ItemUpdated) && !_cacheItemUpdated.contains(wrapper)) { _cacheItemUpdated.add(wrapper); updated = true; } } if (_cacheCleared.size() == 1 && cleared && (registerAgainst.contains(CacheNotificationType.CacheCleared) || registerAgainst.contains(CacheNotificationType.ALL))) { registerNotification(NotificationType.REGISTER_CLEAR, true); this._clearNotifRegistered = true; } if (_cacheItemAdded.size() == 1 && added && registerAgainst.contains(CacheNotificationType.ItemAdded) || registerAgainst.contains(CacheNotificationType.ALL)) { registerNotification(NotificationType.REGISTER_ADD, true); this._addNotifRegistered = true; } if (_cacheItemRemoved.size() == 1 && removed && registerAgainst.contains(CacheNotificationType.ItemRemoved) || registerAgainst.contains(CacheNotificationType.ALL)) { registerNotification(NotificationType.REGISTER_REMOVE, true); this._removeNotifRegistered = true; } if (_cacheItemUpdated.size() == 1 && updated && registerAgainst.contains(CacheNotificationType.ItemUpdated) || registerAgainst.contains(CacheNotificationType.ALL)) { registerNotification(NotificationType.REGISTER_INSERT, true); this._updateNotifRegistered = true; } } @Override protected void unregisterCacheEventlistener(CacheListener listener, EnumSet unregisterAgainst) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamNotFoundException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, CommandException { if (unregisterAgainst.contains(CacheNotificationType.ALL)) { removeIfCacheListenerExists(_cacheCleared, listener); removeIfCacheListenerExists(_cacheItemAdded, listener); removeIfCacheListenerExists(_cacheItemRemoved, listener); removeIfCacheListenerExists(_cacheItemUpdated, listener); } else { if (unregisterAgainst.contains(CacheNotificationType.CacheCleared)) { removeIfCacheListenerExists(_cacheCleared, listener); } if (unregisterAgainst.contains(CacheNotificationType.ItemAdded)) { removeIfCacheListenerExists(_cacheItemAdded, listener); } if (unregisterAgainst.contains(CacheNotificationType.ItemRemoved)) { removeIfCacheListenerExists(_cacheItemRemoved, listener); } if (unregisterAgainst.contains(CacheNotificationType.ItemUpdated)) { removeIfCacheListenerExists(_cacheItemUpdated, listener); } } if (_cacheCleared.size() == 0 && unregisterAgainst.contains(CacheNotificationType.CacheCleared)) { unregisterNotifications(NotificationType.UNREGISTER_CLEAR); this._clearNotifRegistered = false; } if (_cacheItemAdded.size() == 0 && unregisterAgainst.contains(CacheNotificationType.ItemAdded)) { unregisterNotifications(NotificationType.UNREGISTER_ADD); this._addNotifRegistered = false; } if (_cacheItemRemoved.size() == 0 && unregisterAgainst.contains(CacheNotificationType.ItemRemoved)) { unregisterNotifications(NotificationType.UNREGISTER_REMOVE); this._removeNotifRegistered = false; } if (_cacheItemUpdated.size() == 0 && unregisterAgainst.contains(CacheNotificationType.ItemUpdated)) { unregisterNotifications(NotificationType.UNREGISTER_INSERT); this._updateNotifRegistered = false; } } private boolean removeIfCacheListenerExists(List list, java.util.EventListener listener) { Iterator ite = list.iterator(); int indexOf = -1; if (listener instanceof CacheListener) { while (ite.hasNext()) { CacheListenerWrapper wrapper = (CacheListenerWrapper) ite.next(); if (wrapper.verifyListenerInstance((CacheListener) listener)) { indexOf = list.indexOf(wrapper); break; } } } if (indexOf > -1) { list.remove(indexOf); return true; } else { return false; } } // @Override // protected void addClusterEventListener(ClusterListener l) // { // if (l == null) // { // // In an ideal world, we would do an assertion here // // to help developers know they are probably doing // // something wrong // return; // } // // int length = clusterListenersList.length; // // ClusterListener[] els = new ClusterListener[length + 1]; // System.arraycopy(clusterListenersList, 0, els, 0, length); // // els[length] = l; // // clusterListenersList = els; // } // @Override // protected void addCustomListener(CustomListener l) // { // if (l == null) // { // // In an ideal world, we would do an assertion here // // to help developers know they are probably doing // // something wrong // return; // } // // int length = customListenersList.length; // // CustomListener[] els = new CustomListener[length + 1]; // System.arraycopy(customListenersList, 0, els, 0, length); // // els[length] = l; // // customListenersList = els; // } // @Override // protected void removeClusterEventListener(ClusterListener l) // { // if (l == null) // { // // In an ideal world, we would do an assertion here // // to help developers know they are probably doing // // something wrong // return; // } // // Is l on the list? // int index = -1; // for (int i = clusterListenersList.length - 1; i >= 0; i--) // { // if ((clusterListenersList[i].equals(l) == true)) // { // index = i; // break; // } // } // // // If so, remove it // if (index != -1) // { // ClusterListener[] tmp = new ClusterListener[clusterListenersList.length - 1]; // // Copy the list up to index // System.arraycopy(clusterListenersList, 0, tmp, 0, index); // // Copy from two past the index, up to // // the end of tmp (which is two elements // // shorter than the old list) // if (index < tmp.length) // { // System.arraycopy(customListenersList, index + 1, tmp, index, // tmp.length - index); // } // // set the listener array to the new array or null // clusterListenersList = (tmp.length == 0) ? new ClusterListener[0] : tmp; // } // } // @Override // protected void removeCustomListener(CustomListener l) // { // if (l == null) // { // // In an ideal world, we would do an assertion here // // to help developers know they are probably doing // // something wrong // return; // } // // Is l on the list? // int index = -1; // for (int i = customListenersList.length - 1; i >= 0; i--) // { // if ((customListenersList[i].equals(l) == true)) // { // index = i; // break; // } // } // // // If so, remove it // if (index != -1) // { // CustomListener[] tmp = new CustomListener[customListenersList.length - 1]; // // Copy the list up to index // System.arraycopy(customListenersList, 0, tmp, 0, index); // // Copy from two past the index, up to // // the end of tmp (which is two elements // // shorter than the old list) // if (index < tmp.length) // { // System.arraycopy(customListenersList, index + 1, tmp, index, // tmp.length - index); // } // // set the listener array to the new array or null // customListenersList = (tmp.length == 0) ? new CustomListener[0] : tmp; // } // } /** * Registers the Add operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void registerAddNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // if (this._addNotifRegistered == false ) // { // registerNotification(NotificationType.REGISTER_ADD, true); // this._addNotifRegistered = true; // } // } /** * Registers the Insert operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void registerInsertNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // if (this._updateNotifRegistered == false) // { // registerNotification(NotificationType.REGISTER_INSERT, true); // this._updateNotifRegistered = true; // } // } /** * Registers the Remove operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void registerRemoveNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // if (this._removeNotifRegistered == false) // { // registerNotification(NotificationType.REGISTER_REMOVE, true); // this._removeNotifRegistered = true; // } // // } /** * Registers the Clear operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void registerClearNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // if (this._clearNotifRegistered == false) // { // registerNotification(NotificationType.REGISTER_CLEAR, true); // this._clearNotifRegistered = true; // } // } /** * Registers the Member Joined notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void registerNodeJoinedNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // registerNotification(NotificationType.REGISTER_MEMBER_JOINED, true); // memberjoinedFlag = true; // } /** * Registers the Member Left notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void registerNodeLeftNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // registerNotification(NotificationType.REGISTER_MEMBER_LEFT, true); // memberleftFlag = true; // // } private boolean removeIfClusterListenerExists(List list, java.util.EventListener listener) { Iterator ite = list.iterator(); int indexOf = -1; if (listener instanceof CacheStatusEventListener) { while (ite.hasNext()) { CacheStatusListenerWrapper wrapper = (CacheStatusListenerWrapper) ite.next(); if (wrapper.verifyListenerInstance((CacheStatusEventListener) listener)) { indexOf = list.indexOf(wrapper); break; } } } if (indexOf > -1) { list.remove(indexOf); return true; } else { return false; } } /** * Register the cache stopped event with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void registerCacheStoppedNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // registerNotification(NotificationType.REGISTER_CACHE_STOPPED, true); // cachestoppedFlag = true; // } /** * Unregisters the Add operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws OperationFailedException Thrown whenever an API fails. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void unregisterAddNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // unregisterNotifications(NotificationType.UNREGISTER_ADD); // this._addNotifRegistered = false; // } /** * Unregisters the Insert operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void unregisterInsertNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // unregisterNotifications(NotificationType.UNREGISTER_INSERT); // this._updateNotifRegistered = false; // } /** * Unregisters the Remove operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void unregisterRemoveNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // unregisterNotifications(NotificationType.UNREGISTER_REMOVE); // this._removeNotifRegistered = false; // } /** * Unregisters the Clear operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void unregisterClearNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // unregisterNotifications(NotificationType.UNREGISTER_CLEAR); // this._clearNotifRegistered = false; // } /** * Unregisters the Member Joined Event notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void unregisterNodeJoinedNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // unregisterNotifications(NotificationType.UNREGISTER_MEMBER_JOINED); // memberjoinedFlag = false; // } /** * Unregisters the Memeber Left Event notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void unregisterNodeLeftNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // unregisterNotifications(NotificationType.UNREGISTER_MEMBER_LEFT); // memberleftFlag = false; // } /** * Unregisters the cache stopped even notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws OperationFailedException Thrown whenever an API fails. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ // @Override // public void unregisterCacheStoppedNotification() // throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException // { // unregisterNotifications(NotificationType.UNREGISTER_MEMBER_LEFT); // cachestoppedFlag = false; // } private boolean removeIfCustomListenerExists(List list, java.util.EventListener listener) { Iterator ite = list.iterator(); int indexOf = -1; if (listener instanceof CustomListener) { while (ite.hasNext()) { CustomListenerWrapper wrapper = (CustomListenerWrapper) ite.next(); if (wrapper.verifyListenerInstance((CustomListener) listener)) { indexOf = list.indexOf(wrapper); break; } } } if (indexOf > -1) { list.remove(indexOf); return true; } else { return false; } } /** * @param modifier whenever an API fails. * when an exception occurs during a clustered operation. * exception is thrown when multiple exceptions occur from multiple nodes. * It combines all the exceptions as inner exceptions and throw it to the * client application. */ private void registerNotification(int modifier, boolean checkConnected) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { Command command = new RegisterNotification(modifier); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); } private void registerNotification(Connection connection, int modifier, boolean checkConnected) throws OperationFailedException, CommandException, StreamNotFoundException, StreamException, OperationNotSupportedException, StreamAlreadyLockedException, AggregateException, GeneralFailureException, ConfigurationException, LicensingException, SecurityException { Command command = new RegisterNotification(modifier, (short) -1); Request request = new Request(false, Broker.getOperationTimeout()); Address ipAddress = connection.getServerAddress(); request.addCommand(ipAddress, command); try { Broker.executeRequest(request, connection, checkConnected, true); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); } /** * * @param connection */ // // /** * Notifies the Add Event to all the listeners registered with the cache. * * @param id * @param key The cache key used to reference the item. * * @see CacheEvent * @see CacheListener * @see CacheAdapter */ // private void notifyAddEvent(String key) // { // // Makeup a EventObject // CacheEvent event = new CacheEvent(this, CacheEvent.EventType.ADDED, key); //// System.out.println("Cache.notifyAddEvent : "+Thread.currentThread().getName()); // int length = _cacheItemAdded.size(); // for (int i = 0; i < length; i++) // { // _cacheItemAdded.get(i).getCacheEvent().cacheItemAdded(event); // } // } /** * Notifies the Update Event to all the listeners registered with the cache. * * @param id * @param key The cache key used to reference the item. * * @see CacheEvent * @see CacheListener * @see CacheAdapter */ // private void notifyUpdateEvent(String key) // { // // Makeup a EventObject // CacheEvent event = new CacheEvent(this, CacheEvent.EventType.UPDATED, key); // // int length = _cacheItemUpdated.size(); // for (int i = 0; i < length; i++) // { // _cacheItemUpdated.get(i).getCacheEvent().cacheItemUpdated(event); // } // } /** * Notifies the Remove Event to all the listeners registered with the cache. * * @param id * @param key The cache key used to reference the item. * * @param value * @param reason * @see CacheEvent * @see CacheListener * @see CacheAdapter */ // private void notifyRemoveEvent(String key, Object value, CacheItemRemovedReason reason) // { // // Makeup a EventObject // CacheEvent event = new CacheEvent(this, CacheEvent.EventType.REMOVED, key, value, reason); // // int length = _cacheItemRemoved.size(); // for (int i = 0; i < length; i++) // { // _cacheItemRemoved.get(i).getCacheEvent().cacheItemRemoved(event); // } // } /** * Notifies the Clear Event to all the listeners registered with the cache. * * @see CacheEvent * @see CacheListener */ // private void notifyClearEvent() // { // // int length = _cacheCleared.size(); // for (int i = 0; i < length; i++) // { // _cacheCleared.get(i).getCacheEvent().cacheCleared(); // } // } @Override protected void registerCacheStatusEventlistener(CacheStatusEventListener listener, EnumSet registerAgainst) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamNotFoundException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, CommandException { boolean joined = false, left = false, stopped = false; CacheStatusListenerWrapper wrapper = new CacheStatusListenerWrapper(listener); if (registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.ALL)) { if (!_memberJoined.contains(wrapper)) { _memberJoined.add(wrapper); joined = true; } if (_memberLeft.contains(wrapper)) { _memberLeft.add(wrapper); left = true; } if (!_cacheStopped.contains(wrapper)) { _cacheStopped.add(wrapper); stopped = true; } } else { if (registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.MemberJoined) && !_memberJoined.contains(wrapper)) { _memberJoined.add(wrapper); joined = true; } if (registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.MemberLeft) && !_memberLeft.contains(wrapper)) { _memberLeft.add(wrapper); left = true; } if (registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.CacheStopped) && !_cacheStopped.contains(wrapper)) { _cacheStopped.add(wrapper); stopped = true; } } if (_memberJoined.size() == 1 && joined && registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.MemberJoined) || registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.ALL)) { registerNotification(NotificationType.REGISTER_MEMBER_JOINED, true); this.memberjoinedFlag = true; } if (_memberLeft.size() == 1 && left && registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.MemberLeft) || registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.ALL)) { registerNotification(NotificationType.REGISTER_MEMBER_LEFT, true); this.memberleftFlag = true; } if (_cacheStopped.size() == 1 && stopped && registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.CacheStopped) || registerAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.ALL)) { registerNotification(NotificationType.REGISTER_CACHE_STOPPED, true); this.cachestoppedFlag = true; } } @Override protected void unregisterCacheStatusEventlistener(CacheStatusEventListener listener, EnumSet unregisterAgainst) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamNotFoundException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, CommandException { if (unregisterAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.ALL)) { removeIfCacheListenerExists(_memberJoined, listener); removeIfCacheListenerExists(_memberLeft, listener); removeIfCacheListenerExists(_cacheStopped, listener); } else { if (unregisterAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.MemberJoined)) { removeIfCacheListenerExists(_memberJoined, listener); } if (unregisterAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.MemberLeft)) { removeIfCacheListenerExists(_memberLeft, listener); } if (unregisterAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.CacheStopped)) { removeIfCacheListenerExists(_cacheStopped, listener); } } if (_memberJoined.size() == 1 && unregisterAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.MemberJoined)) { unregisterNotifications(NotificationType.REGISTER_MEMBER_JOINED); this.memberjoinedFlag = false; } if (_memberLeft.size() == 1 && unregisterAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.MemberLeft)) { unregisterNotifications(NotificationType.REGISTER_MEMBER_LEFT); this.memberleftFlag = false; } if (_cacheStopped.size() == 1 && unregisterAgainst.contains(com.alachisoft.ncache.client.CacheStatusNotificationType.CacheStopped)) { unregisterNotifications(NotificationType.REGISTER_CACHE_STOPPED); this.cachestoppedFlag = false; } } @Override protected void registerCustomEventListener(CustomListener listener) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, Exception { if (listener != null) { CustomListenerWrapper wrapper = new CustomListenerWrapper(listener); if (!_customListener.contains(wrapper)) { _customListener.add(wrapper); if (_customListener.size() == 1) { registerCustomNotification(); } } } } @Override protected void unregisterCustomEventListener(CustomListener listener) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { if (listener != null) { removeIfCustomListenerExists(_customListener, listener); if (_customListener.size() == 0) { this.unregisterCustomNotification(); } } } /** * Registers the Clear operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ private void registerCustomNotification() throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamNotFoundException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, CommandException { registerNotification(NotificationType.REGISTER_CUSTOM, true); this._customNotifRegistered = true; } /** * Registers the Clear operation notification with the server. * * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws OperationFailedException Thrown whenever an API fails. * @throws AggregateException This exception is thrown when multiple * exceptions occur from multiple nodes. It combines all the exceptions as * inner exceptions and throw it to the client application. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. * @throws ConfigurationException Thrown when an exception occurs during * configuration. Likely causes are badly specified configuration strings. */ private void unregisterCustomNotification() throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamNotFoundException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, CommandException { unregisterNotifications(NotificationType.UNREGISTER_CUSTOM); this._customNotifRegistered = false; } /** * @param modifier */ private void unregisterNotifications(int modifier) throws GeneralFailureException, OperationFailedException, AggregateException, SecurityException, ConfigurationException, ConnectionException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { Command command = new RegisterNotification(modifier, (short) -1); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); } //- Asad:20110330 /** * Notifies the Member Joined Event to all the listeners registered with the * cache. * * @see CacheEvent * @see CacheListener */ private void notifyMemberJoinedEvent(String ip, int port) throws UnknownHostException { // Makeup a EventObject if (!memberjoinedFlag) { return; } final ClusterEvent event = new ClusterEvent(this, CacheStatusNotificationType.MemberJoined, ip, port, this.cacheId); int length = _memberJoined.size(); for (int i = 0; i < length; i++) { final CacheStatusEventListener listener = _memberJoined.get(i).getClusterEvent(); ThreadPool.getInstance().executeTask(new Runnable() { public void run() { listener.onCacheStatusChanged(event); } }); } } // // /** * Notifies the Member Left Event to all the listeners registered with the * cache. * * @see CacheEvent * @see CacheListener */ private void notifyMemberLeftEvent(String ip, int port) throws UnknownHostException { // Makeup a EventObject if (!memberleftFlag) { return; } final ClusterEvent event = new ClusterEvent(this, CacheStatusNotificationType.MemberJoined, ip, port, this.cacheId); int length = _memberLeft.size(); for (int i = 0; i < length; i++) { final CacheStatusEventListener listener = _memberLeft.get(i).getClusterEvent(); ThreadPool.getInstance().executeTask(new Runnable() { public void run() { listener.onCacheStatusChanged(event); } }); } } /** * Notifies the Cache Stopped Event to all the listeners registered with the * cache. * * @see CacheEvent * @see CacheListener */ private void notifyCacheStoppedEvent(String cacheId) { // Makeup a EventObject if (!cachestoppedFlag) { return; } final ClusterEvent event = new ClusterEvent(this, CacheStatusNotificationType.CacheStopped, cacheId); int length = _cacheStopped.size(); for (int i = 0; i < length; i++) { final CacheStatusEventListener listener = _cacheStopped.get(i).getClusterEvent(); ThreadPool.getInstance().executeTask(new Runnable() { public void run() { listener.onCacheStatusChanged(event); } }); } } /** * */ // protected class WebCacheEnumerator implements Enumeration // { // // private ArrayList _currentChunks; // private Iterator _currentChunkEnumerator; // private String _group; // private String _subGroup; // private Cache.Entry _de; // // /** // * // * @param cacheId // * @param group // * @param subGroup // */ // public WebCacheEnumerator(String cacheId, String group, String subGroup) // { // _group = group; // _subGroup = subGroup; // _de = new Cache.Entry(); // // Initialize(_group, _subGroup); // } // // /** // * // * @param group // * @param subGroup // */ // public void Initialize(String group, String subGroup) // { // ArrayList pointers = new ArrayList(); // // if (group != null && !group.equals("")) // { // pointers.add(new GroupEnumerationPointer(group, subGroup)); // } // else // { // pointers.add(new EnumerationPointer()); // } // // _currentChunks = getChunk(pointers); // ArrayList data = new ArrayList(); // for (int i = 0; i < _currentChunks.size(); i++) // { // EnumerationDataChunk chunk = _currentChunks.get(i); // if (chunk != null && chunk.getData() != null) // { // data.addAll(chunk.getData()); // } // } // _currentChunkEnumerator = data.iterator(); // } // // ///

// /// Advance the enumerator to the next element of the collection // /// // /// // public boolean hasMoreElements() // { // // boolean result = false; // if (_currentChunkEnumerator != null) // { // result = _currentChunkEnumerator.hasNext(); // // if (!result) // { // if (_currentChunks != null && !isLastChunk(_currentChunks)) // { // _currentChunks = getChunk(getPointerList(_currentChunks)); // // ArrayList data = new ArrayList(); // for (int i = 0; i < _currentChunks.size(); i++) // { // if (_currentChunks.get(i) != null && _currentChunks.get(i).getData() != null) // { // data.addAll(_currentChunks.get(i).getData()); // } // } // if (data != null && data.size() > 0) // { // _currentChunkEnumerator = data.iterator(); // result = _currentChunkEnumerator.hasNext(); // } // } // else if (_currentChunks != null && _currentChunks.size() > 0) // { // ArrayList pointers = getPointerList(_currentChunks); // if (pointers.size() > 0) // { // getChunk(pointers); //just an empty call to dispose enumerator for this particular list of pointer // } // } // } // } // return result; // } // // public Object nextElement() // { // String key = (String) getKey(); // _de.setKey(key); // _de.setValue(getValue(key)); // return _de; // } // // /// // /// Gets the key of the current dictionary entry // /// // /** // * // * @return // */ // public Object getKey() // { // Object key = null; // if (_currentChunkEnumerator != null) // { // key = _currentChunkEnumerator.next(); // } // // return key; // } // // /// // /// Gets the value of the current dictionary entry // /// // /** // * // * @param key // * @return // */ // public Object getValue(String key) // { // Object value = null; // try // { // value = get(key); // } // catch (Exception ex) // { // if (ex.getMessage().startsWith("Connection with server lost")) // { // try // { // value = get(key); // } // catch (Exception inner) // { // throw new RuntimeException(inner); // } // } // throw new RuntimeException(ex); // } // return value; // } // // private boolean isLastChunk(List chunks) // { // for (int i = 0; i < chunks.size(); i++) // { // if (!chunks.get(i).isLastChunk()) // { // return false; // } // } // // return true; // } // // private ArrayList getPointerList(ArrayList chunks) // { // ArrayList pointers = new ArrayList(); // for (int i = 0; i < chunks.size(); i++) // { // if (!chunks.get(i).isLastChunk()) // { // pointers.add(chunks.get(i).getPointer()); // } // } // return pointers; // } //// private ArrayList getChunk(ArrayList pointer) //// { //// ArrayList chunks = null; //// //// try //// { //// chunks = getNextChunk(pointer); //// } //// catch (Exception ex) //// { //// //this is a empty call just to dispose the enumeration pointers for this particular enumerator //// //on all the nodes. //// for (int i = 0; i < pointer.size(); i++) //// { //// pointer.get(i).setDisposable(true); //// } //// try //// { //// getNextChunk(pointer); //// } //// catch (Exception exc) //// { //// } //// //// if (exceptionsEnabled) //// { //// //throw ex; //// } //// } //// //// return chunks; //// } // } public void onDataSourceUpdated(short callbackID, HashMap result, OpCode operationCode, boolean notifyAsync) { _asyncListener.onDataSourceUpdated(callbackID, result, operationCode, notifyAsync); } /** * @param pointers * @return * @throws SecurityException * @throws GeneralFailureException */ @Override public java.util.ArrayList getNextChunk(java.util.ArrayList pointers) throws SecurityException, GeneralFailureException, OperationFailedException, AggregateException, ConnectionException, ConfigurationException, StreamException, StreamAlreadyLockedException, LicensingException, OperationNotSupportedException, StreamNotFoundException, CommandException { ArrayList nextChunk = null; Request request; Command command = null; if (pointers.size() > 0 && pointers.get(0).getNodeIpAddress() != null)//&& !pointers.get(0).getNodeIpAddress().equals("")) { if (Broker.getImportHashmap()) { request = new Request(true, Broker.getOperationTimeout()); } else { request = new Request(false, Broker.getOperationTimeout()); } for (int i = 0; i < pointers.size(); i++) { EnumerationPointer pointer = pointers.get(i); if (pointer.isGroupPointer()) { GroupEnumerationPointer groupPointer = (GroupEnumerationPointer) pointer; command = new GetGroupNextChunkCommand(groupPointer.getId(), groupPointer.getChunkId(), groupPointer.getGroup(), groupPointer.getSubGroup()); } else { command = new GetNextChunkCommand(pointer.getId(), pointer.getChunkId(), pointer.isDisposable()); } request.addCommand(pointer.getNodeIpAddress(), command); } } else { if (!Broker.poolHasAllServers() || !Broker.getImportHashmap()) { EnumerationPointer pointer = pointers.get(0); if (pointer.isGroupPointer()) { GroupEnumerationPointer groupPointer = (GroupEnumerationPointer) pointer; command = new GetGroupNextChunkCommand(groupPointer.getId(), groupPointer.getChunkId(), groupPointer.getGroup(), groupPointer.getSubGroup()); } else { command = new GetNextChunkCommand(pointer.getId(), pointer.getChunkId(), pointer.isDisposable()); } request = Broker.createRequest(command); } else { request = new Request(true, Broker.getOperationTimeout()); EnumerationPointer pointer = pointers.get(0); for (int i = 0; i < Broker.getClientServerList().size(); i++) { command = new GetNextChunkCommand(pointer.getId(), pointer.getChunkId(), pointer.isDisposable()); command.setClientLastViewId(-1); ServerInfo server = (ServerInfo) Broker.getClientServerList().get(i); command.setIntendedRecipient(server.getName()); request.addCommand(new Address(server.getName(), server.getPort()), command); } } } try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); response.parseResponse(); nextChunk = response.getNextChunk(); return nextChunk; } /** * @return */ @Override public Enumeration getEnumerator() { return null; } @Override public void finalize() throws Throwable { this.Broker = null; _cacheCleared.clear(); _customListener.clear(); super.finalize(); } private HashMap getQueryInfo(Object value) throws GeneralFailureException { HashMap queryInfo = null; if (this.typeMap == null) { return null; } try { int handleId = typeMap.getHandleId(value.getClass().getCanonicalName()); if (handleId != -1) { queryInfo = new HashMap(); ArrayList attribValues = new ArrayList(); ArrayList attributes = typeMap.getAttribList(handleId); for (int i = 0; i < attributes.size(); i++) { Field fieldAttrib = value.getClass().getField((String) attributes.get(i)); if (fieldAttrib != null) { Object attribValue = fieldAttrib.get(value); // if (attribValue instanceof java.lang.String) //add all strings as lower case in index tree // { // attribValue = (Object) (attribValue.toString()).toLowerCase(); // } attribValues.add(attribValue); } else { throw new Exception("Unable to extract query information from user object."); } } queryInfo.put(handleId, attribValues); } } catch (Exception e) { throw new GeneralFailureException("Unable to extract query information from user object."); } return queryInfo; } private void InitializeLogging(String fileName, Level logLevel) throws GeneralFailureException { if (logLevel == Level.OFF) { Logger logger = Logger.getLogger("com.alachisoft"); logger.setLevel(logLevel); return; } try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); // Create a file handler that uses 3 logfiles, each with a limit of 1Mbyte String pattern = fileName + "." + sdf.format(new java.util.Date()) + ".log-%g.htm"; String path = null; String separator = System.getProperty("file.separator"); int limit = 1000000; // 1 Mb int numLogFiles = 3; if (System.getProperty("os.name").toLowerCase().startsWith("win")) { // path = RegUtil.getNCHome(); if (path != null) { if (!path.endsWith(separator)) { path = path.concat(separator); } } pattern = path.concat(ServicePropValues.LOGS_FOLDER + separator + "Java" + separator + pattern); FileHandler fh = new FileHandler(pattern, limit, numLogFiles); // Add to logger Logger logger = Logger.getLogger("com.alachisoft"); fh.setLevel(logLevel); logger.addHandler(fh); // Root logger has the console out put Hanler attached by default // to disable we can either remove Console handler of the root logger by getting all root loggers // or simply setUseParentHandlers to false to disable passing of logs to the root logger logger.setUseParentHandlers(false); logger.setLevel(Level.OFF); } else { path = System.getenv("NCACHE_ROOT"); if (path != null && path.equalsIgnoreCase("") == false) { path = path.concat(separator + pattern); } else { path = System.getenv("NCACHE_MEMCACHED_ROOT"); if (path != null && path.equalsIgnoreCase("") == false) { path = path.concat(separator + pattern); } } if (path == null) { path = "/usr/local/ncache/"; } // if (!path.endsWith(separator)) { path = path.concat(separator); } pattern = path.concat("logs" + separator + pattern); FileHandler fh = new FileHandler(pattern, limit, numLogFiles); // Add to logger Logger logger = Logger.getLogger("com.alachisoft"); fh.setLevel(logLevel); logger.addHandler(fh); logger.setLevel(logLevel); // Root logger has the console out put Hanler attached by default // to disable we can either remove Console handler of the root logger by getting all root loggers // or simply setUseParentHandlers to false to disable passing of logs to the root logger logger.setUseParentHandlers(false); logger.setLevel(Level.OFF); } } catch (IOException e) { throw new GeneralFailureException(e.getMessage()); } catch (Exception e) { } } // // public HashMap GetExpirationInfo() { return _expirations; } /** * Gets client Cache status, true if enabled * * @return */ public boolean getClientCacheStatus() { return _clientCacheEnabled; } /** * @return */ public long getCompressionThreshold() { return _compressionThresholdSize; } @Override protected void setCompressionThreshold(long value) { _compressionThresholdSize = value; } /** * @return */ public boolean getCompressionEnabled() { return _compressionEnabled; } @Override public void setCompressionEnabled(boolean value) { _compressionEnabled = value; } // //end of Compression Settings // @Override public void registerCacheClientConnectivityEvent() throws CacheException { registerNotifications(NotificationsType.RegisterClientConnectivityNotif); } @Override protected void unregisterCacheClientConnectivityEvent() throws CacheException { registerNotifications(NotificationsType.UnregisterClientConnectivityNotif); } @Override void registerCacheStoppedEvent() throws CacheException { registerNotifications(NotificationsType.RegCacheStoppedNotif); } @Override void unregisterCacheStoppedEvent() throws CacheException { registerNotifications(NotificationsType.UnregCacheStoppedNotif); } @Override void registerClearEvent() throws CacheException { _clearNotifRegistered = true; registerNotifications(NotificationsType.RegClearNotif); } @Override void unregisterClearEvent() throws CacheException { registerNotifications(NotificationsType.UnregClearNotif); } private void registerNotifications(NotificationsType notifMask)throws CacheException { RegisterNotification command = new RegisterNotification(notifMask.getValue(),(short)-1); Request request = Broker.createRequest(command); Broker.executeRequest(request); CommandResponse res = request.getResponse(); res.parseResponse(); } // Contains reference to all User defined Classes to be dynaimically Serialized /** * @param connection * @throws OperationFailedException * @throws GeneralFailureException Thrown when an exception occurs during a * clustered operation. * @throws SecurityException Thrown when current user is not allowed to * perform this operation on this cache. */ protected void getCompressionSettings(Connection connection) throws OperationFailedException, GeneralFailureException, SecurityException, ConnectionException, CommandException { GetCompressionSettings command = new GetCompressionSettings(false); Request request = Broker.createRequest(command); try { Broker.executeRequest(request); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } CommandResponse response = request.getResponse(); this._compressionThresholdSize = response.getCompressionThreshold(); this._compressionEnabled = response.getCompressionEnable(); } /** * Initialize the Compact Serialization Framework */ void initializeCompactFramework() throws NCacheArgumentException, OperationFailedException { impl = FormatterServices.getDefault(); // get User assigned Classes to be Dynamically Serialize Map type = getCompactTypes(); if (type != null) { if (!type.isEmpty() || type.size() != 0) { impl.register(type, getAttributeOrder(), this.cacheId, getPortability()); } } // String[][] temp = new String[2][]; // //Attribute Name // temp[0] = new String[2]; // //Order Number // temp[1] = new String[2]; // // temp[0][0] = "sum"; // temp[0][1] = "count"; // // temp[1][0] = "1"; // temp[1][1] = "2"; // // HashMap attributeOrder = new HashMap(); // attributeOrder.put("com.alachisoft.ncache.web.caching.queries.AverageResult", temp); // try { // Class cls = Class.forName("com.alachisoft.ncache.web.caching.queries.AverageResult"); // // impl.registerBuiltInPortableType(cls, attributeOrder, this.cacheId, (short)159, (short)2); // } // catch(ClassNotFoundException ex) { // // } } /** * @return */ @Override public HashMap getCompactTypes() { return _compactTypes; } void setCompactTypes(HashMap types) { _compactTypes = types; } private HashMap getAttributeOrder() { return _attributeOrder; } private void setAttributeOrder(HashMap attrib) { _attributeOrder = attrib; } private HashMap getPortability() { return _portablity; } private void setPortability(HashMap attrib) { _portablity = attrib; } // @Override public boolean getOrCreate(String topicName, TopicOperationType type) throws CacheException { Command command = new com.alachisoft.ncache.client.internal.command.GetTopicCommand(topicName, type); Request request = Broker.createRequest(command); Broker.executeRequest(request); CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } return response.success(); } // @Override public boolean unSubscribe(String topicName, String recepientId,SubscriptionPolicyType subscriptionPolicyType, SubscriptionType pubSubType, boolean dispose) throws CacheException, InterruptedException { Command command = new com.alachisoft.ncache.client.internal.command.UnSubscribeTopicCommand(topicName, recepientId, pubSubType,subscriptionPolicyType,dispose); Request request = Broker.createRequest(command); Broker.executeRequest(request); CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } return response.success(); } @Override public boolean removeTopic(String topicName, boolean forcefully) throws CacheException { Command command = new com.alachisoft.ncache.client.internal.command.RemoveTopicCommand(topicName, forcefully); Request request = Broker.createRequest(command); Broker.executeRequest(request); CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } return response.success(); } @Override public void publishMessage(String messageId, Object payLoad, long creationTime, long expirationTime, java.util.Hashtable metadata, BitSet flagMap) throws CacheException, InterruptedException { Command command = new com.alachisoft.ncache.client.internal.command.MessagePublishCommand(messageId, (byte[]) payLoad, creationTime, expirationTime, metadata, flagMap); Request request = Broker.createRequest(command); Broker.executeRequest(request); CommandResponse response = request.getResponse(); if (this.isExceptionsEnabled()) { response.parseResponse(); } } @Override public ReceivedMessages getMessageData(BitSet flagMap) throws CacheException { Command command = new com.alachisoft.ncache.client.internal.command.GetMessageCommand(flagMap); ReceivedMessages response = new ReceivedMessages(); Request request = Broker.createRequest(command); Broker.executeRequest(request); CommandResponse res = request.getResponse(); try { res.parseResponse(); } catch (StateTransferInProgressException ex) { command = new com.alachisoft.ncache.client.internal.command.GetMessageCommand(flagMap); request = Broker.createDedicatedRequest(command); Broker.executeRequest(request); res = request.getResponse(); res.parseResponse(); } catch (Exception ex) { throw new OperationFailedException(ex.getMessage()); } response.setAssignedMessages(res.getMessageDic()); response.setRegisteredPatterns(res.getRegisteredPatterns()); return response; } //region DataStructures //endregion @Override public void acknowledgeMessageReceipt(java.util.Map> topicWiseMessageIds) throws Exception { Request request; if (topicWiseMessageIds == null) { return; } if (Broker.getImportHashmap() && Broker.getPoolFullyConnected()) { request = new Request(true, Broker.getOperationTimeout()); HashMap>> messagesDistributionMap = new HashMap<>(); boolean isMrgKey = Broker.GetMessageDistribution(topicWiseMessageIds, messagesDistributionMap); for (Address serverAddress : messagesDistributionMap.keySet()) { HashMap> topicWiseMessages = messagesDistributionMap.get(serverAddress); Command command = new com.alachisoft.ncache.client.internal.command.MesasgeAcknowledgmentCommand(topicWiseMessages); command.setClientLastViewId(isMrgKey ? Broker.ForcedViewId : Broker.getClientLastViewId()); request.addCommand(serverAddress, command); } } else { Command command = new com.alachisoft.ncache.client.internal.command.MesasgeAcknowledgmentCommand(topicWiseMessageIds); request = Broker.createRequest(command); } CommandResponse response = null; try { Broker.executeRequest(request); response = request.getResponse(); } catch (Exception ex) { if (ex instanceof ActivityBlockedException && request.getCommandRequestType() == RequestType.KeyBulkRead) { com.alachisoft.ncache.client.internal.command.MesasgeAcknowledgmentCommand command = new com.alachisoft.ncache.client.internal.command.MesasgeAcknowledgmentCommand(topicWiseMessageIds); response = ExecuteCacheRequest(command, true); } } if (this.isExceptionsEnabled()) { response.parseResponse(); } } // @Override RecordSetEnumerator executeReader(String query, Map values, boolean getData, int chunkSize) throws OperationFailedException { ExecuteReaderCommand command = new ExecuteReaderCommand(query, values, getData, chunkSize, TargetMethodAttribute.getMethodOverload()); CommandResponse res = null; try { try { res = ExecuteCacheRequest(command, false); } catch (ActivityBlockedException ex) { command = new ExecuteReaderCommand(query, values, getData, chunkSize, TargetMethodAttribute.getMethodOverload()); res = ExecuteCacheRequest(command, true); //dedicated request in case of node down } try { res.parseResponse(); } catch (StateTransferInProgressException ex) { SetDedicatedCall(); command = new ExecuteReaderCommand(query, values, getData, chunkSize, TargetMethodAttribute.getMethodOverload()); res = ExecuteCacheRequest(command, true); res.parseResponse(); } } catch (Exception e) { throw new OperationFailedException(e); } java.util.List readerResultSets = null; readerResultSets = res.getReaderResultSets(); java.util.ArrayList prsEnum = new java.util.ArrayList(); for (ReaderResultSet resultSet : readerResultSets) { if (resultSet.getRecordSet() != null) { RecordSetEnumerator rse = resultSet.getRecordSet().getEnumerator(); PartitionRSEnumerator partitionRS = new PartitionRSEnumerator(rse, resultSet.getReaderID(), resultSet.getNodeAddress(), resultSet.getNextIndex(), this); prsEnum.add(partitionRS); updateOpenReaders(partitionRS.getServer(), partitionRS); } } DistributedRSEnumerator drsEnum = null; if (readerResultSets.size() > 0) { if (readerResultSets.get(0).getIsGrouped()) { drsEnum = new DistributedGroupedRSEnumerator(prsEnum, readerResultSets.get(0).getOrderByArguments(), validReaders); } else if (readerResultSets.get(0).getOrderByArguments() != null && readerResultSets.get(0).getOrderByArguments().size() > 0) { drsEnum = new DistributedOrderedRSEnumerator(prsEnum, readerResultSets.get(0).getOrderByArguments(), validReaders); } else { drsEnum = new DistributedRSEnumerator(prsEnum, validReaders); } } return (RecordSetEnumerator)drsEnum; } // endregion //region RecordSetLoader Implementation @Override public ReaderResultSet getRecordSet(String readerID, int nextIndex, String nodeIP, String reciepent) throws OperationFailedException { GetRecordSetNextChunkCommand command = new GetRecordSetNextChunkCommand(readerID, reciepent, nextIndex); Request request; try { if (Broker.getImportHashmap()) { request = new Request(true, Broker.getOperationTimeout()); request.addCommand(new Address(nodeIP, Broker._clientConfig.getServerPort()), command); } else { request = Broker.createRequest(command); } CommandResponse res = null; try { Broker.executeRequest(request); res = request.getResponse(); } catch (Exception ex) { if(ex instanceof ActivityBlockedException){ command = new GetRecordSetNextChunkCommand(readerID, nodeIP, nextIndex); // retry request res = ExecuteCacheRequest(command, false); } throw ex; } try { if (res == null) { throw new InvalidReaderException("Reader state has been lost."); } res.parseResponse(); } catch (StateTransferInProgressException ex) { SetDedicatedCall(); command = new GetRecordSetNextChunkCommand(readerID, nodeIP, nextIndex); // retry request res = ExecuteCacheRequest(command, false); res.parseResponse(); } return res.getReaderNextChunk(); } catch (Exception e) { throw new OperationFailedException(e); } } /** Dispose reader resources on node specified */ @Override public void disposeReader(String readerId, String nodeIp) throws OperationFailedException { DisposeReaderCommand command = new DisposeReaderCommand(readerId, nodeIp, TargetMethodAttribute.getMethodOverload()); Request request; try { if (Broker.getImportHashmap()) { request = new Request(true, Broker.getOperationTimeout()); request.addCommand(new Address(nodeIp, Broker._clientConfig.getServerPort()), command); } else { request = Broker.createRequest(command); } CommandResponse res = null; try { Broker.executeRequest(request); res = request.getResponse(); } catch (Exception ex) { if(ex instanceof ActivityBlockedException){ command = new DisposeReaderCommand(readerId, nodeIp, TargetMethodAttribute.getMethodOverload()); res = ExecuteCacheRequest(command, false); // retry request } throw ex; } try { res.parseResponse(); } catch (StateTransferInProgressException ex) { SetDedicatedCall(); command = new DisposeReaderCommand(readerId, nodeIp, TargetMethodAttribute.getMethodOverload()); res = ExecuteCacheRequest(command, false); // retry request res.parseResponse(); } } catch (Exception e) { throw new OperationFailedException(e); } } private boolean getIsDedicated() { synchronized (_mutexlock) { if (_dedicatedCallMonitoring.getElapsedTime() > 60000) { _dedicatedCallMonitoring.stop(); _isDedicatedCall = false; } return _isDedicatedCall; } } private void SetDedicatedCall() { synchronized (_mutexlock) { _isDedicatedCall = true; _dedicatedCallMonitoring.restart(); } } private void updateOpenReaders(String address, PartitionRSEnumerator partition) { synchronized (validReaders) { HashMap readers = new HashMap<>(); if (validReaders.containsKey(address)) { readers = validReaders.get(address); if (readers != null) { readers.put(partition, null); } } else { readers = new java.util.HashMap(); readers.put(partition, null); } validReaders.put(address,readers); } } //endregion @Override public List getConnectedClientList() throws OperationFailedException, CommandException, StreamNotFoundException, StreamException, OperationNotSupportedException, StreamAlreadyLockedException, AggregateException, GeneralFailureException, ConfigurationException, LicensingException, SecurityException { Request request = Broker.createRequest(new GetConnectedClientsCommand()); Broker.executeRequest(request); CommandResponse response = request.getResponse(); response.parseResponse(); return response.getConnectedClients(); } @Override public void PublishMetadata(MetricsTransporter transporter) throws Exception { ClientMetaData tempVar = new ClientMetaData(); tempVar.setCacheConfigId(_cacheConfigId); tempVar.setCacheName(cacheId); tempVar.setBindIP(ServiceConfiguration.getBindToClientServerIP().toString()); ClientMetaData clientMetaData = tempVar; transporter.PublishMetadata(_monitoringSessionId, "5.2", clientMetaData); } /** * @param * @param */ public class Entry implements Map.Entry { /** * */ K key; /** * */ V value; /** * @param key * @param value */ protected Entry(K key, V value) { this.key = key; this.value = value; } /** * */ protected Entry() { } /** * @return */ @Override protected Object clone() { return new Entry(/*hash,*/key, value/*, (next==null ? null : (Entry) next.clone())*/); } /** * @return */ public K getKey() { return key; } /** * @param key */ public void setKey(K key) { if (key == null) { throw new NullPointerException(); } this.key = key; } /** * @return */ public V getValue() { return value; } /** * @param value * @return */ public V setValue(V value) { // if(value == null) { // throw new NullPointerException(); // } V oldValue = this.value; this.value = value; return oldValue; } /** * @param o * @return */ @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; return (key == null ? e.getKey() == null : key.equals(e.getKey())) && (value == null ? e.getValue() == null : value.equals(e.getValue())); } /** * @return */ @Override public String toString() { return key.toString() + "=" + (value != null ? value.toString() : "null"); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy