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

com.hazelcast.client.proxy.ClientQueueProxy Maven / Gradle / Ivy

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

package com.hazelcast.client.proxy;

import com.hazelcast.client.impl.client.BaseClientRemoveListenerRequest;
import com.hazelcast.client.impl.client.ClientRequest;
import com.hazelcast.client.spi.ClientProxy;
import com.hazelcast.client.spi.EventHandler;
import com.hazelcast.collection.common.DataAwareItemEvent;
import com.hazelcast.collection.impl.queue.QueueIterator;
import com.hazelcast.collection.impl.queue.client.AddAllRequest;
import com.hazelcast.collection.impl.queue.client.AddListenerRequest;
import com.hazelcast.collection.impl.queue.client.ClearRequest;
import com.hazelcast.collection.impl.queue.client.CompareAndRemoveRequest;
import com.hazelcast.collection.impl.queue.client.ContainsRequest;
import com.hazelcast.collection.impl.queue.client.DrainRequest;
import com.hazelcast.collection.impl.queue.client.IsEmptyRequest;
import com.hazelcast.collection.impl.queue.client.IteratorRequest;
import com.hazelcast.collection.impl.queue.client.OfferRequest;
import com.hazelcast.collection.impl.queue.client.PeekRequest;
import com.hazelcast.collection.impl.queue.client.PollRequest;
import com.hazelcast.collection.impl.queue.client.RemainingCapacityRequest;
import com.hazelcast.collection.impl.queue.client.RemoveListenerRequest;
import com.hazelcast.collection.impl.queue.client.RemoveRequest;
import com.hazelcast.collection.impl.queue.client.SizeRequest;
import com.hazelcast.core.HazelcastException;
import com.hazelcast.core.IQueue;
import com.hazelcast.core.ItemEvent;
import com.hazelcast.core.ItemEventType;
import com.hazelcast.core.ItemListener;
import com.hazelcast.core.Member;
import com.hazelcast.internal.serialization.SerializationService;
import com.hazelcast.monitor.LocalQueueStats;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.impl.PortableCollection;
import com.hazelcast.spi.impl.PortableItemEvent;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;

import static com.hazelcast.util.Preconditions.checkNotNull;

/**
 * @author ali 5/19/13
 */
public final class ClientQueueProxy extends ClientProxy implements IQueue {

    private final String name;

    public ClientQueueProxy(String serviceName, String name) {
        super(serviceName, name);
        this.name = name;
    }

    public String addItemListener(final ItemListener listener, final boolean includeValue) {
        final AddListenerRequest addRequest = new AddListenerRequest(name, includeValue);
        EventHandler eventHandler = new EventHandler() {
            public void handle(PortableItemEvent portableItemEvent) {
                SerializationService ss = getContext().getSerializationService();
                Member member = getContext().getClusterService().getMember(portableItemEvent.getUuid());
                Data item = portableItemEvent.getItem();
                ItemEvent itemEvent =
                        new DataAwareItemEvent(name, portableItemEvent.getEventType(), item, member, ss);
                if (portableItemEvent.getEventType() == ItemEventType.ADDED) {
                    listener.itemAdded(itemEvent);
                } else {
                    listener.itemRemoved(itemEvent);
                }
            }

            @Override
            public void beforeListenerRegister() {
            }

            @Override
            public void onListenerRegister() {

            }
        };
        BaseClientRemoveListenerRequest removeRequest =
                new RemoveListenerRequest(getName());
        return registerListener(addRequest, removeRequest, eventHandler);
    }

    public boolean removeItemListener(String registrationId) {
        return deregisterListener(registrationId);
    }

    public LocalQueueStats getLocalQueueStats() {
        throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
    }

    public boolean add(E e) {
        if (offer(e)) {
            return true;
        }
        throw new IllegalStateException("Queue is full!");
    }

    /**
     * It is advised to use this method in a try-catch block to take the offer operation
     * full lifecycle control, in a "lost node" scenario you can not be sure
     * offer is succeeded or not so you may want to retry.
     *
     * @param e the element to add
     * @return true if the element was added to this queue.
     * false if there is not enough capacity to insert the element.
     * @throws HazelcastException if client loses the connected node.
     */
    public boolean offer(E e) {
        try {
            return offer(e, 0, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            return false;
        }
    }

    public void put(E e) throws InterruptedException {
        offer(e, -1, TimeUnit.MILLISECONDS);
    }

    public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
        checkNotNull(e, "item can't be null");

        Data data = getContext().getSerializationService().toData(e);
        OfferRequest request = new OfferRequest(name, unit.toMillis(timeout), data);
        final Boolean result = invokeInterruptibly(request);
        return result;
    }

    public E take() throws InterruptedException {
        return poll(-1, TimeUnit.MILLISECONDS);
    }

    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        PollRequest request = new PollRequest(name, unit.toMillis(timeout));
        return invokeInterruptibly(request);
    }

    public int remainingCapacity() {
        RemainingCapacityRequest request = new RemainingCapacityRequest(name);
        Integer result = invoke(request);
        return result;
    }

    public boolean remove(Object o) {
        Data data = getContext().getSerializationService().toData(o);
        RemoveRequest request = new RemoveRequest(name, data);
        Boolean result = invoke(request);
        return result;
    }

    public boolean contains(Object o) {
        final Collection list = new ArrayList(1);
        list.add(getContext().getSerializationService().toData(o));
        ContainsRequest request = new ContainsRequest(name, list);
        Boolean result = invoke(request);
        return result;
    }

    public int drainTo(Collection objects) {
        return drainTo(objects, -1);
    }

    public int drainTo(Collection c, int maxElements) {
        DrainRequest request = new DrainRequest(name, maxElements);
        PortableCollection result = invoke(request);
        Collection coll = result.getCollection();
        for (Data data : coll) {
            E e = getContext().getSerializationService().toObject(data);
            c.add(e);
        }
        return coll.size();
    }

    public E remove() {
        final E res = poll();
        if (res == null) {
            throw new NoSuchElementException("Queue is empty!");
        }
        return res;
    }

    public E poll() {
        try {
            return poll(0, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return null;
        }
    }

    public E element() {
        final E res = peek();
        if (res == null) {
            throw new NoSuchElementException("Queue is empty!");
        }
        return res;
    }

    public E peek() {
        PeekRequest request = new PeekRequest(name);
        return invoke(request);
    }

    public int size() {
        SizeRequest request = new SizeRequest(name);
        Integer result = invoke(request);
        return result;
    }

    public boolean isEmpty() {
        IsEmptyRequest request = new IsEmptyRequest(name);
        Boolean result = invoke(request);
        return result;
    }

    public Iterator iterator() {
        IteratorRequest request = new IteratorRequest(name);
        PortableCollection result = invoke(request);
        Collection coll = result.getCollection();
        return new QueueIterator(coll.iterator(), getContext().getSerializationService(), false);
    }

    public Object[] toArray() {
        IteratorRequest request = new IteratorRequest(name);
        PortableCollection result = invoke(request);
        Collection coll = result.getCollection();
        int i = 0;
        Object[] array = new Object[coll.size()];
        for (Data data : coll) {
            array[i++] = getContext().getSerializationService().toObject(data);
        }
        return array;
    }

    public  T[] toArray(T[] ts) {
        IteratorRequest request = new IteratorRequest(name);
        PortableCollection result = invoke(request);
        Collection coll = result.getCollection();
        int size = coll.size();
        if (ts.length < size) {
            ts = (T[]) java.lang.reflect.Array.newInstance(ts.getClass().getComponentType(), size);
        }
        int i = 0;
        for (Data data : coll) {
            ts[i++] = (T) getContext().getSerializationService().toObject(data);
        }
        return ts;
    }

    public boolean containsAll(Collection c) {
        List list = getDataList(c);
        ContainsRequest request = new ContainsRequest(name, list);
        Boolean result = invoke(request);
        return result;
    }

    public boolean addAll(Collection c) {
        AddAllRequest request = new AddAllRequest(name, getDataList(c));
        Boolean result = invoke(request);
        return result;
    }

    public boolean removeAll(Collection c) {
        CompareAndRemoveRequest request = new CompareAndRemoveRequest(name, getDataList(c), false);
        Boolean result = invoke(request);
        return result;
    }

    public boolean retainAll(Collection c) {
        CompareAndRemoveRequest request = new CompareAndRemoveRequest(name, getDataList(c), true);
        Boolean result = invoke(request);
        return result;
    }

    public void clear() {
        ClearRequest request = new ClearRequest(name);
        invoke(request);
    }

    protected  T invoke(ClientRequest req) {
        return super.invoke(req, getPartitionKey());
    }

    protected  T invokeInterruptibly(ClientRequest req) throws InterruptedException {
        return super.invokeInterruptibly(req, getPartitionKey());
    }

    private List getDataList(Collection objects) {
        List dataList = new ArrayList(objects.size());
        for (Object o : objects) {
            dataList.add(getContext().getSerializationService().toData(o));
        }
        return dataList;
    }

    @Override
    public String toString() {
        return "IQueue{" + "name='" + getName() + '\'' + '}';
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy