Java Code Examples for org.infinispan.client.hotrod.RemoteCacheManager#getCache()

The following examples show how to use org.infinispan.client.hotrod.RemoteCacheManager#getCache() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RemoteCaches.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testRemoteLoginCache() {
    RemoteCacheManager cacheManager = new RemoteCacheManager("192.168.0.58:11422;192.168.0.58:11322", true);
    RemoteCache<Object, Object> cache = cacheManager.getCache("KHAN_SESSION_LOGIN_REMOTE");

    Set<Object> keySet = cache.keySet();

    Iterator<Object> i = keySet.iterator();
    System.out.println("============= KHAN_SESSION_LOGIN_REMOTE");
    while (i.hasNext()) {
        Object key = i.next();
        System.out.println("> key=" + key);
        Object value = cache.get(key);
        System.out.println("> value=" + value);
        System.out.println("");
    }
    System.out.println("=============");
}
 
Example 2
Source File: InfinispanScripting.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
   // Create a configuration for a locally-running server
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
   // Connect to the server
   RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
   // Retrieve the cache containing the scripts
   RemoteCache<String, String> scriptCache = cacheManager.getCache("___script_cache");
   // Create a simple script which multiplies to numbers
   scriptCache.put("simple.js", "multiplicand * multiplier");
   // Obtain the remote cache
   RemoteCache<String, Integer> cache = cacheManager.administration().getOrCreateCache("test", DefaultTemplate.DIST_SYNC);
   // Create the parameters for script execution
   Map<String, Object> params = new HashMap<>();
   params.put("multiplicand", 10);
   params.put("multiplier", 20);
   // Run the script on the server, passing in the parameters
   Object result = cache.execute("simple.js", params);
   // Print the result
   System.out.printf("Result = %s\n", result);
   // Stop the cache manager and release resources
   cacheManager.stop();
}
 
Example 3
Source File: RemoteCaches.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testRemoteCache() {
    RemoteCacheManager cacheManager = new RemoteCacheManager("192.168.0.58:11422;192.168.0.58:11322", true);
    RemoteCache<Object, Object> cache = cacheManager.getCache("KHAN_SESSION_REMOTE");

    Set<Object> keySet = cache.keySet();

    Iterator<Object> i = keySet.iterator();
    System.out.println("============= KHAN_SESSION_REMOTE");
    while (i.hasNext()) {
        Object key = i.next();
        System.out.println("> key=" + key);
        Object value = cache.get(key);
        System.out.println("> value=" + value);
        System.out.println("");
    }
    System.out.println("=============");
}
 
Example 4
Source File: InfinispanRemoteQuery.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
private static void addPersonSchema(RemoteCacheManager cacheManager) throws IOException {
   // Get the serialization context of the client
   SerializationContext ctx = MarshallerUtil.getSerializationContext(cacheManager);

   // Use ProtoSchemaBuilder to define a Protobuf schema on the client
   ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder();
   String fileName = "person.proto";
   String protoFile = protoSchemaBuilder
         .fileName(fileName)
         .addClass(Person.class)
         .packageName("tutorial")
         .build(ctx);

   // Retrieve metadata cache
   RemoteCache<String, String> metadataCache =
         cacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME);

   // Define the new schema on the server too
   metadataCache.put(fileName, protoFile);
}
 
Example 5
Source File: InfinispanRemoteContinuousQuery.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
private static void addInstapostsSchema(RemoteCacheManager cacheManager) throws IOException {
   // Get the serialization context of the client
   SerializationContext ctx = MarshallerUtil.getSerializationContext(cacheManager);

   // Use ProtoSchemaBuilder to define a Protobuf schema on the client
   ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder();
   String fileName = "instapost.proto";
   String protoFile = protoSchemaBuilder
         .fileName(fileName)
         .addClass(InstaPost.class)
         .packageName("tutorial")
         .build(ctx);

   // Retrieve metadata cache
   RemoteCache<String, String> metadataCache =
         cacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME);

   // Define the new schema on the server too
   metadataCache.putIfAbsent(fileName, protoFile);
}
 
Example 6
Source File: RemoteCaches.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void test2() {
    RemoteCacheManager cacheManager = new RemoteCacheManager("192.168.0.58:11322;192.168.0.58:11422", true);
    RemoteCache<Object, Object> cache = cacheManager.getCache("KHAN_SESSION_LOGIN");

    Set<Object> keySet = cache.keySet();

    Iterator<Object> i = keySet.iterator();
    System.out.println("============= KHAN_SESSION_LOGIN");
    while (i.hasNext()) {
        Object key = i.next();
        System.out.println("> key=" + key);
        Object value = cache.get(key);
        System.out.println("> value=" + value);
        System.out.println("");
    }
    System.out.println("=============");
}
 
Example 7
Source File: InfinispanRemote.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
   // Create a configuration for a locally-running server
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.addServer()
            .host("127.0.0.1")
            .port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
          .security().authentication()
            //Add user credentials.
            .username("username")
            .password("password")
            .realm("default")
            .saslMechanism("DIGEST-MD5");
   // Connect to the server
   RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
   // Create test cache, if such does not exist
   cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).getOrCreateCache("test", DefaultTemplate.DIST_SYNC);
   // Obtain the remote cache
   RemoteCache<String, String> cache = cacheManager.getCache("test");
   /// Store a value
   cache.put("key", "value");
   // Retrieve the value and print it out
   System.out.printf("key = %s\n", cache.get("key"));
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 8
Source File: RemoteCaches.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void test() {

        RemoteCacheManager cacheManager = new RemoteCacheManager("192.168.0.58:11322;192.168.0.58:11422", true);
        RemoteCache<Object, Object> cache = cacheManager.getCache("KHAN_SESSION");

        Set<Object> keySet = cache.keySet();

        Iterator<Object> i = keySet.iterator();
        System.out.println("============= KHAN_SESSION");
        while (i.hasNext()) {
            Object key = i.next();
            System.out.println("> key=" + key);
            Object value = cache.get(key);
            System.out.println("> value=" + value);
            System.out.println("");
        }
        System.out.println("=============");
    }
 
Example 9
Source File: InfinispanRemoteSecured.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
   // Create a configuration for a locally-running server
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
   // Workaround for docker 4 mac
   builder.clientIntelligence(ClientIntelligence.BASIC);

   //Configure the security properties
   builder.security().authentication()
           .username("Titus Bramble")
           .password("Shambles")
           .saslMechanism("DIGEST-MD5")
           .realm("default")
           .serverName("infinispan");

   // Connect to the server
   RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
   // Create test cache, if such does not exist
   cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).getOrCreateCache("test",
         DefaultTemplate.DIST_SYNC);
   // Obtain the remote cache
   RemoteCache<String, String> cache = cacheManager.getCache("test");
   /// Store a value
   cache.put("key", "value");
   // Retrieve the value and print it out
   System.out.printf("key = %s\n", cache.get("key"));
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 10
Source File: DistributedCacheConcurrentWritesTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static BasicCache<String, SessionEntityWrapper<UserSessionEntity>> createRemoteCache(String nodeName) {
    int port = ("node1".equals(nodeName)) ? 12232 : 13232;

    org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder();
    org.infinispan.client.hotrod.configuration.Configuration cfg = builder
            .addServer().host("localhost").port(port)
            .version(ProtocolVersion.PROTOCOL_VERSION_26)
            .build();
    RemoteCacheManager mgr = new RemoteCacheManager(cfg);
    return mgr.getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME);
}
 
Example 11
Source File: RemoteCacheProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected synchronized RemoteCache loadRemoteCache(String cacheName) {
    RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cacheManager.getCache(cacheName));

    Boolean remoteStoreSecurity = config.getBoolean("remoteStoreSecurityEnabled");
    if (remoteStoreSecurity == null) {
        try {
            logger.debugf("Detecting remote security settings of HotRod server, cache %s. Disable by explicitly setting \"remoteStoreSecurityEnabled\" property in spi=connectionsInfinispan/provider=default", cacheName);
            remoteStoreSecurity = false;
            final RemoteCache<Object, Object> scriptCache = remoteCache.getRemoteCacheManager().getCache(SCRIPT_CACHE_NAME);
            if (scriptCache == null) {
                logger.debug("Cannot detect remote security settings of HotRod server, disabling.");
            } else {
                scriptCache.containsKey("");
            }
        } catch (HotRodClientException ex) {
            logger.debug("Seems that HotRod server requires authentication, enabling.");
            remoteStoreSecurity = true;
        }
    }

    if (remoteStoreSecurity) {
        logger.infof("Remote store security for cache %s is enabled. Disable by setting \"remoteStoreSecurityEnabled\" property to \"false\" in spi=connectionsInfinispan/provider=default", cacheName);
        RemoteCacheManager securedMgr = getOrCreateSecuredRemoteCacheManager(config, cacheName, remoteCache.getRemoteCacheManager());
        return securedMgr.getCache(remoteCache.getName());
    } else {
        logger.infof("Remote store security for cache %s is disabled. If server fails to connect to remote JDG server, enable it.", cacheName);
        return remoteCache;
    }
}
 
Example 12
Source File: InfinispanHotRodImpl.java    From khan-session with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 초기화 함수, 설정파일을 읽어서 캐시를 초기화한다.
 *
 * @param configFile
 * @param cacheName
 * @param loginCacheName
 * @throws IOException
 */
@Override
public void initialize(String configFile, String cacheName, String loginCacheName)
        throws IOException {
    StringUtils.isNotNull("configFile", configFile);

    Configuration configuration = null;
    ConfigurationBuilder builder = new ConfigurationBuilder();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    builder.classLoader(cl);

    InputStream stream = cl.getResourceAsStream(configFile);

    if (stream == null) {
        logger.error("Can't Found configFile=" + configFile);
    } else {
        try {
            builder.withProperties(loadFromStream(stream));
        } finally {
            Util.close(stream);
        }
    }
    configuration = builder.build();


    cacheManager = new RemoteCacheManager(configuration);

    cache = cacheManager.getCache(cacheName);
    loginCache = cacheManager.getCache(loginCacheName);

    waitForConnectionReady();
}
 
Example 13
Source File: HotRodSearchClientTest.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
void clearSearchCache() {
    RemoteCacheManager manager = null;
    try {
        manager = raw();
        RemoteCache<String, Search.Artifact> cache = manager.getCache(InfinispanSearchClient.SEARCH_CACHE_DEFAULT);
        if (cache != null) {
            cache.clear();
        }
    } finally {
        IoUtil.closeIgnore(manager);
    }
}
 
Example 14
Source File: InfinispanClientProducer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@io.quarkus.infinispan.client.Remote
@Produces
public <K, V> RemoteCache<K, V> getRemoteCache(InjectionPoint injectionPoint, RemoteCacheManager cacheManager) {
    Set<Annotation> annotationSet = injectionPoint.getQualifiers();

    final io.quarkus.infinispan.client.Remote remote = getRemoteAnnotation(annotationSet);

    if (remote != null && !remote.value().isEmpty()) {
        return cacheManager.getCache(remote.value());
    }

    return cacheManager.getCache();
}
 
Example 15
Source File: SimpleSparkJob.java    From infinispan-simple-tutorials with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws UnknownHostException {
   // Obtain the Infinispan address
   String infinispanAddress = args[0];

   // Adjust log levels
   Logger.getLogger("org").setLevel(Level.WARN);

   // Create the remote cache manager
   Configuration build = new ConfigurationBuilder().addServer().host(infinispanAddress).build();
   RemoteCacheManager remoteCacheManager = new RemoteCacheManager(build);

   // Obtain the remote cache
   RemoteCache<Integer, Temperature> cache = remoteCacheManager.getCache();

   // Add some data
   cache.put(1, new Temperature(21, "London"));
   cache.put(2, new Temperature(34, "Rome"));
   cache.put(3, new Temperature(33, "Barcelona"));
   cache.put(4, new Temperature(8, "Oslo"));

   // Create java spark context
   SparkConf conf = new SparkConf().setAppName("infinispan-spark-simple-job");
   JavaSparkContext jsc = new JavaSparkContext(conf);

   // Create InfinispanRDD
   ConnectorConfiguration config = new ConnectorConfiguration().setServerList(infinispanAddress);

   JavaPairRDD<Integer, Temperature> infinispanRDD = InfinispanJavaRDD.createInfinispanRDD(jsc, config);

   // Convert RDD to RDD of doubles
   JavaDoubleRDD javaDoubleRDD = infinispanRDD.values().mapToDouble(Temperature::getValue);

   // Calculate average temperature
   Double meanTemp = javaDoubleRDD.mean();
   System.out.printf("\nAVERAGE TEMPERATURE: %f C\n", meanTemp);

   // Calculate standard deviation
   Double stdDev = javaDoubleRDD.sampleStdev();
   System.out.printf("STD DEVIATION: %f C\n ", stdDev);

   // Calculate histogram of temperatures
   System.out.println("TEMPERATURE HISTOGRAM:");
   double[] buckets = {0d, 10d, 20d, 30d, 40d};
   long[] histogram = javaDoubleRDD.histogram(buckets);

   for (int i = 0; i < buckets.length - 1; i++) {
      System.out.printf("Between %f C and %f C: %d cities\n", buckets[i], buckets[i + 1], histogram[i]);
   }
}
 
