/** * Fetches a value from the shared cache. If values were wrapped, then they will be unwrapped * before being returned. If code requires direct access to the wrapper object as well, then this * call should not be used. * * <p>If a TransactionStats instance is passed in, then cache access stats are tracked, otherwise * - if null is passed in then stats are not tracked. * * @param key the key * @return Returns the value or <tt>null</tt> */ @SuppressWarnings("unchecked") public static <KEY extends Serializable, VAL> VAL getSharedCacheValue( SimpleCache<KEY, ValueHolder<VAL>> sharedCache, KEY key, TransactionStats stats) { final long startNanos = stats != null ? System.nanoTime() : 0; Object possibleWrapper = sharedCache.get(key); final long endNanos = stats != null ? System.nanoTime() : 0; if (possibleWrapper == null) { if (stats != null) { stats.record(startNanos, endNanos, OpType.GET_MISS); } return null; } else if (possibleWrapper instanceof ValueHolder) { if (stats != null) { stats.record(startNanos, endNanos, OpType.GET_HIT); } ValueHolder<VAL> wrapper = (ValueHolder<VAL>) possibleWrapper; return wrapper.getValue(); } else { if (stats != null) { stats.record(startNanos, endNanos, OpType.GET_MISS); } throw new IllegalStateException( "All entries for TransactionalCache must be put using TransactionalCache.putSharedCacheValue."); } }
/* * Tests the {@link MessageHelper#resetStreamCache(Message)} method */ public void testResetStreamCache() throws Exception { // should not throw exceptions when Message or message body is null MessageHelper.resetStreamCache(null); MessageHelper.resetStreamCache(message); // handle StreamCache final ValueHolder<Boolean> reset = new ValueHolder<Boolean>(Boolean.FALSE); message.setBody( new StreamCache() { @SuppressWarnings("deprecation") public void reset() { reset.set(Boolean.TRUE); } public void writeTo(OutputStream os) throws IOException { // noop } public StreamCache copy(Exchange exchange) throws IOException { return null; } public boolean inMemory() { return true; } @Override public long length() { return 0; } }); MessageHelper.resetStreamCache(message); assertTrue("Should have reset the stream cache", reset.get()); }
@Override public boolean isValid( CharSequence value, ConstraintValidatorContext constraintValidatorContext) { if (value == null || value.length() == 0) { return true; } ValueHolder values = parseUrl(value.toString()); if (values == null) { return false; } if (protocol != null && protocol.length() > 0 && !protocol.equals(values.getProtocol())) { return false; } if (host != null && host.length() > 0 && !host.equals(values.getHost())) { return false; } if (port != -1 && values.getPort() != port) { return false; } return true; }
public void doPostCommit( SimpleCache<Serializable, ValueHolder<BV>> sharedCache, Serializable key, boolean mutable, boolean allowEqualsCheck, boolean readOnly, TransactionStats stats) { ValueHolder<BV> sharedObjValueHolder = sharedCache.get(key); if (sharedObjValueHolder == null) { // Nothing has changed, write it through TransactionalCache.putSharedCacheValue(sharedCache, key, value, stats); } else if (!mutable) { // Someone else put the object there // The assumption is that the value will be correct because the values are immutable // Don't write it unnecessarily. } else if (allowEqualsCheck && EqualsHelper.nullSafeEquals(value, sharedObjValueHolder.getValue())) { // The value we want to write is the same as the one in the shared cache. // Don't write it unnecessarily. } else { // The shared value moved on in a way that was not possible to // validate. We pessimistically remove the entry. sharedCache.remove(key); } }
// Populate a pristine component to be used in state holder tests @Override protected void populateComponent(UIComponent component) { super.populateComponent(component); ValueHolder vh = (ValueHolder) component; vh.setValue("component value"); vh.setConverter(createNumberConverter()); }
@Test public void latchOnFalse() { source = new ValueHolder<Boolean>(null); latch = Latch.onFalse(source); latch.addValueChangeHandler(changeHandler); Assert.assertEquals(latch.getValue(), Boolean.TRUE); source.setValue(true); Assert.assertEquals(latch.getValue(), Boolean.TRUE); source.setValue(null); Assert.assertEquals(latch.getValue(), Boolean.TRUE); source.setValue(false); Assert.assertEquals(latch.getValue(), Boolean.FALSE); verify(changeHandler).onValueChange(argThat(new IsValueChangeEventWithValue<Boolean>(false))); source.setValue(true); Assert.assertEquals(latch.getValue(), Boolean.FALSE); latch.reset(); Assert.assertEquals(latch.getValue(), Boolean.TRUE); verify(changeHandler).onValueChange(argThat(new IsValueChangeEventWithValue<Boolean>(true))); }
public void doPostCommit( SimpleCache<Serializable, ValueHolder<BV>> sharedCache, Serializable key, boolean mutable, boolean allowEqualsCheck, boolean readOnly, TransactionStats stats) { ValueHolder<BV> sharedObjValueHolder = sharedCache.get(key); if (sharedObjValueHolder == null) { // Someone removed the value if (!mutable) { // We can assume that our value is correct because it's immutable TransactionalCache.putSharedCacheValue(sharedCache, key, value, stats); } else { // The value is mutable, so we must behave pessimistically i.e. leave the shared cache // empty } } else if (!mutable) { // We assume the configuration is correct and therefore, that we do not need to compare // the cached value with the updated value. This applies to null as well. } else if (allowEqualsCheck && EqualsHelper.nullSafeEquals(value, sharedObjValueHolder.getValue())) { // The value we want to write is the same as the one in the shared cache. // Don't write it unnecessarily. } else if (EqualsHelper.nullSafeEquals(originalValueHolder, sharedObjValueHolder)) { // The value in the cache did not change from what we observed before. // Update the value. TransactionalCache.putSharedCacheValue(sharedCache, key, value, stats); } else { // The shared value moved on in a way that was not possible to // validate. We pessimistically remove the entry. sharedCache.remove(key); } }
// Test a pristine ValueHolderBase instance @Override public void testPristine() { super.testPristine(); ValueHolder vh = (ValueHolder) component; // Validate properties assertNull("no value", vh.getValue()); assertNull("no converter", vh.getConverter()); }
private ValueHolder getSynchingUpdateWorkerTasks() { ValueHolder synching = new ValueHolder(); final List<UpdateWorkerTask> tasks = connectorUpdateService.getAllSynchingUpdateWorkerTasks(); for (UpdateWorkerTask task : tasks) { if (synching.get(task.apiKeyId) != null) synching.put(task.apiKeyId, synching.get(task.apiKeyId) + 1); else synching.put(task.apiKeyId, 1); } return synching; }
@Override public boolean remove(final String key, final String value) throws CacheAccessException { this.checkFailingKey(key); final ValueHolder<String> currentValue = this.entries.get(key); if (currentValue == null || !currentValue.value().equals(value)) { return false; } this.entries.remove(key); return true; }
public void execute(FacesContext context) { if (valueHolder.selectionSet) { ValueBinding vb = getValueBinding("selection"); if (vb != null) { vb.setValue(context, valueHolder.selection); valueHolder.selection = null; valueHolder.selectionSet = false; } } }
public void execute(FacesContext context) { if (valueHolder.activeItemSet) { ValueBinding vb = getValueBinding("activeItem"); if (vb != null) { vb.setValue(context, valueHolder.activeItem); valueHolder.activeItem = null; valueHolder.activeItemSet = false; } } }
@Override public boolean replace(final String key, final String oldValue, final String newValue) throws CacheAccessException { this.checkFailingKey(key); final ValueHolder<String> currentValue = this.entries.get(key); if (currentValue != null && currentValue.value().equals(oldValue)) { this.entries.put(key, new FakeValueHolder(newValue)); return true; } return false; }
private ValueHolder getDueUpdateWorkerWorkerTasks( final List<UpdateWorkerTask> tasks, long consumerTriggerRepeatInterval) { ValueHolder due = new ValueHolder(); for (UpdateWorkerTask task : tasks) { if (task.timeScheduled > System.currentTimeMillis() - consumerTriggerRepeatInterval) { if (due.get(task.apiKeyId) != null) due.put(task.apiKeyId, due.get(task.apiKeyId) + 1); else due.put(task.apiKeyId, 1); } } return due; }
/** * This is called when a client looks up a key which isn't contained in the grid. The grid then * calls this method to fetch the values for the keys. If a key doesn't exist in the backend then * Loader.KEY_NOT_FOUND is returned. */ @SuppressWarnings("unchecked") public List get(TxID tx, List keys, boolean arg2) throws LoaderException { LoaderMBeanImpl mbean = WXSUtils.getLoaderMBeanManager() .getBean(tx.getSession().getObjectGrid().getName(), mapName); try { mbean.getGetSizeMetrics().logTime(keys.size()); long startNS = System.nanoTime(); // Get a Data instance for these database selects Connection conn = getConnection(tx); // list for the results ArrayList<Object> rc = new ArrayList<Object>(); Iterator<Object> iter = keys.iterator(); ValueHolder v = new ValueHolder(); NamedParameterStatement s = new NamedParameterStatement(conn, selectSQL); // for each key in the list while (iter.hasNext()) { Object keyValue = iter.next(); Object value = null; // wrap with a Key object for purequery if needed if (keyAttributeColumn != null) { v._wxsutil_value = keyValue; copyPojoToStatement(s, v, keyFieldNames, keyFields); } else { copyPojoToStatement(s, keyValue, keyFieldNames, keyFields); } ResultSet rs = s.executeQuery(); if (rs.first()) { value = copyResultSetToPojo(rs, theClass, normalFields); } // if we found the value then add it otherwise add KEY_NOT_FOUND if (value != null) { rc.add(value); if (logger.isLoggable(Level.FINE)) logger.fine("Found " + keyValue + " in " + tableName + " = " + value); } else { rc.add(Loader.KEY_NOT_FOUND); if (logger.isLoggable(Level.FINE)) logger.fine("Cant find " + keyValue + " in " + tableName); } } mbean.getGetMetrics().logTime(System.nanoTime() - startNS); return rc; } catch (Exception e) { logger.log(Level.SEVERE, "Unexpected exception in get", e); mbean.getGetMetrics().logException(e); throw new LoaderException(e); } }
public void setValue(Object value) { if (value instanceof ValueHolder) { this.valueHolder = (ValueHolder) value; } else { createValueHolder(); valueHolder.value = value; setLocalValueSet(true); } }
// Test setting properties to valid values public void testPropertiesValid() throws Exception { super.testPropertiesValid(); ValueHolder vh = (ValueHolder) component; // value vh.setValue("foo.bar"); assertEquals("expected value", "foo.bar", vh.getValue()); vh.setValue(null); assertNull("erased value", vh.getValue()); // converter vh.setConverter(new LongConverter()); assertTrue("expected converter", vh.getConverter() instanceof LongConverter); vh.setConverter(null); assertNull("erased converter", vh.getConverter()); }
/** * Algorithm works as follows; - If it's an input component, submitted value is checked first * since it'd be the value to be used in case validation errors terminates jsf lifecycle - Finally * the value of the component is retrieved from backing bean and if there's a converter, converted * value is returned * * <p>- If the component is not a value holder, toString of component is used to support Facelets * UIInstructions. * * @param facesContext FacesContext instance * @param component UIComponent instance whose value will be returned * @return End text */ public static String getStringValueToRender(FacesContext facesContext, UIComponent component) { if (component instanceof ValueHolder) { if (component instanceof EditableValueHolder) { Object submittedValue = ((EditableValueHolder) component).getSubmittedValue(); if (submittedValue != null) { return submittedValue.toString(); } } ValueHolder valueHolder = (ValueHolder) component; Object value = valueHolder.getValue(); if (value == null) return ""; // first ask the converter if (valueHolder.getConverter() != null) { return valueHolder.getConverter().getAsString(facesContext, component, value); } // Try to guess else { ValueExpression expr = component.getValueExpression("value"); if (expr != null) { Class<?> valueType = expr.getType(facesContext.getELContext()); if (valueType != null) { Converter converterForType = facesContext.getApplication().createConverter(valueType); if (converterForType != null) return converterForType.getAsString(facesContext, component, value); } } } // No converter found just return the value as string return value.toString(); } else { // This would get the plain texts on UIInstructions when using Facelets String value = component.toString(); if (value != null) return value.trim(); else return ""; } }
@Test public void testNoCopyCache() { cacheManager.addCache( new Cache( new CacheConfiguration() .name(NO_COPY_CACHE) .persistence(new PersistenceConfiguration().strategy(strategy)))); Cache cache = cacheManager.getCache(NO_COPY_CACHE); ValueHolder valueHolder = new ValueHolder("value"); String key = "key"; Element element = new Element(key, valueHolder, true); cache.put(element); String otherValue = "otherValue"; valueHolder.value = otherValue; Element cacheContent = cache.get(key); assertThat(cacheContent, sameInstance(element)); assertThat(((ValueHolder) cacheContent.getObjectValue()).value, is(otherValue)); }
/** * Resolves the end text to render by using a specified value * * @param facesContext FacesContext instance * @param component UIComponent instance whose value will be returned * @return End text */ public static String getStringValueToRender( FacesContext facesContext, UIComponent component, Object value) { if (value == null) return null; ValueHolder valueHolder = (ValueHolder) component; Converter converter = valueHolder.getConverter(); if (converter != null) { return converter.getAsString(facesContext, component, value); } else { ValueExpression expr = component.getValueExpression("value"); if (expr != null) { Class<?> valueType = expr.getType(facesContext.getELContext()); Converter converterForType = facesContext.getApplication().createConverter(valueType); if (converterForType != null) return converterForType.getAsString(facesContext, component, value); } } return value.toString(); }
// Check that the properties on the specified components are equal @Override protected void checkProperties(UIComponent comp1, UIComponent comp2) { super.checkProperties(comp1, comp2); ValueHolder vh1 = (ValueHolder) comp1; ValueHolder vh2 = (ValueHolder) comp2; assertEquals(vh1.getValue(), vh2.getValue()); checkNumberConverter( (NumberConverter) vh1.getConverter(), (NumberConverter) vh2.getConverter()); }
private ToStringHelper addHolder(String name, @Nullable Object value) { ValueHolder valueHolder = addHolder(); valueHolder.value = value; valueHolder.name = checkNotNull(name); return this; }
private ToStringHelper addHolder(@Nullable Object value) { ValueHolder valueHolder = addHolder(); valueHolder.value = value; return this; }
private ValueHolder addHolder() { ValueHolder valueHolder = new ValueHolder(); holderTail = holderTail.next = valueHolder; return valueHolder; }
public String toString() { return String.valueOf(valueHolder != null ? valueHolder.getValueAsString() : value.get()); }
public void setSelection(Set selection) { createValueHolder(); valueHolder.selection = selection; valueHolder.selectionSet = true; }
public void setActiveItem(Object activeItem) { createValueHolder(); valueHolder.activeItem = activeItem; valueHolder.activeItemSet = true; }
// Test attribute-property transparency public boolean doTestAttributesTransparency(ValueHolder vh, UIComponent newComp) { assertEquals(vh.getValue(), (String) newComp.getAttributes().get("value")); vh.setValue("foo"); assertEquals("foo", (String) newComp.getAttributes().get("value")); vh.setValue(null); assertNull((String) newComp.getAttributes().get("value")); newComp.getAttributes().put("value", "bar"); assertEquals("bar", vh.getValue()); newComp.getAttributes().put("value", null); assertNull(vh.getValue()); assertEquals(vh.getConverter(), (String) newComp.getAttributes().get("converter")); vh.setConverter(new LongConverter()); assertNotNull((Converter) newComp.getAttributes().get("converter")); assertTrue(newComp.getAttributes().get("converter") instanceof LongConverter); vh.setConverter(null); assertNull(newComp.getAttributes().get("converter")); newComp.getAttributes().put("converter", new ShortConverter()); assertNotNull(vh.getConverter()); assertTrue(vh.getConverter() instanceof ShortConverter); newComp.getAttributes().put("converter", null); assertNull(vh.getConverter()); return true; }