Merge from helma_1_2_4

This commit is contained in:
hns 2003-04-16 16:28:04 +00:00
parent df40e73b63
commit 66663c8b20
177 changed files with 28899 additions and 18112 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -8,7 +8,7 @@
<target name="init"> <target name="init">
<property name="Name" value="helma"/> <property name="Name" value="helma"/>
<property name="year" value="1998-${year}"/> <property name="year" value="1998-${year}"/>
<property name="version" value="1.2.3"/> <property name="version" value="1.3cvs"/>
<property name="project" value="helma"/> <property name="project" value="helma"/>
<property name="build.compiler" value="classic"/> <property name="build.compiler" value="classic"/>
@ -28,8 +28,8 @@
<property name="jar.name" value="${project}"/> <property name="jar.name" value="${project}"/>
<property name="package.name" value="${project}-${version}"/> <property name="package.name" value="${project}-${version}"/>
<property name="antclick.name" value="antclick-1.0pre5"/> <property name="antclick.name" value="antclick-1.0cvs"/>
<property name="antville.name" value="antville-1.0pre1"/> <property name="antville.name" value="antville-1.0cvs"/>
<property name="debug" value="on"/> <property name="debug" value="on"/>
<property name="optimize" value="on"/> <property name="optimize" value="on"/>

Binary file not shown.

View file

@ -1,98 +1,197 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import helma.framework.IPathElement; import helma.framework.IPathElement;
import helma.main.Server; import helma.main.Server;
import helma.util.SystemProperties;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
public class DocApplication extends DocDirElement { /**
*
*/
public class DocApplication extends DocDirElement {
HashSet excluded;
public static void main (String args[]) { /**
// DocApplication app; * Creates a new DocApplication object.
// app = new DocApplication (args[0], args[1]); *
// app.readApplication (); * @param name ...
* @param location ...
*
* @throws DocException ...
*/
public DocApplication(String name, File location) throws DocException {
super(name, location, APPLICATION);
readProps();
}
// DocPrototype el = DocPrototype.newInstance (new File(args[0])); /**
// el.readFiles (); * Creates a new DocApplication object.
*
* @param name ...
* @param appDir ...
*
* @throws DocException ...
*/
public DocApplication(String name, String appDir) throws DocException {
super(name, new File(appDir), APPLICATION);
readProps();
}
// DocFunction func = DocFunction.newTemplate (new File(args[0])); /**
// DocFunction func = DocFunction.newAction (new File(args[0])); *
*
* @param args ...
*/
public static void main(String[] args) {
// DocApplication app;
// app = new DocApplication (args[0], args[1]);
// app.readApplication ();
// DocPrototype el = DocPrototype.newInstance (new File(args[0]));
// el.readFiles ();
// DocFunction func = DocFunction.newTemplate (new File(args[0]));
// DocFunction func = DocFunction.newAction (new File(args[0]));
DocFunction[] func = DocFunction.newFunctions(new File(args[0]));
DocFunction[] func = DocFunction.newFunctions (new File (args[0])); // DocSkin skin = DocSkin.newInstance (new File (args[0]));
// System.out.println (func.getContent ());
// System.out.println ("\n\n\ncomment = " + func.getComment ());
}
// DocSkin skin = DocSkin.newInstance (new File (args[0])); /**
// System.out.println (func.getContent ()); * reads the app.properties file and parses for helma.excludeDocs
// System.out.println ("\n\n\ncomment = " + func.getComment ()); */
} private void readProps() {
File propsFile = new File(location, "app.properties");
SystemProperties serverProps = Server.getServer().getProperties();
SystemProperties appProps = new SystemProperties(propsFile.getAbsolutePath(),
serverProps);
excluded = new HashSet();
addExclude("cvs");
addExclude(".docs");
public DocApplication (String name, File location) throws DocException { String excludeProps = appProps.getProperty("helma.excludeDocs");
super (name, location, APPLICATION);
}
public DocApplication (String name, String appDir) throws DocException { if (excludeProps != null) {
super (name, new File (appDir), APPLICATION); StringTokenizer tok = new StringTokenizer(excludeProps, ",");
}
while (tok.hasMoreTokens()) {
String str = tok.nextToken().trim();
/** addExclude(str);
* reads all prototypes and files of the application }
*/ }
public void readApplication () { }
String arr[] = location.list ();
children.clear ();
for (int i=0; i<arr.length; i++) {
if (Util.isExcluded (arr[i]))
continue;
File f = new File (location.getAbsolutePath (), arr[i]);
if (!f.isDirectory ())
continue;
try {
DocPrototype pt = DocPrototype.newInstance (f, this);
addChild (pt);
pt.readFiles ();
} catch (DocException e) {
debug ("Couldn't read prototype " + arr[i] + ": " + e.getMessage ());
}
System.out.println (f);
}
for (Iterator i=children.values ().iterator (); i.hasNext ();) {
((DocPrototype) i.next ()).checkInheritance ();
}
}
public DocElement[] listFunctions () { /**
Vector allFunctions = new Vector (); *
for (Iterator i = children.values ().iterator (); i.hasNext ();) { *
DocElement proto = (DocElement) i.next (); * @param str ...
allFunctions.addAll (proto.children.values ()); */
} public void addExclude(String str) {
Collections.sort (allFunctions, new DocComparator (DocComparator.BY_NAME, this)); excluded.add(str.toLowerCase());
return (DocElement[]) allFunctions.toArray (new DocElement[allFunctions.size ()]); }
}
/**
*
*
* @param str ...
*
* @return ...
*/
public boolean isExcluded(String str) {
return (excluded.contains(str.toLowerCase()));
}
/** /**
* from helma.framework.IPathElement, overridden with "api" * reads all prototypes and files of the application
* to work in manage-application */
*/ public void readApplication() {
public String getElementName() { readProps();
return "api";
}
String[] arr = location.list();
/** children.clear();
* from helma.framework.IPathElement, overridden with
* Server.getServer() to work in manage-application
*/
public IPathElement getParentElement() {
Server s = helma.main.Server.getServer();
return s.getChildElement(this.name);
}
for (int i = 0; i < arr.length; i++) {
if (isExcluded(arr[i])) {
continue;
}
File f = new File(location.getAbsolutePath(), arr[i]);
if (!f.isDirectory()) {
continue;
}
try {
DocPrototype pt = DocPrototype.newInstance(f, this);
addChild(pt);
pt.readFiles();
} catch (DocException e) {
debug("Couldn't read prototype " + arr[i] + ": " + e.getMessage());
}
System.out.println(f);
}
for (Iterator i = children.values().iterator(); i.hasNext();) {
((DocPrototype) i.next()).checkInheritance();
}
}
/**
*
*
* @return ...
*/
public DocElement[] listFunctions() {
Vector allFunctions = new Vector();
for (Iterator i = children.values().iterator(); i.hasNext();) {
DocElement proto = (DocElement) i.next();
allFunctions.addAll(proto.children.values());
}
Collections.sort(allFunctions, new DocComparator(DocComparator.BY_NAME, this));
return (DocElement[]) allFunctions.toArray(new DocElement[allFunctions.size()]);
}
/**
* from helma.framework.IPathElement, overridden with "api"
* to work in manage-application
*/
public String getElementName() {
return "api";
}
/**
* from helma.framework.IPathElement, overridden with
* Server.getServer() to work in manage-application
*/
public IPathElement getParentElement() {
Server s = helma.main.Server.getServer();
return s.getChildElement(this.name);
}
} }

View file

@ -1,44 +1,88 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import java.util.Comparator; import java.util.Comparator;
/**
*
*/
public class DocComparator implements Comparator { public class DocComparator implements Comparator {
public static final int BY_TYPE = 0;
public static final int BY_NAME = 1;
int mode;
DocElement docEl;
public static final int BY_TYPE = 0; /**
public static final int BY_NAME = 1; * Creates a new DocComparator object.
*
* @param mode ...
* @param docEl ...
*/
public DocComparator(int mode, DocElement docEl) {
this.mode = mode;
this.docEl = docEl;
}
int mode; /**
DocElement docEl; * Creates a new DocComparator object.
*
* @param docEl ...
*/
public DocComparator(DocElement docEl) {
this.mode = 0;
this.docEl = docEl;
}
public DocComparator(int mode, DocElement docEl) { /**
this.mode = mode; *
this.docEl = docEl; *
} * @param obj1 ...
* @param obj2 ...
*
* @return ...
*/
public int compare(Object obj1, Object obj2) {
DocElement e1 = (DocElement) obj1;
DocElement e2 = (DocElement) obj2;
public DocComparator(DocElement docEl) { if ((mode == BY_TYPE) && (e1.getType() > e2.getType())) {
this.mode = 0; return 1;
this.docEl = docEl; } else if ((mode == BY_TYPE) && (e1.getType() < e2.getType())) {
} return -1;
} else {
return e1.name.compareTo(e2.name);
}
}
public int compare(Object obj1, Object obj2) { /**
DocElement e1 = (DocElement)obj1; *
DocElement e2 = (DocElement)obj2; *
if (mode==BY_TYPE && e1.getType()>e2.getType()) * @param obj ...
return 1; *
else if (mode==BY_TYPE && e1.getType()<e2.getType()) * @return ...
return -1; */
else { public boolean equals(Object obj) {
return e1.name.compareTo(e2.name); DocElement el = (DocElement) obj;
}
}
public boolean equals(Object obj) {
DocElement el = (DocElement) obj;
if (el.name.equals(docEl.name) && el.getType()==docEl.getType()) {
return true;
} else {
return false;
}
}
if (el.name.equals(docEl.name) && (el.getType() == docEl.getType())) {
return true;
} else {
return false;
}
}
} }

View file

@ -1,36 +1,53 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import FESI.Parser.*;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import FESI.Parser.*; /**
*
*/
public abstract class DocDirElement extends DocElement { public abstract class DocDirElement extends DocElement {
// a default file that is read as comment for applications
// and prototypes if found in their directories
public static final String[] DOCFILES = {
"doc.html", "doc.htm", "app.html",
"app.htm", "prototype.html",
"prototype.htm", "index.html", "index.htm"
};
// a default file that is read as comment for applications protected DocDirElement(String name, File location, int type) {
// and prototypes if found in their directories super(name, location, type);
public static final String[] DOCFILES = { checkCommentFiles();
"doc.html", "doc.htm", }
"app.html", "app.htm",
"prototype.html", "prototype.htm",
"index.html", "index.htm"
};
protected DocDirElement (String name, File location, int type) { private void checkCommentFiles() throws DocException {
super (name, location, type); for (int i = 0; i < DOCFILES.length; i++) {
checkCommentFiles (); File f = new File(location, DOCFILES[i]);
}
private void checkCommentFiles () throws DocException { if (f.exists()) {
for (int i=0; i<DOCFILES.length; i++) { String rawComment = readFile(f);
File f = new File (location, DOCFILES[i]);
if (f.exists ()) {
String rawComment = readFile (f);
parseComment (rawComment);
return;
}
}
}
parseComment(rawComment);
return;
}
}
}
} }

View file

@ -1,304 +1,403 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import helma.framework.IPathElement;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import helma.framework.IPathElement; /**
*
*/
public abstract class DocElement implements IPathElement {
public static final int APPLICATION = 0;
public static final int PROTOTYPE = 1;
public static final int ACTION = 2;
public static final int TEMPLATE = 3;
public static final int FUNCTION = 4;
public static final int MACRO = 5;
public static final int SKIN = 6;
public static final int PROPERTIES = 7;
public abstract class DocElement implements IPathElement { // above constants are used as array indices
public static final String[] typeNames = {
"Application", "Prototype", "Action",
"Template", "Function", "Macro", "Skin",
"Properties"
};
// identifiers of this element // identifiers of this element
String name; String name;
int type; int type;
File location; File location;
DocElement parent = null; DocElement parent = null;
Map children = new HashMap (); Map children = new HashMap();
// content // content
String content = ""; String content = "";
String comment = ""; String comment = "";
List tags = new Vector (); List tags = new Vector();
List parameters = new Vector (); List parameters = new Vector();
public static final int APPLICATION = 0; protected DocElement(String name, String location, int type)
public static final int PROTOTYPE = 1; throws DocException {
public static final int ACTION = 2; this(name, new File(location), type);
public static final int TEMPLATE = 3; }
public static final int FUNCTION = 4;
public static final int MACRO = 5;
public static final int SKIN = 6;
public static final int PROPERTIES = 7;
// above constants are used as array indices protected DocElement(String name, File location, int type)
public static final String[] typeNames = { throws DocException {
"Application", if (location.exists() == false) {
"Prototype", throw new DocException(name + " not found in " + location.toString());
"Action", }
"Template",
"Function",
"Macro",
"Skin",
"Properties"
};
protected DocElement (String name, String location, int type) throws DocException { this.name = name;
this (name, new File (location), type); this.location = location;
} this.type = type;
}
protected DocElement (String name, File location, int type) throws DocException { /**
if (location.exists()==false) * the simple name of the element
throw new DocException( name + " not found in " + location.toString ()); */
this.name = name; public String getName() {
this.location = location; return name;
this.type = type; }
}
/** /**
* the simple name of the element * @return absolute path to location of element
*/ * (directory for apps and prototypes, file for
public String getName() { * methods and properties files)
return name; */
} public File getLocation() {
return location;
}
/** /**
* @return absolute path to location of element *
* (directory for apps and prototypes, file for *
* methods and properties files) * @return ...
*/ */
public File getLocation() { public int getType() {
return location; return type;
} }
public int getType() { /**
return type; *
} *
* @return ...
*/
public String getTypeName() {
return typeNames[type];
}
public String getTypeName () { /**
return typeNames [type]; * returns the comment string, empty string if no comment is set.
} */
public String getComment() {
return comment;
}
/**
* the actual content of the doc element (the function body, the properties
* list, the file list etc.
*/
public String getContent() {
return content;
}
/** /**
* returns the comment string, empty string if no comment is set. *
*/ *
public String getComment () { * @param rawContent ...
return comment; */
} public void addTag(String rawContent) {
if (tags == null) {
tags = new Vector();
}
try {
DocTag tag = DocTag.parse(rawContent);
/** tags.add(tag);
* the actual content of the doc element (the function body, the properties } catch (DocException doc) {
* list, the file list etc. debug(doc.toString());
*/ }
public String getContent () { }
return content;
}
/**
* list all tags
*/
public DocTag[] listTags() {
return (DocTag[]) tags.toArray(new DocTag[0]);
}
public void addTag (String rawContent) { /**
if (tags==null) { * filter the tags according to DocTag.TYPE
tags = new Vector (); */
} public DocTag[] listTags(int type) {
try { Vector retval = new Vector();
DocTag tag = DocTag.parse (rawContent);
tags.add (tag);
} catch (DocException doc) {
debug (doc.toString ());
}
}
for (int i = 0; i < tags.size(); i++) {
if (((DocTag) tags.get(i)).getType() == type) {
retval.add(tags.get(i));
}
}
/** return (DocTag[]) retval.toArray();
* list all tags }
*/
public DocTag[] listTags () {
return (DocTag[]) tags.toArray (new DocTag[0]);
}
/**
*
*
* @param param ...
*
* @return ...
*/
public boolean hasParameter(String param) {
return parameters.contains(param);
}
/** /**
* filter the tags according to DocTag.TYPE * the list of parameters
*/ */
public DocTag[] listTags (int type) { public String[] listParameters() {
Vector retval = new Vector (); return (String[]) parameters.toArray(new String[0]);
for (int i=0; i<tags.size (); i++) { }
if ( ((DocTag) tags.get (i)).getType() == type)
retval.add (tags.get (i));
}
return (DocTag[]) retval.toArray ();
}
/**
* add a string to the parameters-list
*/
protected void addParameter(String param) {
parameters.add(param);
}
public boolean hasParameter (String param) { /**
return parameters.contains (param); * parse rawComment, render DocTags
} */
void parseComment(String rawComment) {
try {
StringTokenizer tok = new StringTokenizer(rawComment, "\n", true);
int BLANK = 0;
int TEXT = 1;
int TAGS = 2;
boolean lastEmpty = false;
int mode = BLANK;
StringBuffer buf = new StringBuffer();
/** while (tok.hasMoreTokens()) {
* the list of parameters String line = Util.chopDelimiters(tok.nextToken().trim());
*/
public String[] listParameters () {
return (String[]) parameters.toArray (new String[0]);
}
if ("".equals(line)) {
// if we've already had text, store that this line was empty
lastEmpty = (mode != BLANK) ? true : false;
/** continue;
* add a string to the parameters-list }
*/
protected void addParameter (String param) {
parameters.add (param);
}
// if we come here the first time, start with TEXT mode
mode = (mode == BLANK) ? TEXT : mode;
/** // check if we have a new tag
* parse rawComment, render DocTags if (DocTag.isTagStart(line)) {
*/ // if we appended to comment text until now, store that ...
void parseComment (String rawComment) { if (mode == TEXT) {
try { comment = buf.toString();
StringTokenizer tok = new StringTokenizer (rawComment, "\n", true); }
int BLANK = 0;
int TEXT = 1;
int TAGS = 2;
boolean lastEmpty = false;
int mode = BLANK;
StringBuffer buf = new StringBuffer ();
while (tok.hasMoreTokens ()) {
String line = Util.chopDelimiters (tok.nextToken ().trim ());
if ("".equals(line)) {
// if we've already had text, store that this line was empty
lastEmpty = (mode!=BLANK) ? true : false;
continue;
}
// if we come here the first time, start with TEXT mode
mode = (mode==BLANK) ? TEXT : mode;
// check if we have a new tag
if (DocTag.isTagStart (line)) {
// if we appended to comment text until now, store that ...
if (mode==TEXT)
comment = buf.toString ();
// if we appended to a tag, store that ...
if (mode==TAGS)
addTag (buf.toString ());
// reset buffer
buf = new StringBuffer ();
mode = TAGS;
}
// append to current buffer
if (lastEmpty==true)
buf.append ("\n");
buf.append (line);
buf.append (" ");
lastEmpty = false;
}
// store the last element, if there was at least one element ...
if (mode==TEXT)
comment = buf.toString ();
else if (mode==TAGS)
addTag (buf.toString ());
} catch (RuntimeException rt) {
debug ("parse error in " + location + ": " + rt.getMessage());
}
}
/** // if we appended to a tag, store that ...
* utility: read a complete file into a string if (mode == TAGS) {
*/ addTag(buf.toString());
protected static String readFile (File file) { }
try {
StringBuffer buf = new StringBuffer ();
BufferedReader in = new BufferedReader (new FileReader (file));
String line = in.readLine ();
while(line!=null) {
buf.append (line+"\n");
line = in.readLine ();
}
in.close ();
return buf.toString();
} catch (IOException e) {
return ("");
}
}
// reset buffer
buf = new StringBuffer();
mode = TAGS;
}
public void setParent (DocElement parent) { // append to current buffer
this.parent = parent; if (lastEmpty == true) {
} buf.append("\n");
}
public void addChild (DocElement child) { buf.append(line);
if (child==null) buf.append(" ");
return; lastEmpty = false;
children.put (child.getElementName (), child); }
}
public int countChildren () { // store the last element, if there was at least one element ...
return children.size (); if (mode == TEXT) {
} comment = buf.toString();
} else if (mode == TAGS) {
addTag(buf.toString());
}
} catch (RuntimeException rt) {
debug("parse error in " + location + ": " + rt.getMessage());
}
}
public Map getChildren () { /**
return children; * utility: read a complete file into a string
} */
protected static String readFile(File file) {
try {
StringBuffer buf = new StringBuffer();
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
/** while (line != null) {
* returns an array of doc elements, sorted by their name buf.append(line + "\n");
*/ line = in.readLine();
public DocElement[] listChildren () { }
String[] keys = (String[]) children.keySet ().toArray (new String[0]);
Arrays.sort (keys);
DocElement[] arr = new DocElement [keys.length];
for (int i=0; i<keys.length; i++) {
arr [i] = (DocElement) children.get (keys[i]);
}
return arr;
}
/** in.close();
* from helma.framework.IPathElement. Elements are named
* like this: typename_name
*/
public String getElementName() {
return typeNames[type].toLowerCase() + "_" + name;
}
return buf.toString();
} catch (IOException e) {
return ("");
}
}
/** /**
* from helma.framework.IPathElement. Retrieves a child from the *
* children map. *
*/ * @param parent ...
public IPathElement getChildElement (String name) { */
try { public void setParent(DocElement parent) {
return (IPathElement) children.get (name); this.parent = parent;
} catch (ClassCastException cce) { }
debug (cce.toString ());
cce.printStackTrace ();
return null;
}
}
/**
*
*
* @param child ...
*/
public void addChild(DocElement child) {
if (child == null) {
return;
}
/** children.put(child.getElementName(), child);
* from helma.framework.IPathElement. Returns the parent object }
* of this instance if assigned.
*/
public IPathElement getParentElement () {
return parent;
}
/**
*
*
* @return ...
*/
public int countChildren() {
return children.size();
}
/** /**
* from helma.framework.IPathElement. Prototypes are assigned like *
* this: "doc" + typename (e.g. docapplication, docprototype etc) *
*/ * @return ...
public java.lang.String getPrototype () { */
return "doc" + typeNames[type].toLowerCase (); public Map getChildren() {
} return children;
}
/**
* returns an array of doc elements, sorted by their name
*/
public DocElement[] listChildren() {
String[] keys = (String[]) children.keySet().toArray(new String[0]);
public String toString () { Arrays.sort(keys);
return "[" + typeNames [type] + " " + name + "]";
}
public static void debug (String msg) { DocElement[] arr = new DocElement[keys.length];
System.out.println(msg);
}
for (int i = 0; i < keys.length; i++) {
arr[i] = (DocElement) children.get(keys[i]);
}
return arr;
}
/**
* walks up the tree and tries to find a DocApplication object
*/
public DocApplication getDocApplication() {
DocElement el = this;
while (el != null) {
if (el instanceof DocApplication) {
return (DocApplication) el;
}
el = (DocElement) el.getParentElement();
}
return null;
}
/**
* from helma.framework.IPathElement. Elements are named
* like this: typename_name
*/
public String getElementName() {
return typeNames[type].toLowerCase() + "_" + name;
}
/**
* from helma.framework.IPathElement. Retrieves a child from the
* children map.
*/
public IPathElement getChildElement(String name) {
try {
return (IPathElement) children.get(name);
} catch (ClassCastException cce) {
debug(cce.toString());
cce.printStackTrace();
return null;
}
}
/**
* from helma.framework.IPathElement. Returns the parent object
* of this instance if assigned.
*/
public IPathElement getParentElement() {
return parent;
}
/**
* from helma.framework.IPathElement. Prototypes are assigned like
* this: "doc" + typename (e.g. docapplication, docprototype etc)
*/
public java.lang.String getPrototype() {
return "doc" + typeNames[type].toLowerCase();
}
/**
*
*
* @return ...
*/
public String toString() {
return "[" + typeNames[type] + " " + name + "]";
}
/**
*
*
* @param msg ...
*/
public static void debug(String msg) {
System.out.println(msg);
}
} }

View file

@ -1,16 +1,43 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
/**
*
*/
public class DocException extends RuntimeException { public class DocException extends RuntimeException {
String str; String str;
public DocException (String str) { /**
super (str); * Creates a new DocException object.
this.str = str; *
* @param str ...
*/
public DocException(String str) {
super(str);
this.str = str;
} }
/**
*
*
* @return ...
*/
public String getMessage() { public String getMessage() {
return str; return str;
} }
} }

View file

@ -1,84 +1,112 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import FESI.Parser.*;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import FESI.Parser.*; /**
*
*/
public abstract class DocFileElement extends DocElement { public abstract class DocFileElement extends DocElement {
protected DocFileElement(String name, File location, int type) {
super(name, location, type);
}
/** /**
* extracts the function name from a file. basically chops the given suffix * extracts the function name from a file. basically chops the given suffix
* and throws an error if the file name doesn't fit. * and throws an error if the file name doesn't fit.
*/ */
static protected String nameFromFile (File f, String suffix) throws DocException { static protected String nameFromFile(File f, String suffix)
String filename = f.getName (); throws DocException {
if (!filename.endsWith (suffix)) String filename = f.getName();
throw new DocException ("file doesn't have suffix " + suffix + ": " + f.toString());
return filename.substring (0, filename.lastIndexOf(suffix));
}
if (!filename.endsWith(suffix)) {
throw new DocException("file doesn't have suffix " + suffix + ": " +
f.toString());
}
/** return filename.substring(0, filename.lastIndexOf(suffix));
* creates fesi token manager for a given file. }
*/
static protected EcmaScriptTokenManager createTokenManager (File f) {
try {
ASCII_CharStream is = new ASCII_CharStream(new FileReader(f), 1, 1);
EcmaScriptTokenManager mgr = new EcmaScriptTokenManager(is,0);
return mgr;
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace ();
throw new DocException (fnfe.toString ());
}
}
/**
* creates fesi token manager for a given file.
*/
static protected EcmaScriptTokenManager createTokenManager(File f) {
try {
ASCII_CharStream is = new ASCII_CharStream(new FileReader(f), 1, 1);
EcmaScriptTokenManager mgr = new EcmaScriptTokenManager(is, 0);
protected DocFileElement (String name, File location, int type) { return mgr;
super (name, location, type); } catch (FileNotFoundException fnfe) {
} fnfe.printStackTrace();
throw new DocException(fnfe.toString());
}
}
/**
* extracts a part of the source code, used to get the code for a
* single function from a function file. sets the field "content".
*/
protected void parseSource(File sourceFile, int beginLine, int beginColumn,
int endLine, int endColumn) {
StringBuffer buf = new StringBuffer();
int ct = 0;
/** try {
* extracts a part of the source code, used to get the code for a BufferedReader in = new BufferedReader(new FileReader(sourceFile));
* single function from a function file. sets the field "content". String line = "";
*/
protected void parseSource (File sourceFile, int beginLine, int beginColumn, int endLine, int endColumn) {
StringBuffer buf = new StringBuffer ();
int ct=0;
try {
BufferedReader in = new BufferedReader (new FileReader (sourceFile));
String line="";
while (line!=null) {
line = in.readLine();
if (line==null) break;
ct++;
if (ct==beginLine)
buf.append (line.substring(beginColumn-1, line.length())+"\n");
else if ( ct>beginLine && ct<endLine )
buf.append (line+"\n");
else if (ct==endLine)
buf.append (line.substring(0,endColumn));
}
} catch (Exception e) {
debug (e.getMessage ());
}
content = buf.toString ();
}
while (line != null) {
line = in.readLine();
/** if (line == null) {
* connects all available specialTokens starting at the given token. break;
*/ }
protected void parseCommentFromToken (Token tok) {
StringBuffer buf = new StringBuffer();
while (tok.specialToken!=null) {
buf.append (tok.specialToken.toString() );
tok = tok.specialToken;
}
parseComment (buf.toString().trim());
}
ct++;
if (ct == beginLine) {
buf.append(line.substring(beginColumn - 1, line.length()) + "\n");
} else if ((ct > beginLine) && (ct < endLine)) {
buf.append(line + "\n");
} else if (ct == endLine) {
buf.append(line.substring(0, endColumn));
}
}
} catch (Exception e) {
debug(e.getMessage());
}
content = buf.toString();
}
/**
* connects all available specialTokens starting at the given token.
*/
protected void parseCommentFromToken(Token tok) {
StringBuffer buf = new StringBuffer();
while (tok.specialToken != null) {
buf.append(tok.specialToken.toString());
tok = tok.specialToken;
}
parseComment(buf.toString().trim());
}
} }

View file

@ -1,154 +1,185 @@
package helma.doc; /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
import java.io.*; package helma.doc;
import java.util.*;
import FESI.Parser.*; import FESI.Parser.*;
import helma.framework.IPathElement; import helma.framework.IPathElement;
import java.io.*;
import java.util.*;
/**
*
*/
public class DocFunction extends DocFileElement { public class DocFunction extends DocFileElement {
protected DocFunction(String name, File location, DocElement parent, int type) {
super(name, location, type);
this.parent = parent;
}
/** /**
* creates a new independent DocFunction object of type ACTION * creates a new independent DocFunction object of type ACTION
*/ */
public static DocFunction newAction (File location) { public static DocFunction newAction(File location) {
return newAction (location, null); return newAction(location, null);
} }
/**
* creates a new DocFunction object of type ACTION connected to another DocElement
*/
public static DocFunction newAction(File location, DocElement parent) {
String name = nameFromFile(location, ".hac");
DocFunction func = new DocFunction(name, location, parent, ACTION);
/** func.parseActionFile();
* creates a new DocFunction object of type ACTION connected to another DocElement
*/
public static DocFunction newAction (File location, DocElement parent) {
String name = nameFromFile (location, ".hac");
DocFunction func = new DocFunction (name, location, parent, ACTION);
func.parseActionFile ();
return func;
}
/** return func;
* creates a new independent DocFunction object of type TEMPLATE }
*/
public static DocFunction newTemplate (File location) {
return newTemplate (location, null);
}
/**
* creates a new independent DocFunction object of type TEMPLATE
*/
public static DocFunction newTemplate(File location) {
return newTemplate(location, null);
}
/** /**
* creates a new DocFunction object of type TEMPLATE connected to another DocElement * creates a new DocFunction object of type TEMPLATE connected to another DocElement
*/ */
public static DocFunction newTemplate (File location, DocElement parent) { public static DocFunction newTemplate(File location, DocElement parent) {
String name = nameFromFile (location, ".hsp"); String name = nameFromFile(location, ".hsp");
DocFunction func = new DocFunction (name, location, parent, TEMPLATE); DocFunction func = new DocFunction(name, location, parent, TEMPLATE);
func.parseTemplateFile ();
return func;
}
func.parseTemplateFile();
/** return func;
* reads a function file and creates independent DocFunction objects of type FUNCTION }
*/
public static DocFunction[] newFunctions (File location) {
return newFunctions (location, null);
}
/**
* reads a function file and creates independent DocFunction objects of type FUNCTION
*/
public static DocFunction[] newFunctions(File location) {
return newFunctions(location, null);
}
/** /**
* reads a function file and creates DocFunction objects of type FUNCTION * reads a function file and creates DocFunction objects of type FUNCTION
* connected to another DocElement. * connected to another DocElement.
*/ */
public static DocFunction[] newFunctions (File location, DocElement parent) { public static DocFunction[] newFunctions(File location, DocElement parent) {
Vector vec = new Vector (); Vector vec = new Vector();
EcmaScriptTokenManager mgr = createTokenManager(location); EcmaScriptTokenManager mgr = createTokenManager(location);
Token tok = mgr.getNextToken(); Token tok = mgr.getNextToken();
while (tok.kind!=0) {
if (tok.kind == EcmaScriptConstants.FUNCTION) {
// store the start position of the function:
int beginLine = tok.beginLine;
int beginColumn = tok.beginColumn;
// the name is stored in the next token:
String funcName = mgr.getNextToken().toString();
// create the function object
DocFunction func;
if (funcName.endsWith("_action"))
func = new DocFunction (funcName, location, parent, ACTION);
else if (funcName.endsWith("_macro"))
func = new DocFunction (funcName, location, parent, MACRO);
else
func = new DocFunction (funcName, location, parent, FUNCTION);
// parse the comment from the special token(s) before this token:
func.parseCommentFromToken (tok);
// find the parameters of this function, but only if it's
// neither macro nor action:
if (func.type==FUNCTION) {
while (tok.kind!=0 && tok.kind!=EcmaScriptConstants.RPAREN) {
if (tok.kind==EcmaScriptConstants.IDENTIFIER) {
func.addParameter (tok.image);
}
tok = mgr.getNextToken ();
}
} else {
tok = mgr.getNextToken ();
}
// now find the end of the function:
int endLine=0, endColumn=0;
while (tok.kind!=0 && tok.kind!=EcmaScriptConstants.FUNCTION) {
endLine = tok.endLine;
endColumn = tok.endColumn;
tok = mgr.getNextToken ();
}
// now we know the exact position of the function in the file,
// re-read it and extract the source code:
func.parseSource (location, beginLine, beginColumn, endLine, endColumn);
vec.add (func);
}
if (tok.kind != EcmaScriptConstants.FUNCTION) {
tok = mgr.getNextToken();
}
}
return (DocFunction[]) vec.toArray (new DocFunction[0]);
}
protected DocFunction (String name, File location, DocElement parent, int type) { while (tok.kind != 0) {
super (name, location, type); if (tok.kind == EcmaScriptConstants.FUNCTION) {
this.parent = parent; // store the start position of the function:
} int beginLine = tok.beginLine;
int beginColumn = tok.beginColumn;
// the name is stored in the next token:
String funcName = mgr.getNextToken().toString();
/** // create the function object
* reads the content of a .hac file and parses the comment before the first DocFunction func;
* javascript element
*/
private void parseActionFile () {
EcmaScriptTokenManager mgr = createTokenManager(location);
Token tok = mgr.getNextToken();
parseCommentFromToken (tok);
content = readFile (location);
}
if (funcName.endsWith("_action")) {
func = new DocFunction(funcName, location, parent, ACTION);
} else if (funcName.endsWith("_macro")) {
func = new DocFunction(funcName, location, parent, MACRO);
} else {
func = new DocFunction(funcName, location, parent, FUNCTION);
}
/** // parse the comment from the special token(s) before this token:
* reads the content of a .hsp file and parses the comment before the first func.parseCommentFromToken(tok);
* javascript element (only if file starts with &gt;%-tag!).
*/
private void parseTemplateFile () {
content = readFile (location);
StringReader str = new StringReader (content.substring (content.indexOf("<%") + 2, content.indexOf ("%>")));
ASCII_CharStream ascii = new ASCII_CharStream (str,1,1);
EcmaScriptTokenManager mgr = new EcmaScriptTokenManager (ascii);
Token tok = mgr.getNextToken();
parseCommentFromToken (tok);
}
// find the parameters of this function, but only if it's
// neither macro nor action:
if (func.type == FUNCTION) {
while ((tok.kind != 0) && (tok.kind != EcmaScriptConstants.RPAREN)) {
if (tok.kind == EcmaScriptConstants.IDENTIFIER) {
func.addParameter(tok.image);
}
/** tok = mgr.getNextToken();
* from helma.framework.IPathElement. All macros, templates, actions etc }
* have the same prototype. } else {
*/ tok = mgr.getNextToken();
public java.lang.String getPrototype () { }
return "docfunction";
}
// now find the end of the function:
int endLine = 0;
// now find the end of the function:
int endColumn = 0;
while ((tok.kind != 0) && (tok.kind != EcmaScriptConstants.FUNCTION)) {
endLine = tok.endLine;
endColumn = tok.endColumn;
tok = mgr.getNextToken();
}
// now we know the exact position of the function in the file,
// re-read it and extract the source code:
func.parseSource(location, beginLine, beginColumn, endLine, endColumn);
vec.add(func);
}
if (tok.kind != EcmaScriptConstants.FUNCTION) {
tok = mgr.getNextToken();
}
}
return (DocFunction[]) vec.toArray(new DocFunction[0]);
}
/**
* reads the content of a .hac file and parses the comment before the first
* javascript element
*/
private void parseActionFile() {
EcmaScriptTokenManager mgr = createTokenManager(location);
Token tok = mgr.getNextToken();
parseCommentFromToken(tok);
content = readFile(location);
}
/**
* reads the content of a .hsp file and parses the comment before the first
* javascript element (only if file starts with &gt;%-tag!).
*/
private void parseTemplateFile() {
content = readFile(location);
StringReader str = new StringReader(content.substring(content.indexOf("<%") + 2,
content.indexOf("%>")));
ASCII_CharStream ascii = new ASCII_CharStream(str, 1, 1);
EcmaScriptTokenManager mgr = new EcmaScriptTokenManager(ascii);
Token tok = mgr.getNextToken();
parseCommentFromToken(tok);
}
/**
* from helma.framework.IPathElement. All macros, templates, actions etc
* have the same prototype.
*/
public java.lang.String getPrototype() {
return "docfunction";
}
} }

View file

@ -1,3 +1,19 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import helma.framework.IPathElement; import helma.framework.IPathElement;
@ -5,59 +21,76 @@ import helma.util.SystemProperties;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
public class DocProperties extends DocFileElement { /**
*
*/
public class DocProperties extends DocFileElement {
Properties props = null;
Properties props = null; protected DocProperties(File location, DocElement parent)
throws DocException {
super(location.getName(), location, PROPERTIES);
this.parent = parent;
content = readFile(location);
props = new SystemProperties();
/** try {
* creates a new independent DocProperties object props.load(new FileInputStream(location));
*/ } catch (IOException e) {
public static DocProperties newInstance (File location) { debug("couldn't read file: " + e.toString());
return newInstance (location, null); } catch (Exception e) {
} throw new DocException(e.toString());
}
}
/** /**
* creates a new DocProperties object connected to another DocElement * creates a new independent DocProperties object
*/ */
public static DocProperties newInstance (File location, DocElement parent) { public static DocProperties newInstance(File location) {
try { return newInstance(location, null);
return new DocProperties (location, parent); }
} catch (DocException doc) {
return null;
}
}
protected DocProperties (File location, DocElement parent) throws DocException { /**
super (location.getName (), location, PROPERTIES); * creates a new DocProperties object connected to another DocElement
this.parent = parent; */
content = readFile (location); public static DocProperties newInstance(File location, DocElement parent) {
props = new SystemProperties (); try {
try { return new DocProperties(location, parent);
props.load (new FileInputStream (location)); } catch (DocException doc) {
} catch (IOException e) { return null;
debug ("couldn't read file: " + e.toString ()); }
} catch (Exception e) { }
throw new DocException (e.toString ());
}
}
public Properties getProperties () { /**
return props; *
} *
* @return ...
*/
public Properties getProperties() {
return props;
}
public Properties getMappings () { /**
Properties childProps = new Properties (); *
for (Enumeration e = props.keys (); e.hasMoreElements (); ) { *
String key = (String) e.nextElement (); * @return ...
String value = props.getProperty (key); */
if (value.startsWith ("collection") || value.startsWith ("object") || value.startsWith ("mountpoint")) { public Properties getMappings() {
String prototype = value.substring (value.indexOf("(")+1, value.indexOf(")")).trim (); Properties childProps = new Properties();
childProps.setProperty (key, prototype);
}
} for (Enumeration e = props.keys(); e.hasMoreElements();) {
return childProps; String key = (String) e.nextElement();
} String value = props.getProperty(key);
if (value.startsWith("collection") || value.startsWith("object") ||
value.startsWith("mountpoint")) {
String prototype = value.substring(value.indexOf("(") + 1,
value.indexOf(")")).trim();
childProps.setProperty(key, prototype);
}
}
return childProps;
}
} }

View file

@ -1,110 +1,150 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import FESI.Parser.*;
import helma.framework.IPathElement; import helma.framework.IPathElement;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import FESI.Parser.*;
/**
*
*/
public class DocPrototype extends DocDirElement {
private DocProperties typeProperties = null;
private DocPrototype parentPrototype = null;
public class DocPrototype extends DocDirElement { private DocPrototype(String name, File location, DocElement parent) {
super(name, location, PROTOTYPE);
this.parent = parent;
typeProperties = DocProperties.newInstance(new File(location, "type.properties"));
}
private DocProperties typeProperties = null; /**
private DocPrototype parentPrototype = null; * creates a prototype that is independent of an
* application object
* @param homedirectory
*/
public static DocPrototype newInstance(File location) {
return newInstance(location, null);
}
/** /**
* creates a prototype that is independent of an * creates a prototype that is connected to an
* application object * application object and resides in app's home dir.
* @param homedirectory * @param application
*/ * @param name
public static DocPrototype newInstance (File location) { */
return newInstance (location, null); public static DocPrototype newInstance(File location, DocElement parent) {
} DocPrototype pt = new DocPrototype(location.getName(), location, parent);
/** return pt;
* creates a prototype that is connected to an }
* application object and resides in app's home dir.
* @param application
* @param name
*/
public static DocPrototype newInstance (File location, DocElement parent) {
DocPrototype pt = new DocPrototype (location.getName (), location, parent);
return pt;
}
private DocPrototype (String name, File location, DocElement parent) { /**
super (name, location, PROTOTYPE); * checks the type.properites for _extend values and connected a possible
this.parent = parent; * parent prototype with this prototype. this can't be successfull at construction
typeProperties = DocProperties.newInstance (new File (location, "type.properties")); * time but only -after- all prototypes are parsed and attached to a parent
} * DocApplication object.
*/
public void checkInheritance() {
// hopobject is the top prototype:
if (name.equals("hopobject")) {
return;
}
if (typeProperties != null) {
// check for "_extends" in the the type.properties
String ext = typeProperties.getProperties().getProperty("_extends");
/** if ((ext != null) && (parent != null)) {
* checks the type.properites for _extend values and connected a possible // try to get the prototype if available
* parent prototype with this prototype. this can't be successfull at construction parentPrototype = (DocPrototype) parent.getChildElement("prototype_" +
* time but only -after- all prototypes are parsed and attached to a parent ext);
* DocApplication object. }
*/ }
public void checkInheritance () {
// hopobject is the top prototype:
if (name.equals("hopobject"))
return;
if (typeProperties!=null) {
// check for "_extends" in the the type.properties
String ext = typeProperties.getProperties ().getProperty ("_extends");
if (ext!=null && parent!=null) {
// try to get the prototype if available
parentPrototype = (DocPrototype) parent.getChildElement ("prototype_" + ext);
}
}
if (parentPrototype==null && parent!=null && !name.equals("global")) {
// if no _extend was set, get the hopobject prototype
parentPrototype = (DocPrototype) parent.getChildElement ("prototype_hopobject");
}
}
public DocPrototype getParentPrototype () { if ((parentPrototype == null) && (parent != null) && !name.equals("global")) {
return parentPrototype; // if no _extend was set, get the hopobject prototype
} parentPrototype = (DocPrototype) parent.getChildElement("prototype_hopobject");
}
}
/**
*
*
* @return ...
*/
public DocPrototype getParentPrototype() {
return parentPrototype;
}
public DocProperties getTypeProperties () { /**
return typeProperties; *
} *
* @return ...
*/
public DocProperties getTypeProperties() {
return typeProperties;
}
/**
* runs through the prototype directory and parses all helma files
*/
public void readFiles() {
children.clear();
/** String[] arr = location.list();
* runs through the prototype directory and parses all helma files
*/
public void readFiles () {
children.clear ();
String arr[] = location.list ();
for (int i=0; i<arr.length; i++) {
if (Util.isExcluded (arr[i]))
continue;
File f = new File (location.getAbsolutePath (), arr[i]);
if (f.isDirectory ())
continue;
try {
if (arr[i].endsWith (".skin")) {
addChild (DocSkin.newInstance (f, this));
} else if (arr[i].endsWith (".properties")) {
continue;
} else if (arr[i].endsWith (".hac")) {
addChild (DocFunction.newAction (f, this));
} else if (arr[i].endsWith (".hsp")) {
addChild (DocFunction.newTemplate (f, this));
} else if (arr[i].endsWith (".js")) {
DocElement[] elements = DocFunction.newFunctions (f, this);
for (int j=0; j<elements.length; j++) {
addChild (elements[j]);
}
}
} catch (Exception ex) {
System.out.println ("couldn't parse file " + f.getAbsolutePath () + ": " + ex.toString ());
ex.printStackTrace ();
}
}
}
for (int i = 0; i < arr.length; i++) {
if (getDocApplication().isExcluded(arr[i])) {
continue;
}
File f = new File(location.getAbsolutePath(), arr[i]);
if (f.isDirectory()) {
continue;
}
try {
if (arr[i].endsWith(".skin")) {
addChild(DocSkin.newInstance(f, this));
} else if (arr[i].endsWith(".properties")) {
continue;
} else if (arr[i].endsWith(".hac")) {
addChild(DocFunction.newAction(f, this));
} else if (arr[i].endsWith(".hsp")) {
addChild(DocFunction.newTemplate(f, this));
} else if (arr[i].endsWith(".js")) {
DocElement[] elements = DocFunction.newFunctions(f, this);
for (int j = 0; j < elements.length; j++) {
addChild(elements[j]);
}
}
} catch (Exception ex) {
System.out.println("couldn't parse file " + f.getAbsolutePath() + ": " +
ex.toString());
ex.printStackTrace();
} catch (FESI.Parser.TokenMgrError err) {
System.out.println("couldn't parse file " + f.getAbsolutePath() + ": " +
err.toString());
}
}
}
} }

View file

@ -1,87 +1,118 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import helma.framework.IPathElement; import helma.framework.IPathElement;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
public class DocSkin extends DocFileElement { /**
*
*/
public class DocSkin extends DocFileElement {
protected DocSkin(String name, File location, DocElement parent) {
super(name, location, SKIN);
this.parent = parent;
content = readFile(location);
parseHandlers();
}
/** /**
* creates a new independent DocSkin object * creates a new independent DocSkin object
*/ */
public static DocSkin newInstance (File location) { public static DocSkin newInstance(File location) {
return newInstance (location, null); return newInstance(location, null);
} }
/** /**
* creates a new DocSkin object connected to another DocElement * creates a new DocSkin object connected to another DocElement
*/ */
public static DocSkin newInstance (File location, DocElement parent) { public static DocSkin newInstance(File location, DocElement parent) {
String skinname = nameFromFile (location, ".skin"); String skinname = nameFromFile(location, ".skin");
DocSkin skin = new DocSkin (skinname, location, parent); DocSkin skin = new DocSkin(skinname, location, parent);
return skin;
}
protected DocSkin (String name, File location, DocElement parent) { return skin;
super (name, location, SKIN); }
this.parent = parent;
content = readFile (location);
parseHandlers ();
}
/**
* parses the source code of the skin and
* extracts all included macros. code taken
* from helma.framework.core.Skin
* @see helma.framework.core.Skin
*/
private void parseHandlers() {
ArrayList partBuffer = new ArrayList();
char[] source = content.toCharArray();
int sourceLength = source.length;
int start = 0;
/** for (int i = 0; i < (sourceLength - 1); i++) {
* parses the source code of the skin and if ((source[i] == '<') && (source[i + 1] == '%')) {
* extracts all included macros. code taken // found macro start tag
* from helma.framework.core.Skin int j = i + 2;
* @see helma.framework.core.Skin
*/
private void parseHandlers () {
ArrayList partBuffer = new ArrayList ();
char[] source = content.toCharArray ();
int sourceLength = source.length;
int start = 0;
for (int i = 0; i < sourceLength-1; i++) {
if (source[i] == '<' && source[i+1] == '%') {
// found macro start tag
int j = i+2;
// search macro end tag
while (j < sourceLength-1 && (source[j] != '%' || source[j+1] != '>')) {
j++;
}
if (j > i+2) {
String str = (new String (source, i+2, j-i)).trim ();
if (str.endsWith("%>"))
str = str.substring (0, str.length()-2);
if (str.indexOf (" ")>-1)
str = str.substring (0, str.indexOf(" "));
if (str.indexOf(".")>-1 &&
(str.startsWith ("param.")
|| str.startsWith ("response.")
|| str.startsWith("request.")
|| str.startsWith ("session.")
) && !partBuffer.contains(str)) {
partBuffer.add (str);
}
start = j+2;
}
i = j+1;
}
}
String[] strArr = (String[]) partBuffer.toArray (new String [0]);
Arrays.sort (strArr);
for (int i=0; i<strArr.length; i++) {
addParameter (strArr[i]);
}
}
/** // search macro end tag
* from helma.framework.IPathElement. Use the same prototype as functions etc. while ((j < (sourceLength - 1)) &&
*/ ((source[j] != '%') || (source[j + 1] != '>'))) {
public java.lang.String getPrototype () { j++;
return "docfunction"; }
}
if (j > (i + 2)) {
String str = (new String(source, i + 2, j - i)).trim();
if (str.endsWith("%>")) {
str = str.substring(0, str.length() - 2);
}
if (str.startsWith("//")) {
parseComment(str);
} else {
if (str.indexOf(" ") > -1) {
str = str.substring(0, str.indexOf(" "));
}
if ((str.indexOf(".") > -1) &&
(str.startsWith("param.") || str.startsWith("response.") ||
str.startsWith("request.") || str.startsWith("session.")) &&
!partBuffer.contains(str)) {
partBuffer.add(str);
}
}
start = j + 2;
}
i = j + 1;
}
}
String[] strArr = (String[]) partBuffer.toArray(new String[0]);
Arrays.sort(strArr);
for (int i = 0; i < strArr.length; i++) {
addParameter(strArr[i]);
}
}
/**
* from helma.framework.IPathElement. Use the same prototype as functions etc.
*/
public java.lang.String getPrototype() {
return "docfunction";
}
} }

View file

@ -1,108 +1,176 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import java.util.*; import java.util.*;
public final class DocTag { /**
*
*/
public final class DocTag {
// for public use we have less types than
// internally. eg, we're combining "return" and "returns"
// or "arg" and "param".
// the values here have to match the index of
// the tags-array!
public static final int PARAMETER = 0;
public static final int RETURN = 2;
public static final int AUTHOR = 4;
public static final int VERSION = 5;
public static final int SEE = 6;
public static final int DEPRECATED = 7;
public static final int OVERRIDES = 8;
public static final String[][] tags = {
{ "@arg", "Argument" },
{ "@param", "Parameter" },
{ "@return", "Returns" },
{ "@returns", "Returns" },
{ "@author", "Author" },
{ "@version", "Version" },
{ "@see", "See also" },
{ "@deprecated", "Deprecated" },
{ "@overrides", "Overrides" }
};
private String name;
// for public use we have less types than // "kind" is for internal use, "type" is external
// internally. eg, we're combining "return" and "returns" private int kind;
// or "arg" and "param". private String text;
// the values here have to match the index of
// the tags-array!
public static final int PARAMETER = 0;
public static final int RETURN = 2;
public static final int AUTHOR = 4;
public static final int VERSION = 5;
public static final int SEE = 6;
public static final int DEPRECATED = 7;
public static final int OVERRIDES = 8;
public static final String[][] tags = { private DocTag(int kind, String name, String text) {
{"@arg","Argument"}, this.kind = kind;
{"@param","Parameter"}, this.name = (name != null) ? name : "";
{"@return","Returns"}, this.text = (text != null) ? text : "";
{"@returns","Returns"}, }
{"@author","Author"},
{"@version","Version"},
{"@see","See also"},
{"@deprecated", "Deprecated"},
{"@overrides", "Overrides"}
};
private String name; /**
// "kind" is for internal use, "type" is external *
private int kind; *
private String text; * @param rawTag ...
*
* @return ...
*/
public static boolean isTagStart(String rawTag) {
if (getTagNumber(rawTag) > -1) {
return true;
} else {
return false;
}
}
public static boolean isTagStart (String rawTag) { /**
if (getTagNumber(rawTag) > -1) *
return true; *
else * @param rawTag ...
return false; *
} * @return ...
*
* @throws DocException ...
*/
public static DocTag parse(String rawTag) throws DocException {
int kind = getTagNumber(rawTag);
public static DocTag parse (String rawTag) throws DocException { if (kind == -1) {
int kind = getTagNumber (rawTag); throw new DocException("unsupported tag type: " + rawTag);
if (kind == -1) }
throw new DocException ("unsupported tag type: " + rawTag);
String content = rawTag.substring (tags[kind][0].length ()+1).trim ();
if (kind == 0 || kind==1) {
StringTokenizer tok = new StringTokenizer (content);
String name = "";
if (tok.hasMoreTokens ())
name = tok.nextToken ();
String comment = "";
try {
comment = content.substring (name.length ()+1).trim ();
} catch (StringIndexOutOfBoundsException e) { }
return new DocTag (kind, name, comment);
} else {
return new DocTag (kind, "", content);
}
}
private static int getTagNumber (String rawTag) { String content = rawTag.substring(tags[kind][0].length() + 1).trim();
rawTag = rawTag.trim ().toLowerCase ();
for (int i=0; i<tags.length; i++) {
if (rawTag.startsWith (tags[i][0])) {
return i;
}
}
return -1;
}
if ((kind == 0) || (kind == 1)) {
StringTokenizer tok = new StringTokenizer(content);
String name = "";
private DocTag (int kind, String name, String text) { if (tok.hasMoreTokens()) {
this.kind = kind; name = tok.nextToken();
this.name = (name!=null) ? name : ""; }
this.text = (text!=null) ? text : "";
}
public String getName () { String comment = "";
return name;
}
public int getType () { try {
if (kind==0 || kind==1) comment = content.substring(name.length() + 1).trim();
return PARAMETER; } catch (StringIndexOutOfBoundsException e) {
else if (kind==2 || kind==3) }
return RETURN;
else
return kind;
}
return new DocTag(kind, name, comment);
} else {
return new DocTag(kind, "", content);
}
}
public String getTag () { private static int getTagNumber(String rawTag) {
return tags[kind][0]; rawTag = rawTag.trim().toLowerCase();
}
public String getText () { for (int i = 0; i < tags.length; i++) {
return text; if (rawTag.startsWith(tags[i][0])) {
} return i;
}
}
public String toString() { return -1;
return tags [kind][1] + ": " + name + " " + text; }
}
/**
*
*
* @return ...
*/
public String getName() {
return name;
}
/**
*
*
* @return ...
*/
public int getType() {
if ((kind == 0) || (kind == 1)) {
return PARAMETER;
} else if ((kind == 2) || (kind == 3)) {
return RETURN;
} else {
return kind;
}
}
/**
*
*
* @return ...
*/
public String getTag() {
return tags[kind][0];
}
/**
*
*
* @return ...
*/
public String getText() {
return text;
}
/**
*
*
* @return ...
*/
public String toString() {
return tags[kind][1] + ": " + name + " " + text;
}
} }

View file

@ -1,40 +1,50 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.doc; package helma.doc;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
/**
*
*/
public final class Util { public final class Util {
/**
static Vector excluded = new Vector (); *
*
public static void addExlude (String str) { * @param line ...
excluded.add (str.toLowerCase ()); *
} * @return ...
*/
public static boolean isExcluded (String str) { public static String chopDelimiters(String line) {
if (excluded.size ()==0) { if (line == null) {
excluded.add ("cvs"); return null;
excluded.add (".docs"); } else if (line.startsWith("/**")) {
} return line.substring(3).trim();
return (excluded.contains (str.toLowerCase ())); } else if (line.startsWith("/*")) {
} return line.substring(2).trim();
} else if (line.endsWith("*/")) {
public static String chopDelimiters (String line) { return line.substring(0, line.length() - 2);
if (line==null) } else if (line.startsWith("*")) {
return null; return line.substring(1).trim();
else if (line.startsWith("/**")) } else if (line.startsWith("//")) {
return line.substring (3).trim (); return line.substring(2).trim();
else if (line.startsWith("/*")) } else {
return line.substring (2).trim (); return line;
else if (line.endsWith ("*/")) }
return line.substring (0, line.length ()-2); }
else if (line.startsWith("*"))
return line.substring (1).trim ();
else if (line.startsWith("//"))
return line.substring (2).trim ();
else
return line;
}
} }

View file

@ -1,9 +1,31 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.extensions; package helma.extensions;
/**
*
*/
public class ConfigurationException extends RuntimeException { public class ConfigurationException extends RuntimeException {
/**
public ConfigurationException (String msg) { * Creates a new ConfigurationException object.
super (msg); *
* @param msg ...
*/
public ConfigurationException(String msg) {
super(msg);
} }
} }

View file

@ -1,53 +1,71 @@
package helma.extensions; /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
import java.util.HashMap; package helma.extensions;
import helma.framework.core.Application; import helma.framework.core.Application;
import helma.main.Server; import helma.main.Server;
import helma.scripting.ScriptingEngine; import helma.scripting.ScriptingEngine;
import java.util.HashMap;
/** /**
* Helma extensions have to subclass this. The extensions to be loaded are * Helma extensions have to subclass this. The extensions to be loaded are
* defined in <code>server.properties</code> by setting <code>extensions = * defined in <code>server.properties</code> by setting <code>extensions =
* packagename.classname, packagename.classname</code>. * packagename.classname, packagename.classname</code>.
*/ */
public abstract class HelmaExtension { public abstract class HelmaExtension {
/**
* called by the Server at startup time. should check wheter the needed classes
* are present and throw a ConfigurationException if not.
*/
public abstract void init(Server server) throws ConfigurationException;
/** /**
* called by the Server at startup time. should check wheter the needed classes * called when an Application is started. This should be <b>synchronized</b> when
* are present and throw a ConfigurationException if not. * any self-initialization is performed.
*/ */
public abstract void init (Server server) throws ConfigurationException; public abstract void applicationStarted(Application app)
throws ConfigurationException;
/** /**
* called when an Application is started. This should be <b>synchronized</b> when * called when an Application is stopped.
* any self-initialization is performed. * This should be <b>synchronized</b> when any self-destruction is performed.
*/ */
public abstract void applicationStarted (Application app) throws ConfigurationException; public abstract void applicationStopped(Application app);
/** /**
* called when an Application is stopped. * called when an Application's properties are have been updated.
* This should be <b>synchronized</b> when any self-destruction is performed. * note that this will be called at startup once *before* applicationStarted().
*/ */
public abstract void applicationStopped (Application app); public abstract void applicationUpdated(Application app);
/** /**
* called when an Application's properties are have been updated. * called by the ScriptingEngine when it is initizalized. Throws a ConfigurationException
* note that this will be called at startup once *before* applicationStarted(). * when this type of ScriptingEngine is not supported. New methods and prototypes can be
*/ * added to the scripting environment. New global vars should be returned in a HashMap
public abstract void applicationUpdated (Application app); * with pairs of varname and ESObjects. This method should be <b>synchronized</b>, if it
* performs any other self-initialization outside the scripting environment.
/** */
* called by the ScriptingEngine when it is initizalized. Throws a ConfigurationException public abstract HashMap initScripting(Application app, ScriptingEngine engine)
* when this type of ScriptingEngine is not supported. New methods and prototypes can be throws ConfigurationException;
* added to the scripting environment. New global vars should be returned in a HashMap
* with pairs of varname and ESObjects. This method should be <b>synchronized</b>, if it
* performs any other self-initialization outside the scripting environment.
*/
public abstract HashMap initScripting (Application app, ScriptingEngine engine) throws ConfigurationException;
public abstract String getName ();
/**
*
*
* @return ...
*/
public abstract String getName();
} }

View file

@ -1,12 +1,21 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.extensions.demo; package helma.extensions.demo;
import java.util.HashMap;
import helma.extensions.HelmaExtension;
import helma.extensions.ConfigurationException;
import helma.framework.core.Application;
import helma.main.Server;
import helma.scripting.ScriptingEngine;
// fesi-related stuff: // fesi-related stuff:
import FESI.Data.ESObject; import FESI.Data.ESObject;
@ -14,55 +23,104 @@ import FESI.Data.ESWrapper;
import FESI.Data.GlobalObject; import FESI.Data.GlobalObject;
import FESI.Exceptions.EcmaScriptException; import FESI.Exceptions.EcmaScriptException;
import FESI.Interpreter.Evaluator; import FESI.Interpreter.Evaluator;
import helma.extensions.ConfigurationException;
import helma.extensions.HelmaExtension;
import helma.framework.core.Application;
import helma.main.Server;
import helma.scripting.ScriptingEngine;
import helma.scripting.fesi.FesiEngine; import helma.scripting.fesi.FesiEngine;
import java.util.HashMap;
/** /**
* a demo extension implementation, to activate this add <code>extensions = * a demo extension implementation, to activate this add <code>extensions =
* helma.extensions.demo.DemoExtensions</code> to your <code>server.properties</code>. * helma.extensions.demo.DemoExtensions</code> to your <code>server.properties</code>.
* a new global object <code>demo</code> that wraps helma.main.Server * a new global object <code>demo</code> that wraps helma.main.Server
* will be added to the scripting environment. * will be added to the scripting environment.
*/ */
public class DemoExtension extends HelmaExtension { public class DemoExtension extends HelmaExtension {
/**
*
*
* @param server ...
*
* @throws ConfigurationException ...
*/
public void init(Server server) throws ConfigurationException {
try {
// just a demo with the server class itself (which is always there, obviously)
Class check = Class.forName("helma.main.Server");
} catch (ClassNotFoundException e) {
throw new ConfigurationException("helma-library not present in classpath. make sure helma.jar is included. get it from http://www.helma.org/");
}
}
public void init (Server server) throws ConfigurationException { /**
try { *
// just a demo with the server class itself (which is always there, obviously) *
Class check = Class.forName("helma.main.Server"); * @param app ...
} catch (ClassNotFoundException e) { *
throw new ConfigurationException("helma-library not present in classpath. make sure helma.jar is included. get it from http://www.helma.org/"); * @throws ConfigurationException ...
} */
} public void applicationStarted(Application app) throws ConfigurationException {
app.logEvent("DemoExtension init with app " + app.getName());
}
public void applicationStarted (Application app) throws ConfigurationException { /**
app.logEvent ("DemoExtension init with app " + app.getName () ); *
} *
* @param app ...
*/
public void applicationStopped(Application app) {
app.logEvent("DemoExtension stopped on app " + app.getName());
}
public void applicationStopped (Application app) { /**
app.logEvent ("DemoExtension stopped on app " + app.getName () ); *
} *
* @param app ...
*/
public void applicationUpdated(Application app) {
app.logEvent("DemoExtension updated on app " + app.getName());
}
public void applicationUpdated (Application app) { /**
app.logEvent ("DemoExtension updated on app " + app.getName () ); *
} *
* @param app ...
* @param engine ...
*
* @return ...
*
* @throws ConfigurationException ...
*/
public HashMap initScripting(Application app, ScriptingEngine engine)
throws ConfigurationException {
if (!(engine instanceof FesiEngine)) {
throw new ConfigurationException("scripting engine " + engine.toString() +
" not supported in DemoExtension");
}
public HashMap initScripting (Application app, ScriptingEngine engine) throws ConfigurationException { app.logEvent("initScripting DemoExtension with " + app.getName() + " and " +
if (!(engine instanceof FesiEngine)) engine.toString());
throw new ConfigurationException ("scripting engine " + engine.toString () + " not supported in DemoExtension");
app.logEvent("initScripting DemoExtension with " + app.getName () + " and " + engine.toString() );
// fesi-specific code:
Evaluator evaluator = ((FesiEngine)engine).getEvaluator ();
// initialize prototypes and global vars here, but don't add them to fesi's global object
ESWrapper demo = new ESWrapper(Server.getServer (), evaluator);
HashMap globals = new HashMap ();
globals.put ("demo",demo);
return globals;
}
public String getName () { // fesi-specific code:
return "DemoExtension"; Evaluator evaluator = ((FesiEngine) engine).getEvaluator();
}
// initialize prototypes and global vars here, but don't add them to fesi's global object
ESWrapper demo = new ESWrapper(Server.getServer(), evaluator);
HashMap globals = new HashMap();
globals.put("demo", demo);
return globals;
}
/**
*
*
* @return ...
*/
public String getName() {
return "DemoExtension";
}
} }

View file

@ -1,19 +1,31 @@
// ApplicationStoppedException.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
/** /**
* This is thrown when a request is made to a stopped * This is thrown when a request is made to a stopped
* application * application
*/ */
public class ApplicationStoppedException extends RuntimeException { public class ApplicationStoppedException extends RuntimeException {
/**
* Creates a new ApplicationStoppedException object.
public ApplicationStoppedException () { */
super ("The application has been stopped"); public ApplicationStoppedException() {
super("The application has been stopped");
} }
} }

View file

@ -1,4 +1,18 @@
// CookieTrans.java /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
@ -11,64 +25,106 @@ import javax.servlet.http.Cookie;
* of an HTTP cookie. * of an HTTP cookie.
*/ */
public final class CookieTrans implements Serializable { public final class CookieTrans implements Serializable {
String name;
String name, value, path, domain; String value;
String path;
String domain;
int days; int days;
CookieTrans (String name, String value) { CookieTrans(String name, String value) {
this.name = name; this.name = name;
this.value = value; this.value = value;
} }
void setValue (String value) { void setValue(String value) {
this.value = value; this.value = value;
} }
void setDays (int days) { void setDays(int days) {
this.days = days; this.days = days;
} }
void setPath (String path) { void setPath(String path) {
this.path = path; this.path = path;
} }
void setDomain (String domain) { void setDomain(String domain) {
this.domain = domain; this.domain = domain;
} }
/**
*
*
* @return ...
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
*
*
* @return ...
*/
public String getValue() { public String getValue() {
return value; return value;
} }
/**
*
*
* @return ...
*/
public int getDays() { public int getDays() {
return days; return days;
} }
public String getPath () { /**
return path; *
*
* @return ...
*/
public String getPath() {
return path;
} }
public String getDomain () { /**
return domain; *
*
* @return ...
*/
public String getDomain() {
return domain;
} }
public Cookie getCookie (String defaultPath, String defaultDomain) { /**
Cookie c = new Cookie (name, value); *
if (days > 0) *
// Cookie time to live, days -> seconds * @param defaultPath ...
c.setMaxAge (days*60*60*24); * @param defaultDomain ...
if (path != null) *
c.setPath (path); * @return ...
else if (defaultPath != null) */
c.setPath (defaultPath); public Cookie getCookie(String defaultPath, String defaultDomain) {
if (domain != null) Cookie c = new Cookie(name, value);
c.setDomain (domain);
else if (defaultDomain != null) if (days > 0) {
c.setDomain (defaultDomain); // Cookie time to live, days -> seconds
return c; c.setMaxAge(days * 60 * 60 * 24);
}
if (path != null) {
c.setPath(path);
} else if (defaultPath != null) {
c.setPath(defaultPath);
}
if (domain != null) {
c.setDomain(domain);
} else if (defaultDomain != null) {
c.setDomain(defaultDomain);
}
return c;
} }
} }

View file

@ -1,17 +1,33 @@
// FrameworkException.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
/** /**
* The basic exception class used to tell when certain things go * The basic exception class used to tell when certain things go
* wrong in evaluation of requests. * wrong in evaluation of requests.
*/ */
public class FrameworkException extends RuntimeException { public class FrameworkException extends RuntimeException {
/**
public FrameworkException (String msg) { * Creates a new FrameworkException object.
super (msg); *
* @param msg ...
*/
public FrameworkException(String msg) {
super(msg);
} }
} }

View file

@ -1,5 +1,18 @@
// IPathElement.java /*
// Copyright (c) Hannes Wallnöfer 2001 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
@ -14,34 +27,26 @@ package helma.framework;
* parent element. <p> * parent element. <p>
* *
*/ */
public interface IPathElement { public interface IPathElement {
/** /**
* Return the name to be used to get this element from its parent * Return the name to be used to get this element from its parent
*/ */
public String getElementName (); public String getElementName();
/** /**
* Retrieve a child element of this object by name. * Retrieve a child element of this object by name.
*/ */
public IPathElement getChildElement (String name); public IPathElement getChildElement(String name);
/** /**
* Return the parent element of this object. * Return the parent element of this object.
*/ */
public IPathElement getParentElement (); public IPathElement getParentElement();
/** /**
* Get the name of the prototype to be used for this object. This will * Get the name of the prototype to be used for this object. This will
* determine which scripts, actions and skins can be called on it * determine which scripts, actions and skins can be called on it
* within the Helma scripting and rendering framework. * within the Helma scripting and rendering framework.
*/ */
public String getPrototype (); public String getPrototype();
} }

View file

@ -1,5 +1,18 @@
// IRemoteApp.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
@ -9,11 +22,22 @@ import java.util.Vector;
/** /**
* RMI interface for an application. Currently only execute is used and supported. * RMI interface for an application. Currently only execute is used and supported.
*/ */
public interface IRemoteApp extends Remote { public interface IRemoteApp extends Remote {
/**
*
*
* @param param ...
*
* @return ...
*
* @throws RemoteException ...
*/
public ResponseTrans execute(RequestTrans param) throws RemoteException;
public ResponseTrans execute (RequestTrans param) throws RemoteException; /**
*
public void ping () throws RemoteException; *
* @throws RemoteException ...
} */
public void ping() throws RemoteException;
}

View file

@ -1,5 +1,18 @@
// RedirectException.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
@ -8,26 +21,43 @@ package helma.framework;
* RedirectException is thrown internally when a response is redirected to a * RedirectException is thrown internally when a response is redirected to a
* new URL. * new URL.
*/ */
public class RedirectException extends RuntimeException { public class RedirectException extends RuntimeException {
String url; String url;
public RedirectException (String url) { /**
super ("Redirection Request to "+url); * Creates a new RedirectException object.
this.url = url; *
* @param url ...
*/
public RedirectException(String url) {
super("Redirection Request to " + url);
this.url = url;
} }
public String getMessage () { /**
return url; *
*
* @return ...
*/
public String getMessage() {
return url;
} }
/**
*
*
* @param s ...
*/
public void printStackTrace(java.io.PrintStream s) { public void printStackTrace(java.io.PrintStream s) {
// do nothing // do nothing
} }
/**
*
*
* @param w ...
*/
public void printStackTrace(java.io.PrintWriter w) { public void printStackTrace(java.io.PrintWriter w) {
// do nothing // do nothing
} }
} }

View file

@ -1,74 +1,138 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
import helma.framework.core.Application;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date;
import java.util.Map; import java.util.Map;
import helma.framework.core.Application; /**
import java.util.Date; *
*/
public class RequestBean implements Serializable { public class RequestBean implements Serializable {
RequestTrans req;
RequestTrans req; /**
* Creates a new RequestBean object.
*
* @param req ...
*/
public RequestBean(RequestTrans req) {
this.req = req;
}
public RequestBean(RequestTrans req) { /**
this.req = req; *
} *
* @param name ...
*
* @return ...
*/
public Object get(String name) {
return req.get(name);
}
public Object get (String name) { /**
return req.get (name); *
} *
* @return ...
*/
public boolean isGet() {
return req.isGet();
}
public boolean isGet () { /**
return req.isGet (); *
} *
* @return ...
*/
public boolean isPost() {
return req.isPost();
}
public boolean isPost () { /**
return req.isPost (); *
} *
* @return ...
*/
public String toString() {
return "[Request]";
}
public String toString() { // property related methods:
return "[Request]"; public String getaction() {
} return req.action;
}
// property related methods: /**
*
*
* @return ...
*/
public Map getdata() {
return req.getRequestData();
}
public String getaction () { /**
return req.action; *
} *
* @return ...
*/
public long getruntime() {
return (System.currentTimeMillis() - req.startTime);
}
public Map getdata () { /**
return req.getRequestData (); *
} *
* @return ...
*/
public String getpassword() {
return req.getPassword();
}
public long getruntime () { /**
return (System.currentTimeMillis() - req.startTime); *
} *
* @return ...
*/
public String getpath() {
return req.path;
}
public String getpassword () { /**
return req.getPassword (); *
} *
* @return ...
*/
public String getusername() {
return req.getUsername();
}
public String getpath () { /* public Date getLastModified () {
return req.path; long since = req.getIfModifiedSince ();
} if (since < 0)
return null;
public String getusername () { else
return req.getUsername (); return new Date (since);
} }
public void setLastModified () {
/* public Date getLastModified () { throw new RuntimeException ("The lastModified property of the Request object is read-only. "+
long since = req.getIfModifiedSince (); "Set lastModified on the Response object if you want to mark the last modification date of a resource.");
if (since < 0) } */
return null;
else
return new Date (since);
}
public void setLastModified () {
throw new RuntimeException ("The lastModified property of the Request object is read-only. "+
"Set lastModified on the Response object if you want to mark the last modification date of a resource.");
} */
} }

View file

@ -1,31 +1,48 @@
// RequestTrans.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
import java.io.*;
import java.util.*;
import helma.objectmodel.*; import helma.objectmodel.*;
import helma.util.Base64; import helma.util.Base64;
import java.io.*;
import java.util.*;
/** /**
* A Transmitter for a request from the servlet client. Objects of this * A Transmitter for a request from the servlet client. Objects of this
* class are directly exposed to JavaScript as global property req. * class are directly exposed to JavaScript as global property req.
*/ */
public class RequestTrans implements Externalizable { public class RequestTrans implements Externalizable {
static final long serialVersionUID = 5398880083482000580L;
// the uri path of the request // the uri path of the request
public String path; public String path;
// the request's session id // the request's session id
public String session; public String session;
// the map of form and cookie data // the map of form and cookie data
private Map values; private Map values;
// the request method - 0 for GET, 1 for POST // the request method - 0 for GET, 1 for POST
private byte httpMethod = 0; private byte httpMethod = 0;
// timestamp of client-cached version, if present in request // timestamp of client-cached version, if present in request
private long ifModifiedSince = -1; private long ifModifiedSince = -1;
// set of ETags the client sent with If-None-Match header // set of ETags the client sent with If-None-Match header
private Set etags; private Set etags;
@ -34,185 +51,237 @@ public class RequestTrans implements Externalizable {
// the name of the action being invoked // the name of the action being invoked
public transient String action; public transient String action;
private transient String httpUsername; private transient String httpUsername;
private transient String httpPassword; private transient String httpPassword;
static final long serialVersionUID = 5398880083482000580L;
/** /**
* Create a new Request transmitter with an empty data map. * Create a new Request transmitter with an empty data map.
*/ */
public RequestTrans () { public RequestTrans() {
httpMethod = 0; httpMethod = 0;
values = new HashMap (); values = new HashMap();
} }
/** /**
* Create a new request transmitter with the given data map. * Create a new request transmitter with the given data map.
*/ */
public RequestTrans (byte method) { public RequestTrans(byte method) {
httpMethod = method; httpMethod = method;
values = new HashMap (); values = new HashMap();
} }
/** /**
* Set a parameter value in this request transmitter. * Set a parameter value in this request transmitter.
*/ */
public void set (String name, Object value) { public void set(String name, Object value) {
values.put (name, value); values.put(name, value);
} }
/** /**
* Get a value from the requests map by key. * Get a value from the requests map by key.
*/ */
public Object get (String name) { public Object get(String name) {
try { try {
return values.get (name); return values.get(name);
} catch (Exception x) { } catch (Exception x) {
return null; return null;
} }
} }
/** /**
* Get the data map for this request transmitter. * Get the data map for this request transmitter.
*/ */
public Map getRequestData () { public Map getRequestData() {
return values; return values;
} }
/** /**
* The hash code is computed from the session id if available. This is used to * The hash code is computed from the session id if available. This is used to
* detect multiple identic requests. * detect multiple identic requests.
*/ */
public int hashCode () { public int hashCode() {
return session == null ? super.hashCode () : session.hashCode (); return (session == null) ? super.hashCode() : session.hashCode();
} }
/** /**
* A request is considered equal to another one if it has the same user, path, * A request is considered equal to another one if it has the same user, path,
* and request data. This is used to evaluate multiple simultanous requests only once * and request data. This is used to evaluate multiple simultanous requests only once
*/ */
public boolean equals (Object what) { public boolean equals(Object what) {
try { try {
RequestTrans other = (RequestTrans) what; RequestTrans other = (RequestTrans) what;
return (session.equals (other.session) &&
path.equalsIgnoreCase (other.path) && return (session.equals(other.session) && path.equalsIgnoreCase(other.path) &&
values.equals (other.getRequestData ())); values.equals(other.getRequestData()));
} catch (Exception x) { } catch (Exception x) {
return false; return false;
} }
} }
/** /**
* Return true if this object represents a HTTP GET Request. * Return true if this object represents a HTTP GET Request.
*/ */
public boolean isGet () { public boolean isGet() {
return httpMethod == 0; return httpMethod == 0;
} }
/** /**
* Return true if this object represents a HTTP GET Request. * Return true if this object represents a HTTP GET Request.
*/ */
public boolean isPost () { public boolean isPost() {
return httpMethod == 1; return httpMethod == 1;
} }
/** /**
* Custom externalization code for quicker serialization. * Custom externalization code for quicker serialization.
*/ */
public void readExternal (ObjectInput s) throws ClassNotFoundException, IOException { public void readExternal(ObjectInput s) throws ClassNotFoundException, IOException {
path = s.readUTF (); path = s.readUTF();
session = s.readUTF (); session = s.readUTF();
values = (Map) s.readObject (); values = (Map) s.readObject();
httpMethod = s.readByte (); httpMethod = s.readByte();
ifModifiedSince = s.readLong (); ifModifiedSince = s.readLong();
etags = (Set) s.readObject (); etags = (Set) s.readObject();
} }
/** /**
* Custom externalization code for quicker serialization. * Custom externalization code for quicker serialization.
*/ */
public void writeExternal (ObjectOutput s) throws IOException { public void writeExternal(ObjectOutput s) throws IOException {
s.writeUTF (path); s.writeUTF(path);
s.writeUTF (session); s.writeUTF(session);
s.writeObject (values); s.writeObject(values);
s.writeByte (httpMethod); s.writeByte(httpMethod);
s.writeLong (ifModifiedSince); s.writeLong(ifModifiedSince);
s.writeObject (etags); s.writeObject(etags);
} }
public void setIfModifiedSince (long since) { /**
ifModifiedSince = since; *
*
* @param since ...
*/
public void setIfModifiedSince(long since) {
ifModifiedSince = since;
} }
public long getIfModifiedSince () { /**
return ifModifiedSince; *
*
* @return ...
*/
public long getIfModifiedSince() {
return ifModifiedSince;
} }
public void setETags (String etagHeader) { /**
etags = new HashSet(); *
if (etagHeader.indexOf (",") > -1) { *
StringTokenizer st = new StringTokenizer (etagHeader, ", \r\n"); * @param etagHeader ...
while (st.hasMoreTokens()) */
etags.add (st.nextToken ()); public void setETags(String etagHeader) {
} else { etags = new HashSet();
etags.add (etagHeader);
} if (etagHeader.indexOf(",") > -1) {
StringTokenizer st = new StringTokenizer(etagHeader, ", \r\n");
while (st.hasMoreTokens())
etags.add(st.nextToken());
} else {
etags.add(etagHeader);
}
} }
public Set getETags () { /**
return etags; *
*
* @return ...
*/
public Set getETags() {
return etags;
} }
public boolean hasETag (String etag) { /**
if (etags == null || etag == null) *
return false; *
return etags.contains (etag); * @param etag ...
*
* @return ...
*/
public boolean hasETag(String etag) {
if ((etags == null) || (etag == null)) {
return false;
}
return etags.contains(etag);
} }
/**
*
*
* @return ...
*/
public String getUsername() { public String getUsername() {
if ( httpUsername!=null ) if (httpUsername != null) {
return httpUsername; return httpUsername;
String auth = (String)get("authorization"); }
if ( auth==null || "".equals(auth) ) {
return null; String auth = (String) get("authorization");
}
decodeHttpAuth(auth); if ((auth == null) || "".equals(auth)) {
return httpUsername; return null;
}
decodeHttpAuth(auth);
return httpUsername;
} }
public String getPassword() { /**
if ( httpPassword!=null ) *
return httpPassword; *
String auth = (String)get("authorization"); * @return ...
if ( auth==null || "".equals(auth) ) { */
return null; public String getPassword() {
} if (httpPassword != null) {
decodeHttpAuth(auth); return httpPassword;
return httpPassword; }
String auth = (String) get("authorization");
if ((auth == null) || "".equals(auth)) {
return null;
}
decodeHttpAuth(auth);
return httpPassword;
} }
private void decodeHttpAuth(String auth) { private void decodeHttpAuth(String auth) {
if ( auth==null ) if (auth == null) {
return; return;
StringTokenizer tok; }
if( auth.startsWith("Basic ") )
tok = new StringTokenizer ( new String( Base64.decode((auth.substring(6)).toCharArray()) ), ":" );
else
tok = new StringTokenizer ( new String( Base64.decode(auth.toCharArray()) ), ":" );
try {
httpUsername = tok.nextToken();
} catch ( NoSuchElementException e ) {
httpUsername = null;
}
try {
httpPassword = tok.nextToken();
} catch ( NoSuchElementException e ) {
httpPassword = null;
}
}
StringTokenizer tok;
if (auth.startsWith("Basic ")) {
tok = new StringTokenizer(new String(Base64.decode((auth.substring(6)).toCharArray())),
":");
} else {
tok = new StringTokenizer(new String(Base64.decode(auth.toCharArray())), ":");
}
try {
httpUsername = tok.nextToken();
} catch (NoSuchElementException e) {
httpUsername = null;
}
try {
httpPassword = tok.nextToken();
} catch (NoSuchElementException e) {
httpPassword = null;
}
}
} }

View file

@ -1,175 +1,386 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
import helma.framework.core.Application;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date;
import java.util.Map; import java.util.Map;
import helma.framework.core.Application; /**
import java.util.Date; *
*/
public class ResponseBean implements Serializable { public class ResponseBean implements Serializable {
ResponseTrans res; ResponseTrans res;
public ResponseBean(ResponseTrans res) { /**
this.res = res; * Creates a new ResponseBean object.
*
* @param res ...
*/
public ResponseBean(ResponseTrans res) {
this.res = res;
} }
public void encode (Object what) { /**
res.encode (what); *
*
* @param what ...
*/
public void encode(Object what) {
res.encode(what);
} }
public void encodeXml (Object what) { /**
res.encodeXml (what); *
*
* @param what ...
*/
public void encodeXml(Object what) {
res.encodeXml(what);
} }
public void format (Object what) { /**
res.format (what); *
*
* @param what ...
*/
public void format(Object what) {
res.format(what);
} }
public void redirect (String url) throws RedirectException { /**
res.redirect (url); *
*
* @param url ...
*
* @throws RedirectException ...
*/
public void redirect(String url) throws RedirectException {
res.redirect(url);
} }
public void reset () { /**
res.reset (); *
*/
public void reset() {
res.reset();
} }
public void setCookie (String key, String value) { /**
res.setCookie (key, value, -1, null, null); *
*
* @param key ...
* @param value ...
*/
public void setCookie(String key, String value) {
res.setCookie(key, value, -1, null, null);
} }
public void setCookie (String key, String value, int days) { /**
res.setCookie (key, value, days, null, null); *
*
* @param key ...
* @param value ...
* @param days ...
*/
public void setCookie(String key, String value, int days) {
res.setCookie(key, value, days, null, null);
} }
public void setCookie (String key, String value, int days, String path) { /**
res.setCookie (key, value, days, path, null); *
*
* @param key ...
* @param value ...
* @param days ...
* @param path ...
*/
public void setCookie(String key, String value, int days, String path) {
res.setCookie(key, value, days, path, null);
} }
public void setCookie (String key, String value, int days, String path, String domain) { /**
res.setCookie (key, value, days, path, domain); *
*
* @param key ...
* @param value ...
* @param days ...
* @param path ...
* @param domain ...
*/
public void setCookie(String key, String value, int days, String path, String domain) {
res.setCookie(key, value, days, path, domain);
} }
public void write (Object what) { /**
res.write (what); *
*
* @param what ...
*/
public void write(Object what) {
res.write(what);
} }
public void writeln (Object what) { /**
res.writeln (what); *
*
* @param what ...
*/
public void writeln(Object what) {
res.writeln(what);
} }
public void writeBinary (byte[] what) { /**
res.writeBinary (what); *
*
* @param what ...
*/
public void writeBinary(byte[] what) {
res.writeBinary(what);
} }
public void debug (Object message) { /**
res.debug (message); *
*
* @param message ...
*/
public void debug(Object message) {
res.debug(message);
} }
/**
*
*
* @return ...
*/
public String toString() { public String toString() {
return "[Response]"; return "[Response]";
} }
// property-related methods:
// property-related methods: public boolean getcache() {
return res.cache;
public boolean getcache () {
return res.cache;
} }
public void setcache (boolean cache) { /**
res.cache = cache; *
*
* @param cache ...
*/
public void setcache(boolean cache) {
res.cache = cache;
} }
public String getcharset () { /**
return res.charset; *
*
* @return ...
*/
public String getcharset() {
return res.charset;
} }
public void setcharset (String charset) { /**
res.charset = charset; *
*
* @param charset ...
*/
public void setcharset(String charset) {
res.charset = charset;
} }
public String getcontentType () { /**
return res.contentType; *
*
* @return ...
*/
public String getcontentType() {
return res.contentType;
} }
public void setcontentType (String contentType) { /**
res.contentType = contentType; *
*
* @param contentType ...
*/
public void setcontentType(String contentType) {
res.contentType = contentType;
} }
public Map getdata () { /**
return res.getResponseData (); *
*
* @return ...
*/
public Map getdata() {
return res.getResponseData();
} }
public Map gethandlers () { /**
return res.getMacroHandlers (); *
*
* @return ...
*/
public Map gethandlers() {
return res.getMacroHandlers();
} }
public String geterror () { /**
return res.error; *
*
* @return ...
*/
public String geterror() {
return res.error;
} }
public String getmessage () { /**
return res.message; *
*
* @return ...
*/
public String getmessage() {
return res.message;
} }
public void setmessage (String message) { /**
res.message = message; *
*
* @param message ...
*/
public void setmessage(String message) {
res.message = message;
} }
public String getrealm () { /**
return res.realm; *
*
* @return ...
*/
public String getrealm() {
return res.realm;
} }
public void setrealm (String realm) { /**
res.realm = realm; *
*
* @param realm ...
*/
public void setrealm(String realm) {
res.realm = realm;
} }
public void setskinpath (Object[] arr) { /**
res.setSkinpath (arr); *
*
* @param arr ...
*/
public void setskinpath(Object[] arr) {
res.setSkinpath(arr);
} }
public Object[] getskinpath () { /**
return res.getSkinpath (); *
*
* @return ...
*/
public Object[] getskinpath() {
return res.getSkinpath();
} }
public int getstatus () { /**
return res.status; *
*
* @return ...
*/
public int getstatus() {
return res.status;
} }
public void setstatus (int status) { /**
res.status = status; *
*
* @param status ...
*/
public void setstatus(int status) {
res.status = status;
} }
public Date getLastModified () { /**
long modified = res.getLastModified (); *
if (modified > -1) *
return new Date (modified); * @return ...
else */
return null; public Date getLastModified() {
long modified = res.getLastModified();
if (modified > -1) {
return new Date(modified);
} else {
return null;
}
} }
public void setLastModified (Date date) { /**
if (date == null) *
res.setLastModified (-1); *
else * @param date ...
res.setLastModified (date.getTime()); */
public void setLastModified(Date date) {
if (date == null) {
res.setLastModified(-1);
} else {
res.setLastModified(date.getTime());
}
} }
public String getETag () { /**
return res.getETag (); *
*
* @return ...
*/
public String getETag() {
return res.getETag();
} }
public void setETag (String etag) { /**
res.setETag (etag); *
*
* @param etag ...
*/
public void setETag(String etag) {
res.setETag(etag);
} }
public void dependsOn (Object what) { /**
res.dependsOn (what); *
*
* @param what ...
*/
public void dependsOn(Object what) {
res.dependsOn(what);
} }
public void digest () { /**
res.digestDependencies (); *
*/
public void digest() {
res.digestDependencies();
} }
///////////////////////////////////// /////////////////////////////////////
@ -177,14 +388,16 @@ public class ResponseBean implements Serializable {
// Helma templates (*.hsp files) and shouldn't // Helma templates (*.hsp files) and shouldn't
// be used otherwise. // be used otherwise.
//////////////////////////////////// ////////////////////////////////////
public void pushStringBuffer() {
public void pushStringBuffer () { res.pushStringBuffer();
res.pushStringBuffer ();
} }
public String popStringBuffer () { /**
return res.popStringBuffer (); *
*
* @return ...
*/
public String popStringBuffer() {
return res.popStringBuffer();
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,31 @@
// TimeoutException.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework; package helma.framework;
/** /**
* TimeoutException is thrown by the request evaluator when a request could * TimeoutException is thrown by the request evaluator when a request could
* not be serviced within the timeout period specified for an application. * not be serviced within the timeout period specified for an application.
*/ */
public class TimeoutException extends RuntimeException { public class TimeoutException extends RuntimeException {
public TimeoutException () { /**
super ("Request timed out"); * Creates a new TimeoutException object.
*/
public TimeoutException() {
super("Request timed out");
} }
} }

View file

@ -1,37 +1,53 @@
// ApplicationClassLoader.java /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.Enumeration;
import java.security.CodeSource; import java.security.CodeSource;
import java.security.Permission; import java.security.Permission;
import java.security.PermissionCollection; import java.security.PermissionCollection;
import java.security.Permissions; import java.security.Permissions;
import java.util.Enumeration;
/** /**
* ClassLoader subclass with package accessible addURL method. * ClassLoader subclass with package accessible addURL method.
*/ */
public class AppClassLoader extends URLClassLoader { public class AppClassLoader extends URLClassLoader {
private final String appname; private final String appname;
/** /**
* Create a HelmaClassLoader with the given application name and the given URLs * Create a HelmaClassLoader with the given application name and the given URLs
*/ */
public AppClassLoader(String appname, URL[] urls) { public AppClassLoader(String appname, URL[] urls) {
super ( urls, AppClassLoader.class.getClassLoader()); super(urls, AppClassLoader.class.getClassLoader());
this.appname = appname; this.appname = appname;
} }
protected void addURL (URL url) { protected void addURL(URL url) {
super.addURL (url); super.addURL(url);
} }
public String getAppName () { /**
return appname; *
*
* @return ...
*/
public String getAppName() {
return appname;
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,215 +1,497 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
import java.io.Serializable; import helma.objectmodel.INode;
import helma.util.CronJob;
import java.io.File; import java.io.File;
import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map;
import java.util.List; import java.util.List;
import java.util.Map;
import helma.objectmodel.INode; /**
*
*/
public class ApplicationBean implements Serializable { public class ApplicationBean implements Serializable {
Application app; Application app;
/**
* Creates a new ApplicationBean object.
*
* @param app ...
*/
public ApplicationBean(Application app) { public ApplicationBean(Application app) {
this.app = app; this.app = app;
} }
public void clearCache () { /**
app.clearCache (); *
*/
public void clearCache() {
app.clearCache();
} }
public void log (Object msg) { /**
String str = msg == null ? "null" : msg.toString(); *
app.logEvent (str); *
* @param msg ...
*/
public void log(Object msg) {
String str = (msg == null) ? "null" : msg.toString();
app.logEvent(str);
} }
public void log (String logname, Object msg) { /**
String str = msg == null ? "null" : msg.toString(); *
app.getLogger (logname).log (str); *
* @param logname ...
* @param msg ...
*/
public void log(String logname, Object msg) {
String str = (msg == null) ? "null" : msg.toString();
app.getLogger(logname).log(str);
} }
public void debug (Object msg) { /**
if (app.debug()) { *
String str = msg == null ? "null" : msg.toString(); *
app.logEvent (str); * @param msg ...
} */
public void debug(Object msg) {
if (app.debug()) {
String str = (msg == null) ? "null" : msg.toString();
app.logEvent(str);
}
} }
public void debug (String logname, Object msg) { /**
if (app.debug()) { *
String str = msg == null ? "null" : msg.toString(); *
app.getLogger (logname).log (str); * @param logname ...
} * @param msg ...
*/
public void debug(String logname, Object msg) {
if (app.debug()) {
String str = (msg == null) ? "null" : msg.toString();
app.getLogger(logname).log(str);
}
} }
public int countSessions () { /**
return app.sessions.size(); *
*
* @return ...
*/
public int countSessions() {
return app.sessions.size();
} }
public SessionBean getSession (String sessionID) { /**
if (sessionID==null) *
return null; *
Session session = app.getSession (sessionID.trim ()); * @param sessionID ...
if (session == null) *
return null; * @return ...
return new SessionBean (session); */
public SessionBean getSession(String sessionID) {
if (sessionID == null) {
return null;
}
Session session = app.getSession(sessionID.trim());
if (session == null) {
return null;
}
return new SessionBean(session);
} }
public SessionBean createSession (String sessionID) { /**
if (sessionID==null) *
return null; *
Session session = session = app.checkSession (sessionID.trim ()); * @param sessionID ...
if (session == null) *
return null; * @return ...
return new SessionBean (session); */
public SessionBean createSession(String sessionID) {
if (sessionID == null) {
return null;
}
Session session = session = app.checkSession(sessionID.trim());
if (session == null) {
return null;
}
return new SessionBean(session);
} }
public SessionBean[] getSessions () { /**
SessionBean[] theArray = new SessionBean[app.sessions.size()]; *
int i=0; *
for (Enumeration e=app.sessions.elements(); e.hasMoreElements(); ) { * @return ...
SessionBean sb = new SessionBean ((Session) e.nextElement ()); */
theArray[i++] = sb; public SessionBean[] getSessions() {
} SessionBean[] theArray = new SessionBean[app.sessions.size()];
return theArray; int i = 0;
for (Enumeration e = app.sessions.elements(); e.hasMoreElements();) {
SessionBean sb = new SessionBean((Session) e.nextElement());
theArray[i++] = sb;
}
return theArray;
} }
public INode registerUser (String username, String password) { /**
if (username==null || password==null || "".equals (username.trim ()) || "".equals (password.trim ()) ) *
return null; *
else * @param username ...
return app.registerUser (username, password); * @param password ...
*
* @return ...
*/
public INode registerUser(String username, String password) {
if ((username == null) || (password == null) || "".equals(username.trim()) ||
"".equals(password.trim())) {
return null;
} else {
return app.registerUser(username, password);
}
} }
public INode getUser (String username) { /**
if (username==null || "".equals (username.trim()) ) *
return null; *
return app.getUserNode (username); * @param username ...
*
* @return ...
*/
public INode getUser(String username) {
if ((username == null) || "".equals(username.trim())) {
return null;
}
return app.getUserNode(username);
} }
public INode[] getActiveUsers () { /**
List activeUsers = app.getActiveUsers (); *
return (INode[]) activeUsers.toArray (new INode[0]); *
* @return ...
*/
public INode[] getActiveUsers() {
List activeUsers = app.getActiveUsers();
return (INode[]) activeUsers.toArray(new INode[0]);
} }
public INode[] getRegisteredUsers () { /**
List registeredUsers = app.getRegisteredUsers (); *
return (INode[]) registeredUsers.toArray (new INode[0]); *
} * @return ...
*/
public INode[] getRegisteredUsers() {
List registeredUsers = app.getRegisteredUsers();
public SessionBean[] getSessionsForUser (INode usernode) { return (INode[]) registeredUsers.toArray(new INode[0]);
if (usernode==null)
return new SessionBean[0];
else
return getSessionsForUser(usernode.getName());
} }
public SessionBean[] getSessionsForUser (String username) { /**
if (username==null || "".equals (username.trim ()) ) *
return new SessionBean[0]; *
List userSessions = app.getSessionsForUsername (username); * @param usernode ...
return (SessionBean[]) userSessions.toArray (new SessionBean[0]); *
* @return ...
*/
public SessionBean[] getSessionsForUser(INode usernode) {
if (usernode == null) {
return new SessionBean[0];
} else {
return getSessionsForUser(usernode.getName());
}
}
/**
*
*
* @param username ...
*
* @return ...
*/
public SessionBean[] getSessionsForUser(String username) {
if ((username == null) || "".equals(username.trim())) {
return new SessionBean[0];
}
List userSessions = app.getSessionsForUsername(username);
return (SessionBean[]) userSessions.toArray(new SessionBean[0]);
}
/**
*
*
* @param functionName ...
*/
public void addCronJob(String functionName) {
CronJob job = new CronJob(functionName);
job.setFunction(functionName);
app.customCronJobs.put(functionName, job);
}
/**
*
*
* @param functionName ...
* @param year ...
* @param month ...
* @param day ...
* @param weekday ...
* @param hour ...
* @param minute ...
*/
public void addCronJob(String functionName, String year, String month, String day,
String weekday, String hour, String minute) {
CronJob job = CronJob.newJob(functionName, year, month, day, weekday, hour, minute);
app.customCronJobs.put(functionName, job);
}
/**
*
*
* @param functionName ...
*/
public void removeCronJob(String functionName) {
app.customCronJobs.remove(functionName);
} }
// getter methods for readonly properties of this application // getter methods for readonly properties of this application
public int getcacheusage() {
public int getcacheusage () { return app.getCacheUsage();
return app.getCacheUsage ();
} }
/**
*
*
* @return ...
*/
public INode getdata() { public INode getdata() {
return app.getCacheNode (); return app.getCacheNode();
} }
/**
*
*
* @return ...
*/
public Map getmodules() { public Map getmodules() {
return app.modules; return app.modules;
} }
public String getdir () { /**
return app.getAppDir ().getAbsolutePath (); *
*
* @return ...
*/
public String getdir() {
return app.getAppDir().getAbsolutePath();
} }
public Date getupSince () { /**
return new Date (app.starttime); *
*
* @return ...
*/
public String getname() {
return app.getName();
} }
public long getrequestCount () { /**
return app.getRequestCount (); *
*
* @return ...
*/
public Date getupSince() {
return new Date(app.starttime);
} }
public long getxmlrpcCount () { /**
return app.getXmlrpcCount (); *
*
* @return ...
*/
public long getrequestCount() {
return app.getRequestCount();
} }
public long geterrorCount () { /**
return app.getErrorCount (); *
*
* @return ...
*/
public long getxmlrpcCount() {
return app.getXmlrpcCount();
} }
public Application get__app__ () { /**
return app; *
*
* @return ...
*/
public long geterrorCount() {
return app.getErrorCount();
} }
public Map getproperties () { /**
return app.getProperties (); *
*
* @return ...
*/
public Application get__app__() {
return app;
} }
public int getfreeThreads () { /**
return app.countFreeEvaluators (); *
*
* @return ...
*/
public Map getproperties() {
return app.getProperties();
} }
public int getactiveThreads () { /**
return app.countActiveEvaluators (); *
*
* @return ...
*/
public int getfreeThreads() {
return app.countFreeEvaluators();
} }
public int getmaxThreads () { /**
return app.countEvaluators (); *
*
* @return ...
*/
public int getactiveThreads() {
return app.countActiveEvaluators();
} }
public void setmaxThreads (int n) { /**
// add one to the number to compensate for the internal scheduler. *
app.setNumberOfEvaluators (n+1); *
* @return ...
*/
public int getmaxThreads() {
return app.countEvaluators();
} }
public Map getSkinfiles () { /**
Map skinz = new HashMap (); *
for (Iterator it = app.getPrototypes().iterator(); it.hasNext(); ) { *
Prototype p = (Prototype) it.next (); * @param n ...
skinz.put (p.getName(), p.getSkinMap()); */
} public void setmaxThreads(int n) {
return skinz; // add one to the number to compensate for the internal scheduler.
app.setNumberOfEvaluators(n + 1);
} }
public Map getSkinfiles (Object[] skinpath) { /**
Map skinz = new HashMap (); *
for (Iterator it = app.getPrototypes().iterator(); it.hasNext(); ) { *
Prototype p = (Prototype) it.next (); * @return ...
skinz.put (p.getName(), p.getSkinMap(skinpath)); */
} public Map getSkinfiles() {
return skinz; Map skinz = new HashMap();
for (Iterator it = app.getPrototypes().iterator(); it.hasNext();) {
Prototype p = (Prototype) it.next();
skinz.put(p.getName(), p.getSkinMap());
}
return skinz;
} }
public String getAppDir () { /**
return app.getAppDir().getAbsolutePath(); *
*
* @param skinpath ...
*
* @return ...
*/
public Map getSkinfiles(Object[] skinpath) {
Map skinz = new HashMap();
for (Iterator it = app.getPrototypes().iterator(); it.hasNext();) {
Prototype p = (Prototype) it.next();
skinz.put(p.getName(), p.getSkinMap(skinpath));
}
return skinz;
} }
public String getServerDir () { /**
File f = app.getServerDir(); *
if (f == null) *
f = app.getAppDir(); * @return ...
return f.getAbsolutePath(); */
public String getAppDir() {
return app.getAppDir().getAbsolutePath();
} }
/**
*
*
* @return ...
*/
public String getServerDir() {
File f = app.getServerDir();
if (f == null) {
f = app.getAppDir();
}
return f.getAbsolutePath();
}
/**
*
*
* @return ...
*/
public String toString() { public String toString() {
return "[Application " + app.getName() + "]"; return "[Application " + app.getName() + "]";
} }
} }

View file

@ -1,16 +1,28 @@
// Prototype.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
import java.util.*;
import java.io.*;
import helma.framework.*; import helma.framework.*;
import helma.scripting.*;
import helma.objectmodel.*; import helma.objectmodel.*;
import helma.objectmodel.db.DbMapping; import helma.objectmodel.db.DbMapping;
import helma.scripting.*;
import helma.util.Updatable; import helma.util.Updatable;
import java.io.*;
import java.util.*;
/** /**
* The Prototype class represents Script prototypes/type defined in a Helma * The Prototype class represents Script prototypes/type defined in a Helma
@ -18,161 +30,195 @@ import helma.util.Updatable;
* as well as optional information about the mapping of this type to a * as well as optional information about the mapping of this type to a
* relational database table. * relational database table.
*/ */
public final class Prototype { public final class Prototype {
String name; String name;
Application app; Application app;
File directory; File directory;
File[] files;
File [] files;
long lastDirectoryListing; long lastDirectoryListing;
long checksum; long checksum;
HashMap code;
HashMap code, zippedCode; HashMap zippedCode;
HashMap skins, zippedSkins; HashMap skins;
HashMap zippedSkins;
HashMap updatables; HashMap updatables;
// a map of this prototype's skins as raw strings // a map of this prototype's skins as raw strings
// used for exposing skins to application (script) code (via app.skinfiles). // used for exposing skins to application (script) code (via app.skinfiles).
SkinMap skinMap; SkinMap skinMap;
DbMapping dbmap; DbMapping dbmap;
// lastCheck is the time the prototype's files were last checked // lastCheck is the time the prototype's files were last checked
private long lastChecksum; private long lastChecksum;
// lastUpdate is the time at which any of the prototype's files were // lastUpdate is the time at which any of the prototype's files were
// found updated the last time // found updated the last time
private long lastUpdate; private long lastUpdate;
private Prototype parent; private Prototype parent;
// Tells us whether this prototype is used to script a generic Java object, // Tells us whether this prototype is used to script a generic Java object,
// as opposed to a Helma objectmodel node object. // as opposed to a Helma objectmodel node object.
boolean isJavaPrototype; boolean isJavaPrototype;
public Prototype (String name, File dir, Application app) { /**
// app.logEvent ("Constructing Prototype "+app.getName()+"/"+name); * Creates a new Prototype object.
this.app = app; *
this.name = name; * @param name ...
this.directory = dir; * @param dir ...
* @param app ...
*/
public Prototype(String name, File dir, Application app) {
// app.logEvent ("Constructing Prototype "+app.getName()+"/"+name);
this.app = app;
this.name = name;
this.directory = dir;
code = new HashMap (); code = new HashMap();
zippedCode = new HashMap (); zippedCode = new HashMap();
skins = new HashMap (); skins = new HashMap();
zippedSkins = new HashMap (); zippedSkins = new HashMap();
updatables = new HashMap (); updatables = new HashMap();
skinMap = new SkinMap (); skinMap = new SkinMap();
isJavaPrototype = app.isJavaPrototype (name); isJavaPrototype = app.isJavaPrototype(name);
lastUpdate = lastChecksum = 0; lastUpdate = lastChecksum = 0;
} }
/** /**
* Return the application this prototype is a part of * Return the application this prototype is a part of
*/ */
public Application getApplication () { public Application getApplication() {
return app; return app;
} }
/** /**
* Return this prototype's directory. * Return this prototype's directory.
*/ */
public File getDirectory () { public File getDirectory() {
return directory; return directory;
} }
/** /**
* Get the list of files in this prototype's directory * Get the list of files in this prototype's directory
*/ */
public File[] getFiles () { public File[] getFiles() {
if (files == null || directory.lastModified() != lastDirectoryListing) { if ((files == null) || (directory.lastModified() != lastDirectoryListing)) {
lastDirectoryListing = directory.lastModified (); lastDirectoryListing = directory.lastModified();
files = directory.listFiles(); files = directory.listFiles();
if (files == null)
files = new File[0]; if (files == null) {
} files = new File[0];
return files; }
}
return files;
} }
/** /**
* Get a checksum over the files in this prototype's directory * Get a checksum over the files in this prototype's directory
*/ */
public long getChecksum () { public long getChecksum() {
// long start = System.currentTimeMillis(); // long start = System.currentTimeMillis();
File[] f = getFiles (); File[] f = getFiles();
long c = 0; long c = 0;
for (int i=0; i<f.length; i++)
c += f[i].lastModified(); for (int i = 0; i < f.length; i++)
checksum = c; c += f[i].lastModified();
// System.err.println ("CHECKSUM "+name+": "+(System.currentTimeMillis()-start));
return checksum; checksum = c;
// System.err.println ("CHECKSUM "+name+": "+(System.currentTimeMillis()-start));
return checksum;
} }
public boolean isUpToDate () { /**
return checksum == lastChecksum; *
*
* @return ...
*/
public boolean isUpToDate() {
return checksum == lastChecksum;
} }
/** /**
* Set the parent prototype of this prototype, i.e. the prototype this * Set the parent prototype of this prototype, i.e. the prototype this
* prototype inherits from. * prototype inherits from.
*/ */
public void setParentPrototype (Prototype parent) { public void setParentPrototype(Prototype parent) {
// this is not allowed for the hopobject and global prototypes // this is not allowed for the hopobject and global prototypes
if ("hopobject".equalsIgnoreCase (name) || "global".equalsIgnoreCase (name)) if ("hopobject".equalsIgnoreCase(name) || "global".equalsIgnoreCase(name)) {
return; return;
this.parent = parent; }
this.parent = parent;
} }
/** /**
* Get the parent prototype from which we inherit, or null * Get the parent prototype from which we inherit, or null
* if we are top of the line. * if we are top of the line.
*/ */
public Prototype getParentPrototype () { public Prototype getParentPrototype() {
return parent; return parent;
} }
/** /**
* Check if the given prototype is within this prototype's parent chain. * Check if the given prototype is within this prototype's parent chain.
*/ */
public final boolean isInstanceOf (String pname) { public final boolean isInstanceOf(String pname) {
if (name.equals (pname)) if (name.equals(pname)) {
return true; return true;
if (parent != null && !"hopobject".equalsIgnoreCase (parent.getName())) }
return parent.isInstanceOf (pname);
return false; if ((parent != null) && !"hopobject".equalsIgnoreCase(parent.getName())) {
return parent.isInstanceOf(pname);
}
return false;
} }
/** /**
* Register an object as handler for this prototype and all our parent prototypes. * Register an object as handler for this prototype and all our parent prototypes.
*/ */
public final void addToHandlerMap (Map handlers, Object obj) { public final void addToHandlerMap(Map handlers, Object obj) {
if (parent != null && !"hopobject".equalsIgnoreCase (parent.getName())) if ((parent != null) && !"hopobject".equalsIgnoreCase(parent.getName())) {
parent.addToHandlerMap (handlers, obj); parent.addToHandlerMap(handlers, obj);
handlers.put (name, obj); }
handlers.put(name, obj);
} }
public void setDbMapping (DbMapping dbmap) { /**
this.dbmap = dbmap; *
*
* @param dbmap ...
*/
public void setDbMapping(DbMapping dbmap) {
this.dbmap = dbmap;
} }
public DbMapping getDbMapping () { /**
return dbmap; *
*
* @return ...
*/
public DbMapping getDbMapping() {
return dbmap;
} }
/** /**
* Get a Skinfile for this prototype. This only works for skins * Get a Skinfile for this prototype. This only works for skins
* residing in the prototype directory, not for skin files in * residing in the prototype directory, not for skin files in
* other locations or database stored skins. * other locations or database stored skins.
*/ */
public SkinFile getSkinFile (String sfname) { public SkinFile getSkinFile(String sfname) {
SkinFile sf = (SkinFile) skins.get (sfname); SkinFile sf = (SkinFile) skins.get(sfname);
if (sf == null)
sf = (SkinFile) zippedSkins.get (sfname); if (sf == null) {
return sf; sf = (SkinFile) zippedSkins.get(sfname);
}
return sf;
} }
/** /**
@ -180,25 +226,30 @@ public final class Prototype {
* residing in the prototype directory, not for skins files in * residing in the prototype directory, not for skins files in
* other locations or database stored skins. * other locations or database stored skins.
*/ */
public Skin getSkin (String sfname) { public Skin getSkin(String sfname) {
SkinFile sf = getSkinFile (sfname); SkinFile sf = getSkinFile(sfname);
if (sf != null)
return sf.getSkin (); if (sf != null) {
else return sf.getSkin();
return null; } else {
return null;
}
} }
/**
public String getName () { *
return name; *
* @return ...
*/
public String getName() {
return name;
} }
/** /**
* Get the last time any script has been re-read for this prototype. * Get the last time any script has been re-read for this prototype.
*/ */
public long getLastUpdate () { public long getLastUpdate() {
return lastUpdate; return lastUpdate;
} }
/** /**
@ -206,35 +257,35 @@ public final class Prototype {
* re-read from disk and needs to be re-compiled by * re-read from disk and needs to be re-compiled by
* the evaluators. * the evaluators.
*/ */
public void markUpdated () { public void markUpdated() {
lastUpdate = System.currentTimeMillis (); lastUpdate = System.currentTimeMillis();
} }
/** /**
* Get the time at which this prototype's scripts were checked * Get the time at which this prototype's scripts were checked
* for changes for the last time. * for changes for the last time.
*/ */
/* public long getLastCheck () { /* public long getLastCheck () {
return lastCheck; return lastCheck;
} */ } */
/** /**
* Signal that the prototype's scripts have been checked for * Signal that the prototype's scripts have been checked for
* changes. * changes.
*/ */
public void markChecked () { public void markChecked() {
// lastCheck = System.currentTimeMillis (); // lastCheck = System.currentTimeMillis ();
lastChecksum = checksum; lastChecksum = checksum;
} }
/** /**
* Return a clone of this prototype's actions container. Synchronized * Return a clone of this prototype's actions container. Synchronized
* to not return a map in a transient state where it is just being * to not return a map in a transient state where it is just being
* updated by the type manager. * updated by the type manager.
*/ */
public synchronized Map getCode () { public synchronized Map getCode() {
return (Map) code.clone(); return (Map) code.clone();
} }
/** /**
@ -242,232 +293,304 @@ public final class Prototype {
* to not return a map in a transient state where it is just being * to not return a map in a transient state where it is just being
* updated by the type manager. * updated by the type manager.
*/ */
public synchronized Map getZippedCode () { public synchronized Map getZippedCode() {
return (Map) zippedCode.clone(); return (Map) zippedCode.clone();
} }
/**
*
*
* @param action ...
*/
public synchronized void addActionFile(ActionFile action) {
File f = action.getFile();
public synchronized void addActionFile (ActionFile action) { if (f != null) {
File f = action.getFile (); code.put(action.getSourceName(), action);
if (f != null) { updatables.put(f.getName(), action);
code.put (action.getSourceName(), action); } else {
updatables.put (f.getName(), action); zippedCode.put(action.getSourceName(), action);
} else { }
zippedCode.put (action.getSourceName(), action);
}
} }
public synchronized void addTemplate (Template template) { /**
File f = template.getFile (); *
if (f != null) { *
code.put (template.getSourceName(), template); * @param template ...
updatables.put (f.getName(), template); */
} else { public synchronized void addTemplate(Template template) {
zippedCode.put (template.getSourceName(), template); File f = template.getFile();
}
if (f != null) {
code.put(template.getSourceName(), template);
updatables.put(f.getName(), template);
} else {
zippedCode.put(template.getSourceName(), template);
}
} }
public synchronized void addFunctionFile (FunctionFile funcfile) { /**
File f = funcfile.getFile (); *
if (f != null) { *
code.put (funcfile.getSourceName(), funcfile); * @param funcfile ...
updatables.put (f.getName(), funcfile); */
} else { public synchronized void addFunctionFile(FunctionFile funcfile) {
zippedCode.put (funcfile.getSourceName(), funcfile); File f = funcfile.getFile();
}
if (f != null) {
code.put(funcfile.getSourceName(), funcfile);
updatables.put(f.getName(), funcfile);
} else {
zippedCode.put(funcfile.getSourceName(), funcfile);
}
} }
public synchronized void addSkinFile (SkinFile skinfile) { /**
File f = skinfile.getFile (); *
if (f != null) { *
skins.put (skinfile.getName(), skinfile); * @param skinfile ...
updatables.put (f.getName(), skinfile); */
} else { public synchronized void addSkinFile(SkinFile skinfile) {
zippedSkins.put (skinfile.getName(), skinfile); File f = skinfile.getFile();
}
if (f != null) {
skins.put(skinfile.getName(), skinfile);
updatables.put(f.getName(), skinfile);
} else {
zippedSkins.put(skinfile.getName(), skinfile);
}
} }
/**
*
*
* @param action ...
*/
public synchronized void removeActionFile(ActionFile action) {
File f = action.getFile();
public synchronized void removeActionFile (ActionFile action) { if (f != null) {
File f = action.getFile (); code.remove(action.getSourceName());
if (f != null) { updatables.remove(f.getName());
code.remove (action.getSourceName()); } else {
updatables.remove (f.getName()); zippedCode.remove(action.getSourceName());
} else { }
zippedCode.remove (action.getSourceName());
}
} }
public synchronized void removeFunctionFile (FunctionFile funcfile) { /**
File f = funcfile.getFile (); *
if (f != null) { *
code.remove (funcfile.getSourceName()); * @param funcfile ...
updatables.remove (f.getName()); */
} else { public synchronized void removeFunctionFile(FunctionFile funcfile) {
zippedCode.remove (funcfile.getSourceName()); File f = funcfile.getFile();
}
if (f != null) {
code.remove(funcfile.getSourceName());
updatables.remove(f.getName());
} else {
zippedCode.remove(funcfile.getSourceName());
}
} }
public synchronized void removeTemplate (Template template) { /**
File f = template.getFile (); *
if (f != null) { *
code.remove (template.getSourceName()); * @param template ...
updatables.remove (f.getName()); */
} else { public synchronized void removeTemplate(Template template) {
zippedCode.remove (template.getSourceName()); File f = template.getFile();
}
if (f != null) {
code.remove(template.getSourceName());
updatables.remove(f.getName());
} else {
zippedCode.remove(template.getSourceName());
}
} }
public synchronized void removeSkinFile (SkinFile skinfile) { /**
File f = skinfile.getFile (); *
if (f != null) { *
skins.remove (skinfile.getName()); * @param skinfile ...
updatables.remove (f.getName()); */
} else { public synchronized void removeSkinFile(SkinFile skinfile) {
zippedSkins.remove (skinfile.getName()); File f = skinfile.getFile();
}
if (f != null) {
skins.remove(skinfile.getName());
updatables.remove(f.getName());
} else {
zippedSkins.remove(skinfile.getName());
}
} }
/**
/** * Return a string representing this prototype.
* Return a string representing this prototype. */
*/ public String toString() {
public String toString () { return "[Prototype " + app.getName() + "/" + name + "]";
return "[Prototype "+ app.getName()+"/"+name+"]";
} }
/**
public SkinMap getSkinMap () { *
return skinMap; *
* @return ...
*/
public SkinMap getSkinMap() {
return skinMap;
} }
// not yet implemented // not yet implemented
public SkinMap getSkinMap (Object[] skinpath) { public SkinMap getSkinMap(Object[] skinpath) {
return new SkinMap (skinpath); return new SkinMap(skinpath);
} }
// a map that dynamically expands to all skins in this prototype // a map that dynamically expands to all skins in this prototype
final class SkinMap extends HashMap { final class SkinMap extends HashMap {
long lastSkinmapLoad = 0;
Object[] skinpath;
long lastSkinmapLoad = 0; SkinMap() {
super();
skinpath = null;
}
Object[] skinpath; SkinMap(Object[] path) {
super();
skinpath = path;
}
SkinMap () { public boolean containsKey(Object key) {
super (); checkForUpdates();
skinpath = null;
}
SkinMap (Object[] path) { return super.containsKey(key);
super (); }
skinpath = path;
}
public boolean containsKey (Object key) { public boolean containsValue(Object value) {
checkForUpdates (); checkForUpdates();
return super.containsKey (key);
}
public boolean containsValue (Object value) { return super.containsValue(value);
checkForUpdates (); }
return super.containsValue (value);
}
public Set entrySet () { public Set entrySet() {
checkForUpdates (); checkForUpdates();
return super.entrySet ();
}
public boolean equals (Object obj) { return super.entrySet();
checkForUpdates (); }
return super.equals (obj);
}
public Object get (Object key) { public boolean equals(Object obj) {
if (key == null) checkForUpdates();
return null;
checkForUpdates ();
SkinFile sf = (SkinFile) super.get (key);
if (sf == null)
return null;
return sf.getSkin().getSource ();
}
public int hashCode () { return super.equals(obj);
checkForUpdates (); }
return super.hashCode ();
}
public boolean isEmpty () { public Object get(Object key) {
checkForUpdates (); if (key == null) {
return super.isEmpty (); return null;
} }
public Set keySet () { checkForUpdates();
checkForUpdates ();
return super.keySet ();
}
public Object put (Object key, Object value) { SkinFile sf = (SkinFile) super.get(key);
// checkForUpdates ();
return super.put (key, value);
}
public void putAll (Map t) { if (sf == null) {
// checkForUpdates (); return null;
super.putAll (t); }
}
public Object remove (Object key) { return sf.getSkin().getSource();
checkForUpdates (); }
return super.remove (key);
}
public int size () { public int hashCode() {
checkForUpdates (); checkForUpdates();
return super.size ();
}
public Collection values () { return super.hashCode();
checkForUpdates (); }
return super.values ();
}
public boolean isEmpty() {
checkForUpdates();
private void checkForUpdates () { return super.isEmpty();
if (/* lastCheck < System.currentTimeMillis()- 2000l*/ !isUpToDate()) }
app.typemgr.updatePrototype (Prototype.this);
if (lastUpdate > lastSkinmapLoad)
load ();
}
private synchronized void load () { public Set keySet() {
if (lastUpdate == lastSkinmapLoad) checkForUpdates();
return;
super.clear ();
// System.err.println ("LOADING SKIN VALUES: "+Prototype.this);
for (Iterator i = skins.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry) i.next ();
super.put (e.getKey(), e.getValue());
}
// if skinpath is not null, overload/add skins from there
if (skinpath != null) {
for (int i=skinpath.length-1; i>=0; i--) {
if (skinpath[i] != null && skinpath[i] instanceof String) {
Map m = app.skinmgr.getSkinFiles ((String) skinpath[i], Prototype.this);
if (m != null)
super.putAll (m);
}
}
}
lastSkinmapLoad = lastUpdate;
}
public String toString () { return super.keySet();
return "[SkinMap "+name+"]"; }
}
public Object put(Object key, Object value) {
// checkForUpdates ();
return super.put(key, value);
}
public void putAll(Map t) {
// checkForUpdates ();
super.putAll(t);
}
public Object remove(Object key) {
checkForUpdates();
return super.remove(key);
}
public int size() {
checkForUpdates();
return super.size();
}
public Collection values() {
checkForUpdates();
return super.values();
}
private void checkForUpdates() {
if ( /* lastCheck < System.currentTimeMillis()- 2000l*/
!isUpToDate()) {
app.typemgr.updatePrototype(Prototype.this);
}
if (lastUpdate > lastSkinmapLoad) {
load();
}
}
private synchronized void load() {
if (lastUpdate == lastSkinmapLoad) {
return;
}
super.clear();
// System.err.println ("LOADING SKIN VALUES: "+Prototype.this);
for (Iterator i = skins.entrySet().iterator(); i.hasNext();) {
Map.Entry e = (Map.Entry) i.next();
super.put(e.getKey(), e.getValue());
}
// if skinpath is not null, overload/add skins from there
if (skinpath != null) {
for (int i = skinpath.length - 1; i >= 0; i--) {
if ((skinpath[i] != null) && skinpath[i] instanceof String) {
Map m = app.skinmgr.getSkinFiles((String) skinpath[i],
Prototype.this);
if (m != null) {
super.putAll(m);
}
}
}
}
lastSkinmapLoad = lastUpdate;
}
public String toString() {
return "[SkinMap " + name + "]";
}
} }
} }

View file

@ -1,5 +1,18 @@
// RemoteApplication.java /*
// Copyright (c) Hannes Wallnöfer 2002 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
@ -12,43 +25,45 @@ import java.util.Vector;
/** /**
* Proxy class for Aplication that listens to requests via RMI. * Proxy class for Aplication that listens to requests via RMI.
*/ */
public class RemoteApplication extends UnicastRemoteObject implements IRemoteApp,
public class RemoteApplication IReplicationListener {
extends UnicastRemoteObject
implements IRemoteApp, IReplicationListener {
Application app; Application app;
/**
public RemoteApplication (Application app) throws RemoteException { * Creates a new RemoteApplication object.
this.app = app; *
* @param app ...
*
* @throws RemoteException ...
*/
public RemoteApplication(Application app) throws RemoteException {
this.app = app;
} }
/** /**
* ping method to let clients know if the server is reachable * ping method to let clients know if the server is reachable
*/ */
public void ping () { public void ping() {
// do nothing // do nothing
} }
/** /**
* Execute a request coming in from a web client. * Execute a request coming in from a web client.
*/ */
public ResponseTrans execute (RequestTrans req) { public ResponseTrans execute(RequestTrans req) {
return app.execute (req); return app.execute(req);
} }
/** /**
* Update HopObjects in this application's cache. This is used to replicate * Update HopObjects in this application's cache. This is used to replicate
* application caches in a distributed app environment * application caches in a distributed app environment
*/ */
public void replicateCache (Vector add, Vector delete) { public void replicateCache(Vector add, Vector delete) {
if (!"true".equalsIgnoreCase (app.getProperty ("allowReplication"))) { if (!"true".equalsIgnoreCase(app.getProperty("allowReplication"))) {
app.logEvent ("Rejecting cache replication event: allowReplication property is not set to true"); app.logEvent("Rejecting cache replication event: allowReplication property is not set to true");
throw new RuntimeException ("Replication event rejected: setup does not allow replication."); throw new RuntimeException("Replication event rejected: setup does not allow replication.");
} }
app.nmgr.replicateCache (add, delete);
app.nmgr.replicateCache(add, delete);
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,26 @@
// Session.java /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
import java.io.*;
import java.util.*;
import java.net.URLEncoder;
import helma.objectmodel.*; import helma.objectmodel.*;
import helma.objectmodel.db.*; import helma.objectmodel.db.*;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
/** /**
* This represents a session currently using the Hop application. * This represents a session currently using the Hop application.
@ -14,9 +28,7 @@ import helma.objectmodel.db.*;
* Depending on whether the user is logged in or not, the user object holds a * Depending on whether the user is logged in or not, the user object holds a
* persistent user node. * persistent user node.
*/ */
public class Session implements Serializable { public class Session implements Serializable {
transient Application app; transient Application app;
String sessionID; String sessionID;
@ -29,118 +41,175 @@ public class Session implements Serializable {
// the transient cache node that is exposed to javascript // the transient cache node that is exposed to javascript
// this stays the same across logins and logouts. // this stays the same across logins and logouts.
public TransientNode cacheNode; public TransientNode cacheNode;
long onSince;
long onSince, lastTouched, lastModified; long lastTouched;
long lastModified;
// used to remember messages to the user between requests - // used to remember messages to the user between requests -
// used for redirects. // used for redirects.
String message; String message;
public Session (String sessionID, Application app) { /**
this.sessionID = sessionID; * Creates a new Session object.
this.app = app; *
this.uid = null; * @param sessionID ...
this.userHandle = null; * @param app ...
cacheNode = new TransientNode ("session"); */
onSince = System.currentTimeMillis (); public Session(String sessionID, Application app) {
lastTouched = lastModified = onSince; this.sessionID = sessionID;
this.app = app;
this.uid = null;
this.userHandle = null;
cacheNode = new TransientNode("session");
onSince = System.currentTimeMillis();
lastTouched = lastModified = onSince;
} }
/** /**
* attach the given user node to this session. * attach the given user node to this session.
*/ */
public void login (INode usernode) { public void login(INode usernode) {
if (usernode==null) { if (usernode == null) {
userHandle = null; userHandle = null;
uid = null; uid = null;
} else { } else {
userHandle = ((Node)usernode).getHandle(); userHandle = ((Node) usernode).getHandle();
uid = usernode.getElementName(); uid = usernode.getElementName();
} }
lastModified = System.currentTimeMillis ();
lastModified = System.currentTimeMillis();
} }
/** /**
* remove this sessions's user node. * remove this sessions's user node.
*/ */
public void logout() { public void logout() {
userHandle = null; userHandle = null;
uid = null; uid = null;
lastModified = System.currentTimeMillis (); lastModified = System.currentTimeMillis();
} }
/**
*
*
* @return ...
*/
public boolean isLoggedIn() { public boolean isLoggedIn() {
if (userHandle!=null && uid!=null) { if ((userHandle != null) && (uid != null)) {
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** /**
* Gets the user Node from this Application's NodeManager. * Gets the user Node from this Application's NodeManager.
*/ */
public INode getUserNode() { public INode getUserNode() {
if (userHandle!=null) if (userHandle != null) {
return userHandle.getNode (app.getWrappedNodeManager()); return userHandle.getNode(app.getWrappedNodeManager());
else } else {
return null; return null;
}
} }
/** /**
* Gets the transient cache node. * Gets the transient cache node.
*/ */
public INode getCacheNode () { public INode getCacheNode() {
return cacheNode; return cacheNode;
} }
public Application getApp () { /**
return app; *
*
* @return ...
*/
public Application getApp() {
return app;
} }
public void setApp (Application app) { /**
this.app = app; *
*
* @param app ...
*/
public void setApp(Application app) {
this.app = app;
} }
public String getSessionID () { /**
return sessionID; *
*
* @return ...
*/
public String getSessionID() {
return sessionID;
} }
public void touch () { /**
lastTouched = System.currentTimeMillis (); *
*/
public void touch() {
lastTouched = System.currentTimeMillis();
} }
public long lastTouched () { /**
return lastTouched; *
*
* @return ...
*/
public long lastTouched() {
return lastTouched;
} }
public long lastModified () { /**
return lastModified; *
*
* @return ...
*/
public long lastModified() {
return lastModified;
} }
public void setLastModified (Date date) { /**
if (date != null) *
lastModified = date.getTime (); *
* @param date ...
*/
public void setLastModified(Date date) {
if (date != null) {
lastModified = date.getTime();
}
} }
public long onSince () { /**
return onSince; *
*
* @return ...
*/
public long onSince() {
return onSince;
} }
public String toString () { /**
if ( uid!=null ) *
return "[Session for user " + uid + "]"; *
else * @return ...
return "[Anonymous Session]"; */
public String toString() {
if (uid != null) {
return "[Session for user " + uid + "]";
} else {
return "[Anonymous Session]";
}
} }
/** /**
* Get the persistent user id of a registered user. This is usually the user name, or * Get the persistent user id of a registered user. This is usually the user name, or
* null if the user is not logged in. * null if the user is not logged in.
*/ */
public String getUID () { public String getUID() {
return uid; return uid;
} }
} }

View file

@ -1,79 +1,163 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
import helma.objectmodel.INode;
import helma.scripting.fesi.*;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import helma.objectmodel.INode; /**
import helma.scripting.fesi.*; *
*/
public class SessionBean implements Serializable { public class SessionBean implements Serializable {
// the wrapped session object // the wrapped session object
Session session; Session session;
public SessionBean(Session session) { /**
this.session = session; * Creates a new SessionBean object.
*
* @param session ...
*/
public SessionBean(Session session) {
this.session = session;
} }
public String toString() { /**
return session.toString (); *
*
* @return ...
*/
public String toString() {
return session.toString();
} }
public boolean login (String username, String password) { /**
boolean success = session.getApp().loginSession (username, password, session); *
return success; *
* @param username ...
* @param password ...
*
* @return ...
*/
public boolean login(String username, String password) {
boolean success = session.getApp().loginSession(username, password, session);
return success;
} }
public void logout () { /**
session.getApp().logoutSession (session); *
*/
public void logout() {
session.getApp().logoutSession(session);
} }
public void touch () { /**
session.touch (); *
*/
public void touch() {
session.touch();
} }
/**
*
*
* @return ...
*/
public Date lastActive() { public Date lastActive() {
return new Date (session.lastTouched ()); return new Date(session.lastTouched());
} }
/**
*
*
* @return ...
*/
public Date onSince() { public Date onSince() {
return new Date (session.onSince ()); return new Date(session.onSince());
} }
// property-related methods: // property-related methods:
public INode getdata() { public INode getdata() {
return session.getCacheNode (); return session.getCacheNode();
} }
/**
*
*
* @return ...
*/
public INode getuser() { public INode getuser() {
return session.getUserNode(); return session.getUserNode();
} }
public String get_id () { /**
return session.getSessionID (); *
*
* @return ...
*/
public String get_id() {
return session.getSessionID();
} }
/**
*
*
* @return ...
*/
public String getcookie() { public String getcookie() {
return session.getSessionID (); return session.getSessionID();
} }
/**
*
*
* @return ...
*/
public Date getlastActive() { public Date getlastActive() {
return new Date (session.lastTouched ()); return new Date(session.lastTouched());
} }
/**
*
*
* @return ...
*/
public Date getonSince() { public Date getonSince() {
return new Date (session.onSince ()); return new Date(session.onSince());
} }
public Date getLastModified () { /**
return new Date (session.lastModified ()); *
*
* @return ...
*/
public Date getLastModified() {
return new Date(session.lastModified());
} }
public void setLastModified (Date date) { /**
session.setLastModified (date); *
*
* @param date ...
*/
public void setLastModified(Date date) {
session.setLastModified(date);
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,20 +1,29 @@
// SkinFile.java /*
// Copyright (c) Hannes Wallnöfer 2001 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
import java.util.*;
import java.io.*;
import helma.util.Updatable; import helma.util.Updatable;
import java.io.*;
import java.util.*;
/** /**
* This represents a File containing a Hop skin * This represents a File containing a Hop skin
*/ */
public final class SkinFile implements Updatable { public final class SkinFile implements Updatable {
String name; String name;
Prototype prototype; Prototype prototype;
Application app; Application app;
@ -22,12 +31,19 @@ public final class SkinFile implements Updatable {
Skin skin; Skin skin;
long lastmod = 0; long lastmod = 0;
public SkinFile (File file, String name, Prototype proto) { /**
this.prototype = proto; * Creates a new SkinFile object.
this.file = file; *
this.name = name; * @param file ...
this.app = proto.app; * @param name ...
skin = null; * @param proto ...
*/
public SkinFile(File file, String name, Prototype proto) {
this.prototype = proto;
this.file = file;
this.name = name;
this.app = proto.app;
skin = null;
} }
/** /**
@ -35,88 +51,113 @@ public final class SkinFile implements Updatable {
* Skins contained in zipped applications. The whole update mechanism is bypassed * Skins contained in zipped applications. The whole update mechanism is bypassed
* by immediately setting the skin member. * by immediately setting the skin member.
*/ */
public SkinFile (String body, String name, Prototype proto) { public SkinFile(String body, String name, Prototype proto) {
this.prototype = proto; this.prototype = proto;
this.app = proto.app; this.app = proto.app;
this.name = name; this.name = name;
this.file = null; this.file = null;
skin = new Skin (body, app); skin = new Skin(body, app);
} }
/** /**
* Create a skinfile that doesn't belong to a prototype, or at * Create a skinfile that doesn't belong to a prototype, or at
* least it doesn't know about its prototype and isn't managed by the prototype. * least it doesn't know about its prototype and isn't managed by the prototype.
*/ */
public SkinFile (File file, String name, Application app) { public SkinFile(File file, String name, Application app) {
this.app = app; this.app = app;
this.file = file; this.file = file;
this.name = name; this.name = name;
this.prototype = null; this.prototype = null;
skin = null; skin = null;
} }
/**
/**
* Tell the type manager whether we need an update. this is the case when * Tell the type manager whether we need an update. this is the case when
* the file has been modified or deleted. * the file has been modified or deleted.
*/ */
public boolean needsUpdate () { public boolean needsUpdate() {
// if skin object is null we only need to call update if the file doesn't // if skin object is null we only need to call update if the file doesn't
// exist anymore, while if the skin is initialized, we'll catch both // exist anymore, while if the skin is initialized, we'll catch both
// cases (file deleted and file changed) by just calling lastModified(). // cases (file deleted and file changed) by just calling lastModified().
return skin != null ? lastmod != file.lastModified () : !file.exists (); return (skin != null) ? (lastmod != file.lastModified()) : (!file.exists());
} }
/**
public void update () { *
if (!file.exists ()) { */
// remove skin from prototype public void update() {
remove (); if (!file.exists()) {
} else { // remove skin from prototype
// we only need to update if the skin has already been initialized remove();
if (skin != null) } else {
read (); // we only need to update if the skin has already been initialized
} if (skin != null) {
read();
}
}
} }
private void read () { private void read() {
try { try {
FileReader reader = new FileReader (file); FileReader reader = new FileReader(file);
char c[] = new char[(int) file.length()]; char[] c = new char[(int) file.length()];
int length = reader.read (c); int length = reader.read(c);
reader.close();
skin = new Skin (c, length, app); reader.close();
} catch (IOException x) { skin = new Skin(c, length, app);
app.logEvent ("Error reading Skin "+file+": "+x); } catch (IOException x) {
} app.logEvent("Error reading Skin " + file + ": " + x);
lastmod = file.lastModified (); }
lastmod = file.lastModified();
} }
public void remove () { /**
if (prototype != null) { *
prototype.removeSkinFile (this); */
} public void remove() {
if (prototype != null) {
prototype.removeSkinFile(this);
}
} }
/**
public File getFile () { *
return file; *
* @return ...
*/
public File getFile() {
return file;
} }
public Skin getSkin () { /**
if (skin == null) *
read (); *
return skin; * @return ...
*/
public Skin getSkin() {
if (skin == null) {
read();
}
return skin;
} }
public String getName () { /**
return name; *
*
* @return ...
*/
public String getName() {
return name;
} }
public String toString () { /**
return prototype.getName()+"/"+file.getName(); *
*
* @return ...
*/
public String toString() {
return prototype.getName() + "/" + file.getName();
} }
} }

View file

@ -1,107 +1,140 @@
// SkinManager.java /*
// Copyright (c) Hannes Wallnöfer 2002 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
import java.util.*;
import helma.objectmodel.INode; import helma.objectmodel.INode;
import java.io.*; import java.io.*;
import java.util.*;
/** /**
* Manages skins for a Helma application * Manages skins for a Helma application
*/ */
public final class SkinManager implements FilenameFilter { public final class SkinManager implements FilenameFilter {
Application app; Application app;
public SkinManager (Application app) { /**
this.app = app; * Creates a new SkinManager object.
*
* @param app ...
*/
public SkinManager(Application app) {
this.app = app;
} }
protected Skin getSkin(Prototype proto, String skinname, Object[] skinpath) {
if (proto == null) {
return null;
}
protected Skin getSkin (Prototype proto, String skinname, Object[] skinpath) { Skin skin = null;
if (proto == null)
return null; // First check if the skin has been already used within the execution of this request
Skin skin = null; // check for skinsets set via res.skinpath property
// First check if the skin has been already used within the execution of this request do {
// check for skinsets set via res.skinpath property if (skinpath != null) {
do { for (int i = 0; i < skinpath.length; i++) {
if (skinpath != null) { skin = getSkinInternal(skinpath[i], proto.getName(), skinname);
for (int i=0; i<skinpath.length; i++) {
skin = getSkinInternal (skinpath[i], proto.getName (), skinname); if (skin != null) {
if (skin != null) { return skin;
return skin; }
} }
} }
}
// skin for this prototype wasn't found in the skinsets. // skin for this prototype wasn't found in the skinsets.
// the next step is to look if it is defined as skin file in the application directory // the next step is to look if it is defined as skin file in the application directory
skin = proto.getSkin (skinname); skin = proto.getSkin(skinname);
if (skin != null) {
return skin; if (skin != null) {
} return skin;
// still not found. See if there is a parent prototype which might define the skin. }
proto = proto.getParentPrototype ();
} while (proto != null); // still not found. See if there is a parent prototype which might define the skin.
// looked every where, nothing to be found proto = proto.getParentPrototype();
return null; } while (proto != null);
// looked every where, nothing to be found
return null;
} }
protected Skin getSkinInternal(Object skinset, String prototype, String skinname) {
if ((prototype == null) || (skinset == null)) {
return null;
}
protected Skin getSkinInternal (Object skinset, String prototype, String skinname) { // check if the skinset object is a HopObject (db based skin)
if (prototype == null || skinset == null) // or a String (file based skin)
return null; if (skinset instanceof INode) {
// check if the skinset object is a HopObject (db based skin) INode n = ((INode) skinset).getNode(prototype);
// or a String (file based skin)
if (skinset instanceof INode) { if (n != null) {
INode n = ((INode) skinset).getNode (prototype); n = n.getNode(skinname);
if (n != null) {
n = n.getNode (skinname); if (n != null) {
if (n != null) { String skin = n.getString("skin");
String skin = n.getString ("skin");
if (skin != null) { if (skin != null) {
return new Skin (skin, app); return new Skin(skin, app);
} }
} }
} }
} else { } else {
// Skinset is interpreted as directory name from which to // Skinset is interpreted as directory name from which to
// retrieve the skin // retrieve the skin
File f = new File (skinset.toString (), prototype); File f = new File(skinset.toString(), prototype);
f = new File (f, skinname+".skin");
if (f.exists() && f.canRead()) { f = new File(f, skinname + ".skin");
SkinFile sf = new SkinFile (f, skinname, app);
return sf.getSkin (); if (f.exists() && f.canRead()) {
} SkinFile sf = new SkinFile(f, skinname, app);
}
// Inheritance is taken care of in the above getSkin method. return sf.getSkin();
// the sequence is prototype.skin-from-db, prototype.skin-from-file, parent.from-db, parent.from-file etc. }
return null; }
// Inheritance is taken care of in the above getSkin method.
// the sequence is prototype.skin-from-db, prototype.skin-from-file, parent.from-db, parent.from-file etc.
return null;
} }
protected Map getSkinFiles(String skinDir, Prototype proto) {
File dir = new File(skinDir.toString(), proto.getName());
String[] skinNames = dir.list(this);
protected Map getSkinFiles (String skinDir, Prototype proto) { if ((skinNames == null) || (skinNames.length == 0)) {
File dir = new File (skinDir.toString (), proto.getName ()); return null;
String[] skinNames = dir.list (this); }
if (skinNames == null || skinNames.length == 0)
return null; HashMap map = new HashMap();
HashMap map = new HashMap ();
for (int i=0; i<skinNames.length; i++) { for (int i = 0; i < skinNames.length; i++) {
String name = skinNames[i].substring (0, skinNames[i].length()-5); String name = skinNames[i].substring(0, skinNames[i].length() - 5);
File file = new File (dir, skinNames[i]); File file = new File(dir, skinNames[i]);
map.put (name, new SkinFile(file, name, proto));
} map.put(name, new SkinFile(file, name, proto));
return map; }
return map;
} }
/** /**
* Implements java.io.FilenameFilter.accept() * Implements java.io.FilenameFilter.accept()
*/ */
public boolean accept (File d, String n) { public boolean accept(File d, String n) {
return n.endsWith (".skin"); return n.endsWith(".skin");
} }
} }

View file

@ -1,5 +1,18 @@
// TypeManager.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
@ -7,224 +20,281 @@ import helma.objectmodel.*;
import helma.objectmodel.db.DbMapping; import helma.objectmodel.db.DbMapping;
import helma.scripting.*; import helma.scripting.*;
import helma.util.*; import helma.util.*;
import java.util.*;
import java.io.*; import java.io.*;
import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.net.MalformedURLException; import java.util.*;
/** /**
* The type manager periodically checks the prototype definitions for its * The type manager periodically checks the prototype definitions for its
* applications and updates the evaluators if anything has changed. * applications and updates the evaluators if anything has changed.
*/ */
public final class TypeManager { public final class TypeManager {
final static String[] standardTypes = { "user", "global", "root", "hopobject" };
final static String templateExtension = ".hsp";
final static String scriptExtension = ".js";
final static String actionExtension = ".hac";
final static String skinExtension = ".skin";
Application app; Application app;
File appDir; File appDir;
HashMap prototypes; // map of prototypes HashMap prototypes; // map of prototypes
HashMap zipfiles; // map of zipped script files HashMap zipfiles; // map of zipped script files
HashSet jarfiles; // set of Java archives HashSet jarfiles; // set of Java archives
long lastCheck = 0; long lastCheck = 0;
long appDirMod = 0; long appDirMod = 0;
// a checksum that changes whenever something in the application files changes. // a checksum that changes whenever something in the application files changes.
long checksum; long checksum;
// the hopobject prototype // the hopobject prototype
Prototype hopobjectProto; Prototype hopobjectProto;
// the global prototype // the global prototype
Prototype globalProto; Prototype globalProto;
// app specific class loader, includes jar files in the app directory // app specific class loader, includes jar files in the app directory
AppClassLoader loader; AppClassLoader loader;
final static String[] standardTypes = {"user", "global", "root", "hopobject"}; /**
* Creates a new TypeManager object.
final static String templateExtension = ".hsp"; *
final static String scriptExtension = ".js"; * @param app ...
final static String actionExtension = ".hac"; *
final static String skinExtension = ".skin"; * @throws MalformedURLException ...
* @throws RuntimeException ...
public TypeManager (Application app) throws MalformedURLException { */
public TypeManager(Application app) throws MalformedURLException {
this.app = app; this.app = app;
appDir = app.appDir; appDir = app.appDir;
// make sure the directories for the standard prototypes exist, and lament otherwise // make sure the directories for the standard prototypes exist, and lament otherwise
if (appDir.list().length == 0) { if (appDir.list().length == 0) {
for (int i=0; i<standardTypes.length; i++) { for (int i = 0; i < standardTypes.length; i++) {
File f = new File (appDir, standardTypes[i]); File f = new File(appDir, standardTypes[i]);
if (!f.exists() && !f.mkdir ())
app.logEvent ("Warning: directory "+f.getAbsolutePath ()+" could not be created."); if (!f.exists() && !f.mkdir()) {
else if (!f.isDirectory ()) app.logEvent("Warning: directory " + f.getAbsolutePath() +
app.logEvent ("Warning: "+f.getAbsolutePath ()+" is not a directory."); " could not be created.");
} else if (!f.isDirectory()) {
app.logEvent("Warning: " + f.getAbsolutePath() +
" is not a directory.");
}
} }
} }
prototypes = new HashMap ();
zipfiles = new HashMap (); prototypes = new HashMap();
jarfiles = new HashSet (); zipfiles = new HashMap();
jarfiles = new HashSet();
URL[] urls = ((URLClassLoader) TypeManager.class.getClassLoader()).getURLs(); URL[] urls = ((URLClassLoader) TypeManager.class.getClassLoader()).getURLs();
URL helmajar = null; URL helmajar = null;
for (int i=0; i<urls.length; i++) {
for (int i = 0; i < urls.length; i++) {
String url = urls[i].toString().toLowerCase(); String url = urls[i].toString().toLowerCase();
if (url.endsWith ("helma.jar")) {
if (url.endsWith("helma.jar")) {
helmajar = urls[i]; helmajar = urls[i];
break; break;
} }
} }
if (helmajar == null)
throw new RuntimeException ("helma.jar not found in embedding classpath"); if (helmajar == null) {
throw new RuntimeException("helma.jar not found in embedding classpath");
}
loader = new AppClassLoader(app.getName(), new URL[] { helmajar }); loader = new AppClassLoader(app.getName(), new URL[] { helmajar });
} }
/** /**
* Run through application's prototype directories and create prototypes, but don't * Run through application's prototype directories and create prototypes, but don't
* compile or evaluate any scripts. * compile or evaluate any scripts.
*/ */
public void createPrototypes () { public void createPrototypes() {
// create standard prototypes. // create standard prototypes.
createPrototype ("root"); createPrototype("root");
createPrototype ("user"); createPrototype("user");
// get references to hopobject and global protos, // get references to hopobject and global protos,
// since we need it regularly when setting parent prototypes. // since we need it regularly when setting parent prototypes.
hopobjectProto = createPrototype ("hopobject"); hopobjectProto = createPrototype("hopobject");
globalProto = createPrototype ("global"); globalProto = createPrototype("global");
// loop through directories and create prototypes
checkFiles ();
}
// loop through directories and create prototypes
checkFiles();
}
/** /**
* Run through application's prototype directories and check if anything has been updated. * Run through application's prototype directories and check if anything has been updated.
* If so, update prototypes and scripts. * If so, update prototypes and scripts.
*/ */
public synchronized void checkPrototypes () { public synchronized void checkPrototypes() {
if (System.currentTimeMillis () - lastCheck < 1000l) if ((System.currentTimeMillis() - lastCheck) < 1000L) {
return; return;
try { }
checkFiles ();
} catch (Exception ignore) {} try {
lastCheck = System.currentTimeMillis (); checkFiles();
} catch (Exception ignore) {
}
lastCheck = System.currentTimeMillis();
} }
/** /**
* Run through application's prototype directories and check if * Run through application's prototype directories and check if
* there are any prototypes to be created. * there are any prototypes to be created.
*/ */
public void checkFiles () { public void checkFiles() {
// check if any files have been created/removed since last time we // check if any files have been created/removed since last time we
// checked... // checked...
if (appDir.lastModified() > appDirMod) { if (appDir.lastModified() > appDirMod) {
appDirMod = appDir.lastModified (); appDirMod = appDir.lastModified();
String[] list = appDir.list ();
if (list == null)
throw new RuntimeException ("Can't read app directory "+appDir+" - check permissions");
for (int i=0; i<list.length; i++) {
if (list[i].endsWith (".zip")) {
ZippedAppFile zipped = (ZippedAppFile) zipfiles.get (list[i]);
if (zipped == null) {
File f = new File (appDir, list[i]);
if (!f.isDirectory ()) {
zipped = new ZippedAppFile (f, app);
zipfiles.put (list[i], zipped);
}
}
continue;
}
if (list[i].endsWith (".jar")) {
if (!jarfiles.contains (list[i])) {
jarfiles.add (list[i]);
File f = new File (appDir, list[i]);
try {
loader.addURL (new URL ("file:"+f.getAbsolutePath()));
} catch (MalformedURLException ignore) {}
}
continue;
}
if (list[i].indexOf ('.') > -1)
continue;
Prototype proto = getPrototype (list[i]);
// if prototype doesn't exist, create it
if (proto == null && isValidTypeName (list[i])) {
File f = new File (appDir, list[i]);
if (f.isDirectory ()) {
// create new prototype
createPrototype (list[i], f);
}
}
}
}
// calculate this app's checksum by adding all checksums from all prototypes String[] list = appDir.list();
long newChecksum = 0;
// loop through zip files to check for updates if (list == null) {
for (Iterator it=zipfiles.values ().iterator (); it.hasNext (); ) { throw new RuntimeException("Can't read app directory " + appDir +
ZippedAppFile zipped = (ZippedAppFile) it.next (); " - check permissions");
if (zipped.needsUpdate ()) { }
zipped.update ();
}
newChecksum += zipped.lastmod;
}
// loop through prototypes and check if type.properties needs updates for (int i = 0; i < list.length; i++) {
// it's important that we do this _after_ potentially new prototypes if (list[i].endsWith(".zip")) {
// have been created in the previous loop. ZippedAppFile zipped = (ZippedAppFile) zipfiles.get(list[i]);
for (Iterator i=prototypes.values().iterator(); i.hasNext(); ) {
Prototype proto = (Prototype) i.next (); if (zipped == null) {
// calculate this app's type checksum File f = new File(appDir, list[i]);
newChecksum += proto.getChecksum();
// update prototype's type mapping if (!f.isDirectory()) {
DbMapping dbmap = proto.getDbMapping (); zipped = new ZippedAppFile(f, app);
if (dbmap != null && dbmap.needsUpdate ()) { zipfiles.put(list[i], zipped);
dbmap.update (); }
if (proto != hopobjectProto && proto != globalProto) { }
// set parent prototype, in case it has changed.
String parentName = dbmap.getExtends (); continue;
if (parentName != null) }
proto.setParentPrototype (getPrototype (parentName));
else if (!app.isJavaPrototype (proto.getName())) if (list[i].endsWith(".jar")) {
proto.setParentPrototype (hopobjectProto); if (!jarfiles.contains(list[i])) {
} jarfiles.add(list[i]);
}
} File f = new File(appDir, list[i]);
checksum = newChecksum;
try {
loader.addURL(new URL("file:" + f.getAbsolutePath()));
} catch (MalformedURLException ignore) {
}
}
continue;
}
if (list[i].indexOf('.') > -1) {
continue;
}
Prototype proto = getPrototype(list[i]);
// if prototype doesn't exist, create it
if ((proto == null) && isValidTypeName(list[i])) {
File f = new File(appDir, list[i]);
if (f.isDirectory()) {
// create new prototype
createPrototype(list[i], f);
}
}
}
}
// calculate this app's checksum by adding all checksums from all prototypes
long newChecksum = 0;
// loop through zip files to check for updates
for (Iterator it = zipfiles.values().iterator(); it.hasNext();) {
ZippedAppFile zipped = (ZippedAppFile) it.next();
if (zipped.needsUpdate()) {
zipped.update();
}
newChecksum += zipped.lastmod;
}
// loop through prototypes and check if type.properties needs updates
// it's important that we do this _after_ potentially new prototypes
// have been created in the previous loop.
for (Iterator i = prototypes.values().iterator(); i.hasNext();) {
Prototype proto = (Prototype) i.next();
// calculate this app's type checksum
newChecksum += proto.getChecksum();
// update prototype's type mapping
DbMapping dbmap = proto.getDbMapping();
if ((dbmap != null) && dbmap.needsUpdate()) {
dbmap.update();
if ((proto != hopobjectProto) && (proto != globalProto)) {
// set parent prototype, in case it has changed.
String parentName = dbmap.getExtends();
if (parentName != null) {
proto.setParentPrototype(getPrototype(parentName));
} else if (!app.isJavaPrototype(proto.getName())) {
proto.setParentPrototype(hopobjectProto);
}
}
}
}
checksum = newChecksum;
} }
protected void removeZipFile (String zipname) { protected void removeZipFile(String zipname) {
zipfiles.remove (zipname); zipfiles.remove(zipname);
for (Iterator i=prototypes.values().iterator(); i.hasNext(); ) {
Prototype proto = (Prototype) i.next (); for (Iterator i = prototypes.values().iterator(); i.hasNext();) {
// update prototype's type mapping Prototype proto = (Prototype) i.next();
DbMapping dbmap = proto.getDbMapping ();
SystemProperties props = dbmap.getProperties(); // update prototype's type mapping
props.removeProps (zipname); DbMapping dbmap = proto.getDbMapping();
} SystemProperties props = dbmap.getProperties();
props.removeProps(zipname);
}
} }
private boolean isValidTypeName(String str) {
if (str == null) {
return false;
}
private boolean isValidTypeName (String str) { char[] c = str.toCharArray();
if (str == null)
return false;
char[] c = str.toCharArray ();
for (int i=0; i<c.length; i++)
if (!Character.isJavaIdentifierPart (c[i]))
return false;
return true;
}
/** for (int i = 0; i < c.length; i++)
* Return a checksum over all files in all prototypes in this application. if (!Character.isJavaIdentifierPart(c[i])) {
* The checksum can be used to find out quickly if any file has changed. return false;
*/ }
public long getChecksum () {
return checksum; return true;
} }
/** /**
* Get a prototype defined for this application * Return a checksum over all files in all prototypes in this application.
*/ * The checksum can be used to find out quickly if any file has changed.
public Prototype getPrototype (String typename) { */
return (Prototype) prototypes.get (typename); public long getChecksum() {
return checksum;
}
/**
* Get a prototype defined for this application
*/
public Prototype getPrototype(String typename) {
return (Prototype) prototypes.get(typename);
} }
/** /**
@ -232,152 +302,167 @@ public final class TypeManager {
* that it doesn't create a DbMapping - this is left to the * that it doesn't create a DbMapping - this is left to the
* caller (e.g. ZippedAppFile). * caller (e.g. ZippedAppFile).
*/ */
public Prototype createPrototype (String typename) { public Prototype createPrototype(String typename) {
return createPrototype (typename, new File (appDir, typename)); return createPrototype(typename, new File(appDir, typename));
} }
/** /**
* Create a prototype from a directory containing scripts and other stuff * Create a prototype from a directory containing scripts and other stuff
*/ */
public Prototype createPrototype (String typename, File dir) { public Prototype createPrototype(String typename, File dir) {
Prototype proto = new Prototype (typename, dir, app); Prototype proto = new Prototype(typename, dir, app);
// Create and register type properties file
File propfile = new File (dir, "type.properties"); // Create and register type properties file
SystemProperties props = new SystemProperties (propfile.getAbsolutePath ()); File propfile = new File(dir, "type.properties");
DbMapping dbmap = new DbMapping (app, typename, props); SystemProperties props = new SystemProperties(propfile.getAbsolutePath());
// we don't need to put the DbMapping into proto.updatables, because DbMapping dbmap = new DbMapping(app, typename, props);
// dbmappings are checked separately in checkFiles for each request
// proto.updatables.put ("type.properties", dbmap); // we don't need to put the DbMapping into proto.updatables, because
proto.setDbMapping (dbmap); // dbmappings are checked separately in checkFiles for each request
// put the prototype into our map // proto.updatables.put ("type.properties", dbmap);
prototypes.put (typename, proto); proto.setDbMapping(dbmap);
return proto;
// put the prototype into our map
prototypes.put(typename, proto);
return proto;
} }
/** /**
* Update a prototype to the files in the prototype directory. * Update a prototype to the files in the prototype directory.
*/ */
public void updatePrototype (String name) { public void updatePrototype(String name) {
// System.err.println ("UPDATE PROTO: "+app.getName()+"/"+name); // System.err.println ("UPDATE PROTO: "+app.getName()+"/"+name);
Prototype proto = getPrototype (name); Prototype proto = getPrototype(name);
updatePrototype (proto);
updatePrototype(proto);
} }
/** /**
* Update a prototype to the files in the prototype directory. * Update a prototype to the files in the prototype directory.
*/ */
public void updatePrototype (Prototype proto) { public void updatePrototype(Prototype proto) {
if (proto == null || proto.isUpToDate()) if ((proto == null) || proto.isUpToDate()) {
return; return;
}
synchronized (proto) { synchronized (proto) {
// check again because another thread may have checked the // check again because another thread may have checked the
// prototype while we were waiting for access to the synchronized section // prototype while we were waiting for access to the synchronized section
/* if (System.currentTimeMillis() - proto.getLastCheck() < 1000)
return; */
File dir = proto.getDirectory (); /* if (System.currentTimeMillis() - proto.getLastCheck() < 1000)
return; */
File dir = proto.getDirectory();
HashSet updateSet = null; HashSet updateSet = null;
HashSet createSet = null; HashSet createSet = null;
// our plan is to do as little as possible, so first check if // our plan is to do as little as possible, so first check if
// anything the prototype knows about has changed on disk // anything the prototype knows about has changed on disk
for (Iterator i = proto.updatables.values().iterator(); i.hasNext(); ) { for (Iterator i = proto.updatables.values().iterator(); i.hasNext();) {
Updatable upd = (Updatable) i.next(); Updatable upd = (Updatable) i.next();
if (upd.needsUpdate ()) {
if (updateSet == null) if (upd.needsUpdate()) {
updateSet = new HashSet (); if (updateSet == null) {
updateSet.add (upd); updateSet = new HashSet();
}
updateSet.add(upd);
} }
} }
// next we check if files have been created or removed since last update // next we check if files have been created or removed since last update
// if (proto.getLastCheck() < dir.lastModified ()) { // if (proto.getLastCheck() < dir.lastModified ()) {
File[] list = proto.getFiles(); File[] list = proto.getFiles();
for (int i=0; i<list.length; i++) {
String fn = list[i].getName(); for (int i = 0; i < list.length; i++) {
if (!proto.updatables.containsKey (fn)) { String fn = list[i].getName();
if (fn.endsWith (templateExtension) ||
fn.endsWith (scriptExtension) || if (!proto.updatables.containsKey(fn)) {
fn.endsWith (actionExtension) || if (fn.endsWith(templateExtension) || fn.endsWith(scriptExtension) ||
fn.endsWith (skinExtension) || fn.endsWith(actionExtension) || fn.endsWith(skinExtension) ||
"type.properties".equalsIgnoreCase (fn)) "type.properties".equalsIgnoreCase(fn)) {
{ if (createSet == null) {
if (createSet == null) createSet = new HashSet();
createSet = new HashSet ();
createSet.add (list[i]);
} }
createSet.add(list[i]);
} }
} }
// } }
// }
// if nothing needs to be updated, mark prototype as checked and return // if nothing needs to be updated, mark prototype as checked and return
if (updateSet == null && createSet == null) { if ((updateSet == null) && (createSet == null)) {
proto.markChecked (); proto.markChecked();
return; return;
} }
// first go through new files and create new items // first go through new files and create new items
if (createSet != null) { if (createSet != null) {
Object[] newFiles = createSet.toArray (); Object[] newFiles = createSet.toArray();
for (int i=0; i<newFiles.length; i++) {
for (int i = 0; i < newFiles.length; i++) {
File file = (File) newFiles[i]; File file = (File) newFiles[i];
String filename = file.getName (); String filename = file.getName();
int dot = filename.lastIndexOf ("."); int dot = filename.lastIndexOf(".");
String tmpname = filename.substring(0, dot); String tmpname = filename.substring(0, dot);
if (filename.endsWith (templateExtension)) { if (filename.endsWith(templateExtension)) {
try { try {
Template t = new Template (file, tmpname, proto); Template t = new Template(file, tmpname, proto);
proto.addTemplate (t);
proto.addTemplate(t);
} catch (Throwable x) { } catch (Throwable x) {
app.logEvent ("Error updating prototype: "+x); app.logEvent("Error updating prototype: " + x);
} }
} else if (filename.endsWith (scriptExtension)) { } else if (filename.endsWith(scriptExtension)) {
try { try {
FunctionFile ff = new FunctionFile (file, proto); FunctionFile ff = new FunctionFile(file, proto);
proto.addFunctionFile (ff);
proto.addFunctionFile(ff);
} catch (Throwable x) { } catch (Throwable x) {
app.logEvent ("Error updating prototype: "+x); app.logEvent("Error updating prototype: " + x);
} }
} else if (filename.endsWith (actionExtension)) { } else if (filename.endsWith(actionExtension)) {
try { try {
ActionFile af = new ActionFile (file, tmpname, proto); ActionFile af = new ActionFile(file, tmpname, proto);
proto.addActionFile (af);
proto.addActionFile(af);
} catch (Throwable x) { } catch (Throwable x) {
app.logEvent ("Error updating prototype: "+x); app.logEvent("Error updating prototype: " + x);
} }
} else if (filename.endsWith (skinExtension)) { } else if (filename.endsWith(skinExtension)) {
SkinFile sf = new SkinFile (file, tmpname, proto); SkinFile sf = new SkinFile(file, tmpname, proto);
proto.addSkinFile (sf);
proto.addSkinFile(sf);
} }
} }
} }
// next go through existing updatables // next go through existing updatables
if (updateSet != null) { if (updateSet != null) {
for (Iterator i = updateSet.iterator(); i.hasNext(); ) { for (Iterator i = updateSet.iterator(); i.hasNext();) {
Updatable upd = (Updatable) i.next(); Updatable upd = (Updatable) i.next();
try { try {
upd.update (); upd.update();
} catch (Exception x) { } catch (Exception x) {
if (upd instanceof DbMapping) if (upd instanceof DbMapping) {
app.logEvent ("Error updating db mapping for type "+proto.getName()+": "+x); app.logEvent("Error updating db mapping for type " +
else proto.getName() + ": " + x);
app.logEvent ("Error updating "+upd+" of prototye type "+proto.getName()+": "+x); } else {
app.logEvent("Error updating " + upd + " of prototye type " +
proto.getName() + ": " + x);
}
} }
} }
} }
// mark prototype as checked and updated. // mark prototype as checked and updated.
proto.markChecked (); proto.markChecked();
proto.markUpdated(); proto.markUpdated();
}
} // end of synchronized (proto) // end of synchronized (proto)
} }
} }

View file

@ -1,160 +1,208 @@
// ZippedFile.java /*
// Copyright (c) Hannes Wallnöfer 2001 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.framework.core; package helma.framework.core;
import helma.framework.*;
import helma.objectmodel.db.DbMapping;
import helma.scripting.*;
import helma.util.SystemProperties;
import helma.util.Updatable;
import java.io.*;
import java.util.*; import java.util.*;
import java.util.zip.*; import java.util.zip.*;
import java.io.*;
import helma.framework.*;
import helma.scripting.*;
import helma.util.Updatable;
import helma.util.SystemProperties;
import helma.objectmodel.db.DbMapping;
/** /**
* This represents a Zip-File which may contain other Updatables for one or more prototypes. * This represents a Zip-File which may contain other Updatables for one or more prototypes.
*/ */
public class ZippedAppFile implements Updatable { public class ZippedAppFile implements Updatable {
Application app; Application app;
File file; File file;
long lastmod; long lastmod;
Set updatables; Set updatables;
/**
* Creates a new ZippedAppFile object.
*
* @param file ...
* @param app ...
*/
public ZippedAppFile(File file, Application app) {
this.app = app;
this.file = file;
public ZippedAppFile (File file, Application app) { // System.err.println ("CREATING ZIP FILE "+this);
this.app = app;
this.file = file;
// System.err.println ("CREATING ZIP FILE "+this);
} }
/** /**
* Tell the type manager whether we need an update. this is the case when * Tell the type manager whether we need an update. this is the case when
* the file has been modified or deleted. * the file has been modified or deleted.
*/ */
public boolean needsUpdate () { public boolean needsUpdate() {
return !file.exists () || lastmod != file.lastModified (); return !file.exists() || (lastmod != file.lastModified());
} }
/**
*
*/
public void update() {
if (!file.exists()) {
remove();
} else {
ZipFile zip = null;
public void update () { // collect created protos - we need this to check DbMappings for each created
// prototype afterwards
HashSet newPrototypes = new HashSet();
if (!file.exists ()) { try {
remove (); lastmod = file.lastModified();
} else { // System.err.println ("UPDATING ZIP FILE "+this);
zip = new ZipFile(file);
updatables = new HashSet();
ZipFile zip = null; for (Enumeration en = zip.entries(); en.hasMoreElements();) {
// collect created protos - we need this to check DbMappings for each created ZipEntry entry = (ZipEntry) en.nextElement();
// prototype afterwards String ename = entry.getName();
HashSet newPrototypes = new HashSet (); StringTokenizer st = new StringTokenizer(ename, "/");
try {
lastmod = file.lastModified ();
// System.err.println ("UPDATING ZIP FILE "+this);
zip = new ZipFile (file);
updatables = new HashSet ();
for (Enumeration en = zip.entries (); en.hasMoreElements (); ) {
ZipEntry entry = (ZipEntry) en.nextElement ();
String ename = entry.getName ();
StringTokenizer st = new StringTokenizer (ename, "/");
if (st.countTokens () == 2) {
String dir = st.nextToken ();
String fname = st.nextToken ();
// System.err.println ("ZIPENTRY: "+ dir +" ~ "+fname);
Prototype proto = app.typemgr.getPrototype (dir);
if (proto == null) {
proto = app.typemgr.createPrototype (dir);
newPrototypes.add (proto);
}
if (fname.endsWith (".hac")) {
String name = fname.substring (0, fname.lastIndexOf ("."));
String sourceName = file.getName()+"/"+ename;
String content = getZipEntryContent (zip, entry);
// System.err.println ("["+content+"]");
ActionFile act = new ActionFile (content, name, sourceName, proto);
proto.addActionFile (act);
updatables.add (act);
// mark prototype as updated
proto.markUpdated ();
}
else if (fname.endsWith (".hsp")) {
String name = fname.substring (0, fname.lastIndexOf ("."));
String sourceName = file.getName()+"/"+ename;
String content = getZipEntryContent (zip, entry);
// System.err.println ("["+content+"]");
Template tmp = new Template (content, name, sourceName, proto);
proto.addTemplate (tmp);
updatables.add (tmp);
// mark prototype as updated
proto.markUpdated ();
}
else if (fname.endsWith (".skin")) {
String name = fname.substring (0, fname.lastIndexOf ("."));
String content = getZipEntryContent (zip, entry);
// System.err.println ("["+content+"]");
SkinFile skin = new SkinFile (content, name, proto);
proto.addSkinFile (skin);
updatables.add (skin);
}
else if (fname.endsWith (".js")) {
String sourceName = file.getName()+"/"+ename;
String content = getZipEntryContent (zip, entry);
// System.err.println ("["+content+"]");
FunctionFile ff = new FunctionFile (content, sourceName, proto);
proto.addFunctionFile (ff);
updatables.add (ff);
// mark prototype as updated
proto.markUpdated ();
}
else if ("type.properties".equalsIgnoreCase (fname)) {
DbMapping dbmap = proto.getDbMapping ();
SystemProperties props = dbmap.getProperties ();
props.addProps (file.getName(), zip.getInputStream (entry));
// mark prototype as updated
proto.markUpdated ();
}
}
}
} catch (Throwable x) {
System.err.println ("Error updating ZipFile: "+x);
} finally {
try {
zip.close ();
} catch (Exception ignore) {}
}
}
if (st.countTokens() == 2) {
String dir = st.nextToken();
String fname = st.nextToken();
// System.err.println ("ZIPENTRY: "+ dir +" ~ "+fname);
Prototype proto = app.typemgr.getPrototype(dir);
if (proto == null) {
proto = app.typemgr.createPrototype(dir);
newPrototypes.add(proto);
}
if (fname.endsWith(".hac")) {
String name = fname.substring(0, fname.lastIndexOf("."));
String sourceName = file.getName() + "/" + ename;
String content = getZipEntryContent(zip, entry);
// System.err.println ("["+content+"]");
ActionFile act = new ActionFile(content, name, sourceName,
proto);
proto.addActionFile(act);
updatables.add(act);
// mark prototype as updated
proto.markUpdated();
} else if (fname.endsWith(".hsp")) {
String name = fname.substring(0, fname.lastIndexOf("."));
String sourceName = file.getName() + "/" + ename;
String content = getZipEntryContent(zip, entry);
// System.err.println ("["+content+"]");
Template tmp = new Template(content, name, sourceName, proto);
proto.addTemplate(tmp);
updatables.add(tmp);
// mark prototype as updated
proto.markUpdated();
} else if (fname.endsWith(".skin")) {
String name = fname.substring(0, fname.lastIndexOf("."));
String content = getZipEntryContent(zip, entry);
// System.err.println ("["+content+"]");
SkinFile skin = new SkinFile(content, name, proto);
proto.addSkinFile(skin);
updatables.add(skin);
} else if (fname.endsWith(".js")) {
String sourceName = file.getName() + "/" + ename;
String content = getZipEntryContent(zip, entry);
// System.err.println ("["+content+"]");
FunctionFile ff = new FunctionFile(content, sourceName, proto);
proto.addFunctionFile(ff);
updatables.add(ff);
// mark prototype as updated
proto.markUpdated();
} else if ("type.properties".equalsIgnoreCase(fname)) {
DbMapping dbmap = proto.getDbMapping();
SystemProperties props = dbmap.getProperties();
props.addProps(file.getName(), zip.getInputStream(entry));
// mark prototype as updated
proto.markUpdated();
}
}
}
} catch (Throwable x) {
System.err.println("Error updating ZipFile: " + x);
} finally {
try {
zip.close();
} catch (Exception ignore) {
}
}
}
} }
public void remove () { /**
if (updatables != null) { *
for (Iterator it = updatables.iterator(); it.hasNext(); ) */
((Updatable) it.next()).remove (); public void remove() {
} if (updatables != null) {
app.typemgr.removeZipFile (file.getName()); for (Iterator it = updatables.iterator(); it.hasNext();)
// System.err.println ("REMOVING ZIP FILE "+this); ((Updatable) it.next()).remove();
}
app.typemgr.removeZipFile(file.getName());
// System.err.println ("REMOVING ZIP FILE "+this);
} }
/**
*
*
* @param zip ...
* @param entry ...
*
* @return ...
*
* @throws IOException ...
*/
public String getZipEntryContent(ZipFile zip, ZipEntry entry)
throws IOException {
int size = (int) entry.getSize();
char[] c = new char[size];
InputStreamReader reader = new InputStreamReader(zip.getInputStream(entry));
public String getZipEntryContent (ZipFile zip, ZipEntry entry) throws IOException { reader.read(c);
int size = (int) entry.getSize ();
char[] c = new char[size]; return new String(c);
InputStreamReader reader = new InputStreamReader (zip.getInputStream (entry));
reader.read (c);
return new String (c);
} }
/**
public String toString () { *
return file.getName(); *
* @return ...
*/
public String toString() {
return file.getName();
} }
} }

View file

@ -1,198 +1,295 @@
// ImageGenerator.java /*
// Copyright (c) Hannes Wallnöfer 1999-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.image; package helma.image;
import java.awt.*; import java.awt.*;
import java.awt.image.*; import java.awt.image.*;
import java.net.URL;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL;
/** /**
* Factory class for generating Image objects from various sources. * Factory class for generating Image objects from various sources.
* *
*/ */
public class ImageGenerator { public class ImageGenerator {
/**
public ImageGenerator () { * Creates a new ImageGenerator object.
// nothing to do */
public ImageGenerator() {
// nothing to do
} }
public ImageWrapper createPaintableImage (int w, int h) { /**
BufferedImage img = new BufferedImage (w, h, BufferedImage.TYPE_INT_RGB); *
Graphics g = img.getGraphics (); *
ImageWrapper rimg = new SunImageWrapper (img, g, w, h, this); * @param w ...
return rimg; * @param h ...
*
* @return ...
*/
public ImageWrapper createPaintableImage(int w, int h) {
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
ImageWrapper rimg = new SunImageWrapper(img, g, w, h, this);
return rimg;
} }
public ImageWrapper createPaintableImage (byte src[]) { /**
ImageWrapper rimg = null; *
Image img1 = Toolkit.getDefaultToolkit ().createImage (src); *
ImageLoader loader = new ImageLoader (img1); * @param src ...
try { *
loader.getDimensions (); * @return ...
int w = loader.getWidth (); */
int h = loader.getHeight (); public ImageWrapper createPaintableImage(byte[] src) {
Image img = new BufferedImage (w, h, BufferedImage.TYPE_INT_RGB); ImageWrapper rimg = null;
Graphics g = img.getGraphics (); Image img1 = Toolkit.getDefaultToolkit().createImage(src);
g.drawImage (img1, 0, 0, null); ImageLoader loader = new ImageLoader(img1);
rimg = new SunImageWrapper (img, g, w, h, this);
} finally {
loader.done();
}
return rimg;
}
public ImageWrapper createImage (byte src[]) { try {
ImageWrapper rimg = null; loader.getDimensions();
Image img = Toolkit.getDefaultToolkit ().createImage (src);
ImageLoader loader = new ImageLoader (img);
try {
loader.getDimensions ();
int w = loader.getWidth ();
int h = loader.getHeight ();
rimg = new SunImageWrapper (img, null, w, h, this);
} finally {
loader.done();
}
return rimg;
}
int w = loader.getWidth();
int h = loader.getHeight();
Image img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
public ImageWrapper createPaintableImage (String urlstring) throws MalformedURLException { g.drawImage(img1, 0, 0, null);
ImageWrapper rimg = null; rimg = new SunImageWrapper(img, g, w, h, this);
URL url = new URL (urlstring); } finally {
Image img1 = Toolkit.getDefaultToolkit ().createImage (url);
ImageLoader loader = new ImageLoader (img1);
try {
loader.getDimensions ();
int w = loader.getWidth ();
int h = loader.getHeight ();
Image img = new BufferedImage (w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics ();
g.drawImage (img1, 0, 0, null);
rimg = new SunImageWrapper (img, g, w, h, this);
} finally {
loader.done(); loader.done();
} }
return rimg;
return rimg;
} }
public ImageWrapper createPaintableImage (ImageWrapper iw, ImageFilter filter) { /**
ImageWrapper rimg = null; *
FilteredImageSource fis = new FilteredImageSource (iw.getSource(), filter); *
Image img1 = Toolkit.getDefaultToolkit().createImage (fis); * @param src ...
ImageLoader loader = new ImageLoader (img1); *
try { * @return ...
loader.getDimensions (); */
int w = loader.getWidth (); public ImageWrapper createImage(byte[] src) {
int h = loader.getHeight (); ImageWrapper rimg = null;
Image img = new BufferedImage (w, h, BufferedImage.TYPE_INT_RGB); Image img = Toolkit.getDefaultToolkit().createImage(src);
Graphics g = img.getGraphics (); ImageLoader loader = new ImageLoader(img);
g.drawImage (img1, 0, 0, null);
rimg = new SunImageWrapper (img, g, w, h, this); try {
} finally { loader.getDimensions();
int w = loader.getWidth();
int h = loader.getHeight();
rimg = new SunImageWrapper(img, null, w, h, this);
} finally {
loader.done(); loader.done();
} }
return rimg;
return rimg;
} }
/**
*
*
* @param urlstring ...
*
* @return ...
*
* @throws MalformedURLException ...
*/
public ImageWrapper createPaintableImage(String urlstring)
throws MalformedURLException {
ImageWrapper rimg = null;
URL url = new URL(urlstring);
Image img1 = Toolkit.getDefaultToolkit().createImage(url);
ImageLoader loader = new ImageLoader(img1);
public Image createImage (String filename) { try {
Image img = null; loader.getDimensions();
img = Toolkit.getDefaultToolkit ().createImage (filename);
ImageLoader loader = new ImageLoader (img); int w = loader.getWidth();
loader.getDimensions (); int h = loader.getHeight();
loader.done(); Image img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
return img; Graphics g = img.getGraphics();
g.drawImage(img1, 0, 0, null);
rimg = new SunImageWrapper(img, g, w, h, this);
} finally {
loader.done();
}
return rimg;
} }
public Image createImage (ImageProducer producer) { /**
Image img = null; *
img = Toolkit.getDefaultToolkit ().createImage (producer); *
ImageLoader loader = new ImageLoader (img); * @param iw ...
loader.getDimensions (); * @param filter ...
loader.done(); *
return img; * @return ...
*/
public ImageWrapper createPaintableImage(ImageWrapper iw, ImageFilter filter) {
ImageWrapper rimg = null;
FilteredImageSource fis = new FilteredImageSource(iw.getSource(), filter);
Image img1 = Toolkit.getDefaultToolkit().createImage(fis);
ImageLoader loader = new ImageLoader(img1);
try {
loader.getDimensions();
int w = loader.getWidth();
int h = loader.getHeight();
Image img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.drawImage(img1, 0, 0, null);
rimg = new SunImageWrapper(img, g, w, h, this);
} finally {
loader.done();
}
return rimg;
}
/**
*
*
* @param filename ...
*
* @return ...
*/
public Image createImage(String filename) {
Image img = null;
img = Toolkit.getDefaultToolkit().createImage(filename);
ImageLoader loader = new ImageLoader(img);
loader.getDimensions();
loader.done();
return img;
}
/**
*
*
* @param producer ...
*
* @return ...
*/
public Image createImage(ImageProducer producer) {
Image img = null;
img = Toolkit.getDefaultToolkit().createImage(producer);
ImageLoader loader = new ImageLoader(img);
loader.getDimensions();
loader.done();
return img;
} }
class ImageLoader implements ImageObserver { class ImageLoader implements ImageObserver {
Image img;
int w;
int h;
boolean waiting;
boolean firstFrameLoaded;
Image img; ImageLoader(Image img) {
int w, h; this.img = img;
boolean waiting; waiting = true;
boolean firstFrameLoaded; firstFrameLoaded = false;
}
ImageLoader (Image img) { synchronized void getDimensions() {
this.img = img; w = img.getWidth(this);
waiting = true; h = img.getHeight(this);
firstFrameLoaded = false;
}
synchronized void getDimensions () { if ((w == -1) || (h == -1)) {
w = img.getWidth(this); try {
h = img.getHeight (this); wait(45000);
if (w == -1 || h == -1) { } catch (InterruptedException x) {
try { waiting = false;
wait (45000);
} catch (InterruptedException x) {
waiting = false;
return;
} finally {
waiting = false;
}
}
// if width and height haven't been set, throw tantrum
if (w == -1 || h == -1) {
throw new RuntimeException ("Error loading image");
}
}
synchronized void done () { return;
waiting = false; } finally {
notifyAll (); waiting = false;
} }
}
int getWidth () { // if width and height haven't been set, throw tantrum
return w; if ((w == -1) || (h == -1)) {
} throw new RuntimeException("Error loading image");
}
}
int getHeight () { synchronized void done() {
return h; waiting = false;
} notifyAll();
}
public synchronized boolean imageUpdate(Image img, int getWidth() {
int infoflags, return w;
int x, }
int y,
int width,
int height) {
// check if there was an error
if (!waiting || (infoflags & ERROR) > 0 || (infoflags & ABORT) > 0) {
// we either timed out or there was an error.
notifyAll ();
return false;
}
if ((infoflags & WIDTH) > 0 || (infoflags & HEIGHT) > 0) {
if ((infoflags & WIDTH) > 0)
w = width;
if ((infoflags & HEIGHT) > 0)
h = height;
if (w > -1 && h > -1 && firstFrameLoaded) {
notifyAll ();
return false;
}
}
if ((infoflags & ALLBITS) > 0 || (infoflags & FRAMEBITS) > 0) {
firstFrameLoaded = true;
notifyAll ();
return false;
}
return true;
}
int getHeight() {
return h;
}
public synchronized boolean imageUpdate(Image img, int infoflags, int x, int y,
int width, int height) {
// check if there was an error
if (!waiting || ((infoflags & ERROR) > 0) || ((infoflags & ABORT) > 0)) {
// we either timed out or there was an error.
notifyAll();
return false;
}
if (((infoflags & WIDTH) > 0) || ((infoflags & HEIGHT) > 0)) {
if ((infoflags & WIDTH) > 0) {
w = width;
}
if ((infoflags & HEIGHT) > 0) {
h = height;
}
if ((w > -1) && (h > -1) && firstFrameLoaded) {
notifyAll();
return false;
}
}
if (((infoflags & ALLBITS) > 0) || ((infoflags & FRAMEBITS) > 0)) {
firstFrameLoaded = true;
notifyAll();
return false;
}
return true;
}
} }
} }

View file

@ -1,247 +1,396 @@
// ImageWrapper.java /*
// Copyright (c) Hannes Wallnöfer 1999-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.image; package helma.image;
import java.awt.*; import java.awt.*;
import java.awt.image.*; import java.awt.image.*;
import java.util.*; import java.io.*;
import java.rmi.*; import java.rmi.*;
import java.rmi.server.*; import java.rmi.server.*;
import java.io.*; import java.util.*;
/** /**
* Abstract base class for Image Wrappers. * Abstract base class for Image Wrappers.
*/ */
public abstract class ImageWrapper { public abstract class ImageWrapper {
Image img; Image img;
Graphics g; Graphics g;
int width, height; int width;
int fontstyle, fontsize; int height;
int fontstyle;
int fontsize;
String fontname; String fontname;
ImageGenerator imggen; ImageGenerator imggen;
public ImageWrapper (Image img, Graphics g, int width, int height, ImageGenerator imggen) { /**
this.img = img; * Creates a new ImageWrapper object.
this.g = g; *
this.width = width; * @param img ...
this.height = height; * @param g ...
this.imggen = imggen; * @param width ...
if (g != null) { * @param height ...
Font f = g.getFont (); * @param imggen ...
fontname = f.getName (); */
fontstyle = f.getStyle (); public ImageWrapper(Image img, Graphics g, int width, int height,
fontsize = f.getSize (); ImageGenerator imggen) {
} this.img = img;
this.g = g;
this.width = width;
this.height = height;
this.imggen = imggen;
if (g != null) {
Font f = g.getFont();
fontname = f.getName();
fontstyle = f.getStyle();
fontsize = f.getSize();
}
} }
/** /**
* image manipulation methods * image manipulation methods
*/ */
public void setFont(String name, int style, int size) {
public void setFont (String name, int style, int size) { this.fontname = name;
this.fontname = name; this.fontstyle = style;
this.fontstyle = style; this.fontsize = size;
this.fontsize = size; g.setFont(new Font(name, style, size));
g.setFont (new Font (name, style, size));
} }
public void setColor (int red, int green, int blue) { /**
g.setColor (new Color (red, green, blue)); *
*
* @param red ...
* @param green ...
* @param blue ...
*/
public void setColor(int red, int green, int blue) {
g.setColor(new Color(red, green, blue));
} }
public void setColor (int color) { /**
g.setColor (new Color (color)); *
*
* @param color ...
*/
public void setColor(int color) {
g.setColor(new Color(color));
} }
public void drawString (String str, int x, int y) { /**
g.drawString (str, x, y); *
*
* @param str ...
* @param x ...
* @param y ...
*/
public void drawString(String str, int x, int y) {
g.drawString(str, x, y);
} }
public void drawLine (int x1, int y1, int x2, int y2) { /**
g.drawLine (x1, y1, x2, y2); *
*
* @param x1 ...
* @param y1 ...
* @param x2 ...
* @param y2 ...
*/
public void drawLine(int x1, int y1, int x2, int y2) {
g.drawLine(x1, y1, x2, y2);
} }
public void drawRect (int x, int y, int w, int h) { /**
g.drawRect (x, y, w, h); *
*
* @param x ...
* @param y ...
* @param w ...
* @param h ...
*/
public void drawRect(int x, int y, int w, int h) {
g.drawRect(x, y, w, h);
} }
public void drawImage (String filename, int x, int y) { /**
try { *
Image i = imggen.createImage (filename); *
g.drawImage (i, x, y, null); * @param filename ...
} catch (Exception ignore) {} * @param x ...
* @param y ...
*/
public void drawImage(String filename, int x, int y) {
try {
Image i = imggen.createImage(filename);
g.drawImage(i, x, y, null);
} catch (Exception ignore) {
}
} }
public void fillRect (int x, int y, int w, int h) { /**
g.fillRect (x, y, w, h); *
*
* @param x ...
* @param y ...
* @param w ...
* @param h ...
*/
public void fillRect(int x, int y, int w, int h) {
g.fillRect(x, y, w, h);
} }
public int getWidth () { /**
return width; *
*
* @return ...
*/
public int getWidth() {
return width;
} }
public int getHeight () { /**
return height; *
*
* @return ...
*/
public int getHeight() {
return height;
} }
public void crop (int x, int y, int w, int h) { /**
ImageFilter filter = new CropImageFilter (x, y, w, h); *
img = Toolkit.getDefaultToolkit ().createImage(new FilteredImageSource(img.getSource(), filter)); *
* @param x ...
* @param y ...
* @param w ...
* @param h ...
*/
public void crop(int x, int y, int w, int h) {
ImageFilter filter = new CropImageFilter(x, y, w, h);
img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(img.getSource(),
filter));
} }
public void resize (int w, int h) { /**
img = img.getScaledInstance (w, h, Image.SCALE_SMOOTH); *
width = w; *
height = h; * @param w ...
* @param h ...
*/
public void resize(int w, int h) {
img = img.getScaledInstance(w, h, Image.SCALE_SMOOTH);
width = w;
height = h;
} }
public void resizeFast (int w, int h) { /**
img = img.getScaledInstance (w, h, Image.SCALE_FAST); *
width = w; *
height = h; * @param w ...
* @param h ...
*/
public void resizeFast(int w, int h) {
img = img.getScaledInstance(w, h, Image.SCALE_FAST);
width = w;
height = h;
} }
public abstract void reduceColors (int colors); /**
*
*
* @param colors ...
*/
public abstract void reduceColors(int colors);
public abstract void saveAs (String filename); /**
*
*
* @param filename ...
*/
public abstract void saveAs(String filename);
/** /**
* Get ImageProducer of the wrapped image * Get ImageProducer of the wrapped image
*/ */
public ImageProducer getSource () { public ImageProducer getSource() {
return img.getSource (); return img.getSource();
} }
public void fillString (String str) { /**
Filler filler = new Filler (0, 0, width, height); *
filler.layout (str); *
* @param str ...
*/
public void fillString(String str) {
Filler filler = new Filler(0, 0, width, height);
filler.layout(str);
} }
public void fillString (String str, int x, int y, int w, int h) { /**
Filler filler = new Filler (x, y, w, h); *
filler.layout (str); *
* @param str ...
* @param x ...
* @param y ...
* @param w ...
* @param h ...
*/
public void fillString(String str, int x, int y, int w, int h) {
Filler filler = new Filler(x, y, w, h);
filler.layout(str);
} }
class Filler { class Filler {
int x;
int y;
int w;
int h;
int addedSpace = 0;
int xLeft;
int yLeft;
int realHeight;
transient Vector lines;
int x, y, w, h; public Filler(int x, int y, int w, int h) {
int addedSpace = 0; this.x = x;
int xLeft, yLeft; this.y = y;
int realHeight; this.w = w;
transient Vector lines; this.h = h;
}
public Filler (int x, int y, int w, int h) { public void layout(String str) {
this.x = x; int size = fontsize;
this.y = y;
this.w = w; lines = new Vector();
this.h = h;
while (!splitMessage(str, size) && (size > 10)) {
lines.setSize(0);
size = Math.max(2, size - 1);
}
Font oldfont = g.getFont();
g.setFont(new Font(fontname, fontstyle, size));
int l = lines.size();
for (int i = 0; i < l; i++) {
((Line) lines.elementAt(i)).paint(g, xLeft / 2, (yLeft / 2) + y);
}
g.setFont(oldfont);
}
private boolean splitMessage(String string, int size) {
Font font = new Font(fontname, fontstyle, size);
FontMetrics metrics = Toolkit.getDefaultToolkit().getFontMetrics(font);
int longestLine = 0;
int heightSoFar = 0;
int heightIncrement = (int) (0.84f * metrics.getHeight());
StringTokenizer tk = new StringTokenizer(string);
StringBuffer buffer = new StringBuffer();
int spaceWidth = metrics.stringWidth(" ");
int currentLine = 0;
int currentWidth = 0;
int maxWidth = w - 2;
int maxHeight = (h + addedSpace) - 2;
while (tk.hasMoreTokens()) {
String nextToken = tk.nextToken();
int nextWidth = metrics.stringWidth(nextToken);
if ((((currentWidth + nextWidth) >= maxWidth) && (currentWidth != 0))) {
Line line = new Line(buffer.toString(), x, heightSoFar, metrics);
lines.addElement(line);
if (line.textwidth > longestLine) {
longestLine = line.textwidth;
}
buffer = new StringBuffer();
currentWidth = 0;
heightSoFar += heightIncrement;
}
buffer.append(nextToken);
buffer.append(" ");
currentWidth += (nextWidth + spaceWidth);
if (((1.18 * heightSoFar) > maxHeight) && (fontsize > 10)) {
return false;
}
}
if (!"".equals(buffer.toString().trim())) {
Line line = new Line(buffer.toString(), x, heightSoFar, metrics);
lines.addElement(line);
if (line.textwidth > longestLine) {
longestLine = line.textwidth;
}
if ((longestLine > maxWidth) && (fontsize > 10)) {
return false;
}
heightSoFar += heightIncrement;
}
xLeft = w - longestLine;
yLeft = (addedSpace + h) - heightSoFar;
realHeight = heightSoFar;
return ((1.18 * heightSoFar) <= maxHeight);
}
} }
public void layout (String str) {
int size = fontsize;
lines = new Vector ();
while (!splitMessage (str, size) && size > 10) {
lines.setSize (0);
size = Math.max (2, size-1);
}
Font oldfont = g.getFont ();
g.setFont (new Font (fontname, fontstyle, size));
int l = lines.size();
for (int i = 0; i < l; i++) {
((Line) lines.elementAt (i)).paint (g, xLeft/2, yLeft/2 + y);
}
g.setFont (oldfont);
}
private boolean splitMessage (String string, int size) {
Font font = new Font (fontname, fontstyle, size);
FontMetrics metrics = Toolkit.getDefaultToolkit ().getFontMetrics (font);
int longestLine = 0;
int heightSoFar = 0;
int heightIncrement = (int) (0.84f * metrics.getHeight ());
StringTokenizer tk = new StringTokenizer (string);
StringBuffer buffer = new StringBuffer();
int spaceWidth = metrics.stringWidth(" ");
int currentLine = 0;
int currentWidth = 0;
int maxWidth = w - 2, maxHeight = h + addedSpace - 2;
while (tk.hasMoreTokens()) {
String nextToken = tk.nextToken();
int nextWidth = metrics.stringWidth(nextToken);
if ((currentWidth + nextWidth >= maxWidth && currentWidth != 0)) {
Line line = new Line (buffer.toString(), x, heightSoFar, metrics);
lines.addElement (line);
if (line.textwidth > longestLine)
longestLine = line.textwidth;
buffer = new StringBuffer();
currentWidth = 0;
heightSoFar += heightIncrement;
}
buffer.append (nextToken);
buffer.append (" ");
currentWidth += (nextWidth + spaceWidth);
if (1.18*heightSoFar > maxHeight && fontsize > 10)
return false;
}
if (! "".equals (buffer.toString().trim())) {
Line line = new Line (buffer.toString(), x, heightSoFar, metrics);
lines.addElement (line);
if (line.textwidth > longestLine)
longestLine = line.textwidth;
if (longestLine > maxWidth && fontsize > 10)
return false;
heightSoFar += heightIncrement;
}
xLeft = w - longestLine;
yLeft = addedSpace + h - heightSoFar;
realHeight = heightSoFar;
return (1.18*heightSoFar <= maxHeight);
}
}
class Line implements Serializable { class Line implements Serializable {
String text;
int xoff;
int yoff;
FontMetrics fm;
public int textwidth;
public int len;
int ascent;
String text; public Line(String text, int xoff, int yoff, FontMetrics fm) {
int xoff, yoff; this.text = text.trim();
FontMetrics fm; len = text.length();
public int textwidth, len; this.xoff = xoff;
int ascent; this.yoff = yoff;
this.fm = fm;
textwidth = (len == 0) ? 0 : fm.stringWidth(this.text);
ascent = (int) (0.9f * fm.getAscent());
}
public void paint(Graphics g, int xadd, int yadd) {
g.drawString(text, xoff + xadd, yoff + ascent + yadd);
}
public Line (String text, int xoff, int yoff, FontMetrics fm) { public boolean contains(int y) {
this.text = text.trim(); return (y < (yoff + fm.getHeight())) ? true : false;
len = text.length(); }
this.xoff = xoff;
this.yoff = yoff;
this.fm = fm;
textwidth = (len == 0) ? 0 : fm.stringWidth(this.text);
ascent = (int) (0.9f * fm.getAscent());
} }
public void paint (Graphics g, int xadd, int yadd) {
g.drawString (text, xoff+xadd, yoff+ascent+yadd);
}
public boolean contains (int y) {
return (y < yoff+fm.getHeight()) ? true : false;
}
}
} }

View file

@ -1,87 +1,121 @@
// ActivatedImageWrapper.java /*
// Copyright (c) Hannes Wallnöfer 1999-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.image; package helma.image;
import java.awt.*; import Acme.JPM.Encoders.GifEncoder;
import java.awt.image.*;
import com.sun.jimi.core.*; import com.sun.jimi.core.*;
import com.sun.jimi.core.util.*; import com.sun.jimi.core.util.*;
import Acme.JPM.Encoders.GifEncoder; import java.awt.*;
import java.io.IOException; import java.awt.image.*;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
/** /**
* A wrapper for an image that uses the Sun version of JIMI available at * A wrapper for an image that uses the Sun version of JIMI available at
* http://java.sun.com/products/jimi. * http://java.sun.com/products/jimi.
*/ */
public class SunImageWrapper extends ImageWrapper { public class SunImageWrapper extends ImageWrapper {
/**
public SunImageWrapper (Image img, Graphics g, int width, int height, * Creates a new SunImageWrapper object.
ImageGenerator imggen) { *
super (img, g, width, height, imggen); * @param img ...
} * @param g ...
* @param width ...
* @param height ...
public void reduceColors (int colors) { * @param imggen ...
try { */
int pixels[][] = getPixels(); public SunImageWrapper(Image img, Graphics g, int width, int height,
int palette[] = Quantize.quantizeImage(pixels, colors); ImageGenerator imggen) {
int w = pixels.length; super(img, g, width, height, imggen);
int h = pixels[0].length;
int pix[] = new int[w * h];
// convert to RGB
for (int x = w; x-- > 0; ) {
for (int y = h; y-- > 0; ) {
pix[y * w + x] = palette[pixels[x][y]];
}
}
img = imggen.createImage (new MemoryImageSource(w, h, pix, 0, w));
} catch (Exception x) {
// throw new RuntimeException (x.getMessage ());
}
} }
/** /**
* Snag the pixels from an image. *
*
* @param colors ...
*/ */
int[][] getPixels () throws IOException { public void reduceColors(int colors) {
int pix[] = new int[width * height]; try {
PixelGrabber grabber = new PixelGrabber(img, 0, 0, width, height, pix, 0, width); int[][] pixels = getPixels();
try { int[] palette = Quantize.quantizeImage(pixels, colors);
if (grabber.grabPixels() != true) { int w = pixels.length;
throw new IOException("Grabber returned false: " + grabber.status()); int h = pixels[0].length;
} int[] pix = new int[w * h];
} catch (InterruptedException e) {
e.printStackTrace(); // convert to RGB
} for (int x = w; x-- > 0;) {
int pixels[][] = new int[width][height]; for (int y = h; y-- > 0;) {
for (int x = width; x-- > 0; ) { pix[(y * w) + x] = palette[pixels[x][y]];
for (int y = height; y-- > 0; ) { }
pixels[x][y] = pix[y * width + x]; }
}
} img = imggen.createImage(new MemoryImageSource(w, h, pix, 0, w));
return pixels; } catch (Exception x) {
// throw new RuntimeException (x.getMessage ());
}
} }
/**
* Snag the pixels from an image.
*/
int[][] getPixels() throws IOException {
int[] pix = new int[width * height];
PixelGrabber grabber = new PixelGrabber(img, 0, 0, width, height, pix, 0, width);
public void saveAs (String filename) { try {
try { if (grabber.grabPixels() != true) {
if (filename.toLowerCase().endsWith (".gif")) { throw new IOException("Grabber returned false: " + grabber.status());
// sun's jimi package doesn't encode gifs, use Acme encoder }
FileOutputStream fout = new FileOutputStream (filename); } catch (InterruptedException e) {
// Acme gif encoder e.printStackTrace();
GifEncoder enc = new GifEncoder (img, fout); }
enc.encode ();
fout.close (); int[][] pixels = new int[width][height];
} else {
Jimi.putImage (img, filename); for (int x = width; x-- > 0;) {
} for (int y = height; y-- > 0;) {
} catch (Exception x) { pixels[x][y] = pix[(y * width) + x];
throw new RuntimeException (x.getMessage ()); }
} }
return pixels;
} }
/**
*
*
* @param filename ...
*/
public void saveAs(String filename) {
try {
if (filename.toLowerCase().endsWith(".gif")) {
// sun's jimi package doesn't encode gifs, use Acme encoder
FileOutputStream fout = new FileOutputStream(filename);
// Acme gif encoder
GifEncoder enc = new GifEncoder(img, fout);
enc.encode();
fout.close();
} else {
Jimi.putImage(img, filename);
}
} catch (Exception x) {
throw new RuntimeException(x.getMessage());
}
}
} }

View file

@ -1,33 +1,43 @@
// ApplicationManager.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.main; package helma.main;
import java.util.*;
import java.io.*;
import java.lang.reflect.*;
import java.rmi.*;
import java.rmi.server.*;
import java.net.URLEncoder;
import helma.framework.*; import helma.framework.*;
import helma.framework.core.*; import helma.framework.core.*;
import helma.objectmodel.*; import helma.objectmodel.*;
import helma.servlet.*; import helma.servlet.*;
import helma.util.SystemProperties; import helma.util.SystemProperties;
import org.apache.xmlrpc.XmlRpcHandler;
import org.mortbay.http.*; import org.mortbay.http.*;
import org.mortbay.http.handler.*; import org.mortbay.http.handler.*;
import org.mortbay.jetty.servlet.*; import org.mortbay.jetty.servlet.*;
import org.mortbay.util.*; import org.mortbay.util.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.URLEncoder;
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import javax.servlet.Servlet; import javax.servlet.Servlet;
import org.apache.xmlrpc.XmlRpcHandler;
/** /**
* This class is responsible for starting and stopping Helma applications. * This class is responsible for starting and stopping Helma applications.
*/ */
public class ApplicationManager implements XmlRpcHandler { public class ApplicationManager implements XmlRpcHandler {
private Hashtable applications; private Hashtable applications;
private Hashtable xmlrpcHandlers; private Hashtable xmlrpcHandlers;
private Properties mountpoints; private Properties mountpoints;
@ -37,258 +47,368 @@ public class ApplicationManager implements XmlRpcHandler {
private Server server; private Server server;
private long lastModified; private long lastModified;
public ApplicationManager (int port, File hopHome, SystemProperties props, Server server) { /**
this.port = port; * Creates a new ApplicationManager object.
this.hopHome = hopHome; *
this.props = props; * @param port ...
this.server = server; * @param hopHome ...
applications = new Hashtable (); * @param props ...
xmlrpcHandlers = new Hashtable (); * @param server ...
mountpoints = new Properties (); */
lastModified = 0; public ApplicationManager(int port, File hopHome, SystemProperties props,
Server server) {
this.port = port;
this.hopHome = hopHome;
this.props = props;
this.server = server;
applications = new Hashtable();
xmlrpcHandlers = new Hashtable();
mountpoints = new Properties();
lastModified = 0;
} }
// regularely check applications property file to create and start new applications // regularely check applications property file to create and start new applications
protected void checkForChanges () { protected void checkForChanges() {
if (props.lastModified () > lastModified) { if (props.lastModified() > lastModified) {
try { try {
for (Enumeration e = props.keys(); e.hasMoreElements (); ) { for (Enumeration e = props.keys(); e.hasMoreElements();) {
String appName = (String) e.nextElement (); String appName = (String) e.nextElement();
if (appName.indexOf (".") == -1 && applications.get (appName) == null) {
start (appName);
register (appName);
}
}
// then stop deleted ones
for (Enumeration e = applications.keys(); e.hasMoreElements (); ) {
String appName = (String) e.nextElement ();
// check if application has been removed and should be stopped
if (!props.containsKey (appName)) {
stop (appName);
} else if (server.http != null) {
// check if application should be remounted at a
// different location on embedded web server
String oldMountpoint = mountpoints.getProperty (appName);
String mountpoint = getMountpoint (appName);
String pattern = getPathPattern (mountpoint);
if (!pattern.equals (oldMountpoint)) {
Server.getLogger().log("Moving application "+appName+" from "+oldMountpoint+" to "+pattern);
HttpContext oldContext = server.http.getContext (null, oldMountpoint);
if (oldContext != null) {
// oldContext.setContextPath(pattern);
oldContext.stop ();
oldContext.destroy ();
}
Application app = (Application) applications.get (appName);
if (!app.hasExplicitBaseURI())
app.setBaseURI (mountpoint);
ServletHttpContext context = new ServletHttpContext ();
context.setContextPath(pattern);
server.http.addContext (context);
ServletHolder holder = context.addServlet (appName, "/*", "helma.servlet.EmbeddedServletClient");
holder.setInitParameter ("application", appName);
holder.setInitParameter ("mountpoint", mountpoint);
if ("true".equalsIgnoreCase (props.getProperty (appName+".responseEncoding")))
context.addHandler(new ContentEncodingHandler());
String cookieDomain = props.getProperty (appName+".cookieDomain");
if (cookieDomain != null)
holder.setInitParameter ("cookieDomain", cookieDomain);
String uploadLimit = props.getProperty (appName+".uploadLimit");
if (uploadLimit != null)
holder.setInitParameter ("uploadLimit", uploadLimit);
// holder.start ();
context.start ();
mountpoints.setProperty (appName, pattern);
}
}
}
} catch (Exception mx) {
Server.getLogger().log ("Error checking applications: "+mx);
}
lastModified = System.currentTimeMillis (); if ((appName.indexOf(".") == -1) &&
} (applications.get(appName) == null)) {
start(appName);
register(appName);
}
}
// then stop deleted ones
for (Enumeration e = applications.keys(); e.hasMoreElements();) {
String appName = (String) e.nextElement();
// check if application has been removed and should be stopped
if (!props.containsKey(appName)) {
stop(appName);
} else if (server.http != null) {
// check if application should be remounted at a
// different location on embedded web server
String oldMountpoint = mountpoints.getProperty(appName);
String mountpoint = getMountpoint(appName);
String pattern = getPathPattern(mountpoint);
if (!pattern.equals(oldMountpoint)) {
Server.getLogger().log("Moving application " + appName +
" from " + oldMountpoint + " to " +
pattern);
HttpContext oldContext = server.http.getContext(null,
oldMountpoint);
if (oldContext != null) {
// oldContext.setContextPath(pattern);
oldContext.stop();
oldContext.destroy();
}
Application app = (Application) applications.get(appName);
if (!app.hasExplicitBaseURI()) {
app.setBaseURI(mountpoint);
}
ServletHttpContext context = new ServletHttpContext();
context.setContextPath(pattern);
server.http.addContext(context);
ServletHolder holder = context.addServlet(appName, "/*",
"helma.servlet.EmbeddedServletClient");
holder.setInitParameter("application", appName);
holder.setInitParameter("mountpoint", mountpoint);
if ("true".equalsIgnoreCase(props.getProperty(appName +
".responseEncoding"))) {
context.addHandler(new ContentEncodingHandler());
}
String cookieDomain = props.getProperty(appName +
".cookieDomain");
if (cookieDomain != null) {
holder.setInitParameter("cookieDomain", cookieDomain);
}
String uploadLimit = props.getProperty(appName +
".uploadLimit");
if (uploadLimit != null) {
holder.setInitParameter("uploadLimit", uploadLimit);
}
// holder.start ();
context.start();
mountpoints.setProperty(appName, pattern);
}
}
}
} catch (Exception mx) {
Server.getLogger().log("Error checking applications: " + mx);
}
lastModified = System.currentTimeMillis();
}
} }
void start (String appName) { void start(String appName) {
Server.getLogger().log ("Building application "+appName); Server.getLogger().log("Building application " + appName);
try {
// check if application and db dirs are set, otherwise go with try {
// the defaults, passing null dirs to the constructor. // check if application and db dirs are set, otherwise go with
String appDirName = props.getProperty (appName+".appdir"); // the defaults, passing null dirs to the constructor.
File appDir = appDirName == null ? null : new File (appDirName); String appDirName = props.getProperty(appName + ".appdir");
String dbDirName = props.getProperty (appName+".dbdir"); File appDir = (appDirName == null) ? null : new File(appDirName);
File dbDir = dbDirName == null ? null : new File (dbDirName); String dbDirName = props.getProperty(appName + ".dbdir");
// create the application instance File dbDir = (dbDirName == null) ? null : new File(dbDirName);
Application app = new Application (appName, server, appDir, dbDir);
applications.put (appName, app); // create the application instance
// the application is started later in the register method, when it's bound Application app = new Application(appName, server, appDir, dbDir);
app.init ();
} catch (Exception x) { applications.put(appName, app);
Server.getLogger().log ("Error creating application "+appName+": "+x);
x.printStackTrace (); // the application is started later in the register method, when it's bound
} app.init();
} catch (Exception x) {
Server.getLogger().log("Error creating application " + appName + ": " + x);
x.printStackTrace();
}
} }
void stop (String appName) { void stop(String appName) {
Server.getLogger().log ("Stopping application "+appName); Server.getLogger().log("Stopping application " + appName);
try {
Application app = (Application) applications.get (appName); try {
// unbind from RMI server Application app = (Application) applications.get(appName);
if (port > 0) {
Naming.unbind ("//:"+port+"/"+appName); // unbind from RMI server
} if (port > 0) {
// unbind from Jetty HTTP server Naming.unbind("//:" + port + "/" + appName);
if (server.http != null) { }
String mountpoint = mountpoints.getProperty (appName);
HttpContext context = server.http.getContext (null, mountpoint); // unbind from Jetty HTTP server
if (context != null) { if (server.http != null) {
context.stop (); String mountpoint = mountpoints.getProperty(appName);
context.destroy (); HttpContext context = server.http.getContext(null, mountpoint);
}
} if (context != null) {
// unregister as XML-RPC handler context.stop();
xmlrpcHandlers.remove (app.getXmlRpcHandlerName()); context.destroy();
app.stop (); }
Server.getLogger().log ("Unregistered application "+appName); }
} catch (Exception x) {
Server.getLogger().log ("Couldn't unregister app: "+x); // unregister as XML-RPC handler
} xmlrpcHandlers.remove(app.getXmlRpcHandlerName());
applications.remove (appName); app.stop();
Server.getLogger().log("Unregistered application " + appName);
} catch (Exception x) {
Server.getLogger().log("Couldn't unregister app: " + x);
}
applications.remove(appName);
} }
void register (String appName) { void register(String appName) {
try { try {
Server.getLogger().log ("Binding application "+appName); Server.getLogger().log("Binding application " + appName);
Application app = (Application) applications.get (appName);
// bind to RMI server Application app = (Application) applications.get(appName);
if (port > 0) {
Naming.rebind ("//:"+port+"/"+appName, new RemoteApplication (app)); // bind to RMI server
} if (port > 0) {
// bind to Jetty HTTP server Naming.rebind("//:" + port + "/" + appName, new RemoteApplication(app));
if (server.http != null) { }
String mountpoint = getMountpoint (appName);
// if using embedded webserver (not AJP) set application URL prefix // bind to Jetty HTTP server
if (!app.hasExplicitBaseURI ()) if (server.http != null) {
app.setBaseURI (mountpoint); String mountpoint = getMountpoint(appName);
String pattern = getPathPattern (mountpoint);
ServletHttpContext context = new ServletHttpContext (); // if using embedded webserver (not AJP) set application URL prefix
context.setContextPath(pattern); if (!app.hasExplicitBaseURI()) {
server.http.addContext (context); app.setBaseURI(mountpoint);
ServletHolder holder = context.addServlet (appName, "/*", "helma.servlet.EmbeddedServletClient"); }
holder.setInitParameter ("application", appName);
holder.setInitParameter ("mountpoint", mountpoint); String pattern = getPathPattern(mountpoint);
if ("true".equalsIgnoreCase (props.getProperty (appName+".responseEncoding"))) ServletHttpContext context = new ServletHttpContext();
context.addHandler(new ContentEncodingHandler());
String cookieDomain = props.getProperty (appName+".cookieDomain"); context.setContextPath(pattern);
if (cookieDomain != null) server.http.addContext(context);
holder.setInitParameter ("cookieDomain", cookieDomain);
String uploadLimit = props.getProperty (appName+".uploadLimit"); ServletHolder holder = context.addServlet(appName, "/*",
if (uploadLimit != null) "helma.servlet.EmbeddedServletClient");
holder.setInitParameter ("uploadLimit", uploadLimit);
String debug = props.getProperty (appName+".debug"); holder.setInitParameter("application", appName);
if (debug != null) holder.setInitParameter("mountpoint", mountpoint);
holder.setInitParameter ("debug", debug);
// holder.start (); if ("true".equalsIgnoreCase(props.getProperty(appName +
context.start (); ".responseEncoding"))) {
mountpoints.setProperty (appName, pattern); context.addHandler(new ContentEncodingHandler());
} }
// register as XML-RPC handler
xmlrpcHandlers.put (app.getXmlRpcHandlerName(), app); String cookieDomain = props.getProperty(appName + ".cookieDomain");
app.start ();
} catch (Exception x) { if (cookieDomain != null) {
Server.getLogger().log ("Couldn't register and start app: "+x); holder.setInitParameter("cookieDomain", cookieDomain);
x.printStackTrace (); }
}
String uploadLimit = props.getProperty(appName + ".uploadLimit");
if (uploadLimit != null) {
holder.setInitParameter("uploadLimit", uploadLimit);
}
String debug = props.getProperty(appName + ".debug");
if (debug != null) {
holder.setInitParameter("debug", debug);
}
// holder.start ();
context.start();
mountpoints.setProperty(appName, pattern);
}
// register as XML-RPC handler
xmlrpcHandlers.put(app.getXmlRpcHandlerName(), app);
app.start();
} catch (Exception x) {
Server.getLogger().log("Couldn't register and start app: " + x);
x.printStackTrace();
}
} }
public void startAll () { /**
try { *
for (Enumeration e = props.keys(); e.hasMoreElements (); ) { */
String appName = (String) e.nextElement (); public void startAll() {
if (appName.indexOf (".") == -1) try {
start (appName); for (Enumeration e = props.keys(); e.hasMoreElements();) {
} String appName = (String) e.nextElement();
for (Enumeration e = props.keys(); e.hasMoreElements (); ) {
String appName = (String) e.nextElement (); if (appName.indexOf(".") == -1) {
if (appName.indexOf (".") == -1) start(appName);
register (appName); }
} }
if (server.http != null) {
// add handler for static files. for (Enumeration e = props.keys(); e.hasMoreElements();) {
File staticContent = new File (server.getHopHome(), "static"); String appName = (String) e.nextElement();
Server.getLogger().log("Serving static content from "+staticContent.getAbsolutePath());
HttpContext context = server.http.addContext ("/static/*"); if (appName.indexOf(".") == -1) {
context.setResourceBase (staticContent.getAbsolutePath()); register(appName);
ResourceHandler handler = new ResourceHandler(); }
context.addHandler(handler); }
context.start ();
} if (server.http != null) {
lastModified = System.currentTimeMillis (); // add handler for static files.
} catch (Exception mx) { File staticContent = new File(server.getHopHome(), "static");
Server.getLogger().log ("Error starting applications: "+mx);
mx.printStackTrace (); Server.getLogger().log("Serving static content from " +
} staticContent.getAbsolutePath());
HttpContext context = server.http.addContext("/static/*");
context.setResourceBase(staticContent.getAbsolutePath());
ResourceHandler handler = new ResourceHandler();
context.addHandler(handler);
context.start();
}
lastModified = System.currentTimeMillis();
} catch (Exception mx) {
Server.getLogger().log("Error starting applications: " + mx);
mx.printStackTrace();
}
} }
public void stopAll () { /**
for (Enumeration en=applications.keys(); en.hasMoreElements(); ) { *
String appName = (String) en.nextElement(); */
stop (appName); public void stopAll() {
} for (Enumeration en = applications.keys(); en.hasMoreElements();) {
String appName = (String) en.nextElement();
stop(appName);
}
} }
/** /**
* Get an array containing all currently running applications. * Get an array containing all currently running applications.
*/ */
public Object[] getApplications () { public Object[] getApplications() {
return applications.values ().toArray (); return applications.values().toArray();
} }
/** /**
* Get an application by name. * Get an application by name.
*/ */
public Application getApplication(String name) { public Application getApplication(String name) {
return (Application)applications.get(name); return (Application) applications.get(name);
} }
/** /**
* Implements org.apache.xmlrpc.XmlRpcHandler.execute() * Implements org.apache.xmlrpc.XmlRpcHandler.execute()
*/ */
public Object execute (String method, Vector params) throws Exception { public Object execute(String method, Vector params)
int dot = method.indexOf ("."); throws Exception {
if (dot == -1) int dot = method.indexOf(".");
throw new Exception ("Method name \""+method+"\" does not specify a handler application");
if (dot == 0 || dot == method.length()-1) if (dot == -1) {
throw new Exception ("\""+method+"\" is not a valid XML-RPC method name"); throw new Exception("Method name \"" + method +
String handler = method.substring (0, dot); "\" does not specify a handler application");
String method2 = method.substring (dot+1); }
Application app = (Application) xmlrpcHandlers.get (handler);
if (app == null) if ((dot == 0) || (dot == (method.length() - 1))) {
throw new Exception ("Handler \""+handler+"\" not found for "+method); throw new Exception("\"" + method + "\" is not a valid XML-RPC method name");
return app.executeXmlRpc (method2, params); }
String handler = method.substring(0, dot);
String method2 = method.substring(dot + 1);
Application app = (Application) xmlrpcHandlers.get(handler);
if (app == null) {
throw new Exception("Handler \"" + handler + "\" not found for " + method);
}
return app.executeXmlRpc(method2, params);
} }
private String getMountpoint(String appName) {
String mountpoint = props.getProperty(appName + ".mountpoint");
private String getMountpoint (String appName) { if (mountpoint == null) {
String mountpoint = props.getProperty (appName+".mountpoint"); return "/" + URLEncoder.encode(appName);
if (mountpoint == null) }
return "/"+URLEncoder.encode(appName);
mountpoint = mountpoint.trim (); mountpoint = mountpoint.trim();
if ("".equals (mountpoint))
return "/"; if ("".equals(mountpoint)) {
else if (!mountpoint.startsWith ("/")) return "/";
return "/"+mountpoint; } else if (!mountpoint.startsWith("/")) {
return mountpoint; return "/" + mountpoint;
}
return mountpoint;
} }
private String getPathPattern (String mountpoint) { private String getPathPattern(String mountpoint) {
if ("/".equals (mountpoint)) if ("/".equals(mountpoint)) {
return "/"; return "/";
if (!mountpoint.endsWith ("/")) }
return mountpoint+"/*";
return mountpoint+"*";
}
if (!mountpoint.endsWith("/")) {
return mountpoint + "/*";
}
return mountpoint + "*";
}
} }

View file

@ -1,12 +1,26 @@
// HelmaSecurityManager.java /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.main; package helma.main;
import java.security.Permission; import helma.framework.core.AppClassLoader;
import java.io.FileDescriptor; import java.io.FileDescriptor;
import java.net.InetAddress; import java.net.InetAddress;
import java.security.Permission;
import java.util.HashSet; import java.util.HashSet;
import helma.framework.core.AppClassLoader;
/** /**
* Liberal security manager for Helma system that makes sure application code * Liberal security manager for Helma system that makes sure application code
@ -17,78 +31,297 @@ import helma.framework.core.AppClassLoader;
* the name of the application trying to execute the action in question, if any. * the name of the application trying to execute the action in question, if any.
*/ */
public class HelmaSecurityManager extends SecurityManager { public class HelmaSecurityManager extends SecurityManager {
// The set of actions forbidden to application code. // The set of actions forbidden to application code.
// We are pretty permissive, forbidding only System.exit() // We are pretty permissive, forbidding only System.exit()
// and setting the security manager. // and setting the security manager.
private final static HashSet forbidden = new HashSet (); private final static HashSet forbidden = new HashSet();
static { static {
forbidden.add ("exitVM"); forbidden.add("exitVM");
forbidden.add ("setSecurityManager"); forbidden.add("setSecurityManager");
} }
/**
*
*
* @param p ...
*/
public void checkPermission(Permission p) { public void checkPermission(Permission p) {
if (p instanceof RuntimePermission) { if (p instanceof RuntimePermission) {
if (forbidden.contains (p.getName())) { if (forbidden.contains(p.getName())) {
Class[] classes = getClassContext(); Class[] classes = getClassContext();
for (int i=0; i<classes.length; i++) {
if (classes[i].getClassLoader() instanceof AppClassLoader) for (int i = 0; i < classes.length; i++) {
throw new SecurityException (p.getName()+" not allowed for application code"); if (classes[i].getClassLoader() instanceof AppClassLoader) {
} throw new SecurityException(p.getName() +
} " not allowed for application code");
} }
}
}
}
} }
/**
*
*
* @param p ...
* @param context ...
*/
public void checkPermission(Permission p, Object context) { public void checkPermission(Permission p, Object context) {
} }
public void checkCreateClassLoader() {}
public void checkAccess(Thread thread) {} /**
public void checkAccess(ThreadGroup group) {} *
public void checkExit(int status) { */
Class[] classes = getClassContext(); public void checkCreateClassLoader() {
for (int i=0; i<classes.length; i++) { }
if (classes[i].getClassLoader() instanceof AppClassLoader)
throw new SecurityException ("operation not allowed for application code"); /**
} *
*
* @param thread ...
*/
public void checkAccess(Thread thread) {
}
/**
*
*
* @param group ...
*/
public void checkAccess(ThreadGroup group) {
}
/**
*
*
* @param status ...
*/
public void checkExit(int status) {
Class[] classes = getClassContext();
for (int i = 0; i < classes.length; i++) {
if (classes[i].getClassLoader() instanceof AppClassLoader) {
throw new SecurityException("operation not allowed for application code");
}
}
}
/**
*
*
* @param cmd ...
*/
public void checkExec(String cmd) {
}
/**
*
*
* @param lib ...
*/
public void checkLink(String lib) {
}
/**
*
*
* @param fdesc ...
*/
public void checkRead(FileDescriptor fdesc) {
}
/**
*
*
* @param file ...
*/
public void checkRead(String file) {
}
/**
*
*
* @param file ...
* @param context ...
*/
public void checkRead(String file, Object context) {
}
/**
*
*
* @param fdesc ...
*/
public void checkWrite(FileDescriptor fdesc) {
}
/**
*
*
* @param file ...
*/
public void checkWrite(String file) {
}
/**
*
*
* @param file ...
*/
public void checkDelete(String file) {
}
/**
*
*
* @param host ...
* @param port ...
*/
public void checkConnect(String host, int port) {
}
/**
*
*
* @param host ...
* @param port ...
* @param context ...
*/
public void checkConnect(String host, int port, Object context) {
}
/**
*
*
* @param port ...
*/
public void checkListen(int port) {
}
/**
*
*
* @param host ...
* @param port ...
*/
public void checkAccept(String host, int port) {
}
/**
*
*
* @param addr ...
*/
public void checkMulticast(InetAddress addr) {
}
/**
*
*
* @param addr ...
* @param ttl ...
*/
public void checkMulticast(InetAddress addr, byte ttl) {
}
/**
*
*/
public void checkPropertiesAccess() {
}
/**
*
*
* @param key ...
*/
public void checkPropertyAccess(String key) {
}
/**
*
*
* @param window ...
*
* @return ...
*/
public boolean checkTopLevelWindow(Object window) {
return true;
}
/**
*
*/
public void checkPrintJobAccess() {
}
/**
*
*/
public void checkSystemClipboardAccess() {
}
/**
*
*/
public void checkAwtEventQueueAccess() {
}
/**
*
*
* @param pkg ...
*/
public void checkPackageAccess(String pkg) {
}
/**
*
*
* @param pkg ...
*/
public void checkPackageDefinition(String pkg) {
}
/**
*
*/
public void checkSetFactory() {
}
/**
*
*
* @param clazz ...
* @param which ...
*/
public void checkMemberAccess(Class clazz, int which) {
}
/**
*
*
* @param target ...
*/
public void checkSecurityAccess(String target) {
} }
public void checkExec(String cmd) {}
public void checkLink(String lib) {}
public void checkRead(FileDescriptor fdesc) {}
public void checkRead(String file) {}
public void checkRead(String file, Object context) {}
public void checkWrite(FileDescriptor fdesc) {}
public void checkWrite(String file) {}
public void checkDelete(String file) {}
public void checkConnect(String host, int port) {}
public void checkConnect(String host, int port, Object context) {}
public void checkListen(int port) {}
public void checkAccept(String host, int port) {}
public void checkMulticast(InetAddress addr) {}
public void checkMulticast(InetAddress addr, byte ttl) {}
public void checkPropertiesAccess() {}
public void checkPropertyAccess(String key) {}
public boolean checkTopLevelWindow(Object window) { return true; }
public void checkPrintJobAccess() {}
public void checkSystemClipboardAccess() {}
public void checkAwtEventQueueAccess() {}
public void checkPackageAccess(String pkg) {}
public void checkPackageDefinition(String pkg) {}
public void checkSetFactory() {}
public void checkMemberAccess(Class clazz, int which) {}
public void checkSecurityAccess(String target) {}
/** /**
* Utility method that returns the name of the application trying * Utility method that returns the name of the application trying
* to execute the code in question. Returns null if the current code * to execute the code in question. Returns null if the current code
* does not belong to any application. * does not belong to any application.
*/ */
protected String getApplication () { protected String getApplication() {
Class[] classes = getClassContext(); Class[] classes = getClassContext();
for (int i=0; i<classes.length; i++) {
if (classes[i].getClassLoader() instanceof AppClassLoader)
return ((AppClassLoader) classes[i].getClassLoader()).getAppName ();
}
// no application class loader found in stack - return null
return null;
}
for (int i = 0; i < classes.length; i++) {
if (classes[i].getClassLoader() instanceof AppClassLoader) {
return ((AppClassLoader) classes[i].getClassLoader()).getAppName();
}
}
// no application class loader found in stack - return null
return null;
}
} }

View file

@ -1,4 +1,19 @@
// HelmaShutdownHook.java /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.main; package helma.main;
import helma.util.Logger; import helma.util.Logger;
@ -8,23 +23,35 @@ import java.util.List;
* ShutdownHook that shuts down all running Helma applications on exit. * ShutdownHook that shuts down all running Helma applications on exit.
*/ */
public class HelmaShutdownHook extends Thread { public class HelmaShutdownHook extends Thread {
ApplicationManager appmgr; ApplicationManager appmgr;
public HelmaShutdownHook (ApplicationManager appmgr) { /**
this.appmgr = appmgr; * Creates a new HelmaShutdownHook object.
*
* @param appmgr ...
*/
public HelmaShutdownHook(ApplicationManager appmgr) {
this.appmgr = appmgr;
} }
public void run () { /**
Logger logger = Server.getLogger(); *
if (logger != null) */
logger.log ("Shutting down Helma"); public void run() {
appmgr.stopAll (); Logger logger = Server.getLogger();
List loggers = Logger.getLoggers();
int l = loggers.size();
for (int i=0; i<l; i++)
((Logger) loggers.get(i)).close();
Logger.wakeup();
}
if (logger != null) {
logger.log("Shutting down Helma");
}
appmgr.stopAll();
List loggers = Logger.getLoggers();
int l = loggers.size();
for (int i = 0; i < l; i++)
((Logger) loggers.get(i)).close();
Logger.wakeup();
}
} }

View file

@ -1,42 +1,79 @@
// HopSocketFactory.java /*
// Copyright (c) Hannes Wallnöfer 1999-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.main; package helma.main;
import helma.util.*; import helma.util.*;
import java.io.IOException;
import java.net.*; import java.net.*;
import java.rmi.server.*; import java.rmi.server.*;
import java.io.IOException;
/** /**
* An RMI socket factory that has a "paranoid" option to filter clients. * An RMI socket factory that has a "paranoid" option to filter clients.
* We only do direct connections, no HTTP proxy stuff, since this is * We only do direct connections, no HTTP proxy stuff, since this is
* server-to-server. * server-to-server.
*/ */
public class HelmaSocketFactory extends RMISocketFactory { public class HelmaSocketFactory extends RMISocketFactory {
private InetAddressFilter filter; private InetAddressFilter filter;
public HelmaSocketFactory () { /**
filter = new InetAddressFilter (); * Creates a new HelmaSocketFactory object.
*/
public HelmaSocketFactory() {
filter = new InetAddressFilter();
} }
public void addAddress (String address) { /**
try { *
filter.addAddress (address); *
} catch (IOException x) { * @param address ...
Server.getLogger().log ("Could not add "+address+" to Socket Filter: invalid address."); */
} public void addAddress(String address) {
try {
filter.addAddress(address);
} catch (IOException x) {
Server.getLogger().log("Could not add " + address +
" to Socket Filter: invalid address.");
}
} }
/**
*
*
* @param host ...
* @param port ...
*
* @return ...
*
* @throws IOException ...
*/
public Socket createSocket(String host, int port) throws IOException { public Socket createSocket(String host, int port) throws IOException {
return new Socket (host, port); return new Socket(host, port);
} }
/**
*
*
* @param port ...
*
* @return ...
*
* @throws IOException ...
*/
public ServerSocket createServerSocket(int port) throws IOException { public ServerSocket createServerSocket(int port) throws IOException {
return new ParanoidServerSocket (port, filter); return new ParanoidServerSocket(port, filter);
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,36 +1,51 @@
// FilteredClassLoader.java /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.main.launcher; package helma.main.launcher;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.Hashtable; import java.security.CodeSource;
import java.security.PermissionCollection; import java.security.PermissionCollection;
import java.security.Permissions; import java.security.Permissions;
import java.security.Policy; import java.security.Policy;
import java.security.CodeSource; import java.util.Hashtable;
/** /**
* ClassLoader that is able to exclude certain packages from loading. * ClassLoader that is able to exclude certain packages from loading.
*/ */
public class FilteredClassLoader extends URLClassLoader { public class FilteredClassLoader extends URLClassLoader {
/**
/** * Create a server wide class loader that doesn't see the scripting engine(s)
* Create a server wide class loader that doesn't see the scripting engine(s) * embedded in helma.jar. These files should be loaded by the per-application
* embedded in helma.jar. These files should be loaded by the per-application * class loaders so that special security policies can be applied to them and
* class loaders so that special security policies can be applied to them and * so that they can load classes from jar files in the app directories.
* so that they can load classes from jar files in the app directories. */
*/
public FilteredClassLoader(URL[] urls) { public FilteredClassLoader(URL[] urls) {
super (urls); super(urls);
} }
/** /**
* Mask classes that implement the scripting engine(s) contained in helma.jar * Mask classes that implement the scripting engine(s) contained in helma.jar
*/ */
protected Class findClass (String name) throws ClassNotFoundException { protected Class findClass(String name) throws ClassNotFoundException {
if (name != null && "helma.scripting.fesi.PhantomEngine".equals (name)) if ((name != null) && "helma.scripting.fesi.PhantomEngine".equals(name)) {
throw new ClassNotFoundException (name); throw new ClassNotFoundException(name);
return super.findClass (name); }
return super.findClass(name);
} }
} }

View file

@ -1,114 +1,145 @@
// helma.main.Main /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.main.launcher; package helma.main.launcher;
import java.net.URLClassLoader;
import java.net.URL;
import java.net.URLDecoder;
import java.io.File; import java.io.File;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.security.Policy; import java.security.Policy;
import java.util.ArrayList;
/** /**
* Helma bootstrap class. Figures out Helma home directory, sets up class path and * Helma bootstrap class. Figures out Helma home directory, sets up class path and
* lauchnes main class. * lauchnes main class.
*/ */
public class Main { public class Main {
public static final String[] jars = { public static final String[] jars = {
"helma.jar", "helma.jar", "jetty.jar", "crimson.jar",
"jetty.jar", "xmlrpc.jar", "servlet.jar", "regexp.jar",
"crimson.jar", "mail.jar", "activation.jar",
"xmlrpc.jar", "netcomponents.jar", "jimi.jar",
"servlet.jar", "apache-dom.jar", "jdom.jar"
"regexp.jar", };
"mail.jar",
"activation.jar",
"netcomponents.jar",
"jimi.jar",
"apache-dom.jar",
"jdom.jar"
};
/**
*
*
* @param args ...
*
* @throws Exception ...
*/
public static void main(String[] args) throws Exception {
// check if home directory is set via command line arg. If not,
// we'll get it from the location of the jar file this class
// has been loaded from.
String installDir = null;
public static void main (String[] args) throws Exception { // first, try to get helma home dir from command line options
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-i") && ((i + 1) < args.length)) {
installDir = args[i + 1];
}
}
// check if home directory is set via command line arg. If not, URLClassLoader apploader = (URLClassLoader) ClassLoader.getSystemClassLoader();
// we'll get it from the location of the jar file this class
// has been loaded from.
String installDir = null;
// first, try to get helma home dir from command line options
for (int i=0; i<args.length; i++) {
if (args[i].equals ("-i") && i+1<args.length) {
installDir = args[i+1];
}
}
URLClassLoader apploader = (URLClassLoader) ClassLoader.getSystemClassLoader();
// try to get Helma installation directory
if (installDir == null) {
try {
URL launcherUrl = apploader.findResource("helma/main/launcher/Main.class");
// this is a JAR URL of the form
// jar:<url>!/{entry}
// we strip away the jar: prefix and the !/{entry} suffix
// to get the original jar file URL
installDir = launcherUrl.toString().substring(4);
int excl = installDir.indexOf ("!");
if (excl > -1) {
installDir = installDir.substring(0, excl);
launcherUrl = new URL (installDir);
File f = new File (launcherUrl.getPath());
installDir = f.getParentFile().getCanonicalPath();
}
} catch (Exception x) {
// unable to get Helma installation dir from launcher jar
System.err.println ("Unable to get Helma installation directory: "+x);
System.exit (2);
}
}
// decode installDir in case it is URL-encoded // try to get Helma installation directory
installDir = URLDecoder.decode (installDir); if (installDir == null) {
try {
URL launcherUrl = apploader.findResource("helma/main/launcher/Main.class");
// set up the class path // this is a JAR URL of the form
File libdir = new File (installDir, "lib"); // jar:<url>!/{entry}
ArrayList jarlist = new ArrayList (); // we strip away the jar: prefix and the !/{entry} suffix
for (int i=0;i<jars.length;i++) { // to get the original jar file URL
File jar = new File (libdir, jars[i]); installDir = launcherUrl.toString().substring(4);
jarlist.add (new URL ("file:" + jar.getAbsolutePath()));
} int excl = installDir.indexOf("!");
// add all jar files from the lib/ext directory
File extdir =new File (libdir, "ext"); if (excl > -1) {
File[] files = extdir.listFiles (new FilenameFilter() { installDir = installDir.substring(0, excl);
public boolean accept (File dir, String name) { launcherUrl = new URL(installDir);
String n = name.toLowerCase();
return n.endsWith (".jar") || n.endsWith (".zip"); File f = new File(launcherUrl.getPath());
}
}); installDir = f.getParentFile().getCanonicalPath();
if (files != null) }
for (int i=0;i<files.length; i++) { } catch (Exception x) {
// WORKAROUND: add the files in lib/ext before // unable to get Helma installation dir from launcher jar
// lib/apache-dom.jar, since otherwise putting a full version System.err.println("Unable to get Helma installation directory: " + x);
// of Xerces in lib/ext would cause a version conflict with the System.exit(2);
// xerces classes in lib/apache-dom.jar. Generally, having some pieces }
// of Xerces in lib/apache-dom.jar is kind of problematic. }
jarlist.add (jars.length-3, new URL ("file:" + files[i].getAbsolutePath()));
System.err.println ("Adding to classpath: "+files[i].getAbsolutePath()); // decode installDir in case it is URL-encoded
} installDir = URLDecoder.decode(installDir);
URL[] urls = new URL[jarlist.size()];
jarlist.toArray (urls); // set up the class path
FilteredClassLoader loader = new FilteredClassLoader (urls); File libdir = new File(installDir, "lib");
// set the new class loader as context class loader ArrayList jarlist = new ArrayList();
Thread.currentThread().setContextClassLoader (loader);
// get the main server class for (int i = 0; i < jars.length; i++) {
Class clazz = loader.loadClass ("helma.main.Server"); File jar = new File(libdir, jars[i]);
Class[] cargs = new Class[] { args.getClass() };
Method main = clazz.getMethod ("main", cargs); jarlist.add(new URL("file:" + jar.getAbsolutePath()));
Object[] nargs = new Object[] { args }; }
// run
main.invoke (null, nargs); // add all jar files from the lib/ext directory
File extdir = new File(libdir, "ext");
File[] files = extdir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
String n = name.toLowerCase();
return n.endsWith(".jar") || n.endsWith(".zip");
}
});
if (files != null) {
for (int i = 0; i < files.length; i++) {
// WORKAROUND: add the files in lib/ext before
// lib/apache-dom.jar, since otherwise putting a full version
// of Xerces in lib/ext would cause a version conflict with the
// xerces classes in lib/apache-dom.jar. Generally, having some pieces
// of Xerces in lib/apache-dom.jar is kind of problematic.
jarlist.add(jars.length - 3, new URL("file:" +
files[i].getAbsolutePath()));
System.err.println("Adding to classpath: " + files[i].getAbsolutePath());
}
}
URL[] urls = new URL[jarlist.size()];
jarlist.toArray(urls);
FilteredClassLoader loader = new FilteredClassLoader(urls);
// set the new class loader as context class loader
Thread.currentThread().setContextClassLoader(loader);
// get the main server class
Class clazz = loader.loadClass("helma.main.Server");
Class[] cargs = new Class[] { args.getClass() };
Method main = clazz.getMethod("main", cargs);
Object[] nargs = new Object[] { args };
// run
main.invoke(null, nargs);
} }
} }

View file

@ -1,5 +1,18 @@
// ConcurrencyException.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.objectmodel; package helma.objectmodel;
@ -8,44 +21,13 @@ package helma.objectmodel;
* Thrown when more than one thrad tries to modify a Node. The evaluator * Thrown when more than one thrad tries to modify a Node. The evaluator
* will normally catch this and try again after a period of time. * will normally catch this and try again after a period of time.
*/ */
public class ConcurrencyException extends RuntimeException { public class ConcurrencyException extends RuntimeException {
/**
public ConcurrencyException (String msg) { * Creates a new ConcurrencyException object.
super (msg); *
* @param msg ...
*/
public ConcurrencyException(String msg) {
super(msg);
} }
} }

View file

@ -1,4 +1,18 @@
// DatabaseException.java /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.objectmodel; package helma.objectmodel;
@ -6,44 +20,13 @@ package helma.objectmodel;
/** /**
* Thrown on any kind of Database-Error * Thrown on any kind of Database-Error
*/ */
public class DatabaseException extends RuntimeException { public class DatabaseException extends RuntimeException {
/**
public DatabaseException (String msg) { * Creates a new DatabaseException object.
super (msg); *
* @param msg ...
*/
public DatabaseException(String msg) {
super(msg);
} }
} }

View file

@ -1,35 +1,108 @@
// IDatabase.java /*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.objectmodel; package helma.objectmodel;
import helma.objectmodel.db.IDGenerator;
import helma.objectmodel.INode; import helma.objectmodel.INode;
import helma.objectmodel.db.IDGenerator;
import java.io.IOException;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
/** /**
* Interface that is implemented by Database wrappers * Interface that is implemented by Database wrappers
*/ */
public interface IDatabase { public interface IDatabase {
// db-related
public void shutdown();
// db-related // id-related
public void shutdown (); public String nextID() throws ObjectNotFoundException;
// id-related /**
public String nextID() throws ObjectNotFoundException; *
public IDGenerator getIDGenerator (ITransaction transaction) throws Exception; *
public void saveIDGenerator (ITransaction transaction, IDGenerator idgen) throws Exception; * @param transaction ...
*
* @return ...
*
* @throws IOException ...
*/
public IDGenerator getIDGenerator(ITransaction transaction)
throws IOException, ObjectNotFoundException;
// node-related /**
public INode getNode (ITransaction transaction, String key) throws Exception; *
public void saveNode (ITransaction transaction, String key, INode node) throws Exception; *
public void deleteNode (ITransaction transaction, String key) throws Exception; * @param transaction ...
* @param idgen ...
*
* @throws IOException ...
*/
public void saveIDGenerator(ITransaction transaction, IDGenerator idgen)
throws IOException;
// transaction-related // node-related
public ITransaction beginTransaction (); public INode getNode(ITransaction transaction, String key)
public void commitTransaction (ITransaction transaction) throws DatabaseException; throws IOException, ObjectNotFoundException,
public void abortTransaction (ITransaction transaction) throws DatabaseException; SAXException, ParserConfigurationException;
/**
*
*
* @param transaction ...
* @param key ...
* @param node ...
*
* @throws IOException ...
*/
public void saveNode(ITransaction transaction, String key, INode node)
throws IOException;
/**
*
*
* @param transaction ...
* @param key ...
*
* @throws IOException ...
*/
public void deleteNode(ITransaction transaction, String key)
throws IOException;
// transaction-related
public ITransaction beginTransaction();
/**
*
*
* @param transaction ...
*
* @throws DatabaseException ...
*/
public void commitTransaction(ITransaction transaction)
throws DatabaseException;
/**
*
*
* @param transaction ...
*
* @throws DatabaseException ...
*/
public void abortTransaction(ITransaction transaction)
throws DatabaseException;
} }

