Search in sources :

Example 16 with Factory

use of javax.cache.configuration.Factory in project ignite by apache.

the class ClientCacheEntryListenerHandler method startListen.

/**
 * Send request to the server and start
 */
public synchronized void startListen(CacheEntryUpdatedListener<K, V> locLsnr, ClientDisconnectListener disconnectLsnr, Factory<? extends CacheEntryEventFilter<? super K, ? super V>> rmtFilterFactory, int pageSize, long timeInterval, boolean includeExpired) {
    assert locLsnr != null;
    if (clientCh != null)
        throw new IllegalStateException("Listener was already started");
    this.locLsnr = locLsnr;
    this.disconnectLsnr = disconnectLsnr;
    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(JAVA_PLATFORM);
        }
    };
    Function<PayloadInputChannel, T2<ClientChannel, Long>> qryReader = payloadCh -> {
        ClientChannel ch = payloadCh.clientChannel();
        Long rsrcId = payloadCh.in().readLong();
        ch.addNotificationListener(CONTINUOUS_QUERY_EVENT, rsrcId, this);
        return new T2<>(ch, rsrcId);
    };
    try {
        T2<ClientChannel, Long> params = ch.service(ClientOperation.QUERY_CONTINUOUS, qryWriter, qryReader);
        clientCh = params.get1();
        rsrcId = params.get2();
    } catch (ClientError e) {
        throw new ClientException(e);
    }
}
Also used : Factory(javax.cache.configuration.Factory) BinaryInputStream(org.apache.ignite.internal.binary.streams.BinaryInputStream) EventType(javax.cache.event.EventType) ClientDisconnectListener(org.apache.ignite.client.ClientDisconnectListener) CONTINUOUS_QUERY_EVENT(org.apache.ignite.internal.client.thin.ClientNotificationType.CONTINUOUS_QUERY_EVENT) U(org.apache.ignite.internal.util.typedef.internal.U) BinaryOutputStream(org.apache.ignite.internal.binary.streams.BinaryOutputStream) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) Function(java.util.function.Function) ByteBuffer(java.nio.ByteBuffer) GridBinaryMarshaller(org.apache.ignite.internal.binary.GridBinaryMarshaller) ArrayList(java.util.ArrayList) T2(org.apache.ignite.internal.util.typedef.T2) Consumer(java.util.function.Consumer) List(java.util.List) CacheEntryEvent(javax.cache.event.CacheEntryEvent) CacheEntryEventFilter(javax.cache.event.CacheEntryEventFilter) ClientException(org.apache.ignite.client.ClientException) BinaryByteBufferInputStream(org.apache.ignite.internal.binary.streams.BinaryByteBufferInputStream) Cache(javax.cache.Cache) CacheEntryUpdatedListener(javax.cache.event.CacheEntryUpdatedListener) JAVA_PLATFORM(org.apache.ignite.internal.client.thin.TcpClientCache.JAVA_PLATFORM) BinaryOutputStream(org.apache.ignite.internal.binary.streams.BinaryOutputStream) ClientException(org.apache.ignite.client.ClientException) T2(org.apache.ignite.internal.util.typedef.T2)

Example 17 with Factory

use of javax.cache.configuration.Factory in project ignite by apache.

the class ClientSslUtils method getSslContext.

/**
 * Gets SSL context for the given client configuration.
 *
 * @param cfg Configuration.
 * @return {@link SSLContext} when SSL is enabled in the configuration; null otherwise.
 */
public static SSLContext getSslContext(ClientConfiguration cfg) {
    if (cfg.getSslMode() == SslMode.DISABLED)
        return null;
    Factory<SSLContext> sslCtxFactory = cfg.getSslContextFactory();
    if (sslCtxFactory != null) {
        try {
            return sslCtxFactory.create();
        } catch (Exception e) {
            throw new ClientError("SSL Context Factory failed", e);
        }
    }
    BiFunction<String, String, String> or = (val, dflt) -> val == null || val.isEmpty() ? dflt : val;
    String keyStore = or.apply(cfg.getSslClientCertificateKeyStorePath(), System.getProperty("javax.net.ssl.keyStore"));
    String keyStoreType = or.apply(cfg.getSslClientCertificateKeyStoreType(), or.apply(System.getProperty("javax.net.ssl.keyStoreType"), DFLT_STORE_TYPE));
    String keyStorePwd = or.apply(cfg.getSslClientCertificateKeyStorePassword(), System.getProperty("javax.net.ssl.keyStorePassword"));
    String trustStore = or.apply(cfg.getSslTrustCertificateKeyStorePath(), System.getProperty("javax.net.ssl.trustStore"));
    String trustStoreType = or.apply(cfg.getSslTrustCertificateKeyStoreType(), or.apply(System.getProperty("javax.net.ssl.trustStoreType"), DFLT_STORE_TYPE));
    String trustStorePwd = or.apply(cfg.getSslTrustCertificateKeyStorePassword(), System.getProperty("javax.net.ssl.trustStorePassword"));
    String algorithm = or.apply(cfg.getSslKeyAlgorithm(), DFLT_KEY_ALGORITHM);
    String proto = toString(cfg.getSslProtocol());
    if (Stream.of(keyStore, keyStorePwd, keyStoreType, trustStore, trustStorePwd, trustStoreType).allMatch(s -> s == null || s.isEmpty())) {
        try {
            return SSLContext.getDefault();
        } catch (NoSuchAlgorithmException e) {
            throw new ClientError("Default SSL context cryptographic algorithm is not available", e);
        }
    }
    KeyManager[] keyManagers = getKeyManagers(algorithm, keyStore, keyStoreType, keyStorePwd);
    TrustManager[] trustManagers = cfg.isSslTrustAll() ? new TrustManager[] { ignoreErrorsTrustMgr } : getTrustManagers(algorithm, trustStore, trustStoreType, trustStorePwd);
    try {
        SSLContext sslCtx = SSLContext.getInstance(proto);
        sslCtx.init(keyManagers, trustManagers, null);
        return sslCtx;
    } catch (NoSuchAlgorithmException e) {
        throw new ClientError("SSL context cryptographic algorithm is not available", e);
    } catch (KeyManagementException e) {
        throw new ClientError("Failed to create SSL Context", e);
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) SSLContext(javax.net.ssl.SSLContext) BiFunction(java.util.function.BiFunction) TrustManager(javax.net.ssl.TrustManager) DFLT_STORE_TYPE(org.apache.ignite.ssl.SslContextFactory.DFLT_STORE_TYPE) SslMode(org.apache.ignite.client.SslMode) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) Factory(javax.cache.configuration.Factory) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) Predicate(java.util.function.Predicate) DFLT_KEY_ALGORITHM(org.apache.ignite.ssl.SslContextFactory.DFLT_KEY_ALGORITHM) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) IOException(java.io.IOException) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) KeyManager(javax.net.ssl.KeyManager) Stream(java.util.stream.Stream) ClientConfiguration(org.apache.ignite.configuration.ClientConfiguration) X509TrustManager(javax.net.ssl.X509TrustManager) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SslProtocol(org.apache.ignite.client.SslProtocol) InputStream(java.io.InputStream) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) KeyManager(javax.net.ssl.KeyManager)

Example 18 with Factory

use of javax.cache.configuration.Factory in project ignite by apache.

the class JdbcThinTcpIo method handshake.

/**
 * Used for versions: 2.1.5 and 2.3.0. The protocol version is changed but handshake format isn't changed.
 *
 * @param ver JDBC client version.
 * @throws IOException On IO error.
 * @throws SQLException On connection reject.
 */
private HandshakeResult handshake(ClientListenerProtocolVersion ver) throws IOException, SQLException {
    BinaryContext ctx = new BinaryContext(BinaryCachingMetadataHandler.create(), new IgniteConfiguration(), null);
    BinaryMarshaller marsh = new BinaryMarshaller();
    marsh.setContext(new MarshallerContextImpl(null, null));
    ctx.configure(marsh);
    BinaryWriterExImpl writer = new BinaryWriterExImpl(ctx, new BinaryHeapOutputStream(HANDSHAKE_MSG_SIZE), null, null);
    writer.writeByte((byte) ClientListenerRequest.HANDSHAKE);
    writer.writeShort(ver.major());
    writer.writeShort(ver.minor());
    writer.writeShort(ver.maintenance());
    writer.writeByte(ClientListenerNioListener.JDBC_CLIENT);
    writer.writeBoolean(connProps.isDistributedJoins());
    writer.writeBoolean(connProps.isEnforceJoinOrder());
    writer.writeBoolean(connProps.isCollocated());
    writer.writeBoolean(connProps.isReplicatedOnly());
    writer.writeBoolean(connProps.isAutoCloseServerCursor());
    writer.writeBoolean(connProps.isLazy());
    writer.writeBoolean(connProps.isSkipReducerOnUpdate());
    if (ver.compareTo(VER_2_7_0) >= 0)
        writer.writeString(connProps.nestedTxMode());
    if (ver.compareTo(VER_2_8_0) >= 0) {
        writer.writeByte(nullableBooleanToByte(connProps.isDataPageScanEnabled()));
        JdbcUtils.writeNullableInteger(writer, connProps.getUpdateBatchSize());
    }
    if (ver.compareTo(VER_2_9_0) >= 0) {
        String userAttrs = connProps.getUserAttributesFactory();
        if (F.isEmpty(userAttrs))
            writer.writeMap(null);
        else {
            try {
                Class<Factory<Map<String, String>>> cls = (Class<Factory<Map<String, String>>>) JdbcThinSSLUtil.class.getClassLoader().loadClass(userAttrs);
                Map<String, String> attrs = cls.newInstance().create();
                writer.writeMap(attrs);
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                throw new SQLException("Could not found user attributes factory class: " + userAttrs, SqlStateCode.CLIENT_CONNECTION_FAILED, e);
            }
        }
        writer.writeByteArray(ThinProtocolFeature.featuresAsBytes(enabledFeatures()));
    }
    if (!F.isEmpty(connProps.getUsername())) {
        assert ver.compareTo(VER_2_5_0) >= 0 : "Authentication is supported since 2.5";
        writer.writeString(connProps.getUsername());
        writer.writeString(connProps.getPassword());
    }
    send(writer.array());
    BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx, new BinaryHeapInputStream(read()), null, null, false);
    boolean accepted = reader.readBoolean();
    if (accepted) {
        HandshakeResult handshakeRes = new HandshakeResult();
        if (reader.available() > 0) {
            byte maj = reader.readByte();
            byte min = reader.readByte();
            byte maintenance = reader.readByte();
            String stage = reader.readString();
            long ts = reader.readLong();
            byte[] hash = reader.readByteArray();
            if (ver.compareTo(VER_2_8_0) >= 0)
                handshakeRes.nodeId(reader.readUuid());
            handshakeRes.igniteVersion(new IgniteProductVersion(maj, min, maintenance, stage, ts, hash));
            if (ver.compareTo(VER_2_9_0) >= 0) {
                byte[] srvFeatures = reader.readByteArray();
                EnumSet<JdbcThinFeature> features = JdbcThinFeature.enumSet(srvFeatures);
                handshakeRes.features(features);
            }
        } else {
            handshakeRes.igniteVersion(new IgniteProductVersion((byte) 2, (byte) 0, (byte) 0, "Unknown", 0L, null));
        }
        handshakeRes.serverProtocolVersion(ver);
        return handshakeRes;
    } else {
        short maj = reader.readShort();
        short min = reader.readShort();
        short maintenance = reader.readShort();
        String err = reader.readString();
        ClientListenerProtocolVersion srvProtoVer0 = ClientListenerProtocolVersion.create(maj, min, maintenance);
        if (srvProtoVer0.compareTo(VER_2_5_0) < 0 && !F.isEmpty(connProps.getUsername())) {
            throw new SQLException("Authentication doesn't support by remote server[driverProtocolVer=" + CURRENT_VER + ", remoteNodeProtocolVer=" + srvProtoVer0 + ", err=" + err + ", url=" + connProps.getUrl() + " address=" + sockAddr + ']', SqlStateCode.CONNECTION_REJECTED);
        }
        if (VER_2_8_0.equals(srvProtoVer0) || VER_2_7_0.equals(srvProtoVer0) || VER_2_5_0.equals(srvProtoVer0) || VER_2_4_0.equals(srvProtoVer0) || VER_2_3_0.equals(srvProtoVer0) || VER_2_1_5.equals(srvProtoVer0))
            return handshake(srvProtoVer0);
        else if (VER_2_1_0.equals(srvProtoVer0))
            return handshake_2_1_0();
        else {
            throw new SQLException("Handshake failed [driverProtocolVer=" + CURRENT_VER + ", remoteNodeProtocolVer=" + srvProtoVer0 + ", err=" + err + ']', SqlStateCode.CONNECTION_REJECTED);
        }
    }
}
Also used : BinaryReaderExImpl(org.apache.ignite.internal.binary.BinaryReaderExImpl) BinaryMarshaller(org.apache.ignite.internal.binary.BinaryMarshaller) SQLException(java.sql.SQLException) Factory(javax.cache.configuration.Factory) IgniteProductVersion(org.apache.ignite.lang.IgniteProductVersion) BinaryHeapInputStream(org.apache.ignite.internal.binary.streams.BinaryHeapInputStream) BinaryContext(org.apache.ignite.internal.binary.BinaryContext) MarshallerContextImpl(org.apache.ignite.internal.MarshallerContextImpl) BinaryHeapOutputStream(org.apache.ignite.internal.binary.streams.BinaryHeapOutputStream) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) ClientListenerProtocolVersion(org.apache.ignite.internal.processors.odbc.ClientListenerProtocolVersion) BinaryWriterExImpl(org.apache.ignite.internal.binary.BinaryWriterExImpl) JdbcThinFeature(org.apache.ignite.internal.processors.odbc.jdbc.JdbcThinFeature) Map(java.util.Map)

Example 19 with Factory

use of javax.cache.configuration.Factory in project ignite by apache.

the class CacheContinuousQueryOperationP2PTest method testMultithreadedUpdatesNodeJoin.

/**
 * @throws Exception If failed.
 */
@Test
public void testMultithreadedUpdatesNodeJoin() throws Exception {
    Ignite client = startGrid("client");
    CacheConfiguration<Object, Object> cacheCfg = cacheConfiguration(PARTITIONED, 0, ATOMIC);
    IgniteCache<Object, Object> cache = client.createCache(cacheCfg);
    int iterations = 50;
    int keysNum = 100;
    int threadsNum = Runtime.getRuntime().availableProcessors();
    CountDownLatch updatesLatch = new CountDownLatch(iterations * keysNum * threadsNum / 2);
    ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
    final Class<Factory<CacheEntryEventFilter>> evtFilterFactoryCls = (Class<Factory<CacheEntryEventFilter>>) getExternalClassLoader().loadClass("org.apache.ignite.tests.p2p.CacheDeploymentEntryEventFilterFactory");
    qry.setRemoteFilterFactory((Factory<? extends CacheEntryEventFilter<Object, Object>>) (Object) evtFilterFactoryCls.newInstance());
    qry.setLocalListener((evts) -> {
        for (CacheEntryEvent<?, ?> ignored : evts) updatesLatch.countDown();
    });
    cache.query(qry);
    for (int t = 0; t < threadsNum; t++) {
        int threadId = t;
        GridTestUtils.runAsync(() -> {
            for (int i = 0; i < iterations; i++) {
                log.info("Iteration #" + (i + 1));
                for (int k = 0; k < keysNum; k++) {
                    int key = keysNum * threadId + k;
                    cache.put(key, key);
                }
            }
        }, "cache-writer-thread-" + threadId);
    }
    startGrid(NODES);
    assertTrue("Failed to wait for all cache updates invocations. Latch: " + updatesLatch, updatesLatch.await(30, TimeUnit.SECONDS));
}
Also used : Factory(javax.cache.configuration.Factory) CountDownLatch(java.util.concurrent.CountDownLatch) CacheEntryEventFilter(javax.cache.event.CacheEntryEventFilter) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) Ignite(org.apache.ignite.Ignite) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 20 with Factory

use of javax.cache.configuration.Factory in project Payara by payara.

the class JSR107Producer method createCache.

/**
 * Produces a Cache for injection. If the @NamedCache annotation is present the
 * cache will be created based on the values of the annotation field
 *
 * Otherwise the cache will be created with the cache name being equal
 * to the fully qualified name of the class into which it is injected
 * @param ip
 * @return
 */
@Produces
public <K, V> Cache<K, V> createCache(InjectionPoint ip) {
    Cache<K, V> result;
    if (!hazelcastCore.isEnabled()) {
        logger.warning("Unable to inject Cache as Hazelcast is Disabled");
        return null;
    }
    // determine the cache name first start with the default name
    String cacheName = ip.getMember().getDeclaringClass().getCanonicalName();
    NamedCache ncqualifier = ip.getAnnotated().getAnnotation(NamedCache.class);
    CacheManager manager = getCacheManager(ip);
    if (ncqualifier != null) {
        // configure the cache based on the annotation
        String qualifierName = ncqualifier.cacheName();
        if (!"".equals(cacheName)) {
            cacheName = qualifierName;
        }
        Class keyClass = ncqualifier.keyClass();
        Class valueClass = ncqualifier.valueClass();
        result = manager.getCache(cacheName, keyClass, valueClass);
        if (result == null) {
            MutableConfiguration<K, V> config = new MutableConfiguration<>();
            config.setTypes(keyClass, valueClass);
            // determine the expiry policy
            Class expiryPolicyFactoryClass = ncqualifier.expiryPolicyFactoryClass();
            if (!"Object".equals(expiryPolicyFactoryClass.getSimpleName())) {
                Factory factory = FactoryBuilder.factoryOf(expiryPolicyFactoryClass);
                config.setExpiryPolicyFactory(factory);
            }
            // determine the cache writer if any
            Class writerFactoryClass = ncqualifier.cacheWriterFactoryClass();
            if (!"Object".equals(writerFactoryClass.getSimpleName())) {
                Factory factory = FactoryBuilder.factoryOf(writerFactoryClass);
                config.setCacheWriterFactory(factory);
            }
            config.setWriteThrough(ncqualifier.writeThrough());
            // determine the cache loader if any
            Class loaderFactoryClass = ncqualifier.cacheLoaderFactoryClass();
            if (!"Object".equals(loaderFactoryClass.getSimpleName())) {
                Factory factory = FactoryBuilder.factoryOf(loaderFactoryClass);
                config.setCacheLoaderFactory(factory);
            }
            config.setReadThrough(ncqualifier.readThrough());
            config.setManagementEnabled(ncqualifier.managementEnabled());
            config.setStatisticsEnabled(ncqualifier.statisticsEnabled());
            result = manager.createCache(cacheName, config);
        }
    } else {
        // configure a "raw" cache
        Bean<?> bean = ip.getBean();
        if (bean != null) {
            Class<?> beanClass = bean.getBeanClass();
            CacheDefaults defaults = beanClass.getAnnotation(CacheDefaults.class);
            if (defaults != null) {
                String cacheNameFromAnnotation = defaults.cacheName();
                if (!"".equals(cacheNameFromAnnotation)) {
                    cacheName = cacheNameFromAnnotation;
                }
            }
        }
        result = manager.getCache(cacheName);
        if (result == null) {
            MutableConfiguration<K, V> config = new MutableConfiguration<>();
            config.setManagementEnabled(true);
            config.setStatisticsEnabled(true);
            result = manager.createCache(cacheName, config);
        }
    }
    return result;
}
Also used : Factory(javax.cache.configuration.Factory) MutableConfiguration(javax.cache.configuration.MutableConfiguration) NamedCache(fish.payara.cdi.jsr107.impl.NamedCache) CacheDefaults(javax.cache.annotation.CacheDefaults) CacheManager(javax.cache.CacheManager) Produces(javax.enterprise.inject.Produces)

Aggregations

Factory (javax.cache.configuration.Factory)20 CacheEntryEventFilter (javax.cache.event.CacheEntryEventFilter)10 ContinuousQuery (org.apache.ignite.cache.query.ContinuousQuery)10 IgniteCache (org.apache.ignite.IgniteCache)6 CacheEntryEvent (javax.cache.event.CacheEntryEvent)5 Ignite (org.apache.ignite.Ignite)5 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)5 IgniteEx (org.apache.ignite.internal.IgniteEx)5 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)5 Test (org.junit.Test)5 Map (java.util.Map)4 AbstractContinuousQuery (org.apache.ignite.cache.query.AbstractContinuousQuery)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 Cache (javax.cache.Cache)3 CacheException (javax.cache.CacheException)3 FactoryBuilder (javax.cache.configuration.FactoryBuilder)3 IgniteException (org.apache.ignite.IgniteException)3 ContinuousQueryWithTransformer (org.apache.ignite.cache.query.ContinuousQueryWithTransformer)3 CacheConfiguration (org.apache.ignite.configuration.CacheConfiguration)3 GridDeploymentRequest (org.apache.ignite.internal.managers.deployment.GridDeploymentRequest)3