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

com.alachisoft.ncache.client.internal.command.BulkAddCommand Maven / Gradle / Ivy

There is a newer version: 5.3.0
Show newest version
/*
 * BulkAddCommand.java
 *
 * Created on September 19, 2006, 5:46 PM
 *
 * Copyright 2005 Alachisoft, Inc. All rights reserved.
 * ALACHISOFT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.alachisoft.ncache.client.internal.command;

import Alachisoft.NCache.Common.BitSetConstants;
import Alachisoft.NCache.Common.Util.DependencyHelper;

import com.alachisoft.ncache.client.CacheItem;
import com.alachisoft.ncache.client.CacheItemWrapperInternal;
import com.alachisoft.ncache.client.internal.caching.CacheHelper;
import com.alachisoft.ncache.client.internal.caching.CacheImpl;
import com.alachisoft.ncache.client.internal.util.ConversionUtil;
import com.alachisoft.ncache.common.protobuf.*;
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.CacheException;
import com.alachisoft.ncache.runtime.exceptions.CommandException;
import com.alachisoft.ncache.runtime.exceptions.OperationFailedException;
import com.alachisoft.ncache.runtime.util.HelperFxn;
import com.alachisoft.ncache.runtime.util.NCDateTime;
import Alachisoft.NCache.Common.Caching.UserBinaryObject;
import com.google.protobuf.ByteString;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;

/**
 * @author Administrator
 */
public final class BulkAddCommand extends Command {

    private final int _methodOveload;
    private EventDataFilter itemUpdateDataFilter;
    private EventDataFilter itemRemoveDataFilter;
    private final boolean _returnVersions;
    private final ListenerType _listenerType;
    private String keys[];
    private com.alachisoft.ncache.client.CacheItem[] items;
    private String group = "";
    private String subGroup = "";
    private boolean isResyncExpiredItems = false;
    //+ Asad:20110330
    private int dsItemsAddedCallbackId;
    private String providerName;
    //- Asad:20110330
    private boolean encryption;
    private String cacheId;
    private short _updateCallbackId;
    private short _removeCallbackId;
    private short _dsItemAddedCallbackId;
    private String _clientId;
    private CacheImpl _parent;

    protected com.alachisoft.ncache.common.protobuf.BulkAddCommandProtocol.BulkAddCommand _commandInstance;
    private BulkAddCommandProtocol.BulkAddCommand.Builder builder = BulkAddCommandProtocol.BulkAddCommand.newBuilder();
    /**
     * Creates a new instance of BulkAddCommand
     */
    public BulkAddCommand(String[] keys, com.alachisoft.ncache.client.CacheItem[] items,
                          CacheImpl parent, String providerName, boolean encryption, String cacheId, int methodOverload,
                          String clientId, short updateCallbackId, short removedCallbackId, EventDataFilter updateCallbackFilter,
                          EventDataFilter removeCallbackFilter, boolean returnVersions, ListenerType listenerType) throws CommandException {
        super.name = "BulkAddCommand";
        this.keys = keys;
        this.items = items;
        this._parent = parent;
        this.providerName = providerName;
        this.encryption = encryption;
        this.cacheId = cacheId;
        this._methodOveload = methodOverload;
        this._clientId = clientId;
        this._updateCallbackId = updateCallbackId;
        this._removeCallbackId = removedCallbackId;

        this.itemUpdateDataFilter = updateCallbackFilter;
        this.itemRemoveDataFilter = removeCallbackFilter;
        this._returnVersions = returnVersions;
        this._listenerType = listenerType;

        super.setBulkKeys(keys);
        buildCommand();

    }

    protected void buildCommand() throws CommandException
    {
        if (this.keys == null) {
            throw new NullPointerException("keys");
        }
        if (this.items == null) {
            throw new NullPointerException("items");
        }
        if (this.keys.length == 0) {
            throw new IllegalArgumentException(
                    "There is no key present in keys array");
        }
        if (this.items.length == 0) {
            throw new IllegalArgumentException(
                    "There is no cache item in items array");
        }
        if (this.keys.length != items.length) {
            throw new IllegalArgumentException(
                    "keys count is not equal to items count");
        }

        int keyLen = keys.length;

        short initialUpdateCallbackId = _updateCallbackId;
        short initialRemoveCallBackId = _removeCallbackId;

        if (providerName != null) {
            builder = builder.setProviderName(providerName);
        }
        builder = builder.setDatasourceItemAddedCallbackId(dsItemsAddedCallbackId);

        for (int i = 0; i < keyLen; i++) {
            CacheItem item = items[i];
            if (keys[i] == null) {
                throw new NullPointerException("keys");
            }
            long absExp = 0, sldExp = 0;

            try {
                if (ConversionUtil.getAbsoluteExpiration(item.getExpiration()).equals(NCDateTime.getUTCDate(CacheImpl.defaultAbsolute))) {
                    absExp = 1;
                }
                else if (ConversionUtil.getAbsoluteExpiration(item.getExpiration()).equals(NCDateTime.getUTCDate(CacheImpl.defaultAbsoluteLonger))) {
                    absExp = 2;
                }
                else if (ConversionUtil.getAbsoluteExpiration(item.getExpiration()) != CacheImpl.NoAbsoluteExpiration) {
                    //absExp = ticks(items[i].getAbsoluteExpiration());
                    absExp = HelperFxn.getUTCTicks(ConversionUtil.getAbsoluteExpiration(item.getExpiration()));
                }
            } catch (ParseException ignored) {
            }
            if (ConversionUtil.getSlidingExpiration(item.getExpiration()).equals(CacheImpl.DefaultSliding)) {
                sldExp = 1;
            }
            else if (ConversionUtil.getSlidingExpiration(item.getExpiration()).equals(CacheImpl.DefaultSlidingLonger)) {
                sldExp = 2;
            }
            else if (ConversionUtil.getSlidingExpiration(item.getExpiration()) != CacheImpl.NoSlidingExpiration) {
                sldExp = ConversionUtil.getSlidingExpiration(item.getExpiration()).getTotalTicks();
            }
            if (absExp != 0 && sldExp != 0) {
                throw new NullPointerException(
                        "You cannot set both sliding and absolute expirations on the same cached item");
            }

            if (item.getGroup() != null) {
                group = item.getGroup();
            }


            AddCommandProtocol.AddCommand.Builder addBuilder =
                    AddCommandProtocol.AddCommand.newBuilder();

            addBuilder = addBuilder.setKey(keys[i])
                    .setAbsExpiration(absExp)
                    .setSldExpiration(sldExp)
                    .setFlag(BitSetConstants.getBitSetData(CacheItemWrapperInternal.getFlagValue(item)))
                    .setPriority(item.getCacheItemPriority().value())
                    .setIsResync(isResyncExpiredItems)
                    .setCallbackType(_listenerType.getValue());

            //[express]

            //[endexpress]
            if (group != null) {
                addBuilder = addBuilder.setGroup(group);
                if (subGroup != null) {
                    addBuilder = addBuilder.setSubGroup(subGroup);
                }
                if(CacheItemWrapperInternal.getTypeName(item) != null)
                    addBuilder.setGroupType(CacheItemWrapperInternal.getTypeName(item));
            }
            if(_clientId != null){
                addBuilder.setClientID(_clientId);
            }
            //[professional]
            //[express]




//
            if (_removeCallbackId <= 0)
            {
                if (CacheItemWrapperInternal.getCacheItemRemovedListener(item) != null)
                {
                    itemRemoveDataFilter = CacheItemWrapperInternal.getItemRemovedDataFilter(item);
                    short[] callabackIds = new short[0];
                    try {
                        callabackIds = _parent.getEventManager().registerSelectiveEvent(CacheItemWrapperInternal.getCacheItemRemovedListener(item), EnumSet.of(EventType.ItemRemoved), itemRemoveDataFilter, _listenerType);
                    } catch (CacheException e) {
                        throw new CommandException(e.getMessage());
                    }
                    _removeCallbackId = callabackIds[1];
                }
            }
            if (_updateCallbackId <= 0)
            {
                if (CacheItemWrapperInternal.getCacheItemUpdatedListener(item) != null)
                {
                    itemUpdateDataFilter = CacheItemWrapperInternal.getItemUpdatedDataFilter(item);
                    short[] callabackIds = new short[0];
                    try {
                        callabackIds = _parent.getEventManager().registerSelectiveEvent(CacheItemWrapperInternal.getCacheItemUpdatedListener(item), EnumSet.of(EventType.ItemUpdated), itemUpdateDataFilter, _listenerType);
                    } catch (CacheException e) {
                        throw new CommandException(e.getMessage());
                    }
                    _updateCallbackId = callabackIds[0];
                }
            }

            if(itemUpdateDataFilter==null)
            {
                itemUpdateDataFilter=EventDataFilter.None;
            }
            if(itemRemoveDataFilter==null)
            {
                itemRemoveDataFilter=EventDataFilter.None;
            }

            addBuilder.setRemoveCallbackId(_removeCallbackId)
                    .setUpdateCallbackId(_updateCallbackId)
                    .setUpdateDataFilter(itemUpdateDataFilter.getValue())
                    .setRemoveDataFilter(itemRemoveDataFilter.getValue());

            ///Get user data and add to protobuf data array
            UserBinaryObject userBin =null;
            try {
                userBin = UserBinaryObject.createUserBinaryObject((byte[]) items[i].getValue(Object.class));
            }
            catch(OperationFailedException ex){
                throw new CommandException(ex.getMessage());
            }
            List dataList = userBin.getDataList();
            int noOfChunks = dataList.size();

            ///Copy the chunks to protobuf list
            List dataChunks = new ArrayList();
            for (int j = 0; j < noOfChunks; j++) {
                dataChunks.add(ByteString.copyFrom(dataList.get(j)));
            }
            addBuilder = addBuilder.addAllData(dataChunks);

            builder.addAddCommand(addBuilder.build());

            _updateCallbackId = initialUpdateCallbackId ;
            _removeCallbackId = initialRemoveCallBackId ;

        }
        if(this.getIntendedRecipient() != null){
            builder.setIntendedRecipient(this.getIntendedRecipient());
        }
    }

    protected void createCommand() throws CommandException {

        builder.setRequestId(super.getRequestId()) .setReturnVersions(this._returnVersions);
        _commandInstance =builder
                .setClientLastViewId(this.getClientLastViewId())
                .setVersion(Command.VERSION)
                .setMethodOverload(_methodOveload)
                .build();
    }

    public CommandType getCommandType() {
        return CommandType.ADD_BULK;
    }

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

    @Override
    public RequestType getCommandRequestType() {
        return RequestType.KeyBulkWrite;
    }
    @Override
    protected  void serializeCommandInternal(ByteArrayOutputStream stream) throws IOException
    {
        _commandInstance.writeTo(stream);
    }
    @Override
    protected short getCommandHandle()
    {
        return (short)CommandProtocol.Command.Type.ADD_BULK.getNumber();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy