[demo] / insanejava / trunk / rest-demo / src / main / java / no / brodwall / insanejava / rest / MemoryRepository.java Repository:
ViewVC logotype

View of /insanejava/trunk/rest-demo/src/main/java/no/brodwall/insanejava/rest/MemoryRepository.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 187 - (download) (as text) (annotate)
Thu Aug 30 22:15:18 2007 UTC (3 years ago) by johannes
File size: 1861 byte(s)
Decreased use of generics
package no.brodwall.insanejava.rest;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class MemoryRepository implements Repository {

    private Map<Serializable, Object> dataset = new HashMap<Serializable, Object>();

    private long nextId = 0;

    public synchronized Serializable insert(Object entity) {
        Serializable key = newKey();
        dataset.put(key, entity);
        return key;
    }

    public Object retrieve(Serializable key) {
        return dataset.get(key);
    }

    public void update(Serializable key, Object entity) {
        if (dataset.containsKey(key)) {
            dataset.put(key, entity);
        } else {
            throw new IllegalArgumentException("Unsaved object with key " + key);
        }
    }

    public void delete(Serializable key) {
        dataset.remove(key);
    }

    public void writeChanges() {
        throw new UnsupportedOperationException("If you need a session, put SessionCachedRepository in from of " + this);
    }

    public void discardChanges() {
        throw new UnsupportedOperationException("If you need a session, put SessionCachedRepository in from of " + this);
    }

    public Serializable getKey(Object entity) {
        for (Map.Entry<Serializable, Object> entry : dataset.entrySet()) {
            if (entry.getValue().equals(entity)) {
                return entry.getKey();
            }
        }
        return null;
    }

    public void insertWithKey(Serializable key, Object entity) {
        dataset.put(key, entity);
    }

    public static Repository createCachedRepository(Class<?> entityType) {
        return new SessionCachedRepository(new MemoryRepository());
    }


    protected Serializable newKey() {
        return new Long(nextId++);
    }


}

Johannes Brodwall
ViewVC Help
Powered by ViewVC 1.0.0