You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@struts.apache.org by mr...@apache.org on 2005/09/21 21:42:44 UTC
svn commit: r290802 [2/10] - in /struts/sandbox/trunk/ti: ./
jars/core/src/java/org/apache/ti/compiler/internal/
jars/core/src/java/org/apache/ti/compiler/internal/genmodel/
jars/core/src/java/org/apache/ti/compiler/internal/grammar/
jars/core/src/java...
Modified: struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenSimpleActionModel.java
URL: http://svn.apache.org/viewcvs/struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenSimpleActionModel.java?rev=290802&r1=290801&r2=290802&view=diff
==============================================================================
--- struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenSimpleActionModel.java (original)
+++ struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenSimpleActionModel.java Wed Sep 21 12:42:20 2005
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -29,11 +29,9 @@
import java.util.Iterator;
import java.util.List;
-
public class GenSimpleActionModel
extends GenXWorkActionModel
implements JpfLanguageConstants {
-
public GenSimpleActionModel(AnnotationInstance annotation, GenXWorkModuleConfigModel parentApp, ClassDeclaration jclass) {
super(CompilerUtils.getString(annotation, NAME_ATTR, true), annotation, parentApp, jclass);
@@ -41,12 +39,13 @@
addForwards(annotation, parentApp, jclass);
String formMember = getFormBeanMember();
+
if (formMember != null) {
FieldDeclaration field = CompilerUtils.findField(jclass, formMember);
- assert field != null; // checker should prevent this
+ assert field != null; // checker should prevent this
setFormBeanType(addFormBean(field.getType(), parentApp));
} else {
- setReadonly(true); // can't modify member state; mark as read-only
+ setReadonly(true); // can't modify member state; mark as read-only
TypeInstance formBeanType = CompilerUtils.getTypeInstance(annotation, USE_FORM_BEAN_TYPE_ATTR, true);
@@ -55,7 +54,7 @@
}
}
- StringBuilder comment = new StringBuilder("Generated from @");
+ StringBuffer comment = new StringBuffer("Generated from @");
comment.append(ANNOTATION_INTERFACE_PREFIX);
comment.append(annotation.getAnnotationType().getAnnotationTypeDeclaration().getSimpleName());
comment.append("(name=");
@@ -80,17 +79,17 @@
if (forwardRef == null) {
forwardRef = DEFAULT_SIMPLE_ACTION_FORWARD_NAME;
+
XWorkResultModel fwd = new SimpleActionXWorkResult(forwardRef, parentApp, annotation, jclass);
- if (fwd.getPath() != null || fwd.isNavigateTo() || fwd.isNestedReturn()) {
+ if ((fwd.getPath() != null) || fwd.isNavigateTo() || fwd.isNestedReturn()) {
addForward(fwd);
}
}
setDefaultForwardName(forwardRef);
- List conditionalFwdAnnotations =
- CompilerUtils.getAnnotationArray(annotation, CONDITIONAL_FORWARDS_ATTR, true);
+ List conditionalFwdAnnotations = CompilerUtils.getAnnotationArray(annotation, CONDITIONAL_FORWARDS_ATTR, true);
if (conditionalFwdAnnotations != null) {
int anonCount = 0;
@@ -101,20 +100,24 @@
String expression = CompilerUtils.getString(conditionalFwdAnnotation, CONDITION_ATTR, true);
assert expression != null;
- if (conditionalFwd.getName() == null) conditionalFwd.setName("_anon" + ++anonCount);
+ if (conditionalFwd.getName() == null) {
+ conditionalFwd.setName("_anon" + ++anonCount);
+ }
+
addForward(conditionalFwd);
addConditionalForward(expression, conditionalFwd.getName());
}
}
}
- private static class SimpleActionXWorkResult extends GenXWorkResultModel {
-
+ private static class SimpleActionXWorkResult
+ extends GenXWorkResultModel {
public SimpleActionXWorkResult(GenXWorkModuleConfigModel parent, AnnotationInstance annotation, ClassDeclaration jclass) {
super(parent, annotation, jclass, null);
}
- public SimpleActionXWorkResult(String name, GenXWorkModuleConfigModel parent, AnnotationInstance annotation, ClassDeclaration jclass) {
+ public SimpleActionXWorkResult(String name, GenXWorkModuleConfigModel parent, AnnotationInstance annotation,
+ ClassDeclaration jclass) {
super(parent, annotation, jclass, null);
setName(name);
}
@@ -124,4 +127,3 @@
}
}
}
-
Modified: struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenValidationModel.java
URL: http://svn.apache.org/viewcvs/struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenValidationModel.java?rev=290802&r1=290801&r2=290802&view=diff
==============================================================================
--- struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenValidationModel.java (original)
+++ struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenValidationModel.java Wed Sep 21 12:42:20 2005
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +21,7 @@
import org.apache.ti.compiler.internal.FatalCompileTimeException;
import org.apache.ti.compiler.internal.JpfLanguageConstants;
import org.apache.ti.compiler.internal.MergedControllerAnnotation;
+import org.apache.ti.compiler.internal.model.XmlModelWriterException;
import org.apache.ti.compiler.internal.model.validation.ValidationModel;
import org.apache.ti.compiler.internal.model.validation.ValidatorConstants;
import org.apache.ti.compiler.internal.model.validation.ValidatorRule;
@@ -35,12 +36,12 @@
import org.apache.ti.compiler.internal.typesystem.type.ClassType;
import org.apache.ti.compiler.internal.typesystem.type.DeclaredType;
import org.apache.ti.compiler.internal.typesystem.type.TypeInstance;
-import org.apache.xmlbeans.XmlException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
+
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
@@ -50,14 +51,11 @@
public class GenValidationModel
extends ValidationModel
implements JpfLanguageConstants, ValidatorConstants {
-
private static final ValidatorRuleFactory VALIDATOR_RULE_FACTORY = new DefaultValidatorRuleFactory();
-
private GenXWorkModuleConfigModel _strutsApp;
private File _mergeFile;
private AnnotationProcessorEnvironment _env;
-
public GenValidationModel(ClassDeclaration jclass, GenXWorkModuleConfigModel strutsApp, AnnotationProcessorEnvironment env)
throws FatalCompileTimeException {
MergedControllerAnnotation mca = strutsApp.getFlowControllerInfo().getMergedControllerAnnotation();
@@ -66,6 +64,7 @@
addRulesFromBeans(jclass);
addRulesFromActions(jclass, mca);
addRulesFromClass(mca);
+
String mergeFileName = mca.getValidatorMerge();
_mergeFile = strutsApp.getMergeFile(mergeFileName);
_env = env;
@@ -79,9 +78,9 @@
for (Iterator ii = innerTypes.iterator(); ii.hasNext();) {
TypeDeclaration innerType = (TypeDeclaration) ii.next();
- if (innerType instanceof ClassDeclaration
- && innerType.hasModifier(Modifier.PUBLIC)
- && innerType.hasModifier(Modifier.STATIC)) {
+
+ if (innerType instanceof ClassDeclaration && innerType.hasModifier(Modifier.PUBLIC) &&
+ innerType.hasModifier(Modifier.STATIC)) {
addRulesFromBeanClass((ClassDeclaration) innerType);
}
}
@@ -119,18 +118,15 @@
}
}
-
private void addRulesFromAnnotation(AnnotationInstance validationFieldAnn, String entityName, String propertyName) {
//
// Add rules from the FieldValidationRules annotations in the "localeRules" member.
//
- Collection localeRulesAnnotations =
- CompilerUtils.getAnnotationArray(validationFieldAnn, LOCALE_RULES_ATTR, false);
+ Collection localeRulesAnnotations = CompilerUtils.getAnnotationArray(validationFieldAnn, LOCALE_RULES_ATTR, false);
String displayName = CompilerUtils.getString(validationFieldAnn, DISPLAY_NAME_ATTR, true);
String displayNameKey = CompilerUtils.getString(validationFieldAnn, DISPLAY_NAME_KEY_ATTR, true);
RuleInfo ruleInfo = new RuleInfo(entityName, propertyName, displayName, displayNameKey);
-
for (Iterator ii = localeRulesAnnotations.iterator(); ii.hasNext();) {
AnnotationInstance ann = (AnnotationInstance) ii.next();
addFieldRules(ann, ruleInfo, false);
@@ -149,43 +145,46 @@
addRulesFromActionAnnotation(actionAnnotation, method.getSimpleName());
ParameterDeclaration[] parameters = method.getParameters();
+
if (parameters.length > 0) {
TypeInstance type = parameters[0].getType();
if (type instanceof ClassType) {
ClassDeclaration classDecl = ((ClassType) type).getClassTypeDeclaration();
- if (classDecl.getDeclaringType() == null) addRulesFromBeanClass(classDecl);
+
+ if (classDecl.getDeclaringType() == null) {
+ addRulesFromBeanClass(classDecl);
+ }
}
}
}
-
Collection simpleActions = mca.getSimpleActions();
if (simpleActions != null) {
for (Iterator ii = simpleActions.iterator(); ii.hasNext();) {
AnnotationInstance simpleAction = (AnnotationInstance) ii.next();
String actionName = CompilerUtils.getString(simpleAction, NAME_ATTR, true);
- assert actionName != null; //checker should enforce this.
+ assert actionName != null; //checker should enforce this.
addRulesFromActionAnnotation(simpleAction, actionName);
}
}
}
private void addRulesFromActionAnnotation(AnnotationInstance actionAnnotation, String actionName) {
- Collection validatablePropertyAnnotations =
- CompilerUtils.getAnnotationArray(actionAnnotation, VALIDATABLE_PROPERTIES_ATTR, false);
+ Collection validatablePropertyAnnotations = CompilerUtils.getAnnotationArray(actionAnnotation,
+ VALIDATABLE_PROPERTIES_ATTR, false);
for (Iterator ii = validatablePropertyAnnotations.iterator(); ii.hasNext();) {
AnnotationInstance validationFieldAnnotation = (AnnotationInstance) ii.next();
String propertyName = CompilerUtils.getString(validationFieldAnnotation, PROPERTY_NAME_ATTR, true);
- assert propertyName != null; // TODO: checker must enforce this
- assert ! propertyName.equals(""); // TODO: checker must enforce this
+ assert propertyName != null; // TODO: checker must enforce this
+ assert !propertyName.equals(""); // TODO: checker must enforce this
//
// Add the rules, and associate them with the action path ("/" + the action name).
//
- String actionPath = '/' + actionName; // Struts validator needs the slash in front
+ String actionPath = '/' + actionName; // Struts validator needs the slash in front
addRulesFromAnnotation(validationFieldAnnotation, actionPath, propertyName);
}
}
@@ -196,16 +195,16 @@
for (Iterator ii = validationBeanAnnotations.iterator(); ii.hasNext();) {
AnnotationInstance validationBeanAnnotation = (AnnotationInstance) ii.next();
DeclaredType beanType = CompilerUtils.getDeclaredType(validationBeanAnnotation, TYPE_ATTR, true);
- assert beanType != null; // checker should enforce this
+ assert beanType != null; // checker should enforce this
- Collection validationFieldAnnotations =
- CompilerUtils.getAnnotationArray(validationBeanAnnotation, VALIDATABLE_PROPERTIES_ATTR, false);
+ Collection validationFieldAnnotations = CompilerUtils.getAnnotationArray(validationBeanAnnotation,
+ VALIDATABLE_PROPERTIES_ATTR, false);
for (Iterator i2 = validationFieldAnnotations.iterator(); i2.hasNext();) {
AnnotationInstance validationFieldAnnotation = (AnnotationInstance) i2.next();
String propName = CompilerUtils.getString(validationFieldAnnotation, PROPERTY_NAME_ATTR, true);
- assert propName != null; // checker should enforce this
- assert ! propName.equals(""); // TODO: get checker to enforce this
+ assert propName != null; // checker should enforce this
+ assert !propName.equals(""); // TODO: get checker to enforce this
//
// Add the rules -- associate them with the classname of the bean type.
@@ -219,14 +218,13 @@
/**
* Add field rules from either a Jpf.ValidationField or a Jpf.ValidationLocaleRules annotation.
*/
- private void addFieldRules(AnnotationInstance rulesContainerAnnotation, RuleInfo ruleInfo,
- boolean applyToAllLocales) {
+ private void addFieldRules(AnnotationInstance rulesContainerAnnotation, RuleInfo ruleInfo, boolean applyToAllLocales) {
//
// First parse the locale from the wrapper annotation. This will apply to all rules inside.
//
Locale locale = null;
- if (! applyToAllLocales) {
+ if (!applyToAllLocales) {
String language = CompilerUtils.getString(rulesContainerAnnotation, LANGUAGE_ATTR, true);
//
@@ -238,13 +236,22 @@
String variant = CompilerUtils.getString(rulesContainerAnnotation, VARIANT_ATTR, true);
language = language.trim();
- if (country != null) country = country.trim();
- if (variant != null) variant = variant.trim();
- if (country != null && variant != null) locale = new Locale(language, country, variant);
- else if (country != null) locale = new Locale(language, country);
- else
+ if (country != null) {
+ country = country.trim();
+ }
+
+ if (variant != null) {
+ variant = variant.trim();
+ }
+
+ if ((country != null) && (variant != null)) {
+ locale = new Locale(language, country, variant);
+ } else if (country != null) {
+ locale = new Locale(language, country);
+ } else {
locale = new Locale(language);
+ }
}
}
@@ -267,12 +274,11 @@
}
}
- setEmpty(false); // this ValidationModel is only "empty" if there are no rules.
+ setEmpty(false); // this ValidationModel is only "empty" if there are no rules.
}
private void addFieldRuleFromAnnotation(RuleInfo ruleInfo, AnnotationInstance annotation, Locale locale,
boolean applyToAllLocales) {
-
ValidatorRule rule = getFieldRule(ruleInfo.getEntityName(), ruleInfo.getFieldName(), annotation);
if (rule != null) {
@@ -294,7 +300,10 @@
rule.setMessage(CompilerUtils.getString(ruleAnnotation, MESSAGE_ATTR, true));
rule.setMessageKey(CompilerUtils.getString(ruleAnnotation, MESSAGE_KEY_ATTR, true));
rule.setBundle(CompilerUtils.getString(ruleAnnotation, BUNDLE_NAME_ATTR, true));
- if (rule.getMessage() != null) assert rule.getMessageKey() == null; // TODO: checker should enforce
+
+ if (rule.getMessage() != null) {
+ assert rule.getMessageKey() == null; // TODO: checker should enforce
+ }
//
// args
@@ -306,11 +315,11 @@
}
protected static void addMessageArgs(ValidatorRule rule, AnnotationInstance annotation) {
- List messageArgs =
- CompilerUtils.getAnnotationArray(annotation, MESSAGE_ARGS_ATTR, true);
+ List messageArgs = CompilerUtils.getAnnotationArray(annotation, MESSAGE_ARGS_ATTR, true);
if (messageArgs != null) {
int inferredPosition = 0;
+
for (Iterator ii = messageArgs.iterator(); ii.hasNext();) {
AnnotationInstance ann = (AnnotationInstance) ii.next();
String arg = CompilerUtils.getString(ann, ARG_ATTR, true);
@@ -325,7 +334,10 @@
rule.setArg(arg, false, bundle, position);
} else {
String argKey = CompilerUtils.getString(ann, ARG_KEY_ATTR, true);
- if (argKey != null) rule.setArg(argKey, true, bundle, position);
+
+ if (argKey != null) {
+ rule.setArg(argKey, true, bundle, position);
+ }
}
inferredPosition++;
@@ -333,25 +345,23 @@
}
}
- protected String getHeaderComment(File mergeFile)
- throws FatalCompileTimeException {
+ protected String getHeaderComment(File mergeFile) throws FatalCompileTimeException {
return _strutsApp.getHeaderComment(mergeFile);
}
- public void writeToFile()
- throws FileNotFoundException, XmlException, IOException, FatalCompileTimeException {
- String outputFilePath = getOutputFileURI();
+ public void writeToFile() throws FileNotFoundException, IOException, FatalCompileTimeException, XmlModelWriterException {
+ String outputFilePath = getOutputFilePath();
File outputFile = new File(outputFilePath);
PrintWriter writer = _env.getFiler().createTextFile(outputFile);
+
try {
writeXml(writer, _mergeFile);
- }
- finally {
+ } finally {
writer.close();
}
}
- public String getOutputFileURI() {
+ public String getOutputFilePath() {
return _strutsApp.getOutputFileURI(_strutsApp.getValidationFilePrefix());
}
}
Modified: struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenXWorkModuleConfigModel.java
URL: http://svn.apache.org/viewcvs/struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenXWorkModuleConfigModel.java?rev=290802&r1=290801&r2=290802&view=diff
==============================================================================
--- struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenXWorkModuleConfigModel.java (original)
+++ struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/genmodel/GenXWorkModuleConfigModel.java Wed Sep 21 12:42:20 2005
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -37,26 +37,23 @@
import org.apache.ti.compiler.internal.typesystem.env.AnnotationProcessorEnvironment;
import org.apache.ti.compiler.internal.typesystem.type.DeclaredType;
import org.apache.ti.compiler.internal.typesystem.type.TypeInstance;
-import org.apache.xmlbeans.XmlException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
-
public class GenXWorkModuleConfigModel
extends XWorkModuleConfigModel
implements JpfLanguageConstants {
-
private static final boolean CASE_INSENSITIVE_FILES = new File("x").equals(new File("X"));
-
private ClassDeclaration _jclass;
private String _containingPackage;
private File _strutsConfigFile;
@@ -64,8 +61,7 @@
private AnnotationProcessorEnvironment _env;
private FlowControllerInfo _fcInfo;
- protected void recalculateStrutsConfigFile()
- throws XmlException, IOException, FatalCompileTimeException {
+ protected void recalculateStrutsConfigFile() throws IOException, FatalCompileTimeException {
_strutsConfigFile = calculateStrutsConfigFile(); // caching this
}
@@ -75,7 +71,7 @@
public GenXWorkModuleConfigModel(File sourceFile, ClassDeclaration jclass, AnnotationProcessorEnvironment env,
FlowControllerInfo fcInfo, boolean checkOnly, Diagnostics diagnostics)
- throws XmlException, IOException, FatalCompileTimeException {
+ throws IOException, FatalCompileTimeException {
super(jclass.getQualifiedName());
_jclass = jclass;
@@ -87,12 +83,15 @@
recalculateStrutsConfigFile();
- if (checkOnly) return;
+ if (checkOnly) {
+ return;
+ }
if (_jclass != null) {
MergedControllerAnnotation mca = fcInfo.getMergedControllerAnnotation();
setNestedPageFlow(mca.isNested());
setLongLivedPageFlow(mca.isLongLived());
+
//addMessageBundles( mca.getMessageBundles() );
addSimpleActions(mca.getSimpleActions());
setMultipartHandler(mca.getMultipartHandler());
@@ -112,19 +111,19 @@
if (fcInfo != null) {
setSharedFlows(fcInfo.getSharedFlowTypeNames());
- setReturnToActionDisabled(! fcInfo.isNavigateToActionEnabled());
- setReturnToPageDisabled(! fcInfo.isNavigateToPageEnabled());
+ setReturnToActionDisabled(!fcInfo.isNavigateToActionEnabled());
+ setReturnToPageDisabled(!fcInfo.isNavigateToPageEnabled());
}
}
private void inferBeginAction(ClassDeclaration jclass, FlowControllerInfo fcInfo) {
boolean isAbstract = jclass.hasModifier(Modifier.ABSTRACT);
- if (! isAbstract
- && ! WebappPathOrActionType.actionExists(BEGIN_ACTION_NAME, jclass, null, getEnv(), fcInfo, true)) {
+ if (!isAbstract && !WebappPathOrActionType.actionExists(BEGIN_ACTION_NAME, jclass, null, getEnv(), fcInfo, true)) {
XWorkActionModel inferredBeginAction = new XWorkActionModel(BEGIN_ACTION_NAME, this);
inferredBeginAction.setSimpleAction(true);
inferredBeginAction.setDefaultForwardName("success");
+
XWorkResultModel fwd = new XWorkResultModel("success", BEGIN_ACTION_NAME + getDefaultFileExtension(), this);
inferredBeginAction.addForward(fwd);
inferredBeginAction.setComment("(implicit)");
@@ -137,16 +136,16 @@
for (Iterator ii = innerTypes.iterator(); ii.hasNext();) {
TypeDeclaration innerType = (TypeDeclaration) ii.next();
+
if (innerType instanceof ClassDeclaration) {
ClassDeclaration innerClass = (ClassDeclaration) innerType;
- if (innerType.hasModifier(Modifier.PUBLIC)
- && CompilerUtils.isAssignableFrom(PAGEFLOW_FORM_CLASS_NAME, innerClass, _env)) {
+ if (innerType.hasModifier(Modifier.PUBLIC) &&
+ CompilerUtils.isAssignableFrom(PAGEFLOW_FORM_CLASS_NAME, innerClass, _env)) {
addFormBean(innerClass, null);
}
}
}
-
}
/**
@@ -166,8 +165,9 @@
// See if the app already has a form-bean of this type. If so,
// we'll just use it; otherwise, we need to create it.
//
- boolean usesPageFlowScopedFormBean = usedByAction != null ? usedByAction.getFormBeanMember() != null : false;
+ boolean usesPageFlowScopedFormBean = (usedByAction != null) ? (usedByAction.getFormBeanMember() != null) : false;
getMessageResourcesFromForm(formType, usedByAction);
+
return formClass;
}
@@ -176,7 +176,7 @@
{
if ( messageBundles != null )
{
- for ( Iterator ii = messageBundles.iterator(); ii.hasNext(); )
+ for ( Iterator ii = messageBundles.iterator(); ii.hasNext(); )
{
AnnotationInstance ann = ( AnnotationInstance ) ii.next();
addMessageResources( new GenMessageBundleModel( this, ann ) );
@@ -184,7 +184,6 @@
}
}
*/
-
private void addSimpleActions(Collection simpleActionAnnotations) {
if (simpleActionAnnotations != null) {
for (Iterator ii = simpleActionAnnotations.iterator(); ii.hasNext();) {
@@ -211,7 +210,7 @@
}
private void addTilesDefinitionsConfigs(List tilesDefinitionsConfigs) {
- if (tilesDefinitionsConfigs == null || tilesDefinitionsConfigs.isEmpty()) {
+ if ((tilesDefinitionsConfigs == null) || tilesDefinitionsConfigs.isEmpty()) {
return;
}
@@ -220,7 +219,7 @@
for (Iterator ii = tilesDefinitionsConfigs.iterator(); ii.hasNext();) {
String definitionsConfig = (String) ii.next();
- if (definitionsConfig != null && definitionsConfig.length() > 0) {
+ if ((definitionsConfig != null) && (definitionsConfig.length() > 0)) {
paths.add(definitionsConfig);
}
}
@@ -234,9 +233,10 @@
for (int i = 0; i < actionMethods.length; i++) {
MethodDeclaration actionMethod = actionMethods[i];
- if (! actionMethod.hasModifier(Modifier.ABSTRACT)) {
+ if (!actionMethod.hasModifier(Modifier.ABSTRACT)) {
XWorkActionModel actionModel = new GenXWorkActionModel(actionMethod, this, _jclass);
addAction(actionModel);
+
ParameterDeclaration[] params = actionMethod.getParameters();
if (params.length > 0) {
@@ -252,7 +252,9 @@
}
private void getMessageResourcesFromForm(TypeDeclaration formTypeDecl, XWorkActionModel actionModel) {
- if (! (formTypeDecl instanceof ClassDeclaration)) return;
+ if (!(formTypeDecl instanceof ClassDeclaration)) {
+ return;
+ }
ClassDeclaration formClassDecl = (ClassDeclaration) formTypeDecl;
@@ -265,12 +267,12 @@
String key = "formMessages:" + CompilerUtils.getLoadableName(formClassDecl);
/* TODO: re-add message bundle support
- for ( Iterator ii = getMessageResourcesList().iterator(); ii.hasNext(); )
+ for ( Iterator ii = getMessageResourcesList().iterator(); ii.hasNext(); )
{
MessageResourcesModel i = ( MessageResourcesModel ) ii.next();
if ( key.equals( i.getKey() ) && i.getParameter().equals( defaultMessageResources ) ) return;
}
-
+
MessageResourcesModel mrm = new MessageResourcesModel( this );
mrm.setKey( key );
mrm.setParameter( defaultMessageResources );
@@ -283,23 +285,20 @@
}
protected String getMergeFileName() {
- return null; // In Beehive, this was Struts merge. Will we have XWork-merge?
+ return null; // In Beehive, this was Struts merge. Will we have XWork-merge?
}
- public void writeToFile()
- throws FileNotFoundException, IOException, XmlModelWriterException, FatalCompileTimeException {
+ public void writeToFile() throws FileNotFoundException, IOException, XmlModelWriterException, FatalCompileTimeException {
PrintWriter writer = getEnv().getFiler().createTextFile(_strutsConfigFile);
try {
writeXml(writer, getMergeFile(getMergeFileName()));
- }
- finally {
+ } finally {
writer.close();
}
}
- public boolean isStale()
- throws FatalCompileTimeException {
+ public boolean isStale() throws FatalCompileTimeException {
return isStale(getMergeFile(getMergeFileName()));
}
@@ -327,13 +326,13 @@
//
// We can write to the file if it doesn't exist yet.
//
- if (! _strutsConfigFile.exists()) {
+ if (!_strutsConfigFile.exists()) {
return true;
}
long lastWrite = _strutsConfigFile.lastModified();
- if (mergeFile != null && mergeFile.exists() && mergeFile.lastModified() > lastWrite) {
+ if ((mergeFile != null) && mergeFile.exists() && (mergeFile.lastModified() > lastWrite)) {
return true;
}
@@ -350,7 +349,7 @@
* the file as a test to see whether it's possible.
*/
public boolean canWrite() {
- if (! _strutsConfigFile.canWrite()) {
+ if (!_strutsConfigFile.canWrite()) {
return false;
}
@@ -361,11 +360,9 @@
// (NTFS only?) will cause an exception to be thrown.
//
new FileOutputStream(_strutsConfigFile, true).close();
- }
- catch (FileNotFoundException e) {
+ } catch (FileNotFoundException e) {
return false;
- }
- catch (IOException e) {
+ } catch (IOException e) {
return false;
}
@@ -376,8 +373,7 @@
return _strutsConfigFile;
}
- public File getMergeFile(String mergeFileName)
- throws FatalCompileTimeException {
+ public File getMergeFile(String mergeFileName) throws FatalCompileTimeException {
if (mergeFileName != null) {
return CompilerUtils.getFileRelativeToSourceFile(_jclass, mergeFileName, getEnv());
}
@@ -385,19 +381,20 @@
return null;
}
- protected String getHeaderComment(File mergeFile)
- throws FatalCompileTimeException {
+ protected String getHeaderComment(File mergeFile) throws FatalCompileTimeException {
StringBuffer comment = new StringBuffer(" Generated from ");
comment.append(getWebappRelativePath(_sourceFile));
+
if (mergeFile != null) {
comment.append(" and ").append(getWebappRelativePath(mergeFile));
}
+
comment.append(" on ").append(new Date().toString()).append(' ');
+
return comment.toString();
}
- private String getWebappRelativePath(File file)
- throws FatalCompileTimeException {
+ private String getWebappRelativePath(File file) throws FatalCompileTimeException {
String filePath = file.getAbsoluteFile().getPath();
String[] sourceRoots = CompilerUtils.getWebSourceRoots(_env);
@@ -416,6 +413,7 @@
// Look in the web content root.
//
String[] webContentRoots = CompilerUtils.getWebContentRoots(getEnv());
+
for (int i = 0; i < webContentRoots.length; i++) {
String webContentRoot = webContentRoots[i].replace('/', File.separatorChar);
@@ -425,6 +423,7 @@
}
assert false : "could not calculate webapp-relative file from " + file;
+
return file.toString();
}
Modified: struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/ControllerGrammar.java
URL: http://svn.apache.org/viewcvs/struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/ControllerGrammar.java?rev=290802&r1=290801&r2=290802&view=diff
==============================================================================
--- struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/ControllerGrammar.java (original)
+++ struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/ControllerGrammar.java Wed Sep 21 12:42:20 2005
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,12 +22,9 @@
import org.apache.ti.compiler.internal.FlowControllerInfo;
import org.apache.ti.compiler.internal.RuntimeVersionChecker;
import org.apache.ti.compiler.internal.typesystem.env.AnnotationProcessorEnvironment;
-import org.apache.ti.schema.validator11.FormValidationDocument;
-
public class ControllerGrammar
extends BaseFlowControllerGrammar {
-
public ControllerGrammar(AnnotationProcessorEnvironment env, Diagnostics diags, RuntimeVersionChecker rvc,
FlowControllerInfo fcInfo) {
super(env, diags, null, rvc, fcInfo);
@@ -36,7 +33,7 @@
addMemberType(ROLES_ALLOWED_ATTR, new RolesAllowedType(this));
addMemberType(READONLY_ATTR, new AnnotationMemberType(null, this));
addMemberType(VALIDATOR_VERSION_ATTR, new AnnotationMemberType(null, this));
- addMemberType(VALIDATOR_MERGE_ATTR, new ValidXmlFileType(FormValidationDocument.type, null, this, fcInfo));
+ addMemberType(VALIDATOR_MERGE_ATTR, new ValidXmlFileType(null, null, this, fcInfo));
addMemberType(TILES_DEFINITIONS_CONFIGS_ATTR, new TilesDefinitionsConfigsType(null, this, fcInfo));
addMemberType(MULTIPART_HANDLER_ATTR, new AnnotationMemberType(null, this));
Modified: struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/ValidXmlFileType.java
URL: http://svn.apache.org/viewcvs/struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/ValidXmlFileType.java?rev=290802&r1=290801&r2=290802&view=diff
==============================================================================
--- struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/ValidXmlFileType.java (original)
+++ struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/ValidXmlFileType.java Wed Sep 21 12:42:20 2005
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,140 +19,177 @@
import org.apache.ti.compiler.internal.AnnotationGrammar;
import org.apache.ti.compiler.internal.FlowControllerInfo;
+import org.apache.ti.compiler.internal.LocalFileEntityResolver;
import org.apache.ti.compiler.internal.typesystem.declaration.AnnotationValue;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.XmlError;
-import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlOptions;
+
+import org.w3c.dom.Document;
+
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.helpers.DefaultHandler;
import java.io.File;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+/**
+ * A type that requires a valid XML file. Can accept a specific XML schema, and will fall back to DTD-checking.
+ */
public class ValidXmlFileType
extends WebappPathType {
-
- private SchemaType _schema;
+ private String _schemaFileName;
private static Map _parseResults = Collections.synchronizedMap(new HashMap());
- public ValidXmlFileType(SchemaType schema, String requiredRuntimeVersion, AnnotationGrammar parentGrammar,
+ public ValidXmlFileType(String schemaFileName, String requiredRuntimeVersion, AnnotationGrammar parentGrammar,
FlowControllerInfo fcInfo) {
super(false, requiredRuntimeVersion, parentGrammar, fcInfo);
- _schema = schema;
+ _schemaFileName = schemaFileName;
}
-
protected boolean checkAnyExtension() {
return true;
}
-
protected boolean doFatalError() {
return true;
}
-
protected boolean ignoreDirectories() {
return false;
}
-
protected boolean allowFileInPageFlowSourceDir() {
return true;
}
-
protected void runAdditionalChecks(File file, AnnotationValue value) {
- try {
- //
- // We cache the results of parsing the file until the file is actually modified,
- // so we don't end up continually re-parsing it.
- //
- ParseResults prevResults = (ParseResults) _parseResults.get(file.getPath());
-
- if (prevResults == null || file.lastModified() > prevResults.getFileModTime()) {
- try {
- XmlOptions options = new XmlOptions();
- options.setDocumentType(_schema);
- XmlObject xml = XmlObject.Factory.parse(file, options);
- List errorListener = new ArrayList();
- options.setErrorListener(errorListener);
+ //
+ // We cache the results of parsing the file until the file is actually modified,
+ // so we don't end up continually re-parsing it.
+ //
+ ParseResults prevResults = (ParseResults) _parseResults.get(file.getPath());
+ long lastModTime = file.lastModified();
+
+ if ((prevResults == null) || (lastModTime > prevResults.getFileModTime())) {
+ try {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ LocalFileEntityResolver entityResolver = LocalFileEntityResolver.getInstance();
+
+ // If a schema was specified, we'll validate against that; otherwise, we'll just use the DTD.
+ if (_schemaFileName != null) {
+ InputSource schemaInput = entityResolver.resolveLocalEntity(_schemaFileName);
+ assert schemaInput != null : "could not get schema resource for " + _schemaFileName;
+ factory.setNamespaceAware(true);
+ factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
+ "http://www.w3.org/2001/XMLSchema");
+ factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaInput);
+ }
- if (!xml.validate(options)) {
- assert !errorListener.isEmpty();
+ factory.setValidating(true);
- XmlError err = (XmlError) errorListener.get(0);
- assert err != null;
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ builder.setEntityResolver(LocalFileEntityResolver.getInstance());
- throw new XmlException(err.getMessage(), null, err);
- }
- }
- catch (Exception e) {
- _parseResults.put(file.getPath(), new ParseResults(file.lastModified(), e));
- throw e;
- }
+ ParseResults results = new ParseResults(lastModTime);
+ Validator handler = new Validator(results);
+ builder.setErrorHandler(handler);
- _parseResults.put(file.getPath(), new ParseResults(file.lastModified(), null));
- } else {
- Exception e = prevResults.getException();
+ Document doc = builder.parse(file);
- if (e != null) {
- throw e;
+ if ((doc.getDoctype() == null) && (_schemaFileName == null)) {
+ // If the doctype is null, then we don't want to add errors -- there was no DTD identified.
+ results = new ParseResults(lastModTime);
}
+
+ _parseResults.put(file.getPath(), results);
+ addErrorDiagnostics(file, results, value);
+ } catch (SAXParseException e) {
+ _parseResults.put(file.getPath(), new ParseResults(lastModTime, e));
+ addDiagnostic(file, e, value, true);
+
+ return;
+ } catch (Exception e) {
+ _parseResults.put(file.getPath(), new ParseResults(lastModTime, e));
+ addError(value, "error.xml-read-error", new Object[] { file.getPath(), e.getClass().getName(), e.getMessage() });
+
+ return;
}
+ } else {
+ addErrorDiagnostics(file, prevResults, value);
}
- catch (XmlException e) {
- addErrorDiagnostic(e.getError(), value);
+ }
+
+ private void addErrorDiagnostics(File file, ParseResults results, AnnotationValue value) {
+ List errors = results.getErrors();
+
+ for (Iterator i = errors.iterator(); i.hasNext();) {
+ Exception e = (Exception) i.next();
+
+ if (e instanceof SAXParseException) {
+ addDiagnostic(file, (SAXParseException) e, value, true);
+ } else {
+ addError(value, "error.xml-read-error", new Object[] { file.getPath(), e.getClass().getName(), e.getMessage() });
+ }
}
- catch (Exception e) {
- addError(value, "error.xml-read-error", new Object[]{file.getPath(), e.getMessage()});
+
+ List warnings = results.getWarnings();
+
+ for (Iterator i = warnings.iterator(); i.hasNext();) {
+ Exception e = (Exception) i.next();
+ assert e instanceof SAXParseException : e.getClass().getName();
+ addDiagnostic(file, (SAXParseException) e, value, false);
}
}
- private void addErrorDiagnostic(XmlError err, AnnotationValue value) {
- if (err.getColumn() != -1 && err.getLine() != -1) {
- Object[] args =
- {
- err.getSourceName(),
- new Integer(err.getLine()),
- new Integer(err.getColumn()),
- err.getMessage()
- };
-
- addError(value, "error.xml-parse-error", args);
- } else if (err.getLine() != -1) {
- Object[] args =
- {
- err.getSourceName(),
- new Integer(err.getLine()),
- err.getMessage()
- };
+ private void addDiagnostic(File file, SAXParseException err, AnnotationValue value, boolean isError) {
+ if ((err.getColumnNumber() != -1) && (err.getLineNumber() != -1)) {
+ Object[] args = { file.getPath(), new Integer(err.getLineNumber()), new Integer(err.getColumnNumber()), err.getMessage() };
+
+ if (isError) {
+ addError(value, "error.xml-parse-error", args);
+ } else {
+ addWarning(value, "error.xml-parse-error", args);
+ }
+ } else if (err.getLineNumber() != -1) {
+ Object[] args = { file.getPath(), new Integer(err.getLineNumber()), err.getMessage() };
- addError(value, "error.xml-parse-error-nocolumn", args);
+ if (isError) {
+ addError(value, "error.xml-parse-error-nocolumn", args);
+ } else {
+ addWarning(value, "error.xml-parse-error-nocolumn", args);
+ }
} else {
- Object[] args =
- {
- err.getSourceName(),
- err.getMessage()
- };
+ Object[] args = { file.getPath(), err.getMessage() };
- addError(value, "error.xml-parse-error-nolinecolumn", args);
+ if (isError) {
+ addError(value, "error.xml-parse-error-nolinecolumn", args);
+ } else {
+ addWarning(value, "error.xml-parse-error-nolinecolumn", args);
+ }
}
}
private static class ParseResults {
-
private long _fileModTime;
- private Exception _exception;
+ private List _errors = null;
+ private List _warnings = null;
- public ParseResults(long fileModTime, Exception exception) {
+ public ParseResults(long fileModTime) {
_fileModTime = fileModTime;
- _exception = exception;
+ }
+
+ public ParseResults(long fileModTime, Exception ex) {
+ _fileModTime = fileModTime;
+ addError(ex);
}
public long getFileModTime() {
@@ -163,12 +200,53 @@
_fileModTime = fileModTime;
}
- public Exception getException() {
- return _exception;
+ public void addError(Exception e) {
+ if (_errors == null) {
+ _errors = new ArrayList();
+ }
+
+ _errors.add(e);
+ }
+
+ public void addWarning(Exception e) {
+ if (_warnings == null) {
+ _warnings = new ArrayList();
+ }
+
+ _warnings.add(e);
+ }
+
+ public List getErrors() {
+ return (_errors != null) ? _errors : Collections.EMPTY_LIST;
+ }
+
+ public List getWarnings() {
+ return (_warnings != null) ? _warnings : Collections.EMPTY_LIST;
+ }
+ }
+
+ private static class Validator
+ extends DefaultHandler {
+ private ParseResults _results;
+
+ public Validator(ParseResults results) {
+ _results = results;
+ }
+
+ public ParseResults getResults() {
+ return _results;
+ }
+
+ public void error(SAXParseException ex) throws SAXException {
+ _results.addError(ex);
+ }
+
+ public void fatalError(SAXParseException ex) throws SAXException {
+ _results.addError(ex);
}
- public void setException(Exception exception) {
- _exception = exception;
+ public void warning(SAXParseException ex) throws SAXException {
+ _results.addWarning(ex);
}
}
}
Modified: struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/WebappPathType.java
URL: http://svn.apache.org/viewcvs/struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/WebappPathType.java?rev=290802&r1=290801&r2=290802&view=diff
==============================================================================
--- struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/WebappPathType.java (original)
+++ struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/grammar/WebappPathType.java Wed Sep 21 12:42:20 2005
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -32,6 +32,7 @@
import org.apache.ti.compiler.internal.typesystem.env.AnnotationProcessorEnvironment;
import java.io.File;
+
import java.net.URI;
import java.net.URISyntaxException;
@@ -40,21 +41,10 @@
*/
public class WebappPathType
extends AnnotationMemberType {
-
- private static final String[] CHECKABLE_EXTENSIONS =
- {
- JSP_FILE_EXTENSION,
- XJSP_FILE_EXTENSION,
- JPF_FILE_EXTENSION,
- "xml",
- "htm",
- "html"
- };
-
+ private static final String[] CHECKABLE_EXTENSIONS = { JSP_FILE_EXTENSION, XJSP_FILE_EXTENSION, JPF_FILE_EXTENSION, "xml", "htm", "html" };
private boolean _pathMustBeRelative = false;
private FlowControllerInfo _flowControllerInfo;
-
public WebappPathType(boolean pathMustBeRelative, String requiredRuntimeVersion, AnnotationGrammar parentGrammar,
FlowControllerInfo fcInfo) {
super(requiredRuntimeVersion, parentGrammar);
@@ -64,15 +54,16 @@
private static boolean isCheckableExtension(String filePath) {
for (int i = 0; i < CHECKABLE_EXTENSIONS.length; ++i) {
- if (filePath.endsWith(CHECKABLE_EXTENSIONS[i])) return true;
+ if (filePath.endsWith(CHECKABLE_EXTENSIONS[i])) {
+ return true;
+ }
}
return false;
}
public Object onCheck(AnnotationTypeElementDeclaration valueDecl, AnnotationValue value,
- AnnotationInstance[] parentAnnotations, MemberDeclaration classMember,
- int annotationArrayIndex)
+ AnnotationInstance[] parentAnnotations, MemberDeclaration classMember, int annotationArrayIndex)
throws FatalCompileTimeException {
String filePath = (String) value.getValue();
@@ -81,34 +72,40 @@
//
try {
URI uri = new URI(filePath);
- filePath = uri.getPath(); // decodes the path
- }
- catch (URISyntaxException e) {
+ filePath = uri.getPath(); // decodes the path
+ } catch (URISyntaxException e) {
addError(value, "error.invalid-uri", e.getLocalizedMessage());
+
return null;
}
//
// The path will be null for an 'opaque' URI, like "news:comp.lang.java".
//
- if (filePath == null || filePath.length() == 0) return null;
+ if ((filePath == null) || (filePath.length() == 0)) {
+ return null;
+ }
//
// Make sure it's a filetype that should exist on the filesystem. If not, ignore it.
//
- if (! checkAnyExtension() && ! isCheckableExtension(filePath)) return null;
+ if (!checkAnyExtension() && !isCheckableExtension(filePath)) {
+ return null;
+ }
boolean fileExists = true;
TypeDeclaration outerClass = CompilerUtils.getOutermostClass(classMember);
File fileToCheck = null;
- if (filePath.charAt(0) == '/') // relative to webapp root
- {
- if (_pathMustBeRelative) addError(value, "error.relative-uri");
+ if (filePath.charAt(0) == '/') // relative to webapp root
+ {
+ if (_pathMustBeRelative) {
+ addError(value, "error.relative-uri");
+ }
if (filePath.endsWith(JPF_FILE_EXTENSION_DOT)) {
TypeDeclaration type = CompilerUtils.inferTypeFromPath(filePath, getEnv());
- fileToCheck = type != null ? CompilerUtils.getSourceFile(type, false) : null;
+ fileToCheck = (type != null) ? CompilerUtils.getSourceFile(type, false) : null;
// Note that if we can't infer the file from the type, we'll fall through to the next case, where
// we actually look for the file in the webapp.
@@ -124,26 +121,27 @@
if (jpfSourceFile != null) {
fileToCheck = CompilerUtils.getWebappRelativeFile(filePath, allowFileInPageFlowSourceDir(), getEnv());
- if (fileToCheck != null && ! fileToCheck.exists() && ! (ignoreDirectories() && fileToCheck.isDirectory())) {
+ if ((fileToCheck != null) && !fileToCheck.exists() && !(ignoreDirectories() && fileToCheck.isDirectory())) {
fileExists = false;
}
}
}
}
-
//
// If the class being compiled is abstract, don't print warnings for relative-path files that aren't
// found. The derived class might have them.
//
- else if (filePath.indexOf('/') != 0 && ! outerClass.hasModifier(Modifier.ABSTRACT)) {
+ else if ((filePath.indexOf('/') != 0) && !outerClass.hasModifier(Modifier.ABSTRACT)) {
CompilerUtils.Mutable retFileToCheck = new CompilerUtils.Mutable();
fileExists = checkRelativePath(filePath, outerClass, retFileToCheck, ignoreDirectories(),
- allowFileInPageFlowSourceDir(), getEnv());
+ allowFileInPageFlowSourceDir(), getEnv());
fileToCheck = (File) retFileToCheck.get();
}
if (fileExists) {
- if (fileToCheck != null) runAdditionalChecks(fileToCheck, value);
+ if (fileToCheck != null) {
+ runAdditionalChecks(fileToCheck, value);
+ }
} else {
if (doFatalError()) {
addError(value, "error.file-not-found", filePath);
@@ -152,41 +150,50 @@
}
}
- if (fileToCheck != null) _flowControllerInfo.addReferencedFile(fileToCheck);
+ if (fileToCheck != null) {
+ _flowControllerInfo.addReferencedFile(fileToCheck);
+ }
return null;
}
- public static boolean relativePathExists(String filePath, TypeDeclaration outerClass,
- AnnotationProcessorEnvironment env)
+ public static boolean relativePathExists(String filePath, TypeDeclaration outerClass, AnnotationProcessorEnvironment env)
throws FatalCompileTimeException {
assert filePath.charAt(0) != '/' : filePath + " is not a relative path";
- if (! isCheckableExtension(filePath)) return true;
+
+ if (!isCheckableExtension(filePath)) {
+ return true;
+ }
+
return checkRelativePath(filePath, outerClass, null, true, false, env);
}
- private static boolean checkRelativePath(String filePath, TypeDeclaration outerClass,
- CompilerUtils.Mutable retFileToCheck,
+ private static boolean checkRelativePath(String filePath, TypeDeclaration outerClass, CompilerUtils.Mutable retFileToCheck,
boolean ignoreDirectories, boolean allowFileInPageFlowSourceDir,
AnnotationProcessorEnvironment env)
- throws FatalCompileTimeException
-
- {
+ throws FatalCompileTimeException {
File fileToCheck = null;
boolean fileExists = true;
if (filePath.endsWith(JPF_FILE_EXTENSION_DOT)) {
String className = filePath.substring(0, filePath.length() - JPF_FILE_EXTENSION_DOT.length());
String pkg = outerClass.getPackage().getQualifiedName();
- while (className.startsWith("../") && className.length() > 3) {
+
+ while (className.startsWith("../") && (className.length() > 3)) {
className = className.substring(3);
+
int lastDot = pkg.lastIndexOf('.');
- pkg = lastDot != -1 ? pkg.substring(0, lastDot) : "";
+ pkg = (lastDot != -1) ? pkg.substring(0, lastDot) : "";
}
- className = (pkg.length() > 0 ? pkg + '.' : "") + className.replace('/', '.');
+
+ className = ((pkg.length() > 0) ? (pkg + '.') : "") + className.replace('/', '.');
+
TypeDeclaration type = env.getTypeDeclaration(className);
- fileToCheck = type != null ? CompilerUtils.getSourceFile(type, false) : null;
- if (fileToCheck == null) fileExists = false;
+ fileToCheck = (type != null) ? CompilerUtils.getSourceFile(type, false) : null;
+
+ if (fileToCheck == null) {
+ fileExists = false;
+ }
}
// In certain error conditions (jpfFile == null), we can't determine the file. In this case, just ignore.
else if (CompilerUtils.getSourceFile(outerClass, false) != null) {
@@ -197,22 +204,31 @@
String[] webContentRoots = CompilerUtils.getWebContentRoots(env);
String jpfParentRelativePath = "";
PackageDeclaration jpfPackage = outerClass.getPackage();
- if (jpfPackage != null) jpfParentRelativePath = jpfPackage.getQualifiedName().replace('.', '/');
+
+ if (jpfPackage != null) {
+ jpfParentRelativePath = jpfPackage.getQualifiedName().replace('.', '/');
+ }
for (int i = 0; i < webContentRoots.length; i++) {
String webContentRoot = webContentRoots[i];
File desiredParentDir = new File(webContentRoot, jpfParentRelativePath);
fileToCheck = new File(desiredParentDir, filePath);
- if (fileToCheck.exists()) break;
+
+ if (fileToCheck.exists()) {
+ break;
+ }
}
}
- if (fileToCheck != null && ! fileToCheck.exists() && ! (ignoreDirectories && fileToCheck.isDirectory())) {
+ if ((fileToCheck == null) || !fileToCheck.exists()) {
fileExists = false;
}
}
- if (retFileToCheck != null) retFileToCheck.set(fileToCheck);
+ if (retFileToCheck != null) {
+ retFileToCheck.set(fileToCheck);
+ }
+
return fileExists;
}
Modified: struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/model/XWorkModuleConfigModel.java
URL: http://svn.apache.org/viewcvs/struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/model/XWorkModuleConfigModel.java?rev=290802&r1=290801&r2=290802&view=diff
==============================================================================
--- struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/model/XWorkModuleConfigModel.java (original)
+++ struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/model/XWorkModuleConfigModel.java Wed Sep 21 12:42:20 2005
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,11 +20,13 @@
import org.apache.ti.compiler.internal.FatalCompileTimeException;
import org.apache.ti.compiler.internal.JpfLanguageConstants;
import org.apache.ti.compiler.internal.model.validation.ValidationModel;
+
import org.w3c.dom.Element;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -33,11 +35,9 @@
import java.util.List;
import java.util.Map;
-
public abstract class XWorkModuleConfigModel
extends AbstractResultContainer
implements XWorkResultContainer, XWorkExceptionHandlerContainer, JpfLanguageConstants {
-
static final String PATH_RESULT = "pathResult";
static final String NAVIGATE_TO_PAGE_RESULT = "navigateToPageResult";
static final String NAVIGATE_TO_ACTION_RESULT = "navigateToActionResult";
@@ -49,12 +49,12 @@
private ArrayList _messageResources = new ArrayList();
private ValidationModel _validationModel;
private List _additionalValidatorConfigs;
-
private boolean _returnToPageDisabled = true;
private boolean _returnToActionDisabled = true;
private boolean _isNestedPageFlow = false;
private boolean _isLongLivedPageFlow = false;
private boolean _isSharedFlow = false;
+
/**
* Map of name to typename
*/
@@ -63,18 +63,11 @@
private String _multipartHandlerClassName = null;
private String _memFileSize = null;
private List _tilesDefinitionsConfigs = null;
-
-
- protected static final String DUPLICATE_ACTION_COMMENT = "Note that there is more than one action with path \"{0}\"."
- + " Use a form-qualified action path if this is not the "
- + "one you want.";
-
- protected static final String PAGEFLOW_REQUESTPROCESSOR_CLASSNAME
- = PAGEFLOW_PACKAGE + ".PageFlowRequestProcessor";
-
- protected static final String PAGEFLOW_CONTROLLER_CONFIG_CLASSNAME
- = PAGEFLOW_PACKAGE + ".config.PageFlowControllerConfig";
-
+ protected static final String DUPLICATE_ACTION_COMMENT = "Note that there is more than one action with path \"{0}\"." +
+ " Use a form-qualified action path if this is not the " +
+ "one you want.";
+ protected static final String PAGEFLOW_REQUESTPROCESSOR_CLASSNAME = PAGEFLOW_PACKAGE + ".PageFlowRequestProcessor";
+ protected static final String PAGEFLOW_CONTROLLER_CONFIG_CLASSNAME = PAGEFLOW_PACKAGE + ".config.PageFlowControllerConfig";
protected static final String XWORK_CONFIG_PREFIX = "xwork-pageflow";
protected static final char STRUTS_CONFIG_SEPARATOR = '-';
protected static final String WEBINF_DIR_NAME = "WEB-INF";
@@ -84,18 +77,18 @@
protected static final String TILES_PLUG_IN_CLASSNAME = STRUTS_PACKAGE + ".tiles.TilesPlugin";
protected static final String TILES_DEFINITIONS_CONFIG_PROPERTY = "definitions-config";
protected static final String TILES_MODULE_AWARE_PROPERTY = "moduleAware";
- protected static final String NETUI_VALIDATOR_RULES_URI = '/' + WEBINF_DIR_NAME + "/beehive-netui-validator-rules.xml";
+ protected static final String NETUI_VALIDATOR_RULES_URI = '/' + WEBINF_DIR_NAME + "/ti-validator-rules.xml";
protected static final String STRUTS_VALIDATOR_RULES_URI = '/' + WEBINF_DIR_NAME + "/validator-rules.xml";
-
public XWorkModuleConfigModel(String controllerClassName) {
super(null);
setParentApp(this);
_controllerClassName = controllerClassName;
//
- // Add a reference for the default validation message resources (in beehive-netui-pageflow.jar).
+ // Add a reference for the default validation message resources (in the runtime jar).
//
+
/* TODO: re-add message bundle support
MessageResourcesModel mrm = new MessageResourcesModel( this );
mrm.setParameter( DEFAULT_VALIDATION_MESSAGE_BUNDLE );
@@ -129,9 +122,9 @@
// "natural" mapping for the given path. Otherwise, replace the existing one if the existing one has a
// form bean and if the new mapping's form bean type comes alphabetically before the existing one's.
//
- if (mapping.getFormBeanType() == null
- || (conflictingAction.getFormBeanType() != null
- && mapping.getFormBeanType().compareTo(conflictingAction.getFormBeanType()) < 0)) {
+ if ((mapping.getFormBeanType() == null) ||
+ ((conflictingAction.getFormBeanType() != null) &&
+ (mapping.getFormBeanType().compareTo(conflictingAction.getFormBeanType()) < 0))) {
_actions.put(mappingPath, mapping);
defaultMappingForThisPath = mapping;
conflictingAction.setOverloaded(false);
@@ -140,7 +133,7 @@
addDisambiguatedAction(mapping);
addDisambiguatedAction(conflictingAction);
defaultMappingForThisPath.setOverloaded(true);
- defaultMappingForThisPath.setComment(DUPLICATE_ACTION_COMMENT.replaceAll("\\{0\\}", mappingPath)); // @TODO I18N
+ defaultMappingForThisPath.setComment(DUPLICATE_ACTION_COMMENT.replaceAll("\\{0\\}", mappingPath)); // @TODO I18N
} else {
_actions.put(mappingPath, mapping);
}
@@ -148,7 +141,9 @@
protected String getFormQualifiedActionPath(XWorkActionModel action) {
assert action.getFormBeanType() != null : "action " + action.getName() + " has no form bean";
+
String beanType = action.getFormBeanType();
+
return action.getName() + '_' + makeFullyQualifiedBeanName(beanType);
}
@@ -163,15 +158,16 @@
return formType.replace('.', '_').replace('$', '_');
}
- protected static class ActionComparator implements Comparator {
-
+ protected static class ActionComparator
+ implements Comparator {
public int compare(Object o1, Object o2) {
assert o1 instanceof XWorkActionModel && o2 instanceof XWorkActionModel;
XWorkActionModel am1 = (XWorkActionModel) o1;
XWorkActionModel am2 = (XWorkActionModel) o2;
- assert ! am1.getName().equals(am2.getName()); // there should be no duplicate paths
+ assert !am1.getName().equals(am2.getName()); // there should be no duplicate paths
+
return am1.getName().compareTo(am2.getName());
}
}
@@ -184,6 +180,7 @@
ArrayList sortedActions = new ArrayList();
sortedActions.addAll(_actions.values());
Collections.sort(sortedActions, new ActionComparator());
+
return sortedActions;
}
@@ -198,15 +195,16 @@
/**
* Get the MessageResourcesModel for which no "key" is set (the default one used at runtime).
*/
+
/* TODO: re-add message bundle support
public MessageResourcesModel getDefaultMessageResources()
{
- for ( java.util.Iterator ii = _messageResources.iterator(); ii.hasNext(); )
+ for ( java.util.Iterator ii = _messageResources.iterator(); ii.hasNext(); )
{
MessageResourcesModel i = ( MessageResourcesModel ) ii.next();
if ( i.getKey() == null ) return i;
}
-
+
return null;
}
*/
@@ -227,14 +225,14 @@
}
public void setAdditionalValidatorConfigs(List additionalValidatorConfigs) {
- if (additionalValidatorConfigs != null && ! additionalValidatorConfigs.isEmpty()) {
+ if ((additionalValidatorConfigs != null) && !additionalValidatorConfigs.isEmpty()) {
_additionalValidatorConfigs = additionalValidatorConfigs;
}
}
public void setValidationModel(ValidationModel validationModel) {
- if (! validationModel.isEmpty()) // if there's nothing in the validation model, we don't care about it.
- {
+ if (!validationModel.isEmpty()) // if there's nothing in the validation model, we don't care about it.
+ {
_validationModel = validationModel;
}
}
@@ -244,7 +242,11 @@
*/
public String getNamespace() {
int lastDot = _controllerClassName.lastIndexOf('.');
- if (lastDot == -1) return "/";
+
+ if (lastDot == -1) {
+ return "/";
+ }
+
return "/" + _controllerClassName.substring(0, lastDot).replace('.', '/');
}
@@ -256,10 +258,8 @@
public void writeXml(PrintWriter writer, File mergeFile)
throws IOException, XmlModelWriterException, FatalCompileTimeException {
- XmlModelWriter xw = new XmlModelWriter(mergeFile, "xwork",
- "-//OpenSymphony Group//XWork 1.0//EN",
- "http://www.opensymphony.com/xwork/xwork-1.0.dtd",
- getHeaderComment(mergeFile));
+ XmlModelWriter xw = new XmlModelWriter(mergeFile, "xwork", "-//OpenSymphony Group//XWork 1.0//EN",
+ "http://www.opensymphony.com/xwork/xwork-1.0.dtd", getHeaderComment(mergeFile));
Element root = xw.getDocument().getDocumentElement();
@@ -295,21 +295,18 @@
// message-resources
//
//writeMessageResources( scElement );
-
//
// ValidatorPlugIn
//
//writeValidatorInit( scElement );
-
//
// TilesPlugin
//
//writeTilesInit( scElement );
-
//
// Write the file.
//
- xw.write(writer);
+ xw.simpleFastWrite(writer);
}
private void writeActions(XmlModelWriter xw, Element parentElement) {
@@ -324,7 +321,7 @@
private void writeExceptions(XmlModelWriter xw, Element parentElement) {
List exceptionCatches = getExceptionCatchesList();
- if (exceptionCatches != null && ! exceptionCatches.isEmpty()) {
+ if ((exceptionCatches != null) && !exceptionCatches.isEmpty()) {
for (int i = 0; i < exceptionCatches.size(); ++i) {
XWorkExceptionHandlerModel ec = (XWorkExceptionHandlerModel) exceptionCatches.get(i);
ec.writeXML(xw, parentElement);
@@ -335,25 +332,44 @@
protected void writeModuleMetadataElement(XmlModelWriter xw, Element parentElement) {
Element metadataElement = xw.addElement(parentElement, "action");
xw.addComment(metadataElement,
- "This is hopefully temporary. It's a dummy action with metadata (params) related to this module");
+ "This is hopefully temporary. It's a dummy action with metadata (params) related to this module");
metadataElement.setAttribute("name", "_moduleMetadata");
addParam(xw, metadataElement, "controllerClassName", _controllerClassName);
- if (_isNestedPageFlow) addParam(xw, metadataElement, "nestedFlow", true);
- if (_isLongLivedPageFlow) addParam(xw, metadataElement, "longLivedFlow", true);
- if (_isSharedFlow) addParam(xw, metadataElement, "sharedFlow", true);
- if (isReturnToPageDisabled()) addParam(xw, metadataElement, "returnToPageDisabled", true);
- if (isReturnToActionDisabled()) addParam(xw, metadataElement, "returnToActionDisabled", true);
+ if (_isNestedPageFlow) {
+ addParam(xw, metadataElement, "nestedFlow", true);
+ }
+
+ if (_isLongLivedPageFlow) {
+ addParam(xw, metadataElement, "longLivedFlow", true);
+ }
+
+ if (_isSharedFlow) {
+ addParam(xw, metadataElement, "sharedFlow", true);
+ }
+
+ if (isReturnToPageDisabled()) {
+ addParam(xw, metadataElement, "returnToPageDisabled", true);
+ }
- if (_sharedFlows != null && _sharedFlows.size() > 0) {
+ if (isReturnToActionDisabled()) {
+ addParam(xw, metadataElement, "returnToActionDisabled", true);
+ }
+
+ if ((_sharedFlows != null) && (_sharedFlows.size() > 0)) {
StringBuffer str = new StringBuffer();
boolean first = true;
for (java.util.Iterator i = _sharedFlows.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
- if (! first) str.append(',');
+
+ if (!first) {
+ str.append(',');
+ }
+
first = false;
+
String name = (String) entry.getKey();
String type = (String) entry.getValue();
str.append(name).append('=').append(type);
@@ -384,26 +400,26 @@
{
PlugInDocument.PlugIn plugInElementToEdit = null;
PlugInDocument.PlugIn[] existingPlugIns = scElement.getPlugInArray();
-
+
for ( int i = 0; i < existingPlugIns.length; i++ )
{
PlugInDocument.PlugIn existingPlugIn = existingPlugIns[i];
-
+
if ( VALIDATOR_PLUG_IN_CLASSNAME.equals( existingPlugIn.getClassName() ) )
{
plugInElementToEdit = existingPlugIn;
break;
}
}
-
+
if ( plugInElementToEdit == null )
{
plugInElementToEdit = scElement.addNewPlugIn();
plugInElementToEdit.setClassName( VALIDATOR_PLUG_IN_CLASSNAME );
}
-
+
SetPropertyDocument.SetProperty[] existingSetProperties = plugInElementToEdit.getSetPropertyArray();
-
+
for ( int i = 0; i < existingSetProperties.length; i++ )
{
if ( VALIDATOR_PATHNAMES_PROPERTY.equals( existingSetProperties[i].getProperty() ) )
@@ -415,31 +431,31 @@
return;
}
}
-
+
SetPropertyDocument.SetProperty pathnamesProperty = plugInElementToEdit.addNewSetProperty();
pathnamesProperty.setProperty( VALIDATOR_PATHNAMES_PROPERTY );
StringBuffer pathNames = new StringBuffer();
pathNames.append( NETUI_VALIDATOR_RULES_URI );
pathNames.append( ",/WEB-INF/classes/" ).append( _validationModel.getOutputFileURI() );
-
+
if ( _validationModel != null && ! _validationModel.isEmpty() )
{
pathNames.append( ',' ).append( _validationModel.getOutputFileURI() );
}
-
+
if ( _additionalValidatorConfigs != null )
{
- for ( java.util.Iterator ii = _additionalValidatorConfigs.iterator(); ii.hasNext(); )
+ for ( java.util.Iterator ii = _additionalValidatorConfigs.iterator(); ii.hasNext(); )
{
String configFile = ( String ) ii.next();
pathNames.append( ',' ).append( configFile );
}
}
-
+
pathnamesProperty.setValue( pathNames.toString() );
}
}
-
+
protected void writeTilesInit( StrutsConfigDocument.StrutsConfig scElement )
{
if ( _tilesDefinitionsConfigs == null || _tilesDefinitionsConfigs.isEmpty() )
@@ -498,7 +514,7 @@
StringBuffer pathNames = new StringBuffer();
boolean firstOne = true;
- for ( java.util.Iterator ii = _tilesDefinitionsConfigs.iterator(); ii.hasNext(); )
+ for ( java.util.Iterator ii = _tilesDefinitionsConfigs.iterator(); ii.hasNext(); )
{
String definitionsConfig = ( String ) ii.next();
if ( ! firstOne ) pathNames.append( ',' );
@@ -516,9 +532,7 @@
}
}
*/
-
- protected String getHeaderComment(File mergeFile)
- throws FatalCompileTimeException {
+ protected String getHeaderComment(File mergeFile) throws FatalCompileTimeException {
return null;
}
@@ -533,10 +547,15 @@
public static String getOutputFilePath(String baseFileName, String containingPackage) {
StringBuffer fileName = new StringBuffer(XWORK_CONFIG_OUTPUT_DIR);
fileName.append('/');
- if (containingPackage != null) fileName.append(containingPackage.replace('.', '/'));
+
+ if (containingPackage != null) {
+ fileName.append(containingPackage.replace('.', '/'));
+ }
+
fileName.append('/');
fileName.append(baseFileName);
fileName.append(".xml");
+
return fileName.toString();
}
Added: struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/model/XmlElementSupport.java
URL: http://svn.apache.org/viewcvs/struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/model/XmlElementSupport.java?rev=290802&view=auto
==============================================================================
--- struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/model/XmlElementSupport.java (added)
+++ struts/sandbox/trunk/ti/jars/core/src/java/org/apache/ti/compiler/internal/model/XmlElementSupport.java Wed Sep 21 12:42:20 2005
@@ -0,0 +1,217 @@
+/*
+ * Copyright 2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * $Header:$
+ */
+package org.apache.ti.compiler.internal.model;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+
+import java.util.ArrayList;
+
+public abstract class XmlElementSupport {
+ private String _comment;
+
+ public void setComment(String comment) {
+ _comment = comment;
+ }
+
+ public final void writeXML(XmlModelWriter xw, Element element) {
+ if (_comment != null) {
+ xw.addComment(element, ' ' + _comment + ' ');
+ }
+
+ writeToElement(xw, element);
+ }
+
+ protected abstract void writeToElement(XmlModelWriter xw, Element element);
+
+ protected final void setElementAttributeMayBeEmpty(Element element, String attrName, String value) {
+ if (value != null) {
+ String existingAttr = getElementAttribute(element, attrName);
+
+ if ((existingAttr == null) || (existingAttr.length() == 0)) {
+ element.setAttribute(attrName, value);
+ }
+ }
+ }
+
+ protected final void setElementAttribute(Element element, String attrName, String value) {
+ if ((value != null) && (value.length() > 0)) {
+ String existingAttr = getElementAttribute(element, attrName);
+
+ if ((existingAttr == null) || (existingAttr.length() == 0)) {
+ element.setAttribute(attrName, value);
+ }
+ }
+ }
+
+ protected final void setElementAttribute(Element element, String attrName, Boolean value) {
+ if (value != null) {
+ String existingAttr = getElementAttribute(element, attrName);
+
+ if ((existingAttr == null) || (existingAttr.length() == 0)) {
+ element.setAttribute(attrName, value.toString());
+ }
+ }
+ }
+
+ /**
+ * Gets the attribute value, or <code>null</code> (unlike <code>Element.getAttribute</code>).
+ */
+ protected String getElementAttribute(Element element, String attrName) {
+ Attr attr = element.getAttributeNode(attrName);
+
+ return (attr != null) ? attr.getValue() : null;
+ }
+
+ protected final void setElementAttribute(Element element, String attrName, boolean value) {
+ if (value) {
+ String existingAttr = getElementAttribute(element, attrName);
+
+ if (existingAttr == null) {
+ element.setAttribute(attrName, Boolean.toString(value));
+ }
+ }
+ }
+
+ protected final Element findChildElement(XmlModelWriter xw, Element parent, String childName, boolean createIfNotPresent) {
+ return findChildElement(xw, parent, childName, null, null, createIfNotPresent);
+ }
+
+ protected final Element findChildElementWithChildText(XmlModelWriter xw, Element parent, String childName,
+ String childSubElementName, String textValue, boolean createIfNotPresent) {
+ Element[] matchingChildren = getChildElements(parent, childName);
+
+ for (int i = 0; i < matchingChildren.length; i++) {
+ Element childSubElement = findChildElement(xw, matchingChildren[i], childSubElementName, false);
+
+ if (childSubElement != null) {
+ String text = getTextContent(childSubElement);
+
+ if (textValue.equals(text)) {
+ return childSubElement;
+ }
+ }
+ }
+
+ if (createIfNotPresent) {
+ Element newChild = xw.addElement(parent, childName);
+ xw.addElementWithText(newChild, childSubElementName, textValue);
+
+ return newChild;
+ }
+
+ return null;
+ }
+
+ protected final Element findChildElement(XmlModelWriter xw, Element parent, String childName, String keyAttributeName,
+ String keyAttributeValue, boolean createIfNotPresent) {
+ NodeList childNodes = parent.getChildNodes();
+
+ for (int i = 0; i < childNodes.getLength(); ++i) {
+ Node node = childNodes.item(i);
+
+ if (node instanceof Element) {
+ Element childElement = (Element) node;
+
+ if (childName.equals(childElement.getTagName())) {
+ // If there's no target key attribute to match, just return the element.
+ if (keyAttributeName == null) {
+ return childElement;
+ }
+
+ // Return the element if the key attribute values match (or if both are null).
+ String childElementAttributeValue = getElementAttribute(childElement, keyAttributeName);
+
+ if (((keyAttributeValue == null) && (childElementAttributeValue == null)) ||
+ ((keyAttributeValue != null) && keyAttributeValue.equals(childElementAttributeValue))) {
+ return childElement;
+ }
+ }
+ }
+ }
+
+ if (createIfNotPresent) {
+ Element newChild = xw.getDocument().createElement(childName);
+ parent.appendChild(newChild);
+
+ if ((keyAttributeName != null) && (keyAttributeValue != null)) {
+ newChild.setAttribute(keyAttributeName, keyAttributeValue);
+ }
+
+ return newChild;
+ }
+
+ return null;
+ }
+
+ protected Element[] getChildElements(Element element, String nameFilter) {
+ NodeList children = element.getChildNodes();
+ ArrayList list = new ArrayList(children.getLength());
+
+ for (int i = 0; i < children.getLength(); ++i) {
+ Node node = children.item(i);
+
+ if (node instanceof Element) {
+ if ((nameFilter == null) || nameFilter.equals(((Element) node).getTagName())) {
+ list.add(node);
+ }
+ }
+ }
+
+ return (Element[]) list.toArray(new Element[list.size()]);
+ }
+
+ public static boolean isWhiteSpace(String s) {
+ for (int j = 0; j < s.length(); ++j) {
+ if (!Character.isWhitespace(s.charAt(j))) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public static String getTextContent(Element element) // TODO: move to a utils class, so XmlModelWriter is independentf
+ {
+ NodeList children = element.getChildNodes();
+ String retVal = null;
+
+ for (int i = 0, len = children.getLength(); i < len; ++i) {
+ Node child = children.item(i);
+
+ if (!(child instanceof Text)) {
+ return null;
+ }
+
+ String text = child.getNodeValue();
+
+ if (!isWhiteSpace(text)) {
+ if (retVal != null) {
+ return null;
+ }
+
+ retVal = text;
+ }
+ }
+
+ return retVal;
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@struts.apache.org
For additional commands, e-mail: dev-help@struts.apache.org