ptupitsyn commented on a change in pull request #8960:
URL: https://github.com/apache/ignite/pull/8960#discussion_r606299495



##########
File path: modules/core/src/main/java/org/apache/ignite/client/ClientCache.java
##########
@@ -703,11 +705,14 @@
     public <K1, V1> ClientCache<K1, V1> withExpirePolicy(ExpiryPolicy 
expirePlc);
 
     /**
-     * Queries cache. Supports {@link ScanQuery} and {@link SqlFieldsQuery}.
+     * Queries cache. Supports {@link ScanQuery}, {@link SqlFieldsQuery} and 
{@link ContinuousQuery}.
+     * <p>
+     * NOTE: For continuous query listeners there is no failover in case of 
client channel failure, this event should
+     * be handled on the user's side. Listeners will be notified about client 
disconnect event if they implement
+     * {@link ClientChannelDisconnectListener} interface.

Review comment:
       As noted on the [dev 
list](http://apache-ignite-developers.2346864.n4.nabble.com/DISCUSSION-Java-thin-client-Continuous-Queries-public-API-td52114.html),
 maybe we can provide an overload instead?
    ```java
   query(ContinuousQuery, ClientChannelDisconnectListener)
   ```

##########
File path: modules/core/src/main/java/org/apache/ignite/client/ClientCache.java
##########
@@ -718,4 +723,27 @@
      * @return Cursor.
      */
     public FieldsQueryCursor<List<?>> query(SqlFieldsQuery qry);
+
+    /**
+     * Registers a {@link CacheEntryListener}. The supplied {@link 
CacheEntryListenerConfiguration} is used to
+     * instantiate a listener and apply it to those events specified in the 
configuration.
+     * <p>
+     * NOTE: There is no failover in case of client channel failure, this 
event should be handled on the user's side.
+     * Listeners will be notified about client disconnect event if they 
implement {@link ClientChannelDisconnectListener}
+     * interface.
+     *
+     * @param cacheEntryListenerConfiguration a factory and related 
configuration for creating the listener.
+     * @throws IllegalArgumentException is the same 
CacheEntryListenerConfiguration is used more than once or
+     *          if some unsupported by thin client properties are set.
+     * @see CacheEntryListener
+     */
+    public void registerCacheEntryListener(CacheEntryListenerConfiguration<K, 
V> cacheEntryListenerConfiguration);

Review comment:
       Those 2 methods seem to be redundant - listener can be configured 
through `ContinuousQuery` class. In Thick API those are dictated by JCache, 
which we don't have here.

##########
File path: 
modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientCacheEntryListenerHandler.java
##########
@@ -0,0 +1,266 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.ignite.internal.client.thin;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import javax.cache.Cache;
+import javax.cache.configuration.Factory;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryEventFilter;
+import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
+import org.apache.ignite.client.ClientChannelDisconnectListener;
+import org.apache.ignite.client.ClientException;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.apache.ignite.internal.binary.streams.BinaryByteBufferInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryOutputStream;
+import org.apache.ignite.internal.util.typedef.T2;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ *

Review comment:
       Missing javadoc

##########
File path: 
modules/core/src/main/java/org/apache/ignite/client/ClientChannelDisconnectListener.java
##########
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.ignite.client;
+
+import javax.cache.configuration.CacheEntryListenerConfiguration;
+import org.apache.ignite.cache.query.ContinuousQuery;
+
+/**
+ * This interface can be implemented by {@link ContinuousQuery} local 
listeners or by cache entry listeners
+ * registered via {@link 
ClientCache#registerCacheEntryListener(CacheEntryListenerConfiguration)} to get 
notification
+ * about client channel disconnected event.
+ */
+public interface ClientChannelDisconnectListener {

Review comment:
       `ClientDisconnectListener` seems to be a better name - `channel` sounds 
like an implementation detail.

##########
File path: 
modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientCacheEntryListenerHandler.java
##########
@@ -0,0 +1,266 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.ignite.internal.client.thin;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import javax.cache.Cache;
+import javax.cache.configuration.Factory;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryEventFilter;
+import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
+import org.apache.ignite.client.ClientChannelDisconnectListener;
+import org.apache.ignite.client.ClientException;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.apache.ignite.internal.binary.streams.BinaryByteBufferInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryOutputStream;
+import org.apache.ignite.internal.util.typedef.T2;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ *
+ */
+public class ClientCacheEntryListenerHandler<K, V> implements 
NotificationListener, AutoCloseable {
+    /** "Keep binary" flag mask. */
+    private static final byte KEEP_BINARY_FLAG_MASK = 0x01;
+
+    /** */
+    private final Cache<K, V> jCacheAdapter;
+
+    /** */
+    private final ReliableChannel ch;
+
+    /** */
+    private final boolean keepBinary;
+
+    /** */
+    private final ClientUtils utils;
+
+    /** */
+    private final Consumer<ClientChannel> chCloseLsnr = this::onChannelClosed;
+
+    /** */
+    private volatile CacheEntryUpdatedListener<K, V> locLsnr;
+
+    /** */
+    private volatile ClientChannel clientCh;
+
+    /** */
+    private volatile long rsrcId;
+
+    /** */
+    ClientCacheEntryListenerHandler(
+        Cache<K, V> jCacheAdapter,
+        ReliableChannel ch,
+        ClientBinaryMarshaller marsh,
+        boolean keepBinary
+    ) {
+        this.jCacheAdapter = jCacheAdapter;
+        this.ch = ch;
+        this.keepBinary = keepBinary;
+        utils = new ClientUtils(marsh);
+    }
+
+    /**
+     * Send request to the server and start
+     */
+    public synchronized void startListen(
+        CacheEntryUpdatedListener<K, V> locLsnr,
+        Factory<? extends CacheEntryEventFilter<? super K, ? super V>> 
rmtFilterFactory,
+        int pageSize,
+        long timeInterval,
+        boolean includeExpired
+    ) {
+        if (clientCh != null)
+            throw new IllegalStateException("Listener was already started");
+
+        this.locLsnr = locLsnr;
+
+        Consumer<PayloadOutputChannel> qryWriter = payloadCh -> {
+            BinaryOutputStream out = payloadCh.out();
+
+            out.writeInt(ClientUtils.cacheId(jCacheAdapter.getName()));
+            out.writeByte(keepBinary ? KEEP_BINARY_FLAG_MASK : 0);
+            out.writeInt(pageSize);
+            out.writeLong(timeInterval);
+            out.writeBoolean(includeExpired);
+
+            if (rmtFilterFactory == null)
+                out.writeByte(GridBinaryMarshaller.NULL);
+            else {
+                utils.writeObject(out, rmtFilterFactory);
+                out.writeByte((byte)1); // Java platform
+            }
+        };
+
+        ch.addChannelCloseListener(chCloseLsnr);
+
+        try {
+            T2<ClientChannel, Long> params = ch.service(
+                ClientOperation.QUERY_CONTINUOUS,
+                qryWriter,
+                res -> new T2<>(res.clientChannel(), res.in().readLong())
+            );
+
+            clientCh = params.get1();
+            rsrcId = params.get2();
+        }
+        catch (ClientError e) {
+            ch.removeChannelCloseListener(chCloseLsnr);
+
+            throw new ClientException(e);
+        }
+
+        clientCh.addNotificationListener(this);
+    }
+
+    /**
+     * @param ch Channel.
+     */
+    private void onChannelClosed(ClientChannel ch) {
+        if (ch == clientCh) {
+            if (locLsnr instanceof ClientChannelDisconnectListener)
+                ((ClientChannelDisconnectListener)locLsnr).onDisconnected();
+
+            U.closeQuiet(this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void acceptNotification(
+            ClientChannel ch,
+            ClientOperation op,
+            long rsrcId,
+            ByteBuffer payload,
+            Exception err
+    ) {
+        if (op == ClientOperation.QUERY_CONTINUOUS_EVENT_NOTIFICATION && 
rsrcId == this.rsrcId) {

Review comment:
       nit: Invert condition to reduce nesting

##########
File path: 
modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientCacheEntryListenerHandler.java
##########
@@ -0,0 +1,266 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.ignite.internal.client.thin;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import javax.cache.Cache;
+import javax.cache.configuration.Factory;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryEventFilter;
+import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
+import org.apache.ignite.client.ClientChannelDisconnectListener;
+import org.apache.ignite.client.ClientException;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.apache.ignite.internal.binary.streams.BinaryByteBufferInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryOutputStream;
+import org.apache.ignite.internal.util.typedef.T2;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ *
+ */
+public class ClientCacheEntryListenerHandler<K, V> implements 
NotificationListener, AutoCloseable {
+    /** "Keep binary" flag mask. */
+    private static final byte KEEP_BINARY_FLAG_MASK = 0x01;
+
+    /** */
+    private final Cache<K, V> jCacheAdapter;
+
+    /** */
+    private final ReliableChannel ch;
+
+    /** */
+    private final boolean keepBinary;
+
+    /** */
+    private final ClientUtils utils;
+
+    /** */
+    private final Consumer<ClientChannel> chCloseLsnr = this::onChannelClosed;
+
+    /** */
+    private volatile CacheEntryUpdatedListener<K, V> locLsnr;
+
+    /** */
+    private volatile ClientChannel clientCh;
+
+    /** */
+    private volatile long rsrcId;
+
+    /** */
+    ClientCacheEntryListenerHandler(
+        Cache<K, V> jCacheAdapter,
+        ReliableChannel ch,
+        ClientBinaryMarshaller marsh,
+        boolean keepBinary
+    ) {
+        this.jCacheAdapter = jCacheAdapter;
+        this.ch = ch;
+        this.keepBinary = keepBinary;
+        utils = new ClientUtils(marsh);
+    }
+
+    /**
+     * Send request to the server and start
+     */
+    public synchronized void startListen(
+        CacheEntryUpdatedListener<K, V> locLsnr,
+        Factory<? extends CacheEntryEventFilter<? super K, ? super V>> 
rmtFilterFactory,
+        int pageSize,
+        long timeInterval,
+        boolean includeExpired
+    ) {
+        if (clientCh != null)
+            throw new IllegalStateException("Listener was already started");
+
+        this.locLsnr = locLsnr;
+
+        Consumer<PayloadOutputChannel> qryWriter = payloadCh -> {
+            BinaryOutputStream out = payloadCh.out();
+
+            out.writeInt(ClientUtils.cacheId(jCacheAdapter.getName()));
+            out.writeByte(keepBinary ? KEEP_BINARY_FLAG_MASK : 0);
+            out.writeInt(pageSize);
+            out.writeLong(timeInterval);
+            out.writeBoolean(includeExpired);
+
+            if (rmtFilterFactory == null)
+                out.writeByte(GridBinaryMarshaller.NULL);
+            else {
+                utils.writeObject(out, rmtFilterFactory);
+                out.writeByte((byte)1); // Java platform

Review comment:
       `ClientPlatform.JAVA`

##########
File path: 
modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientCacheEntryListenerHandler.java
##########
@@ -0,0 +1,266 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.ignite.internal.client.thin;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import javax.cache.Cache;
+import javax.cache.configuration.Factory;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryEventFilter;
+import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
+import org.apache.ignite.client.ClientChannelDisconnectListener;
+import org.apache.ignite.client.ClientException;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.apache.ignite.internal.binary.streams.BinaryByteBufferInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryOutputStream;
+import org.apache.ignite.internal.util.typedef.T2;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ *
+ */
+public class ClientCacheEntryListenerHandler<K, V> implements 
NotificationListener, AutoCloseable {
+    /** "Keep binary" flag mask. */
+    private static final byte KEEP_BINARY_FLAG_MASK = 0x01;
+
+    /** */
+    private final Cache<K, V> jCacheAdapter;
+
+    /** */
+    private final ReliableChannel ch;
+
+    /** */
+    private final boolean keepBinary;
+
+    /** */
+    private final ClientUtils utils;
+
+    /** */
+    private final Consumer<ClientChannel> chCloseLsnr = this::onChannelClosed;
+
+    /** */
+    private volatile CacheEntryUpdatedListener<K, V> locLsnr;
+
+    /** */
+    private volatile ClientChannel clientCh;
+
+    /** */
+    private volatile long rsrcId;
+
+    /** */
+    ClientCacheEntryListenerHandler(
+        Cache<K, V> jCacheAdapter,
+        ReliableChannel ch,
+        ClientBinaryMarshaller marsh,
+        boolean keepBinary
+    ) {
+        this.jCacheAdapter = jCacheAdapter;
+        this.ch = ch;
+        this.keepBinary = keepBinary;
+        utils = new ClientUtils(marsh);
+    }
+
+    /**
+     * Send request to the server and start
+     */
+    public synchronized void startListen(
+        CacheEntryUpdatedListener<K, V> locLsnr,
+        Factory<? extends CacheEntryEventFilter<? super K, ? super V>> 
rmtFilterFactory,
+        int pageSize,
+        long timeInterval,
+        boolean includeExpired
+    ) {
+        if (clientCh != null)
+            throw new IllegalStateException("Listener was already started");
+
+        this.locLsnr = locLsnr;
+
+        Consumer<PayloadOutputChannel> qryWriter = payloadCh -> {
+            BinaryOutputStream out = payloadCh.out();
+
+            out.writeInt(ClientUtils.cacheId(jCacheAdapter.getName()));
+            out.writeByte(keepBinary ? KEEP_BINARY_FLAG_MASK : 0);
+            out.writeInt(pageSize);
+            out.writeLong(timeInterval);
+            out.writeBoolean(includeExpired);
+
+            if (rmtFilterFactory == null)
+                out.writeByte(GridBinaryMarshaller.NULL);
+            else {
+                utils.writeObject(out, rmtFilterFactory);
+                out.writeByte((byte)1); // Java platform
+            }
+        };
+
+        ch.addChannelCloseListener(chCloseLsnr);
+
+        try {
+            T2<ClientChannel, Long> params = ch.service(
+                ClientOperation.QUERY_CONTINUOUS,
+                qryWriter,
+                res -> new T2<>(res.clientChannel(), res.in().readLong())
+            );
+
+            clientCh = params.get1();
+            rsrcId = params.get2();
+        }
+        catch (ClientError e) {
+            ch.removeChannelCloseListener(chCloseLsnr);
+
+            throw new ClientException(e);
+        }
+
+        clientCh.addNotificationListener(this);
+    }
+
+    /**
+     * @param ch Channel.
+     */
+    private void onChannelClosed(ClientChannel ch) {
+        if (ch == clientCh) {
+            if (locLsnr instanceof ClientChannelDisconnectListener)
+                ((ClientChannelDisconnectListener)locLsnr).onDisconnected();
+
+            U.closeQuiet(this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void acceptNotification(
+            ClientChannel ch,
+            ClientOperation op,
+            long rsrcId,
+            ByteBuffer payload,
+            Exception err
+    ) {
+        if (op == ClientOperation.QUERY_CONTINUOUS_EVENT_NOTIFICATION && 
rsrcId == this.rsrcId) {
+            if (err == null && payload != null) {

Review comment:
       Combine with the previous condition?

##########
File path: 
modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientCacheEntryListenerHandler.java
##########
@@ -0,0 +1,266 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.ignite.internal.client.thin;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import javax.cache.Cache;
+import javax.cache.configuration.Factory;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryEventFilter;
+import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
+import org.apache.ignite.client.ClientChannelDisconnectListener;
+import org.apache.ignite.client.ClientException;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.apache.ignite.internal.binary.streams.BinaryByteBufferInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryOutputStream;
+import org.apache.ignite.internal.util.typedef.T2;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ *
+ */
+public class ClientCacheEntryListenerHandler<K, V> implements 
NotificationListener, AutoCloseable {
+    /** "Keep binary" flag mask. */
+    private static final byte KEEP_BINARY_FLAG_MASK = 0x01;
+
+    /** */
+    private final Cache<K, V> jCacheAdapter;
+
+    /** */
+    private final ReliableChannel ch;
+
+    /** */
+    private final boolean keepBinary;
+
+    /** */
+    private final ClientUtils utils;
+
+    /** */
+    private final Consumer<ClientChannel> chCloseLsnr = this::onChannelClosed;
+
+    /** */
+    private volatile CacheEntryUpdatedListener<K, V> locLsnr;
+
+    /** */
+    private volatile ClientChannel clientCh;
+
+    /** */
+    private volatile long rsrcId;
+
+    /** */
+    ClientCacheEntryListenerHandler(
+        Cache<K, V> jCacheAdapter,
+        ReliableChannel ch,
+        ClientBinaryMarshaller marsh,
+        boolean keepBinary
+    ) {
+        this.jCacheAdapter = jCacheAdapter;
+        this.ch = ch;
+        this.keepBinary = keepBinary;
+        utils = new ClientUtils(marsh);
+    }
+
+    /**
+     * Send request to the server and start
+     */
+    public synchronized void startListen(
+        CacheEntryUpdatedListener<K, V> locLsnr,
+        Factory<? extends CacheEntryEventFilter<? super K, ? super V>> 
rmtFilterFactory,
+        int pageSize,
+        long timeInterval,
+        boolean includeExpired
+    ) {
+        if (clientCh != null)
+            throw new IllegalStateException("Listener was already started");
+
+        this.locLsnr = locLsnr;
+
+        Consumer<PayloadOutputChannel> qryWriter = payloadCh -> {
+            BinaryOutputStream out = payloadCh.out();
+
+            out.writeInt(ClientUtils.cacheId(jCacheAdapter.getName()));
+            out.writeByte(keepBinary ? KEEP_BINARY_FLAG_MASK : 0);
+            out.writeInt(pageSize);
+            out.writeLong(timeInterval);
+            out.writeBoolean(includeExpired);
+
+            if (rmtFilterFactory == null)
+                out.writeByte(GridBinaryMarshaller.NULL);
+            else {
+                utils.writeObject(out, rmtFilterFactory);
+                out.writeByte((byte)1); // Java platform
+            }
+        };
+
+        ch.addChannelCloseListener(chCloseLsnr);
+
+        try {
+            T2<ClientChannel, Long> params = ch.service(
+                ClientOperation.QUERY_CONTINUOUS,
+                qryWriter,
+                res -> new T2<>(res.clientChannel(), res.in().readLong())
+            );
+
+            clientCh = params.get1();
+            rsrcId = params.get2();
+        }
+        catch (ClientError e) {
+            ch.removeChannelCloseListener(chCloseLsnr);
+
+            throw new ClientException(e);
+        }
+
+        clientCh.addNotificationListener(this);
+    }
+
+    /**
+     * @param ch Channel.
+     */
+    private void onChannelClosed(ClientChannel ch) {
+        if (ch == clientCh) {
+            if (locLsnr instanceof ClientChannelDisconnectListener)
+                ((ClientChannelDisconnectListener)locLsnr).onDisconnected();
+
+            U.closeQuiet(this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void acceptNotification(
+            ClientChannel ch,
+            ClientOperation op,
+            long rsrcId,
+            ByteBuffer payload,
+            Exception err
+    ) {
+        if (op == ClientOperation.QUERY_CONTINUOUS_EVENT_NOTIFICATION && 
rsrcId == this.rsrcId) {
+            if (err == null && payload != null) {
+                BinaryInputStream in = 
BinaryByteBufferInputStream.create(payload);
+
+                int cnt = in.readInt();
+
+                List<CacheEntryEvent<? extends K, ? extends V>> evts = new 
ArrayList<>(cnt);
+
+                for (int i = 0; i < cnt; i++) {
+                    K key = utils.readObject(in, keepBinary);
+                    V oldVal = utils.readObject(in, keepBinary);
+                    V val = utils.readObject(in, keepBinary);
+                    byte evtTypeByte = in.readByte();
+
+                    EventType evtType = eventType(evtTypeByte);
+
+                    if (evtType != null) // Skip unknown event types.
+                        evts.add(new CacheEntryEventImpl<>(jCacheAdapter, 
evtType, key, oldVal, val));
+                }
+
+                locLsnr.onUpdated(evts);
+            }
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public synchronized void close() {
+        ch.removeChannelCloseListener(chCloseLsnr);
+
+        if (clientCh != null) {
+            clientCh.removeNotificationListener(this);

Review comment:
       Even though we never set `clientCh` from non-null to null, and this code 
seems to be safe right now,
   the field is still marked `volatile`, so this use-after-nullcheck looks 
suspicious.
   
   To reduce cognitive load, copy `clientCh` to a temp variable, and then check 
for null.

##########
File path: 
modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientCacheEntryListenersRegistry.java
##########
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.ignite.internal.client.thin;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.cache.configuration.CacheEntryListenerConfiguration;
+
+/**
+ * Per-cache cache entry listeners registry. Listeners can't be stored inside 
ClientCache instance, since there can be
+ * several such instances per one cache.
+ */
+public class ClientCacheEntryListenersRegistry {

Review comment:
       I think we should do the following:
   * Refactor existing `TcpClientChannel.notificationLsnrs` to a `Map<Long, 
NotificationListener>`
   * Instead of iterating over all `notificationLsnrs` and checking the id in 
every listener, get the listener by id from map and invoke it without inner 
checks
   * Use this mechanism for continuous query notifications, avoid creating a 
new registry
   
   This approach seems to work fine in .NET thin client.

##########
File path: 
modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientCacheEntryListenerHandler.java
##########
@@ -0,0 +1,266 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.ignite.internal.client.thin;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import javax.cache.Cache;
+import javax.cache.configuration.Factory;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryEventFilter;
+import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
+import org.apache.ignite.client.ClientChannelDisconnectListener;
+import org.apache.ignite.client.ClientException;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.apache.ignite.internal.binary.streams.BinaryByteBufferInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryOutputStream;
+import org.apache.ignite.internal.util.typedef.T2;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ *
+ */
+public class ClientCacheEntryListenerHandler<K, V> implements 
NotificationListener, AutoCloseable {
+    /** "Keep binary" flag mask. */
+    private static final byte KEEP_BINARY_FLAG_MASK = 0x01;
+
+    /** */
+    private final Cache<K, V> jCacheAdapter;
+
+    /** */
+    private final ReliableChannel ch;
+
+    /** */
+    private final boolean keepBinary;
+
+    /** */
+    private final ClientUtils utils;
+
+    /** */
+    private final Consumer<ClientChannel> chCloseLsnr = this::onChannelClosed;
+
+    /** */
+    private volatile CacheEntryUpdatedListener<K, V> locLsnr;
+
+    /** */
+    private volatile ClientChannel clientCh;
+
+    /** */
+    private volatile long rsrcId;
+
+    /** */
+    ClientCacheEntryListenerHandler(
+        Cache<K, V> jCacheAdapter,
+        ReliableChannel ch,
+        ClientBinaryMarshaller marsh,
+        boolean keepBinary
+    ) {
+        this.jCacheAdapter = jCacheAdapter;
+        this.ch = ch;
+        this.keepBinary = keepBinary;
+        utils = new ClientUtils(marsh);
+    }
+
+    /**
+     * Send request to the server and start
+     */
+    public synchronized void startListen(
+        CacheEntryUpdatedListener<K, V> locLsnr,
+        Factory<? extends CacheEntryEventFilter<? super K, ? super V>> 
rmtFilterFactory,
+        int pageSize,
+        long timeInterval,
+        boolean includeExpired
+    ) {
+        if (clientCh != null)
+            throw new IllegalStateException("Listener was already started");
+
+        this.locLsnr = locLsnr;
+
+        Consumer<PayloadOutputChannel> qryWriter = payloadCh -> {
+            BinaryOutputStream out = payloadCh.out();
+
+            out.writeInt(ClientUtils.cacheId(jCacheAdapter.getName()));
+            out.writeByte(keepBinary ? KEEP_BINARY_FLAG_MASK : 0);
+            out.writeInt(pageSize);
+            out.writeLong(timeInterval);
+            out.writeBoolean(includeExpired);
+
+            if (rmtFilterFactory == null)
+                out.writeByte(GridBinaryMarshaller.NULL);
+            else {
+                utils.writeObject(out, rmtFilterFactory);
+                out.writeByte((byte)1); // Java platform
+            }
+        };
+
+        ch.addChannelCloseListener(chCloseLsnr);
+
+        try {
+            T2<ClientChannel, Long> params = ch.service(
+                ClientOperation.QUERY_CONTINUOUS,
+                qryWriter,
+                res -> new T2<>(res.clientChannel(), res.in().readLong())
+            );
+
+            clientCh = params.get1();
+            rsrcId = params.get2();
+        }
+        catch (ClientError e) {
+            ch.removeChannelCloseListener(chCloseLsnr);
+
+            throw new ClientException(e);
+        }
+
+        clientCh.addNotificationListener(this);
+    }
+
+    /**
+     * @param ch Channel.
+     */
+    private void onChannelClosed(ClientChannel ch) {
+        if (ch == clientCh) {
+            if (locLsnr instanceof ClientChannelDisconnectListener)
+                ((ClientChannelDisconnectListener)locLsnr).onDisconnected();
+
+            U.closeQuiet(this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void acceptNotification(
+            ClientChannel ch,
+            ClientOperation op,
+            long rsrcId,
+            ByteBuffer payload,
+            Exception err
+    ) {
+        if (op == ClientOperation.QUERY_CONTINUOUS_EVENT_NOTIFICATION && 
rsrcId == this.rsrcId) {
+            if (err == null && payload != null) {
+                BinaryInputStream in = 
BinaryByteBufferInputStream.create(payload);
+
+                int cnt = in.readInt();
+
+                List<CacheEntryEvent<? extends K, ? extends V>> evts = new 
ArrayList<>(cnt);
+
+                for (int i = 0; i < cnt; i++) {
+                    K key = utils.readObject(in, keepBinary);
+                    V oldVal = utils.readObject(in, keepBinary);
+                    V val = utils.readObject(in, keepBinary);
+                    byte evtTypeByte = in.readByte();
+
+                    EventType evtType = eventType(evtTypeByte);
+
+                    if (evtType != null) // Skip unknown event types.
+                        evts.add(new CacheEntryEventImpl<>(jCacheAdapter, 
evtType, key, oldVal, val));
+                }
+
+                locLsnr.onUpdated(evts);
+            }
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public synchronized void close() {
+        ch.removeChannelCloseListener(chCloseLsnr);
+
+        if (clientCh != null) {
+            clientCh.removeNotificationListener(this);
+
+            if (!clientCh.closed())
+                clientCh.service(ClientOperation.RESOURCE_CLOSE, ch -> 
ch.out().writeLong(rsrcId), null);
+        }
+    }
+
+    /**
+     * Client channel.
+     */
+    public ClientChannel clientChannel() {
+        return clientCh;
+    }
+
+    /** */
+    private EventType eventType(byte evtTypeByte) {
+        switch (evtTypeByte) {
+            case 0: return EventType.CREATED;
+            case 1: return EventType.UPDATED;
+            case 2: return EventType.REMOVED;
+            case 3: return EventType.EXPIRED;
+            default: return null;

Review comment:
       Should we log an error instead? Other event types are not valid.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to