private setState(List<KeyValuePair> pairs) { for (KeyValuePair pair : pairs) { String key = pair.getKey(); String value = pair.getValue(); hungry = (key.equals("hunger") && value.equals("Y")) || hungry; sleepy = (key.equals("tired") && value.equals("Y")) || sleepy; happy = (key.equals("sad") && value.equals("N")) || happy; } }
public Map<String, String> getAll() { Map<String, String> ret = new HashMap<String, String>(); Query query = em.createQuery("select kvp from KeyValuePair kvp"); for (KeyValuePair kvp : query.getResultList()) { ret.put(kvp.getKey(), kvp.getValue()); } return ret; }
static String getDecoratedCacheKey(String cacheName, KeyValuePair<String, String> mediaTypes) { return cacheName + "|" + mediaTypes.getKey() + "|" + mediaTypes.getValue(); }
void start(SearchFactoryHandler searchFactoryHandler) { if (indexedEntities != null) { throw new IllegalStateException("Cannot start internal cache unless we are in autodetect mode"); } if (searchFactoryHandler == null) { throw new IllegalArgumentException("null argument not allowed"); } this.searchFactoryHandler = searchFactoryHandler; startInternalCache(); knownClassesCache.addListener(searchFactoryHandler.getCacheListener(), key -> key.getKey().equals(cacheName)); }
void start(SearchFactoryHandler searchFactoryHandler) { if (indexedEntities != null) { throw new IllegalStateException("Cannot start internal cache unless we are in autodetect mode"); } if (searchFactoryHandler == null) { throw new IllegalArgumentException("null argument not allowed"); } this.searchFactoryHandler = searchFactoryHandler; startInternalCache(); knownClassesCache.addListener(searchFactoryHandler.getCacheListener(), key -> key.getKey().equals(cacheName)); }
if (!validateRecordKey(kvp.getKey())) { badKey.add(kvp); } else if (!validateRecord(kvp.getValue())) {
protected void customDecodeKey(ChannelHandlerContext ctx, ByteBuf buffer) throws IOException { Channel ch = ctx.channel(); switch (header.operation) { case AppendRequest: case PrependRequest: case IncrementRequest: case DecrementRequest: key = readKey(buffer).getKey(); checkpoint(MemcachedDecoderState.DECODE_PARAMETERS); break; case FlushAllRequest: flushAll(buffer, ch, true); // With params break; default: throw new IllegalArgumentException("Operation " + header.operation + " not supported!"); } }
@Override public MarshalledEntry next() { try { if (rs.next()) { rowIndex++; Object key = key2StringMapper.getKeyMapping(rs.getString(2)); KeyValuePair<ByteBuffer, ByteBuffer> icv = unmarshall(rs.getBinaryStream(1)); return new MarshalledEntryImpl(key, icv.getKey(), icv.getValue(), marshaller); } else { close(); throw new NoSuchElementException(); } } catch (SQLException e) { throw new PersistenceException("SQL error while fetching all StoredEntries", e); } }
Set<Class<?>> keys() { if (indexedEntities != null) { return indexedEntities; } startInternalCache(); Set<Class<?>> result = new HashSet<>(); Transaction tx = transactionHelper.suspendTxIfExists(); try { for (KeyValuePair<String, Class<?>> key : knownClassesCache.keySet()) { if (key.getKey().equals(cacheName)) { result.add(key.getValue()); } } return result; } finally { transactionHelper.resume(tx); } }
Set<Class<?>> keys() { if (indexedEntities != null) { return indexedEntities; } startInternalCache(); Set<Class<?>> result = new HashSet<>(); Transaction tx = transactionHelper.suspendTxIfExists(); try { for (KeyValuePair<String, Class<?>> key : knownClassesCache.keySet()) { if (key.getKey().equals(cacheName)) { result.add(key.getValue()); } } return result; } finally { transactionHelper.resume(tx); } }
private void writeNamedFactory(Optional<KeyValuePair<String, List<byte[]>>> namedFactory, ByteBuf buffer) { if (namedFactory.isPresent()) { KeyValuePair<String, List<byte[]>> factory = namedFactory.get(); writeString(factory.getKey(), buffer); buffer.writeByte(factory.getValue().size()); factory.getValue().forEach(bytes -> writeRangedBytes(bytes, buffer)); } else { buffer.writeByte(0); } }
AdvancedCache getCacheInstance(KeyValuePair<String, String> requestTypes, HotRodHeader header, String cacheName, EmbeddedCacheManager cacheManager, Boolean skipCacheCheck, Boolean addToKnownCaches) { AdvancedCache cache = null; String scopedCacheKey = getDecoratedCacheKey(cacheName, requestTypes); if (!skipCacheCheck) cache = knownCaches.get(scopedCacheKey); if (cache == null) { String validCacheName = cacheName.isEmpty() ? configuration.defaultCacheName() : cacheName; cache = SecurityActions.getCache(cacheManager, validCacheName).getAdvancedCache(); Configuration cacheConfiguration = SecurityActions.getCacheConfiguration(cache); // We don't need synchronization as long as we store the cache last knownCacheConfigurations.put(cacheName, cacheConfiguration); knownCacheRegistries.put(cacheName, SecurityActions.getCacheComponentRegistry(cache.getAdvancedCache())); cache = cache.withMediaType(requestTypes.getKey(), requestTypes.getValue()); if (addToKnownCaches) { knownCaches.put(scopedCacheKey, cache); } // make sure we register a Migrator for this cache! tryRegisterMigrationManager(cache); } return cache; }
@Override public Flowable<K> publishKeys(Predicate<? super K> filter) { return Flowable.using(() -> { DefaultHttpRequest get = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path + "?global"); get.headers().add(HttpHeaderNames.ACCEPT, "text/plain"); get.headers().add(HttpHeaderNames.ACCEPT_CHARSET, "UTF-8"); HttpResponseHandler handler = new HttpResponseHandler(true); try { Channel ch = bootstrap.connect(configuration.host(), configuration.port()).awaitUninterruptibly().channel().pipeline().addLast( new HttpObjectAggregator(maxContentLength), handler).channel(); ch.writeAndFlush(get).sync().channel().closeFuture().sync(); BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteBufInputStream((handler.getResponse()).content()), StandardCharsets.UTF_8)); // Response can't be null now return new KeyValuePair<>(handler.getResponse(), reader); } catch (Throwable t) { FullHttpResponse response = handler.getResponse(); if (response != null) { response.release(); } throw t; } }, kvp -> Flowable.fromIterable(() -> new RestIterator(kvp, filter)), kvp -> { try { kvp.getValue().close(); } finally { kvp.getKey().release(); } }); }
void handleModification(Channel ch, ByteBuf buf) throws IOException { KeyValuePair<byte[], Boolean> pair = readKey(buf); key = pair.getKey(); if (pair.getValue()) { // If it's the end of the operation, it can only be a remove writeResponse(ch, remove()); } else { checkpoint(MemcachedDecoderState.DECODE_PARAMETERS); } }
private Events.Event createRemoteEvent(byte[] key, byte[] value, long dataVersion, CacheEntryEvent event) { // Embedded listener event implementation implements all interfaces, // so can't pattern match on the event instance itself. Instead, pattern // match on the type and the cast down to the expected event instance type switch (targetEventType) { case PLAIN: switch (event.getType()) { case CACHE_ENTRY_CREATED: case CACHE_ENTRY_MODIFIED: KeyValuePair<HotRodOperation, Boolean> responseType = getEventResponseType(event); return new Events.KeyWithVersionEvent(version, getEventId(event), responseType.getKey(), listenerId, responseType.getValue(), key, dataVersion); case CACHE_ENTRY_REMOVED: case CACHE_ENTRY_EXPIRED: responseType = getEventResponseType(event); return new Events.KeyEvent(version, getEventId(event), responseType.getKey(), listenerId, responseType.getValue(), key); default: throw log.unexpectedEvent(event); } case CUSTOM_PLAIN: KeyValuePair<HotRodOperation, Boolean> responseType = getEventResponseType(event); return new Events.CustomEvent(version, getEventId(event), responseType.getKey(), listenerId, responseType.getValue(), value); case CUSTOM_RAW: responseType = getEventResponseType(event); return new Events.CustomRawEvent(version, getEventId(event), responseType.getKey(), listenerId, responseType.getValue(), value); default: throw new IllegalArgumentException("Event type not supported: " + targetEventType); } }
@Test(dataProvider = "readWriteRemove") public void testReadWriteRemove(int capacity, int numKeys, int readerThreads, int writerThreads, int removerThreads) throws Exception { System.out.printf("Testing independent read/write/remove performance " + "with capacity %d, keys %d, readers %d, writers %d, removers %d\n", capacity, numKeys, readerThreads, writerThreads, removerThreads); generateKeyList(numKeys); Map<String, KeyValuePair<AdvancedAsyncCacheLoader, AdvancedAsyncCacheWriter>> stores = createAsyncStores(); try { for (Map.Entry<String, KeyValuePair<AdvancedAsyncCacheLoader, AdvancedAsyncCacheWriter>> e : stores.entrySet()) { mapTestReadWriteRemove(e.getKey(), e.getValue().getKey(), e.getValue().getValue(), numKeys, readerThreads, writerThreads, removerThreads); e.setValue(null); } } finally { for (Iterator<KeyValuePair<AdvancedAsyncCacheLoader, AdvancedAsyncCacheWriter>> it = stores.values().iterator(); it.hasNext(); ) { KeyValuePair<AdvancedAsyncCacheLoader, AdvancedAsyncCacheWriter> store = it.next(); try { store.getKey().stop(); store.getValue().stop(); it.remove(); } catch (Exception ex) { log.error("Failed to stop cache store", ex); } } } assertTrue("Not all stores were properly shut down", stores.isEmpty()); }
}, kvp -> { JdbcUtil.safeClose(kvp.getValue()); connectionFactory.releaseConnection(kvp.getKey()); });
@Override public Flowable<K> publishKeys(Predicate<? super K> filter) { return Flowable.using(() -> { EntityManager emStream = emf.createEntityManager(); Session session = emStream.unwrap(Session.class); Criteria criteria = session.createCriteria(configuration.entityClass()).setProjection(Projections.id()).setReadOnly(true); if (setFetchSizeMinInteger) { criteria.setFetchSize(Integer.MIN_VALUE); } ScrollableResults results = criteria.scroll(ScrollMode.FORWARD_ONLY); return new KeyValuePair<>(emStream, results); }, kvp -> { ScrollableResults results = kvp.getValue(); return Flowable.fromIterable(() -> new ScrollableResultsIterator(results, filter) ); }, kvp -> { try { kvp.getValue().close(); } finally { kvp.getKey().close(); } }); }
private MarshalledEntry deserialize(Object key, byte[] b, boolean fetchValue, boolean fetchMetadata) { try { if (b == null) return null; // We have to fetch metadata to tell if a key or entry is expired. Note this can be changed // after API changes fetchMetadata = true; KeyValuePair<Object, InternalMetadata> keyValuePair = (KeyValuePair<Object, InternalMetadata>) marshaller.objectFromByteBuffer(b); return ctx.getMarshalledEntryFactory().newMarshalledEntry(key, fetchValue ? keyValuePair.getKey() : null, fetchMetadata ? keyValuePair.getValue() : null); } catch (IOException e) { throw new CacheException(e); } catch (ClassNotFoundException e) { throw new CacheException(e); } }
public void testReadEventWithoutValue() { RemoteApplicationPublishedBridge remoteApplicationPublishedBridge = new RemoteApplicationPublishedBridge(createSpringCache()); String id = "1234"; ClientCacheEntryCustomEvent<byte[]> event = new TestEvent(id); KeyValuePair<String, Session> keyValuePair = remoteApplicationPublishedBridge.readEvent(event); assertEquals(id, keyValuePair.getKey()); assertNotNull(keyValuePair.getValue()); MapSession value = (MapSession) keyValuePair.getValue(); assertEquals(id, value.getId()); }