001/* 002 * flattr4j - A Java library for Flattr 003 * 004 * Copyright (C) 2011 Richard "Shred" Körber 005 * http://flattr4j.shredzone.org 006 * 007 * This program is free software: you can redistribute it and/or modify 008 * it under the terms of the GNU General Public License / GNU Lesser 009 * General Public License as published by the Free Software Foundation, 010 * either version 3 of the License, or (at your option) any later version. 011 * 012 * Licensed under the Apache License, Version 2.0 (the "License"); 013 * you may not use this file except in compliance with the License. 014 * 015 * This program is distributed in the hope that it will be useful, 016 * but WITHOUT ANY WARRANTY; without even the implied warranty of 017 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 018 */ 019package org.shredzone.flattr4j.web.tag; 020 021import javax.servlet.jsp.JspException; 022import javax.servlet.jsp.PageContext; 023import javax.servlet.jsp.tagext.Tag; 024 025/** 026 * Utility methods for tag libraries. 027 * 028 * @author Richard "Shred" Körber 029 */ 030public final class TagUtils { 031 032 private TagUtils() { 033 // Private constructor 034 } 035 036 /** 037 * Set an attribute with the given scope. 038 * 039 * @param pageContext 040 * {@link PageContext} of the invoking tag 041 * @param attribute 042 * Attribute name 043 * @param value 044 * Value of that attribute 045 * @param scope 046 * Scope to be used. {@code null} means page scope. 047 * @throws JspException 048 * if the scope was unknown 049 */ 050 public static void setScopedAttribute(PageContext pageContext, String attribute, Object value, String scope) 051 throws JspException { 052 int scopeId = PageContext.PAGE_SCOPE; 053 if (scope != null) { 054 if ("page".equals(scope)) { 055 scopeId = PageContext.PAGE_SCOPE; 056 } else if ("request".equals(scope)) { 057 scopeId = PageContext.REQUEST_SCOPE; 058 } else if ("session".equals(scope)) { 059 scopeId = PageContext.SESSION_SCOPE; 060 } else if ("application".equals(scope)) { 061 scopeId = PageContext.APPLICATION_SCOPE; 062 } else { 063 throw new JspException("Unknown scope: " + scope); 064 } 065 } 066 pageContext.setAttribute(attribute, value, scopeId); 067 } 068 069 /** 070 * Finds an ancestor tag of the given type. Starting from the given Tag, it traverses 071 * up the parent tags until a tag of the given type is found. 072 * 073 * @param <T> 074 * Type to find and return 075 * @param from 076 * Tag to start from 077 * @param type 078 * Type to find 079 * @return Ancestor of that type, or {@code null} if none was found. 080 */ 081 @SuppressWarnings("unchecked") 082 public static <T> T findAncestorWithType(Tag from, Class<T> type) { 083 Tag parent = from.getParent(); 084 while (parent != null) { 085 if (type.isAssignableFrom(parent.getClass())) { 086 return (T) parent; 087 } 088 parent = parent.getParent(); 089 } 090 return null; 091 } 092 093}