protected static Map<String, Object> prepareParams(Map<String, ?> parameterValues) { Map<String, Object> parameterValuesWithStats = new HashMap<>(parameterValues); parameterValuesWithStats.put("statics", BeansWrapper.getDefaultInstance().getStaticModels()); @SuppressWarnings("unchecked") Map<String, Object> params = LazyMap.lazyMap(parameterValuesWithStats, propertyName -> { for (String appProperty : AppContext.getPropertyNames()) { if (appProperty.replace(".", "_").equals(propertyName)) { return AppContext.getProperty(propertyName); } } return null; }); return params; }
public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); LazyMap<String, Integer> lazyMap = LazyMap.lazyMap(map, new Transformer<String, Integer>() { @Override public Integer transform(String input) { if (StringUtils.isNotBlank(input)) { return Integer.parseInt(input); } return null; } }); lazyMap.get("123"); lazyMap.get("123"); System.out.println(lazyMap.size()); lazyMap.get("12"); System.out.println(lazyMap.size()); }
/** * Usage: <code>${connectors.string['xyz']}</code> returns the first founded Value in all Connectors: * <code>connector.getString("xyz");</code>. * * @return the first founded Value in all connectors */ public Map<String, String> getString() { final Transformer<String, String> transformer = new Transformer<String, String>() { @Override public String transform(final String key) { if (key != null) { for (Connector connector : ELConnectorWrapper.this.connectors) { final String result = connector.getString(key); if (result != null) { return result; } } } return null; } }; return LazyMap.lazyMap(new HashMap<String, String>(), transformer); }
/** * Usage: <code>${connectors.content['xyz']}</code> returns the first founded Value in all Connectors: * <code>connector.getContent("xyz");</code>. * * @return the first founded Value in all connectors */ public Map<String, byte[]> getContent() { final Transformer<String, byte[]> transformer = new Transformer<String, byte[]>() { // SuppressWarnings PMD.ReturnEmptyArrayRatherThanNull: returning null for this byte-Arrays is OK. @Override @SuppressWarnings("PMD.ReturnEmptyArrayRatherThanNull") public byte[] transform(final String key) { if (key != null) { for (Connector connector : ELConnectorWrapper.this.connectors) { final byte[] result = connector.getContent(key); if (result != null) { return result; } } } return null; } }; return LazyMap.lazyMap(new HashMap<String, byte[]>(), transformer); }
/** * Usage: <code>${connectors.object['xyz']}</code> returns the first founded Value in all Connectors: * <code>connector.getObject("xyz");</code>. * * @return the first founded Value in all connectors */ public Map<String, Object> getObject() { final Transformer<String, Object> transformer = new Transformer<String, Object>() { @Override public Object transform(final String key) { if (key != null) { for (Connector connector : ELConnectorWrapper.this.connectors) { final Object result = connector.getObject(key); if (result != null) { return result; } } } return null; } }; return LazyMap.lazyMap(new HashMap<String, Object>(), transformer); }
public GetValueCommand() { EventBusManager.subscribe( WriteToStorageEvent.class, e -> { MetricStorage destination = e.storageToWriteTo().getSubStorageCalled( "commandExecution" ) .getSubStorageCalled( "get_values" ) .getSubStorageCalled( "stage-timing" ); Map<String, LongAdder> stageRuntimes = LazyMap.lazyMap( new HashMap<>(), () -> new LongAdder() ); watches.forEach( (id, watch) -> { synchronized (watch) { watch.consumeStateDurations( (stage, duration) -> { stageRuntimes.get( stage ).add( duration.toNanos() ); }); } }); stageRuntimes.forEach( (stage, time) -> { destination.store( stage, time.doubleValue() ); }); }); }
@Override public void output( Collection<Metric> metrics ) { if( metrics.size() == 0 ) { return; } Map<RetentionTable, BatchStatement> stms = LazyMap.<RetentionTable, BatchStatement>lazyMap( new HashMap<>(), () -> new BatchStatement() ); for ( Metric metric : metrics ) { insertMetricIntoBatch( metric, stms ); } KeyspaceMetadata metadata = cluster.getMetadata().getKeyspace( keyspace ); for (RetentionTable table : stms.keySet()) { createTableIfNecessary( table, metadata ); } for ( BatchStatement batch : stms.values() ) { try { session.execute( batch ); } catch ( WriteTimeoutException e ) { log.info( "WriteTimeoutException while sending Metrics to cassandra." ); log.info( e.getMessage() ); log.info( "According to http://www.datastax.com/dev/blog/how-cassandra-deals-with-replica-failure, this is harmless" ); } } EventBusManager.fire( new DrainMetricOutputEvent( ( new PersistentCassandraDrainFactory<>().handledType() ), metrics.size() ) ); }
public ThreadCountOptimizer( JSONObject config, ShouldRunOptimizerStrategy strategy ) { this.persistenceFile = Paths.get( config.getString( "persistenceFile" ) ); try ( Reader r = Files.newBufferedReader( this.persistenceFile, Charset.forName( "UTF-8" ) ) ){ JSONObject contents = new JSONObject( new JSONTokener( r ) ); this.currentOptimalPoolSize = contents.getInt( "poolsize" ); log.info( "Successfully read initial number of threads from state file ({})", this.currentOptimalPoolSize ); } catch (JSONException | IOException e) { log.warn( "Couldn't read saved value for poolsize, using initialPoolSize from config!" ); this.currentOptimalPoolSize = config.getInt( "initialPoolSize" ); } this.repeatOptimization = config.getInt( "repeat" ); this.optimizationRunCount = 0; this.averageRuntimes = LazyMap.<Integer, TotalAverageAggregation>lazyMap( new HashMap<>(), TotalAverageAggregation::new); this.strategy = strategy; this.currentlyOptimizing = false; }
/** * TestCase for {@link LazyMap#lazyMap(Map, org.apache.commons.collections4.Factory)} * and {@link MatchPatternTransformer}. * * @throws Exception if an error occurs. */ @Test public void testLazyMapMatchPattern() throws Exception { // the Map with all params Map<String, Object> context = new HashMap<String, Object>(); /* * A complex Test to parse a LazyMap and access the dynamic generated values */ context.put("test", LazyMap.lazyMap(new HashMap<String, Boolean>(), new MatchPatternTransformer("testString"))); Assert.assertTrue(((Boolean) ExpressionLanguageUtil.evaluateExpressionLanguage(// "${test['testString']}", context, Boolean.class)).booleanValue()); Assert.assertFalse(((Boolean) ExpressionLanguageUtil.evaluateExpressionLanguage(// "${test['teststring']}", context, Boolean.class)).booleanValue()); Assert.assertFalse(((Boolean) ExpressionLanguageUtil.evaluateExpressionLanguage(// "${test['tesString']}", context, Boolean.class)).booleanValue()); Assert.assertTrue(((Boolean) ExpressionLanguageUtil.evaluateExpressionLanguage(// "${test['.*String']}", context, Boolean.class)).booleanValue()); Assert.assertFalse(((Boolean) ExpressionLanguageUtil.evaluateExpressionLanguage(// "${test['.*string']}", context, Boolean.class)).booleanValue()); Assert.assertTrue(((Boolean) ExpressionLanguageUtil.evaluateExpressionLanguage(// "${test['test.*']}", context, Boolean.class)).booleanValue()); Assert.assertFalse(((Boolean) ExpressionLanguageUtil.evaluateExpressionLanguage(// "${test['askjlf.*']}", context, Boolean.class)).booleanValue()); Assert.assertFalse(((Boolean) ExpressionLanguageUtil.evaluateExpressionLanguage(// "${test['invalid Expresion: \\\\']}", context, Boolean.class)).booleanValue()); }
private CommandStateTrackerBuilder( String command, String[] substorageNames ) { clock = new AsyncClock(); watches = LazyMap.lazyMap( new HashMap<Long, StopWatchWithStates>(), () -> new StopWatchWithStates( clock ) ); eventBus = EventBusManager.getEventBus(); eventBus.subscribe( WriteToStorageEvent.class, e -> { clock.setInstant( e.when() ); MetricStorage destination = e.storageToWriteTo(); for ( String subStorageName : substorageNames ) { destination = destination.getSubStorageCalled( subStorageName ); } MetricStorage finalDestination = destination.getSubStorageCalled( command ); Map<String, LongAdder> stageRuntimes = LazyMap.lazyMap( new HashMap<>(), () -> new LongAdder() ); watches.forEach( (id, watch) -> { watch.consumeStateDurations( (stage, duration) -> { stageRuntimes.get( stage ).add( duration.toNanos() ); }); }); stageRuntimes.forEach( (stage, time) -> { finalDestination.store( stage, time.doubleValue() ); }); }); }
public StopWatchWithStates( Clock clock ) { this.watches = LazyMap.<String, Stopwatch>lazyMap( new HashMap<>(), () -> new Stopwatch( clock ) ); currentState = Optional.empty(); }
public void build() { AsyncClock clock = new AsyncClock(); Map<Long, StopWatchWithStates> watches = LazyMap.lazyMap( new HashMap<Long, StopWatchWithStates>(), () -> new StopWatchWithStates( clock ) ); EventBus eventBus = EventBusManager.getEventBus(); log.trace( eventBus ); eventBus.subscribe( ProgramStateChanged.class, e -> { log.trace( "Received ProgramStateChanged in context {} to {}.", contextIdentifier, e.contextIdentifier() ); if ( e.contextIdentifier().equals( this.contextIdentifier ) ) { clock.setInstant( e.when() ); StopWatchWithStates stopwatch = watches.get( e.threadId() ); if ( e.nextState().isPresent() ) { stopwatch.startState( e.nextState().get() ); } else { stopwatch.stop(); } } }); eventBus.subscribe( WriteToStorageEvent.class, e -> { clock.setInstant( e.when() ); MetricStorage destination = e.storageToWriteTo(); for ( String subStorageNamePart : substorageName ) { destination = destination.getSubStorageCalled( subStorageNamePart ); } MetricStorage finalDestination = destination; Map<String, LongAdder> stageRuntimes = LazyMap.lazyMap( new HashMap<>(), () -> new LongAdder() ); watches.forEach( (id, watch) -> { watch.consumeStateDurations( (stage, duration) -> { stageRuntimes.get( stage ).add( duration.toNanos() ); }); }); stageRuntimes.forEach( (stage, time) -> { finalDestination.store( stage, time.doubleValue() ); }); }); }
/** * Returns a "lazy" map whose values will be created on demand. * <p> * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. * <p> * For instance: * <pre> * Factory factory = new Factory() { * public Object create() { * return new Date(); * } * } * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory); * Object obj = lazyMap.get("test"); * </pre> * * After the above code is executed, <code>obj</code> will contain * a new <code>Date</code> instance. Furthermore, that <code>Date</code> * instance is the value for the <code>"test"</code> key in the map. * * @param <K> the key type * @param <V> the value type * @param map the map to make lazy, must not be null * @param factory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws NullPointerException if the Map or Factory is null */ public static <K, V> IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory) { return LazyMap.lazyMap(map, factory); }
/** * Returns a "lazy" map whose values will be created on demand. * <p> * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. The factory is a {@link Transformer} * that will be passed the key which it must transform into the value. * <p> * For instance: * <pre> * Transformer factory = new Transformer() { * public Object transform(Object mapKey) { * return new File(mapKey); * } * } * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory); * Object obj = lazyMap.get("C:/dev"); * </pre> * * After the above code is executed, <code>obj</code> will contain * a new <code>File</code> instance for the C drive dev directory. * Furthermore, that <code>File</code> instance is the value for the * <code>"C:/dev"</code> key in the map. * <p> * If a lazy map is wrapped by a synchronized map, the result is a simple * synchronized cache. When an object is not is the cache, the cache itself * calls back to the factory Transformer to populate itself, all within the * same synchronized block. * * @param <K> the key type * @param <V> the value type * @param map the map to make lazy, must not be null * @param transformerFactory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws NullPointerException if the Map or Transformer is null */ public static <K, V> IterableMap<K, V> lazyMap(final Map<K, V> map, final Transformer<? super K, ? extends V> transformerFactory) { return LazyMap.lazyMap(map, transformerFactory); }