Skip to content

Instantly share code, notes, and snippets.

@billy-bacon
Created October 22, 2013 22:11
Show Gist options
  • Save billy-bacon/7109097 to your computer and use it in GitHub Desktop.
Save billy-bacon/7109097 to your computer and use it in GitHub Desktop.
KindService with static cache
public class KindService extends BaseCacheService {
public static final String LIST = "/browse/kinds/list";
private Logger log = LoggerFactory.getLogger(KindService.class);
static List<Kind> cachedList;
@Inject
public KindService(CacheWrapper<String, Object> cache,
HttpExecutor httpExecutor,
@Named("webservice.endpoint") String hostName) {
super(cache, hostName, httpExecutor);
}
public Response<List<Kind>> list(final Integer libraryId) {
Response<List<Kind>> response = new Response<List<Kind>>();
final String cacheKey = getKindsCacheKey(libraryId);
cachedList = (List<Kind>) cache.get(cacheKey);
if (cachedList != null) {
response.setResults(cachedList);
return response;
} else {
URIBuilder builder = httpExecutor.createUriBuilder(hostName).setPath(LIST);
if (libraryId != null) builder.addParameter("libraryId", libraryId.toString());
Document document = httpExecutor.executeGet(builder);
response = MessageParser.getResponse(document.getDocumentElement());
if (response.getErrors() == null) {
final Element body = MessageParser.getBody("kinds", document);
final List<Kind> items = KindParser.parse(body);
response.setResults(items);
// update the cache
cache.put(cacheKey, items);
log.debug("fetched cached kinds list");
}
return response;
}
}
public Response<Kind> findKindForName(final String kindName, final Integer libraryId) {
Response<Kind> response = new Response<Kind>();
final String cacheKey = getKindsCacheKey(libraryId);
cachedList = (List<Kind>) cache.get(cacheKey);
// if we don't the kinds cached, we need to make a web service call...
if (cachedList == null) {
cachedList = list(libraryId).getResults();
}
for (Kind kind : cachedList) {
if (kind.getName().toUpperCase().equals(kindName.toUpperCase())) {
response.setResults(kind);
break;
}
}
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment