All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.xlcloud.rest.client.cache.EntitiesCache Maven / Gradle / Ivy

Go to download

This module provides base classes for creation of REST client (SDK). Default client has preconfigured filters, Oauth2 token injection or even object mapper.

The newest version!
/*
 * Copyright 2012 AMG.lab, a Bull Group Company
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.xlcloud.rest.client.cache;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.cache.Cache;
import javax.cache.Cache.Entry;
import javax.cache.CacheBuilder;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.xlcloud.config.ConfigParam;
import org.xlcloud.logging.LoggingUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.research.ws.wadl.HTTPMethods;

/**
 *  Implementation of cache based on Jcache
 * 
 * @author Michał Kamiński, AMG.net
 */
@ApplicationScoped
public class EntitiesCache {

    private Cache responsesCache;

    @Inject
    ObjectMapper mapper;
    
    @Inject
    @ConfigParam
    String xmsApiUri;

    public EntitiesCache() {
    }

    @PostConstruct
    public void init() {
        CacheManager manager = Caching.getCacheManager("xms-cache");
        CacheBuilder cacheBuilder = manager.createCacheBuilder("xmsObjectsCache");
        responsesCache = cacheBuilder.build();
    }

    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(EntitiesCache.class);

    /**
     * Caches response if method is different than POST and PUT and response
     * status is correct. Caching policy of entity is based on Cache-Control
     * header of response
     * 
     * @param request
     * @param authorization
     * @param response
     */
    public  T cacheResponse(WebResource request, String authorization, ClientResponse response, Class c, String method) {
        T entity = response.getEntity(c);

        byte[] entityAsBytes;
        try {
            entityAsBytes = mapper.writer().writeValueAsBytes(entity);
        } catch (IOException e) {
            LOG.error(method + " " + request.getURI() + " has problem with serialization of entity", e);
            throw new RuntimeException(e.getMessage(), e);
        }

        if (!StringUtils.equals(method, HTTPMethods.PUT.name()) && !StringUtils.equals(method, HTTPMethods.POST.name())
                && response.getStatus() < 300 && response.getStatus() >= 200) {
            List cacheContol = response.getHeaders().get("Cache-Control");
            if (cacheContol == null) {
                return entity;
            }
            boolean noCache = false;
            Long cacheTimeout = 0l;
            for (String cacheControlParam : cacheContol) {
                if (StringUtils.equals(cacheControlParam, "no-cache")) {
                    noCache = true;
                    break;
                } else if (StringUtils.contains(cacheControlParam, "max-age: ")) {
                    cacheTimeout = Long.parseLong(StringUtils.substringAfter(cacheControlParam, "max-age: "));
                }
            }

            if (noCache || cacheTimeout == null || cacheTimeout <= 0) {
                return entity;
            }
            responsesCache.put(new CacheKey(getPath(request), authorization, method),
                    new CacheObject(entityAsBytes, new Date(System.currentTimeMillis() + 1000l * cacheTimeout)));
        }
        return entity;
    }

    private String getPath(WebResource webResource) {
        return StringUtils.substringAfter(webResource.getURI().toString(), xmsApiUri);
    }

    /**
     * Retrieves from private cache entity and validates if cache entity does
     * not expired.
     * 
     * @param webResource
     * @param authorization
     * @return
     */
    public  T retrieveFromCache(WebResource webResource, String authorization, Class c, String method) {
        CacheObject cacheObject = responsesCache.get(new CacheKey(getPath(webResource), authorization, method));
        if (cacheObject != null) {
            if (!cacheObject.isObjectValid()) {
                responsesCache.remove(new CacheKey(getPath(webResource), authorization, method));
                return null;
            }
            try {
                return mapper.readValue(cacheObject.getCacheObjectBytes(), c);
            } catch (IOException e) {
                LOG.error(method + " " + LoggingUtils.maskResource(webResource.getURI().toASCIIString()) + " has problem with serialization of entity");
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        return null;
    }

    /**
     * Removes from all public caches all entities which match
     * {@link ResourceComparator}
     * 
     * @param resourceComparator
     */
    public void removeFromCache(ResourceComparator resourceComparator) {
        List entriesToRemove = new ArrayList<>();
        Iterator> entitiesIterator = responsesCache.iterator();
        while (entitiesIterator.hasNext()) {
            Entry entry = entitiesIterator.next();
            if (resourceComparator.match(entry.getKey().getPath())) {
                entriesToRemove.add(entry.getKey());
            }
        }
        for (CacheKey cacheKey : entriesToRemove) {
            LOG.debug("Removing from cace: " + cacheKey);
            responsesCache.remove(cacheKey);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy