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

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

There is a newer version: 5.3.0
Show newest version
/*
 * AddBulkCommand.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 BulkInsertCommand extends Command {

    private  int _methodOveload;
    private EventDataFilter itemUpdateDataFilter;
    private EventDataFilter itemRemoveDataFilter;
    private  boolean _returnVersions;
    private ListenerType _listenerType;
    private String[] keys;
    private CacheItem[] items;
    private String group = "";
    private String subGroup = "";
    private HashMap queryInfo[];
    private boolean isResyncExpiredItems = false;
    //+ Asad:20110330
    private int dsItemUpdatedtCallbackId;
    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.BulkInsertCommandProtocol.BulkInsertCommand _commandInstance;
    BulkInsertCommandProtocol.BulkInsertCommand.Builder builder = BulkInsertCommandProtocol.BulkInsertCommand.newBuilder();



    /**
     * Creates a new instance of AddBulkCommand
     */
    public BulkInsertCommand(String[] keys, CacheItem[] items,  CacheImpl parent, String providerName, boolean encryption, String cacheId, int methodOverload, String clientId, short updateCallbackId, short removeCallbackId, EventDataFilter updateCallbackDataFilter, EventDataFilter removeCallbackDataFilter, boolean returnVersions, ListenerType listenerType)  throws CommandException {
        super.name = "BulkInsertCommand";
        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 = removeCallbackId;
        this.itemUpdateDataFilter = updateCallbackDataFilter;
        this.itemRemoveDataFilter = removeCallbackDataFilter;
        this._returnVersions = returnVersions;
        this._listenerType = listenerType;

        super.setBulkKeys(keys);
        buildCommand();

    }
    protected void buildCommand() throws CommandException {
        if (this.keys == null) {
            throw new IllegalArgumentException("keys");
        }
        if (this.items == null) {
            throw new IllegalArgumentException("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");
        }

        if (providerName != null) {
            builder = builder.setProviderName(providerName);
        }
        builder = builder.setDatasourceUpdatedCallbackId(dsItemUpdatedtCallbackId)
                .setReturnVersions(_returnVersions);

        int keyLen = keys.length;

        short initialUpdateCallbackId = _updateCallbackId;
        short initialRemoveCallBackId = _removeCallbackId;

        for (int i = 0; i < keyLen; i++) {
            CacheItem item = items[i];
            if (keys[i] == null) {
                throw new IllegalArgumentException("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 = 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();
            }


            InsertCommandProtocol.InsertCommand.Builder insertBuilder =
                    InsertCommandProtocol.InsertCommand.newBuilder();

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

            if(_clientId != null){
                insertBuilder.setClientID(_clientId);
            }
            if (group != null) {
                insertBuilder = insertBuilder.setGroup(group);
                if (subGroup != null) {
                    insertBuilder = insertBuilder.setSubGroup(subGroup);
                }
                if(CacheItemWrapperInternal.getTypeName(item) != null)
                    insertBuilder.setGroupType(CacheItemWrapperInternal.getTypeName(item));
            }






            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;

            insertBuilder.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[]) item.getValue(Object.class));
            } catch (OperationFailedException e) {
                throw new CommandException(e.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)));
            }
            insertBuilder = insertBuilder.addAllData(dataChunks);

            builder.addInsertCommand(insertBuilder.build());

            _updateCallbackId = initialUpdateCallbackId ;
            _removeCallbackId = initialRemoveCallBackId ;

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

    }

    protected void createCommand() throws CommandException {

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

    public CommandType getCommandType() {
        return CommandType.INSERT_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.INSERT_BULK.getNumber();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy