Java Code Examples for org.infinispan.client.hotrod.RemoteCache#put()

The following examples show how to use org.infinispan.client.hotrod.RemoteCache#put() . 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: HotRodSearchClient.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
private void registerProto(boolean reset, String... protoKeys) {
    RemoteCache<Object, Object> cache = manager.getCache(PROTO_CACHE);
    if (cache == null) {
        throw new IllegalStateException(String.format("Missing %s cache!", PROTO_CACHE));
    }

    SerializationContext ctx = MarshallerUtil.getSerializationContext(manager);
    FileDescriptorSource fds = new FileDescriptorSource();
    for (String protoKey : protoKeys) {
        if (reset || !cache.containsKey(protoKey)) {
            String protoContent = IoUtil.toString(getClass().getResourceAsStream("/" + protoKey));
            log.info(String.format("Using proto schema: %s%n%s", protoKey, protoContent));
            fds.addProtoFile(protoKey, protoContent);
            cache.put(protoKey, protoContent);
        }
    }
    ctx.registerProtoFiles(fds);
    ctx.registerMarshaller(new ArtifactTypeMarshaller());
    ctx.registerMarshaller(new ArtifactMarshaller());
}
 
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: 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 4
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 5
Source File: InfinispanNearCache.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
   // Create a client configuration connecting to a local server
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
   builder.nearCache().mode(NearCacheMode.INVALIDATED).maxEntries(20).cacheNamePattern("near-.*");

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

   // Create one remote cache with near caching disabled and one with near caching enabled
   RemoteCache<Integer, String> numbers = cacheManager.administration().getOrCreateCache("numbers", DefaultTemplate.DIST_SYNC);
   RemoteCache<Integer, String> nearNumbers = cacheManager.administration().getOrCreateCache("near-numbers", DefaultTemplate.DIST_SYNC);

   for (int i = 1; i<= 20; i++) {
      numbers.put(i, String.valueOf(i));
      nearNumbers.put(i, String.valueOf(i));
   }

   // Read both caches data
   readCache(numbers);
   readCache(nearNumbers);

   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 6
Source File: InfinispanRemotePerCache.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)
          .security().authentication()
            //Add user credentials.
            .username("username")
            .password("password")
            .realm("default")
            .saslMechanism("DIGEST-MD5");
   //Add per-cache configuration that uses an org.infinispan cache template.
   builder.remoteCache("my-cache")
            .templateName("org.infinispan.DIST_SYNC");
   //Add per-cache configuration with a cache definition in XML format.
   builder.remoteCache("another-cache")
            .configuration("<infinispan><cache-container><distributed-cache name=\"another-cache\"><encoding media-type=\"application/x-protostream\"/></distributed-cache></cache-container></infinispan>");
   // Connect to the server
   try (RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build())) {
      // Obtain a remote cache that does not exist.
      // Rather than return null, create the cache from a template.
      RemoteCache<String, String> cache = cacheManager.getCache("my-cache");
      /// Store a value
      cache.put("hello", "world");
      // Retrieve the value and print it out
      System.out.printf("key = %s\n", cache.get("hello"));
   }
}
 
Example 7
Source File: InfinispanRemoteListen.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
   // 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());
   // Get the cache, create it if needed with an existing template name
   RemoteCache<String, String> cache = cacheManager.administration()
           .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
           .getOrCreateCache("listen", DefaultTemplate.DIST_SYNC);
   // Register a listener
   MyListener listener = new MyListener();
   cache.addClientListener(listener);
   // Store some values
   cache.put("key1", "value1");
   cache.put("key2", "value2");
   cache.put("key1", "newValue");
   // Remote events are asynchronous, so wait a bit
   Thread.sleep(1000);
   // Remove listener
   cache.removeClientListener(listener);
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 8
Source File: InfinispanRemoteContinuousQuery.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
private static void addRandomPost(RemoteCache<String, InstaPost> cache) {
   String id = UUID.randomUUID().toString();
   Random random = new Random();
   // Create the random post
   InstaPost post = new InstaPost(id, USERS.get(random.nextInt(USERS.size())), HASHTAGS.get(random.nextInt(HASHTAGS.size())));
   // Put a post in the cache
   cache.put(id, post);
}
 
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: RemoteCacheInvoker.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private <K, V extends SessionEntity> void runOnRemoteCache(TopologyInfo topology, RemoteCache<K, SessionEntityWrapper<V>> remoteCache, long maxIdleMs, K key, SessionUpdateTask<V> task, SessionEntityWrapper<V> sessionWrapper) {
    final V session = sessionWrapper.getEntity();
    SessionUpdateTask.CacheOperation operation = task.getOperation(session);

    switch (operation) {
        case REMOVE:
            remoteCache.remove(key);
            break;
        case ADD:
            remoteCache.put(key, sessionWrapper.forTransport(), task.getLifespanMs(), TimeUnit.MILLISECONDS, maxIdleMs, TimeUnit.MILLISECONDS);
            break;
        case ADD_IF_ABSENT:
            SessionEntityWrapper<V> existing = remoteCache
                    .withFlags(Flag.FORCE_RETURN_VALUE)
                    .putIfAbsent(key, sessionWrapper.forTransport(), -1, TimeUnit.MILLISECONDS, maxIdleMs, TimeUnit.MILLISECONDS);
            if (existing != null) {
                logger.debugf("Existing entity in remote cache for key: %s . Will update it", key);

                replace(topology, remoteCache, task.getLifespanMs(), maxIdleMs, key, task);
            }
            break;
        case REPLACE:
            replace(topology, remoteCache, task.getLifespanMs(), maxIdleMs, key, task);
            break;
        default:
            throw new IllegalStateException("Unsupported state " +  operation);
    }
}
 
Example 11
Source File: InfinispanClientApp.java    From quarkus-quickstarts with Apache License 2.0 4 votes vote down vote up
void onStart(@Observes StartupEvent ev) {
    LOGGER.info("Create or get cache named mycache with the default configuration");
    RemoteCache<Object, Object> cache = cacheManager.administration().getOrCreateCache("mycache",
            new XMLStringConfiguration(String.format(CACHE_CONFIG, "mycache")));
    cache.put("hello", "Hello World, Infinispan is up!");
}
 
Example 12
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);
            }
        }
    }
}
 
Example 13
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 14
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 15
Source File: RemoteCacheSessionsLoaderTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
        String cacheName = InfinispanConnectionProvider.USER_SESSION_CACHE_NAME;
        Cache cache1 = createManager(1, cacheName).getCache(cacheName);
        Cache cache2 = cache1.getCacheManager().getCache("local");
        RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache1);
        cache1.clear();
        cache2.clear();
        remoteCache.clear();

        try {

            for (int i=0 ; i<COUNT ; i++) {
                // Create initial item
                UserSessionEntity session = new UserSessionEntity();
                session.setId("loader-key-" + i);
                session.setRealmId("master");
                session.setBrokerSessionId("!23123123");
                session.setBrokerUserId(null);
                session.setUser("admin");
                session.setLoginUsername("admin");
                session.setIpAddress("123.44.143.178");
                session.setStarted(Time.currentTime());
                session.setLastSessionRefresh(Time.currentTime());

                SessionEntityWrapper<UserSessionEntity> wrappedSession = new SessionEntityWrapper<>(session);

                // Create caches, listeners and finally worker threads
                remoteCache.put("loader-key-" + i, wrappedSession);
                Assert.assertFalse(cache2.containsKey("loader-key-" + i));

                if (i % 1000 == 0) {
                    logger.infof("%d sessions added", i);
                }
            }


//            RemoteCacheSessionsLoader loader = new RemoteCacheSessionsLoader(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME, 64) {
//
//                @Override
//                protected Cache getCache(KeycloakSession session) {
//                    return cache2;
//                }
//
//                @Override
//                protected RemoteCache getRemoteCache(KeycloakSession session) {
//                    return remoteCache;
//                }
//
//            };

            // Just to be able to test serializability
            RemoteCacheSessionsLoader loader = new CustomLoader(cacheName, 64, cache2, remoteCache);

            loader.init(null);
            RemoteCacheSessionsLoaderContext ctx = loader.computeLoaderContext(null);
            Assert.assertEquals(ctx.getSessionsTotal(), COUNT);
            Assert.assertEquals(ctx.getIspnSegmentsCount(), 256);
            //Assert.assertEquals(ctx.getSegmentsCount(), 16);
            Assert.assertEquals(ctx.getSessionsPerSegment(), 64);

            int totalCount = 0;
            logger.infof("segmentsCount: %d", ctx.getSegmentsCount());

            Set<String> visitedKeys = new HashSet<>();
            for (int currentSegment=0 ; currentSegment<ctx.getSegmentsCount() ; currentSegment++) {
                logger.infof("Loading segment %d", currentSegment);
                loader.loadSessions(null, ctx, new SessionLoader.WorkerContext(currentSegment, currentSegment));

                logger.infof("Loaded %d keys for segment %d", cache2.keySet().size(), currentSegment);
                totalCount = totalCount + cache2.keySet().size();
                visitedKeys.addAll(cache2.keySet());
                cache2.clear();
            }

            Assert.assertEquals(totalCount, COUNT);
            Assert.assertEquals(visitedKeys.size(), COUNT);
            logger.infof("SUCCESS: Loaded %d sessions", totalCount);
        } finally {
            // Finish JVM
            cache1.getCacheManager().stop();
        }
    }