Kawai Wiki

Compare Revisions

Ignore whitespace Rev 192 → Rev 193

/trunk/src/test/java/org/kawai/helper/PropertyAsserter.java
33,157 → 33,223
import static org.junit.Assert.fail;
 
/**
* Test utility class that makes easy work of testing default behavior of getters and setters.
* Test utility class that makes easy work of testing
* default behavior of getters and setters.
*/
public final class PropertyAsserter {
 
private static final Log log = LogFactory.getLog(PropertyAsserter.class);
/**
* Attribute constant log of PropertyAsserter.
*/
private static final Log log = LogFactory.getLog(PropertyAsserter.class);
/**
* Attribute constant TYPE_ARGUMENTS of PropertyAsserter.
*/
private static final Map<Class, Object> TYPE_ARGUMENTS = new HashMap<Class, Object>();
/**
* Attribute constant DEFAULT_TYPE_ARGUMENTS of PropertyAsserter.
*/
private static final Map<Class, Object> DEFAULT_TYPE_ARGUMENTS = Collections.unmodifiableMap(new HashMap<Class, Object>(TYPE_ARGUMENTS));
/**
* Attribute constant TEST_ARRAY_SIZE of PropertyAsserter.
*/
private static final int TEST_ARRAY_SIZE = 10;
 
private static final Map<Class, Object> TYPE_ARGUMENTS = new HashMap<Class, Object>();
static {
TYPE_ARGUMENTS.put(Collection.class, new ArrayList());
TYPE_ARGUMENTS.put(List.class, new ArrayList());
TYPE_ARGUMENTS.put(Set.class, new HashSet());
TYPE_ARGUMENTS.put(SortedSet.class, new TreeSet());
TYPE_ARGUMENTS.put(Map.class, new HashMap());
TYPE_ARGUMENTS.put(SortedMap.class, new TreeMap());
TYPE_ARGUMENTS.put(Boolean.class, true);
TYPE_ARGUMENTS.put(Boolean.TYPE, true);
TYPE_ARGUMENTS.put(Character.class, 'Z');
TYPE_ARGUMENTS.put(Character.TYPE, 'Z');
TYPE_ARGUMENTS.put(Byte.class, (byte) 10);
TYPE_ARGUMENTS.put(Byte.TYPE, (byte) 10);
TYPE_ARGUMENTS.put(Short.class, (short) 10);
TYPE_ARGUMENTS.put(Short.TYPE, (short) 10);
TYPE_ARGUMENTS.put(Integer.class, 10);
TYPE_ARGUMENTS.put(Integer.TYPE, 10);
TYPE_ARGUMENTS.put(Long.class, 10L);
TYPE_ARGUMENTS.put(Long.TYPE, 10L);
TYPE_ARGUMENTS.put(Float.class, 3.14159F);
TYPE_ARGUMENTS.put(Float.TYPE, 3.14159F);
TYPE_ARGUMENTS.put(Double.class, 3.14159);
TYPE_ARGUMENTS.put(Double.TYPE, 3.14159);
TYPE_ARGUMENTS.put(java.sql.Date.class, new java.sql.Date(new Date().getTime()));
TYPE_ARGUMENTS.put(Timestamp.class, new Timestamp(new Date().getTime()));
TYPE_ARGUMENTS.put(Calendar.class, Calendar.getInstance());
}
 
static {
TYPE_ARGUMENTS.put(Collection.class, new ArrayList());
TYPE_ARGUMENTS.put(List.class, new ArrayList());
TYPE_ARGUMENTS.put(Set.class, new HashSet());
TYPE_ARGUMENTS.put(SortedSet.class, new TreeSet());
TYPE_ARGUMENTS.put(Map.class, new HashMap());
TYPE_ARGUMENTS.put(SortedMap.class, new TreeMap());
TYPE_ARGUMENTS.put(Boolean.class, true);
TYPE_ARGUMENTS.put(Boolean.TYPE, true);
TYPE_ARGUMENTS.put(Character.class, 'Z');
TYPE_ARGUMENTS.put(Character.TYPE, 'Z');
TYPE_ARGUMENTS.put(Byte.class, (byte) 10);
TYPE_ARGUMENTS.put(Byte.TYPE, (byte) 10);
TYPE_ARGUMENTS.put(Short.class, (short) 10);
TYPE_ARGUMENTS.put(Short.TYPE, (short) 10);
TYPE_ARGUMENTS.put(Integer.class, 10);
TYPE_ARGUMENTS.put(Integer.TYPE, 10);
TYPE_ARGUMENTS.put(Long.class, 10L);
TYPE_ARGUMENTS.put(Long.TYPE, 10L);
TYPE_ARGUMENTS.put(Float.class, 3.14159F);
TYPE_ARGUMENTS.put(Float.TYPE, 3.14159F);
TYPE_ARGUMENTS.put(Double.class, 3.14159);
TYPE_ARGUMENTS.put(Double.TYPE, 3.14159);
TYPE_ARGUMENTS.put(java.sql.Date.class, new java.sql.Date(new Date().getTime()));
TYPE_ARGUMENTS.put(Timestamp.class, new Timestamp(new Date().getTime()));
TYPE_ARGUMENTS.put(Calendar.class, Calendar.getInstance());
}
/**
* Default constructor.
*/
private PropertyAsserter() {
 
private static final Map<Class, Object> DEFAULT_TYPE_ARGUMENTS = Collections.unmodifiableMap(new HashMap<Class, Object>(TYPE_ARGUMENTS));
}
 
private static final int TEST_ARRAY_SIZE = 10;
/**
* Helper method.
* @param type Class
* @param defaultArgument Object
*/
public static void registerTypeAndDefaultArgument(Class type, Object defaultArgument) {
TYPE_ARGUMENTS.put(type, defaultArgument);
}
 
private PropertyAsserter() {
}
/**
* Helper method.
* @param type Class
*/
public static void deregisterType(Class type) {
TYPE_ARGUMENTS.remove(type);
}
 
public static void registerTypeAndDefaultArgument(Class type, Object defaultArgument) {
TYPE_ARGUMENTS.put(type, defaultArgument);
}
/**
* Helper method.
*/
public static void resetToDefaultTypes() {
TYPE_ARGUMENTS.clear();
TYPE_ARGUMENTS.putAll(DEFAULT_TYPE_ARGUMENTS);
}
 
public static void deregisterType(Class type) {
TYPE_ARGUMENTS.remove(type);
}
/**
* Helper method.
* @param type Class
* @return Object
*/
public static Object defaultArgumentForType(Class type) {
return TYPE_ARGUMENTS.get(type);
}
 
public static void resetToDefaultTypes() {
TYPE_ARGUMENTS.clear();
TYPE_ARGUMENTS.putAll(DEFAULT_TYPE_ARGUMENTS);
}
/**
* Assert method.
* @param target Object
* @param property String
*/
public static void assertBasicGetterSetterBehavior(Object target, String property) {
assertBasicGetterSetterBehavior(target, property, null);
}
 
public static Object defaultArgumentForType(Class type) {
return TYPE_ARGUMENTS.get(type);
}
/**
* Assert method.
* @param target Object
* @param property String
* @param argument Object
*/
public static void assertBasicGetterSetterBehavior(Object target, String property, Object argument) {
try {
PropertyDescriptor descriptor = new PropertyDescriptor(property, target.getClass());
Object arg = argument;
Class type = descriptor.getPropertyType();
if (arg == null) {
if (type.isArray()) {
arg = Array.newInstance(type.getComponentType(), new int[] {TEST_ARRAY_SIZE });
} else if (type.isEnum()) {
arg = type.getEnumConstants()[0];
} else if (TYPE_ARGUMENTS.containsKey(type)) {
arg = TYPE_ARGUMENTS.get(type);
} else {
arg = invokeDefaultConstructorEvenIfPrivate(type);
}
}
 
public static void assertBasicGetterSetterBehavior(Object target, String property) {
assertBasicGetterSetterBehavior(target, property, null);
}
Method writeMethod = descriptor.getWriteMethod();
Method readMethod = descriptor.getReadMethod();
 
public static void assertBasicGetterSetterBehavior(Object target, String property, Object argument) {
try {
PropertyDescriptor descriptor = new PropertyDescriptor(property, target.getClass());
Object arg = argument;
Class type = descriptor.getPropertyType();
if (arg == null) {
if (type.isArray()) {
arg = Array.newInstance(type.getComponentType(), new int[] {TEST_ARRAY_SIZE });
} else if (type.isEnum()) {
arg = type.getEnumConstants()[0];
} else if (TYPE_ARGUMENTS.containsKey(type)) {
arg = TYPE_ARGUMENTS.get(type);
} else {
arg = invokeDefaultConstructorEvenIfPrivate(type);
}
}
writeMethod.invoke(target, arg);
Object propertyValue = readMethod.invoke(target);
if (type.isPrimitive()) {
assertEquals(property + " getter/setter failed test", arg, propertyValue);
} else {
assertSame(property + " getter/setter failed test", arg, propertyValue);
}
} catch (IntrospectionException e) {
String msg = "Error creating PropertyDescriptor for property [" + property + "]. Do you have a getter and a setter?";
log.error(msg, e);
fail(msg);
} catch (IllegalAccessException e) {
String msg = "Error accessing property. Are the getter and setter both accessible?";
log.error(msg, e);
fail(msg);
} catch (InvocationTargetException e) {
String msg = "Error invoking method on target";
log.error(msg, e);
fail(msg);
}
}
 
Method writeMethod = descriptor.getWriteMethod();
Method readMethod = descriptor.getReadMethod();
/**
* Reflection method.
* @param type Class
* @return Object
*/
private static Object invokeDefaultConstructorEvenIfPrivate(Class type) {
try {
Constructor ctor = type.getDeclaredConstructor();
ctor.setAccessible(true);
return ctor.newInstance();
} catch (Exception ex) {
throw new RuntimeException("Could not invoke default constructor on type " + type, ex);
}
}
 
writeMethod.invoke(target, arg);
Object propertyValue = readMethod.invoke(target);
if (type.isPrimitive()) {
assertEquals(property + " getter/setter failed test", arg, propertyValue);
} else {
assertSame(property + " getter/setter failed test", arg, propertyValue);
}
} catch (IntrospectionException e) {
String msg = "Error creating PropertyDescriptor for property [" + property + "]. Do you have a getter and a setter?";
log.error(msg, e);
fail(msg);
} catch (IllegalAccessException e) {
String msg = "Error accessing property. Are the getter and setter both accessible?";
log.error(msg, e);
fail(msg);
} catch (InvocationTargetException e) {
String msg = "Error invoking method on target";
log.error(msg, e);
fail(msg);
}
}
/**
* Assert method.
* @param target Object
* @param properties Map<String, Object>
*/
public static void assertBasicGetterSetterBehavior(Object target, Map<String, Object> properties) {
Set<Map.Entry<String, Object>> entries = properties.entrySet();
for (Map.Entry<String, Object> entry : entries) {
assertBasicGetterSetterBehavior(target, entry.getKey(), entry.getValue());
}
}
 
private static Object invokeDefaultConstructorEvenIfPrivate(Class type) {
try {
Constructor ctor = type.getDeclaredConstructor();
ctor.setAccessible(true);
return ctor.newInstance();
} catch (Exception ex) {
throw new RuntimeException("Could not invoke default constructor on type " + type, ex);
}
}
/**
* Assert method.
* @param target Object
* @param propertyNames String...
*/
public static void assertBasicGetterSetterBehavior(Object target, String... propertyNames) {
Map<String, Object> properties = new LinkedHashMap<String, Object>();
for (String propertyName : propertyNames) {
properties.put(propertyName, null);
}
assertBasicGetterSetterBehavior(target, properties);
}
 
public static void assertBasicGetterSetterBehavior(Object target, Map<String, Object> properties) {
Set<Map.Entry<String, Object>> entries = properties.entrySet();
for (Map.Entry<String, Object> entry : entries) {
assertBasicGetterSetterBehavior(target, entry.getKey(), entry.getValue());
}
}
/**
* Assert method.
* @param target Object
*/
public static void assertBasicGetterSetterBehavior(Object target) {
assertBasicGetterSetterBehaviorWithBlacklist(target);
}
 
public static void assertBasicGetterSetterBehavior(Object target, String... propertyNames) {
Map<String, Object> properties = new LinkedHashMap<String, Object>();
for (String propertyName : propertyNames) {
properties.put(propertyName, null);
}
assertBasicGetterSetterBehavior(target, properties);
}
/**
* Assert method.
* @param target Object
* @param propertyNames String...
*/
public static void assertBasicGetterSetterBehaviorWithBlacklist(Object target, String... propertyNames) {
List<String> blacklist = Arrays.asList(propertyNames);
try {
BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : descriptors) {
if (descriptor.getWriteMethod() == null) {
continue;
}
if (!blacklist.contains(descriptor.getDisplayName())) {
assertBasicGetterSetterBehavior(target, descriptor.getDisplayName());
}
}
} catch (IntrospectionException e) {
fail("Failed while introspecting target " + target.getClass());
}
}
 
