Example usage for java.util TreeMap putAll

List of usage examples for java.util TreeMap putAll

Introduction

In this page you can find the example usage for java.util TreeMap putAll.

Prototype

public void putAll(Map<? extends K, ? extends V> map) 

Source Link

Document

Copies all of the mappings from the specified map to this map.

Usage

From source file:org.intermine.pathquery.PathQuery.java

/**
 * A method to sort constraints by a given lists, provided to allow TemplateQuery to set a
 * specific sort order that will be preserved in a round-trip to XML.  A list of constraints
 * is provided, the constraints map is updated to reflect that order.  The list does not need
 * to contain all constraints in the query - TemplateQuery only needs to order the editable
 * constraints.//from   w ww. j  av a  2 s.c  o m
 * @param listToSortBy a list to define the new constraint order
 */
protected synchronized void sortConstraints(List<PathConstraint> listToSortBy) {
    ConstraintComparator comparator = new ConstraintComparator(listToSortBy);
    TreeMap<PathConstraint, String> orderedConstraints = new TreeMap<PathConstraint, String>(comparator);
    orderedConstraints.putAll(constraints);
    constraints = new LinkedHashMap<PathConstraint, String>(orderedConstraints);
}

From source file:org.opencms.staticexport.CmsStaticExportManager.java

/**
 * Returns a map of all export names with export name as key 
 * and the vfs folder path as value.<p>
 * /*w  ww  . j a v a 2s .c  o  m*/
 * @return a map of export names
 */

public Map<String, String> getExportnames() {

    Map<String, String> exportnames = new HashMap<String, String>();
    if (m_exportnameResources == null) {
        m_exportnameResources = Collections.unmodifiableMap(computeVfsExportnames());
        exportnames.putAll(m_exportnameResources);
    } else {
        exportnames.putAll(m_exportnameResources);
    }
    TreeMap<String, String> sortedMap = new TreeMap<String, String>(new CmsStringUtil.CmsSlashComparator());
    sortedMap.putAll(exportnames);

    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_UPDATE_EXPORTNAME_PROP_FINISHED_0));
    }
    return Collections.unmodifiableMap(sortedMap);
}

From source file:net.spfbl.core.User.java

public synchronized TreeMap<Long, Query> getQueryHeadMap(Long begin) {
    if (queryMap == null) {
        return new TreeMap<Long, Query>();
    } else if (begin == null) {
        TreeMap<Long, Query> resultMap = new TreeMap<Long, Query>();
        resultMap.putAll(queryMap);
        return resultMap;
    } else {/*from   www  . jav  a  2  s  . c  om*/
        TreeMap<Long, Query> resultMap = new TreeMap<Long, Query>();
        resultMap.putAll(queryMap.headMap(begin));
        return resultMap;
    }
}

From source file:com.sidekickApp.analytics.LocalyticsSession.java

/**
 * <p>/*www. j ava  2  s. c o  m*/
 * Within the currently open session, tags that {@code event} occurred (with optionally included attributes and dimensions).
 * </p>
 * <p>
 * Attributes: Additional key/value pairs with data related to an event. For example, let's say your app displays a dialog
 * with two buttons: OK and Cancel. When the user clicks on one of the buttons, the event might be "button clicked." The
 * attribute key might be "button_label" and the value would either be "OK" or "Cancel" depending on which button was clicked.
 * </p>
 * <p>
 * Custom dimensions: TODO
 * </p>
 * <strong>Best Practices</strong>
 * <ul>
 * <li>DO NOT use events, attributes, or dimensions to record personally identifiable information.</li>
 * <li>The best way to use events is to create all the event strings as predefined constants and only use those. This is more
 * efficient and removes the risk of collecting personal information.</li>
 * <li>Do not tag events inside loops or any other place which gets called frequently. This can cause a lot of data to be
 * stored and uploaded.</li>
 * </ul>
 *
 * @param event The name of the event which occurred. Cannot be null or empty string.
 * @param attributes The collection of attributes for this particular event. If this parameter is null or empty, then no
 *            attributes are recorded and the behavior with respect to attributes is like simply calling
 *            {@link #tagEvent(String)}. This parameter may not contain null or empty keys or values.
 * @param customDimensions A set of custom reporting dimensions. If this parameter is null or empty, then no custom dimensions
 *            are recorded and the behavior with respect to custom dimensions is like simply calling {@link #tagEvent(String)}
 *            . The number of dimensions is capped at four. If there are more than four elements, the extra elements are
 *            ignored. This parameter may not contain null or empty elements. This parameter is only used for enterprise level
 *            accounts. For non-enterprise accounts, custom dimensions will be uploaded but will not be accessible in reports
 *            until the account is upgraded to enterprise status.
 * @throws IllegalArgumentException if {@code event} is null.
 * @throws IllegalArgumentException if {@code event} is empty.
 * @throws IllegalArgumentException if {@code attributes} contains null keys, empty keys, null values, or empty values.
 * @throws IllegalArgumentException if {@code customDimensions} contains null or empty elements.
 */
public void tagEvent(final String event, final Map<String, String> attributes,
        final List<String> customDimensions) {
    if (Constants.IS_PARAMETER_CHECKING_ENABLED) {
        if (null == event) {
            throw new IllegalArgumentException("event cannot be null"); //$NON-NLS-1$
        }

        if (0 == event.length()) {
            throw new IllegalArgumentException("event cannot be empty"); //$NON-NLS-1$
        }

        if (null != attributes) {
            /*
             * Calling this with empty attributes is a smell that indicates a possible programming error on the part of the
             * caller
             */
            if (attributes.isEmpty()) {
                if (Constants.IS_LOGGABLE) {
                    Log.w(Constants.LOG_TAG, "attributes is empty.  Did the caller make an error?"); //$NON-NLS-1$
                }
            }

            if (attributes.size() > Constants.MAX_NUM_ATTRIBUTES) {
                if (Constants.IS_LOGGABLE) {
                    Log.w(Constants.LOG_TAG, String.format(
                            "attributes size is %d, exceeding the maximum size of %d.  Did the caller make an error?", //$NON-NLS-1$
                            Integer.valueOf(attributes.size()), Integer.valueOf(Constants.MAX_NUM_ATTRIBUTES)));
                }
            }

            for (final Entry<String, String> entry : attributes.entrySet()) {
                final String key = entry.getKey();
                final String value = entry.getValue();

                if (null == key) {
                    throw new IllegalArgumentException("attributes cannot contain null keys"); //$NON-NLS-1$
                }
                if (null == value) {
                    throw new IllegalArgumentException("attributes cannot contain null values"); //$NON-NLS-1$
                }
                if (0 == key.length()) {
                    throw new IllegalArgumentException("attributes cannot contain empty keys"); //$NON-NLS-1$
                }
                if (0 == value.length()) {
                    throw new IllegalArgumentException("attributes cannot contain empty values"); //$NON-NLS-1$
                }
            }
        }

        if (null != customDimensions) {
            /*
             * Calling this with empty dimensions is a smell that indicates a possible programming error on the part of the
             * caller
             */
            if (customDimensions.isEmpty()) {
                if (Constants.IS_LOGGABLE) {
                    Log.w(Constants.LOG_TAG, "customDimensions is empty.  Did the caller make an error?"); //$NON-NLS-1$
                }
            }

            if (customDimensions.size() > Constants.MAX_CUSTOM_DIMENSIONS) {
                if (Constants.IS_LOGGABLE) {
                    Log.w(Constants.LOG_TAG, String.format(
                            "customDimensions size is %d, exceeding the maximum size of %d.  Did the caller make an error?", //$NON-NLS-1$
                            Integer.valueOf(customDimensions.size()),
                            Integer.valueOf(Constants.MAX_CUSTOM_DIMENSIONS)));
                }
            }

            for (final String element : customDimensions) {
                if (null == element) {
                    throw new IllegalArgumentException("customDimensions cannot contain null elements"); //$NON-NLS-1$
                }
                if (0 == element.length()) {
                    throw new IllegalArgumentException("customDimensions cannot contain empty elements"); //$NON-NLS-1$
                }
            }
        }
    }

    final String eventString = String.format(EVENT_FORMAT, mContext.getPackageName(), event);

    if (null == attributes && null == customDimensions) {
        mSessionHandler.sendMessage(mSessionHandler.obtainMessage(SessionHandler.MESSAGE_TAG_EVENT,
                new Pair<String, Map<String, String>>(eventString, null)));
    } else {
        /*
         * Convert the attributes and custom dimensions into the internal representation of packagename:key
         */

        final TreeMap<String, String> remappedAttributes = new TreeMap<String, String>();

        if (null != attributes) {
            final String packageName = mContext.getPackageName();
            for (final Entry<String, String> entry : attributes.entrySet()) {
                remappedAttributes.put(
                        String.format(AttributesDbColumns.ATTRIBUTE_FORMAT, packageName, entry.getKey()),
                        entry.getValue());
            }
        }

        if (null != customDimensions) {
            remappedAttributes.putAll(convertDimensionsToAttributes(customDimensions));
        }

        /*
         * Copying the map is very important to ensure that a client can't modify the map after this method is called. This is
         * especially important because the map is subsequently processed on a background thread.
         *
         * A TreeMap is used to ensure that the order that the attributes are written is deterministic. For example, if the
         * maximum number of attributes is exceeded the entries that occur later alphabetically will be skipped consistently.
         */

        mSessionHandler.sendMessage(mSessionHandler.obtainMessage(SessionHandler.MESSAGE_TAG_EVENT,
                new Pair<String, Map<String, String>>(eventString,
                        new TreeMap<String, String>(remappedAttributes))));
    }
}

From source file:org.apache.hadoop.mapred.TaskTracker.java

/**
 * Close down the TaskTracker and all its components.  We must also shutdown
 * any running tasks or threads, and cleanup disk space.  A new TaskTracker
 * within the same process space might be restarted, so everything must be
 * clean./*  w  w w.ja va2 s .  c  o  m*/
 * @throws InterruptedException 
 */
public synchronized void close() throws IOException, InterruptedException {
    //
    // Kill running tasks.  Do this in a 2nd vector, called 'tasksToClose',
    // because calling jobHasFinished() may result in an edit to 'tasks'.
    //
    TreeMap<TaskAttemptID, TaskInProgress> tasksToClose = new TreeMap<TaskAttemptID, TaskInProgress>();
    tasksToClose.putAll(tasks);
    for (TaskInProgress tip : tasksToClose.values()) {
        tip.jobHasFinished(false);
    }

    this.running = false;

    // Clear local storage
    cleanupStorage();

    // Shutdown the fetcher thread
    this.mapEventsFetcher.interrupt();

    //stop the launchers
    this.mapLauncher.interrupt();
    this.reduceLauncher.interrupt();

    this.distributedCacheManager.stopCleanupThread();
    jvmManager.stop();

    // shutdown RPC connections
    RPC.stopProxy(jobClient);

    // wait for the fetcher thread to exit
    for (boolean done = false; !done;) {
        try {
            this.mapEventsFetcher.join();
            done = true;
        } catch (InterruptedException e) {
        }
    }

    if (taskReportServer != null) {
        taskReportServer.stop();
        taskReportServer = null;
    }
    if (healthChecker != null) {
        //stop node health checker service
        healthChecker.stop();
        healthChecker = null;
    }
    if (jettyBugMonitor != null) {
        jettyBugMonitor.shutdown();
        jettyBugMonitor = null;
    }
}

From source file:com.localytics.android.LocalyticsSession.java

/**
 * <p>/*from w w  w .  j av  a  2  s .  co  m*/
 * Within the currently open session, tags that {@code event} occurred (with optionally included attributes and dimensions).
 * </p>
 * <p>
 * Attributes: Additional key/value pairs with data related to an event. For example, let's say your app displays a dialog
 * with two buttons: OK and Cancel. When the user clicks on one of the buttons, the event might be "button clicked." The
 * attribute key might be "button_label" and the value would either be "OK" or "Cancel" depending on which button was clicked.
 * </p>
 * <p>
* Custom dimensions:
* (PREMIUM ONLY) Sets the value of a custom dimension. Custom dimensions are dimensions
* which contain user defined data unlike the predefined dimensions such as carrier, model, and country.
* The proper use of custom dimensions involves defining a dimension with less than ten distinct possible
* values and assigning it to one of the fogur available custom dimensions. Once assigned this definition should
* never be changed without changing the App Key otherwise old installs of the application will pollute new data.
* </p>
 * <strong>Best Practices</strong>
 * <ul>
 * <li>DO NOT use events, attributes, or dimensions to record personally identifiable information.</li>
 * <li>The best way to use events is to create all the event strings as predefined constants and only use those. This is more
 * efficient and removes the risk of collecting personal information.</li>
 * <li>Do not tag events inside loops or any other place which gets called frequently. This can cause a lot of data to be
 * stored and uploaded.</li>
 * </ul>
 *
 * @param event The name of the event which occurred. Cannot be null or empty string.
 * @param attributes The collection of attributes for this particular event. If this parameter is null or empty, then no
 *            attributes are recorded and the behavior with respect to attributes is like simply calling
 *            {@link #tagEvent(String)}. This parameter may not contain null or empty keys or values.
 * @param customDimensions A set of custom reporting dimensions. If this parameter is null or empty, then no custom dimensions
 *            are recorded and the behavior with respect to custom dimensions is like simply calling {@link #tagEvent(String)}
 *            . The number of dimensions is capped at four. If there are more than four elements, the extra elements are
 *            ignored. This parameter may not contain null or empty elements. This parameter is only used for enterprise level
 *            accounts. For non-enterprise accounts, custom dimensions will be uploaded but will not be accessible in reports
 *            until the account is upgraded to enterprise status.
 * @param customerValueIncrease Added to customer lifetime value. Try to use lowest possible unit, such as cents for US currency. 
 * @throws IllegalArgumentException if {@code event} is null.
 * @throws IllegalArgumentException if {@code event} is empty.
 * @throws IllegalArgumentException if {@code attributes} contains null keys, empty keys, null values, or empty values.
 * @throws IllegalArgumentException if {@code customDimensions} contains null or empty elements.
 */
public void tagEvent(final String event, final Map<String, String> attributes,
        final List<String> customDimensions, final long customerValueIncrease) {
    if (Constants.IS_PARAMETER_CHECKING_ENABLED) {
        if (null == event) {
            throw new IllegalArgumentException("event cannot be null"); //$NON-NLS-1$
        }

        if (0 == event.length()) {
            throw new IllegalArgumentException("event cannot be empty"); //$NON-NLS-1$
        }

        if (null != attributes) {
            /*
             * Calling this with empty attributes is a smell that indicates a possible programming error on the part of the
             * caller
             */
            if (attributes.isEmpty()) {
                if (Constants.IS_LOGGABLE) {
                    Log.w(Constants.LOG_TAG, "attributes is empty.  Did the caller make an error?"); //$NON-NLS-1$
                }
            }

            if (attributes.size() > Constants.MAX_NUM_ATTRIBUTES) {
                if (Constants.IS_LOGGABLE) {
                    Log.w(Constants.LOG_TAG, String.format(
                            "attributes size is %d, exceeding the maximum size of %d.  Did the caller make an error?", //$NON-NLS-1$
                            Integer.valueOf(attributes.size()), Integer.valueOf(Constants.MAX_NUM_ATTRIBUTES)));
                }
            }

            for (final Entry<String, String> entry : attributes.entrySet()) {
                final String key = entry.getKey();
                final String value = entry.getValue();

                if (null == key) {
                    throw new IllegalArgumentException("attributes cannot contain null keys"); //$NON-NLS-1$
                }
                if (null == value) {
                    throw new IllegalArgumentException("attributes cannot contain null values"); //$NON-NLS-1$
                }
                if (0 == key.length()) {
                    throw new IllegalArgumentException("attributes cannot contain empty keys"); //$NON-NLS-1$
                }
                if (0 == value.length()) {
                    throw new IllegalArgumentException("attributes cannot contain empty values"); //$NON-NLS-1$
                }
            }
        }

        if (null != customDimensions) {
            /*
             * Calling this with empty dimensions is a smell that indicates a possible programming error on the part of the
             * caller
             */
            if (customDimensions.isEmpty()) {
                if (Constants.IS_LOGGABLE) {
                    Log.w(Constants.LOG_TAG, "customDimensions is empty.  Did the caller make an error?"); //$NON-NLS-1$
                }
            }

            if (customDimensions.size() > Constants.MAX_CUSTOM_DIMENSIONS) {
                if (Constants.IS_LOGGABLE) {
                    Log.w(Constants.LOG_TAG, String.format(
                            "customDimensions size is %d, exceeding the maximum size of %d.  Did the caller make an error?", //$NON-NLS-1$
                            Integer.valueOf(customDimensions.size()),
                            Integer.valueOf(Constants.MAX_CUSTOM_DIMENSIONS)));
                }
            }

            for (final String element : customDimensions) {
                if (null == element) {
                    throw new IllegalArgumentException("customDimensions cannot contain null elements"); //$NON-NLS-1$
                }
                if (0 == element.length()) {
                    throw new IllegalArgumentException("customDimensions cannot contain empty elements"); //$NON-NLS-1$
                }
            }
        }
    }

    final String eventString = String.format(EVENT_FORMAT, mContext.getPackageName(), event);

    if (null == attributes && null == customDimensions) {
        mSessionHandler.sendMessage(mSessionHandler.obtainMessage(SessionHandler.MESSAGE_TAG_EVENT,
                new Triple<String, Map<String, String>, Long>(eventString, null, customerValueIncrease)));
    } else {
        /*
         * Convert the attributes and custom dimensions into the internal representation of packagename:key
         */

        final TreeMap<String, String> remappedAttributes = new TreeMap<String, String>();

        if (null != attributes) {
            final String packageName = mContext.getPackageName();
            for (final Entry<String, String> entry : attributes.entrySet()) {
                remappedAttributes.put(
                        String.format(AttributesDbColumns.ATTRIBUTE_FORMAT, packageName, entry.getKey()),
                        entry.getValue());
            }
        }

        if (null != customDimensions) {
            remappedAttributes.putAll(convertDimensionsToAttributes(customDimensions));
        }

        /*
         * Copying the map is very important to ensure that a client can't modify the map after this method is called. This is
         * especially important because the map is subsequently processed on a background thread.
         *
         * A TreeMap is used to ensure that the order that the attributes are written is deterministic. For example, if the
         * maximum number of attributes is exceeded the entries that occur later alphabetically will be skipped consistently.
         */

        mSessionHandler.sendMessage(mSessionHandler.obtainMessage(SessionHandler.MESSAGE_TAG_EVENT,
                new Triple<String, Map<String, String>, Long>(eventString,
                        new TreeMap<String, String>(remappedAttributes), customerValueIncrease)));
    }
}

From source file:org.infoglue.deliver.util.CacheController.java

public static void clearCaches(String entity, String entityId, Map<String, String> extraInformation,
        String[] cachesToSkip, boolean forceClear) throws Exception {
    Timer t = new Timer();
    //t.setActive(false);

    if (CmsPropertyHandler.getOperatingMode().equals("3")) {
        long wait = 0;
        //while(true && !getForcedCacheEvictionMode())
        while (!forceClear && !getForcedCacheEvictionMode()
                && RequestAnalyser.getRequestAnalyser().getNumberOfActiveRequests() > 0) {
            logger.info(//  w w w . j  a va2 s  .co m
                    "Number of requests: " + RequestAnalyser.getRequestAnalyser().getNumberOfCurrentRequests()
                            + " was more than 0 - lets wait a bit.");
            if (wait > 1000) {
                logger.warn("The clearCache method waited over " + ((wait * 10) / 1000)
                        + " seconds but there seems to be "
                        + RequestAnalyser.getRequestAnalyser().getNumberOfCurrentRequests()
                        + " requests blocking all the time. Continuing anyway.");
                //printThreads();
                break;
            }

            if (wait > 100)
                setForcedCacheEvictionMode(true);

            Thread.sleep(10);
            wait++;
        }
    }

    logger.info("clearCaches start in " + CmsPropertyHandler.getContextRootPath());
    if (entity == null) {
        logger.info("Clearing the caches");
        //synchronized(caches)
        //{
        for (Iterator i = caches.entrySet().iterator(); i.hasNext();) {
            Map.Entry e = (Map.Entry) i.next();
            logger.info("e:" + e.getKey());
            boolean skip = false;
            if (cachesToSkip != null) {
                for (int index = 0; index < cachesToSkip.length; index++) {
                    if (e.getKey().equals(cachesToSkip[index])) {
                        skip = true;
                        break;
                    }
                }
            }

            if (!skip) {
                Object object = e.getValue();
                if (object instanceof Map) {
                    Map cacheInstance = (Map) e.getValue();
                    synchronized (cacheInstance) {
                        cacheInstance.clear();
                    }
                } else {
                    GeneralCacheAdministrator cacheInstance = (GeneralCacheAdministrator) e.getValue();
                    synchronized (cacheInstance) {
                        cacheInstance.flushAll();
                    }
                }
                logger.info("Cleared cache:" + e.getKey());

                i.remove();
            }
        }
        //}
    } else if (entity.equalsIgnoreCase("CacheNames")) {
        String[] cacheNames = entityId.split(",");
        for (int i = 0; i < cacheNames.length; i++) {
            String cacheName = cacheNames[i];
            CacheController.clearCache(cacheName);
        }
    } else {
        logger.info("Clearing some caches");
        logger.info("entity:" + entity);

        String useSelectivePageCacheUpdateString = CmsPropertyHandler.getUseSelectivePageCacheUpdate();
        boolean useSelectivePageCacheUpdate = false;
        if (useSelectivePageCacheUpdateString != null
                && useSelectivePageCacheUpdateString.equalsIgnoreCase("true"))
            useSelectivePageCacheUpdate = true;

        String operatingMode = CmsPropertyHandler.getOperatingMode();

        TreeMap<String, Object> orderedCaches = new TreeMap<String, Object>(new CacheComparator());
        orderedCaches.putAll(caches);

        /*
        for (String key : orderedCaches.keySet()) 
        {
          System.out.println("key:" + key);
        }
        */
        //t.printElapsedTime("Start cache eviction");
        RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Start cache eviction",
                t.getElapsedTime());
        //t.printElapsedTime("START cachesLoop:" + entity + ":" + entityId);

        //synchronized(caches)
        //{
        //for (Iterator i = caches.entrySet().iterator(); i.hasNext(); ) 
        cachesLoop: for (Iterator i = orderedCaches.entrySet().iterator(); i.hasNext();) {
            RequestAnalyser.getRequestAnalyser().registerComponentStatistics("cache iteration top",
                    t.getElapsedTime());

            Map.Entry e = (Map.Entry) i.next();
            logger.info("e:" + e.getKey());

            boolean clear = false;
            boolean selectiveCacheUpdate = false;
            String cacheName = e.getKey().toString();

            if (cachesToSkip != null) {
                for (int index = 0; index < cachesToSkip.length; index++) {
                    if (cacheName.equals(cachesToSkip[index])) {
                        continue cachesLoop;
                    }
                }
            }

            //t.printElapsedTime("clearCaches 3");

            if (cacheName.equalsIgnoreCase("serviceDefinitionCache") && entity.indexOf("ServiceBinding") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("qualifyerListCache")
                    && (entity.indexOf("Qualifyer") > 0 || entity.indexOf("ServiceBinding") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("availableServiceBindingCache")
                    && entity.indexOf("AvailableServiceBinding") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("categoriesCache") && entity.indexOf("Category") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("repositoryCache") && entity.indexOf("Repository") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("languageCache") && entity.indexOf("Language") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("localeCache") && entity.indexOf("Language") > 0) {
                clear = true;
            }
            if ((cacheName.equalsIgnoreCase("latestSiteNodeVersionCache")
                    || cacheName.equalsIgnoreCase("pageCacheLatestSiteNodeVersions")
                    || cacheName.equalsIgnoreCase("pageCacheSiteNodeTypeDefinition"))
                    && entity.indexOf("SiteNode") > 0) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if ((cacheName.equalsIgnoreCase("parentSiteNodeCache")
                    || cacheName.equalsIgnoreCase("pageCacheParentSiteNodeCache"))
                    && entity.indexOf("SiteNode") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("NavigationCache")
                    && (entity.indexOf("SiteNode") > 0 || entity.indexOf("Content") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("pagePathCache")
                    && (entity.indexOf("SiteNode") > 0 || entity.indexOf("Content") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("componentEditorCache")
                    && (entity.indexOf("SiteNode") > 0 || entity.indexOf("Content") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("componentEditorVersionIdCache")
                    && (entity.indexOf("SiteNode") > 0 || entity.indexOf("Content") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("masterLanguageCache")
                    && (entity.indexOf("Repository") > 0 || entity.indexOf("Language") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("parentRepository") && entity.indexOf("Repository") > 0) {
                clear = true;
            }
            if (cacheName.startsWith("contentAttributeCache") && (entity.indexOf("Content") > -1
                    || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                    || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.startsWith("metaInfoContentAttributeCache") && entity.indexOf("Content") > -1) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("contentVersionCache") && (entity.indexOf("Content") > -1
                    || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                    || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.startsWith("contentVersionIdCache") && (entity.indexOf("Content") > -1
                    || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                    || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("referencingPagesCache")
                    && (entity.indexOf("ContentVersion") > -1 || entity.indexOf("Qualifyer") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("boundSiteNodeCache") && (entity.indexOf("ServiceBinding") > 0
                    || entity.indexOf("Qualifyer") > 0 || entity.indexOf("SiteNodeVersion") > 0
                    || entity.indexOf("SiteNodeVersion") > 0 || entity.indexOf("SiteNode") > 0
                    || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                    || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("boundContentCache") && (entity.indexOf("ServiceBinding") > 0
                    || entity.indexOf("Qualifyer") > 0 || entity.indexOf("SiteNodeVersion") > 0
                    || entity.indexOf("ContentVersion") > 0 || entity.indexOf("Content") > 0
                    || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                    || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
            }
            if (cacheName.startsWith("pageCache") && entity.indexOf("Registry") == -1) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.startsWith("pageCacheExtra") && entity.indexOf("Registry") == -1) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("componentCache") && entity.indexOf("Registry") == -1) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("componentPropertyCache")
                    && (entity.indexOf("SiteNode") > -1 || entity.indexOf("ContentVersion") > -1
                            || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                //selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("componentPropertyVersionIdCache")
                    && (entity.indexOf("SiteNode") > -1 || entity.indexOf("ContentVersion") > -1
                            || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                //selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("componentPropertyCacheRepoGroups")
                    && (entity.indexOf("SiteNode") > -1 || entity.indexOf("ContentVersion") > -1
                            || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                if (entity.indexOf("SiteNode") > -1 || entity.indexOf("ContentVersion") > -1)
                    selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("componentPropertyVersionIdCacheRepoGroups")
                    && (entity.indexOf("SiteNode") > -1 || entity.indexOf("ContentVersion") > -1
                            || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                if (entity.indexOf("SiteNode") > -1 || entity.indexOf("ContentVersion") > -1)
                    selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("pageComponentsCache") && (entity.indexOf("ContentVersion") > -1
                    || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                    || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                //selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("includeCache")) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("authorizationCache") && (entity.indexOf("AccessRight") > 0
                    || entity.indexOf("SystemUser") > 0 || entity.indexOf("Role") > 0
                    || entity.indexOf("Group") > 0 || entity.indexOf("Intercept") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("personalAuthorizationCache") && (entity.indexOf("AccessRight") > 0
                    || entity.indexOf("SystemUser") > 0 || entity.indexOf("Role") > 0
                    || entity.indexOf("Group") > 0 || entity.indexOf("Intercept") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("componentPaletteDivCache")
                    && (entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("userCache")
                    && (entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("principalCache") && (entity.indexOf("SystemUser") > 0
                    || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
            }
            if ((cacheName.equalsIgnoreCase("assetUrlCache")
                    || cacheName.equalsIgnoreCase("assetUrlCacheWithGroups")
                    || cacheName.equalsIgnoreCase("assetThumbnailUrlCache"))
                    && (entity.indexOf("DigitalAsset") > 0 || entity.indexOf("ContentVersion") > 0
                            || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                if (cacheName.equalsIgnoreCase("assetUrlCacheWithGroups")
                        && (entity.indexOf("ContentVersion") > -1 || entity.indexOf("DigitalAsset") > -1))
                    selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("digitalAssetCache")
                    && (entity.indexOf("DigitalAsset") > 0 || entity.indexOf("ContentVersion") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("sortedChildContentsCache")
                    && (entity.indexOf("Content") > 0 || entity.indexOf("ContentVersion") > 0
                            || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("childContentCache")
                    && (entity.indexOf("Content") > 0 || entity.indexOf("ContentVersion") > 0
                            || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("matchingContentsCache")
                    && (entity.indexOf("Content") > 0 || entity.indexOf("ContentVersion") > 0
                            || entity.indexOf("AccessRight") > 0 || entity.indexOf("SystemUser") > 0
                            || entity.indexOf("Role") > 0 || entity.indexOf("Group") > 0)) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("workflowCache") && entity.indexOf("WorkflowDefinition") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("rootSiteNodeCache") && entity.indexOf("SiteNode") > 0) {
                if (CmsPropertyHandler.getOperatingMode().equals("0"))
                    clear = true;
            }
            if ((cacheName.equalsIgnoreCase("siteNodeCache") || cacheName.equalsIgnoreCase("siteNodeVOCache"))
                    && entity.indexOf("SiteNode") > 0) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("contentCache") && entity.indexOf("Content") > 0) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("rootContentCache") && entity.indexOf("Content") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("componentContentsCache") && entity.indexOf("Content") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("childSiteNodesCache")
                    && (entity.indexOf("SiteNode") > 0 || entity.indexOf("ContentVersion") > 0)) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("childPagesCache")
                    && (entity.indexOf("SiteNode") > 0 || entity.indexOf("Content") > 0)) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("siteNodeCacheWithLatestVersion")
                    && entity.indexOf("SiteNode") > 0) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("propertySetCache") && entity.indexOf("SiteNode") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("groupVOListCache") && entity.indexOf("Group") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("roleListCache") && entity.indexOf("Role") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("groupPropertiesCache")
                    && (entity.indexOf("Group") > 0 || entity.indexOf("PropertiesCategory") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("propertiesCategoryCache")
                    && (entity.indexOf("Group") > 0 || entity.indexOf("Role") > 0 || entity.indexOf("User") > 0
                            || entity.indexOf("PropertiesCategory") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("rolePropertiesCache") && entity.indexOf("Role") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("principalPropertyValueCache") && (entity.indexOf("Group") > 0
                    || entity.indexOf("Role") > 0 || entity.indexOf("User") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("relatedCategoriesCache")
                    && (entity.indexOf("Group") > 0 || entity.indexOf("Role") > 0 || entity.indexOf("User") > 0
                            || entity.indexOf("PropertiesCategory") > 0)) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("categoryCache") && entity.indexOf("Category") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("contentCategoryCache") && entity.indexOf("ContentVersion") > 0) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("redirectCache") && entity.indexOf("Redirect") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("interceptorsCache") && entity.indexOf("Intercept") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("interceptionPointCache") && entity.indexOf("Intercept") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("siteNodeLanguageCache") && (entity.indexOf("Repository") > 0
                    || entity.indexOf("Language") > 0 || entity.indexOf("SiteNode") > 0)) {
                clear = true;
                selectiveCacheUpdate = true;
            }
            if (cacheName.equalsIgnoreCase("contentTypeDefinitionCache")
                    && entity.indexOf("ContentTypeDefinition") > 0) {
                clear = true;
            }
            if (cacheName.equalsIgnoreCase("ServerNodeProperties")) {
                clear = true;
            }

            if (!cacheName.equalsIgnoreCase("serverNodePropertiesCache")
                    && entity.equalsIgnoreCase("ServerNodeProperties")) {
                clear = true;
            }
            if (!cacheName.equalsIgnoreCase("encodedStringsCache")
                    && entity.equalsIgnoreCase("ServerNodeProperties")) {
                clear = true;
            }

            if (logger.isInfoEnabled())
                logger.info("clear:" + clear);

            if (clear) {
                if (logger.isInfoEnabled())
                    logger.info("clearing:" + e.getKey());

                Object object = e.getValue();

                String sentContentId = null;
                String sentParentContentId = null;
                String sentSiteNodeId = null;
                String sentParentSiteNodeId = null;
                String sentRepositoryId = null;
                String sentContentTypeDefinitionId = null;
                String sentContentIsProtected = null;
                if (extraInformation != null) {
                    sentContentId = extraInformation.get("contentId");
                    sentParentContentId = extraInformation.get("parentContentId");
                    sentSiteNodeId = extraInformation.get("siteNodeId");
                    sentParentSiteNodeId = extraInformation.get("parentSiteNodeId");
                    sentRepositoryId = extraInformation.get("repositoryId");
                    sentContentTypeDefinitionId = extraInformation.get("contentTypeDefinitionId");
                    sentContentIsProtected = extraInformation.get("contentIsProtected");
                }

                //System.out.println("sentContentId:" + sentContentId);
                //System.out.println("sentParentContentId:" + sentParentContentId);
                //System.out.println("sentSiteNodeId:" + sentSiteNodeId);
                //System.out.println("sentParentSiteNodeId:" + sentParentSiteNodeId);
                //System.out.println("sentRepositoryId:" + sentRepositoryId);

                if (object instanceof Map) {
                    Map cacheInstance = (Map) e.getValue();
                    synchronized (cacheInstance) {
                        if (cacheName.equals("componentContentsCache")) {
                            try {
                                if (entity.indexOf("ContentVersion") > 0) {
                                    String contentId = sentContentId;
                                    String contentTypeDefinitionId = sentContentTypeDefinitionId;
                                    if (contentId == null || contentId.equals("")) {
                                        try {
                                            contentId = "" + ContentVersionController
                                                    .getContentVersionController()
                                                    .getContentIdForContentVersion(new Integer(entityId));
                                        } catch (Exception e2) {
                                            logger.info("Error loading content with id " + entityId + ":"
                                                    + e2.getMessage());
                                        }
                                    }

                                    if (contentId != null) {
                                        //ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); 
                                        if (contentTypeDefinitionId != null
                                                && !contentTypeDefinitionId.equals("")) {
                                            ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController
                                                    .getController().getContentTypeDefinitionVOWithId(
                                                            new Integer(contentTypeDefinitionId));
                                            if (ctdVO.getName().equals("HTMLTemplate")
                                                    || ctdVO.getName().equals("PagePartTemplate")) {
                                                ComponentController.getController()
                                                        .reIndexComponentContentsDelayed(
                                                                new Integer(contentId));
                                            }
                                        } else
                                            logger.info("No content type for " + contentId);
                                    }
                                } else
                                    logger.info("skipping clearing components as it seems stupid");
                            } catch (Exception e2) {
                                logger.warn("Error clearing componentContentsCache:" + e2.getMessage(), e2);
                            }
                        } else if (!(cacheName.equals("userAccessCache") && cacheInstance.size() < 100)) {
                            logger.info(
                                    "clearing ordinary map:" + e.getKey() + " (" + cacheInstance.size() + ")");
                            cacheInstance.clear();
                        } else
                            logger.info("skipping clearing this as it seems stupid");
                    }
                } else {
                    GeneralCacheAdministrator cacheInstance = (GeneralCacheAdministrator) e.getValue();
                    synchronized (cacheInstance) //Back
                    {
                        //t.printElapsedTime("START:" + entity + ":" + entityId);
                        //ADD logic to flush correct on sitenode and sitenodeversion
                        /*
                        if(selectiveCacheUpdate && entity.indexOf("SiteNode") > 0)
                        {
                           cacheInstance.flushAll();
                           eventListeners.remove(cacheName + "_cacheEntryEventListener");
                           eventListeners.remove(cacheName + "_cacheMapAccessEventListener");
                           logger.info("clearing:" + e.getKey());
                        }
                        */
                        //System.out.println("entity:" + entity);
                        if (entity.indexOf("pageCache") == 0) {
                            if (entity.indexOf("pageCache:") == 0) {
                                String groupQualifyer = entity.substring("pageCache:".length());
                                logger.info(
                                        "CacheController: This is a application pageCache-clear request... specific:"
                                                + groupQualifyer);
                                logger.info("clearing " + e.getKey() + " : " + groupQualifyer);

                                PageCacheHelper.getInstance().notify("" + groupQualifyer);
                                /*
                                if(cacheName.equals("pageCacheExtra"))
                                {
                                   clearFileCacheForGroup(cacheInstance, "" + groupQualifyer);
                                }
                                else if(cacheName.equals("pageCache"))
                                {
                                   cacheInstance.flushGroup("" + groupQualifyer);                               
                                }
                                */
                            } else {
                                PageCacheHelper.getInstance().notify("selectiveCacheUpdateNonApplicable");
                                /*
                                 logger.error("clearing " + e.getKey() + " selectiveCacheUpdateNonApplicable");
                                 if(cacheName.equals("pageCacheExtra"))
                                 {
                                    clearFileCacheForGroup(cacheInstance, "selectiveCacheUpdateNonApplicable");
                                 }
                                 else if(cacheName.equals("pageCache"))
                                 {
                                    cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");                               
                                 }
                                 */
                            }
                        }

                        if (selectiveCacheUpdate && entity.indexOf("Repository") > 0
                                && useSelectivePageCacheUpdate) {
                            if (cacheName.equals("pageCacheExtra")) {
                                PageCacheHelper.getInstance().notify("repository_" + entityId);
                                PageCacheHelper.getInstance().notify("selectiveCacheUpdateNonApplicable");
                            } else {
                                cacheInstance.flushGroup("repository_" + entityId);
                                cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");
                            }

                            /*
                            logger.info("clearing " + e.getKey() + " with group " + "repository_" + entityId);
                            if(cacheName.equals("pageCacheExtra"))
                            {
                               clearFileCacheForGroup(cacheInstance, "repository_" + entityId);
                               clearFileCacheForGroup(cacheInstance, "selectiveCacheUpdateNonApplicable");
                            }
                            else
                            {
                               cacheInstance.flushGroup("repository_" + entityId);
                               cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");                               
                            }
                            */
                        } else if (selectiveCacheUpdate && entity.indexOf("SiteNodeVersion") > 0) {
                            //Thread.dumpStack();
                            //How to solve this good
                            if (CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("0")) {
                                if (cacheName.equals("pageCacheExtra")) {
                                    PageCacheHelper.getInstance().notify("siteNodeVersion_" + entityId);
                                    PageCacheHelper.getInstance().notify("selectiveCacheUpdateNonApplicable");

                                    //clearFileCacheForGroup(cacheInstance, "siteNodeVersion_" + entityId);
                                    //clearFileCacheForGroup(cacheInstance, "selectiveCacheUpdateNonApplicable");
                                } else {
                                    cacheInstance.flushGroup("siteNodeVersion_" + entityId);
                                    cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");
                                }
                                logger.info("clearing " + e.getKey() + " with group " + "siteNodeVersion_"
                                        + entityId);

                                try {
                                    logger.info("BeforesiteNodeVersionVO...");

                                    String siteNodeId = sentSiteNodeId;
                                    String repositoryId = sentRepositoryId;
                                    String parentSiteNodeId = sentParentSiteNodeId;
                                    //System.out.println("siteNodeId:" + siteNodeId);
                                    //System.out.println("repositoryId:" + repositoryId);
                                    //System.out.println("parentSiteNodeId:" + parentSiteNodeId);
                                    if (siteNodeId == null || siteNodeId.equals("")) {
                                        try {
                                            SiteNodeVersionVO snvVO = SiteNodeVersionController.getController()
                                                    .getSiteNodeVersionVOWithId(new Integer(entityId));
                                            siteNodeId = "" + snvVO.getSiteNodeId();
                                            if (repositoryId == null) {
                                                SiteNodeVO snVO = SiteNodeController.getController()
                                                        .getSiteNodeVOWithId(snvVO.getSiteNodeId());
                                                repositoryId = "" + snVO.getRepositoryId();
                                                parentSiteNodeId = "" + snVO.getParentSiteNodeId();
                                            }
                                        } catch (Exception e2) {
                                            logger.info("Error getting siteNodeVersion " + entityId);
                                        }
                                    }

                                    if (siteNodeId != null) {
                                        logger.info("Before flushGroup2...");
                                        if (cacheName.equals("pageCacheExtra")) {
                                            PageCacheHelper.getInstance().notify("siteNode_" + siteNodeId);
                                            //clearFileCacheForGroup(cacheInstance, "siteNode_" + siteNodeId);
                                        } else {
                                            cacheInstance.flushGroup("siteNode_" + siteNodeId);
                                            cacheInstance.flushGroup("" + siteNodeId);
                                        }

                                        if (siteNodeId != null && (cacheName.equals("childSiteNodesCache")
                                                || cacheName.equals("childPagesCache")
                                                || cacheName.equals("siteNodeCache")
                                                || cacheName.equals("componentPropertyCacheRepoGroups")
                                                || cacheName
                                                        .equals("componentPropertyVersionIdCacheRepoGroups"))) {
                                            if (cacheName.equals("componentPropertyCacheRepoGroups")
                                                    || cacheName.equals(
                                                            "componentPropertyVersionIdCacheRepoGroups")) {
                                                cacheInstance.flushGroup("" + repositoryId);
                                                logger.info(
                                                        "Clearing componentPropertyCacheRepoGroups for repo:"
                                                                + repositoryId);
                                            }
                                            if (parentSiteNodeId != null) {
                                                cacheInstance.flushGroup("siteNode_" + parentSiteNodeId);
                                                cacheInstance.flushGroup("" + parentSiteNodeId);
                                                cacheInstance.flushEntry("" + parentSiteNodeId);
                                                logger.info("Clearing for:" + parentSiteNodeId);
                                            }
                                        }

                                        logger.info("After flushGroup2...");
                                    }
                                } catch (Exception se) {
                                    logger.warn("Missing siteNode version: " + se.getMessage(), se);
                                }
                            } else {
                                try {
                                    if ((cacheName.equals("childSiteNodesCache")
                                            || cacheName.equals("childPagesCache")
                                            || cacheName.equals("siteNodeCache")
                                            || cacheName.equals("componentPropertyCacheRepoGroups")
                                            || cacheName.equals("componentPropertyVersionIdCacheRepoGroups"))) {
                                        SiteNodeVersionVO snvVO = SiteNodeVersionController.getController()
                                                .getSiteNodeVersionVOWithId(new Integer(entityId));
                                        SiteNodeVO snVO = SiteNodeController.getController()
                                                .getSiteNodeVOWithId(snvVO.getSiteNodeId());

                                        Integer repositoryId = snVO.getRepositoryId();
                                        Integer parentSiteNodeId = snVO.getParentSiteNodeId();

                                        if (cacheName.equals("componentPropertyCacheRepoGroups") || cacheName
                                                .equals("componentPropertyVersionIdCacheRepoGroups")) {
                                            cacheInstance.flushGroup("" + repositoryId);
                                            logger.info("Clearing componentPropertyCacheRepoGroups for repo:"
                                                    + repositoryId);
                                        }
                                        if (parentSiteNodeId != null) {
                                            cacheInstance.flushGroup("siteNode_" + parentSiteNodeId);
                                            cacheInstance.flushGroup("" + parentSiteNodeId);
                                            cacheInstance.flushEntry("" + parentSiteNodeId);
                                            logger.info("Clearing for:" + parentSiteNodeId);
                                        }
                                    }
                                } catch (Exception e2) {
                                    logger.error(
                                            "Problem clearing cache for site node version:" + e2.getMessage(),
                                            e2);
                                }
                            }
                        } else if (selectiveCacheUpdate
                                && (entity.indexOf("SiteNode") > 0
                                        && entity.indexOf("SiteNodeTypeDefinition") == -1)
                                && useSelectivePageCacheUpdate) {
                            //System.out.println("Entity: " + entity);
                            logger.info("Flushing " + "" + entityId);
                            logger.info("Flushing " + "siteNode_" + entityId);
                            logger.info("Flushing " + "selectiveCacheUpdateNonApplicable");

                            if (cacheName.equals("pageCacheExtra")) {
                                PageCacheHelper.getInstance().notify("siteNode_" + entityId);
                                PageCacheHelper.getInstance().notify("selectiveCacheUpdateNonApplicable");

                                //clearFileCacheForGroup(cacheInstance, "siteNode_" + entityId);
                                //clearFileCacheForGroup(cacheInstance, "selectiveCacheUpdateNonApplicable");
                            } else {
                                cacheInstance.flushEntry("" + entityId);
                                cacheInstance.flushGroup("" + entityId);
                                cacheInstance.flushGroup("siteNode_" + entityId);
                                cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");

                                if (cacheName.equals("childSiteNodesCache")
                                        || cacheName.equals("childPagesCache")
                                        || cacheName.equals("siteNodeCache")
                                        || cacheName.equals("componentPropertyCacheRepoGroups")
                                        || cacheName.equals("componentPropertyVersionIdCacheRepoGroups")) {
                                    logger.info("Flushing parent also");

                                    String repositoryId = sentRepositoryId;
                                    String parentSiteNodeId = sentParentSiteNodeId;
                                    try {
                                        if (repositoryId == null) {
                                            SiteNodeVO snVO = SiteNodeController.getController()
                                                    .getSiteNodeVOWithId(new Integer(entityId));
                                            if (snVO != null) {
                                                repositoryId = "" + snVO.getRepositoryId();
                                                parentSiteNodeId = "" + snVO.getParentSiteNodeId();
                                            }
                                        }
                                        if (cacheName.equals("componentPropertyCacheRepoGroups") || cacheName
                                                .equals("componentPropertyVersionIdCacheRepoGroups")) {
                                            cacheInstance.flushGroup("" + repositoryId);
                                            logger.info("Clearing componentPropertyCacheRepoGroups for repo:"
                                                    + repositoryId);
                                        }

                                        if (parentSiteNodeId != null && !parentSiteNodeId.equals("")) {
                                            logger.info("Flushing " + "" + entityId);
                                            logger.info("Flushing " + "siteNode_" + entityId);

                                            cacheInstance.flushGroup("siteNode_" + parentSiteNodeId);
                                            cacheInstance.flushGroup("" + parentSiteNodeId);
                                            cacheInstance.flushEntry("" + parentSiteNodeId);
                                            logger.info("Clearing for:" + parentSiteNodeId);
                                        }
                                    } catch (SystemException se) {
                                        logger.warn("Missing siteNode: " + se.getMessage(), se);
                                    }
                                }
                            }

                            logger.info("clearing " + e.getKey() + " with group " + "siteNode_" + entityId);
                        } else if (selectiveCacheUpdate && entity.indexOf("ContentVersion") > 0
                                && useSelectivePageCacheUpdate) {
                            //t.printElapsedTime("CV start....");
                            logger.info("ContentVersion entity was sent: " + entity + ":" + entityId
                                    + " and cacheName:" + cacheName);

                            logger.info("Getting eventListeners...");
                            //Object cacheEntryEventListener = eventListeners.get(e.getKey() + "_cacheEntryEventListener");
                            //Object cacheMapAccessEventListener = eventListeners.get(e.getKey() + "_cacheMapAccessEventListener");

                            //System.out.println("entity:" + entity);

                            //System.out.println("Before flushGroup:" +cacheName);
                            logger.info("Before flushGroup...");
                            if (cacheName.equals("pageCacheExtra")) {
                                //clearFileCacheForGroup(cacheInstance, "contentVersion_" + entityId);
                                //clearFileCacheForGroup(cacheInstance, "selectiveCacheUpdateNonApplicable");
                            } else if (cacheName.equals("pageCache")) {
                                logger.info("Skipping clearing pageCache for version");
                                //cacheInstance.flushGroup("contentVersion_" + entityId);
                                //cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");
                            } else if (cacheName.equals("componentPropertyCacheRepoGroups")
                                    || cacheName.equals("componentPropertyVersionIdCacheRepoGroups")) {
                                Timer t2 = new Timer();
                                try {
                                    String repositoryId = sentRepositoryId;
                                    if (repositoryId == null) {
                                        String contentId = sentContentId;
                                        if (contentId == null)
                                            contentId = "" + ContentVersionController
                                                    .getContentVersionController()
                                                    .getContentIdForContentVersion(new Integer(entityId));
                                        ContentVO contentVO = ContentController.getContentController()
                                                .getContentVOWithId(new Integer(contentId));
                                        repositoryId = "" + contentVO.getRepositoryId();
                                    }

                                    cacheInstance.flushGroup("" + repositoryId);
                                    //t2.printElapsedTime("3");
                                    if (cacheName.equals("componentPropertyVersionIdCacheRepoGroups"))
                                        cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");
                                    //t2.printElapsedTime("4");
                                    logger.info("Clearing componentPropertyCacheRepoGroups for repo:"
                                            + repositoryId);
                                } catch (Exception e2) {
                                    logger.info("Error loading content with id " + entityId + ":"
                                            + e2.getMessage());
                                }
                                //t.printElapsedTime("componentPropertyCacheRepoGroups");
                            } else if (cacheName.equals("assetUrlCacheWithGroups")) {
                                try {
                                    String contentId = sentContentId;
                                    if (contentId == null || contentId.equals(""))
                                        contentId = "" + ContentVersionController.getContentVersionController()
                                                .getContentIdForContentVersion(new Integer(entityId));
                                    cacheInstance.flushGroup("content_" + contentId);
                                    logger.info("Clearing assetUrlCacheWithGroups for content:" + "content_"
                                            + contentId);
                                } catch (Exception e2) {
                                    logger.warn(
                                            "Flushing assetUrlCacheWithGroups as it was a missing entity - was probably a delete");
                                    cacheInstance.flushAll();
                                }
                                //t.printElapsedTime("assetUrlCacheWithGroups");
                            } else if (cacheName.equals("childPagesCache")
                                    || cacheName.equals("childSiteNodesCache")) {
                                //System.out.println("childPagesCache:" + entity + "=" + entityId);
                                //t.printElapsedTime("childPagesCache start");
                                try {
                                    String contentId = sentContentId;
                                    //System.out.println("sentContentId:" + sentContentId);
                                    if (contentId == null || contentId.equals(""))
                                        contentId = "" + ContentVersionController.getContentVersionController()
                                                .getContentIdForContentVersion(new Integer(entityId));
                                    //System.out.println("contentId:" + contentId);
                                    //t.printElapsedTime("childPagesCache A");

                                    ContentTypeDefinitionVO metaInfoContentTypeDefinitionVO = ContentTypeDefinitionController
                                            .getController().getContentTypeDefinitionVOWithName("Meta info");
                                    //t.printElapsedTime("childPagesCache B");
                                    ContentVO contentVO = ContentController.getContentController()
                                            .getContentVOWithId(new Integer(contentId));
                                    //t.printElapsedTime("childPagesCache C");

                                    if (metaInfoContentTypeDefinitionVO.getId()
                                            .equals(contentVO.getContentTypeDefinitionId())) {
                                        try {
                                            SiteNodeVO siteNodeVO = SiteNodeController.getController()
                                                    .getSiteNodeVOWithMetaInfoContentId(new Integer(contentId));
                                            //t.printElapsedTime("childPagesCache getSiteNodeVOWithMetaInfoContentId");
                                            if (siteNodeVO != null) {
                                                cacheInstance.flushGroup("siteNode_" + siteNodeVO.getId());
                                                cacheInstance.flushGroup(
                                                        "siteNode_" + siteNodeVO.getParentSiteNodeId());
                                            }
                                        } catch (Exception e2) {
                                            logger.error(
                                                    "Did not find a sitenode with this meta info:" + contentId);
                                        }
                                        cacheInstance.flushGroup("content_" + contentId);
                                        cacheInstance.flushGroup("contentVersion_" + entityId);
                                        cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");
                                        //t.printElapsedTime("childPagesCache flush done...");
                                        logger.info("Clearing childPagesCache for content:" + "content_"
                                                + contentId);
                                    }
                                } catch (Exception e2) {
                                    logger.warn(
                                            "Flushing childPagesCache as it was a missing entity - was probably a delete");
                                    cacheInstance.flushAll();
                                }
                                //t.printElapsedTime("childPagesCache");
                            } else if (cacheName.equals("matchingContentsCache")) {
                                try {
                                    String contentId = sentContentId;
                                    if (contentId == null || contentId.equals(""))
                                        contentId = "" + ContentVersionController.getContentVersionController()
                                                .getContentIdForContentVersion(new Integer(entityId));

                                    try {
                                        ContentVO contentVO = ContentController.getContentController()
                                                .getContentVOWithId(new Integer(contentId));
                                        String contentTypeDefinitionId = ""
                                                + contentVO.getContentTypeDefinitionId();
                                        cacheInstance.flushGroup(
                                                "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                        + contentTypeDefinitionId);
                                        cacheInstance.putInCache("recacheMark_" + contentTypeDefinitionId,
                                                "" + System.currentTimeMillis());
                                        cacheInstance.putInCache("recacheMark",
                                                "" + System.currentTimeMillis());
                                    } catch (Exception e2) {
                                        logger.warn(
                                                "Flushing all as it was a missing entity - was probably a delete:"
                                                        + e2.getMessage());
                                        cacheInstance.flushAll();
                                    }

                                    cacheInstance.flushGroup("content_" + contentId);
                                    logger.info("Clearing assetUrlCacheWithGroups for content:" + "content_"
                                            + contentId);
                                } catch (Exception e2) {
                                    logger.warn(
                                            "Flushing all as it was a missing entity - was probably a delete:"
                                                    + e2.getMessage());
                                    cacheInstance.flushAll();
                                }
                                //t.printElapsedTime("matchingContentsCache");
                            } else {
                                //t.printElapsedTime("Before");
                                cacheInstance.flushGroup("contentVersion_" + entityId);
                                //if(!cacheName.equals("contentCache") && !cacheName.equals("contentVersionCache") && !cacheName.equals("contentAttributeCache") && !cacheName.equals("contentVersionIdCache") && !cacheName.equals("contentCategoryCache") && !cacheName.equals("metaInfoContentAttributeCache"))
                                cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");
                                logger.info(
                                        "clearing " + e.getKey() + " with selectiveCacheUpdateNonApplicable");
                                //t.printElapsedTime("clearing " + e.getKey() + " with selectiveCacheUpdateNonApplicable");
                            }
                            logger.info(
                                    "clearing " + e.getKey() + " with group " + "contentVersion_" + entityId);

                            //String[] changedAttributes = new String[]{"Title","NavigationTitle"}; 

                            try {
                                //t.printElapsedTime("Cache 3.4");
                                logger.info("Before contentVersionVO...");
                                //System.out.println("cacheName:" + cacheName);
                                //System.out.println("entity:" + entity);
                                //System.out.println("entityId:" + entityId);

                                String contentIdString = sentContentId;
                                String contentTypeDefinitionId = sentContentTypeDefinitionId;
                                String contentIsProtected = sentContentIsProtected;
                                if (contentIdString == null || contentIdString.equals("")) {
                                    try {
                                        contentIdString = ""
                                                + ContentVersionController.getContentVersionController()
                                                        .getContentIdForContentVersion(new Integer(entityId));
                                    } catch (Exception e2) {
                                        logger.info("Error loading content with id " + entityId + ":"
                                                + e2.getMessage());
                                    }
                                }

                                Integer contentId = null;
                                if (contentIdString != null)
                                    contentId = new Integer(contentIdString);

                                if (contentTypeDefinitionId == null && contentIsProtected == null
                                        && contentId != null) {
                                    ContentVO contentVO = ContentController.getContentController()
                                            .getContentVOWithId(new Integer(contentId));
                                    contentTypeDefinitionId = "" + contentVO.getContentTypeDefinitionId();
                                    contentIsProtected = "" + contentVO.getIsProtected().intValue();
                                }

                                //t.printElapsedTime("Cache 3.5");
                                //RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Cache 3.5", t.getElapsedTime());

                                if (contentId != null) {
                                    List<String> changes = Collections.EMPTY_LIST;
                                    //System.out.println("extraInformation:" + extraInformation);
                                    String changedAttributes = extraInformation == null ? null
                                            : extraInformation.get("changedAttributeNames");
                                    if (changedAttributes != null && changedAttributes.length() > 0)
                                        changes = new ArrayList<String>(
                                                Arrays.asList(StringUtils.split(changedAttributes, ",")));

                                    //ContentVO contentVO = ContentController.getContentController().getContentVOWithId(new Integer(contentId));

                                    logger.info("Before flushGroup2...");
                                    if (cacheName.equals("pageCacheExtra")) {
                                        if (contentIsProtected.equals("" + ContentVO.YES.intValue())) {
                                            List<InterceptionPointVO> interceptionPointVOList = InterceptionPointController
                                                    .getController().getInterceptionPointVOList("Content");
                                            for (InterceptionPointVO interceptionPointVO : interceptionPointVOList) {
                                                if (interceptionPointVO.getName().endsWith(".Read")) {
                                                    String acKey = "" + interceptionPointVO.getId() + "_"
                                                            + entityId;
                                                    CacheController.clearUserAccessCache(acKey);
                                                }
                                            }
                                        }

                                        PageCacheHelper.getInstance().notify(
                                                "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                        + contentTypeDefinitionId);
                                        PageCacheHelper.getInstance().notify("content_" + contentId);
                                        //clearFileCacheForGroup(cacheInstance, "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_" + contentVO.getContentTypeDefinitionId());

                                        if ((changes == null || changes.size() == 0)
                                                && CmsPropertyHandler.getOperatingMode().equals("3")) {
                                            ContentVersionVO oldContentVersionVO = ContentVersionController
                                                    .getContentVersionController()
                                                    .getContentVersionVOWithId(new Integer(entityId));
                                            ContentVersionVO newContentVersionVO = ContentVersionController
                                                    .getContentVersionController()
                                                    .getLatestActiveContentVersionVO(contentId,
                                                            oldContentVersionVO.getLanguageId(),
                                                            new Integer(CmsPropertyHandler.getOperatingMode()));
                                            if (newContentVersionVO != null && oldContentVersionVO != null
                                                    && newContentVersionVO.getId()
                                                            .equals(oldContentVersionVO.getId())) {
                                                oldContentVersionVO = null;
                                                //System.out.println("SHIT - same version allready - must find other");
                                                List<SmallestContentVersionVO> contentVersionVOList = ContentVersionController
                                                        .getContentVersionController()
                                                        .getSmallestContentVersionVOList(
                                                                new Integer(contentId));
                                                for (SmallestContentVersionVO cvVO : contentVersionVOList) {
                                                    if (!cvVO.getId().equals(newContentVersionVO.getId())
                                                            && cvVO.getStateId()
                                                                    .equals(new Integer(CmsPropertyHandler
                                                                            .getOperatingMode()))
                                                            && cvVO.getLanguageId()
                                                                    .equals(newContentVersionVO.getLanguageId())
                                                            && cvVO.getIsActive()
                                                            && (oldContentVersionVO == null
                                                                    || oldContentVersionVO.getId() < cvVO
                                                                            .getId())) {
                                                        oldContentVersionVO = ContentVersionController
                                                                .getContentVersionController()
                                                                .getContentVersionVOWithId(cvVO.getId());
                                                    }
                                                }
                                            }

                                            //System.out.println("Now we should have current and previous version:" + newContentVersionVO + " / " + oldContentVersionVO);
                                            if (newContentVersionVO != null && oldContentVersionVO != null)
                                                changes = ContentVersionController.getContentVersionController()
                                                        .getChangedAttributeNames(newContentVersionVO,
                                                                oldContentVersionVO);
                                        }

                                        //System.out.println("changes:" + changes);
                                        for (String changedAttributeName : changes) {
                                            if (changedAttributeName.indexOf("ComponentStructure") > -1) {
                                                //Map allreadyFlushedEntries....
                                                Set<String> groupEntries = (Set<String>) cacheInstance
                                                        .getCache().cacheMap
                                                                .getGroup("content_" + contentId
                                                                        + "_ComponentStructureDependency");
                                                //System.out.println("groupEntries:" + groupEntries);
                                                if (groupEntries != null) {
                                                    System.out.println("groupEntries:" + groupEntries.size());
                                                    outer: for (String key : groupEntries) {
                                                        //System.out.println("key 1:" + key);
                                                        try {
                                                            //String[] usedEntities = (String[])cacheInstance.getFromCache(key + "_entities");
                                                            byte[] usedEntitiesByteArray = (byte[]) cacheInstance
                                                                    .getFromCache(key + "_entitiesAsByte");
                                                            String usedEntitiesString = compressionHelper
                                                                    .decompress(usedEntitiesByteArray);
                                                            //t.printElapsedTime("Decompress to " + usedEntitiesString.length() + " took");
                                                            String[] usedEntities = StringUtils
                                                                    .split(usedEntitiesString, "|");
                                                            //t.printElapsedTime("Split to usedEntities " + usedEntities.length + " took");

                                                            ContentVersionVO newContentVersionVO = ContentVersionController
                                                                    .getContentVersionController()
                                                                    .getContentVersionVOWithId(
                                                                            new Integer(entityId));
                                                            String newComponentStructure = ContentVersionController
                                                                    .getContentVersionController()
                                                                    .getAttributeValue(newContentVersionVO,
                                                                            "ComponentStructure", false);

                                                            for (String usedEntity : usedEntities) {
                                                                //System.out.println("usedEntity:" + usedEntity);
                                                                if (usedEntity.startsWith("content_" + contentId
                                                                        + "_ComponentStructure(")) {
                                                                    //System.out.println("Match - now lets parse: " + usedEntity);
                                                                    String arguments = usedEntity.substring(
                                                                            usedEntity.indexOf("(") + 1,
                                                                            usedEntity.indexOf(")"));
                                                                    Integer oldComponentPropertyHash = new Integer(
                                                                            usedEntity.substring(
                                                                                    usedEntity.indexOf("=")
                                                                                            + 1));
                                                                    String[] args = arguments.split(",");
                                                                    Integer componentId = new Integer(args[0]);
                                                                    String propertyName = args[1];
                                                                    Integer siteNodeId = new Integer(args[2]);
                                                                    Integer languageId = new Integer(args[3]);
                                                                    //System.out.println("componentId:" + componentId);
                                                                    //System.out.println("propertyName:" + propertyName);
                                                                    //System.out.println("siteNodeId:" + siteNodeId);
                                                                    //System.out.println("languageId:" + languageId);

                                                                    int newComponentPropertyHash = getPropertyAsStringHashCode(
                                                                            newComponentStructure, componentId,
                                                                            propertyName, siteNodeId,
                                                                            languageId);
                                                                    //System.out.println("oldComponentPropertyHash:" + oldComponentPropertyHash);
                                                                    //System.out.println("newComponentPropertyHash:" + newComponentPropertyHash);
                                                                    if (oldComponentPropertyHash
                                                                            .intValue() != newComponentPropertyHash) {
                                                                        //System.out.println("Yes - clearing - must have changed something important:" + usedEntity);
                                                                        PageCacheHelper.getInstance()
                                                                                .notify(usedEntity);
                                                                        //clearFileCacheForGroup(cacheInstance, usedEntity);
                                                                    } else {
                                                                        //System.out.println("Flushing content_" + currentPageMetaInfoContentId + "_ComponentStructure just to catch page itself");
                                                                        //cacheInstance.flushGroup("content_" + currentPageMetaInfoContentId + "_ComponentStructure");
                                                                        //System.out.println("Flushing content_" + contentId + "_ComponentStructure just to catch page itself");
                                                                        //cacheInstance.flushGroup("content_" + contentId + "_ComponentStructure");
                                                                    }

                                                                } else if (usedEntity.startsWith("content_"
                                                                        + contentId + "_ComponentStructure:")) {
                                                                    //System.out.println("Match - now lets parse component order etc: " + usedEntity);
                                                                    String xPath = usedEntity.substring(
                                                                            usedEntity.indexOf(":") + 1,
                                                                            usedEntity.lastIndexOf("="));
                                                                    Integer oldComponentPropertyHash = new Integer(
                                                                            usedEntity.substring(
                                                                                    usedEntity.lastIndexOf("=")
                                                                                            + 1));
                                                                    //System.out.println("xPath:" + xPath);

                                                                    int newComponentPropertyHash = getComponentsAsStringHashCode(
                                                                            newComponentStructure, xPath);
                                                                    //System.out.println("oldComponentPropertyHash:" + oldComponentPropertyHash);
                                                                    //System.out.println("newComponentPropertyHash:" + newComponentPropertyHash);
                                                                    if (oldComponentPropertyHash
                                                                            .intValue() != newComponentPropertyHash) {
                                                                        //System.out.println("Yes - clearing - must have changed order or added/subtracted components:" + usedEntity);
                                                                        PageCacheHelper.getInstance()
                                                                                .notify(usedEntity);
                                                                        //clearFileCacheForGroup(cacheInstance, usedEntity);
                                                                    }
                                                                }
                                                            }
                                                        } catch (Exception ex) {
                                                            //logger.error("Got error trying to update cache:" + ex.getMessage());
                                                            logger.warn("Got error trying to update cache:"
                                                                    + ex.getMessage(), ex);

                                                            //clearFileCacheForGroup(cacheInstance, "content_" + contentId + "_" + changedAttributeName);
                                                            //cacheInstance.flushGroup("content_" + contentId + "_" + changedAttributeName);
                                                            //logger.warn("Cleared pageCache for " + "content_" + contentId + "_" + changedAttributeName);

                                                            break outer;
                                                        }
                                                    }
                                                }
                                            } else {
                                                PageCacheHelper.getInstance().notify(
                                                        "content_" + contentId + "_" + changedAttributeName);
                                                //clearFileCacheForGroup(cacheInstance, "content_" + contentId + "_" + changedAttributeName);
                                                //System.out.println("Cleared for " + "content_" + contentId + "_" + changedAttributeName);
                                            }
                                        }

                                        //t.printElapsedTime("Handled page cache extra");
                                        RequestAnalyser.getRequestAnalyser().registerComponentStatistics(
                                                "Handled page cache extra", t.getElapsedTime());
                                        //clearFileCacheForGroup(cacheInstance, "content_" + contentId);
                                    } else if (cacheName.equals("pageCache")) {
                                        //t.printElapsedTime("Page cache start");
                                        RequestAnalyser.getRequestAnalyser().registerComponentStatistics(
                                                "Page cache start", t.getElapsedTime());
                                        logger.info("Flushing pageCache for content type def");

                                        String contentTypeDefKey = "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                + contentTypeDefinitionId;
                                        cacheInstance.flushGroup(contentTypeDefKey);
                                        //cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_" + contentVO.getContentTypeDefinitionId());
                                        //cacheInstance.flushGroup("content_" + contentVO.getId());
                                        //System.out.println("Flushing:" + getPooledString(1, contentVO.getId()));
                                        cacheInstance.flushGroup(getPooledString(1, new Integer(contentId)));
                                        PageCacheHelper.getInstance().notify("content_" + contentId);

                                        ContentVersionVO oldContentVersionVO = null;
                                        ContentVersionVO newContentVersionVO = null;

                                        String debug = "";
                                        if ((changes == null || changes.size() == 0)
                                                && CmsPropertyHandler.getOperatingMode().equals("3")) {
                                            debug += "entityId:" + entityId + "\n";
                                            debug += "contentId:" + contentId + "\n";
                                            oldContentVersionVO = ContentVersionController
                                                    .getContentVersionController()
                                                    .getContentVersionVOWithId(new Integer(entityId));
                                            debug += "oldContentVersionVO:" + oldContentVersionVO.getId() + ":"
                                                    + oldContentVersionVO.getLanguageId() + "\n";
                                            debug += "oldContentVersionVO:"
                                                    + CmsPropertyHandler.getOperatingMode() + "\n";
                                            newContentVersionVO = ContentVersionController
                                                    .getContentVersionController()
                                                    .getLatestActiveContentVersionVO(contentId,
                                                            oldContentVersionVO.getLanguageId(),
                                                            new Integer(CmsPropertyHandler.getOperatingMode()));
                                            debug += "newContentVersionVO:" + newContentVersionVO + "\n";
                                            if (newContentVersionVO != null && oldContentVersionVO != null
                                                    && newContentVersionVO.getId()
                                                            .equals(oldContentVersionVO.getId())) {
                                                debug += "newContentVersionVO:" + newContentVersionVO.getId()
                                                        + "\n";
                                                oldContentVersionVO = null;
                                                debug += "SHIT - same version allready - must find other";
                                                List<SmallestContentVersionVO> contentVersionVOList = ContentVersionController
                                                        .getContentVersionController()
                                                        .getSmallestContentVersionVOList(
                                                                new Integer(contentId));
                                                for (SmallestContentVersionVO cvVO : contentVersionVOList) {
                                                    if (!cvVO.getId().equals(newContentVersionVO.getId())
                                                            && cvVO.getStateId()
                                                                    .equals(new Integer(CmsPropertyHandler
                                                                            .getOperatingMode()))
                                                            && cvVO.getLanguageId()
                                                                    .equals(newContentVersionVO.getLanguageId())
                                                            && cvVO.getIsActive()
                                                            && (oldContentVersionVO == null
                                                                    || oldContentVersionVO.getId() < cvVO
                                                                            .getId())) {
                                                        oldContentVersionVO = ContentVersionController
                                                                .getContentVersionController()
                                                                .getContentVersionVOWithId(cvVO.getId());
                                                    }
                                                }
                                                debug += "oldContentVersionVO:"
                                                        + (oldContentVersionVO == null ? "null"
                                                                : oldContentVersionVO.getId())
                                                        + "\n";
                                            }

                                            //System.out.println("Now we should have current and previous version:" + newContentVersionVO + " / " + oldContentVersionVO);
                                            if (newContentVersionVO != null && oldContentVersionVO != null)
                                                changes = ContentVersionController.getContentVersionController()
                                                        .getChangedAttributeNames(newContentVersionVO,
                                                                oldContentVersionVO);
                                        }

                                        //t.printElapsedTime("Changes analyzed");
                                        //RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Changes analyzed", t.getElapsedTime());

                                        if ((changes == null || changes.size() == 0)
                                                && CmsPropertyHandler.getOperatingMode().equals("3")) {
                                            if (oldContentVersionVO == null || newContentVersionVO == null) {
                                                //Hur kan det bli detta????
                                                logger.warn("Fishy 1: " + oldContentVersionVO + ":"
                                                        + newContentVersionVO + " in "
                                                        + CmsPropertyHandler.getContextRootPath());
                                                logger.warn("DEBUG: " + debug);
                                            } else {
                                                logger.warn(
                                                        "Fishy 2: No changes found between content versions "
                                                                + newContentVersionVO.getId() + " and "
                                                                + oldContentVersionVO.getId() + " in "
                                                                + CmsPropertyHandler.getContextRootPath());
                                                logger.warn("DEBUG: " + debug);
                                                logger.warn("Fishy: newContentVersionVO: "
                                                        + newContentVersionVO.getVersionValue());
                                                logger.warn("Fishy: newContentVersionVO: "
                                                        + oldContentVersionVO.getVersionValue());
                                            }
                                            logger.warn(
                                                    "Just to make sure pages are updated we pretend all attributes changed until we find the bug");
                                            changes = ContentVersionController.getContentVersionController()
                                                    .getAttributeNames(newContentVersionVO);
                                        }

                                        //System.out.println("changes:" + changes);
                                        for (String changedAttributeName : changes) {
                                            logger.warn("changedAttributeName: " + changedAttributeName);
                                            if (changedAttributeName.indexOf("ComponentStructure") > -1
                                                    && cacheName.equals("pageCache")) {
                                                //Map allreadyFlushedEntries....
                                                //It's something wrong here..
                                                GeneralCacheAdministrator pageCacheExtraInstance = (GeneralCacheAdministrator) caches
                                                        .get("pageCacheExtra");
                                                String cacheGroupKey = "content_" + contentId
                                                        + "_ComponentStructureDependency";
                                                //Set<String> groupEntries = (Set<String>)cacheInstance.getCache().cacheMap.getGroup("content_" + contentId + "_ComponentStructureDependency");
                                                Set<String> groupEntries = (Set<String>) cacheInstance
                                                        .getCache().cacheMap.getGroup(
                                                                getPooledString(cacheGroupKey.hashCode()));
                                                //System.out.println("groupEntries:" + groupEntries);
                                                if (groupEntries != null) {
                                                    outer: for (String key : groupEntries) {
                                                        logger.info("key 2:" + key);
                                                        try {
                                                            //String[] usedEntities = (String[])pageCacheExtraInstance.getFromCache(key + "_entities");
                                                            byte[] usedEntitiesByteArray = (byte[]) pageCacheExtraInstance
                                                                    .getFromCache(key + "_entitiesAsByte");
                                                            String usedEntitiesString = compressionHelper
                                                                    .decompress(usedEntitiesByteArray);
                                                            //t.printElapsedTime("Decompress to " + usedEntitiesString.length() + " took");
                                                            String[] usedEntities = StringUtils
                                                                    .split(usedEntitiesString, ",");
                                                            //t.printElapsedTime("Split to usedEntities " + usedEntities.length + " took");

                                                            ContentVersionVO newestContentVersionVO = ContentVersionController
                                                                    .getContentVersionController()
                                                                    .getContentVersionVOWithId(
                                                                            new Integer(entityId));
                                                            String newComponentStructure = ContentVersionController
                                                                    .getContentVersionController()
                                                                    .getAttributeValue(newestContentVersionVO,
                                                                            "ComponentStructure", false);

                                                            for (String usedEntity : usedEntities) {
                                                                //System.out.println("usedEntity:" + usedEntity);
                                                                if (usedEntity.startsWith("content_" + contentId
                                                                        + "_ComponentStructure(")) {
                                                                    //System.out.println("Match - now lets parse: " + usedEntity);
                                                                    String arguments = usedEntity.substring(
                                                                            usedEntity.indexOf("(") + 1,
                                                                            usedEntity.indexOf(")"));
                                                                    Integer oldComponentPropertyHash = new Integer(
                                                                            usedEntity.substring(
                                                                                    usedEntity.indexOf("=")
                                                                                            + 1));
                                                                    String[] args = arguments.split(",");
                                                                    Integer componentId = new Integer(args[0]);
                                                                    String propertyName = args[1];
                                                                    Integer siteNodeId = new Integer(args[2]);
                                                                    Integer languageId = new Integer(args[3]);
                                                                    //System.out.println("componentId:" + componentId);
                                                                    //System.out.println("propertyName:" + propertyName);
                                                                    //System.out.println("siteNodeId:" + siteNodeId);
                                                                    //System.out.println("languageId:" + languageId);

                                                                    int newComponentPropertyHash = getPropertyAsStringHashCode(
                                                                            newComponentStructure, componentId,
                                                                            propertyName, siteNodeId,
                                                                            languageId);
                                                                    //System.out.println("oldComponentPropertyHash:" + oldComponentPropertyHash);
                                                                    //System.out.println("newComponentPropertyHash:" + newComponentPropertyHash);
                                                                    if (oldComponentPropertyHash
                                                                            .intValue() != newComponentPropertyHash) {
                                                                        //System.out.println("Yes - clearing - must have changed something important:" + usedEntity);
                                                                        //cacheInstance.flushGroup(usedEntity);
                                                                        cacheInstance
                                                                                .flushGroup(getPooledString(
                                                                                        usedEntity.hashCode()));
                                                                        //clearFileCacheForGroup(cacheInstance, usedEntity);
                                                                    } else {
                                                                        //System.out.println("Flushing content_" + currentPageMetaInfoContentId + "_ComponentStructure just to catch page itself");
                                                                        //cacheInstance.flushGroup("content_" + currentPageMetaInfoContentId + "_ComponentStructure");
                                                                        //System.out.println("Flushing content_" + contentId + "_ComponentStructure just to catch page itself");
                                                                        String componentStructureKey = "content_"
                                                                                + contentId
                                                                                + "_ComponentStructure";
                                                                        //cacheInstance.flushGroup(componentStructureKey);
                                                                        cacheInstance
                                                                                .flushGroup(getPooledString(
                                                                                        componentStructureKey
                                                                                                .hashCode()));
                                                                        cacheInstance
                                                                                .flushGroup(getPooledString(
                                                                                        usedEntity.hashCode()));
                                                                    }

                                                                } else if (usedEntity.startsWith("content_"
                                                                        + contentId + "_ComponentStructure:")) {
                                                                    //System.out.println("Match - now lets parse component order etc: " + usedEntity);
                                                                    String xPath = usedEntity.substring(
                                                                            usedEntity.indexOf(":") + 1,
                                                                            usedEntity.lastIndexOf("="));
                                                                    Integer oldComponentPropertyHash = new Integer(
                                                                            usedEntity.substring(
                                                                                    usedEntity.lastIndexOf("=")
                                                                                            + 1));
                                                                    //System.out.println("xPath:" + xPath);

                                                                    int newComponentPropertyHash = getComponentsAsStringHashCode(
                                                                            newComponentStructure, xPath);
                                                                    //System.out.println("oldComponentPropertyHash:" + oldComponentPropertyHash);
                                                                    //System.out.println("newComponentPropertyHash:" + newComponentPropertyHash);
                                                                    if (oldComponentPropertyHash
                                                                            .intValue() != newComponentPropertyHash) {
                                                                        //System.out.println("Yes - clearing - must have changed order or added/subtracted components:" + usedEntity);
                                                                        cacheInstance
                                                                                .flushGroup(getPooledString(
                                                                                        usedEntity.hashCode()));
                                                                        //cacheInstance.flushGroup(usedEntity);
                                                                    }
                                                                }

                                                            }
                                                        } catch (Exception ex) {
                                                            //logger.error("Got error trying to update cache:" + ex.getMessage());
                                                            logger.warn("Got error trying to update cache:"
                                                                    + ex.getMessage(), ex);

                                                            try {
                                                                String attributeKey = "content_" + contentId
                                                                        + "_" + changedAttributeName;
                                                                //cacheInstance.flushGroup(attributeKey);
                                                                cacheInstance.flushGroup(getPooledString(
                                                                        attributeKey.hashCode()));
                                                                logger.warn("Cleared pageCache for "
                                                                        + getPooledString(
                                                                                attributeKey.hashCode()));
                                                            } catch (Exception ex2) {
                                                                logger.error("Got error trying to flushGroup 2:"
                                                                        + ex2.getMessage());
                                                                cacheInstance.flushAll();
                                                            }
                                                            break outer;
                                                        }
                                                        t.printElapsedTime("Handled group entries");
                                                        //RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Handled group entries", t.getElapsedTime());
                                                    }
                                                }
                                            } else {
                                                String attributeKey = "content_" + contentId + "_"
                                                        + changedAttributeName;
                                                //cacheInstance.flushGroup("content_" + contentId + "_" + changedAttributeName);
                                                cacheInstance
                                                        .flushGroup(getPooledString(attributeKey.hashCode()));
                                                logger.info("Cleared pageCache for " + "content_" + contentId
                                                        + "_" + changedAttributeName);
                                            }
                                        }
                                        //cacheInstance.flushGroup("content_" + contentId);
                                    } else {
                                        String contentTypeDefKey = "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                + contentTypeDefinitionId;
                                        //cacheInstance.flushGroup(contentTypeDefKey);
                                        cacheInstance.flushGroup(contentTypeDefKey);
                                        //System.out.println("Cleared for " + "content_" + contentId + " on cache " + cacheName);
                                        String contentKey = "content_" + contentId;
                                        cacheInstance.flushGroup(contentKey);
                                        //cacheInstance.flushGroup(contentKey);
                                    }

                                    //t.printElapsedTime("Handled page cache");
                                    //RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Handled page cache", t.getElapsedTime());   
                                    logger.info("After flushGroup2...");
                                }
                                //}

                                if (cacheName.equals("contentVersionCache")) {
                                    new AssetUpdatingThread(entityId).start();
                                }
                            } catch (SystemException se) {
                                se.printStackTrace();
                                logger.info("Missing content version: " + se.getMessage());
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        } else if (selectiveCacheUpdate
                                && (entity.indexOf("Content") > 0
                                        && entity.indexOf("ContentTypeDefinition") == -1
                                        && entity.indexOf("ContentCategory") == -1)
                                && useSelectivePageCacheUpdate) {
                            logger.info("Content entity was sent: " + entity + ":" + entityId);
                            //System.out.println("Content entity was called and needs to be fixed:" + entity);

                            //String[] changedAttributes = new String[]{"Title","NavigationTitle"}; 
                            /*
                            ContentVO contentVO = null;
                            if(isObjectCachedInCastor(SmallContentImpl.class, new Integer(entityId)))
                               contentVO = ContentController.getContentController().getContentVOWithId(new Integer(entityId));
                            */

                            String repositoryId = sentRepositoryId;
                            String contentTypeDefinitionId = sentContentTypeDefinitionId;
                            String contentIsProtected = sentContentIsProtected;
                            if (repositoryId == null || contentTypeDefinitionId == null
                                    || contentIsProtected == null) {
                                //System.out.println("repositoryId:" + repositoryId);
                                //System.out.println("contentTypeDefinitionId:" + contentTypeDefinitionId);
                                //System.out.println("contentIsProtected:" + contentIsProtected);
                                try {
                                    ContentVO contentVO = ContentController.getContentController()
                                            .getContentVOWithId(new Integer(entityId));
                                    //t.printElapsedTime("clearCaches cv u1 contentVO", 10);
                                    repositoryId = "" + contentVO.getRepositoryId();
                                    contentTypeDefinitionId = "" + contentVO.getContentTypeDefinitionId();
                                    contentIsProtected = "" + contentVO.getIsProtected();
                                } catch (Exception e2) {
                                    logger.info("Error loading content with id " + entityId + ":"
                                            + e2.getMessage());
                                }
                            }

                            if (cacheName.equals("componentPropertyCacheRepoGroups")
                                    || cacheName.equals("componentPropertyVersionIdCacheRepoGroups")) {
                                cacheInstance.flushGroup("" + repositoryId);
                                logger.info(
                                        "Clearing componentPropertyCacheRepoGroups for repo:" + repositoryId);
                            }

                            if (cacheName.equals("pageCacheExtra")) {
                                //clearFileCacheForGroup(cacheInstance, "content_" + entityId);
                                PageCacheHelper.getInstance().notify("content_" + entityId);

                                try {
                                    //cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_" + contentVO.getContentTypeDefinitionId());
                                    if (contentTypeDefinitionId != null) {
                                        //clearFileCacheForGroup(cacheInstance, "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_" + contentVO.getContentTypeDefinitionId());
                                        PageCacheHelper.getInstance().notify(
                                                "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                        + contentTypeDefinitionId);
                                    }
                                } catch (Exception e2) {
                                    logger.warn("Could not find content type to clear pages based on: "
                                            + e2.getMessage(), e2);
                                }
                            } else if (cacheName.equals("pageCache")) {
                                logger.info("Flushing page cache for {" + entityId + "} and {content_"
                                        + entityId + "}");

                                String entityKey = "" + entityId;
                                String contentEntityKey = "content_" + entityId;
                                //cacheInstance.flushGroup("" + entityId);
                                //cacheInstance.flushGroup(contentEntityKey);
                                cacheInstance.flushGroup(entityKey);
                                cacheInstance.flushGroup(contentEntityKey);
                                try {
                                    if (contentTypeDefinitionId != null) {
                                        String contentTypeCacheKey = "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                + contentTypeDefinitionId;
                                        //cacheInstance.flushGroup(contentTypeCacheKey);
                                        cacheInstance.flushGroup(contentTypeCacheKey);
                                    }
                                } catch (Exception e2) {
                                    logger.warn("Could not find content type to clear pages based on: "
                                            + e2.getMessage(), e2);
                                }
                            } else {
                                cacheInstance.flushGroup("" + entityId);
                                cacheInstance.flushGroup("content_" + entityId);
                                logger.info(
                                        "clearing " + e.getKey() + " with selectiveCacheUpdateNonApplicable");
                                cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");
                                if (contentTypeDefinitionId != null) {
                                    cacheInstance.flushGroup(
                                            "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                    + contentTypeDefinitionId);
                                }
                            }

                            if (contentTypeDefinitionId != null) {
                                //System.out.println("****************************************************************");
                                if (contentIsProtected.equals("" + ContentVO.YES.intValue())) {
                                    List<InterceptionPointVO> interceptionPointVOList = InterceptionPointController
                                            .getController().getInterceptionPointVOList("Content");
                                    for (InterceptionPointVO interceptionPointVO : interceptionPointVOList) {
                                        if (interceptionPointVO.getName().endsWith(".Read")) {
                                            String acKey = "" + interceptionPointVO.getId() + "_" + entityId;
                                            //System.out.println("Clearing access rights for:" + acKey);
                                            CacheController.clearUserAccessCache(acKey);
                                        }
                                    }
                                }
                            }
                            //System.out.println("************************END************************************");

                            logger.info("clearing " + e.getKey() + " with group " + "content_" + entityId);
                        } else if (selectiveCacheUpdate && entity.indexOf("DigitalAsset") > -1) {
                            logger.info("Asset entity was sent: " + entity + ":" + entityId);
                            Integer contentId = assetContentIdMapping.get(new Integer(entityId));
                            if (contentId == null) {
                                logger.info("Checking fot cv for asset:" + entityId);
                                List<SmallestContentVersionVO> contentVersions = DigitalAssetController
                                        .getContentVersionVOListConnectedToAssetWithId(new Integer(entityId));
                                if (contentVersions != null) {
                                    for (SmallestContentVersionVO contentVersionVO : contentVersions) {
                                        contentId = contentVersionVO.getContentId();
                                        assetContentIdMapping.put(new Integer(entityId), contentId);
                                        break;
                                    }
                                }
                            } else
                                logger.info("Using read asset");

                            //Integer contentId = null;

                            ContentVO contentVO = null;
                            try {
                                contentVO = ContentController.getContentController()
                                        .getContentVOWithId(contentId);

                                if (cacheName.equals("componentPropertyCacheRepoGroups")
                                        || cacheName.equals("componentPropertyVersionIdCacheRepoGroups")) {
                                    cacheInstance.flushGroup("" + contentVO.getRepositoryId());
                                    logger.info("Clearing componentPropertyCacheRepoGroups for repo:"
                                            + contentVO.getRepositoryId());
                                }
                            } catch (Exception e2) {
                                logger.info(
                                        "Error loading content with id " + contentId + ":" + e2.getMessage());
                            }
                            //ContentVO contentVO = ContentController.getContentController().getContentVOWithId(new Integer(entityId));

                            if (cacheName.equals("pageCacheExtra")) {
                                //clearFileCacheForGroup(cacheInstance, "content_" + entityId);
                                PageCacheHelper.getInstance().notify("content_" + contentId);

                                try {
                                    //cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_" + contentVO.getContentTypeDefinitionId());
                                    if (contentVO != null) {
                                        //clearFileCacheForGroup(cacheInstance, "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_" + contentVO.getContentTypeDefinitionId());
                                        PageCacheHelper.getInstance().notify(
                                                "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                        + contentVO.getContentTypeDefinitionId());
                                    }
                                } catch (Exception e2) {
                                    logger.warn("Could not find content type to clear pages based on: "
                                            + e2.getMessage(), e2);
                                }
                            } else if (cacheName.equals("pageCache")) {
                                logger.info("Flushing page cache for {" + contentId + "} and {content_"
                                        + contentId + "}");

                                String entityKey = "" + contentId;
                                String contentEntityKey = "content_" + contentId;
                                //cacheInstance.flushGroup("" + entityId);
                                //cacheInstance.flushGroup(contentEntityKey);
                                cacheInstance.flushGroup(entityKey);
                                cacheInstance.flushGroup(contentEntityKey);
                                try {
                                    if (contentVO != null) {
                                        String contentTypeCacheKey = "selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                + contentVO.getContentTypeDefinitionId();
                                        //cacheInstance.flushGroup(contentTypeCacheKey);
                                        cacheInstance.flushGroup(contentTypeCacheKey);
                                    }
                                } catch (Exception e2) {
                                    logger.warn("Could not find content type to clear pages based on: "
                                            + e2.getMessage(), e2);
                                }
                            } else {
                                cacheInstance.flushGroup("" + contentId);
                                cacheInstance.flushGroup("content_" + contentId);
                                logger.info(
                                        "clearing " + e.getKey() + " with selectiveCacheUpdateNonApplicable");
                                cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");
                            }

                            logger.info("clearing " + e.getKey() + " with group " + "content_" + entityId);
                        } else if (selectiveCacheUpdate && entity.indexOf("Publication") > 0
                                && useSelectivePageCacheUpdate
                                && (operatingMode != null && operatingMode.equalsIgnoreCase("3"))
                                && CmsPropertyHandler.getLivePublicationThreadClass().equalsIgnoreCase(
                                        "org.infoglue.deliver.util.SelectiveLivePublicationThread")) {
                            logger.info("Now we will ease out the publication...");
                            /*
                             List publicationDetailVOList = PublicationController.getController().getPublicationDetailVOList(new Integer(entityId));
                            Iterator publicationDetailVOListIterator = publicationDetailVOList.iterator();
                            while(publicationDetailVOListIterator.hasNext())
                            {
                               PublicationDetailVO publicationDetailVO = (PublicationDetailVO)publicationDetailVOListIterator.next();
                               logger.info("publicationDetailVO.getEntityClass():" + publicationDetailVO.getEntityClass());
                               logger.info("publicationDetailVO.getEntityId():" + publicationDetailVO.getEntityId());
                               if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(ContentVersion.class.getName()))
                               {
                                  logger.error("We clear all caches having references to contentVersion: " + publicationDetailVO.getEntityId());
                                  Integer contentId = ContentVersionController.getContentVersionController().getContentIdForContentVersion(publicationDetailVO.getEntityId());
                                    
                                   cacheInstance.flushGroup("content_" + contentId);
                                   cacheInstance.flushGroup(CacheController.getPooledString(2, publicationDetailVO.getEntityId().toString()));
                                   cacheInstance.flushGroup("selectiveCacheUpdateNonApplicable");
                                   logger.info("clearing " + e.getKey() + " with group " + "content_" + contentId);
                                   logger.info("clearing " + e.getKey() + " with group " + "content_" + contentId);
                               }
                               else if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(SiteNodeVersion.class.getName()))
                               {
                                  Integer siteNodeId = SiteNodeVersionController.getController().getSiteNodeVersionVOWithId(publicationDetailVO.getEntityId()).getSiteNodeId();
                                   CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null);
                               }
                                       
                            }
                            */
                        } else if (entity
                                .equals("org.infoglue.cms.entities.management.impl.simple.AccessRightImpl")) {
                            //System.out.println("This was an access right update - do we handle it:" + cacheName);
                            if (!CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("3")) {
                                try {
                                    AccessRightVO acVO = AccessRightController.getController()
                                            .getAccessRightVOWithId(new Integer(entityId));
                                    InterceptionPointVO icpVO = InterceptionPointController.getController()
                                            .getInterceptionPointVOWithId(acVO.getInterceptionPointId());
                                    //System.out.println("icpVO:" + icpVO.getName());
                                    if (icpVO.getName().indexOf("Content.") > -1) {
                                        //System.out.println("Was a content access... let's clear caches for that content.");
                                        String idAsString = acVO.getParameters();
                                        if (idAsString != null && !idAsString.equals(""))
                                            clearCaches(
                                                    "org.infoglue.cms.entities.content.impl.simple.ContentImpl",
                                                    idAsString, null, cachesToSkip, forceClear);
                                    } else if (icpVO.getName().indexOf("ContentVersion.") > -1) {
                                        //System.out.println("Was a contentversion access... let's clear caches for that content.");
                                        String idAsString = acVO.getParameters();
                                        if (idAsString != null && !idAsString.equals(""))
                                            clearCaches(
                                                    "org.infoglue.cms.entities.content.impl.simple.ContentVersionImpl",
                                                    idAsString, null, cachesToSkip, forceClear);
                                    } else if (icpVO.getName().indexOf("SiteNode.") > -1) {
                                        //System.out.println("Was a sitenode access... let's clear caches for that content.");
                                        String idAsString = acVO.getParameters();
                                        if (idAsString != null && !idAsString.equals(""))
                                            clearCaches(
                                                    "org.infoglue.cms.entities.structure.impl.simple.SiteNodeImpl",
                                                    idAsString, null, cachesToSkip, forceClear);
                                    } else if (icpVO.getName().indexOf("SiteNodeVersion.") > -1) {
                                        //System.out.println("Was a sitenode version access... let's clear caches for that content.");
                                        String idAsString = acVO.getParameters();
                                        if (idAsString != null && !idAsString.equals(""))
                                            clearCaches(
                                                    "org.infoglue.cms.entities.structure.impl.simple.SiteNodeVersionImpl",
                                                    idAsString, null, cachesToSkip, forceClear);
                                    } else {
                                        //System.out.println("****************************");
                                        //System.out.println("* WHAT TO DO WITH IN CACHECONTROLLER: " + icpVO.getName() + " *");
                                        //System.out.println("****************************");
                                    }
                                } catch (Exception e2) {
                                    logger.error("Error handling access right update: " + e2.getMessage(), e2);
                                }
                            } else
                                logger.info("Skipping it as this is live mode..");
                        } else if (selectiveCacheUpdate
                                && (entity.indexOf("ServiceBinding") > 0 || entity.indexOf("Qualifyer") > 0)) {
                            logger.info(
                                    "Ignoring this kind of notification... never used anymore:" + cacheName);
                        } else if (entity.indexOf("AccessRightImpl") > -1) {
                            logger.info("Ignoring handling of entity:" + entity);
                        } else if (cacheName.equalsIgnoreCase("matchingContentsCache")
                                && entity.indexOf("MediumContentCategoryImpl") > 0) {
                            try {
                                String contentId = sentContentId;
                                //if(contentId == null || contentId.equals(""))

                                ContentCategoryVO contentCategoryVO = ContentCategoryController.getController()
                                        .findById(new Integer(entityId));
                                ContentVersionVO contentVersionVO = ContentVersionController
                                        .getContentVersionController()
                                        .getContentVersionVOWithId(contentCategoryVO.getContentVersionId());
                                ContentVO contentVO = ContentController.getContentController()
                                        .getContentVOWithId(contentVersionVO.getContentId());
                                String contentTypeDefinitionId = "" + contentVO.getContentTypeDefinitionId();
                                cacheInstance
                                        .flushGroup("selectiveCacheUpdateNonApplicable_contentTypeDefinitionId_"
                                                + contentTypeDefinitionId);
                                cacheInstance.putInCache("recacheMark_" + contentTypeDefinitionId,
                                        "" + System.currentTimeMillis());
                                cacheInstance.putInCache("recacheMark", "" + System.currentTimeMillis());
                            } catch (Exception e2) {
                                cacheInstance.putInCache("recacheAllMark", "" + System.currentTimeMillis());
                                logger.warn("Flushing all as it was a missing entity - was probably a delete: "
                                        + e2.getMessage());
                                cacheInstance.flushAll();
                            }
                        } else if (entity.indexOf("MediumContentCategoryImpl") > 0) {
                            logger.info("Special handling - no handling");
                        } else if (cacheName.equalsIgnoreCase("componentEditorVersionIdCache")
                                && entity.indexOf("ContentVersionImpl") > 0) {
                            logger.info("Special handling componentEditorVersionIdCache");
                            String contentId = sentContentId;
                            if (contentId == null || contentId.equals(""))
                                contentId = "" + ContentVersionController.getContentVersionController()
                                        .getContentIdForContentVersion(new Integer(entityId));

                            cacheInstance.flushGroup("content_" + contentId);
                            cacheInstance.flushGroup("contentVersion_" + entityId);
                        } else if ((cacheName.equalsIgnoreCase("componentEditorCache")
                                || cacheName.equalsIgnoreCase("componentPropertyCache")
                                || cacheName.equalsIgnoreCase("componentPropertyVersionIdCache")
                                || cacheName.equalsIgnoreCase("pageComponentsCache"))
                                && entity.indexOf("ContentVersionImpl") > 0) {
                            try {
                                logger.info("Special handling componentEditorVersionIdCache");
                                String contentId = sentContentId;
                                if (contentId == null || contentId.equals(""))
                                    contentId = "" + ContentVersionController.getContentVersionController()
                                            .getContentIdForContentVersion(new Integer(entityId));

                                ContentVO contentVO = ContentController.getContentController()
                                        .getContentVOWithId(new Integer(contentId));
                                if (contentVO != null && contentVO.getContentTypeDefinitionId() != null) {
                                    ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController
                                            .getController().getContentTypeDefinitionVOWithId(
                                                    contentVO.getContentTypeDefinitionId());
                                    if (ctdVO.getName().equals("Meta info"))
                                        cacheInstance.flushAll();
                                    else {
                                        if (cacheName.equalsIgnoreCase("componentEditorCache")
                                                && (ctdVO.getName().equals("HTMLTemplate")
                                                        || ctdVO.getName().equals("PagePartTemplate"))) {
                                            cacheInstance.flushAll(); //CacheController.clearCache("componentEditorCache");
                                        } else
                                            logger.info("No need to clear page stuff");
                                    }
                                }
                            } catch (Exception e2) {
                                if (e2.getCause() instanceof ObjectNotFoundException || (e2.getCause() != null
                                        && e2.getCause().getCause() instanceof ObjectNotFoundException))
                                    logger.info("Error clearing caches - object was probably deleted.");
                                else
                                    logger.warn("Error handling mixed caches: " + e2.getMessage(), e2);
                            }
                        } else {
                            if (entity.indexOf("EventImpl") == -1 && entity.indexOf(".Publication") == -1) {
                                if (logger.isInfoEnabled())
                                    logger.info("Clearing all on: " + cacheName + ":" + entity);

                                cacheInstance.flushAll();
                                if (logger.isInfoEnabled())
                                    logger.info("clearing:" + e.getKey());

                            }
                        }
                    } //BACK
                }

                long elapsedTime = t.getElapsedTime();
                if (elapsedTime > 20)
                    logger.info("Clear cache end took " + e.getKey() + ": " + elapsedTime);
                logger.info("Cleared cache:" + e.getKey());

                if (!selectiveCacheUpdate)
                    i.remove();

            } else {
                logger.info("Did not clear " + e.getKey());
            }
        }
        //}

        if (!useSelectivePageCacheUpdate || entity.indexOf("AccessRight") > -1) {
            logger.info("Clearing all pageCaches");
            CacheController.clearFileCaches("pageCache");
        }
    }

    t.printElapsedTime("clearCaches stop", 100);
    /*
    logger.info("clearCaches stop");
    long time = t.getElapsedTime();
    if(time > 3000)
       logger.warn("clearCaches took long time:" + time);
    */
}