Example 16
Source File: InfinispanRemoteTx.java    From infinispan-simple-tutorials with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
   // Create a configuration for a locally-running server
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.addServer()
            .host("127.0.0.1")
            .port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
          .security().authentication()
            //Add user credentials.
            .username("username")
            .password("password")
            .realm("default")
            .saslMechanism("DIGEST-MD5");

   // Configure the RemoteCacheManager to use a transactional cache as default
   // Use the simple TransactionManager in hot rod client
   builder.transaction().transactionManagerLookup(RemoteTransactionManagerLookup.getInstance());
   // The cache will be enlisted as Synchronization
   builder.transaction().transactionMode(TransactionMode.NON_XA);

   // Connect to the server
   RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());

   // Create a transactional cache in the server since there is none available by default.
   cacheManager.administration().createCache(CACHE_NAME, new XMLStringConfiguration(TEST_CACHE_XML_CONFIG));
   RemoteCache<String, String> cache = cacheManager.getCache(CACHE_NAME);

   // Obtain the transaction manager
   TransactionManager transactionManager = cache.getTransactionManager();
   // Perform some operations within a transaction and commit it
   transactionManager.begin();
   cache.put("key1", "value1");
   cache.put("key2", "value2");
   transactionManager.commit();
   // Display the current cache contents
   System.out.printf("key1 = %s\nkey2 = %s\n", cache.get("key1"), cache.get("key2"));
   // Perform some operations within a transaction and roll it back
   transactionManager.begin();
   cache.put("key1", "value3");
   cache.put("key2", "value4");
   transactionManager.rollback();
   // Display the current cache contents
   System.out.printf("key1 = %s\nkey2 = %s\n", cache.get("key1"), cache.get("key2"));
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 17
Source File: InfinispanClientProducer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void initialize() {
    log.debug("Initializing CacheManager");
    Configuration conf;
    if (properties == null) {
        // We already loaded and it wasn't present - so use an empty config
        conf = new ConfigurationBuilder().build();
    } else {
        conf = builderFromProperties(properties).build();
    }
    cacheManager = new RemoteCacheManager(conf);

    // TODO: do we want to automatically register all the proto file definitions?
    RemoteCache<String, String> protobufMetadataCache = null;

    Set<SerializationContextInitializer> initializers = (Set) properties.remove(PROTOBUF_INITIALIZERS);
    if (initializers != null) {
        for (SerializationContextInitializer initializer : initializers) {
            if (protobufMetadataCache == null) {
                protobufMetadataCache = cacheManager.getCache(
                        ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME);
            }
            protobufMetadataCache.put(initializer.getProtoFileName(), initializer.getProtoFile());
        }
    }

    for (Map.Entry<Object, Object> property : properties.entrySet()) {
        Object key = property.getKey();
        if (key instanceof String) {
            String keyString = (String) key;
            if (keyString.startsWith(InfinispanClientProducer.PROTOBUF_FILE_PREFIX)) {
                String fileName = keyString.substring(InfinispanClientProducer.PROTOBUF_FILE_PREFIX.length());
                String fileContents = (String) property.getValue();
                if (protobufMetadataCache == null) {
                    protobufMetadataCache = cacheManager.getCache(
                            ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME);
                }
                protobufMetadataCache.put(fileName, fileContents);
            }
        }
    }
}