001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software GmbH & Co. KG, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.flex;
029
030import org.opencms.flex.CmsFlexRequestKey.PathsBean;
031import org.opencms.loader.I_CmsResourceLoader;
032import org.opencms.main.CmsLog;
033import org.opencms.util.CmsStringUtil;
034
035import java.util.Arrays;
036import java.util.Collections;
037import java.util.HashSet;
038import java.util.Iterator;
039import java.util.List;
040import java.util.Map;
041import java.util.Set;
042
043import javax.servlet.http.HttpSession;
044
045import org.apache.commons.logging.Log;
046
047import com.google.common.collect.Lists;
048
049/**
050 * Key used to describe the caching behaviour of a specific resource.<p>
051 *
052 * It has a lot of variables that are directly accessed (which isn't good style, I know)
053 * to avoid method calling overhead (a cache is about speed, isn't it :).<p>
054 *
055 * @since 6.0.0
056 */
057public class CmsFlexCacheKey {
058
059    /** Flex cache keyword: always. */
060    private static final String CACHE_00_ALWAYS = "always";
061
062    /** Flex cache keyword: never. */
063    private static final String CACHE_01_NEVER = "never";
064
065    /** Flex cache keyword: uri. */
066    private static final String CACHE_02_URI = "uri";
067
068    /** Flex cache keyword: user. */
069    private static final String CACHE_03_USER = "user";
070
071    /** Flex cache keyword: params. */
072    private static final String CACHE_04_PARAMS = "params";
073
074    /** Flex cache keyword: no-params. */
075    private static final String CACHE_05_NO_PARAMS = "no-params";
076
077    /** Flex cache keyword: timeout. */
078    private static final String CACHE_06_TIMEOUT = "timeout";
079
080    /** Flex cache keyword: session. */
081    private static final String CACHE_07_SESSION = "session";
082
083    /** Flex cache keyword: schemes. */
084    private static final String CACHE_08_SCHEMES = "schemes";
085
086    /** Flex cache keyword: ports. */
087    private static final String CACHE_09_PORTS = "ports";
088
089    /** Flex cache keyword: false. */
090    private static final String CACHE_10_FALSE = CmsStringUtil.FALSE;
091
092    /** Flex cache keyword: parse-error. */
093    private static final String CACHE_11_PARSE_ERROR = "parse-error";
094
095    /** Flex cache keyword: true. */
096    private static final String CACHE_12_TRUE = CmsStringUtil.TRUE;
097
098    /** Flex cache keyword: ip. */
099    private static final String CACHE_13_IP = "ip";
100
101    /** Flex cache keyword: element. */
102    private static final String CACHE_14_ELEMENT = "element";
103
104    /** Flex cache keyword: locale. */
105    private static final String CACHE_15_LOCALE = "locale";
106
107    /** Flex cache keyword: encoding. */
108    private static final String CACHE_16_ENCODING = "encoding";
109
110    /** Flex cache keyword: site. */
111    private static final String CACHE_17_SITE = "site";
112
113    /** Flex cache keyword: attrs. */
114    private static final String CACHE_18_ATTRS = "attrs";
115
116    /** Flex cache keyword: no-attrs. */
117    private static final String CACHE_19_NO_ATTRS = "no-attrs";
118
119    /** Flex cache keyword: device. */
120    private static final String CACHE_20_DEVICE = "device";
121
122    /** Flex cache keyword: container-element. */
123    private static final String CACHE_21_CONTAINER_ELEMENT = "container-element";
124
125    /** Flex cache key component for the __forceAbsoluteLinks parameter. */
126    private static final String CACHE_FORCE_ABSOLUTE_LINKS = "force-abs";
127
128    /** The list of keywords of the Flex cache language. */
129    private static final List<String> CACHE_COMMANDS = Arrays.asList(
130        new String[] {
131            CACHE_00_ALWAYS,
132            CACHE_01_NEVER,
133            CACHE_02_URI,
134            CACHE_03_USER,
135            CACHE_04_PARAMS,
136            CACHE_05_NO_PARAMS,
137            CACHE_06_TIMEOUT,
138            CACHE_07_SESSION,
139            CACHE_08_SCHEMES,
140            CACHE_09_PORTS,
141            CACHE_10_FALSE,
142            CACHE_11_PARSE_ERROR,
143            CACHE_12_TRUE,
144            CACHE_13_IP,
145            CACHE_14_ELEMENT,
146            CACHE_15_LOCALE,
147            CACHE_16_ENCODING,
148            CACHE_17_SITE,
149            CACHE_18_ATTRS,
150            CACHE_19_NO_ATTRS,
151            CACHE_20_DEVICE,
152            CACHE_21_CONTAINER_ELEMENT});
153
154    /** Marker to identify use of certain String key members (uri, ip etc.). */
155    private static final String IS_USED = "/ /";
156
157    /** The log object for this class. */
158    private static final Log LOG = CmsLog.getLog(CmsFlexCacheKey.class);
159
160    /** Cache key variable: Determines if this resource can be cached alwys, never or under certain conditions. -1 = never, 0=check, 1=always. */
161    private int m_always;
162
163    /** Cache key variable: List of attributes. */
164    private Set<String> m_attrs;
165
166    /** Cache key variable: The current container element. */
167    private String m_containerElement;
168
169    /** Cache key variable: The current device. */
170    private String m_device;
171
172    /** Cache key variable: The requested element. */
173    private String m_element;
174
175    /** Cache key variable: The requested encoding. */
176    private String m_encoding;
177
178    /** Cache key variable: The ip address of the request. */
179    private String m_ip;
180
181    /** Cache key variable: The requested locale. */
182    private String m_locale;
183
184    /** Cache key variable: List of "blocking" attributes. */
185    private Set<String> m_noattrs;
186
187    /** Cache key variable: List of "blocking" parameters. */
188    private Set<String> m_noparams;
189
190    /** Cache key variable: List of parameters. */
191    private Set<String> m_params;
192
193    /** Flag raised in case a key parse error occurred. */
194    private boolean m_parseError;
195
196    /** Cache key variable: The request TCP/IP port. */
197    private Set<Integer> m_ports;
198
199    /** The OpenCms resource that this key is used for. */
200    private String m_resource;
201
202    /** Cache key variable: Distinguishes request schemes (http, https etc.). */
203    private Set<String> m_schemes;
204
205    /** Cache key variable: List of session variables. */
206    private Set<String> m_session;
207
208    /** Cache key variable: The current site root. */
209    private String m_site;
210
211    /** Cache key variable: Timeout of the resource. */
212    private long m_timeout;
213
214    /** Cache key variable: The uri of the original request. */
215    private String m_uri;
216
217    /** Cache key variable: The user id. */
218    private String m_user;
219
220    /** Resource without online / offline suffix. */
221    private String m_actualResource;
222
223    /**
224     * This constructor is used when building a cache key from set of cache directives.<p>
225     *
226     * These directives are attached to the properties of the requested resource
227     * on a property called "cache".
228     * The value of this poperty that is passed in this constructor as "cacheDirectives"
229     * is parsed to build the keys data structure.<p>
230     *
231     * In case a parsing error occures, the value of this key is set to "cache=never",
232     * and the hadParseError() flag is set to true.
233     * This is done to ensure that a valid key is always constructed with the constructor.<p>
234     *
235     * @param resourcename the full name of the resource including site root
236     * @param cacheDirectives the cache directives of the resource (value of the property "cache")
237     * @param online must be true for an online resource, false for offline resources
238     */
239    public CmsFlexCacheKey(String resourcename, String cacheDirectives, boolean online) {
240
241        m_actualResource = resourcename;
242        m_resource = getKeyName(resourcename, online);
243        m_always = -1;
244        m_timeout = -1;
245        if (cacheDirectives != null) {
246            parseFlexKey(cacheDirectives);
247        }
248        if (LOG.isDebugEnabled()) {
249            LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_GENERATED_1, toString()));
250        }
251    }
252
253    /**
254     * Calculates the cache key name that is used as key in
255     * the first level of the FlexCache.<p>
256     *
257     * @param resourcename the full name of the resource including site root
258     * @param online must be true for an online resource, false for offline resources
259     *
260     * @return the FlexCache key name
261     */
262    public static String getKeyName(String resourcename, boolean online) {
263
264        return resourcename.concat(online ? CmsFlexCache.CACHE_ONLINESUFFIX : CmsFlexCache.CACHE_OFFLINESUFFIX);
265    }
266
267    /**
268     * Returns resource name from given key name.<p>
269     *
270     * @param keyName given name of key.
271     * @return name of resource if key is valid, otherwise ""
272     */
273    public static String getResourceName(String keyName) {
274
275        if (keyName.endsWith(CmsFlexCache.CACHE_OFFLINESUFFIX) | keyName.endsWith(CmsFlexCache.CACHE_ONLINESUFFIX)) {
276            return keyName.split(" ")[0];
277        } else {
278            return "";
279        }
280    }
281
282    /**
283     * Appends a flex cache key value to the given buffer.<p>
284     *
285     * @param str the buffer to append to
286     * @param key the key to append
287     * @param value the value to append
288     */
289    private static void appendKeyValue(StringBuffer str, String key, String value) {
290
291        str.append(key);
292        if (value == IS_USED) {
293            str.append(";");
294        } else {
295            str.append("=(");
296            str.append(value);
297            str.append(");");
298        }
299    }
300
301    /**
302     * Returns the actual resource path under which this is cached, without online / offline suffix.<p>
303     *
304     * @return the actual resource path
305     */
306    public String getActualResource() {
307
308        return m_actualResource;
309    }
310
311    /**
312     * Gets the list of root paths for the cache key / request key combination which should be used to determine the set of flex cache buckets for the flex cache entry.<p>
313     *
314     * @param key the flex request key
315     * @return the list of paths which should be used to determine the flex cache buckets
316     */
317    public List<String> getPathsForBuckets(CmsFlexRequestKey key) {
318
319        PathsBean pathBean = key.getPaths();
320        List<String> paths = Lists.newArrayList();
321        if (m_uri != null) {
322            paths.add(pathBean.getUri());
323            paths.add(pathBean.getDetailElement());
324        }
325        if (m_site != null) {
326            paths.add(pathBean.getSite());
327        }
328        if (m_containerElement != null) {
329            paths.add(pathBean.getContainerElement());
330        }
331
332        paths.removeAll(Collections.singletonList(null));
333        return paths;
334    }
335
336    /**
337     * This flag is used to indicate that a parse error had
338     * occurred, which can happen if the cache directives String
339     * passed to the constructor using the response is
340     * not build according to the Flex cache language syntax.<p>
341     *
342     * @return true if a parse error did occur, false otherwise
343     */
344    public boolean hadParseError() {
345
346        return m_parseError;
347    }
348
349    /**
350     * Compares this key to the other key passed as parameter,
351     * from comparing the two keys, a variation String is constructed.<p>
352     *
353     * This method is the "heart" of the key matching process.<p>
354     *
355     * The assumtion is that this key should be the one constructed for the response,
356     * while the parameter key should have been constructed from the request.<p>
357     *
358     * A short example how this works:
359     * If the cache key is "cache=user" and the request is done from a guest user
360     * the constructed variation will be "user=(guest)".<p>
361     *
362     * @param key the key to match this key with
363     * @return null if not cachable, or the Variation String if cachable
364     */
365    public String matchRequestKey(CmsFlexRequestKey key) {
366
367        StringBuffer str = new StringBuffer(100);
368        if (m_always < 0) {
369            if (LOG.isDebugEnabled()) {
370                LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_KEYMATCH_CACHE_NEVER_0));
371            }
372            return null;
373        }
374
375        if (LOG.isDebugEnabled()) {
376            LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_KEYMATCH_CHECK_NO_PARAMS_0));
377        }
378        if ((m_noparams != null) && (key.getParams() != null)) {
379            if ((m_noparams.size() == 0) && (key.getParams().size() > 0)) {
380                return null;
381            }
382            Iterator<String> i = key.getParams().keySet().iterator();
383            while (i.hasNext()) {
384                if (m_noparams.contains(i.next())) {
385                    return null;
386                }
387            }
388        }
389
390        if (LOG.isDebugEnabled()) {
391            LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_KEYMATCH_CHECK_NO_ATTRS_0));
392        }
393        if ((m_noattrs != null) && (key.getAttributes() != null)) {
394            if ((m_noattrs.size() == 0) && (key.getAttributes().size() > 0)) {
395                return null;
396            }
397            Iterator<String> i = key.getAttributes().keySet().iterator();
398            while (i.hasNext()) {
399                if (m_noattrs.contains(i.next())) {
400                    return null;
401                }
402            }
403        }
404
405        if (m_always > 0) {
406            if (LOG.isDebugEnabled()) {
407                LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_KEYMATCH_CACHE_ALWAYS_0));
408            }
409            str.append(CACHE_00_ALWAYS);
410            return str.toString();
411        }
412
413        if (m_uri != null) {
414            appendKeyValue(str, CACHE_02_URI, key.getUri());
415        }
416
417        if (m_site != null) {
418            appendKeyValue(str, CACHE_17_SITE, key.getSite());
419        }
420
421        if (m_element != null) {
422            appendKeyValue(str, CACHE_14_ELEMENT, key.getElement());
423        }
424
425        if (m_device != null) {
426            appendKeyValue(str, CACHE_20_DEVICE, key.getDevice());
427        }
428
429        if (m_containerElement != null) {
430            appendKeyValue(str, CACHE_21_CONTAINER_ELEMENT, key.getContainerElement());
431        }
432
433        if (m_locale != null) {
434            appendKeyValue(str, CACHE_15_LOCALE, key.getLocale());
435        }
436
437        if (m_encoding != null) {
438            appendKeyValue(str, CACHE_16_ENCODING, key.getEncoding());
439        }
440
441        if (m_ip != null) {
442            appendKeyValue(str, CACHE_13_IP, key.getIp());
443        }
444
445        if (m_user != null) {
446            appendKeyValue(str, CACHE_03_USER, key.getUser());
447        }
448
449        if (m_params != null) {
450            str.append(CACHE_04_PARAMS);
451            str.append("=(");
452            Map<String, String[]> keyParams = key.getParams();
453            if (keyParams != null) {
454                if (m_params.size() > 0) {
455                    // match only params listed in cache directives
456                    Iterator<String> i = m_params.iterator();
457                    while (i.hasNext()) {
458                        Object o = i.next();
459                        if (keyParams.containsKey(o)) {
460                            str.append(o);
461                            str.append("=");
462                            // TODO: handle multiple occurrences of the same parameter value
463                            String[] values = keyParams.get(o);
464                            str.append(values[0]);
465                            if (i.hasNext()) {
466                                str.append(",");
467                            }
468                        }
469                    }
470                } else {
471                    // match all request params
472                    Iterator<Map.Entry<String, String[]>> i = keyParams.entrySet().iterator();
473                    while (i.hasNext()) {
474                        Map.Entry<String, String[]> entry = i.next();
475                        str.append(entry.getKey());
476                        str.append("=");
477                        // TODO: handle multiple occurrences of the same parameter value
478                        String[] values = entry.getValue();
479                        str.append(values[0]);
480                        if (i.hasNext()) {
481                            str.append(",");
482                        }
483                    }
484                }
485            }
486            str.append(");");
487        }
488
489        if (m_attrs != null) {
490            str.append(CACHE_18_ATTRS);
491            str.append("=(");
492            Map<String, Object> keyAttrs = key.getAttributes();
493            if (keyAttrs != null) {
494                if (m_attrs.size() > 0) {
495                    // match only attributes listed in cache directives
496                    Iterator<String> i = m_attrs.iterator();
497                    while (i.hasNext()) {
498                        String s = i.next();
499                        if (keyAttrs.containsKey(s)) {
500                            str.append(s);
501                            str.append("=");
502                            Object value = keyAttrs.get(s);
503                            str.append(value);
504                            if (i.hasNext()) {
505                                str.append(",");
506                            }
507                        }
508                    }
509                } else {
510                    // match all request attributes
511                    Iterator<Map.Entry<String, Object>> i = keyAttrs.entrySet().iterator();
512                    while (i.hasNext()) {
513                        Map.Entry<String, Object> entry = i.next();
514                        str.append(entry.getKey());
515                        str.append("=");
516                        Object value = entry.getValue();
517                        str.append(value);
518                        if (i.hasNext()) {
519                            str.append(",");
520                        }
521                    }
522                }
523            }
524            str.append(");");
525        }
526
527        if (m_session != null) {
528            StringBuffer buf = new StringBuffer(32);
529            boolean found = false;
530            buf.append(CACHE_07_SESSION);
531            buf.append("=(");
532            HttpSession keySession = key.getSession();
533            if (keySession != null) {
534                // match only session attributes listed in cache directives
535                Iterator<String> i = m_session.iterator();
536                while (i.hasNext()) {
537                    String name = i.next();
538                    Object val = keySession.getAttribute(name);
539                    if (val != null) {
540                        found = true;
541                        buf.append(name);
542                        buf.append("=");
543                        buf.append(val);
544                        if (i.hasNext()) {
545                            buf.append(",");
546                        }
547                    }
548                }
549            }
550            if (found) {
551                buf.append(");");
552                str.append(buf);
553            }
554        }
555
556        if (m_schemes != null) {
557            String s = key.getScheme();
558            if ((m_schemes.size() > 0) && (!m_schemes.contains(s))) {
559                return null;
560            }
561            appendKeyValue(str, CACHE_08_SCHEMES, s);
562        }
563
564        if (m_ports != null) {
565            Integer i = key.getPort();
566            if ((m_ports.size() > 0) && (!m_ports.contains(i))) {
567                return null;
568            }
569            str.append(CACHE_09_PORTS);
570            str.append("=(");
571            str.append(i);
572            str.append(");");
573        }
574
575        if (m_timeout > 0) {
576            str.append(CACHE_06_TIMEOUT);
577            str.append("=(");
578            str.append(m_timeout);
579            str.append(");");
580        }
581
582        if (str.length() > 0) {
583            // we don't want an element to just be cached with the __forceAbsoluteLinks parameter as key if it wouldn't be cached otherwise
584            appendKeyValue(str, CACHE_FORCE_ABSOLUTE_LINKS, "" + key.isForceAbsoluteLinks());
585            return str.toString();
586        } else {
587            return null;
588        }
589    }
590
591    /**
592     * @see java.lang.Object#toString()
593     *
594     * @return a complete String representation for this key
595     */
596    @Override
597    public String toString() {
598
599        StringBuffer str = new StringBuffer(100);
600
601        if (m_always < 0) {
602            str.append(CACHE_01_NEVER);
603            if (m_parseError) {
604                str.append(";");
605                str.append(CACHE_11_PARSE_ERROR);
606            }
607            return str.toString();
608        }
609        if (m_noparams != null) {
610            // add "no-cachable" parameters
611            str.append(CACHE_05_NO_PARAMS);
612            if (m_noparams.size() == 0) {
613                str.append(";");
614            } else {
615                str.append("=(");
616                Iterator<String> i = m_noparams.iterator();
617                while (i.hasNext()) {
618                    Object o = i.next();
619                    str.append(o);
620                    if (i.hasNext()) {
621                        str.append(",");
622                    }
623                }
624                str.append(");");
625            }
626        }
627        if (m_noattrs != null) {
628            // add "no-cachable" attributes
629            str.append(CACHE_19_NO_ATTRS);
630            if (m_noattrs.size() == 0) {
631                str.append(";");
632            } else {
633                str.append("=(");
634                Iterator<String> i = m_noattrs.iterator();
635                while (i.hasNext()) {
636                    String s = i.next();
637                    str.append(s);
638                    if (i.hasNext()) {
639                        str.append(",");
640                    }
641                }
642                str.append(");");
643            }
644        }
645        if (m_always > 0) {
646            str.append(CACHE_00_ALWAYS);
647            if (m_parseError) {
648                str.append(";");
649                str.append(CACHE_11_PARSE_ERROR);
650            }
651            return str.toString();
652        }
653        if (m_uri != null) {
654            // add uri
655            appendKeyValue(str, CACHE_02_URI, m_uri);
656        }
657        if (m_site != null) {
658            // add site
659            appendKeyValue(str, CACHE_17_SITE, m_site);
660        }
661        if (m_element != null) {
662            // add element
663            appendKeyValue(str, CACHE_14_ELEMENT, m_element);
664        }
665        if (m_device != null) {
666            appendKeyValue(str, CACHE_20_DEVICE, m_device);
667        }
668        if (m_containerElement != null) {
669            appendKeyValue(str, CACHE_21_CONTAINER_ELEMENT, m_containerElement);
670        }
671        if (m_locale != null) {
672            // add locale
673            appendKeyValue(str, CACHE_15_LOCALE, m_locale);
674        }
675        if (m_encoding != null) {
676            // add encoding
677            appendKeyValue(str, CACHE_16_ENCODING, m_encoding);
678        }
679        if (m_ip != null) {
680            // add ip
681            appendKeyValue(str, CACHE_13_IP, m_ip);
682        }
683        if (m_user != null) {
684            // add user
685            appendKeyValue(str, CACHE_03_USER, m_user);
686        }
687        if (m_params != null) {
688            // add parameters
689            str.append(CACHE_04_PARAMS);
690            if (m_params.size() == 0) {
691                str.append(";");
692            } else {
693                str.append("=(");
694                Iterator<String> i = m_params.iterator();
695                while (i.hasNext()) {
696                    Object o = i.next();
697                    if (I_CmsResourceLoader.PARAMETER_ELEMENT.equals(o)) {
698                        continue;
699                    }
700                    str.append(o);
701                    if (i.hasNext()) {
702                        str.append(",");
703                    }
704                }
705                str.append(");");
706            }
707        }
708        if (m_attrs != null) {
709            // add attributes
710            str.append(CACHE_18_ATTRS);
711            if (m_attrs.size() == 0) {
712                str.append(";");
713            } else {
714                str.append("=(");
715                Iterator<String> i = m_attrs.iterator();
716                while (i.hasNext()) {
717                    String s = i.next();
718                    str.append(s);
719                    if (i.hasNext()) {
720                        str.append(",");
721                    }
722                }
723                str.append(");");
724            }
725        }
726        if (m_session != null) {
727            // add session variables
728            str.append(CACHE_07_SESSION);
729            str.append("=(");
730            Iterator<String> i = m_session.iterator();
731            while (i.hasNext()) {
732                Object o = i.next();
733                str.append(o);
734                if (i.hasNext()) {
735                    str.append(",");
736                }
737            }
738            str.append(");");
739        }
740        if (m_timeout >= 0) {
741            // add timeout
742            str.append(CACHE_06_TIMEOUT);
743            str.append("=(");
744            str.append(m_timeout);
745            str.append(");");
746        }
747        if (m_schemes != null) {
748            // add schemes
749            str.append(CACHE_08_SCHEMES);
750            if (m_schemes.size() == 0) {
751                str.append(";");
752            } else {
753                str.append("=(");
754                Iterator<String> i = m_schemes.iterator();
755                while (i.hasNext()) {
756                    str.append(i.next());
757                    if (i.hasNext()) {
758                        str.append(",");
759                    }
760                }
761                str.append(");");
762            }
763        }
764        if (m_ports != null) {
765            // add ports
766            str.append(CACHE_09_PORTS);
767            if (m_ports.size() == 0) {
768                str.append(";");
769            } else {
770                str.append("=(");
771                Iterator<Integer> i = m_ports.iterator();
772                while (i.hasNext()) {
773                    str.append(i.next());
774                    if (i.hasNext()) {
775                        str.append(",");
776                    }
777                }
778                str.append(");");
779            }
780        }
781
782        if (m_parseError) {
783            str.append(CACHE_11_PARSE_ERROR);
784        }
785        return str.toString();
786    }
787
788    /**
789     * Returns the resource.<p>
790     *
791     * @return the resource
792     */
793    protected String getResource() {
794
795        return m_resource;
796    }
797
798    /**
799     * Returns the timeout.<p>
800     *
801     * @return the timeout
802     */
803    protected long getTimeout() {
804
805        return m_timeout;
806    }
807
808    /**
809     * Parse a String in the Flex cache language and construct
810     * the key data structure from this.<p>
811     *
812     * @param key the String to parse (usually read from the file property "cache")
813     */
814    private void parseFlexKey(String key) {
815
816        List<String> tokens = CmsStringUtil.splitAsList(key, ';', false);
817        Iterator<String> i = tokens.iterator();
818        try {
819            while (i.hasNext()) {
820                String t = i.next();
821                String k = null;
822                String v = null;
823                int idx = t.indexOf('=');
824                if (idx >= 0) {
825                    k = t.substring(0, idx).trim();
826                    if (t.length() > idx) {
827                        v = t.substring(idx + 1).trim();
828                    }
829                } else {
830                    k = t.trim();
831                }
832                m_always = 0;
833                if (LOG.isDebugEnabled()) {
834                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_PARSE_FLEXKEY_3, t, k, v));
835                }
836                switch (CACHE_COMMANDS.indexOf(k)) {
837                    case 0: // always
838                    case 12: // true
839                        m_always = 1;
840                        // continue processing (make sure we find a "never" behind "always")
841                        break;
842                    case 1: // never
843                    case 10: // false
844                        m_always = -1;
845                        // no need for any further processing
846                        return;
847                    case 2: // uri
848                        m_uri = IS_USED; // marks m_uri as being used
849                        break;
850                    case 3: // user
851                        m_user = IS_USED; // marks m_user as being used
852                        break;
853                    case 4: // params
854                        if (v != null) {
855                            m_params = parseValueList(v);
856                        } else {
857                            m_params = Collections.emptySet();
858                        }
859
860                        if (m_params.contains(I_CmsResourceLoader.PARAMETER_ELEMENT)) {
861                            // workaround for element setting by parameter in OpenCms < 6.0
862                            m_element = IS_USED;
863                            m_params.remove(I_CmsResourceLoader.PARAMETER_ELEMENT);
864                            if (m_params.size() == 0) {
865                                m_params = null;
866                            }
867                        }
868                        break;
869                    case 5: // no-params
870                        if (v != null) {
871                            // no-params are present
872                            m_noparams = parseValueList(v);
873                        } else {
874                            // never cache with parameters
875                            m_noparams = Collections.emptySet();
876                        }
877                        break;
878                    case 6: // timeout
879                        m_timeout = Integer.parseInt(v);
880                        break;
881                    case 7: // session
882                        m_session = parseValueList(v);
883                        if (m_session.size() <= 0) {
884                            // session must have at last one variable set
885                            m_parseError = true;
886                        }
887                        break;
888                    case 8: // schemes
889                        m_schemes = parseValueList(v);
890                        break;
891                    case 9: // ports
892                        Set<String> ports = parseValueList(v);
893                        m_ports = new HashSet<Integer>(ports.size());
894                        for (String p : ports) {
895                            try {
896                                m_ports.add(Integer.valueOf(p));
897                            } catch (NumberFormatException e) {
898                                // ignore this number
899                            }
900                        }
901                        break;
902                    case 11: // previous parse error - ignore
903                        break;
904                    case 13: // ip
905                        m_ip = IS_USED; // marks ip as being used
906                        break;
907                    case 14: // element
908                        m_element = IS_USED;
909                        break;
910                    case 15: // locale
911                        m_locale = IS_USED;
912                        break;
913                    case 16: // encoding
914                        m_encoding = IS_USED;
915                        break;
916                    case 17: // site
917                        m_site = IS_USED;
918                        break;
919                    case 18: // attrs
920                        if (v != null) {
921                            m_attrs = parseValueList(v);
922                        } else {
923                            m_attrs = null;
924                        }
925                        break;
926                    case 19: // no-attrs
927                        if (v != null) {
928                            // no-attrs are present
929                            m_noattrs = parseValueList(v);
930                        } else {
931                            // never cache with attributes
932                            m_noattrs = Collections.emptySet();
933                        }
934                        break;
935                    case 20: // device
936                        m_device = IS_USED; // marks m_device as being used
937                        break;
938                    case 21: // container element
939                        m_containerElement = IS_USED;
940                        break;
941                    default: // unknown directive, throw error
942                        m_parseError = true;
943                }
944            }
945        } catch (Exception e) {
946            // any Exception here indicates a parsing error
947            if (LOG.isErrorEnabled()) {
948                LOG.error(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_PARSE_ERROR_1, e.toString()), e);
949            }
950            m_parseError = true;
951        }
952        if (m_parseError) {
953            // If string is invalid set cache to "never"
954            m_always = -1;
955        }
956    }
957
958    /**
959     * A helper method for the parsing process which parses
960     * Strings like groups=(a, b, c).<p>
961     *
962     * @param value the String to parse
963     * @return a Map that contains of the parsed values, only the keyset of the Map is needed later
964     */
965    private Set<String> parseValueList(String value) {
966
967        if (value.charAt(0) == '(') {
968            value = value.substring(1);
969        }
970        int len = value.length() - 1;
971        if (value.charAt(len) == ')') {
972            value = value.substring(0, len);
973        }
974        if (value.charAt(len - 1) == ',') {
975            value = value.substring(0, len - 1);
976        }
977        if (LOG.isDebugEnabled()) {
978            LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_PARSE_VALUES_1, value));
979        }
980        List<String> tokens = CmsStringUtil.splitAsList(value, ',', true);
981        Set<String> result = new HashSet<String>();
982        result.addAll(tokens);
983        return result;
984    }
985}