Search in sources :

Example 51 with Element

use of net.sf.ehcache.Element in project uPortal by Jasig.

the class SoffitConnectorController method extractResponseAndCacheIfAppropriate.

private ResponseWrapper extractResponseAndCacheIfAppropriate(final HttpResponse httpResponse, final RenderRequest req, final String serviceUrl) {
    // Extract
    final HttpEntity entity = httpResponse.getEntity();
    ResponseWrapper rslt;
    try {
        rslt = new ResponseWrapper(IOUtils.toByteArray(entity.getContent()));
    } catch (UnsupportedOperationException | IOException e) {
        throw new RuntimeException("Failed to read the response", e);
    }
    // Cache the response if indicated by the remote service
    final Header cacheControlHeader = httpResponse.getFirstHeader(Headers.CACHE_CONTROL.getName());
    if (cacheControlHeader != null) {
        final String cacheControlValue = cacheControlHeader.getValue();
        logger.debug("Soffit with serviceUrl='{}' specified cache-control header value='{}'", serviceUrl, cacheControlValue);
        if (cacheControlHeader != null) {
            switch(cacheControlValue) {
                case Headers.CACHE_CONTROL_NOCACHE:
                /*
                         * This value means we can use validation caching based on
                         * Last-Modified or ETag.  Those things aren't implemented
                         * yet, so fall through to the handling for 'no-store'.
                         */
                case Headers.CACHE_CONTROL_NOSTORE:
                    /*
                         * The value 'no-store' is the default.
                         */
                    logger.debug("Not caching response due to CacheControl directive of '{}'", cacheControlValue);
                    break;
                default:
                    /*
                         * Looks like we're using the expiration cache feature.
                         */
                    CacheTuple cacheTuple = null;
                    // TODO:  Need to find a polished utility that parses a cache-control header, or write one
                    final String[] tokens = cacheControlValue.split(",");
                    // At present, we expect all valid values to be in the form '[public|private], max-age=300'
                    if (tokens.length == 2) {
                        final String maxAge = tokens[1].trim().substring("max-age=".length());
                        int timeToLive = Integer.parseInt(maxAge);
                        if ("private".equals(tokens[0].trim())) {
                            cacheTuple = new CacheTuple(serviceUrl, req.getPortletMode().toString(), req.getWindowState().toString(), req.getRemoteUser());
                        } else if ("public".equals(tokens[0].trim())) {
                            cacheTuple = new CacheTuple(serviceUrl, req.getPortletMode().toString(), req.getWindowState().toString());
                        }
                        logger.debug("Produced cacheTuple='{}' for cacheControlValue='{}'", cacheTuple, cacheControlValue);
                        if (cacheTuple != null) {
                            final Element element = new Element(cacheTuple, rslt);
                            element.setTimeToLive(timeToLive);
                            responseCache.put(element);
                        } else {
                            logger.warn("The remote soffit specified cacheControlValue='{}', " + "but SoffitConnectorController failed to generate a cacheTuple");
                        }
                    }
                    break;
            }
        }
    }
    return rslt;
}
Also used : HttpEntity(org.apache.http.HttpEntity) Header(org.apache.http.Header) Element(net.sf.ehcache.Element) IOException(java.io.IOException)

Example 52 with Element

use of net.sf.ehcache.Element in project uPortal by Jasig.

the class MarketplaceService method getOrCreateMarketplacePortletDefinition.

@Override
public MarketplacePortletDefinition getOrCreateMarketplacePortletDefinition(IPortletDefinition portletDefinition) {
    Element element = marketplacePortletDefinitionCache.get(portletDefinition.getFName());
    if (element == null) {
        final MarketplacePortletDefinition mpd = new MarketplacePortletDefinition(portletDefinition, this, portletCategoryRegistry);
        element = new Element(portletDefinition.getFName(), mpd);
        this.marketplacePortletDefinitionCache.put(element);
    }
    return (MarketplacePortletDefinition) element.getObjectValue();
}
Also used : Element(net.sf.ehcache.Element)

Example 53 with Element

use of net.sf.ehcache.Element in project uPortal by Jasig.

the class MarketplaceService method loadMarketplaceEntriesFor.

/**
     * Load the list of marketplace entries for a user. Will load entries async. This method is
     * primarily intended for seeding data. Most impls should call browseableMarketplaceEntriesFor()
     * instead.
     *
     * <p>Note: Set is immutable since it is potentially shared between threads. If the set needs
     * mutability, be sure to consider the thread safety implications. No protections have been
     * provided against modifying the MarketplaceEntry itself, so be careful when modifying the
     * entities contained in the list.
     *
     * @param user The non-null user
     * @param categories Restricts the output to entries within the specified categories if
     *     non-empty
     * @return a Future that will resolve to a set of MarketplaceEntry objects the requested user
     *     has browse access to.
     * @throws java.lang.IllegalArgumentException if user is null
     * @since 4.2
     */
@Async
public Future<ImmutableSet<MarketplaceEntry>> loadMarketplaceEntriesFor(final IPerson user, final Set<PortletCategory> categories) {
    final IAuthorizationPrincipal principal = AuthorizationPrincipalHelper.principalFromUser(user);
    List<IPortletDefinition> allDisplayablePortletDefinitions = this.portletDefinitionRegistry.getAllPortletDefinitions();
    if (!categories.isEmpty()) {
        // Indicates we plan to restrict portlets displayed in the Portlet
        // Marketplace to those that belong to one or more specified groups.
        Element portletDefinitionsElement = marketplaceCategoryCache.get(categories);
        if (portletDefinitionsElement == null) {
            /*
                 * Collection not in cache -- need to recreate it
                 */
            // Gather the complete collection of allowable categories (specified categories & their descendants)
            final Set<PortletCategory> allSpecifiedAndDecendantCategories = new HashSet<>();
            for (PortletCategory pc : categories) {
                collectSpecifiedAndDescendantCategories(pc, allSpecifiedAndDecendantCategories);
            }
            // Filter portlets that match the criteria
            Set<IPortletDefinition> filteredPortletDefinitions = new HashSet<>();
            for (final IPortletDefinition portletDefinition : allDisplayablePortletDefinitions) {
                final Set<PortletCategory> parents = portletCategoryRegistry.getParentCategories(portletDefinition);
                for (final PortletCategory parent : parents) {
                    if (allSpecifiedAndDecendantCategories.contains(parent)) {
                        filteredPortletDefinitions.add(portletDefinition);
                        break;
                    }
                }
            }
            portletDefinitionsElement = new Element(categories, new ArrayList<>(filteredPortletDefinitions));
            marketplaceCategoryCache.put(portletDefinitionsElement);
        }
        allDisplayablePortletDefinitions = (List<IPortletDefinition>) portletDefinitionsElement.getObjectValue();
    }
    final Set<MarketplaceEntry> visiblePortletDefinitions = new HashSet<>();
    for (final IPortletDefinition portletDefinition : allDisplayablePortletDefinitions) {
        if (mayBrowsePortlet(principal, portletDefinition)) {
            final MarketplacePortletDefinition marketplacePortletDefinition = getOrCreateMarketplacePortletDefinition(portletDefinition);
            final MarketplaceEntry entry = new MarketplaceEntry(marketplacePortletDefinition, user);
            // flag whether this use can add the portlet...
            boolean canAdd = mayAddPortlet(user, portletDefinition);
            entry.setCanAdd(canAdd);
            visiblePortletDefinitions.add(entry);
        }
    }
    logger.trace("These portlet definitions {} are browseable by {}.", visiblePortletDefinitions, user);
    Future<ImmutableSet<MarketplaceEntry>> result = new AsyncResult<>(ImmutableSet.copyOf(visiblePortletDefinitions));
    Element cacheElement = new Element(user.getUserName(), result);
    marketplaceUserPortletDefinitionCache.put(cacheElement);
    return result;
}
Also used : Element(net.sf.ehcache.Element) ArrayList(java.util.ArrayList) MarketplaceEntry(org.apereo.portal.rest.layout.MarketplaceEntry) ImmutableSet(com.google.common.collect.ImmutableSet) IAuthorizationPrincipal(org.apereo.portal.security.IAuthorizationPrincipal) AsyncResult(org.springframework.scheduling.annotation.AsyncResult) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition) HashSet(java.util.HashSet) PortletCategory(org.apereo.portal.portlet.om.PortletCategory) Async(org.springframework.scheduling.annotation.Async)

Example 54 with Element

use of net.sf.ehcache.Element in project uPortal by Jasig.

the class MarketplaceService method browseableMarketplaceEntriesFor.

@Override
public ImmutableSet<MarketplaceEntry> browseableMarketplaceEntriesFor(final IPerson user, final Set<PortletCategory> categories) {
    Element cacheElement = marketplaceUserPortletDefinitionCache.get(user.getUserName());
    Future<ImmutableSet<MarketplaceEntry>> future = null;
    if (cacheElement == null) {
        // not in cache, load it and cache the results...
        future = loadMarketplaceEntriesFor(user, categories);
    } else {
        future = (Future<ImmutableSet<MarketplaceEntry>>) cacheElement.getObjectValue();
    }
    try {
        return future.get();
    } catch (InterruptedException | ExecutionException e) {
        logger.error(e.getMessage(), e);
        return ImmutableSet.of();
    }
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Element(net.sf.ehcache.Element) ExecutionException(java.util.concurrent.ExecutionException)

Example 55 with Element

use of net.sf.ehcache.Element in project uPortal by Jasig.

the class PortletEventCoordinatationService method supportsEvent.

protected boolean supportsEvent(Event event, IPortletDefinitionId portletDefinitionId) {
    final QName eventName = event.getQName();
    //The cache key to use
    final Tuple<IPortletDefinitionId, QName> key = new Tuple<IPortletDefinitionId, QName>(portletDefinitionId, eventName);
    //Check in the cache if the portlet definition supports this event
    final Element element = this.supportedEventCache.get(key);
    if (element != null) {
        final Boolean supported = (Boolean) element.getObjectValue();
        if (supported != null) {
            return supported;
        }
    }
    final PortletApplicationDefinition portletApplicationDescriptor = this.portletDefinitionRegistry.getParentPortletApplicationDescriptor(portletDefinitionId);
    if (portletApplicationDescriptor == null) {
        return false;
    }
    final Set<QName> aliases = this.getAllAliases(eventName, portletApplicationDescriptor);
    final String defaultNamespace = portletApplicationDescriptor.getDefaultNamespace();
    //No support found so far, do more complex namespace matching
    final PortletDefinition portletDescriptor = this.portletDefinitionRegistry.getParentPortletDescriptor(portletDefinitionId);
    if (portletDescriptor == null) {
        return false;
    }
    final List<? extends EventDefinitionReference> supportedProcessingEvents = portletDescriptor.getSupportedProcessingEvents();
    for (final EventDefinitionReference eventDefinitionReference : supportedProcessingEvents) {
        final QName qualifiedName = eventDefinitionReference.getQualifiedName(defaultNamespace);
        if (qualifiedName == null) {
            continue;
        }
        //Look for alias names
        if (qualifiedName.equals(eventName) || aliases.contains(qualifiedName)) {
            this.supportedEventCache.put(new Element(key, Boolean.TRUE));
            return true;
        }
        //Look for namespaced events
        if (StringUtils.isEmpty(qualifiedName.getNamespaceURI())) {
            final QName namespacedName = new QName(defaultNamespace, qualifiedName.getLocalPart());
            if (eventName.equals(namespacedName)) {
                this.supportedEventCache.put(new Element(key, Boolean.TRUE));
                return true;
            }
        }
    }
    this.supportedEventCache.put(new Element(key, Boolean.FALSE));
    return false;
}
Also used : IPortletDefinitionId(org.apereo.portal.portlet.om.IPortletDefinitionId) EventDefinitionReference(org.apache.pluto.container.om.portlet.EventDefinitionReference) PortletApplicationDefinition(org.apache.pluto.container.om.portlet.PortletApplicationDefinition) QName(javax.xml.namespace.QName) Element(net.sf.ehcache.Element) JAXBElement(javax.xml.bind.JAXBElement) Tuple(org.apereo.portal.utils.Tuple) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition) PortletDefinition(org.apache.pluto.container.om.portlet.PortletDefinition)

Aggregations

Element (net.sf.ehcache.Element)114 Test (org.junit.Test)21 CacheKey (org.apereo.portal.utils.cache.CacheKey)8 ArrayList (java.util.ArrayList)7 Date (java.util.Date)7 Cache (net.sf.ehcache.Cache)7 HashSet (java.util.HashSet)6 CacheException (net.sf.ehcache.CacheException)6 MalformedURLException (java.net.MalformedURLException)5 ConfigurationException (javax.naming.ConfigurationException)5 Ehcache (net.sf.ehcache.Ehcache)5 CacheConfiguration (net.sf.ehcache.config.CacheConfiguration)5 EntityIdentifier (org.apereo.portal.EntityIdentifier)5 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 URISyntaxException (java.net.URISyntaxException)4 SQLException (java.sql.SQLException)4 EntityExistsException (javax.persistence.EntityExistsException)4 RouteBuilder (org.apache.camel.builder.RouteBuilder)4 BaseCacheTest (org.apache.camel.component.BaseCacheTest)4