Search in sources :

Example 1 with ClientException

use of org.apache.ignite.client.ClientException in project ignite by apache.

the class ClientPutGetExample method main.

/**
 * Entry point.
 *
 * @param args Command line arguments.
 */
public static void main(String[] args) {
    ClientConfiguration cfg = new ClientConfiguration().setAddresses("127.0.0.1:10800");
    try (IgniteClient igniteClient = Ignition.startClient(cfg)) {
        System.out.println();
        System.out.println(">>> Thin client put-get example started.");
        final String CACHE_NAME = "put-get-example";
        ClientCache<Integer, Address> cache = igniteClient.getOrCreateCache(CACHE_NAME);
        System.out.format(">>> Created cache [%s].\n", CACHE_NAME);
        Integer key = 1;
        Address val = new Address("1545 Jackson Street", 94612);
        cache.put(key, val);
        System.out.format(">>> Saved [%s] in the cache.\n", val);
        Address cachedVal = cache.get(key);
        System.out.format(">>> Loaded [%s] from the cache.\n", cachedVal);
    } catch (ClientException e) {
        System.err.println(e.getMessage());
    }
}
Also used : IgniteClient(org.apache.ignite.client.IgniteClient) Address(org.apache.ignite.examples.model.Address) ClientException(org.apache.ignite.client.ClientException) ClientConfiguration(org.apache.ignite.configuration.ClientConfiguration)

Example 2 with ClientException

use of org.apache.ignite.client.ClientException in project ignite by apache.

the class ReliableChannel method handleServiceAsync.

/**
 * Handles serviceAsync results and retries as needed.
 */
private <T> void handleServiceAsync(final CompletableFuture<T> fut, ClientOperation op, Consumer<PayloadOutputChannel> payloadWriter, Function<PayloadInputChannel, T> payloadReader, int attemptsLimit, ClientConnectionException failure) {
    ClientChannel ch;
    // Workaround to store used attempts value within lambda body.
    int[] attemptsCnt = new int[1];
    try {
        ch = applyOnDefaultChannel(channel -> channel, null, attemptsLimit, v -> attemptsCnt[0] = v);
    } catch (Throwable ex) {
        if (failure != null) {
            failure.addSuppressed(ex);
            fut.completeExceptionally(failure);
            return;
        }
        fut.completeExceptionally(ex);
        return;
    }
    ch.serviceAsync(op, payloadWriter, payloadReader).handle((res, err) -> {
        if (err == null) {
            fut.complete(res);
            return null;
        }
        ClientConnectionException failure0 = failure;
        if (err instanceof ClientConnectionException) {
            try {
                // Will try to reinit channels if topology changed.
                onChannelFailure(ch);
            } catch (Throwable ex) {
                fut.completeExceptionally(ex);
                return null;
            }
            if (failure0 == null)
                failure0 = (ClientConnectionException) err;
            else
                failure0.addSuppressed(err);
            int attempt = attemptsCnt[0];
            int leftAttempts = attemptsLimit - attempt;
            // If it is a first retry then reset attempts (as for initialization we use only 1 attempt).
            if (failure == null)
                leftAttempts = getRetryLimit() - 1;
            if (leftAttempts > 0 && shouldRetry(op, attempt, failure0)) {
                handleServiceAsync(fut, op, payloadWriter, payloadReader, leftAttempts, failure0);
                return null;
            }
        } else {
            fut.completeExceptionally(err instanceof ClientException ? err : new ClientException(err));
            return null;
        }
        fut.completeExceptionally(failure0);
        return null;
    });
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) BiFunction(java.util.function.BiFunction) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) U(org.apache.ignite.internal.util.typedef.internal.U) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClientRetryPolicy(org.apache.ignite.client.ClientRetryPolicy) ClientException(org.apache.ignite.client.ClientException) Map(java.util.Map) ClientConnectionException(org.apache.ignite.client.ClientConnectionException) IgniteBinary(org.apache.ignite.IgniteBinary) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ClientAuthorizationException(org.apache.ignite.client.ClientAuthorizationException) ClientAuthenticationException(org.apache.ignite.client.ClientAuthenticationException) GridNioClientConnectionMultiplexer(org.apache.ignite.internal.client.thin.io.gridnioserver.GridNioClientConnectionMultiplexer) F(org.apache.ignite.internal.util.typedef.F) HostAndPortRange(org.apache.ignite.internal.util.HostAndPortRange) Collection(java.util.Collection) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IgniteClientFuture(org.apache.ignite.client.IgniteClientFuture) Set(java.util.Set) UUID(java.util.UUID) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ClientConnectionMultiplexer(org.apache.ignite.internal.client.thin.io.ClientConnectionMultiplexer) Consumer(java.util.function.Consumer) List(java.util.List) ClientConfiguration(org.apache.ignite.configuration.ClientConfiguration) ForkJoinPool(java.util.concurrent.ForkJoinPool) ClientOperationType(org.apache.ignite.client.ClientOperationType) ClientRetryPolicyContext(org.apache.ignite.client.ClientRetryPolicyContext) ClientConnectorConfiguration(org.apache.ignite.configuration.ClientConnectorConfiguration) ClientConnectionException(org.apache.ignite.client.ClientConnectionException) ClientException(org.apache.ignite.client.ClientException)

Example 3 with ClientException

use of org.apache.ignite.client.ClientException in project ignite by apache.

the class ReliableChannel method initChannelHolders.

/**
 * Init channel holders to all nodes.
 * @return boolean wheter channels was reinited.
 */
synchronized boolean initChannelHolders() {
    List<ClientChannelHolder> holders = channels;
    startChannelsReInit = System.currentTimeMillis();
    // Enable parallel threads to schedule new init of channel holders.
    scheduledChannelsReinit.set(false);
    List<InetSocketAddress> newAddrs = null;
    if (clientCfg.getAddressesFinder() != null) {
        String[] hostAddrs = clientCfg.getAddressesFinder().getAddresses();
        if (hostAddrs.length == 0)
            throw new ClientException("Empty addresses");
        if (!Arrays.equals(hostAddrs, prevHostAddrs)) {
            newAddrs = parsedAddresses(hostAddrs);
            prevHostAddrs = hostAddrs;
        }
    } else if (holders == null)
        newAddrs = parsedAddresses(clientCfg.getAddresses());
    if (newAddrs == null) {
        finishChannelsReInit = System.currentTimeMillis();
        return true;
    }
    Map<InetSocketAddress, ClientChannelHolder> curAddrs = new HashMap<>();
    Map<InetSocketAddress, ClientChannelHolder> newHoldersMap = new HashMap<>();
    Set<InetSocketAddress> newAddrsSet = new HashSet<>(newAddrs);
    // Close obsolete holders or map old but valid addresses to holders
    if (holders != null) {
        for (ClientChannelHolder h : holders) {
            if (newAddrsSet.contains(h.getAddress()))
                curAddrs.put(h.getAddress(), h);
            else
                h.close();
        }
    }
    List<ClientChannelHolder> reinitHolders = new ArrayList<>();
    // The variable holds a new index of default channel after topology change.
    // Suppose that reuse of the channel is better than open new connection.
    int dfltChannelIdx = -1;
    ClientChannelHolder currDfltHolder = null;
    int idx = curChIdx;
    if (idx != -1)
        currDfltHolder = holders.get(idx);
    for (InetSocketAddress addr : newAddrs) {
        if (shouldStopChannelsReinit())
            return false;
        // Create new holders for new addrs.
        if (!curAddrs.containsKey(addr)) {
            ClientChannelHolder hld = newHoldersMap.computeIfAbsent(addr, a -> new ClientChannelHolder(new ClientChannelConfiguration(clientCfg, a)));
            reinitHolders.add(hld);
            continue;
        }
        // This holder is up to date.
        ClientChannelHolder hld = curAddrs.get(addr);
        reinitHolders.add(hld);
        if (hld == currDfltHolder)
            dfltChannelIdx = reinitHolders.size() - 1;
    }
    if (dfltChannelIdx == -1)
        dfltChannelIdx = 0;
    curChannelsGuard.writeLock().lock();
    try {
        channels = reinitHolders;
        curChIdx = dfltChannelIdx;
    } finally {
        curChannelsGuard.writeLock().unlock();
    }
    finishChannelsReInit = System.currentTimeMillis();
    return true;
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) ClientException(org.apache.ignite.client.ClientException) HashSet(java.util.HashSet)

Example 4 with ClientException

use of org.apache.ignite.client.ClientException in project ignite by apache.

the class ClientServicesImpl method serviceDescriptors.

/**
 * {@inheritDoc}
 */
@Override
public Collection<ClientServiceDescriptor> serviceDescriptors() {
    return ch.service(ClientOperation.SERVICE_GET_DESCRIPTORS, req -> checkGetServiceDescriptorsSupported(req.clientChannel().protocolCtx()), res -> {
        try (BinaryReaderExImpl reader = utils.createBinaryReader(res.in())) {
            int sz = res.in().readInt();
            Collection<ClientServiceDescriptor> svcs = new ArrayList<>(sz);
            for (int i = 0; i < sz; i++) svcs.add(readServiceDescriptor(reader));
            return svcs;
        } catch (IOException e) {
            throw new ClientException(e);
        }
    });
}
Also used : BinaryReaderExImpl(org.apache.ignite.internal.binary.BinaryReaderExImpl) ClientServiceDescriptor(org.apache.ignite.client.ClientServiceDescriptor) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ClientException(org.apache.ignite.client.ClientException)

Example 5 with ClientException

use of org.apache.ignite.client.ClientException in project ignite by apache.

the class ClientClusterImpl method changeWalState.

/**
 * @param cacheName Cache name.
 * @param enable {@code True} if WAL should be enabled, {@code false} if WAL should be disabled.
 */
private boolean changeWalState(String cacheName, boolean enable) throws ClientException {
    try {
        return ch.service(ClientOperation.CLUSTER_CHANGE_WAL_STATE, req -> {
            checkClusterApiSupported(req.clientChannel().protocolCtx());
            try (BinaryRawWriterEx writer = utils.createBinaryWriter(req.out())) {
                writer.writeString(cacheName);
                writer.writeBoolean(enable);
            }
        }, res -> res.in().readBoolean());
    } catch (ClientError e) {
        throw new ClientException(e);
    }
}
Also used : ClientException(org.apache.ignite.client.ClientException) BinaryRawWriterEx(org.apache.ignite.internal.binary.BinaryRawWriterEx)

Aggregations

ClientException (org.apache.ignite.client.ClientException)20 ArrayList (java.util.ArrayList)9 UUID (java.util.UUID)6 ClientConfiguration (org.apache.ignite.configuration.ClientConfiguration)6 ClientConnectionException (org.apache.ignite.client.ClientConnectionException)5 IgniteClient (org.apache.ignite.client.IgniteClient)5 HashMap (java.util.HashMap)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 Consumer (java.util.function.Consumer)4 Function (java.util.function.Function)4 BinaryRawWriterEx (org.apache.ignite.internal.binary.BinaryRawWriterEx)4 InetSocketAddress (java.net.InetSocketAddress)3 Collection (java.util.Collection)3 HashSet (java.util.HashSet)3 List (java.util.List)3 Map (java.util.Map)3 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)3 ClientAuthenticationException (org.apache.ignite.client.ClientAuthenticationException)3 ClientFeatureNotSupportedByServerException (org.apache.ignite.client.ClientFeatureNotSupportedByServerException)3