Example usage for com.google.common.cache Cache cleanUp

List of usage examples for com.google.common.cache Cache cleanUp

Introduction

In this page you can find the example usage for com.google.common.cache Cache cleanUp.

Prototype

void cleanUp();

Source Link

Document

Performs any pending maintenance operations needed by the cache.

Usage

From source file:com.fitbur.core.el.spring.internal.ExpressionCacheProvider.java

@Override
public void dispose(Cache<String, Expression> instance) {
    instance.cleanUp();
}

From source file:com.fitbur.core.core.el.mvel.cache.TemplateCacheProvider.java

@Override
public void dispose(Cache<String, CompiledTemplate> instance) {
    instance.cleanUp();
}

From source file:com.fitbur.core.core.el.mvel.cache.ExpressionCacheProvider.java

@Override
public void dispose(Cache<String, CompiledExpression> instance) {
    instance.cleanUp();
}

From source file:com.antonjohansson.lprs.controller.spam.SpamController.java

@Override
public boolean check(String user) {
    LOG.debug("Checking spam detection for user '{}'", user);
    if (!isSpamDetectionEnabled()) {
        LOG.debug("Spam detection is disabled");
        return true;
    }/*from  w w  w  .j  av a  2  s .  c  o m*/

    Cache<Date, Object> cache = getCache().asMap().computeIfAbsent(user,
            key -> newBuilder().expireAfterWrite(expireTime, timeUnit).build());

    cache.cleanUp();
    if (cache.size() < requestCount) {
        LOG.debug("Spam detection OK!");
        cache.asMap().put(new Date(), EMPTY);
        return true;
    }

    LOG.debug("Spam detection not OK!");
    return false;
}

From source file:rickbw.incubator.cache.MultiCache.java

@Override
public final void cleanUp() {
    for (final Cache<?, ?> delegate : this.delegates.values()) {
        delegate.cleanUp();
    }/*w  ww .  ja  v  a 2 s  .  c  om*/
}

From source file:com.toro.torod.cursors.DefaultCursorManager.java

@Override
public void cleanUp() {
    withTimeout.cleanUp();/*from www . j a v  a  2  s . c  o m*/
    for (Cache<CursorId, CursorProperties> cache : oldCaches) {
        cache.cleanUp();
    }
    removeUnusedCaches();
}

From source file:com.turbospaces.spaces.SpaceReceiveAdapter.java

@Override
public void afterPropertiesSet() {
    ScheduledExecutorService scheduledExecutorService = jSpace.getSpaceConfiguration()
            .getScheduledExecutorService();
    cleaupFuture = scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
        @Override//from w w w  .  j a va2  s.c om
        public void run() {
            if (!durableTransactions.isEmpty()) {
                Collection<Cache<Long, SpaceTransactionHolder>> values = durableTransactions.values();
                for (Cache<Long, SpaceTransactionHolder> cache : values) {
                    logger.debug("running automatic cleanup of dead transaction for {}", cache);
                    cache.cleanUp();
                }
            }
        }
    }, 0, jSpace.getSpaceConfiguration().getCacheCleanupPeriod(), TimeUnit.MILLISECONDS);
}

From source file:net.minecrell.serverlistplus.core.ServerListPlusCore.java

public void executeCommand(ServerCommandSender sender, String cmd, String[] args) {
    boolean admin = sender.hasPermission(ADMIN_PERMISSION);

    if (args.length > 0) {
        String sub = Helper.toLowerCase(args[0]);

        if (!SUB_COMMANDS.contains(sub)) {
            if (admin)
                sender.sendMessage(COMMAND_PREFIX + "Unknown command. Type " + ChatFormat.DARK_GRAY
                        + "/slp help" + ChatFormat.GRAY + " for a list of available commands.");
            else//from w  w  w.  jav a  2  s.co m
                sender.sendMessage(COMMAND_PREFIX + "Unknown command.");
            return;
        }

        if (!admin)
            sender.sendMessage(COMMAND_PREFIX_ERROR + "You do not have permission for this command.");

        else if (sub.equals("reload") || sub.equals("rl")) {
            getLogger().log(INFO, "Reloading configuration at request of {}!", sender);
            sender.sendMessage(COMMAND_PREFIX + "Reloading configuration...");

            try { // Reload the configuration
                this.reload();
                sender.sendMessage(COMMAND_PREFIX_SUCCESS + "Configuration successfully reloaded!");
            } catch (ServerListPlusException e) {
                sender.sendMessage(COMMAND_PREFIX_ERROR + "An internal error occurred while reloading the "
                        + "configuration.");
            }
        } else if (sub.equals("save")) {
            getLogger().log(INFO, "Saving configuration at request of {}!", sender);
            sender.sendMessage(COMMAND_PREFIX + "Saving configuration...");

            try { // Save the configuration
                configManager.save();
                ((JSONIdentificationStorage) storage).save();
                sender.sendMessage(COMMAND_PREFIX_SUCCESS + "Configuration successfully saved.");
            } catch (ServerListPlusException e) {
                sender.sendMessage(COMMAND_PREFIX_ERROR + "An internal error occurred while saving the "
                        + "configuration.");
            }
        } else if (sub.equals("enable") || sub.equals("disable")) {
            boolean enable = sub.equalsIgnoreCase("enable");
            String tmp = enable ? "Enabling" : "Disabling";
            getLogger().log(INFO, "{} ServerListPlus at request of {}...", tmp, sender);
            sender.sendMessage(COMMAND_PREFIX + tmp + " ServerListPlus...");

            try { // Enable / disable the ServerListPlus profile
                profileManager.setEnabled(enable);
                sender.sendMessage(COMMAND_PREFIX_SUCCESS + "ServerListPlus has been successfully "
                        + (enable ? "enabled" : "disabled") + "!");
            } catch (ServerListPlusException e) {
                sender.sendMessage(COMMAND_PREFIX_ERROR + "An internal error occurred while "
                        + (enable ? "enabling" : "disabling") + " ServerListPlus.");
            }
        } else if (sub.equals("clean")) {
            if (args.length > 1) {
                String cacheName = Helper.toLowerCase(args[1]);
                Function<ServerListPlusCore, Cache<?, ?>> cacheType = CACHE_TYPES.get(cacheName);
                if (cacheType != null) {
                    Cache<?, ?> cache = cacheType.apply(this);
                    if (cache != null) {
                        getLogger().log(INFO, "Cleaning {} cache at request of {}...", cacheName, sender);
                        cache.invalidateAll();
                        cache.cleanUp();
                        getLogger().log(DEBUG, "Done.");

                        sender.sendMessage(
                                COMMAND_PREFIX_SUCCESS + "Successfully cleaned up " + cacheName + " cache.");
                    } else
                        sender.sendMessage(COMMAND_PREFIX + "The " + cacheName + " cache is currently "
                                + "disabled. There is nothing to clean up.");
                } else
                    sender.sendMessage(COMMAND_PREFIX_ERROR + "Unknown cache type. Type " + ChatFormat.DARK_RED
                            + "/slp help" + ChatFormat.RED + " for more information.");
            } else
                sender.sendMessage(COMMAND_PREFIX_ERROR + "You need to specify the cache type. Type "
                        + ChatFormat.DARK_RED + "/slp help" + ChatFormat.RED + " for more information.");
        } else if (sub.equals("help")) {
            sender.sendMessages(HELP_HEADER, buildCommandHelp("Display an information page about the plugin."),
                    buildCommandHelp("help", "Show this list of all available commands."),
                    buildCommandHelp("reload", "Reload the plugin configuration."),
                    buildCommandHelp("save", "Save the plugin configuration."),
                    buildCommandHelp("enable", "Enable the plugin and start modifying the status ping."),
                    buildCommandHelp("disable", "Disable the plugin and stop modifying the status ping."),
                    buildCommandHelp("clean", "<favicons/players>",
                            "Delete all entries from the specified " + "cache."));
        }

        return;
    }
    // Send the sender some information about the plugin
    sender.sendMessage(ChatFormat.GOLD + this.getDisplayName());
    if (info.getDescription() != null)
        sender.sendMessage(ChatFormat.GRAY + info.getDescription());
    if (info.getAuthor() != null)
        sender.sendMessage(ChatFormat.GOLD + "Author: " + ChatFormat.GRAY + info.getAuthor());
    if (info.getWebsite() != null)
        sender.sendMessage(ChatFormat.GOLD + "Website: " + ChatFormat.GRAY + info.getWebsite());

    if (admin) {
        if (info.getWiki() != null)
            sender.sendMessage(ChatFormat.GOLD + "Wiki: " + ChatFormat.GRAY + info.getWiki());
        sender.sendMessage(ChatFormat.GREEN + "Type " + ChatFormat.DARK_GREEN + "/slp help" + ChatFormat.GREEN
                + " for a list of available commands.");
    }
}

From source file:org.jasig.portal.portlets.search.SearchPortletController.java

@ActionMapping
public void performSearch(@RequestParam(value = "query") String query, ActionRequest request,
        ActionResponse response) {/*w  w  w .jav  a 2 s . com*/
    final PortletSession session = request.getPortletSession();

    final String queryId = RandomStringUtils.randomAlphanumeric(32);

    Cache<String, Boolean> searchCounterCache;
    synchronized (org.springframework.web.portlet.util.PortletUtils.getSessionMutex(session)) {
        searchCounterCache = (Cache<String, Boolean>) session.getAttribute(SEARCH_COUNTER_NAME);
        if (searchCounterCache == null) {
            searchCounterCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES)
                    .<String, Boolean>build();
            session.setAttribute(SEARCH_COUNTER_NAME, searchCounterCache);
        }
    }

    //Store the query id to track number of searches/minute
    searchCounterCache.put(queryId, Boolean.TRUE);
    if (searchCounterCache.size() > this.maximumSearchesPerMinute) {
        //Make sure old data is expired
        searchCounterCache.cleanUp();

        //Too many searches in the last minute, fail the search
        if (searchCounterCache.size() > this.maximumSearchesPerMinute) {
            response.setRenderParameter("hitMaxQueries", Boolean.TRUE.toString());
            response.setRenderParameter("query", query);
            return;
        }
    }

    // construct a new search query object from the string query
    final SearchRequest queryObj = new SearchRequest();
    queryObj.setQueryId(queryId);
    queryObj.setSearchTerms(query);

    // Create the session-shared results object
    final PortalSearchResults results = new PortalSearchResults(defaultTabKey, resultTypeMappings);

    // place the portal search results object in the session using the queryId to namespace it
    Cache<String, PortalSearchResults> searchResultsCache;
    synchronized (org.springframework.web.portlet.util.PortletUtils.getSessionMutex(session)) {
        searchResultsCache = (Cache<String, PortalSearchResults>) session
                .getAttribute(SEARCH_RESULTS_CACHE_NAME);
        if (searchResultsCache == null) {
            searchResultsCache = CacheBuilder.newBuilder().maximumSize(20)
                    .expireAfterAccess(5, TimeUnit.MINUTES).<String, PortalSearchResults>build();
            session.setAttribute(SEARCH_RESULTS_CACHE_NAME, searchResultsCache);
        }
    }
    searchResultsCache.put(queryId, results);

    // send a search query event
    response.setEvent(SearchConstants.SEARCH_REQUEST_QNAME, queryObj);
    response.setRenderParameter("queryId", queryId);
    response.setRenderParameter("query", query);
}

From source file:org.apereo.portal.portlets.search.SearchPortletController.java

@SuppressWarnings("unchecked")
@ActionMapping/*from   ww w .jav a  2 s  .c o  m*/
public void performSearch(@RequestParam(value = "query") String query, ActionRequest request,
        ActionResponse response, @RequestParam(value = "ajax", required = false) final boolean ajax)
        throws IOException {
    final PortletSession session = request.getPortletSession();

    final String queryId = RandomStringUtils.randomAlphanumeric(32);

    Cache<String, Boolean> searchCounterCache;
    synchronized (org.springframework.web.portlet.util.PortletUtils.getSessionMutex(session)) {
        searchCounterCache = (Cache<String, Boolean>) session.getAttribute(SEARCH_COUNTER_NAME);
        if (searchCounterCache == null) {
            searchCounterCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES)
                    .<String, Boolean>build();
            session.setAttribute(SEARCH_COUNTER_NAME, searchCounterCache);
        }
    }

    //Store the query id to track number of searches/minute
    searchCounterCache.put(queryId, Boolean.TRUE);
    if (searchCounterCache.size() > this.maximumSearchesPerMinute) {
        //Make sure old data is expired
        searchCounterCache.cleanUp();

        //Too many searches in the last minute, fail the search
        if (searchCounterCache.size() > this.maximumSearchesPerMinute) {
            logger.debug("Rejecting search for '{}', exceeded max queries per minute for user", query);

            if (!ajax) {
                response.setRenderParameter("hitMaxQueries", Boolean.TRUE.toString());
                response.setRenderParameter("query", query);
            } else {
                // For Ajax return to a nonexistent file to generate the 404 error since it was easier for the
                // UI to have an error response.
                final String contextPath = request.getContextPath();
                response.sendRedirect(contextPath + AJAX_MAX_QUERIES_URL);
            }
            return;
        }
    }

    // construct a new search query object from the string query
    final SearchRequest queryObj = new SearchRequest();
    queryObj.setQueryId(queryId);
    queryObj.setSearchTerms(query);

    // Create the session-shared results object
    final PortalSearchResults results = new PortalSearchResults(defaultTabKey, resultTypeMappings);

    // place the portal search results object in the session using the queryId to namespace it
    Cache<String, PortalSearchResults> searchResultsCache;
    synchronized (org.springframework.web.portlet.util.PortletUtils.getSessionMutex(session)) {
        searchResultsCache = (Cache<String, PortalSearchResults>) session
                .getAttribute(SEARCH_RESULTS_CACHE_NAME);
        if (searchResultsCache == null) {
            searchResultsCache = CacheBuilder.newBuilder().maximumSize(20)
                    .expireAfterAccess(5, TimeUnit.MINUTES).<String, PortalSearchResults>build();
            session.setAttribute(SEARCH_RESULTS_CACHE_NAME, searchResultsCache);
        }
        // Save the last queryId for an ajax autocomplete search response.
        session.setAttribute(SEARCH_LAST_QUERY_ID, queryId);
    }
    searchResultsCache.put(queryId, results);

    /*
     * TODO:  For autocomplete I wish we didn't have to go through a whole render phase just
     * to trigger the events-based features of the portlet, but atm I don't
     * see a way around it, since..
     *
     *   - (1) You can only start an event chain in the Action phase;  and
     *   - (2) You can only return JSON in a Resource phase;  and
     *   - (3) An un-redirected Action phase leads to a Render phase, not a
     *     Resource phase :(
     *
     * It would be awesome either (first choice) to do Action > Event > Resource,
     * or Action > sendRedirect() followed by a Resource request.
     *
     * As it stands, this implementation will trigger a complete render on
     * the portal needlessly.
     */

    // send a search query event
    response.setEvent(SearchConstants.SEARCH_REQUEST_QNAME, queryObj);

    logger.debug("Query initiated for queryId {}, query {}", queryId, query);
    response.setRenderParameter("queryId", queryId);
    response.setRenderParameter("query", query);

}