cachetag.java

来自「一个不错的cache」· Java 代码 · 共 797 行 · 第 1/2 页

JAVA
797
字号
    public void doCatch(Throwable throwable) throws Throwable {        throw throwable;    }    /**    * The end tag - clean up variables used.    *    * @throws JspTagException The standard exception thrown.    * @return The standard BodyTag return.    */    public int doEndTag() throws JspTagException {        return EVAL_PAGE;    }    public void doFinally() {        if (cancelUpdateRequired && (actualKey != null)) {            cache.cancelUpdate(actualKey);        }    }    /**    * The start of the tag.    * <p>    * Grabs the administrator, the cache, the specific cache entry, then decides    * whether to refresh.    * <p>    * If no refresh is needed, this serves the cached content directly.    *    * @throws JspTagException The standard exception thrown.    * @return The standard doStartTag() return.    */    public int doStartTag() throws JspTagException {        cancelUpdateRequired = false;        useBody = true;        content = null;        // We can only skip the body if the cache has the data        int returnCode = EVAL_BODY_BUFFERED;        if (admin == null) {            admin = ServletCacheAdministrator.getInstance(pageContext.getServletContext());        }        // Retrieve the cache        if (scope == PageContext.SESSION_SCOPE) {            cache = admin.getSessionScopeCache(((HttpServletRequest) pageContext.getRequest()).getSession(true));        } else {            cache = admin.getAppScopeCache(pageContext.getServletContext());        }        // This allows to have multiple cache tags on a single page without        // having to specify keys. However, nested cache tags are not supported.        // In that case you would have to supply a key.        String suffix = null;        if (key == null) {            synchronized (pageContext.getRequest()) {                Object o = pageContext.getRequest().getAttribute(CACHE_TAG_COUNTER_KEY);                if (o == null) {                    suffix = "1";                } else {                    suffix = Integer.toString(Integer.parseInt((String) o) + 1);                }            }            pageContext.getRequest().setAttribute(CACHE_TAG_COUNTER_KEY, suffix);        }        // Generate the actual cache key        actualKey = admin.generateEntryKey(key, (HttpServletRequest) pageContext.getRequest(), scope, language, suffix);        /*        if        - refresh is not set,        - the cacheEntry itself does not need to be refreshed before 'time' and        - the administrator has not had the cache entry's scope flushed        send out the cached version!        */        try {            if (refresh) {                // Force a refresh                content = (String) cache.getFromCache(actualKey, 0, cron);            } else {                // Use the specified refresh period                content = (String) cache.getFromCache(actualKey, time, cron);            }            try {                if (log.isDebugEnabled()) {                    log.debug("<cache>: Using cached entry : " + actualKey);                }                // Ensure that the cache returns the data correctly. Else re-evaluate the body                if ((content != null)) {                    if (mode != SILENT_MODE) {                        pageContext.getOut().write(content);                    }                    returnCode = SKIP_BODY;                }            } catch (IOException e) {                throw new JspTagException("IO Exception: " + e.getMessage());            }        } catch (NeedsRefreshException nre) {            cancelUpdateRequired = true;            content = (String) nre.getCacheContent();        }        if (returnCode == EVAL_BODY_BUFFERED) {            if (log.isDebugEnabled()) {                log.debug("<cache>: Cached content not used: New cache entry, cache stale or scope flushed : " + actualKey);            }        }        return returnCode;    }    /**    * Convert a SimpleDateFormat string to seconds    * Acceptable format are :    * <ul>    * <li>0s (seconds)    * <li>0m (minute)    * <li>0h (hour)    * <li>0d (day)    * <li>0w (week)    * </ul>    * @param   duration The simple date time to parse    * @return  The value in seconds    */    private int parseDuration(String duration) {        int time = 0;        //Detect if the factor is specified        try {            time = Integer.parseInt(duration);        } catch (Exception ex) {            //Extract number and ajust this number with the time factor            for (int i = 0; i < duration.length(); i++) {                if (!Character.isDigit(duration.charAt(i))) {                    time = Integer.parseInt(duration.substring(0, i));                    switch ((int) duration.charAt(i)) {                        case (int) 's':                            time *= SECOND;                            break;                        case (int) 'm':                            time *= MINUTE;                            break;                        case (int) 'h':                            time *= HOUR;                            break;                        case (int) 'd':                            time *= DAY;                            break;                        case (int) 'w':                            time *= WEEK;                            break;                        default:                        //no defined use as is                    }                    break;                }                // if            }            // for        }        // catch        return time;    }    /**    * Parse an ISO-8601 format date and return it's value in seconds    *    * @param duration The ISO-8601 date    * @return The equivalent number of seconds    * @throws Exception    */    private int parseISO_8601_Duration(String duration) throws Exception {        int years = 0;        int months = 0;        int days = 0;        int hours = 0;        int mins = 0;        int secs = 0;        // If there is a negative sign, it must be first        // If it is present, we will ignore it        int index = duration.indexOf("-");        if (index > 0) {            throw new Exception("Invalid duration (- must be at the beginning)");        }        // First caracter must be P        String workValue = duration.substring(index + 1);        if (workValue.charAt(0) != 'P') {            throw new Exception("Invalid duration (P must be at the beginning)");        }        // Must contain a value        workValue = workValue.substring(1);        if (workValue.length() == 0) {            throw new Exception("Invalid duration (nothing specified)");        }        // Check if there is a T        index = workValue.indexOf('T');        String timeString = "";        if (index > 0) {            timeString = workValue.substring(index + 1);            // Time cannot be empty            if (timeString.equals("")) {                throw new Exception("Invalid duration (T with no time)");            }            workValue = workValue.substring(0, index);        } else if (index == 0) {            timeString = workValue.substring(1);            workValue = "";        }        if (!workValue.equals("")) {            validateDateFormat(workValue);            int yearIndex = workValue.indexOf('Y');            int monthIndex = workValue.indexOf('M');            int dayIndex = workValue.indexOf('D');            if ((yearIndex != -1) && (monthIndex != -1) && (yearIndex > monthIndex)) {                throw new Exception("Invalid duration (Date part not properly specified)");            }            if ((yearIndex != -1) && (dayIndex != -1) && (yearIndex > dayIndex)) {                throw new Exception("Invalid duration (Date part not properly specified)");            }            if ((dayIndex != -1) && (monthIndex != -1) && (monthIndex > dayIndex)) {                throw new Exception("Invalid duration (Date part not properly specified)");            }            if (yearIndex >= 0) {                years = (new Integer(workValue.substring(0, yearIndex))).intValue();            }            if (monthIndex >= 0) {                months = (new Integer(workValue.substring(yearIndex + 1, monthIndex))).intValue();            }            if (dayIndex >= 0) {                if (monthIndex >= 0) {                    days = (new Integer(workValue.substring(monthIndex + 1, dayIndex))).intValue();                } else {                    if (yearIndex >= 0) {                        days = (new Integer(workValue.substring(yearIndex + 1, dayIndex))).intValue();                    } else {                        days = (new Integer(workValue.substring(0, dayIndex))).intValue();                    }                }            }        }        if (!timeString.equals("")) {            validateHourFormat(timeString);            int hourIndex = timeString.indexOf('H');            int minuteIndex = timeString.indexOf('M');            int secondIndex = timeString.indexOf('S');            if ((hourIndex != -1) && (minuteIndex != -1) && (hourIndex > minuteIndex)) {                throw new Exception("Invalid duration (Time part not properly specified)");            }            if ((hourIndex != -1) && (secondIndex != -1) && (hourIndex > secondIndex)) {                throw new Exception("Invalid duration (Time part not properly specified)");            }            if ((secondIndex != -1) && (minuteIndex != -1) && (minuteIndex > secondIndex)) {                throw new Exception("Invalid duration (Time part not properly specified)");            }            if (hourIndex >= 0) {                hours = (new Integer(timeString.substring(0, hourIndex))).intValue();            }            if (minuteIndex >= 0) {                mins = (new Integer(timeString.substring(hourIndex + 1, minuteIndex))).intValue();            }            if (secondIndex >= 0) {                if (timeString.length() != (secondIndex + 1)) {                    throw new Exception("Invalid duration (Time part not properly specified)");                }                if (minuteIndex >= 0) {                    timeString = timeString.substring(minuteIndex + 1, timeString.length() - 1);                } else {                    if (hourIndex >= 0) {                        timeString = timeString.substring(hourIndex + 1, timeString.length() - 1);                    } else {                        timeString = timeString.substring(0, timeString.length() - 1);                    }                }                if (timeString.indexOf('.') == (timeString.length() - 1)) {                    throw new Exception("Invalid duration (Time part not properly specified)");                }                secs = (new Double(timeString)).intValue();            }        }        // Compute Value        return secs + (mins * MINUTE) + (hours * HOUR) + (days * DAY) + (months * MONTH) + (years * YEAR);    }    /**    * Validate the basic date format    *    * @param basicDate The string to validate    * @throws Exception    */    private void validateDateFormat(String basicDate) throws Exception {        int yearCounter = 0;        int monthCounter = 0;        int dayCounter = 0;        for (int counter = 0; counter < basicDate.length(); counter++) {            // Check if there's any other caracters than Y, M, D and numbers            if (!Character.isDigit(basicDate.charAt(counter)) && (basicDate.charAt(counter) != 'Y') && (basicDate.charAt(counter) != 'M') && (basicDate.charAt(counter) != 'D')) {                throw new Exception("Invalid duration (Date part not properly specified)");            }            // Check if the allowed caracters are present more than 1 time            if (basicDate.charAt(counter) == 'Y') {                yearCounter++;            }            if (basicDate.charAt(counter) == 'M') {                monthCounter++;            }            if (basicDate.charAt(counter) == 'D') {                dayCounter++;            }        }        if ((yearCounter > 1) || (monthCounter > 1) || (dayCounter > 1)) {            throw new Exception("Invalid duration (Date part not properly specified)");        }    }    /**    * Validate the basic hour format    *    * @param basicHour The string to validate    * @throws Exception    */    private void validateHourFormat(String basicHour) throws Exception {        int minuteCounter = 0;        int secondCounter = 0;        int hourCounter = 0;        for (int counter = 0; counter < basicHour.length(); counter++) {            if (!Character.isDigit(basicHour.charAt(counter)) && (basicHour.charAt(counter) != 'H') && (basicHour.charAt(counter) != 'M') && (basicHour.charAt(counter) != 'S') && (basicHour.charAt(counter) != '.')) {                throw new Exception("Invalid duration (Time part not properly specified)");            }            if (basicHour.charAt(counter) == 'H') {                hourCounter++;            }            if (basicHour.charAt(counter) == 'M') {                minuteCounter++;            }            if (basicHour.charAt(counter) == 'S') {                secondCounter++;            }        }        if ((hourCounter > 1) || (minuteCounter > 1) || (secondCounter > 1)) {            throw new Exception("Invalid duration (Time part not properly specified)");        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?