public static void assertBasicGetterSetterBehavior(Object target) {
assertBasicGetterSetterBehaviorWithBlacklist(target);
}
 
public static void assertBasicGetterSetterBehaviorWithBlacklist(Object target, String... propertyNames) {
List<String> blacklist = Arrays.asList(propertyNames);
try {
BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : descriptors) {
if (descriptor.getWriteMethod() == null) {
continue;
}
if (!blacklist.contains(descriptor.getDisplayName())) {
assertBasicGetterSetterBehavior(target, descriptor.getDisplayName());
}
}
} catch (IntrospectionException e) {
fail("Failed while introspecting target " + target.getClass());
}
}
 
}
}
/trunk/src/main/java/org/kawai/model/User.java
1,55 → 1,112
package org.kawai.model;
 
 
/**
* Model class User.
*
* @author Sergio Oliveira
*
*/
public class User {
private int id;
private String username;
private String password;
private int groupId;
public User() { }
 
public int getId() {
return id;
}
/**
* Attribute if of User.
*/
private int id;
/**
* Attribute username of User.
*/
private String username;
/**
* Attribute password of User.
*/
private String password;
/**
* Attribute groupId of User.
*/
private int groupId;
 
public void setId(int id) {
this.id = id;
}
/**
* Default constructor.
*/
public User() { }
 
public String getUsername() {
return username;
}
public boolean isAdmin() {
return groupId == Group.ADMIN.getId();
}
/**
* Gets the id of User.
* @return int
*/
public int getId() {
return id;
}
 
public void setUsername(String username) {
this.username = username;
}
/**
* Sets the id of User.
* @param id int
*/
public void setId(int id) {
this.id = id;
}
 
public String getPassword() {
return password;
}
/**
* Gets the username of User.
* @return String
*/
public String getUsername() {
return username;
}
 
public void setPassword(String password) {
this.password = password;
}
/**
* Check if user is admin.
* @return boolean
*/
public boolean isAdmin() {
return groupId == Group.ADMIN.getId();
}
 
public int getGroupId() {
return groupId;
/**
* Sets the username of User.
* @param username String
*/
public void setUsername(String username) {
this.username = username;
}
public Group getGroup() {
return Group.fromId(groupId);
}
 
public void setGroupId(int groupId) {
this.groupId = groupId;
/**
* Gets the password of User.
* @return String
*/
public String getPassword() {
return password;
}
}
 
/**
* Sets the password of User.
* @param password String
*/
public void setPassword(String password) {
this.password = password;
}
 
/**
* Gets the groupId of User.
* @return int
*/
public int getGroupId() {
return groupId;
}
 
/**
* Gets the group of User.
* @return Group
*/
public Group getGroup() {
return Group.fromId(groupId);
}
 
/**
* Sets the groupId of User.
* @param groupId int
*/
public void setGroupId(int groupId) {
this.groupId = groupId;
}
}
/trunk/src/main/java/org/kawai/tag/kcode/KCodeHandler.java
10,197 → 10,242
import org.kawai.model.Page;
import org.mentawai.tag.util.PrintTag;
 
/**
* Handler class KCodeHandler.
*
* @author Sergio Oliveira
*
*/
public class KCodeHandler extends PrintTag {
private static final Map<String, String> EMPTY_MAP = new HashMap<String, String>();
private static final List<KCode> codes = new ArrayList<KCode>();
public static void add(KCode code) {
codes.add(code);
}
public static void add(String tag) {
String klassName = tag;
try {
if (!klassName.contains(".")) {
klassName = "org.kawai.tag.kcode." + klassName;
}
Class<?> klass = Class.forName(klassName);
KCode code = (KCode) klass.newInstance();
add(code);
} catch(Exception e) {
throw new RuntimeException("Cannot add kcode tag: " + tag + " / " + klassName);
}
}
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String getStringToPrint() throws JspException {
Page page = (Page) pageContext.findAttribute(name);
if (page == null) {
throw new JspException("Cannot find page with name: " + name);
}
String body = page.getBody();
for(KCode code : codes) {
String tag = code.getTag();
while(checkForTag(tag, body)) {
String[] parts = splitCodeBlock(tag, body, code.hasBody());
if (parts == null) {
break;
}
Map<String, String> attributes = parseAttributes(parts[0]);
StringBuilder sb = new StringBuilder(1024 * 10);
sb.append(parts[1]);
sb.append(code.process(pageContext, attributes, parts[2]));
sb.append(parts[3]);
body = sb.toString();
}
}
return body;
}
private static final boolean checkForTag(String tag, String body) {
int start = body.indexOf("[" + tag);
if (start == -1) return false;
int end = body.indexOf(']', start);
return end != -1;
}
private static String[] splitCodeBlock(String tag, String body, boolean hasBody) {
if (hasBody) {
int start = body.indexOf("[" + tag);
if (start == -1) return null;
int closingBracketIndex = body.indexOf("]", start);
if (closingBracketIndex == -1) return null;
int end = body.indexOf("[/" + tag + "]");
if (end > start) {
// body tag...
String part1 = "";
if (start > 0) {
part1 = body.substring(0, start);
}
String part2 = "";
int len = ("[/" + tag + "]").length();
if (end < body.length() - len - 1) {
part2 = body.substring(end + len, body.length());
}
String contents = "";
int contentsStart = body.indexOf("]", start) + 1;
int contentsEnd = end;
if (contentsEnd > contentsStart) {
contents = body.substring(contentsStart, contentsEnd);
}
String tagAttributes = "";
len = ("[" + tag).length();
if (closingBracketIndex > start + len) {
tagAttributes = body.substring(start + len, closingBracketIndex).trim();
}
return new String[] { tagAttributes, part1, contents, part2 };
}
return null;
} else {
int start = body.indexOf("[" + tag);
if (start == -1) return null;
int closingBracketIndex = body.indexOf("/]", start);
if (closingBracketIndex == -1) return null;
int end = closingBracketIndex + 2;
if (end > start) {
String part1 = "";
if (start > 0) {
part1 = body.substring(0, start);
}
String part2 = "";
if (end < body.length()) {
part2 = body.substring(end, body.length());
}
String contents = null;
String tagAttributes = "";
int len = ("[" + tag).length();
if (closingBracketIndex > start + len) {
tagAttributes = body.substring(start + len, closingBracketIndex).trim();
}
return new String[] { tagAttributes, part1, contents, part2 };
}
return null;
}
}
private static Map<String, String> parseAttributes(String attrs) {
if (attrs.trim().equals("")) return EMPTY_MAP;
Map<String, String> map = new HashMap<String, String>();
String[] temp = attrs.split("\" +");
for(int i = 0; i < temp.length; i++) {
String s = temp[i];
if (i != temp.length - 1) {
s = s + "\"";
}
String[] temp2 = s.split("\\=");
if (temp2.length == 2) {
String key = temp2[0];
String val = temp2[1];
if (val.startsWith("\"") && val.endsWith("\"")) {
val = val.substring(1, val.length() - 1);
map.put(key, val);
} else {
if (val.startsWith("\"")) {
val = val.substring(1);
}
map.put(key, val);
}
}
}
return map;
}
public static void main(String[] args) {
String x1 = "house";
String x2 = "home";
String s = "aaaaaa [code a=\"asfadf\" bbb=\"asfasfffff\"]" + x1 + "[/code] bbbbb [code ]" + x2 + "[/code] cccccccccccc";
String[] blocks = splitCodeBlock("code", s, true);
for(String x : blocks) System.out.println("{" + x + "}");
blocks = splitCodeBlock("code", blocks[3], true);
for(String x : blocks) System.out.println("{" + x + "}");
s = "aaaaaa [code flip=\"1\" flop=\"2\" /]";
blocks = splitCodeBlock("code", s, false);
for(String x : blocks) System.out.println("{" + x + "}");
 
s = "aaaaaa [code /]";
blocks = splitCodeBlock("code", s, false);
for(String x : blocks) System.out.println("{" + x + "}");
/** Attribute constant EMPTY_MAP of KCodeHandler. */
private static final Map<String, String> EMPTY_MAP = new HashMap<String, String>();
/** Attribute constant codes of KCodeHandler. */
private static final List<KCode> codes = new ArrayList<KCode>();
 
}
}
/**
* Attribute name of KCodeHandler.
*/
private String name;
 
/**
* Method add.
* @param code KCode
*/
public static void add(KCode code) {
codes.add(code);
}
 
/**
* Method add.
* @param tag String
*/
public static void add(String tag) {
 
String klassName = tag;
 
try {
if (!klassName.contains(".")) {
klassName = "org.kawai.tag.kcode." + klassName;
}
 
Class<?> klass = Class.forName(klassName);
KCode code = (KCode) klass.newInstance();
add(code);
 
} catch (Exception e) {
throw new RuntimeException("Cannot add kcode tag: " + tag + " / " + klassName);
}
}
 
/**
* Sets the name attribute.
* @param name String
*/
public void setName(String name) {
this.name = name;
}
 
/**
* {@inheritDoc}
*/
@Override
public String getStringToPrint() throws JspException {
 
Page page = (Page) pageContext.findAttribute(name);
if (page == null) {
throw new JspException("Cannot find page with name: " + name);
}
 
String body = page.getBody();
 
for(KCode code : codes) {
String tag = code.getTag();
while(checkForTag(tag, body)) {
String[] parts = splitCodeBlock(tag, body, code.hasBody());
if (parts == null) {
break;
}
Map<String, String> attributes = parseAttributes(parts[0]);
StringBuilder sb = new StringBuilder(1024 * 10);
sb.append(parts[1]);
sb.append(code.process(pageContext, attributes, parts[2]));
sb.append(parts[3]);
body = sb.toString();
}
}
 
return body;
}
 
/**
* Checks for the tag.
* @param tag String
* @param body String
* @return boolean
*/
private static final boolean checkForTag(String tag, String body) {
int start = body.indexOf("[" + tag);
if (start == -1) return false;
int end = body.indexOf(']', start);
return end != -1;
}
 
/**
* Splits the code block.
* @param tag String
* @param body String
* @param hasBody boolean
* @return String[]
*/
private static String[] splitCodeBlock(String tag, String body, boolean hasBody) {
 
if (hasBody) {
 
int start = body.indexOf("[" + tag);
if (start == -1) return null;
int closingBracketIndex = body.indexOf("]", start);
if (closingBracketIndex == -1) return null;
int end = body.indexOf("[/" + tag + "]");
if (end > start) {
// body tag...
String part1 = "";
if (start > 0) {
part1 = body.substring(0, start);
}
String part2 = "";
int len = ("[/" + tag + "]").length();
if (end < body.length() - len - 1) {
part2 = body.substring(end + len, body.length());
}
String contents = "";
int contentsStart = body.indexOf("]", start) + 1;
int contentsEnd = end;
if (contentsEnd > contentsStart) {
contents = body.substring(contentsStart, contentsEnd);
}
String tagAttributes = "";
len = ("[" + tag).length();
if (closingBracketIndex > start + len) {
tagAttributes = body.substring(start + len, closingBracketIndex).trim();
}
 
return new String[] { tagAttributes, part1, contents, part2 };
}
 
return null;
 
} else {
 
int start = body.indexOf("[" + tag);
if (start == -1) return null;
int closingBracketIndex = body.indexOf("/]", start);
if (closingBracketIndex == -1) return null;
int end = closingBracketIndex + 2;
if (end > start) {
String part1 = "";
if (start > 0) {
part1 = body.substring(0, start);
}
String part2 = "";
if (end < body.length()) {
part2 = body.substring(end, body.length());
}
String contents = null;
String tagAttributes = "";
int len = ("[" + tag).length();
if (closingBracketIndex > start + len) {
tagAttributes = body.substring(start + len, closingBracketIndex).trim();
}
 
return new String[] { tagAttributes, part1, contents, part2 };
}
 
return null;
 
}
}
 
/**
* Parses the attributes.
* @param attrs String
* @return Map<String, String>
*/
private static Map<String, String> parseAttributes(String attrs) {
if (attrs.trim().equals("")) return EMPTY_MAP;
Map<String, String> map = new HashMap<String, String>();
String[] temp = attrs.split("\" +");
for(int i = 0; i < temp.length; i++) {
String s = temp[i];
if (i != temp.length - 1) {
s = s + "\"";
}
String[] temp2 = s.split("\\=");
if (temp2.length == 2) {
String key = temp2[0];
String val = temp2[1];
if (val.startsWith("\"") && val.endsWith("\"")) {
val = val.substring(1, val.length() - 1);
map.put(key, val);
} else {
if (val.startsWith("\"")) {
val = val.substring(1);
}
map.put(key, val);
}
}
}
return map;
}
 
// TODO put this main on unit tests and remove from here.
public static void main(String[] args) {
 
String x1 = "house";
String x2 = "home";
 
String s = "aaaaaa [code a=\"asfadf\" bbb=\"asfasfffff\"]" + x1 + "[/code] bbbbb [code ]" + x2 + "[/code] cccccccccccc";
 
String[] blocks = splitCodeBlock("code", s, true);
 
for(String x : blocks) System.out.println("{" + x + "}");
 
blocks = splitCodeBlock("code", blocks[3], true);
 
for(String x : blocks) System.out.println("{" + x + "}");
 
s = "aaaaaa [code flip=\"1\" flop=\"2\" /]";
 
blocks = splitCodeBlock("code", s, false);
 
for(String x : blocks) System.out.println("{" + x + "}");
 
s = "aaaaaa [code /]";
 
blocks = splitCodeBlock("code", s, false);
 
for(String x : blocks) System.out.println("{" + x + "}");
 
 
}
}
/trunk/src/main/java/org/kawai/tag/kcode/KCode.java
5,11 → 5,33
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
 
/**
* Interace KCode.
*
* @author Sergio Oliveira
*
*/
public interface KCode {
public String getTag();
public boolean hasBody();
public String process(PageContext pageContext, Map<String, String> attributes, String body) throws JspException;
}
 
/**
* The getTag method.
* @return String
*/
public String getTag();
 
/**
* The hasBody method.
* @return boolean
*/
public boolean hasBody();
 
/**
* The process method.
* @param pageContext PageContext
* @param attributes Map<String, String>
* @param body String
* @return String
* @throws JspException exception
*/
public String process(PageContext pageContext, Map<String, String> attributes, String body) throws JspException;
}
/trunk/src/main/java/org/kawai/tag/kcode/PageLink.java
9,45 → 9,60
import org.kawai.action.PageAction;
import org.kawai.model.Page;
 
/**
* KCode class PageLink.
*
* @author Sergio Oliveira
*
*/
public class PageLink implements KCode {
@Override
public boolean hasBody() {
return false;
}
@Override
public String getTag() {
return "pageLink";
}
@Override
public String process(PageContext pageContext, Map<String, String> attrs, String html) throws JspException {
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
String name = attrs.get("name");
if (name == null) throw new JspException("Name attribute is mandatory for tag pageLink!");
 
String text = attrs.get("text");
if (text == null) throw new JspException("Text attribute is mandatory for tag pageLink!");
String linkClass = attrs.get("linkClass");
String clickedClass = attrs.get("clickedClass");
String sizeClass = attrs.get("class");
if (sizeClass != null) {
linkClass = sizeClass;
clickedClass = sizeClass + "Clicked";
}
// check if we are displaying that page...
Page page = (Page) pageContext.findAttribute(PageAction.BODY_COLUMN_KEY);
if (page != null && page.getName().equals(name)) {
return "<span" + (clickedClass != null ? " class=\"" + clickedClass + "\"" : "") + ">" + text + "</span>";
} else {
return "<a href=\"" + req.getContextPath() + "/Page.mtw?name=" + name + "\"" + (linkClass != null ? " class=\"" + linkClass + "\"" : "") + ">" + text + "</a>";
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasBody() {
return false;
}
 
/**
* {@inheritDoc}
*/
@Override
public String getTag() {
return "pageLink";
}
 
/**
* {@inheritDoc}
*/
@Override
public String process(PageContext pageContext, Map<String, String> attrs, String html) throws JspException {
 
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
 
String name = attrs.get("name");
if (name == null) throw new JspException("Name attribute is mandatory for tag pageLink!");
 
String text = attrs.get("text");
if (text == null) throw new JspException("Text attribute is mandatory for tag pageLink!");
 
String linkClass = attrs.get("linkClass");
String clickedClass = attrs.get("clickedClass");
 
String sizeClass = attrs.get("class");
if (sizeClass != null) {
linkClass = sizeClass;
clickedClass = sizeClass + "Clicked";
}
 
// check if we are displaying that page...
Page page = (Page) pageContext.findAttribute(PageAction.BODY_COLUMN_KEY);
if (page != null && page.getName().equals(name)) {
return "<span" + (clickedClass != null ? " class=\"" + clickedClass + "\"" : "") + ">" + text + "</span>";
} else {
return "<a href=\"" + req.getContextPath() + "/Page.mtw?name=" + name + "\"" + (linkClass != null ? " class=\"" + linkClass + "\"" : "") + ">" + text + "</a>";
}
}
 
}
/trunk/src/main/java/org/kawai/action/PageAction.java
24,16 → 24,29
*/
public class PageAction extends AbstractAction implements AuthenticationFree, Validatable, ValidationInterceptor {
 
/** Attriubte constant LEFT_COLUMN_KEY of PageAction. */
public static final String LEFT_COLUMN_KEY = "leftColumn";
/** Attribute constant LEFT_COLUMN_KEY of PageAction. */
public static final String BODY_COLUMN_KEY = "bodyColumn";
/** Attribute constant LEFT_COLUMN_KEY of PageAction. */
public static final String CSS_KEY = "css";
/** Attribute constant LEFT_COLUMN_KEY of PageAction. */
public static final String LOGO_KEY = "logo";
/** Attribute constant LEFT_COLUMN_KEY of PageAction. */
public static final String JAVASCRIPT_KEY = "js";
 
/**
* Parametric constructor.
* @param userDAO UserDAO
* @param pageDAO PageDAO
*/
public PageAction(UserDAO userDAO, PageDAO pageDAO) {
super(userDAO, pageDAO);
}
 
/**
* {@inheritDoc}
*/
@Override
public boolean bypassAuthentication(String method) {
 
45,6 → 58,9
return false;
}
 
/**
* {@inheritDoc}
*/
@Override
public void prepareValidator(Validator val, String method) {
 
62,20 → 78,32
}
}
 
/**
* {@inheritDoc}
*/
@Override
public boolean beforeValidation(String method) {
return true; // go ahead with validation...
}
 
/**
* {@inheritDoc}
*/
@Override
public void afterValidation(String method, boolean wasOk) {
if (method == null) return;
if (method == null) {
return;
}
 
if (method.equals("add") && !wasOk) {
output.setValue("showForm", method);
}
}
 
/**
* Checks if page does not exist.
* @return boolean
*/
boolean checkPageDoesNotExist() {
Page p = input.getObject(Page.class, "newPage");
if (p.getName() == null || p.getLanguage() == null) {
84,6 → 112,10
return !pageDAO.exists(p.getName(), p.getLanguage());
}
 
/**
* Checks if page is not system page.
* @return boolean
*/
boolean checkNotSystemPage() {
Page p = input.getObject(Page.class, "newPage");
if (p.getName() == null) {
92,6 → 124,11
return !pageDAO.isSystemPage(p.getName());
}
 
/**
* Loads the left column.
* @param lang Language
* @return Page
*/
private Page loadLeftColumn(Language lang) {
if (sessionUser != null) {
return pageDAO.loadByNameWithPreview(sessionUser.getId(), Page.LEFT_COLUMN, lang);
100,6 → 137,11
}
}
 
/**
* Loads the logo.
* @param lang Language
* @return Page
*/
private Page loadLogo(Language lang) {
if (sessionUser != null) {
return pageDAO.loadByNameWithPreview(sessionUser.getId(), Page.LOGO, lang);
108,16 → 150,28
}
}
 
/**
* Sets the logo.
* @param lang Language
*/
private void setLogo(Language lang) {
Page logo = loadLogo(lang);
output.setValue(LOGO_KEY, logo);
}
 
/**
* Sets the left column.
* @param lang Language
*/
private void setLeftColumn(Language lang) {
Page lc = loadLeftColumn(lang);
output.setValue(LEFT_COLUMN_KEY, lc);
}
 
/**
* Loads the css.
* @return Page
*/
private Page loadCSS() {
if (sessionUser != null) {
return pageDAO.loadByNameWithPreview(sessionUser.getId(), Page.CSS, Language.getDefault());
126,11 → 180,18
}
}
 
/**
* Sets the css.
*/
private void setCSS() {
Page css = loadCSS();
output.setValue(CSS_KEY, css);
}
 
/**
* Loads the javascript.
* @return Page
*/
private Page loadJavaScript() {
if (sessionUser != null) {
return pageDAO.loadByNameWithPreview(sessionUser.getId(), Page.JAVASCRIPT, Language.getDefault());
139,6 → 200,9
}
}
 
/**
* Sets the javascript.
*/
private void setJavaScript() {
Page js = loadJavaScript();
output.setValue(JAVASCRIPT_KEY, js);
159,6 → 223,10
return AJAX;
}
 
/**
* Gets the preview.
* @return String
*/
public String getPreview() {
String name = input.getString("name");
String lang = input.getString("lang");
178,21 → 246,38
return AJAX;
}
 
/**
* Gets the css.
* @return String
*/
public String getCSS() {
setCSS();
return SUCCESS;
}
 
/**
* Gets the print css.
* @return String
*/
public String getPrintCSS() {
Page page = pageDAO.loadByName(Page.PRINT_CSS, Language.getDefault());
output.setValue(CSS_KEY, page);
return SUCCESS;
}
 
/**
* Gets the language.
* @return Language
*/
private Language getLanguage() {
return getLanguage(input.getString("lang"));
}
 
/**
* Gets the language.
* @param lang String
* @return Language
*/
private Language getLanguage(String lang) {
if (lang == null) return language;
Language l = Language.fromLocale(lang);
200,11 → 285,19
return l;
}
 
/**
* Gets the name.
* @return String
*/
private String getName() {
String name = input.getString("name");
return getName(name);
return getName(input.getString("name"));
}
 
/**
* Gets the name.
* @param name String
* @return String
*/
private String getName(String name) {
if (name == null) {
name = pageDAO.getFrontPage(language);
215,6 → 308,9
return name;
}
 
/**
* {@inheritDoc}
*/
@Override
public String execute() {
String name = getName();
244,6 → 340,10
}
}
 
/**
* Saves the preview.
* @return String
*/
public String savePreview() {
String name = input.getString("name");
Language lang = Language.fromLocale(input.getString("lang"));
268,13 → 368,20
page = preview.getPage();
pageDAO.insert(page);
pageDAO.deletePreview(userId, name, lang);
insertRevision(page,null, null, null);
insertRevision(page, null, null, null);
}
setPageRedirParams(page);
}
return SUCCESS;
}
 
/**
* Insert the revision.
* @param page Page
* @param comment String
* @param oldTitle String
* @param oldBody String
*/
private void insertRevision(Page page, String comment, String oldTitle, String oldBody) {
Revision r = new Revision();
r.setName(page.getName());
288,12 → 395,17
pageDAO.insertRevision(r);
}
 
/**
* Do the upadte.
* @return String
*/
public String edit() {
if (!isPost()) return INDEX;
String name = input.getString("name");
String lang = input.getString("lang");
if (name.equals("CSS")) {
// does not make sense to have CSS in different languages... (well, maybe it does, but we do NOT want to maintain more than one CSS)
// does not make sense to have CSS in different languages...
// (well, maybe it does, but we do NOT want to maintain more than one CSS)
lang = "en";
}
Page page = pageDAO.loadByName(name, Language.fromLocale(lang));
321,6 → 433,10
return UPDATED;
}
 
/**
* Discards the preview.
* @return String
*/
public String discardPreview() {
String name = input.getString("name");
Language lang = Language.fromLocale(input.getString("lang"));
331,6 → 447,10
return REMOVED;
}
 
/**
* Add a revision.
* @return String
*/
public String add() {
if (!isPost()) return INDEX;
Page p = input.getObject(Page.class, "newPage");
349,12 → 469,20
return CREATED;
}
 
/**
* List pages.
* @return String
*/
public String list() {
List<Page> pages = pageDAO.loadAll(sessionUser.getGroup() == Group.ADMIN);
output.setValue("pages", pages);
return AJAX;
}
 
/**
* Sets the front page.
* @return String
*/
public String setFrontPage() {
int id = input.getInt("pageId");
Page p = pageDAO.load(id);
366,15 → 494,23
return UPDATED;
}
 
/**
* Removes the page.
* @return String
*/
public String delete() {
int id = input.getInt("pageId");
Page p = pageDAO.load(id);
if (p != null ) {
if (p != null) {
pageDAO.delete(p);
}
return UPDATED;
}
 
/**
* Get the revisions.
* @return String
*/
public String getRevisions() {
String name = input.getString("name");
Language lang = Language.fromLocale(input.getString("lang"));
385,9 → 521,13
return AJAX;
}
 
/**
* Gets the last revisions.
* @return String
*/
public String getLastRevisions() {
Language lang = Language.fromLocale(input.getString("lang"));
List<Revision> revisions = pageDAO.loadLastRevisions(lang, sessionUser != null);
List < Revision > revisions = pageDAO.loadLastRevisions(lang, sessionUser != null);
output.setValue("revisions", revisions);
return AJAX;
}