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);
}
}
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);
}
}
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);
}
}
}
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));
}
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;
}
Aggregations