View file

@ -1,88 +1,391 @@
// INode.java /*
// Copyright (c) Hannes Wallnöfer 1998-2000 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.objectmodel; package helma.objectmodel;
import java.util.*;
import java.io.*;
import helma.framework.IPathElement; import helma.framework.IPathElement;
import helma.objectmodel.db.DbMapping; import helma.objectmodel.db.DbMapping;
import java.io.*;
import java.util.*;
/** /**
* Interface that all Nodes implement. Currently, there are two implementations: * Interface that all Nodes implement. Currently, there are two implementations:
* Transient nodes which only exist in memory, and persistent Nodes, which are * Transient nodes which only exist in memory, and persistent Nodes, which are
* stored in a database (either the internal Object DB or an external relational DB). * stored in a database (either the internal Object DB or an external relational DB).
*/ */
public interface INode extends INodeState, IPathElement { public interface INode extends INodeState, IPathElement {
/** /**
* id-related methods * id-related methods
*/ */
public String getID();
public String getID (); /**
public String getName (); *
public void setDbMapping (DbMapping dbmap); *
public DbMapping getDbMapping (); * @return ...
public int getState (); */
public void setState (int s); public String getName();
public void setName (String name);
public long lastModified (); /**
public long created (); *
public boolean isAnonymous (); // is this a named node, or an anonymous node in a collection? *
public String getPrototype (); * @param dbmap ...
public void setPrototype (String prototype); */
public INode getCacheNode (); public void setDbMapping(DbMapping dbmap);
public void clearCacheNode ();
public String getFullName (); /**
public String getFullName (INode root); *
*
* @return ...
*/
public DbMapping getDbMapping();
/**
*
*
* @return ...
*/
public int getState();
/**
*
*
* @param s ...
*/
public void setState(int s);
/**
*
*
* @param name ...
*/
public void setName(String name);
/**
*
*
* @return ...
*/
public long lastModified();
/**
*
*
* @return ...
*/
public long created();
/**
*
*
* @return ...
*/
public boolean isAnonymous(); // is this a named node, or an anonymous node in a collection?
/**
*
*
* @return ...
*/
public String getPrototype();
/**
*
*
* @param prototype ...
*/
public void setPrototype(String prototype);
/**
*
*
* @return ...
*/
public INode getCacheNode();
/**
*
*/
public void clearCacheNode();
/**
*
*
* @return ...
*/
public String getFullName();
/**
*
*
* @param root ...
*
* @return ...
*/
public String getFullName(INode root);
/** /**
* node-related methods * node-related methods
*/ */
public INode getParent();
public INode getParent (); /**
public void setSubnodeRelation (String rel); *
public String getSubnodeRelation (); *
public int numberOfNodes (); * @param rel ...
public INode addNode (INode node); */
public INode addNode (INode node, int where); public void setSubnodeRelation(String rel);
public INode createNode (String name);
public INode createNode (String name, int where); /**
public Enumeration getSubnodes (); *
public INode getSubnode (String name); *
public INode getSubnodeAt (int index); * @return ...
public int contains (INode node); */
public boolean remove (); public String getSubnodeRelation();
public void removeNode (INode node);
/**
*
*
* @return ...
*/
public int numberOfNodes();
/**
*
*
* @param node ...
*
* @return ...
*/
public INode addNode(INode node);
/**
*
*
* @param node ...
* @param where ...
*
* @return ...
*/
public INode addNode(INode node, int where);
/**
*
*
* @param name ...
*
* @return ...
*/
public INode createNode(String name);
/**
*
*
* @param name ...
* @param where ...
*
* @return ...
*/
public INode createNode(String name, int where);
/**
*
*
* @return ...
*/
public Enumeration getSubnodes();
/**
*
*
* @param name ...
*
* @return ...
*/
public INode getSubnode(String name);
/**
*
*
* @param index ...
*
* @return ...
*/
public INode getSubnodeAt(int index);
/**
*
*
* @param node ...
*
* @return ...
*/
public int contains(INode node);
/**
*
*
* @return ...
*/
public boolean remove();
/**
*
*
* @param node ...
*/
public void removeNode(INode node);
/** /**
* property-related methods * property-related methods
*/ */
public Enumeration properties();
public Enumeration properties (); /**
public IProperty get (String name); *
public String getString (String name); *
public boolean getBoolean (String name); * @param name ...
public Date getDate (String name); *
public long getInteger (String name); * @return ...
public double getFloat (String name); */
public INode getNode (String name); public IProperty get(String name);
public Object getJavaObject (String name);
public void setString (String name, String value); /**
public void setBoolean (String name, boolean value); *
public void setDate (String name, Date value); *
public void setInteger (String name, long value); * @param name ...
public void setFloat (String name, double value); *
public void setNode (String name, INode value); * @return ...
public void setJavaObject (String name, Object value); */
public String getString(String name);
public void unset (String name); /**
*
*
* @param name ...
*
* @return ...
*/
public boolean getBoolean(String name);
/**
*
*
* @param name ...
*
* @return ...
*/
public Date getDate(String name);
/**
*
*
* @param name ...
*
* @return ...
*/
public long getInteger(String name);
/**
*
*
* @param name ...
*
* @return ...
*/
public double getFloat(String name);
/**
*
*
* @param name ...
*
* @return ...
*/
public INode getNode(String name);
/**
*
*
* @param name ...
*
* @return ...
*/
public Object getJavaObject(String name);
/**
*
*
* @param name ...
* @param value ...
*/
public void setString(String name, String value);
/**
*
*
* @param name ...
* @param value ...
*/
public void setBoolean(String name, boolean value);
/**
*
*
* @param name ...
* @param value ...
*/
public void setDate(String name, Date value);
/**
*
*
* @param name ...
* @param value ...
*/
public void setInteger(String name, long value);
/**
*
*
* @param name ...
* @param value ...
*/
public void setFloat(String name, double value);
/**
*
*
* @param name ...
* @param value ...
*/
public void setNode(String name, INode value);
/**
*
*
* @param name ...
* @param value ...
*/
public void setJavaObject(String name, Object value);
/**
*
*
* @param name ...
*/
public void unset(String name);
} }

View file

@ -1,17 +1,28 @@
// INodeState.java /*
// Copyright (c) Hannes Wallnöfer 2001 * Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile$
* $Author$
* $Revision$
* $Date$
*/
package helma.objectmodel; package helma.objectmodel;
import java.util.*;
import java.io.*; import java.io.*;
import java.util.*;
/** /**
* Interface that defines states of nodes * Interface that defines states of nodes
*/ */
public interface INodeState { public interface INodeState {
public final static int TRANSIENT = -3; public final static int TRANSIENT = -3;
public final static int VIRTUAL = -2; public final static int VIRTUAL = -2;
public final static int INVALID = -1; public final static int INVALID = -1;
@ -19,9 +30,4 @@ public interface INodeState {
public final static int NEW = 1; public final static int NEW = 1;
public final static int MODIFIED = 2; public final static int MODIFIED = 2;
public final static int DELETED = 3; public final static int DELETED = 3;
} }

Some files were not shown because too many files have changed in this diff Show more